From 5d5925e10553d1b08ff1ef65fdf692573e84e79a Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Fri, 20 Nov 2026 20:16:36 -0700 Subject: [PATCH 01/50] Pin Core with the Stream runtime The Workflow path of Streams needs the Stream commands and jobs of this Core. The payload visitor reaches their payloads, so its generator gets the rule for a Stream body in this commit. --- scripts/gen_payload_visitor.py | 43 +- temporalio/bridge/Cargo.lock | 73 ++++ .../proto/external_data/external_data_pb2.pyi | 382 ++++++++++++++++++ .../workflow_activation_pb2.pyi | 271 ++++++++++++- .../workflow_commands_pb2.pyi | 307 ++++++++++++++ temporalio/bridge/sdk-core | 2 +- temporalio/bridge/worker.py | 13 +- temporalio/worker/_command_aware_visitor.py | 55 ++- temporalio/worker/_workflow_instance.py | 7 + tests/helpers/streams.py | 58 +++ tests/worker/test_workflow_streams.py | 200 +++++++++ 11 files changed, 1390 insertions(+), 21 deletions(-) create mode 100644 tests/helpers/streams.py create mode 100644 tests/worker/test_workflow_streams.py diff --git a/scripts/gen_payload_visitor.py b/scripts/gen_payload_visitor.py index ba5ddc112b..7cf8816e48 100644 --- a/scripts/gen_payload_visitor.py +++ b/scripts/gen_payload_visitor.py @@ -23,21 +23,38 @@ from temporalio.converter._payload_converter import _get_transfer_type_converter -def discover_system_nexus_roots() -> list[Descriptor]: - module_path = base_dir / "temporalio" / "nexus" / "system" / "workflow_service" - spec = spec_from_file_location( - "temporalio_nexus_system_workflow_service", - module_path / "__init__.py", - submodule_search_locations=[str(module_path)], - ) - if spec is None or spec.loader is None: - raise RuntimeError(f"Cannot load generated system service from {module_path}") - module = module_from_spec(spec) - sys.modules[spec.name] = module - spec.loader.exec_module(module) +def discover_system_nexus_services() -> list[type]: + services: list[type] = [] + system_dir = base_dir / "temporalio" / "nexus" / "system" + for module_path in sorted(path.parent for path in system_dir.glob("*/services.py")): + spec = spec_from_file_location( + f"temporalio_nexus_system_{module_path.name}", + module_path / "__init__.py", + submodule_search_locations=[str(module_path)], + ) + if spec is None or spec.loader is None: + raise RuntimeError( + f"Cannot load generated system service from {module_path}" + ) + module = module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + services.extend( + value + for value in vars(module.services).values() + if isinstance(value, type) and nexusrpc.get_service_definition(value) + ) + return services + +def discover_system_nexus_roots() -> list[Descriptor]: roots: list[Descriptor] = [] - for annotation in get_type_hints(module._services.WorkflowService).values(): + annotations = [ + annotation + for service in discover_system_nexus_services() + for annotation in get_type_hints(service).values() + ] + for annotation in annotations: if get_origin(annotation) is not nexusrpc.Operation: continue for operation_type in get_args(annotation): diff --git a/temporalio/bridge/Cargo.lock b/temporalio/bridge/Cargo.lock index 1aaae8a89d..aee3dfdad3 100644 --- a/temporalio/bridge/Cargo.lock +++ b/temporalio/bridge/Cargo.lock @@ -181,6 +181,15 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "bon" version = "3.10.3" @@ -309,6 +318,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "constant_time_eq" version = "0.6.1" @@ -376,6 +391,15 @@ version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "darling" version = "0.24.1" @@ -433,6 +457,17 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + [[package]] name = "dirs" version = "7.0.0" @@ -871,6 +906,15 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.13.0" @@ -2390,6 +2434,17 @@ dependencies = [ "serde", ] +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "sharded-slab" version = "0.1.7" @@ -2757,6 +2812,7 @@ dependencies = [ "reqwest", "serde", "serde_json", + "sha2", "siphasher", "slotmap", "sysinfo", @@ -2764,6 +2820,7 @@ dependencies = [ "temporalio-client", "temporalio-common", "temporalio-macros", + "temporalio-streams", "thiserror", "tokio", "tokio-stream", @@ -2775,6 +2832,16 @@ dependencies = [ "zip", ] +[[package]] +name = "temporalio-streams" +version = "0.1.0" +dependencies = [ + "enum-iterator", + "futures-util", + "prost", + "temporalio-common", +] + [[package]] name = "termtree" version = "0.5.1" @@ -3140,6 +3207,12 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "typetag" version = "0.2.23" diff --git a/temporalio/bridge/proto/external_data/external_data_pb2.pyi b/temporalio/bridge/proto/external_data/external_data_pb2.pyi index edcd4581a1..c1b7256169 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.pyi +++ b/temporalio/bridge/proto/external_data/external_data_pb2.pyi @@ -4,10 +4,13 @@ isort:skip_file """ import builtins +import collections.abc import typing import google.protobuf.descriptor import google.protobuf.duration_pb2 +import google.protobuf.empty_pb2 +import google.protobuf.internal.containers import google.protobuf.message import google.protobuf.timestamp_pb2 @@ -139,3 +142,382 @@ class PatchedMarkerData(google.protobuf.message.Message): ) -> None: ... global___PatchedMarkerData = PatchedMarkerData + +@typing.final +class StreamMarkerData(google.protobuf.message.Message): + """The data of a `core_stream` marker. Core records one in each Workflow Task in which Workflow + code got a Stream result or asked for a close. The marker has these details. + * `data` holds this message as JSON, with each `bytes` field in lower-case hex. + * `records` has the body of each Record of the reads with `records_in_history`, one payload for + each. They're in the order of `reads`, and those of one read in the order of its Stream. It's + absent if the marker has no such Record. + * `record_info` has one `binary/plain` payload with the rest of each of those Records, in the + same order. Each is its `temporalio.api.stream.v1.StreamRecord` with no body, with its length + before it as a varint. It's absent if `records` is. + + Every later version of Core must read the markers in History, so these rules apply to each + message of the marker. + * A field never changes its name, because the name is its key in the JSON. + * A new field is `optional`, because older markers don't have it. + * A new `repeated` field gets `#[serde(default)]` in `build.rs`, for the same reason. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + CLOSE_INTENTS_FIELD_NUMBER: builtins.int + APPENDS_FIELD_NUMBER: builtins.int + CLOSES_FIELD_NUMBER: builtins.int + READS_FIELD_NUMBER: builtins.int + @property + def close_intents( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___StreamCloseIntent + ]: ... + @property + def appends( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___StreamAppendResult + ]: ... + @property + def closes( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___StreamCloseResult + ]: ... + @property + def reads( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___StreamReadResult + ]: ... + def __init__( + self, + *, + close_intents: collections.abc.Iterable[global___StreamCloseIntent] + | None = ..., + appends: collections.abc.Iterable[global___StreamAppendResult] | None = ..., + closes: collections.abc.Iterable[global___StreamCloseResult] | None = ..., + reads: collections.abc.Iterable[global___StreamReadResult] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "appends", + b"appends", + "close_intents", + b"close_intents", + "closes", + b"closes", + "reads", + b"reads", + ], + ) -> None: ... + +global___StreamMarkerData = StreamMarkerData + +@typing.final +class StreamCloseIntent(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + STREAM_ID_FIELD_NUMBER: builtins.int + STORE_FIELD_NUMBER: builtins.int + seq: builtins.int + stream_id: builtins.str + store: builtins.str + """The Store name of the Stream's ref.""" + def __init__( + self, + *, + seq: builtins.int = ..., + stream_id: builtins.str = ..., + store: builtins.str = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "seq", b"seq", "store", b"store", "stream_id", b"stream_id" + ], + ) -> None: ... + +global___StreamCloseIntent = StreamCloseIntent + +@typing.final +class StreamAppendResult(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + STREAM_ID_FIELD_NUMBER: builtins.int + STORE_FIELD_NUMBER: builtins.int + ACTIVATION_INDEX_FIELD_NUMBER: builtins.int + APPENDED_FIELD_NUMBER: builtins.int + FAILURE_FIELD_NUMBER: builtins.int + seq: builtins.int + stream_id: builtins.str + store: builtins.str + """The Store name of the Stream's ref.""" + activation_index: builtins.int + """The index of the activation, within its Workflow Task, in which Workflow code got the result.""" + @property + def appended(self) -> global___StreamAppendOffsets: ... + @property + def failure(self) -> global___StreamFailure: ... + def __init__( + self, + *, + seq: builtins.int = ..., + stream_id: builtins.str = ..., + store: builtins.str = ..., + activation_index: builtins.int = ..., + appended: global___StreamAppendOffsets | None = ..., + failure: global___StreamFailure | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "appended", b"appended", "failure", b"failure", "result", b"result" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "activation_index", + b"activation_index", + "appended", + b"appended", + "failure", + b"failure", + "result", + b"result", + "seq", + b"seq", + "store", + b"store", + "stream_id", + b"stream_id", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["result", b"result"] + ) -> typing.Literal["appended", "failure"] | None: ... + +global___StreamAppendResult = StreamAppendResult + +@typing.final +class StreamAppendOffsets(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FIRST_OFFSET_FIELD_NUMBER: builtins.int + LAST_OFFSET_FIELD_NUMBER: builtins.int + first_offset: builtins.bytes + last_offset: builtins.bytes + def __init__( + self, + *, + first_offset: builtins.bytes = ..., + last_offset: builtins.bytes = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "first_offset", b"first_offset", "last_offset", b"last_offset" + ], + ) -> None: ... + +global___StreamAppendOffsets = StreamAppendOffsets + +@typing.final +class StreamFailure(google.protobuf.message.Message): + """Why a Stream call failed. Core builds the failure that Workflow code gets from these two.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REASON_FIELD_NUMBER: builtins.int + MESSAGE_FIELD_NUMBER: builtins.int + reason: builtins.str + """The name of the `temporalio.api.enums.v1.StreamErrorReason`, such as + `STREAM_ERROR_REASON_CLOSED`. History stores the name, so a reason must never change its name. + """ + message: builtins.str + """The message of the failure, of at most 4096 bytes.""" + def __init__( + self, + *, + reason: builtins.str = ..., + message: builtins.str = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["message", b"message", "reason", b"reason"] + ) -> None: ... + +global___StreamFailure = StreamFailure + +@typing.final +class StreamCloseResult(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + ACTIVATION_INDEX_FIELD_NUMBER: builtins.int + FAILURE_FIELD_NUMBER: builtins.int + seq: builtins.int + activation_index: builtins.int + """The index of the activation, within its Workflow Task, in which Workflow code got the result.""" + @property + def failure(self) -> global___StreamFailure: + """Unset if the Stream is closed.""" + + def __init__( + self, + *, + seq: builtins.int = ..., + activation_index: builtins.int = ..., + failure: global___StreamFailure | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["failure", b"failure"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "activation_index", + b"activation_index", + "failure", + b"failure", + "seq", + b"seq", + ], + ) -> None: ... + +global___StreamCloseResult = StreamCloseResult + +@typing.final +class StreamReadResult(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + STREAM_ID_FIELD_NUMBER: builtins.int + STORE_FIELD_NUMBER: builtins.int + ACTIVATION_INDEX_FIELD_NUMBER: builtins.int + FROM_OFFSET_FIELD_NUMBER: builtins.int + PAGE_FIELD_NUMBER: builtins.int + FAILURE_FIELD_NUMBER: builtins.int + CANCELLED_FIELD_NUMBER: builtins.int + seq: builtins.int + stream_id: builtins.str + store: builtins.str + """The Store name of the Stream's ref.""" + activation_index: builtins.int + """The index of the activation, within its Workflow Task, in which Workflow code got the result.""" + from_offset: builtins.bytes + """The `from_offset` of the read. A replay reads the Records of a page after it.""" + @property + def page(self) -> global___StreamReadPage: ... + @property + def failure(self) -> global___StreamFailure: ... + @property + def cancelled(self) -> google.protobuf.empty_pb2.Empty: + """Workflow code cancelled the read before it got the job of the read.""" + + def __init__( + self, + *, + seq: builtins.int = ..., + stream_id: builtins.str = ..., + store: builtins.str = ..., + activation_index: builtins.int = ..., + from_offset: builtins.bytes = ..., + page: global___StreamReadPage | None = ..., + failure: global___StreamFailure | None = ..., + cancelled: google.protobuf.empty_pb2.Empty | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "cancelled", + b"cancelled", + "failure", + b"failure", + "page", + b"page", + "result", + b"result", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "activation_index", + b"activation_index", + "cancelled", + b"cancelled", + "failure", + b"failure", + "from_offset", + b"from_offset", + "page", + b"page", + "result", + b"result", + "seq", + b"seq", + "store", + b"store", + "stream_id", + b"stream_id", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["result", b"result"] + ) -> typing.Literal["page", "failure", "cancelled"] | None: ... + +global___StreamReadResult = StreamReadResult + +@typing.final +class StreamReadPage(google.protobuf.message.Message): + """A page that a read gave Workflow code.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RECORD_COUNT_FIELD_NUMBER: builtins.int + DONE_FIELD_NUMBER: builtins.int + DIGEST_FIELD_NUMBER: builtins.int + RECORD_BYTES_FIELD_NUMBER: builtins.int + record_count: builtins.int + """The number of Records in the page.""" + done: builtins.bool + """True if the Stream was closed and had no Record after this page.""" + digest: builtins.bytes + """The first 16 bytes of the SHA-256 of the Records. It's empty for a read with + `records_in_history`, whose Records are in the details of the marker, or if the page has no + Record. + """ + record_bytes: builtins.int + """The bytes of the Records, each as a page of a read encodes it, with the tag and the length of + its field. That is the measure of the `max_bytes` of a read. It's set when `digest` is, so a + replay knows how much it reads. + """ + def __init__( + self, + *, + record_count: builtins.int = ..., + done: builtins.bool = ..., + digest: builtins.bytes = ..., + record_bytes: builtins.int = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "digest", + b"digest", + "done", + b"done", + "record_bytes", + b"record_bytes", + "record_count", + b"record_count", + ], + ) -> None: ... + +global___StreamReadPage = StreamReadPage diff --git a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi index e55917d810..20df9b2d5a 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi @@ -13,6 +13,7 @@ import typing import google.protobuf.descriptor import google.protobuf.duration_pb2 +import google.protobuf.empty_pb2 import google.protobuf.internal.containers import google.protobuf.internal.enum_type_wrapper import google.protobuf.message @@ -23,6 +24,7 @@ import temporalio.api.enums.v1.failed_cause_pb2 import temporalio.api.enums.v1.workflow_pb2 import temporalio.api.failure.v1.message_pb2 import temporalio.api.nexus.v1.message_pb2 +import temporalio.api.stream.v1.message_pb2 import temporalio.api.update.v1.message_pb2 import temporalio.bridge.proto.activity_result.activity_result_pb2 import temporalio.bridge.proto.child_workflow.child_workflow_pb2 @@ -49,7 +51,7 @@ class WorkflowActivation(google.protobuf.message.Message): 3. random-seed-updates 4. signals/updates 5. all others - 6. local activity resolutions + 6. local activity resolutions, then Stream results 7. queries 8. evictions @@ -65,6 +67,10 @@ class WorkflowActivation(google.protobuf.message.Message): in that same activation (prime example: cancelling not-wait-for-cancel activities). So, we do this to ensure the LA resolution happens after that cancel (or whatever else it may be) as it normally would have when executing. + * The results of Stream calls go after the local activity resolutions, because a replay also + scans ahead for their marker. Appends go first, then closes, then reads, and each kind is in + `seq` order. When a replay gives the results of several activations in one, the Stream results + keep the order of those activations, after all local activity resolutions. * Queries always go last (and, in fact, always come in their own activation) * Evictions also always come in their own activation @@ -250,6 +256,9 @@ class WorkflowActivationJob(google.protobuf.message.Message): DO_UPDATE_FIELD_NUMBER: builtins.int RESOLVE_NEXUS_OPERATION_START_FIELD_NUMBER: builtins.int RESOLVE_NEXUS_OPERATION_FIELD_NUMBER: builtins.int + RESOLVE_STREAM_READ_FIELD_NUMBER: builtins.int + RESOLVE_STREAM_APPEND_FIELD_NUMBER: builtins.int + RESOLVE_STREAM_CLOSE_FIELD_NUMBER: builtins.int REMOVE_FROM_CACHE_FIELD_NUMBER: builtins.int @property def initialize_workflow(self) -> global___InitializeWorkflow: @@ -324,6 +333,18 @@ class WorkflowActivationJob(google.protobuf.message.Message): def resolve_nexus_operation(self) -> global___ResolveNexusOperation: """A nexus operation resolved.""" + @property + def resolve_stream_read(self) -> global___ResolveStreamRead: + """A read of a Stream finished.""" + + @property + def resolve_stream_append(self) -> global___ResolveStreamAppend: + """An append to a Stream finished.""" + + @property + def resolve_stream_close(self) -> global___ResolveStreamClose: + """A close of a Stream finished.""" + @property def remove_from_cache(self) -> global___RemoveFromCache: """Remove the workflow identified by the [WorkflowActivation] containing this job from the @@ -353,6 +374,9 @@ class WorkflowActivationJob(google.protobuf.message.Message): do_update: global___DoUpdate | None = ..., resolve_nexus_operation_start: global___ResolveNexusOperationStart | None = ..., resolve_nexus_operation: global___ResolveNexusOperation | None = ..., + resolve_stream_read: global___ResolveStreamRead | None = ..., + resolve_stream_append: global___ResolveStreamAppend | None = ..., + resolve_stream_close: global___ResolveStreamClose | None = ..., remove_from_cache: global___RemoveFromCache | None = ..., ) -> None: ... def HasField( @@ -386,6 +410,12 @@ class WorkflowActivationJob(google.protobuf.message.Message): b"resolve_request_cancel_external_workflow", "resolve_signal_external_workflow", b"resolve_signal_external_workflow", + "resolve_stream_append", + b"resolve_stream_append", + "resolve_stream_close", + b"resolve_stream_close", + "resolve_stream_read", + b"resolve_stream_read", "signal_workflow", b"signal_workflow", "update_random_seed", @@ -425,6 +455,12 @@ class WorkflowActivationJob(google.protobuf.message.Message): b"resolve_request_cancel_external_workflow", "resolve_signal_external_workflow", b"resolve_signal_external_workflow", + "resolve_stream_append", + b"resolve_stream_append", + "resolve_stream_close", + b"resolve_stream_close", + "resolve_stream_read", + b"resolve_stream_read", "signal_workflow", b"signal_workflow", "update_random_seed", @@ -452,6 +488,9 @@ class WorkflowActivationJob(google.protobuf.message.Message): "do_update", "resolve_nexus_operation_start", "resolve_nexus_operation", + "resolve_stream_read", + "resolve_stream_append", + "resolve_stream_close", "remove_from_cache", ] | None @@ -1645,3 +1684,233 @@ class RemoveFromCache(google.protobuf.message.Message): ) -> None: ... global___RemoveFromCache = RemoveFromCache + +@typing.final +class ResolveStreamRead(google.protobuf.message.Message): + """The result of a `ReadStream`. A read gets at most one, and a read that lang cancelled gets one + too. It gets none only in the four cases that `ReadStream` lists. The activation rules of + `ResolveStreamAppend` apply to it too. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + PAGE_FIELD_NUMBER: builtins.int + FAILED_FIELD_NUMBER: builtins.int + CANCELLED_FIELD_NUMBER: builtins.int + seq: builtins.int + """The `seq` of the `ReadStream`.""" + @property + def page(self) -> global___StreamPage: ... + @property + def failed(self) -> temporalio.api.failure.v1.message_pb2.Failure: + """The failure of the read. It has the parts of the `failed` of a `ResolveStreamAppend`.""" + + @property + def cancelled(self) -> google.protobuf.empty_pb2.Empty: + """Core got a `RequestCancelStreamRead` for the read before lang got a job for it. The job + comes in the next activation after the cancel, or in the next Workflow Task if the task + in hand completes first. `RequestCancelStreamRead` says when a replay gives it. + """ + + def __init__( + self, + *, + seq: builtins.int = ..., + page: global___StreamPage | None = ..., + failed: temporalio.api.failure.v1.message_pb2.Failure | None = ..., + cancelled: google.protobuf.empty_pb2.Empty | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "cancelled", + b"cancelled", + "failed", + b"failed", + "page", + b"page", + "status", + b"status", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "cancelled", + b"cancelled", + "failed", + b"failed", + "page", + b"page", + "seq", + b"seq", + "status", + b"status", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["status", b"status"] + ) -> typing.Literal["page", "failed", "cancelled"] | None: ... + +global___ResolveStreamRead = ResolveStreamRead + +@typing.final +class StreamPage(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RECORDS_FIELD_NUMBER: builtins.int + DONE_FIELD_NUMBER: builtins.int + done: builtins.bool + """True if the Stream is closed and has no Record after this page. It's false if the page has + no Record because none came within the `wait` of the read. + """ + @property + def records( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + temporalio.api.stream.v1.message_pb2.StreamRecord + ]: + """The Records of the page, in the order of the Stream. It's empty if no Record came within the + `wait` of the read, or if the Stream is closed and has no Record after the `from_offset` of + the read. + """ + + def __init__( + self, + *, + records: collections.abc.Iterable[ + temporalio.api.stream.v1.message_pb2.StreamRecord + ] + | None = ..., + done: builtins.bool = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["done", b"done", "records", b"records"] + ) -> None: ... + +global___StreamPage = StreamPage + +@typing.final +class ResolveStreamAppend(google.protobuf.message.Message): + """The result of an `AppendToStream`. Core gives each result in the next activation after the + Store answers, so each result can cost an activation. + + A replay gives each result in the same activation as the first run only if History has the flag + that turns workflow task chunking off. Without the flag, a replay keeps the order of the results + of a task, but it can give a result in another activation in two cases. + * A Workflow Task completes with no command, and the first activation of the next task has a + result. A replay takes the two tasks as one, and can give the results of the first two + activations of the second task in one. + * A Workflow Task starts with an Update that Workflow code rejects, which leaves no event. When + such a replay has no other job to give, it gives the results of History in one activation, in + the order of the first run, up to the first one whose call Workflow code hasn't made yet. + A task with only Stream calls replays in the same activations as a task with only Local + Activities. In a task with both, a result waits for each result of the other kind that the first + run gave before it, so its activations can differ from those of Local Activities alone. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + APPENDED_FIELD_NUMBER: builtins.int + FAILED_FIELD_NUMBER: builtins.int + seq: builtins.int + """The `seq` of the `AppendToStream`.""" + @property + def appended(self) -> global___StreamAppended: ... + @property + def failed(self) -> temporalio.api.failure.v1.message_pb2.Failure: + """The failure of the append. It has these parts. + * An `ApplicationFailureInfo` whose type is `stream_` plus the reason of the Stream error + in snake case, such as `stream_closed`. Its `non_retryable` is set. + * In its details, one `binary/protobuf` payload of a + `temporalio.api.stream.v1.StreamErrorDetails`. + * A message of at most 4096 bytes. + """ + + def __init__( + self, + *, + seq: builtins.int = ..., + appended: global___StreamAppended | None = ..., + failed: temporalio.api.failure.v1.message_pb2.Failure | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "appended", b"appended", "failed", b"failed", "status", b"status" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "appended", + b"appended", + "failed", + b"failed", + "seq", + b"seq", + "status", + b"status", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["status", b"status"] + ) -> typing.Literal["appended", "failed"] | None: ... + +global___ResolveStreamAppend = ResolveStreamAppend + +@typing.final +class StreamAppended(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FIRST_OFFSET_FIELD_NUMBER: builtins.int + LAST_OFFSET_FIELD_NUMBER: builtins.int + first_offset: builtins.bytes + last_offset: builtins.bytes + def __init__( + self, + *, + first_offset: builtins.bytes = ..., + last_offset: builtins.bytes = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "first_offset", b"first_offset", "last_offset", b"last_offset" + ], + ) -> None: ... + +global___StreamAppended = StreamAppended + +@typing.final +class ResolveStreamClose(google.protobuf.message.Message): + """The result of a `CloseStream`. The activation rules of `ResolveStreamAppend` apply to it too.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + FAILED_FIELD_NUMBER: builtins.int + seq: builtins.int + """The `seq` of the `CloseStream`.""" + @property + def failed(self) -> temporalio.api.failure.v1.message_pb2.Failure: + """Unset if the Stream is closed, also when it was already closed. When set, it has the same + parts as the `failed` of a `ResolveStreamAppend`. + """ + + def __init__( + self, + *, + seq: builtins.int = ..., + failed: temporalio.api.failure.v1.message_pb2.Failure | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["failed", b"failed"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["failed", b"failed", "seq", b"seq"] + ) -> None: ... + +global___ResolveStreamClose = ResolveStreamClose diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi index 81c47c0b03..af36b1712d 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi @@ -25,6 +25,7 @@ import temporalio.api.enums.v1.workflow_pb2 import temporalio.api.failure.v1.message_pb2 import temporalio.api.sdk.v1.event_group_marker_pb2 import temporalio.api.sdk.v1.user_metadata_pb2 +import temporalio.api.stream.v1.message_pb2 import temporalio.api.workflow.v1.message_pb2 import temporalio.bridge.proto.child_workflow.child_workflow_pb2 import temporalio.bridge.proto.common.common_pb2 @@ -105,6 +106,10 @@ class WorkflowCommand(google.protobuf.message.Message): UPDATE_RESPONSE_FIELD_NUMBER: builtins.int SCHEDULE_NEXUS_OPERATION_FIELD_NUMBER: builtins.int REQUEST_CANCEL_NEXUS_OPERATION_FIELD_NUMBER: builtins.int + READ_STREAM_FIELD_NUMBER: builtins.int + REQUEST_CANCEL_STREAM_READ_FIELD_NUMBER: builtins.int + APPEND_TO_STREAM_FIELD_NUMBER: builtins.int + CLOSE_STREAM_FIELD_NUMBER: builtins.int @property def user_metadata(self) -> temporalio.api.sdk.v1.user_metadata_pb2.UserMetadata: """User metadata that may or may not be persisted into history depending on the command type. @@ -181,6 +186,14 @@ class WorkflowCommand(google.protobuf.message.Message): def request_cancel_nexus_operation( self, ) -> global___RequestCancelNexusOperation: ... + @property + def read_stream(self) -> global___ReadStream: ... + @property + def request_cancel_stream_read(self) -> global___RequestCancelStreamRead: ... + @property + def append_to_stream(self) -> global___AppendToStream: ... + @property + def close_stream(self) -> global___CloseStream: ... def __init__( self, *, @@ -219,10 +232,16 @@ class WorkflowCommand(google.protobuf.message.Message): schedule_nexus_operation: global___ScheduleNexusOperation | None = ..., request_cancel_nexus_operation: global___RequestCancelNexusOperation | None = ..., + read_stream: global___ReadStream | None = ..., + request_cancel_stream_read: global___RequestCancelStreamRead | None = ..., + append_to_stream: global___AppendToStream | None = ..., + close_stream: global___CloseStream | None = ..., ) -> None: ... def HasField( self, field_name: typing.Literal[ + "append_to_stream", + b"append_to_stream", "cancel_child_workflow_execution", b"cancel_child_workflow_execution", "cancel_signal_workflow", @@ -231,6 +250,8 @@ class WorkflowCommand(google.protobuf.message.Message): b"cancel_timer", "cancel_workflow_execution", b"cancel_workflow_execution", + "close_stream", + b"close_stream", "complete_workflow_execution", b"complete_workflow_execution", "continue_as_new_workflow_execution", @@ -239,6 +260,8 @@ class WorkflowCommand(google.protobuf.message.Message): b"fail_workflow_execution", "modify_workflow_properties", b"modify_workflow_properties", + "read_stream", + b"read_stream", "request_cancel_activity", b"request_cancel_activity", "request_cancel_external_workflow_execution", @@ -247,6 +270,8 @@ class WorkflowCommand(google.protobuf.message.Message): b"request_cancel_local_activity", "request_cancel_nexus_operation", b"request_cancel_nexus_operation", + "request_cancel_stream_read", + b"request_cancel_stream_read", "respond_to_query", b"respond_to_query", "schedule_activity", @@ -276,6 +301,8 @@ class WorkflowCommand(google.protobuf.message.Message): def ClearField( self, field_name: typing.Literal[ + "append_to_stream", + b"append_to_stream", "cancel_child_workflow_execution", b"cancel_child_workflow_execution", "cancel_signal_workflow", @@ -284,6 +311,8 @@ class WorkflowCommand(google.protobuf.message.Message): b"cancel_timer", "cancel_workflow_execution", b"cancel_workflow_execution", + "close_stream", + b"close_stream", "complete_workflow_execution", b"complete_workflow_execution", "continue_as_new_workflow_execution", @@ -294,6 +323,8 @@ class WorkflowCommand(google.protobuf.message.Message): b"fail_workflow_execution", "modify_workflow_properties", b"modify_workflow_properties", + "read_stream", + b"read_stream", "request_cancel_activity", b"request_cancel_activity", "request_cancel_external_workflow_execution", @@ -302,6 +333,8 @@ class WorkflowCommand(google.protobuf.message.Message): b"request_cancel_local_activity", "request_cancel_nexus_operation", b"request_cancel_nexus_operation", + "request_cancel_stream_read", + b"request_cancel_stream_read", "respond_to_query", b"respond_to_query", "schedule_activity", @@ -354,6 +387,10 @@ class WorkflowCommand(google.protobuf.message.Message): "update_response", "schedule_nexus_operation", "request_cancel_nexus_operation", + "read_stream", + "request_cancel_stream_read", + "append_to_stream", + "close_stream", ] | None ): ... @@ -1931,3 +1968,273 @@ class RequestCancelNexusOperation(google.protobuf.message.Message): def ClearField(self, field_name: typing.Literal["seq", b"seq"]) -> None: ... global___RequestCancelNexusOperation = RequestCancelNexusOperation + +@typing.final +class AppendToStream(google.protobuf.message.Message): + """Appends Records to a Stream as the Workflow's Producer. Core makes the request id of the append + and sends the result in a `ResolveStreamAppend` job. + + An append is at-least-once. A later attempt of the Workflow Task writes it again, on this Worker + or on another one. + + No command cancels an append, so lang must accept the job of an append that nothing awaits. + When lang sends the Workflow's last command, Core drops each append that has no result, as it + does for a Local Activity. Such an append may or may not have reached the Store, and lang gets + no job for it. + + Core sends the appends and the closes of one Stream to the Store one at a time, in the order of + their commands. A close gets its place in that order only when History has its intent. So an + append that lang sends after a `CloseStream`, but before History has the task of that close, is + written before the close. + + Core fails the Workflow Task in each of these cases, and gives lang no failure of the append. + * `seq` is 0, or isn't above the `seq` of the append before it. + * `stream` is unset, its id is empty or longer than 4096 bytes, or its Store name is longer than + 4096 bytes. + * The Worker has no Stream runtime for the Store of `stream`. + * The append must wait for the task's heartbeat to try again, because the Store answered + `StoreUnavailable`, gave no answer or panicked. The failure message then starts with + `StreamStoreUnavailable:`. + + An append with no `bodies`, or with a batch over the limits of its Store, doesn't fail the + Workflow Task. Lang gets a `failed` job for it. + + In a replay, Core compares the `seq` and the `stream` of the command with History, but not the + `bodies`. A `stream` with no Store name matches any Store in History. An append with no result + in History runs again after the replay, as a later attempt, so a reader can see its batch twice. + + If lang completes the Workflow Task while an append has no result in a marker, Core forces a new + task, unless the completion has the Workflow's last command. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + STREAM_FIELD_NUMBER: builtins.int + BODIES_FIELD_NUMBER: builtins.int + seq: builtins.int + """Lang's incremental sequence number for appends, starting at 1.""" + @property + def stream(self) -> temporalio.api.stream.v1.message_pb2.StreamRef: ... + @property + def bodies( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + temporalio.api.common.v1.message_pb2.Payload + ]: ... + def __init__( + self, + *, + seq: builtins.int = ..., + stream: temporalio.api.stream.v1.message_pb2.StreamRef | None = ..., + bodies: collections.abc.Iterable[temporalio.api.common.v1.message_pb2.Payload] + | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["stream", b"stream"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "bodies", b"bodies", "seq", b"seq", "stream", b"stream" + ], + ) -> None: ... + +global___AppendToStream = AppendToStream + +@typing.final +class CloseStream(google.protobuf.message.Message): + """Closes a Stream. The Workflow Task that sends the command records only the intent to close. + Core closes the Stream when History has that task, and sends the result in a + `ResolveStreamClose` job of a later task. So a close needs at least one more Workflow Task. + + These rules of `AppendToStream` apply to a close too. + * No command cancels it. + * Core drops it if it has no result when lang sends the Workflow's last command. + * The same cases fail the Workflow Task. + * A replay compares the command with History in the same way. + * If lang completes the task while the close has no result in a marker, Core forces a new task. + + Workflow code that needs its close must await the result before its last command. A close whose + intent is in History with no result runs again after a replay. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + STREAM_FIELD_NUMBER: builtins.int + seq: builtins.int + """Lang's incremental sequence number for closes, starting at 1.""" + @property + def stream(self) -> temporalio.api.stream.v1.message_pb2.StreamRef: ... + def __init__( + self, + *, + seq: builtins.int = ..., + stream: temporalio.api.stream.v1.message_pb2.StreamRef | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["stream", b"stream"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["seq", b"seq", "stream", b"stream"] + ) -> None: ... + +global___CloseStream = CloseStream + +@typing.final +class ReadStream(google.protobuf.message.Message): + """Reads the next page of a Stream. The result comes in one `ResolveStreamRead` job, which has a + page, a failure or a cancel. Core asks the Store when the command comes, unless the Workflow + replays. A replay gives the read the result that History has for it. + + The page has the Records after `from_offset`, in the order of the Stream: + * the Records that the Stream has, or the first ones that come within `wait` + * no Records and `done`, if the Stream is closed and has none after `from_offset` + * no Records, if none came within `wait` + + To read on, lang sends a new `ReadStream` whose `from_offset` is the offset of the last Record + that it got. A page with no Record gives no offset, so the next read starts at the `from_offset` + of this one. + + What a read costs: + * Each page takes a command, an activation and an entry in the marker of its Workflow Task. + * A read holds its Workflow Task open while it waits for the Store, as a Local Activity does. A + Signal, a timer or an Activity result reaches Workflow code in the next task. The task in hand + completes once Workflow code sends a command for the server while only reads hold the task, + and at the latest at its heartbeat. A read that still waits adds the three events of a forced + Workflow Task at each heartbeat. + * One Workflow Task gives at most 16 MiB of Records, and its marker holds at most 1 MiB of them + for reads with `records_in_history`. A page that doesn't fit comes in the next task, which + Core forces. + * Without `records_in_history`, History has the count and a digest of the Records of each page. + A replay reads each page from the Store again, within the timeout of its Workflow Task. A + query of a run that isn't cached replays too. Once the Store no longer has the same Records, + each replay fails, also the one for a query of a closed Workflow. + + A read gets no job at the Workflow's last command, at a failed Workflow Task, at an eviction and + at the shutdown of the Worker. After the last three the Workflow replays. The replay gives each + read the result that History has for it. A read with no result in History runs again once the + replay is over, unless Workflow code cancelled it. Such a read gets its `cancelled` job then. + + Core fails the Workflow Task, and gives lang no failure of the read, in the cases that + `AppendToStream` lists and in these: + * `from_offset` is longer than 1024 bytes. + * `wait` is negative, or has its nanoseconds out of range. + * `max_records` or `max_bytes` is negative. + + In a replay, Core compares the `seq`, the `stream` and the `from_offset` of the command with + History. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + STREAM_FIELD_NUMBER: builtins.int + FROM_OFFSET_FIELD_NUMBER: builtins.int + WAIT_FIELD_NUMBER: builtins.int + RECORDS_IN_HISTORY_FIELD_NUMBER: builtins.int + MAX_RECORDS_FIELD_NUMBER: builtins.int + MAX_BYTES_FIELD_NUMBER: builtins.int + seq: builtins.int + """Lang's incremental sequence number for reads, starting at 1.""" + from_offset: builtins.bytes + """The page has the Records after this offset. If it's empty, the page starts at the beginning + of the Stream. + """ + records_in_history: builtins.bool + """If set, the marker of the task holds the Records of the page, so a replay doesn't read the + Store. A marker can't hold a Record whose Producer and body have more than 1.5 MiB, so the + read fails with `stream_unsupported` for one. + """ + max_records: builtins.int + """The maximum number of Records in the page, which is 256 if this is zero.""" + max_bytes: builtins.int + """The maximum size of the Records in the page, which is 4 MiB if this is zero. Core asks the + Store for at most 16 MiB, and for at most 1 MiB with `records_in_history`. One larger Record + still comes as a page, unless the read fails for it with `records_in_history`. + """ + @property + def stream(self) -> temporalio.api.stream.v1.message_pb2.StreamRef: ... + @property + def wait(self) -> google.protobuf.duration_pb2.Duration: + """How long the read waits for a Record if the Stream has none after `from_offset`. If it's + unset, the read doesn't wait. + """ + + def __init__( + self, + *, + seq: builtins.int = ..., + stream: temporalio.api.stream.v1.message_pb2.StreamRef | None = ..., + from_offset: builtins.bytes = ..., + wait: google.protobuf.duration_pb2.Duration | None = ..., + records_in_history: builtins.bool = ..., + max_records: builtins.int = ..., + max_bytes: builtins.int = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["stream", b"stream", "wait", b"wait"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "from_offset", + b"from_offset", + "max_bytes", + b"max_bytes", + "max_records", + b"max_records", + "records_in_history", + b"records_in_history", + "seq", + b"seq", + "stream", + b"stream", + "wait", + b"wait", + ], + ) -> None: ... + +global___ReadStream = ReadStream + +@typing.final +class RequestCancelStreamRead(google.protobuf.message.Message): + """Cancels a read, as `RequestCancelLocalActivity` cancels a Local Activity whose cancellation type + is `TRY_CANCEL`. The read still gets its one `ResolveStreamRead` job. Once Core has the cancel, + that job has `cancelled`, unless lang already got the job of the read. Core drops a page or a + failure of the read that lang didn't get, and the next read from the same `from_offset` gives + the Records of a dropped page. + + If the activation that lang answers with the cancel has a job of the read, that job stays as it + is. So an SDK that runs Workflow code between the jobs of one activation can give that code a + page of a read that it already cancelled, in the first run and in a replay. + + A cancel costs an activation and an entry in the marker of its Workflow Task, for the + `cancelled` job. If the task completes at its heartbeat before that job, the cancel also costs + the events of a forced Workflow Task. + + A `ReadStream` and its cancel in one completion, in that order, make no Store call. + + In a replay, the job is the one that History has. A replay of a History without the flag that + turns workflow task chunking off can give the `cancelled` job before lang sends the cancel, in + the activation of the job that made Workflow code cancel. A read with a cancel and no result in + History gets its `cancelled` job once the replay is over. + + Core ignores the cancel of a read that got its job, and the cancel of a `seq` that lang skipped. + The cancel of a `seq` above that of the last read is a nondeterminism error. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + seq: builtins.int + """The `seq` of the `ReadStream` to cancel.""" + def __init__( + self, + *, + seq: builtins.int = ..., + ) -> None: ... + def ClearField(self, field_name: typing.Literal["seq", b"seq"]) -> None: ... + +global___RequestCancelStreamRead = RequestCancelStreamRead diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index 45434777fc..4be3975489 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit 45434777fc4b496c8a9f78c263c030e828d5c5cf +Subproject commit 4be3975489e9f258215b550795741c712c0c7f9f diff --git a/temporalio/bridge/worker.py b/temporalio/bridge/worker.py index fa5f337ca7..fd4d2aae3c 100644 --- a/temporalio/bridge/worker.py +++ b/temporalio/bridge/worker.py @@ -29,7 +29,10 @@ from temporalio.bridge.temporal_sdk_bridge import ( PollShutdownError, # type: ignore # noqa: F401 ) -from temporalio.worker._command_aware_visitor import CommandAwarePayloadVisitor +from temporalio.worker._command_aware_visitor import ( + CommandAwarePayloadVisitor, + StoragePayloadVisitor, +) @dataclass @@ -315,14 +318,14 @@ async def decode_activation( Returns: Metrics from any external storage retrieval operations that occurred. """ - await CommandAwarePayloadVisitor( + await StoragePayloadVisitor( skip_search_attributes=True, skip_headers=not decode_headers, ).visit(_Visitor(data_converter._decode_reference_payload_sequence), activation) metrics = temporalio.converter._extstore.StorageOperationMetrics() with metrics.track(): - await CommandAwarePayloadVisitor( + await StoragePayloadVisitor( skip_search_attributes=True, skip_headers=not decode_headers, concurrency_limit=storage_concurrency_limit, @@ -364,7 +367,7 @@ async def encode_completion( if data_converter.external_storage: with metrics.track(): - await CommandAwarePayloadVisitor( + await StoragePayloadVisitor( skip_search_attributes=True, skip_headers=not encode_headers, concurrency_limit=storage_concurrency_limit, @@ -373,7 +376,7 @@ async def encode_completion( completion, ) - await CommandAwarePayloadVisitor( + await StoragePayloadVisitor( skip_search_attributes=True, skip_headers=not encode_headers, ).visit( diff --git a/temporalio/worker/_command_aware_visitor.py b/temporalio/worker/_command_aware_visitor.py index 888c06f298..16ae76ec3e 100644 --- a/temporalio/worker/_command_aware_visitor.py +++ b/temporalio/worker/_command_aware_visitor.py @@ -1,10 +1,11 @@ """Visitor that sets command context during payload traversal.""" import contextvars -from collections.abc import Iterator +from collections.abc import Iterable, Iterator from contextlib import contextmanager from dataclasses import dataclass +from temporalio.api.common.v1.message_pb2 import Payload from temporalio.api.enums.v1.command_type_pb2 import CommandType from temporalio.bridge._visitor import PayloadVisitor from temporalio.bridge._visitor_functions import VisitorFunctions @@ -16,8 +17,12 @@ ResolveNexusOperationStart, ResolveRequestCancelExternalWorkflow, ResolveSignalExternalWorkflow, + ResolveStreamAppend, + ResolveStreamClose, + ResolveStreamRead, ) from temporalio.bridge.proto.workflow_commands.workflow_commands_pb2 import ( + AppendToStream, CompleteWorkflowExecution, FailWorkflowExecution, ScheduleActivity, @@ -211,6 +216,52 @@ async def _visit_coresdk_workflow_activation_ResolveNexusOperation( fs, o ) + # Stream commands and activation jobs. Core builds the failure of a Stream job with no + # codec, so nothing visits it. + async def _visit_coresdk_workflow_commands_AppendToStream( + self, fs: VisitorFunctions, o: AppendToStream + ) -> None: + await self._visit_stream_payloads(fs, o.seq, o.bodies) + + async def _visit_coresdk_workflow_activation_ResolveStreamRead( + self, fs: VisitorFunctions, o: ResolveStreamRead + ) -> None: + await self._visit_stream_payloads( + fs, o.seq, [record.body for record in o.page.records] + ) + + async def _visit_coresdk_workflow_activation_ResolveStreamAppend( + self, fs: VisitorFunctions, o: ResolveStreamAppend + ) -> None: + pass + + async def _visit_coresdk_workflow_activation_ResolveStreamClose( + self, fs: VisitorFunctions, o: ResolveStreamClose + ) -> None: + pass + + async def _visit_stream_payloads( + self, fs: VisitorFunctions, seq: int, payloads: Iterable[Payload] + ) -> None: + # A Record can come from any writer, so its body isn't trusted to be a system Nexus + # envelope, and a codec gets each body alone as it does in client code. + with current_command(CommandType.COMMAND_TYPE_UNSPECIFIED, seq): + for payload in payloads: + await fs.visit_payload(payload) + + +class StoragePayloadVisitor(CommandAwarePayloadVisitor): + """Payload visitor for the passes of external storage and of its references. + + These passes skip the payloads of a Stream. A Stream body is a value of its + writer, which can look like a reference to the storage of this Worker. + """ + + async def _visit_stream_payloads( + self, fs: VisitorFunctions, seq: int, payloads: Iterable[Payload] + ) -> None: + pass + @contextmanager def current_command( @@ -220,6 +271,8 @@ def current_command( update_protocol_instance_id: str | None = None, ) -> Iterator[None]: """Context manager for setting command info.""" + # `COMMAND_TYPE_UNSPECIFIED` marks the body of a Stream Record, which gets no + # serialization context. No other command may use that type. token = current_command_info.set( CommandInfo( command_type=command_type, diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index ce4282f0bc..04e4f5c555 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -2547,6 +2547,13 @@ def get_serialization_context( # The update's result and failure go back to the Nexus caller return self._nexus_update_contexts[command_info.update_protocol_instance_id] + if ( + command_info.command_type + == temporalio.api.enums.v1.command_type_pb2.CommandType.COMMAND_TYPE_UNSPECIFIED + ): + # The body of a Stream Record, which any code may read, so it has no context + return None + if ( command_info.command_type == temporalio.api.enums.v1.command_type_pb2.CommandType.COMMAND_TYPE_SCHEDULE_ACTIVITY_TASK diff --git a/tests/helpers/streams.py b/tests/helpers/streams.py new file mode 100644 index 0000000000..031aa30792 --- /dev/null +++ b/tests/helpers/streams.py @@ -0,0 +1,58 @@ +"""Helpers for the tests of Streams.""" + +from collections.abc import Sequence + +from temporalio.api.common.v1 import Payload +from temporalio.converter import ( + PayloadCodec, + SerializationContext, + WithSerializationContext, +) + +CodecCall = tuple[str, SerializationContext | None, int] + + +class ContextCodec(PayloadCodec, WithSerializationContext): + """Wraps each payload with the kind of its serialization context as a key, and + refuses to unwrap a payload with another key. ``calls`` logs the context and the + payload count of each call. + """ + + def __init__( + self, + calls: list[CodecCall] | None = None, + context: SerializationContext | None = None, + ) -> None: + self.calls: list[CodecCall] = [] if calls is None else calls + self._context = context + + def with_context(self, context: SerializationContext) -> "ContextCodec": + return ContextCodec(self.calls, context) + + async def encode(self, payloads: Sequence[Payload]) -> list[Payload]: + self.calls.append(("encode", self._context, len(payloads))) + return [wrapped(payload, self._context) for payload in payloads] + + async def decode(self, payloads: Sequence[Payload]) -> list[Payload]: + self.calls.append(("decode", self._context, len(payloads))) + decoded: list[Payload] = [] + for payload in payloads: + if payload.metadata.get("encoding") == b"test/wrapped": + key = wrapped(Payload(), self._context).metadata["context"] + assert payload.metadata["context"] == key, ( + f"{payload} isn't for {key!r}" + ) + payload = Payload.FromString(payload.data) + decoded.append(payload) + return decoded + + +def wrapped(payload: Payload, context: SerializationContext | None = None) -> Payload: + """Return ``payload`` as a :py:class:`ContextCodec` with ``context`` encodes it.""" + return Payload( + metadata={ + "encoding": b"test/wrapped", + "context": type(context).__name__.encode(), + }, + data=payload.SerializeToString(), + ) diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py new file mode 100644 index 0000000000..8874292be3 --- /dev/null +++ b/tests/worker/test_workflow_streams.py @@ -0,0 +1,200 @@ +"""Tests of the Stream calls of one Workflow instance, with no server.""" + +import dataclasses +from datetime import datetime, timedelta, timezone + +import temporalio.api.common.v1 +import temporalio.bridge.worker +import temporalio.common +import temporalio.converter +import temporalio.converter._extstore +import temporalio.nexus.system +import temporalio.worker +from temporalio import workflow +from temporalio.api.common.v1 import Payload +from temporalio.api.failure.v1 import ApplicationFailureInfo, Failure +from temporalio.api.sdk.v1.external_storage_pb2 import ExternalStorageReference +from temporalio.api.stream.v1 import StreamRecord, StreamRef +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 ( + ResolveActivity, + ResolveStreamAppend, + ResolveStreamClose, + ResolveStreamRead, + StreamPage, + WorkflowActivation, + WorkflowActivationJob, +) +from temporalio.bridge.proto.workflow_commands import ( + AppendToStream, + CompleteWorkflowExecution, + WorkflowCommand, +) +from temporalio.bridge.proto.workflow_completion import ( + Success, + WorkflowActivationCompletion, +) +from temporalio.converter import ExternalStorage, WorkflowSerializationContext +from temporalio.worker._workflow import _CommandAwareDataConverter +from tests.helpers.streams import CodecCall, ContextCodec, 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) -> temporalio.worker.WorkflowInstance: + defn = workflow._Definition.must_from_class(workflow_class) + start_time = datetime(2026, 1, 1, tzinfo=timezone.utc) + return temporalio.worker.UnsandboxedWorkflowRunner().create_instance( + temporalio.worker.WorkflowInstanceDetails( + payload_converter_factory=temporalio.converter.DefaultPayloadConverter, + failure_converter_class=temporalio.converter.DefaultFailureConverter, + 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={}, + disable_eager_activity_execution=False, + worker_level_failure_exception_types=[], + patch_activation_callback=None, + last_completion_result=temporalio.api.common.v1.Payloads(), + last_failure=None, + ) + ) + + +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)] + + # A writer with no codec can write a claim of a payload in this Worker's storage, and + # a body that has the mark of a system Nexus envelope. + claim = Payload() + claim.CopyFrom(stored) + claim.metadata[temporalio.converter._extstore._REFERENCE_MARKER_KEY] = b"true" + envelope = to_payload("envelope") + envelope.metadata[temporalio.nexus.system._SYSTEM_PAYLOAD_METADATA_KEY] = b"true" + failure = Failure( + message="The Stream is closed", + application_failure_info=ApplicationFailureInfo( + type="stream_closed", + details=temporalio.api.common.v1.Payloads(payloads=[wrapped(result)]), + ), + ) + records = [*append.append_to_stream.bodies, claim, envelope] + activation = WorkflowActivation( + jobs=[ + WorkflowActivationJob( + resolve_stream_read=ResolveStreamRead( + seq=1, + page=StreamPage( + records=[ + StreamRecord(body=body, offset=bytes([at + 1])) + for at, body in enumerate(records) + ] + ), + ) + ), + WorkflowActivationJob( + resolve_stream_read=ResolveStreamRead(seq=2, failed=failure) + ), + WorkflowActivationJob( + resolve_stream_append=ResolveStreamAppend(seq=1, failed=failure) + ), + WorkflowActivationJob( + resolve_stream_close=ResolveStreamClose(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 + ) + read, failed_read, appended, closed, activity = activation.jobs + assert [record.body for record in read.resolve_stream_read.page.records] == [ + *bodies, + claim, + envelope, + ] + assert failed_read.resolve_stream_read.failed == failure + assert appended.resolve_stream_append.failed == failure + assert closed.resolve_stream_close.failed == failure + assert activity.resolve_activity.result.completed.result == result + assert driver._retrieve_calls == 1 + assert calls == [("decode", None, 1)] * 4 + [("decode", context, 1)] From 818adb305f229ad3fa360781e88ba0caf24c85b9 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Fri, 20 Nov 2026 20:35:52 -0700 Subject: [PATCH 02/50] Add StreamStore and MemoryStreamStore A Stream Store is the handler side of the Stream service, which the generated code doesn't have. The memory Store lets a test use Streams with no other service, behind the checks that Core runs for a Store of Workflow code. --- changelog/added/steady-stream-heron.md | 1 + temporalio/bridge/Cargo.lock | 1 + temporalio/bridge/Cargo.toml | 1 + temporalio/bridge/src/lib.rs | 4 + temporalio/bridge/src/streams.rs | 251 ++++++++++++++ temporalio/bridge/streams.py | 42 +++ temporalio/client/__init__.py | 8 + temporalio/client/_stream_store.py | 442 ++++++++++++++++++++++++ temporalio/exceptions.py | 44 +++ temporalio/testing/__init__.py | 2 + temporalio/testing/_stream_store.py | 406 ++++++++++++++++++++++ tests/helpers/streams.py | 64 +++- tests/testing/test_stream_store.py | 455 +++++++++++++++++++++++++ 13 files changed, 1720 insertions(+), 1 deletion(-) create mode 100644 changelog/added/steady-stream-heron.md create mode 100644 temporalio/bridge/src/streams.rs create mode 100644 temporalio/bridge/streams.py create mode 100644 temporalio/client/_stream_store.py create mode 100644 temporalio/testing/_stream_store.py create mode 100644 tests/testing/test_stream_store.py diff --git a/changelog/added/steady-stream-heron.md b/changelog/added/steady-stream-heron.md new file mode 100644 index 0000000000..0f96918ad1 --- /dev/null +++ b/changelog/added/steady-stream-heron.md @@ -0,0 +1 @@ +Add experimental `temporalio.client.StreamStore`, the base class of a Stream Store, and `temporalio.testing.MemoryStreamStore`, a Store that keeps its Streams in memory for tests and local runs. diff --git a/temporalio/bridge/Cargo.lock b/temporalio/bridge/Cargo.lock index aee3dfdad3..d64fad2906 100644 --- a/temporalio/bridge/Cargo.lock +++ b/temporalio/bridge/Cargo.lock @@ -2649,6 +2649,7 @@ dependencies = [ "temporalio-client", "temporalio-common", "temporalio-sdk-core", + "temporalio-streams", "tokio", "tokio-rustls", "tokio-stream", diff --git a/temporalio/bridge/Cargo.toml b/temporalio/bridge/Cargo.toml index 3d63f69cdf..10ffc2208c 100644 --- a/temporalio/bridge/Cargo.toml +++ b/temporalio/bridge/Cargo.toml @@ -73,6 +73,7 @@ temporalio-sdk-core = { version = "0.12.0", path = "./sdk-core/crates/sdk-core", "envconfig", "prometheus", ] } +temporalio-streams = { version = "0.1.0", path = "./sdk-core/crates/streams" } tokio = "1.26" # Matches the sdk-core client crate's rustls stack; used to build the custom # server certificate verifier for TLSConfig.verification_server_name. diff --git a/temporalio/bridge/src/lib.rs b/temporalio/bridge/src/lib.rs index 867da998ec..05da9d13c9 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; @@ -53,6 +54,9 @@ fn temporal_sdk_bridge(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { (wrap_pyfunction!(runtime::shutdown_runtimes, m)?,), )?; + // Stream stuff + m.add_function(wrap_pyfunction!(streams::call_stream_store, m)?)?; + // Testing stuff m.add_class::()?; m.add_function(wrap_pyfunction!(start_dev_server, m)?)?; diff --git a/temporalio/bridge/src/streams.rs b/temporalio/bridge/src/streams.rs new file mode 100644 index 0000000000..5cc96524c6 --- /dev/null +++ b/temporalio/bridge/src/streams.rs @@ -0,0 +1,251 @@ +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::{IntoPyDict, PyBytes, PyType}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError}; +use temporalio_streams::proto::{ + AppendRecordsRequest, AppendRecordsResponse, CloseStreamRequest, CloseStreamResponse, + CreateStreamRequest, CreateStreamResponse, DescribeStreamRequest, DescribeStreamResponse, + ReadRecordsRequest, ReadRecordsResponse, StreamErrorReason, +}; +use temporalio_streams::record::StoreLimits; +use temporalio_streams::{ + AppendError, CloseError, CreateError, DescribeError, ReadError, Reason, StreamError, + StreamRuntime, StreamStore, WireReason, +}; + +use crate::runtime; + +/// A Stream Store that is a Python object. `caller` is a `_StoreCaller` of +/// `temporalio.client._stream_store`, and its `call` runs on the event loop of the task locals. +struct PythonStore { + caller: Py, + event_loop_task_locals: Arc>, +} + +/// The state of one call of a Python Store, which the call's guard and its `OnTask` share. +enum CallState { + /// Python hasn't started the task of the call. + Pending, + /// The Python task that runs the call. + Running(Py), + /// The caller dropped the call before its answer. + Dropped, + /// The call has its answer. + Done, +} + +// Nothing calls into Python while it holds this lock, since `OnTask` takes it with the GIL held +// and the guard needs the GIL only after it let the lock go. +fn lock(state: &Mutex) -> MutexGuard<'_, CallState> { + state.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// The callback that takes the Python task of a call from `_StoreCaller.call`, which then calls +/// the Store. +#[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(()) + } +} + +/// The guard that cancels the Python task of a call that its caller drops before the answer. Core +/// drops a call when it stops a read, evicts a run, gives up a try or shuts down. +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 { + // The loop may be closed and the interpreter may be finalizing, and then there's no + // task left to cancel. asyncio lets another thread only schedule the cancel. + 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, + ) -> 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::attach(|py| { + let on_task = OnTask { + state: state.clone(), + }; + let request = PyBytes::new(py, &request.encode_to_vec()); + let coroutine = + (self.caller.bind(py)).call_method1("call", (operation, request, on_task))?; + pyo3_async_runtimes::into_future_with_locals(task_locals, coroutine) + }); + let answer = match called { + Ok(answer) => answer.await, + Err(err) => Err(err), + }; + Python::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)), + } + }) + } +} + +/// Returns the error of an operation for the exception of a Store. A `StreamError` is a refusal +/// with its reason, and any other exception is an outage, which the caller can try again. +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, + ) -> BoxFuture<'_, Result> { + Box::pin(self.call("CreateStream", request)) + } + + fn append_records( + &self, + request: AppendRecordsRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(self.call("AppendRecords", request)) + } + + fn read_records( + &self, + request: ReadRecordsRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(self.call("ReadRecords", request)) + } + + fn close_stream( + &self, + request: CloseStreamRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(self.call("CloseStream", request)) + } + + fn describe_stream( + &self, + request: DescribeStreamRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(self.call("DescribeStream", request)) + } +} + +/// Calls the Python Store of `caller` for one Stream operation through a `StreamRuntime`, which +/// checks the request and the response. The awaitable raises `StreamError` for a failed call. The +/// runtime has no limit of a batch, since the SDK that calls the Store has those in its Stream +/// config. +#[pyfunction] +pub fn call_stream_store<'p>( + py: Python<'p>, + runtime_ref: &runtime::RuntimeRef, + caller: Py, + operation: &str, + request: &Bound<'_, PyBytes>, +) -> PyResult> { + let task_locals = pyo3_async_runtimes::TaskLocals::with_running_loop(py)?.copy_context(py)?; + let store = PythonStore { + caller, + event_loop_task_locals: Arc::new(OnceLock::from(task_locals)), + }; + let stream_runtime = StreamRuntime::new(Arc::new(store), StoreLimits::UNBOUNDED); + macro_rules! run { + ($method:ident) => {{ + let request = Message::decode(request.as_bytes()) + .map_err(|err| PyValueError::new_err(format!("Invalid proto: {err}")))?; + runtime_ref.runtime.future_into_py(py, async move { + let response = stream_runtime.$method(request).await; + response + .map(|response| response.encode_to_vec()) + .map_err(|err| stream_error(err.reason.into(), err.message)) + }) + }}; + } + match operation { + "CreateStream" => run!(create_stream), + "AppendRecords" => run!(append_records), + "ReadRecords" => run!(read_records), + "CloseStream" => run!(close_stream), + "DescribeStream" => run!(describe_stream), + _ => Err(PyValueError::new_err(format!( + "Unknown Stream operation: {operation}" + ))), + } +} + +/// Returns a `temporalio.exceptions.StreamError`, or the error that building it raised. +fn stream_error(reason: StreamErrorReason, message: String) -> PyErr { + Python::attach(|py| { + let error = || { + let reason = [("reason", reason as i32)].into_py_dict(py)?; + stream_error_type(py)?.call((message,), Some(&reason)) + }; + error().map_or_else(|err| err, PyErr::from_value) + }) +} diff --git a/temporalio/bridge/streams.py b/temporalio/bridge/streams.py new file mode 100644 index 0000000000..c5516f9aa1 --- /dev/null +++ b/temporalio/bridge/streams.py @@ -0,0 +1,42 @@ +"""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 +from typing import Any, Protocol + +import temporalio.bridge.runtime +import temporalio.bridge.temporal_sdk_bridge + + +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, + on_task: Callable[[asyncio.Task[Any]], None], + ) -> bytes: + """Call the Store for a Stream operation with its encoded request, and + return its encoded response. + """ + ... + + +async def call_stream_store( + runtime: temporalio.bridge.runtime.Runtime, + caller: StoreCaller, + operation: str, + request: bytes, +) -> bytes: + """Call a Stream Store through the Stream runtime of SDK Core, which checks + the request and the response. + """ + return await temporalio.bridge.temporal_sdk_bridge.call_stream_store( + runtime._ref, caller, operation, request + ) 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..036673ffb2 --- /dev/null +++ b/temporalio/client/_stream_store.py @@ -0,0 +1,442 @@ +"""Stream Stores and the Stream config of a client.""" + +from __future__ import annotations + +import asyncio +import logging +from abc import ABC, abstractmethod +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from typing import Any + +import google.protobuf.message +import nexusrpc + +from temporalio.api.enums.v1 import StreamErrorReason +from temporalio.api.streamservice.v1 import ( + AppendRecordsRequest, + AppendRecordsResponse, + CloseStreamRequest, + CloseStreamResponse, + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, +) +from temporalio.converter import StorageDriverActivityInfo, StorageDriverWorkflowInfo +from temporalio.converter._payload_converter import _get_transfer_type_converter +from temporalio.exceptions import StreamError +from temporalio.nexus.system.stream_service import StreamRef, StreamService + +logger = logging.getLogger(__name__) + + +class StreamStore(ABC): + """Base class of a Stream Store, which keeps the Records of Streams. + + A Store serves the operations of the Nexus service + ``temporal.api.streamservice.v1.StreamService``. Each method takes the request + message of its operation and returns its response message, both from + :py:mod:`temporalio.api.streamservice.v1`. A :py:class:`StreamConfig` registers + a Store under its :py:meth:`name`, and the SDK sends each Stream call to the + Store of the call's ``StreamRef``. A request has the id of its Stream and never + a Store name, and no response has one. + + These docs use the following terms. A batch is the Records of one append. A + Producer is one writer of a Stream, which is a Workflow run, an Activity, a + Local Activity or a client. An attempt is the try of a Producer that made a + write, such as one Workflow Task or one attempt of an Activity. + + Callers rely on a Store to follow these rules. SDK Core reads a Stream for + Workflow code and reads it again in a replay, and both depend on the rules of + the log. + + The log: + + * The body of a Record is the payload that the append gave, which the payload + codec has already encoded. The Store keeps it as it is. + * A Store writes a batch whole or not at all. The Records of a batch are next + to each other in the Stream, in the order of the request. + * The offsets of a Stream sort bytewise in the order of its Records, and the + offset of a Record is never empty. + * Once a response returned an offset, no Record ever appears at or below it + later, even from an append that ran at the same time as that call. + * A Store doesn't change or remove a Record before its Stream expires. + + Producers and attempts: + + * Two Producers are the same when they have the same kind and the same ids of + that kind. The attempt isn't part of that. + * Fencing is optional. A Store that fences keeps the newest attempt of each + Producer that appended to a Stream, and refuses an append or a close of + that Producer from an earlier attempt. Only an append changes the newest + attempt, and a close doesn't. Every Record has its Producer and attempt + either way, so a reader can tell the attempts apart. + + A create: + + * A create for an id with no Stream makes the Stream and returns ``created`` + true. + * A create with the ``request_id`` of the create that made the Stream is a + retry of it. A create with an empty ``request_id`` is never a retry. + * A Store checks a create for an id that has a Stream in this order, and the + first check that applies decides the answer: + + 1. The Stream expired, so the create fails with ``EXPIRED``. + 2. The Stream is closed, so the create fails with ``CLOSED``. + 3. The create is a retry, so it returns ``created`` true. + 4. The policy is ``USE_EXISTING``, so the create returns ``created`` + false, and the ``created`` of the caller's ``Stream`` is then ``None``. + With ``FAIL``, or with no policy, it fails with ``ALREADY_EXISTS``. + + An append: + + * A Store remembers the request ids of the recent batches of each Producer of + a Stream. How many is a setting of the Store, and it's at least the last + batch. An append with the Producer, the attempt and the ``request_id`` of a + remembered batch is a resend. An append with an empty ``request_id``, or + one that comes after more batches than the Store remembers, isn't one. A + Store that doesn't fence compares Producers and attempts for this rule too. + * A Store checks an append in this order, and the first check that applies + decides the answer: + + 1. The Stream doesn't exist or it expired, so the append fails with + ``NOT_FOUND`` or ``EXPIRED``. + 2. The append is a resend, so the Store writes nothing and returns the + offsets of the first write of that batch. It doesn't compare the + Records, and the Stream can be closed by then. + 3. The Store fences, and a later attempt of the Producer already wrote. + The append fails with ``FENCED``. + 4. The Stream is closed, so the append fails with ``CLOSED``. + + * An append returns the offsets of its first and its last Record. + + A close: + + * A Store checks a close in this order, and the first check that applies + decides the answer: + + 1. The Stream doesn't exist or it expired, so the close fails with + ``NOT_FOUND`` or ``EXPIRED``. + 2. The Stream is already closed, so the close succeeds. + 3. The Store fences, and a later attempt of the Producer already wrote. + The close fails with ``FENCED``. + + A read: + + * A read returns the Records after ``from_offset``, in the order of the + Stream. Each Record has its body and the Producer of its append. + * A page has at most ``max_records`` Records, and Records of at most + ``max_bytes`` in total, where zero is no limit. It always has its first + Record, even when that Record alone is over ``max_bytes``. + * The ``last_offset`` of a page is where the next read continues. It's never + below ``from_offset`` or the offset of a Record in the page, and it must not + skip a Record. + * A page is ``done`` when the Stream is closed and no Record comes after the + page. That holds for an empty page too. + * A read with nothing after ``from_offset`` answers once a Record comes, once + the Stream is closed, or once its ``wait`` is up. With no ``wait``, or one + of zero, it answers immediately. + * A Store takes every offset that a response returned as the ``from_offset`` + of a read. That's the offset of a Record, an offset of an append, and a + ``last_offset``. A read fails with ``OFFSET_TOO_HIGH`` only when + ``from_offset`` is past the end of the Stream. + + A describe returns the status of the Stream, and a ``last_offset`` that is + never below the offset of the newest Record. + + A method refuses a call by raising a + :py:class:`temporalio.exceptions.StreamError` with the reason, such as + ``STREAM_ERROR_REASON_CLOSED`` for ``CLOSED`` above. Any other exception is an + outage of the Store, and the caller gets a ``StreamError`` with + ``STREAM_ERROR_REASON_STORE_UNAVAILABLE``. + + The SDK calls a Store in these ways: + + * Calls run at the same time on the event loop, and a read can wait while + appends run. + * The SDK cancels the task of a call. It does so at the ``rpc_timeout`` of a + client call, when Workflow code cancels a read, when a Workflow is evicted, + when a Worker shuts down, and at the deadline that SDK Core gives each try + of a call of Workflow code. + * A cancelled call may still have taken effect, and the Store must stay + usable after it. + * A resend can come while its first try still runs, and the Store still + writes the batch once. + + Who checks a call depends on the code that makes it: + + * For an append, a close or a read of Workflow code, SDK Core checks the + request before the Store gets it and the response before Workflow code + does, and it tries the call again during an outage. + * For every call of client or Activity code, and for a create or a describe + of Workflow code, the SDK checks the request of an append as SDK Core + does for one of Workflow code, and no other request. It only checks that + a response is the response message of the operation. It sends one request + for each call and tries nothing again, so a Store that needs more checks + runs them itself. Such a Store then checks the appends, closes and reads + of Workflow code a second time. + + The limits of a batch are those of the :py:class:`StreamConfig` of the + caller. The SDK checks each append against them before the Store gets it, + in Workflow code as in client and Activity code. + + The ``rpc_metadata`` of a Stream call has no effect, since a call to a Store + is not an RPC of the Temporal server. + + .. warning:: + This API is experimental and subject to change. + """ + + @abstractmethod + def name(self) -> str: + """Return the name that a :py:class:`StreamConfig` registers this Store + under. A Store may take its name as an argument, so that two instances of + one Store class can be in one config. + """ + raise NotImplementedError + + @abstractmethod + async def create_stream(self, request: CreateStreamRequest) -> CreateStreamResponse: + """Create a Stream, or return the open one that already exists if the + conflict policy of the request allows it. + """ + raise NotImplementedError + + @abstractmethod + async def append_records( + self, request: AppendRecordsRequest + ) -> AppendRecordsResponse: + """Append one batch from one Producer.""" + raise NotImplementedError + + @abstractmethod + async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: + """Read one page of Records after ``from_offset``.""" + raise NotImplementedError + + @abstractmethod + async def close_stream(self, request: CloseStreamRequest) -> CloseStreamResponse: + """Close a Stream.""" + raise NotImplementedError + + @abstractmethod + async def describe_stream( + self, request: DescribeStreamRequest + ) -> DescribeStreamResponse: + """Return the status and the newest offset of a 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.""" + + target: StorageDriverActivityInfo | StorageDriverWorkflowInfo | None = None + """The Workflow or the Activity that makes the call, or ``None`` for other + client code.""" + + +@dataclass(frozen=True) +class StreamConfig: + """The Stream Stores of a client and of each Worker that uses the client. + + The SDK checks each append against :py:attr:`max_record_bytes`, + :py:attr:`max_batch_bytes` and :py:attr:`max_batch_records` before its Store + gets it, and refuses one over a limit with + ``STREAM_ERROR_REASON_TOO_LARGE``. + + .. 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 + """Picks the Store of a call whose ``StreamRef`` has no Store name. It must + return one of :py:attr:`stores`. + + Required when more than one Store is registered. When ``None``, the one + Store takes each such call. + + A Workflow replay calls the selector again, so it must return the same Store + for the same call. + """ + + max_record_bytes: int = 1536 * 1024 + """Maximum size in bytes of one Record of an append. Defaults to 1.5 MiB. + Must be greater than or equal to one. The size is that of the stored + Record, which counts its Producer. + """ + + 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. + """ + + 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." + ) + names: set[str] = set() + 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 names: + raise ValueError( + f"StreamConfig.stores contains multiple Stores with name '{name}'. " + "Each Store must have a unique name." + ) + names.add(name) + + def _store_for( + self, + ref: StreamRef[Any], + target: StorageDriverActivityInfo | StorageDriverWorkflowInfo | None, + ) -> StreamStore: + """Return the Store of a call on ``ref``, raising :class:`ValueError` if + there is none. + """ + if ref.store: + for store in self.stores: + if store.name() == ref.store: + return store + raise ValueError(f"No Stream Store found with name '{ref.store}'") + if self.store_selector is None: + return self.stores[0] + selected = self.store_selector(StreamSelectContext(id=ref.id, target=target)) + if not any(selected is store for store in self.stores): + raise ValueError( + "Store returned by store_selector is not registered in StreamConfig.stores" + ) + return selected + + +def _operation( + name: str, +) -> tuple[ + str, type[google.protobuf.message.Message], type[google.protobuf.message.Message] +]: + """Return the :py:class:`StreamStore` method of a Stream operation, with the + classes of its request message and of its response message. + """ + definition = nexusrpc.get_service_definition(StreamService) + assert definition + operation = definition.operation_definitions[name] + request, response = ( + _get_transfer_type_converter(model) + for model in (operation.input_type, operation.output_type) + ) + assert request and request.transfer_type and response and response.transfer_type + return operation.method_name, request.transfer_type, response.transfer_type + + +async def _call_method( + store: StreamStore, operation: str, request: google.protobuf.message.Message +) -> google.protobuf.message.Message: + """Call the method of ``store`` for a Stream operation. + + Raises: + StreamError: The Store refused the call. The reason is + ``STREAM_ERROR_REASON_STORE_UNAVAILABLE`` if the method raised any + other exception, and ``STREAM_ERROR_REASON_STORE_CORRUPT`` if it + returned something else than the response message of the operation. + """ + method, _, response_type = _operation(operation) + try: + response = await getattr(store, method)(request) + except StreamError: + raise + except Exception as err: + raise StreamError( + f"The Stream Store '{store.name()}' failed the {operation} call " + f"with {type(err).__name__}: {err}", + reason=StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE, + ) from err + if not isinstance(response, response_type): + raise StreamError( + f"The Stream Store '{store.name()}' answered the {operation} call with " + f"{type(response).__name__}, not with {response_type.__name__}", + reason=StreamErrorReason.STREAM_ERROR_REASON_STORE_CORRUPT, + ) + return response + + +class _StoreCaller: # pyright: ignore[reportUnusedClass] + """The caller of a Stream Store for the bridge, which gives and takes encoded + messages. + + SDK Core calls :py:meth:`call` for each append, close and read of Workflow + code. + """ + + def __init__(self, store: Callable[[], StreamStore]) -> None: + """Create a caller of the Store that ``store`` returns at each call.""" + self._store = store + + async def call( + self, + operation: str, + request: bytes, + on_task: Callable[[asyncio.Task[Any]], None], + ) -> bytes: + """Call the Store for a Stream operation and return its encoded response. + + ``on_task`` gets the task of this call, so that the bridge can cancel it. + It raises :py:class:`asyncio.CancelledError` if the bridge has already + dropped the call. + """ + task = asyncio.current_task() + assert task + on_task(task) + _, request_type, _ = _operation(operation) + try: + response = await _call_method( + self._store(), operation, request_type.FromString(request) + ) + 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 a %s call", operation, exc_info=err.__cause__ + ) + raise + return response.SerializeToString() 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. 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..9d96b77412 --- /dev/null +++ b/temporalio/testing/_stream_store.py @@ -0,0 +1,406 @@ +"""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 + +import temporalio.bridge.streams +import temporalio.runtime +from temporalio.api.enums.v1 import ( + StreamErrorReason, + StreamIdConflictPolicy, + StreamStatus, +) +from temporalio.api.stream.v1 import ( + ActivityAttempt, + LocalActivityAttempt, + Producer, + StreamRecord, + WorkflowTaskAttempt, +) +from temporalio.api.streamservice.v1 import ( + AppendRecordsRequest, + AppendRecordsResponse, + CloseStreamRequest, + CloseStreamResponse, + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, +) +from temporalio.client._stream_store import StreamStore, _StoreCaller +from temporalio.exceptions import StreamError + +_Attempt = tuple[int, ...] + + +class MemoryStreamStore(StreamStore): + """Stream Store that keeps its Streams in the memory of this process. + + It's for tests and local runs. It loses its Streams when the process ends, + and a client and a Worker see the same Streams only through the same + instance, in one event loop. + + The Store runs the checks of SDK Core on each request and on each response, + also for a call of client or Activity code. So a call fails on it as it fails + on a Store package that runs those checks. An append, a close or a read of + Workflow code is then checked twice, by the Worker and by the Store. The + Store has no limit of a batch, since the limits are those of the + :py:class:`temporalio.client.StreamConfig` of the caller. + + .. warning:: + This API is experimental and subject to change. + """ + + def __init__( + self, + *, + name: str = "memory", + retention: timedelta | None = None, + producer_idle_ttl: timedelta | None = None, + resend_window: int | None = None, + fence: bool = False, + runtime: temporalio.runtime.Runtime | None = None, + ) -> None: + """Create a memory Store. + + Args: + name: The name of the Store in a + :py:class:`temporalio.client.StreamConfig`. + retention: How long after its close a Stream expires. Defaults to 7 + days. + producer_idle_ttl: How long after its last write an open Stream + expires. If unset, an open Stream doesn't expire. + 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, and so does its close of + an open Stream. + runtime: The runtime whose threads run the checks of SDK Core. + Defaults to :py:meth:`temporalio.runtime.Runtime.default`. + """ + if resend_window is not None and resend_window < 1: + raise ValueError("resend_window must be greater than zero.") + self._name = name + self._runtime = runtime + streams = _MemoryStreams( + name, + retention=timedelta(days=7) if retention is None else retention, + producer_idle_ttl=producer_idle_ttl, + resend_window=16 if resend_window is None else resend_window, + fence=fence, + ) + self._caller = _StoreCaller(lambda: streams) + + def name(self) -> str: + """See base class.""" + return self._name + + async def create_stream(self, request: CreateStreamRequest) -> CreateStreamResponse: + """See base class.""" + return CreateStreamResponse.FromString( + await self._call("CreateStream", request) + ) + + async def append_records( + self, request: AppendRecordsRequest + ) -> AppendRecordsResponse: + """See base class.""" + return AppendRecordsResponse.FromString( + await self._call("AppendRecords", request) + ) + + async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: + """See base class.""" + return ReadRecordsResponse.FromString(await self._call("ReadRecords", request)) + + async def close_stream(self, request: CloseStreamRequest) -> CloseStreamResponse: + """See base class.""" + return CloseStreamResponse.FromString(await self._call("CloseStream", request)) + + async def describe_stream( + self, request: DescribeStreamRequest + ) -> DescribeStreamResponse: + """See base class.""" + return DescribeStreamResponse.FromString( + await self._call("DescribeStream", request) + ) + + async def _call( + self, operation: str, request: google.protobuf.message.Message + ) -> bytes: + runtime = self._runtime or temporalio.runtime.Runtime.default() + return await temporalio.bridge.streams.call_stream_store( + runtime._core_runtime, self._caller, operation, request.SerializeToString() + ) + + +@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 | None + """The time of the event loop at which the Stream expires, if it does.""" + + records: list[StreamRecord] = field(default_factory=list) + writers: dict[bytes, _Writer] = field(default_factory=dict) + closed: bool = False + changed: asyncio.Event = field(default_factory=asyncio.Event) + """Set at the next append or close, which then puts a new event here.""" + + @property + def last_offset(self) -> bytes: + return self.records[-1].offset if self.records else b"" + + +class _MemoryStreams(StreamStore): + """The Streams of a :py:class:`MemoryStreamStore`, which checks no request.""" + + def __init__( + self, + name: str, + *, + retention: timedelta, + producer_idle_ttl: timedelta | None, + resend_window: int, + fence: bool, + ) -> None: + self._name = name + self._retention = retention + self._producer_idle_ttl = producer_idle_ttl + self._resend_window = resend_window + self._fence = fence + self._streams: dict[str, _Stream] = {} + + def name(self) -> str: + return self._name + + async def create_stream(self, request: CreateStreamRequest) -> CreateStreamResponse: + if request.stream_id not in self._streams: + self._streams[request.stream_id] = _Stream( + request.request_id, self._idle_expiry() + ) + return CreateStreamResponse(created=True) + stream = self._stream(request.stream_id) + if stream.closed: + raise StreamError( + f"The Stream '{request.stream_id}' is closed", + reason=StreamErrorReason.STREAM_ERROR_REASON_CLOSED, + ) + # An empty request id identifies no create, so it never matches. + if request.request_id and request.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 '{request.stream_id}' already exists", + reason=StreamErrorReason.STREAM_ERROR_REASON_ALREADY_EXISTS, + ) + + async def append_records( + self, request: AppendRecordsRequest + ) -> AppendRecordsResponse: + 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.request_id: + for batch in writer.window: + if (batch.attempt, batch.request_id) == (attempt, request.request_id): + return batch.response + if self._fence and attempt < writer.newest: + raise _fenced(request.stream_id) + if stream.closed: + raise StreamError( + f"The Stream '{request.stream_id}' is closed", + reason=StreamErrorReason.STREAM_ERROR_REASON_CLOSED, + ) + 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.request_id, response)) + stream.writers[key] = writer + stream.expires_at = self._idle_expiry() + self._notify(stream) + return response + + async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: + stream = self._stream(request.stream_id) + if request.from_offset > stream.last_offset: + raise StreamError( + f"The from_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.from_offset, key=lambda record: record.offset + ) + wait = request.wait.ToTimedelta().total_seconds() + if start == len(stream.records) and not stream.closed and wait > 0: + try: + async with asyncio.timeout(wait): + await stream.changed.wait() + except TimeoutError: + pass + end = len(stream.records) + if request.max_records > 0: + end = min(end, start + request.max_records) + records = stream.records[start:end] + return ReadRecordsResponse( + records=records, + last_offset=records[-1].offset if records else request.from_offset, + done=stream.closed and end == len(stream.records), + ) + + async def close_stream(self, request: CloseStreamRequest) -> CloseStreamResponse: + stream = self._stream(request.stream_id) + if stream.closed: + return CloseStreamResponse() + writer = stream.writers.get(_producer_key(request.producer)) + if self._fence and writer and _attempt(request.producer) < writer.newest: + raise _fenced(request.stream_id) + stream.closed = True + stream.expires_at = self._now() + self._retention.total_seconds() + self._notify(stream) + return CloseStreamResponse() + + async def describe_stream( + self, request: DescribeStreamRequest + ) -> DescribeStreamResponse: + stream = self._stream(request.stream_id) + return DescribeStreamResponse( + status=StreamStatus.STREAM_STATUS_CLOSED + if stream.closed + else StreamStatus.STREAM_STATUS_OPEN, + 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 stream.expires_at is not None and 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 _idle_expiry(self) -> float | None: + if self._producer_idle_ttl is None: + return None + return self._now() + self._producer_idle_ttl.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, "SDK Core refuses a Producer with no kind" + 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. + + Its fields are these, in the order that two attempts compare by them: + + 1. The started event id of the Workflow Task + 2. The attempt number of that Workflow Task + 3. The seconds of the task's started time + 4. The nanoseconds of the task's started time + 5. The seconds of the Activity attempt's scheduled time + 6. The nanoseconds of the Activity attempt's scheduled time + 7. The attempt number of the Activity or the Local Activity + + 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 index 031aa30792..f4667bdc84 100644 --- a/tests/helpers/streams.py +++ b/tests/helpers/streams.py @@ -1,6 +1,10 @@ """Helpers for the tests of Streams.""" -from collections.abc import Sequence +import asyncio +import selectors +from collections.abc import Coroutine, Iterator, Sequence +from contextlib import contextmanager +from typing import Any, TypeVar from temporalio.api.common.v1 import Payload from temporalio.converter import ( @@ -9,6 +13,8 @@ WithSerializationContext, ) +_T = TypeVar("_T") + CodecCall = tuple[str, SerializationContext | None, int] @@ -56,3 +62,59 @@ def wrapped(payload: Payload, context: SerializationContext | None = None) -> Pa }, data=payload.SerializeToString(), ) + + +@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.""" + loop = VirtualClockLoop() + try: + return loop.run_until_complete(main) + finally: + loop.close() diff --git a/tests/testing/test_stream_store.py b/tests/testing/test_stream_store.py new file mode 100644 index 0000000000..a6f60c48e1 --- /dev/null +++ b/tests/testing/test_stream_store.py @@ -0,0 +1,455 @@ +"""Tests of the memory Stream Store.""" + +import asyncio +import random +import time +from collections.abc import Awaitable +from dataclasses import dataclass, field +from datetime import timedelta +from typing import Any +from unittest.mock import patch + +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, + CloseStreamRequest, + CloseStreamResponse, + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, +) +from temporalio.bridge.streams import call_stream_store +from temporalio.client._stream_store import _StoreCaller +from temporalio.exceptions import StreamError +from temporalio.runtime import Runtime, TelemetryConfig +from temporalio.testing import MemoryStreamStore +from temporalio.testing._stream_store import _MemoryStreams +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 +_CLOSED = StreamErrorReason.STREAM_ERROR_REASON_CLOSED +_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, ...] + """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 = same.ids[0] if same else rng.choice(list(Producer.DESCRIPTOR.fields_by_name)) + kind = getattr(producer, name) + kind.SetInParent() + ids = [name] + for id_field in kind.DESCRIPTOR.fields: + if id_field.type == id_field.TYPE_STRING: + if not same: + setattr(kind, id_field.name, rng.choice("aab")) + 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 + closed: bool = False + 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) -> Any: + stream = self.streams.get(request.stream_id) + if stream is None: + self.streams[request.stream_id] = _ModelStream(request.request_id) + return CreateStreamResponse(created=True) + if stream.closed: + return _CLOSED + if request.request_id and request.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) -> Any: + # SDK Core refuses a batch with no Record before the Store gets it. + if not request.records: + return StreamErrorReason.STREAM_ERROR_REASON_INVALID_ARGUMENT + 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.request_id and (batch.writer.rank, batch.request_id) == ( + writer.rank, + request.request_id, + ): + return batch.response + if self.fence and stream.fenced(writer): + return _FENCED + if stream.closed: + return _CLOSED + 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.request_id, response)) + return response + + def close(self, request: CloseStreamRequest, writer: _Writer) -> Any: + stream = self.streams.get(request.stream_id) + if stream is None: + return _NOT_FOUND + if not stream.closed and self.fence and stream.fenced(writer): + return _FENCED + stream.closed = True + return CloseStreamResponse() + + 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.from_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, + last_offset=records[-1].offset if records else request.from_offset, + done=stream.closed and start + len(records) == len(stream.records), + ) + + +_OPERATIONS = ["create", "append", "again", "close", "read"] +_WEIGHTS = [3, 10, 6, 1, 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_the_memory_store_keeps_the_rules_of_the_redis_store() -> None: + own = Runtime(telemetry=TelemetryConfig()) + for seed in range(150): + with failure_note(f"seed {seed}"): + await _store_script(random.Random(seed), None) + # A Store with a runtime of its own runs its checks there, and not on the default one. + with patch.object(Runtime, "default", side_effect=AssertionError("The default")): + await _store_script(random.Random(0), own) + + +async def _store_script(rng: random.Random, runtime: Runtime | None) -> None: + model = _Model(resend_window=rng.randrange(1, 4), fence=rng.random() < 0.5) + store = MemoryStreamStore( + resend_window=model.resend_window, fence=model.fence, runtime=runtime + ) + appends: list[tuple[AppendRecordsRequest, _Writer]] = [] + 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, + request_id=rng.choice(["", "r1", "r2"]), + id_conflict_policy=rng.choice( + list(StreamIdConflictPolicy.values()) + ), + ) + expected = model.create(request) + answer = await _answer(store.create_stream(request)) + 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 = rng.choice(appends) + request.CopyFrom(earlier) + del request.records[:] + for _ in range(rng.randrange(3)): + body = Payload(data=bytes([rng.randrange(256)])) + request.records.append(AppendRecord(body=body)) + appends.append((request, writer)) + expected = model.append(request, writer) + answer = await _answer(store.append_records(request)) + case "close": + request = CloseStreamRequest( + stream_id=stream_id, producer=writer.producer + ) + expected = model.close(request, writer) + answer = await _answer(store.close_stream(request)) + case _: + request = ReadRecordsRequest( + stream_id=stream_id, + from_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, idle_ttl: int | None = None) -> _MemoryStreams: + return _MemoryStreams( + "memory", + retention=timedelta(seconds=retention), + producer_idle_ttl=None if idle_ttl is None else timedelta(seconds=idle_ttl), + resend_window=1, + fence=False, + ) + + +def _client_append(stream_id: str) -> AppendRecordsRequest: + request = AppendRecordsRequest(stream_id=stream_id, records=[AppendRecord()]) + request.producer.client.SetInParent() + return request + + +def _client_close(stream_id: str) -> CloseStreamRequest: + request = CloseStreamRequest(stream_id=stream_id) + request.producer.client.SetInParent() + return request + + +def test_a_stream_expires_after_its_retention_or_its_idle_ttl() -> None: + async def script(rng: random.Random) -> None: + loop = asyncio.get_running_loop() + retention, idle_ttl = rng.randrange(1, 50), rng.choice([None, 10, 30]) + streams = _streams(retention, idle_ttl) + await streams.create_stream(CreateStreamRequest(stream_id="s")) + closed = False + expires_at = None if idle_ttl is None else loop.time() + idle_ttl + for step in range(12): + await asyncio.sleep(rng.randrange(40)) + expired = expires_at is not None and loop.time() >= expires_at + match rng.choice( + ["append", "append", "close", "read", "describe", "create"] + ): + case "append": + answer = await _answer(streams.append_records(_client_append("s"))) + expected: Any = _CLOSED if closed else AppendRecordsResponse + if not expired and not closed and idle_ttl is not None: + expires_at = loop.time() + idle_ttl + case "close": + answer = await _answer(streams.close_stream(_client_close("s"))) + expected = CloseStreamResponse + if not expired and not closed: + closed, expires_at = True, loop.time() + retention + 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 _: + create = CreateStreamRequest(stream_id="s", request_id="other") + answer = await _answer(streams.create_stream(create)) + expected = ( + _CLOSED + if closed + else StreamErrorReason.STREAM_ERROR_REASON_ALREADY_EXISTS + ) + 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))) + + +def test_a_read_waits_for_the_next_write_or_for_its_wait() -> None: + async def script(rng: random.Random) -> None: + loop = asyncio.get_running_loop() + streams = _streams() + await streams.create_stream(CreateStreamRequest(stream_id="s")) + first = await streams.append_records(_client_append("s")) + wait, write_in = rng.sample(range(1, 60), 2) + write = rng.choice(["append", "close", None]) + read = asyncio.ensure_future( + streams.read_records( + ReadRecordsRequest( + stream_id="s", + from_offset=first.last_offset, + wait=Duration(seconds=wait), + ) + ) + ) + answered_at: list[float] = [] + read.add_done_callback(lambda _: answered_at.append(loop.time())) + await asyncio.sleep(write_in) + if write == "append": + await streams.append_records(_client_append("s")) + elif write == "close": + await streams.close_stream(_client_close("s")) + page = await read + in_time = write is not None and write_in < wait + assert ( + answered_at == [float(write_in if in_time else wait)] + and len(page.records) == (in_time and write == "append") + and page.done == (in_time and write == "close") + ), f"{page} at {answered_at}" + + for seed in range(200): + with failure_note(f"seed {seed}"): + run_with_virtual_clock(script(random.Random(seed))) + + +async def test_a_dropped_store_call_never_reaches_the_store() -> None: + asked: list[str] = [] + + class Waiting(MemoryStreamStore): + async def describe_stream( + self, request: DescribeStreamRequest + ) -> DescribeStreamResponse: + asked.append("call") + try: + return await asyncio.Future() + finally: + asked.append("cancel") + + def store() -> MemoryStreamStore: + asked.append("store") + return Waiting() + + 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, on_task) + assert not asked + + # Core drops this call after it made the task of the call and before the task ran, + # since the loop is blocked in between. A task that ran anyway is cancelled. + loop = asyncio.get_running_loop() + call = asyncio.ensure_future( + call_stream_store( + Runtime.default()._core_runtime, + _StoreCaller(store), + "DescribeStream", + request, + ) + ) + time.sleep(0.05) + await asyncio.sleep(0) + call.cancel() + loop.call_soon(time.sleep, 0.2) + await asyncio.sleep(0.3) + assert asked in ([], ["store", "call", "cancel"]) From 0a8c3463e31e20ce9910dd01c09bac0721b213d9 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Fri, 20 Nov 2026 20:47:04 -0700 Subject: [PATCH 03/50] Add Stream Stores to the client The server has no Streams yet, so the last client interceptor sends each Stream call to a Store of the client's Stream config. The generated Stream code also needs its helpers, with the three that build a Producer. --- changelog/added/steady-stream-heron.md | 1 + temporalio/bridge/src/lib.rs | 1 + temporalio/bridge/src/streams.rs | 27 ++ temporalio/bridge/streams.py | 12 + temporalio/client/_client.py | 22 +- temporalio/client/_impl.py | 7 + temporalio/client/_stream_store.py | 129 +++++- temporalio/contrib/streams/__init__.py | 13 + temporalio/contrib/streams/_producer.py | 60 +++ temporalio/nexus/system/__init__.py | 4 + temporalio/nexus/system/_support.py | 210 ++++++++- temporalio/testing/_workflow.py | 12 + tests/helpers/streams.py | 114 ++++- tests/nexus/test_streams.py | 549 ++++++++++++++++++++++++ 14 files changed, 1153 insertions(+), 8 deletions(-) create mode 100644 temporalio/contrib/streams/__init__.py create mode 100644 temporalio/contrib/streams/_producer.py create mode 100644 tests/nexus/test_streams.py diff --git a/changelog/added/steady-stream-heron.md b/changelog/added/steady-stream-heron.md index 0f96918ad1..c6762b02d4 100644 --- a/changelog/added/steady-stream-heron.md +++ b/changelog/added/steady-stream-heron.md @@ -1 +1,2 @@ Add experimental `temporalio.client.StreamStore`, the base class of a Stream Store, and `temporalio.testing.MemoryStreamStore`, a Store that keeps its Streams in memory for tests and local runs. +Add experimental Streams for client and Activity code. `stream_config=StreamConfig(stores=[...])` of `Client.connect` gives a client its Stream Stores, and `Client.create_stream` and `Client.get_stream` return a `Stream` to append to, read, describe and close. A failed call raises `temporalio.exceptions.StreamError` with a `reason`. `max_record_bytes`, `max_batch_bytes` and `max_batch_records` of `StreamConfig` bound an append, and one over a limit fails before its Store gets it. A read of a Stream from `get_stream` needs `body_type=` or a `StreamRef` with a type argument, and raises `TypeError` with neither. `temporalio.contrib.streams.current_producer` gives the Producer of an Activity attempt, and `as_producer` gives back one that code stored. diff --git a/temporalio/bridge/src/lib.rs b/temporalio/bridge/src/lib.rs index 05da9d13c9..246a6059a9 100644 --- a/temporalio/bridge/src/lib.rs +++ b/temporalio/bridge/src/lib.rs @@ -56,6 +56,7 @@ fn temporal_sdk_bridge(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { // Stream stuff m.add_function(wrap_pyfunction!(streams::call_stream_store, m)?)?; + m.add_function(wrap_pyfunction!(streams::check_stream_append, m)?)?; // Testing stuff m.add_class::()?; diff --git a/temporalio/bridge/src/streams.rs b/temporalio/bridge/src/streams.rs index 5cc96524c6..d14493f625 100644 --- a/temporalio/bridge/src/streams.rs +++ b/temporalio/bridge/src/streams.rs @@ -239,6 +239,33 @@ pub fn call_stream_store<'p>( } } +/// Returns the limits of a Stream config, which Python gives as its `max_record_bytes`, +/// `max_batch_bytes` and `max_batch_records`. +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)) +} + +/// Checks an encoded append of client code as the runtime of a Worker checks one of Workflow +/// code, with the limits of the Stream config. Client code reaches its Store through no such +/// runtime. Raises `StreamError` for an append that the check refuses. +#[pyfunction] +pub fn check_stream_append( + limits: (usize, usize, usize), + request: &Bound<'_, PyBytes>, +) -> PyResult<()> { + let request = Message::decode(request.as_bytes()) + .map_err(|err| PyValueError::new_err(format!("Invalid proto: {err}")))?; + store_limits(limits)? + .check_append(&request) + .map_err(|err| stream_error(err.reason.into(), err.message)) +} + /// Returns a `temporalio.exceptions.StreamError`, or the error that building it raised. fn stream_error(reason: StreamErrorReason, message: String) -> PyErr { Python::attach(|py| { diff --git a/temporalio/bridge/streams.py b/temporalio/bridge/streams.py index c5516f9aa1..70b1ffe10a 100644 --- a/temporalio/bridge/streams.py +++ b/temporalio/bridge/streams.py @@ -40,3 +40,15 @@ async def call_stream_store( return await temporalio.bridge.temporal_sdk_bridge.call_stream_store( runtime._ref, caller, operation, request ) + + +def check_append(limits: tuple[int, int, int], request: bytes) -> None: + """Check an encoded append as SDK Core checks one of Workflow code. + + ``limits`` are the ``max_record_bytes``, the ``max_batch_bytes`` and the + ``max_batch_records`` of a Stream config. + + Raises: + temporalio.exceptions.StreamError: The check refuses the append. + """ + temporalio.bridge.temporal_sdk_bridge.check_stream_append(limits, request) diff --git a/temporalio/client/_client.py b/temporalio/client/_client.py index efef5cb528..e6bdaebcd7 100644 --- a/temporalio/client/_client.py +++ b/temporalio/client/_client.py @@ -2,6 +2,7 @@ from __future__ import annotations +import uuid from collections.abc import ( Awaitable, Callable, @@ -28,6 +29,7 @@ import temporalio.runtime import temporalio.service import temporalio.workflow +from temporalio.nexus.system.stream_service.client import StreamServiceClientExtension from temporalio.service import ( ConnectConfig, DnsLoadBalancingConfig, @@ -94,6 +96,7 @@ ScheduleBackfill, ScheduleHandle, ) +from ._stream_store import StreamConfig from ._worker_versioning import ( BuildIdOp, TaskReachabilityType, @@ -114,7 +117,7 @@ from ._plugin import Plugin -class Client: +class Client(StreamServiceClientExtension): """Client for accessing Temporal. Most users will use :py:meth:`connect` to create a client. The @@ -156,6 +159,7 @@ async def connect( grpc_compression: GrpcCompression = GrpcCompression.GZIP, payload_limits: PayloadLimitsConfig = PayloadLimitsConfig(), header_codec_behavior: HeaderCodecBehavior = HeaderCodecBehavior.NO_CODEC, + stream_config: StreamConfig | None = None, ) -> Self: """Connect to a Temporal server. @@ -225,6 +229,15 @@ async def connect( payload_limits: Warning thresholds for outbound payload/memo sizes. Over-threshold fields are logged but still sent. Set a threshold to 0 to disable it. header_codec_behavior: Encoding behavior for headers sent by the client. + stream_config: Stream Stores of this client and of each worker that + uses it. The client sends each Stream call to one of these + Stores, so a Stream call of a client with none raises + :exc:`ValueError`. A client interceptor that changes the Stream + of a call must change the ``ref`` of the request in place, since + a created Stream takes the ref of its create request. + + .. warning:: + This API is experimental and subject to change. """ connect_config = temporalio.service.ConnectConfig( target_host=target_host, @@ -262,6 +275,7 @@ def make_lambda( default_workflow_query_reject_condition=default_workflow_query_reject_condition, header_codec_behavior=header_codec_behavior, plugins=plugins, + stream_config=stream_config, ) def __init__( @@ -275,6 +289,7 @@ def __init__( default_workflow_query_reject_condition: None | (temporalio.common.QueryRejectCondition) = None, header_codec_behavior: HeaderCodecBehavior = HeaderCodecBehavior.NO_CODEC, + stream_config: StreamConfig | None = None, ): """Create a Temporal client from a service client. @@ -289,8 +304,11 @@ def __init__( interceptors=interceptors, default_workflow_query_reject_condition=default_workflow_query_reject_condition, header_codec_behavior=header_codec_behavior, + stream_config=stream_config, ) self._initial_config = config.copy() + # The id of this client as a Producer of Streams + self._stream_producer_id = str(uuid.uuid4()) for plugin in plugins: config = plugin.configure_client(config) @@ -3029,6 +3047,7 @@ class ClientConnectConfig(TypedDict, total=False): grpc_compression: GrpcCompression payload_limits: PayloadLimitsConfig header_codec_behavior: HeaderCodecBehavior + stream_config: StreamConfig | None class ClientConfig(TypedDict, total=False): @@ -3043,3 +3062,4 @@ class ClientConfig(TypedDict, total=False): temporalio.common.QueryRejectCondition | None ] header_codec_behavior: Required[HeaderCodecBehavior] + stream_config: Required[StreamConfig | None] diff --git a/temporalio/client/_impl.py b/temporalio/client/_impl.py index e6424c15eb..d647abc5e9 100644 --- a/temporalio/client/_impl.py +++ b/temporalio/client/_impl.py @@ -34,6 +34,7 @@ import temporalio.exceptions import temporalio.nexus import temporalio.nexus._operation_context +import temporalio.nexus.system from temporalio.activity import ActivityCancellationDetails from temporalio.converter import ( ActivitySerializationContext, @@ -126,6 +127,7 @@ ScheduleUpdate, ScheduleUpdateInput, ) +from ._stream_store import _STREAM_SERVICE, _call_stream_store from ._worker_versioning import WorkerBuildIdVersionSets, WorkerTaskReachability from ._workflow import ( WorkflowExecutionAsyncIterator, @@ -1581,6 +1583,11 @@ async def start_nexus_operation( self, input: StartNexusOperationInput ) -> NexusOperationHandle[Any]: """Start a nexus operation and return a handle to it.""" + if ( + temporalio.nexus.system.is_system_endpoint(input.endpoint) + and input.service == _STREAM_SERVICE.name + ): + return await _call_stream_store(self._client, input) nexus_context = temporalio.converter.NexusSerializationContext( endpoint=input.endpoint, service=input.service, diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 036673ffb2..5ff339c10e 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -7,11 +7,19 @@ from abc import ABC, abstractmethod from collections.abc import Callable, Sequence from dataclasses import dataclass +from datetime import timedelta from typing import Any import google.protobuf.message import nexusrpc +import temporalio.activity +import temporalio.bridge.streams + +# pydoctor reads this module before the client package, for the worker modules that +# import it. A `from` import of a sibling here would lose the package's re-exports. +import temporalio.client +import temporalio.nexus.system._support from temporalio.api.enums.v1 import StreamErrorReason from temporalio.api.streamservice.v1 import ( AppendRecordsRequest, @@ -25,13 +33,21 @@ ReadRecordsRequest, ReadRecordsResponse, ) -from temporalio.converter import StorageDriverActivityInfo, StorageDriverWorkflowInfo +from temporalio.converter import ( + PayloadCodec, + StorageDriverActivityInfo, + StorageDriverWorkflowInfo, +) from temporalio.converter._payload_converter import _get_transfer_type_converter from temporalio.exceptions import StreamError -from temporalio.nexus.system.stream_service import StreamRef, StreamService +from temporalio.nexus.system.stream_service import StreamRef, StreamService, models logger = logging.getLogger(__name__) +_definition = nexusrpc.get_service_definition(StreamService) +assert _definition +_STREAM_SERVICE: nexusrpc.ServiceDefinition = _definition + class StreamStore(ABC): """Base class of a Stream Store, which keeps the Records of Streams. @@ -348,6 +364,10 @@ def _store_for( ) return selected + def _limits(self) -> tuple[int, int, int]: + """Return the three limits, in the order in which the bridge takes them.""" + return self.max_record_bytes, self.max_batch_bytes, self.max_batch_records + def _operation( name: str, @@ -357,9 +377,7 @@ def _operation( """Return the :py:class:`StreamStore` method of a Stream operation, with the classes of its request message and of its response message. """ - definition = nexusrpc.get_service_definition(StreamService) - assert definition - operation = definition.operation_definitions[name] + operation = _STREAM_SERVICE.operation_definitions[name] request, response = ( _get_transfer_type_converter(model) for model in (operation.input_type, operation.output_type) @@ -399,6 +417,107 @@ async def _call_method( return response +async def _call_store( # pyright: ignore[reportUnusedFunction] + store: StreamStore, + limits: tuple[int, int, int], + codec: PayloadCodec | None, + operation: str, + request: google.protobuf.message.Message, + timeout: timedelta | None = None, +) -> google.protobuf.message.Message: + """Call a Store for client code, which is :py:func:`_call_method` with the + payload codec, the check of an append and a timeout. + + The codec gets each body of an append and each Record of a read alone, with no + serialization context, since the reader of a Record can be any code. ``limits`` + are those of the Stream config, from :py:meth:`StreamConfig._limits`. + """ + if codec and isinstance(request, AppendRecordsRequest): + for appended in request.records: + [body] = await codec.encode([appended.body]) + appended.body.CopyFrom(body) + if isinstance(request, AppendRecordsRequest): + # SDK Core checks an append of Workflow code the same way, so each path refuses + # the same batch before its Store gets it. + temporalio.bridge.streams.check_append(limits, request.SerializeToString()) + try: + # A timeout of zero is no timeout, as for an RPC of the client. + async with asyncio.timeout(timeout.total_seconds() if timeout else None): + response = await _call_method(store, operation, request) + except TimeoutError as err: + raise StreamError( + f"The Stream Store '{store.name()}' didn't answer the {operation} call " + "within its rpc_timeout", + reason=StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE, + ) from err + if codec and isinstance(response, ReadRecordsResponse): + for record in response.records: + [body] = await codec.decode([record.body]) + record.body.CopyFrom(body) + return response + + +def _activity_target() -> StorageDriverActivityInfo | None: + """Return the running Activity as the target of a Stream call, if there is one.""" + if not temporalio.activity.in_activity(): + return None + info = temporalio.activity.info() + return StorageDriverActivityInfo( + id=info.activity_id, + type=info.activity_type, + run_id=info.activity_run_id, + namespace=info.namespace, + ) + + +async def _call_stream_store( # pyright: ignore[reportUnusedFunction] + client: temporalio.client.Client, + input: temporalio.client.StartNexusOperationInput, +) -> temporalio.client.NexusOperationHandle[Any]: + """Call the Stream Store of a Stream operation of a client, and return a handle + that has its result. + """ + stream_config = client._config["stream_config"] + if stream_config is None: + raise ValueError( + "Client has no stream_config, which every Stream call requires." + ) + request = input.arg + store = stream_config._store_for(request.ref, _activity_target()) + if isinstance(request, models.CreateStreamRequest): + # The created Stream takes the ref of its request. + request.ref.store = store.name() + data_converter = client.data_converter + converters = ( + data_converter.payload_converter, + data_converter.failure_converter, + ) + response = await _call_store( + store, + stream_config._limits(), + data_converter.payload_codec, + input.operation, + temporalio.nexus.system._support.model_to_proto(request, *converters), + input.rpc_timeout, + ) + # Each generated Stream call gives its result type. + result_type: Any = input.result_type + handle: temporalio.client.NexusOperationHandle[Any] = ( + temporalio.client.NexusOperationHandle( + client, + input.id, + result_type=result_type, + endpoint=input.endpoint, + service=input.service, + operation=input.operation, + ) + ) + handle._known_outcome = temporalio.nexus.system._support.model_from_proto( + response, result_type, *converters + ) + return handle + + class _StoreCaller: # pyright: ignore[reportUnusedClass] """The caller of a Stream Store for the bridge, which gives and takes encoded messages. diff --git a/temporalio/contrib/streams/__init__.py b/temporalio/contrib/streams/__init__.py new file mode 100644 index 0000000000..7ddbe45e1e --- /dev/null +++ b/temporalio/contrib/streams/__init__.py @@ -0,0 +1,13 @@ +"""Helpers on top of the Streams API. + +: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._producer import as_producer, current_producer + +__all__ = ["as_producer", "current_producer"] diff --git a/temporalio/contrib/streams/_producer.py b/temporalio/contrib/streams/_producer.py new file mode 100644 index 0000000000..b54b67451f --- /dev/null +++ b/temporalio/contrib/streams/_producer.py @@ -0,0 +1,60 @@ +"""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 or a close 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, which is the + sequence number of the Activity in the run unless the Workflow set one. A + run can use an Activity id again after the first Activity with it has + ended. The second Activity is then a later attempt of the same Producer, so + a Store that fences refuses a late write of the first one. + + A Local Activity whose retry waits longer than its ``local_retry_threshold`` + runs again under a new sequence number. Each such retry then writes as a new + Producer, unless the Workflow set ``activity_id``. + + Raises: + RuntimeError: The caller isn't an Activity. + + .. 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/temporalio/nexus/system/__init__.py b/temporalio/nexus/system/__init__.py index 1f8f7c6d29..da102bd304 100644 --- a/temporalio/nexus/system/__init__.py +++ b/temporalio/nexus/system/__init__.py @@ -194,3 +194,7 @@ def _get_serialization_context( # pyright: ignore[reportUnusedFunction] "TEMPORAL_SYSTEM_ENDPOINT", "is_system_endpoint", ] + +# `temporalio.workflow` and the generated Workflow modules of a system service import each +# other. It's loaded here last, so that any of those modules can be the first import. +import temporalio.workflow # noqa: E402 # pyright: ignore[reportUnusedImport] diff --git a/temporalio/nexus/system/_support.py b/temporalio/nexus/system/_support.py index 1ff5f64c52..90d7927878 100644 --- a/temporalio/nexus/system/_support.py +++ b/temporalio/nexus/system/_support.py @@ -1,8 +1,12 @@ import collections.abc +import dataclasses import typing -from datetime import timedelta +import uuid +from datetime import datetime, timedelta import google.protobuf.duration_pb2 +import google.protobuf.message +import google.protobuf.timestamp_pb2 import temporalio.api.common.v1.message_pb2 as common_pb2 import temporalio.api.enums.v1.workflow_pb2 as workflow_enums_pb2 @@ -12,6 +16,22 @@ import temporalio.common import temporalio.converter import temporalio.nexus.system +from temporalio.converter._payload_converter import _get_transfer_type_converter + +if typing.TYPE_CHECKING: + import temporalio.activity + import temporalio.client + from temporalio.nexus.system.stream_service.models import ( + Producer, + ReadRecordsRequest, + ReadRecordsResponse, + StreamRecord, + StreamRef, + Timestamp, + ) + +_BodyT = typing.TypeVar("_BodyT") +_ModelT = typing.TypeVar("_ModelT") class SignalWithStartWorkflowModelRequest(typing.Protocol): @@ -19,6 +39,194 @@ class SignalWithStartWorkflowModelRequest(typing.Protocol): id: str +def model_to_proto( + model: object, + payload_converter: temporalio.converter.PayloadConverter, + failure_converter: temporalio.converter.FailureConverter, +) -> google.protobuf.message.Message: + """Convert a system Nexus model to its proto message, with no payload in between.""" + converter = _get_transfer_type_converter(type(model)) + if converter is None: + raise TypeError(f"{type(model).__name__} is not a system Nexus model") + with temporalio.nexus.system._user_converter_context( + temporalio.nexus.system._SystemNexusUserConverters( + payload_converter, failure_converter + ) + ): + return converter.to_transfer_type(model) + + +def model_from_proto( + proto: google.protobuf.message.Message, + model_type: type[_ModelT], + payload_converter: temporalio.converter.PayloadConverter, + failure_converter: temporalio.converter.FailureConverter, +) -> _ModelT: + """Convert a proto message to the system Nexus model of ``model_type``.""" + converter = _get_transfer_type_converter(model_type) + if converter is None: + raise TypeError(f"{model_type} is not a system Nexus model") + with temporalio.nexus.system._user_converter_context( + temporalio.nexus.system._SystemNexusUserConverters( + payload_converter, failure_converter + ) + ): + return converter.from_transfer_type(proto, model_type) + + +def request_id() -> str: + from temporalio.workflow import in_workflow, info + + # Each run of a chain sends the same id, so a Store answers the create of a later run + # as the create that made the Stream. + if in_workflow(): + return info().first_execution_run_id + return str(uuid.uuid4()) + + +def append_request_id() -> str | None: + from temporalio.workflow import in_workflow + + # Core makes the request id of an append of Workflow code. + if in_workflow(): + return None + return str(uuid.uuid4()) + + +def default_producer( + nexus_client: "temporalio.client.NexusClient[typing.Any]", +) -> "Producer": + """Return the Producer of a write of Activity or client code.""" + import temporalio.activity + from temporalio.nexus.system.stream_service import models + + if temporalio.activity.in_activity(): + return activity_producer(temporalio.activity.info()) + client: temporalio.client.Client = nexus_client._client # type: ignore[attr-defined] + return models.Producer( + kind=models.ProducerKindClient( + models.ClientProducer( + namespace=client.namespace, id=client._stream_producer_id + ) + ) + ) + + +def workflow_producer() -> "Producer": + """Return the Producer of the Workflow run. It has no attempt, which Core sets.""" + from temporalio.nexus.system.stream_service import models + from temporalio.workflow import info + + return models.Producer( + kind=models.ProducerKindWorkflow( + models.WorkflowProducer( + namespace=info().namespace, + workflow_id=info().workflow_id, + run_id=info().run_id, + ) + ) + ) + + +def activity_producer(info: "temporalio.activity.Info") -> "Producer": + """Return the Producer of an attempt of an Activity, of the kind of the Activity.""" + from temporalio.nexus.system.stream_service import models + + workflow_id, run_id = info.workflow_id or "", info.workflow_run_id or "" + if info.is_local: + task = info.workflow_task + if task is None: + raise RuntimeError( + "Local Activity has no Workflow Task, which its Producer requires" + ) + local_attempt = models.LocalActivityAttempt( + task=models.WorkflowTaskAttempt( + started_event_id=task.started_event_id, + attempt=task.attempt, + started_time=_timestamp(task.started_time) + if task.started_time + else None, + ), + attempt=info.attempt, + ) + return models.Producer( + kind=models.ProducerKindLocalActivity( + models.LocalActivityProducer( + namespace=info.namespace, + workflow_id=workflow_id, + run_id=run_id, + activity_id=info.activity_id, + attempt=local_attempt, + ) + ) + ) + attempt = models.ActivityAttempt( + attempt_scheduled_time=_timestamp(info.current_attempt_scheduled_time), + attempt=info.attempt, + ) + if run_id: + return models.Producer( + kind=models.ProducerKindWorkflowActivity( + models.WorkflowActivityProducer( + namespace=info.namespace, + workflow_id=workflow_id, + run_id=run_id, + activity_id=info.activity_id, + attempt=attempt, + ) + ) + ) + if not info.activity_run_id: + raise RuntimeError( + "Standalone Activity has no run id, which its Producer requires" + ) + return models.Producer( + kind=models.ProducerKindStandaloneActivity( + models.StandaloneActivityProducer( + namespace=info.namespace, + activity_id=info.activity_id, + run_id=info.activity_run_id, + attempt=attempt, + ) + ) + ) + + +def _timestamp(time: datetime) -> "Timestamp": + from temporalio.nexus.system.stream_service import models + + proto = google.protobuf.timestamp_pb2.Timestamp() + proto.FromDatetime(time) + return models.Timestamp(seconds=proto.seconds, nanos=proto.nanos) + + +def stream_ref_to_id(ref: "StreamRef[typing.Any]") -> str: + return ref.id + + +def stream_ref_from_id( + id: str, ref_type: "type[StreamRef[_BodyT]]" +) -> "StreamRef[_BodyT]": + return ref_type(id=id) + + +def next_read_request( + request: "ReadRecordsRequest[_BodyT]", response: "ReadRecordsResponse[_BodyT]" +) -> "ReadRecordsRequest[_BodyT] | None": + # A read with no wait, or a wait of zero, ends at its first page with no Record. + if response.done or (not request.wait and not response.records): + return None + return dataclasses.replace( + request, from_offset=response.last_offset or request.from_offset + ) + + +def resume_read_request( + request: "ReadRecordsRequest[_BodyT]", item: "StreamRecord[_BodyT]" +) -> "ReadRecordsRequest[_BodyT]": + return dataclasses.replace(request, from_offset=item.offset) + + def retry_policy_from_proto( proto: common_pb2.RetryPolicy, ) -> temporalio.common.RetryPolicy: diff --git a/temporalio/testing/_workflow.py b/temporalio/testing/_workflow.py index 6c8354162c..54add4e363 100644 --- a/temporalio/testing/_workflow.py +++ b/temporalio/testing/_workflow.py @@ -102,6 +102,7 @@ async def start_local( dev_server_download_ttl: timedelta | None = None, dev_server_startup_timeout: timedelta | None = None, ui_port: int | None = None, + stream_config: temporalio.client.StreamConfig | None = None, ) -> WorkflowEnvironment: """Start a full Temporal server locally, downloading if necessary. @@ -165,6 +166,8 @@ async def start_local( become ready after spawning. Defaults to 5 seconds and does not include download time. ui_port: UI port to use if UI is enabled. + stream_config: See parameter of the same name on + :py:meth:`temporalio.client.Client.connect`. Returns: The started CLI dev server workflow environment. @@ -194,6 +197,7 @@ async def start_local( dev_server_download_ttl=dev_server_download_ttl, dev_server_startup_timeout=dev_server_startup_timeout, ui_port=ui_port, + stream_config=stream_config, ) @classmethod @@ -216,6 +220,7 @@ async def start_time_skipping( test_server_extra_args: Sequence[str] = [], test_server_download_ttl: timedelta | None = None, test_server_startup_timeout: timedelta | None = None, + stream_config: temporalio.client.StreamConfig | None = None, ) -> WorkflowEnvironment: """Start a V1 time skipping workflow environment. @@ -276,6 +281,8 @@ async def start_time_skipping( test_server_startup_timeout: Maximum time to wait for the test server to become ready after spawning. Defaults to 5 seconds and does not include download time. + stream_config: See parameter of the same name on + :py:meth:`temporalio.client.Client.connect`. Returns: The started workflow environment with time skipping. @@ -296,6 +303,7 @@ async def start_time_skipping( test_server_extra_args=test_server_extra_args, test_server_download_ttl=test_server_download_ttl, test_server_startup_timeout=test_server_startup_timeout, + stream_config=stream_config, ) @classmethod @@ -582,6 +590,7 @@ async def _bootstrap_dev_server( dev_server_download_ttl: timedelta | None = None, dev_server_startup_timeout: timedelta | None = None, ui_port: int | None = None, + stream_config: temporalio.client.StreamConfig | None = None, ) -> tuple[ temporalio.bridge.testing.EphemeralServer, temporalio.client.Client, @@ -649,6 +658,7 @@ async def _bootstrap_dev_server( rpc_metadata=rpc_metadata, identity=identity, runtime=runtime, + stream_config=stream_config, ) except: try: @@ -719,6 +729,7 @@ async def _create( test_server_extra_args: Sequence[str], test_server_download_ttl: timedelta | None, test_server_startup_timeout: timedelta | None, + stream_config: temporalio.client.StreamConfig | None, ) -> _V1WorkflowEnvironment: runtime = runtime or temporalio.runtime.Runtime.default() download_ttl_ms = None @@ -753,6 +764,7 @@ async def _create( rpc_metadata=rpc_metadata, identity=identity, runtime=runtime, + stream_config=stream_config, ) except: try: diff --git a/tests/helpers/streams.py b/tests/helpers/streams.py index f4667bdc84..d026e0a04b 100644 --- a/tests/helpers/streams.py +++ b/tests/helpers/streams.py @@ -1,17 +1,34 @@ """Helpers for the tests of Streams.""" import asyncio +import collections import selectors -from collections.abc import Coroutine, Iterator, Sequence +from collections.abc import Awaitable, Callable, Coroutine, Iterator, Sequence from contextlib import contextmanager from typing import Any, TypeVar +from google.protobuf.message import Message + from temporalio.api.common.v1 import Payload +from temporalio.api.streamservice.v1 import ( + AppendRecordsRequest, + AppendRecordsResponse, + CloseStreamRequest, + CloseStreamResponse, + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, +) +from temporalio.client import StreamStore from temporalio.converter import ( PayloadCodec, SerializationContext, WithSerializationContext, ) +from temporalio.testing import MemoryStreamStore _T = TypeVar("_T") @@ -64,6 +81,10 @@ def wrapped(payload: Payload, context: SerializationContext | None = None) -> Pa ) +Fault = Callable[[Callable[[], Awaitable[Any]]], Awaitable[Any]] +"""What a :py:class:`FaultStore` does with one call. It gets the call of the memory Store.""" + + @contextmanager def failure_note(note: str) -> Iterator[None]: """Add ``note`` to a failure in the block, such as the seed of a generated case.""" @@ -74,6 +95,97 @@ 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.""" + + async def fault(_call: Callable[[], Awaitable[Any]]) -> Any: + return response + + return fault + + +def loses_answer() -> Fault: + """Return a fault that calls the memory Store and then fails as an outage.""" + + async def fault(call: Callable[[], Awaitable[Any]]) -> Any: + await call() + raise ConnectionError("The answer of the Store was lost") + + return fault + + +class Hold: + """A fault that holds a call until :py:meth:`release`, before the memory Store.""" + + def __init__(self) -> None: + self.started = asyncio.Event() + self.cancelled = asyncio.Event() + self._released = asyncio.Event() + + def release(self) -> None: + self._released.set() + + async def __call__(self, call: Callable[[], Awaitable[Any]]) -> Any: + self.started.set() + try: + await self._released.wait() + except asyncio.CancelledError: + self.cancelled.set() + raise + return await call() + + +class FaultStore(StreamStore): + """Stream Store around a :py:class:`MemoryStreamStore`, which logs each request + and runs the next fault of its method, if one is queued. + """ + + def __init__(self, name: str = "memory", **options: Any) -> None: + self.memory = MemoryStreamStore(name=name, **options) + self.requests: list[Message] = [] + self.faults: dict[str, collections.deque[Fault]] = collections.defaultdict( + collections.deque + ) + + def name(self) -> str: + return self.memory.name() + + async def create_stream(self, request: CreateStreamRequest) -> CreateStreamResponse: + return await self._call("create_stream", request) + + async def append_records( + self, request: AppendRecordsRequest + ) -> AppendRecordsResponse: + return await self._call("append_records", request) + + async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: + return await self._call("read_records", request) + + async def close_stream(self, request: CloseStreamRequest) -> CloseStreamResponse: + return await self._call("close_stream", request) + + async def describe_stream( + self, request: DescribeStreamRequest + ) -> DescribeStreamResponse: + return await self._call("describe_stream", request) + + async def _call(self, method: str, request: Message) -> Any: + self.requests.append(request) + call = lambda: getattr(self.memory, method)(request) + if self.faults[method]: + return await self.faults[method].popleft()(call) + return await call() + + 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 new file mode 100644 index 0000000000..1e64f989b9 --- /dev/null +++ b/tests/nexus/test_streams.py @@ -0,0 +1,549 @@ +"""Tests of the client path of Streams, with no server.""" + +import asyncio +import concurrent.futures +import dataclasses +import pkgutil +import random +import subprocess +import sys +from collections.abc import Callable +from datetime import datetime, timedelta, timezone +from types import SimpleNamespace +from typing import Any, cast +from unittest.mock import Mock, patch + +import pytest +from google.protobuf.message import Message +from google.protobuf.timestamp_pb2 import Timestamp + +import temporalio.api.streamservice.v1 as proto +import temporalio.client +import temporalio.converter +import temporalio.nexus.system +from temporalio.activity import WorkflowTaskAttempt +from temporalio.api.enums.v1 import StreamErrorReason, StreamIdConflictPolicy +from temporalio.api.stream.v1 import ( + AppendRecord, + ClientProducer, + Producer, +) +from temporalio.client import ( + Client, + NexusOperationHandle, + StreamConfig, + StreamSelectContext, +) +from temporalio.contrib.streams import as_producer, current_producer +from temporalio.converter import StorageDriverActivityInfo +from temporalio.exceptions import StreamError +from temporalio.nexus.system import _support +from temporalio.nexus.system.stream_service import ( + ReadRecordsRequest, + ReadRecordsResponse, + StreamRecord, + StreamRef, +) +from temporalio.nexus.system.stream_service import ( + StreamIdConflictPolicy as ConflictPolicy, +) +from temporalio.service import ServiceClient +from temporalio.testing import ActivityEnvironment +from tests.helpers.streams import ( + FaultStore, + Hold, + failure_note, + run_with_virtual_clock, +) + +_UNAVAILABLE = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE +_INVALID_ARGUMENT = StreamErrorReason.STREAM_ERROR_REASON_INVALID_ARGUMENT + + +class _Interceptor(temporalio.client.Interceptor): + """Gives a client the outbound interceptor that ``outbound`` makes.""" + + def __init__( + self, + outbound: Callable[ + [temporalio.client.OutboundInterceptor], + temporalio.client.OutboundInterceptor, + ], + ) -> None: + super().__init__() + self._outbound = outbound + + def intercept_client( + self, next: temporalio.client.OutboundInterceptor + ) -> temporalio.client.OutboundInterceptor: + return self._outbound(next) + + +class _RecordingOutbound(temporalio.client.OutboundInterceptor): + """Logs the Store name of each Stream request before and after its call.""" + + def __init__( + self, + next: temporalio.client.OutboundInterceptor, + stores: list[tuple[str | None, str | None]], + ) -> None: + super().__init__(next) + self._stores = stores + + async def start_nexus_operation( + self, input: temporalio.client.StartNexusOperationInput + ) -> NexusOperationHandle[Any]: + before = input.arg.ref.store + try: + return await self.next.start_nexus_operation(input) + finally: + self._stores.append((before, input.arg.ref.store)) + + +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 + + +async def test_a_client_call_reaches_the_right_store_as_written() -> None: + request_ids: set[str] = set() + for seed in range(300): + with failure_note(f"seed {seed}"): + await _routing_script(seed, random.Random(seed), request_ids) + + +async def _routing_script(seed: int, rng: random.Random, request_ids: set[str]) -> None: + to_payload = temporalio.converter.PayloadConverter.default.to_payload + service_client = Mock(spec=ServiceClient) + names = rng.sample("abcd", rng.randrange(1, 5)) + has_selector = len(names) > 1 or rng.random() < 0.5 + stores = [FaultStore(name) for name in names] + selects: list[StreamSelectContext] = [] + # The Store that the selector returns at its next call, which may be unregistered. + selected = [FaultStore("other")] + + def selector(context: StreamSelectContext) -> FaultStore: + selects.append(context) + return selected[0] + + # A client with no Stream config refuses a call, and the server gets nothing. + with pytest.raises(ValueError): + await Client(service_client).create_stream(id="s") + assert not service_client.mock_calls + ref_stores: list[tuple[str | None, str | None]] = [] + client = Client( + service_client, + interceptors=[_Interceptor(lambda next: _RecordingOutbound(next, ref_stores))], + stream_config=StreamConfig( + stores=stores, store_selector=selector if has_selector else None + ), + ) + activity = ActivityEnvironment() + activity.info = dataclasses.replace( + activity.info, activity_id=f"activity-{seed}", activity_run_id="run" + ) + # A write has the Producer of its caller, which is the client or the Activity. + producers = [ + Producer( + client=ClientProducer(namespace="default", id=client._stream_producer_id) + ), + _producer_proto(activity.run(current_producer)), + ] + created: list[tuple[Any, FaultStore]] = [] + for step in range(12): + with failure_note(f"step {step}"): + selected[0] = rng.choice([*stores, *stores, FaultStore("other")]) + stream_id = f"stream-{seed}-{step}" + ref_store = rng.choice([None, None, "unknown", *names]) + store: FaultStore | None + in_activity = rng.random() < 0.3 + expected: Message + operation = rng.choice(["create", "read", "describe", "created"]) + if operation == "created" and not created: + operation = "create" + if operation == "created": + # A created Stream stays on its Store, whatever the selector picks at this call. + stream, store = rng.choice(created) + ref_store = stream.ref.store + match rng.choice(["append", "describe", "close"]): + case "append": + bodies = [rng.randrange(100) for _ in range(rng.randrange(3))] + call = stream.append(*bodies) + expected = proto.AppendRecordsRequest( + stream_id=stream.ref.id, + producer=producers[in_activity], + records=[ + AppendRecord(body=to_payload(body)) for body in bodies + ], + ) + case "describe": + call = stream.describe() + expected = proto.DescribeStreamRequest(stream_id=stream.ref.id) + case _: + call = stream.close() + expected = proto.CloseStreamRequest( + stream_id=stream.ref.id, producer=producers[in_activity] + ) + else: + store = next((s for s in stores if s.name() == ref_store), None) + if ref_store is None and has_selector: + store = selected[0] if selected[0] in stores else None + elif ref_store is None: + store = stores[0] + ref = StreamRef[int](id=stream_id, store=ref_store) + match operation: + case "create": + policy = rng.choice(list(StreamIdConflictPolicy.values())) + call = client.create_stream( + id=stream_id, + store=ref_store, + id_conflict_policy=ConflictPolicy(policy) + if policy + else None, + body_type=int, + ) + expected = proto.CreateStreamRequest( + stream_id=stream_id, id_conflict_policy=policy + ) + case "read": + expected = proto.ReadRecordsRequest( + stream_id=stream_id, + from_offset=rng.randbytes(rng.randrange(3)), + max_records=rng.choice([0, 1, 2**31 - 1]), + max_bytes=rng.choice([0, 1, 2**62]), + ) + wait = rng.choice([None, 0, 1, 30 * 24 * 3600]) + if wait is not None: + expected.wait.FromSeconds(wait) + call = client.get_stream(ref).read_page( + from_offset=expected.from_offset or None, + max_records=expected.max_records or None, + wait=None if wait is None else timedelta(seconds=wait), + max_bytes=expected.max_bytes or None, + ) + case _: + call = client.get_stream(ref).describe() + expected = proto.DescribeStreamRequest(stream_id=stream_id) + logs = [list(s.requests) for s in stores] + del selects[:], ref_stores[:] + + async def run_call() -> Any: + # A read or a describe of a Stream that nobody created fails in the Store. + try: + return await call + except StreamError as err: + return err + + if store is None: + with pytest.raises(ValueError): + await (activity.run(run_call) if in_activity else run_call()) + assert [s.requests for s in stores] == logs + continue + result = await (activity.run(run_call) if in_activity else run_call()) + if ( + isinstance(expected, proto.AppendRecordsRequest) + and not expected.records + ): + # The SDK refuses a batch with no Record before the Store gets it. + assert isinstance(result, StreamError) + assert result.reason == _INVALID_ARGUMENT + assert [s.requests for s in stores] == logs + continue + for other, log in zip(stores, logs): + if other is not store: + assert other.requests == log + [request] = store.requests[len(logs[stores.index(store)]) :] + if isinstance( + request, (proto.CreateStreamRequest, proto.AppendRecordsRequest) + ): + assert request.request_id and request.request_id not in request_ids + request_ids.add(request.request_id) + request.request_id = "" + assert request == expected + assert not service_client.mock_calls + # An interceptor sees the ref as the caller wrote it, and the Store's name in + # it after a create. + after = store.name() if operation == "create" else ref_store + assert ref_stores == [(ref_store, after)] + target = None + if in_activity: + target = StorageDriverActivityInfo( + namespace="default", + id=f"activity-{seed}", + run_id="run", + type="unknown", + ) + used_selector = has_selector and ref_store is None + assert selects == ( + [StreamSelectContext(id=stream_id, target=target)] + if used_selector + else [] + ) + if operation == "create": + assert result.ref == StreamRef(id=stream_id, store=store.name()) + created.append((result, store)) + + +@pytest.mark.parametrize( + "limit", ["max_record_bytes", "max_batch_bytes", "max_batch_records"] +) +def test_a_limit_below_one_raises(limit: str) -> None: + limits: Any = {limit: 0} + with pytest.raises( + ValueError, + match=rf"^StreamConfig\.{limit} must be greater than or equal to one\.$", + ): + StreamConfig([FaultStore()], **limits) + + +class _FakeReads(temporalio.client.OutboundInterceptor): + """Answers each read with the next page of a generated Stream.""" + + def __init__( + self, + next: temporalio.client.OutboundInterceptor, + rng: random.Random, + records: int, + closed: bool, + ) -> None: + super().__init__(next) + self._rng = rng + self._records = records + self._closed = closed + self._requests = 0 + + async def start_nexus_operation( + self, input: temporalio.client.StartNexusOperationInput + ) -> NexusOperationHandle[Any]: + request: ReadRecordsRequest[int] = input.arg + # A read that goes on at an end, or that doesn't move on, would never stop. + self._requests += 1 + assert self._requests <= self._records + 3 + start = int.from_bytes(request.from_offset or b"", "big") + # A Store answers with no Record only at the end of the Stream. + size = self._rng.randrange(1, 4) + end = min(self._records, start + size) + page = ReadRecordsResponse( + records=[ + StreamRecord(body=at, offset=at.to_bytes(8, "big")) + for at in range(start + 1, end + 1) + ], + last_offset=end.to_bytes(8, "big") if end else None, + done=self._closed and end == self._records, + ) + handle: NexusOperationHandle[Any] = NexusOperationHandle(Mock(), input.id) + handle._known_outcome = page + return handle + + +async def test_a_polled_read_gives_each_record_once_in_order() -> None: + for seed in range(300): + with failure_note(f"seed {seed}"): + await _read_script(random.Random(seed)) + + +async def _read_script(rng: random.Random) -> None: + records, closed = rng.randrange(12), rng.random() < 0.5 + wait = rng.choice([None, timedelta(0), timedelta(seconds=5)]) + client = Client( + Mock(spec=ServiceClient), + interceptors=[ + _Interceptor(lambda next: _FakeReads(next, rng, records, closed)) + ], + ) + stream = client.get_stream(StreamRef[int](id="s")) + # A Stream that stays open has no last page for a read that waits, so the loop + # of such a read stops at a Record. + waits_forever = bool(wait) and not closed + stop_at = rng.randrange(1, records + 1) if records else 0 + got: list[int] = [] + first = stream.read(wait=wait) + if stop_at: + async for record in first: + got.append(record.body) + if len(got) == stop_at: + break + assert got == list(range(1, stop_at + 1)) + if waits_forever: + assert first.next_request is not None + return + resumed = first.next_request + if resumed is not None: + rest = stream.read( + from_offset=resumed.from_offset, + max_records=resumed.max_records, + wait=resumed.wait, + max_bytes=resumed.max_bytes, + ) + got.extend([record.body async for record in rest]) + assert rest.next_request is None + assert got == list(range(1, records + 1)) + + +@dataclasses.dataclass(frozen=True) +class _WriterInfo: + """A generated writer of a Stream, with the fields that its Producer takes.""" + + kind: str + """The field of the kind in the proto ``Producer``.""" + namespace: str + workflow_id: str + run_id: str + activity_id: str + attempt: int + time: datetime + """The scheduled time of an Activity attempt, or the started time of a task.""" + event_id: int + + +def _writer_info(rng: random.Random) -> _WriterInfo: + def text() -> str: + return "".join(rng.choice("ab:/ '\"é") for _ in range(rng.randrange(1, 5))) + + kinds = ["workflow", "local_activity", "workflow_activity", "standalone_activity"] + return _WriterInfo( + kind=rng.choice(kinds), + namespace=text(), + workflow_id=text(), + run_id=text(), + activity_id=text(), + attempt=rng.randrange(1, 9), + time=datetime.fromtimestamp(rng.randrange(10**9), timezone.utc), + event_id=rng.randrange(3, 99), + ) + + +def _default_producer(writer: _WriterInfo) -> Any: + """Return the Producer that a write of ``writer`` sends with no ``producer=``.""" + 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, writer.attempt + 1, writer.time + ) + if writer.kind == "local_activity" + else None, + ) + 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": + task = kind.attempt.task + task.started_event_id, task.attempt = writer.event_id, writer.attempt + 1 + task.started_time.CopyFrom(time) + else: + kind.attempt.attempt_scheduled_time.CopyFrom(time) + return producer + + +def test_a_writer_is_one_producer_on_each_attempt() -> None: + for seed in range(300): + with failure_note(f"seed {seed}"): + rng = random.Random(seed) + writer = _writer_info(rng) + producer = _producer_proto(_default_producer(writer)) + assert producer == _expected_producer(writer) + + # Two Streams of one client have one Producer, and two clients have two. + service_client = Mock(spec=ServiceClient) + config = StreamConfig(stores=[FaultStore()]) + clients = [Client(service_client, stream_config=config) for _ in range(2)] + [first, second, third] = [ + _producer_proto( + _support.default_producer(client.get_stream(StreamRef(id=id))._nexus_client) + ) + for client, id in ((clients[0], "a"), (clients[0], "b"), (clients[1], "a")) + ] + assert first == second != third + assert first.client.namespace == "default" and first.client.id + + +def test_a_stored_producer_comes_back_as_a_producer() -> None: + converter = temporalio.converter.PayloadConverter.default + for seed in range(50): + with failure_note(f"seed {seed}"): + producer = _default_producer(_writer_info(random.Random(seed))) + # A value such as a heartbeat detail comes back with no type hint. + [stored] = converter.from_payloads(converter.to_payloads([producer])) + assert as_producer(stored) == producer + assert as_producer(producer) is producer + + +def test_each_stream_module_can_be_the_first_import() -> None: + system = temporalio.nexus.system + modules = [ + "temporalio.client._stream_store", + "temporalio.testing._stream_store", + "temporalio.contrib.streams", + "temporalio.workflow", + system.__name__, + *( + module.name + for module in pkgutil.walk_packages(system.__path__, system.__name__ + ".") + ), + ] + assert len(modules) > 15 + + def first_import(module: str) -> str: + imported = subprocess.run( + [sys.executable, "-c", f"import {module}"], capture_output=True, text=True + ) + return imported.stderr if imported.returncode else "" + + with concurrent.futures.ThreadPoolExecutor(8) as pool: + for module, error in zip(modules, pool.map(first_import, modules)): + assert not error, f"{module}: {error}" + + +def test_a_client_call_past_its_rpc_timeout_cancels_the_store_call() -> None: + async def script() -> None: + loop = asyncio.get_running_loop() + store, hold = FaultStore(), Hold() + store.faults["describe_stream"].append(hold) + client = Client(Mock(spec=ServiceClient), stream_config=StreamConfig([store])) + stream = client.get_stream(StreamRef[str](id="s")) + with pytest.raises(StreamError) as timed_out: + await stream.describe(rpc_timeout=timedelta(seconds=5)) + assert timed_out.value.reason == _UNAVAILABLE + assert loop.time() == 5 + assert hold.cancelled.is_set() + assert asyncio.all_tasks() == {asyncio.current_task()} + + run_with_virtual_clock(script()) From d599dc88cbdad019b09b408998d61746d3da5d4a Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Fri, 20 Nov 2026 21:37:09 -0700 Subject: [PATCH 04/50] Run the Stream writes of Workflow code through Core Workflow code can't call a Store itself, since a replay must get the same answers. Core makes the append and the close inside the Workflow Task and records each result in a marker. A create and a describe have no command in Core, so they run in a Local Activity of the SDK. --- changelog/added/steady-stream-heron.md | 1 + temporalio/bridge/src/streams.rs | 29 ++ temporalio/bridge/src/worker.rs | 4 + temporalio/bridge/streams.py | 14 +- temporalio/bridge/worker.py | 2 + temporalio/client/_stream_store.py | 38 +- temporalio/worker/_interceptor.py | 11 +- temporalio/worker/_replayer.py | 11 + temporalio/worker/_worker.py | 13 +- temporalio/worker/_workflow.py | 3 + temporalio/worker/_workflow_instance.py | 36 +- temporalio/worker/_workflow_streams.py | 414 +++++++++++++++ tests/helpers/streams.py | 141 +++++- tests/nexus/test_streams.py | 55 +- tests/nexus/test_streams_with_worker.py | 645 ++++++++++++++++++++++++ tests/worker/test_workflow_streams.py | 451 ++++++++++++++++- 16 files changed, 1835 insertions(+), 33 deletions(-) create mode 100644 temporalio/worker/_workflow_streams.py create mode 100644 tests/nexus/test_streams_with_worker.py diff --git a/changelog/added/steady-stream-heron.md b/changelog/added/steady-stream-heron.md index c6762b02d4..4f747e2f78 100644 --- a/changelog/added/steady-stream-heron.md +++ b/changelog/added/steady-stream-heron.md @@ -1,2 +1,3 @@ Add experimental `temporalio.client.StreamStore`, the base class of a Stream Store, and `temporalio.testing.MemoryStreamStore`, a Store that keeps its Streams in memory for tests and local runs. Add experimental Streams for client and Activity code. `stream_config=StreamConfig(stores=[...])` of `Client.connect` gives a client its Stream Stores, and `Client.create_stream` and `Client.get_stream` return a `Stream` to append to, read, describe and close. A failed call raises `temporalio.exceptions.StreamError` with a `reason`. `max_record_bytes`, `max_batch_bytes` and `max_batch_records` of `StreamConfig` bound an append, and one over a limit fails before its Store gets it. A read of a Stream from `get_stream` needs `body_type=` or a `StreamRef` with a type argument, and raises `TypeError` with neither. `temporalio.contrib.streams.current_producer` gives the Producer of an Activity attempt, and `as_producer` gives back one that code stored. +Add experimental Streams for Workflow code. `workflow.create_stream` and `workflow.get_stream` return a `Stream` to append to, describe and close on the Stream Stores of the Worker's client, and `Replayer(stream_config=...)` gives a replay its Stores. diff --git a/temporalio/bridge/src/streams.rs b/temporalio/bridge/src/streams.rs index d14493f625..064141fa1f 100644 --- a/temporalio/bridge/src/streams.rs +++ b/temporalio/bridge/src/streams.rs @@ -6,6 +6,7 @@ use pyo3::prelude::*; use pyo3::sync::PyOnceLock; use pyo3::types::{IntoPyDict, PyBytes, PyType}; use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError}; +use temporalio_sdk_core::StreamRuntimes; use temporalio_streams::proto::{ AppendRecordsRequest, AppendRecordsResponse, CloseStreamRequest, CloseStreamResponse, CreateStreamRequest, CreateStreamResponse, DescribeStreamRequest, DescribeStreamResponse, @@ -251,6 +252,34 @@ fn store_limits( .map_err(|err| PyValueError::new_err(err.message)) } +/// The Stream Stores of a Worker, which Python gives as a `WorkerStreams` of +/// `temporalio.bridge.streams`. +#[derive(FromPyObject)] +pub(crate) struct WorkerStreams { + limits: Option<(usize, usize, usize)>, + stores: Vec<(String, Py)>, +} + +impl WorkerStreams { + /// Returns the runtime of each Store by its name. Each Store runs its calls on the event + /// loop of `task_locals`. + 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)) + } +} + /// Checks an encoded append of client code as the runtime of a Worker checks one of Workflow /// code, with the limits of the Stream config. Client code reaches its Store through no such /// runtime. Raises `StreamError` for an append that the check refuses. diff --git a/temporalio/bridge/src/worker.rs b/temporalio/bridge/src/worker.rs index 46b6c00de9..4c8de98da8 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 index 70b1ffe10a..dd14e62aa8 100644 --- a/temporalio/bridge/streams.py +++ b/temporalio/bridge/streams.py @@ -6,7 +6,8 @@ from __future__ import annotations import asyncio -from collections.abc import Callable +from collections.abc import Callable, Sequence +from dataclasses import dataclass from typing import Any, Protocol import temporalio.bridge.runtime @@ -28,6 +29,17 @@ async def call( ... +@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.""" + + async def call_stream_store( runtime: temporalio.bridge.runtime.Runtime, caller: StoreCaller, diff --git a/temporalio/bridge/worker.py b/temporalio/bridge/worker.py index fd4d2aae3c..811fa0dfef 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 5ff339c10e..6855e781a4 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -271,6 +271,27 @@ class StreamConfig: gets it, and refuses one over a limit with ``STREAM_ERROR_REASON_TOO_LARGE``. + A client interceptor that changes the ``StreamRef`` of a request must change it + in place, since a created Stream keeps the ref object of the request. + + For the Stream calls of Workflow code: + + - A create and a describe run in a Local Activity of the SDK. The Workflow + and Activity interceptors of the Worker see it, as they see every Local + Activity. + - The ``producer`` argument of ``append`` and ``close`` has no effect. The + Worker writes as the Producer of the Workflow run. + - An append is at-least-once. If a Workflow Task fails after its append, the + next attempt of the task writes the batch again. + - An outage of the Store gives Workflow code no error. The Workflow Task + fails, and the server tries it again. + - A call that Workflow code doesn't await before the Workflow ends may not + happen. A Workflow that needs its close awaits it, as ``async with`` does. + - A call with no Store fails the Workflow Task, also when Workflow code catches + the error. + - A Worker reads the three limits when it starts. It refuses a new client with + other limits, as it refuses one with other Store names. + .. warning:: This API is experimental and subject to change. """ @@ -289,7 +310,8 @@ class StreamConfig: Store takes each such call. A Workflow replay calls the selector again, so it must return the same Store - for the same call. + for the same call. A created Stream has the name of its Store in its ref, so + its calls don't depend on the selector. """ max_record_bytes: int = 1536 * 1024 @@ -342,6 +364,13 @@ def __post_init__(self) -> None: ) names.add(name) + def _store(self, name: str) -> StreamStore: + """Return the Store with a name, raising :class:`ValueError` if none has it.""" + for store in self.stores: + if store.name() == name: + return store + raise ValueError(f"No Stream Store found with name '{name}'") + def _store_for( self, ref: StreamRef[Any], @@ -351,10 +380,7 @@ def _store_for( there is none. """ if ref.store: - for store in self.stores: - if store.name() == ref.store: - return store - raise ValueError(f"No Stream Store found with name '{ref.store}'") + return self._store(ref.store) if self.store_selector is None: return self.stores[0] selected = self.store_selector(StreamSelectContext(id=ref.id, target=target)) @@ -555,7 +581,7 @@ async def call( 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 a %s call", operation, exc_info=err.__cause__ + "Stream Store failed the %s call", operation, exc_info=err.__cause__ ) raise return response.SerializeToString() diff --git a/temporalio/worker/_interceptor.py b/temporalio/worker/_interceptor.py index 09d49884db..f164103a09 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 1542b3e0f2..5cd4b5015b 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,10 @@ 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`` is the Stream config of the client that the worker + used. A replay takes the result of each append, close, create and + describe of a Stream from history, so it calls no Store for them. """ self._config = ReplayerConfig( workflows=list(workflows), @@ -88,6 +94,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 +260,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 +289,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 +367,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 +447,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 cf8125d819..cebe0d7f92 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,10 @@ 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"): + # Workflow code creates and describes a Stream in this Local Activity. + activities.append(_stream_store_call) if activities: _warn_if_activity_executor_max_workers_is_inconsistent(config) self._activity_worker = _ActivityWorker( @@ -575,6 +579,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 +672,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 +721,7 @@ 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 +764,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 b0f18b7b8c..2c1922f293 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 04e4f5c555..c640855226 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,14 @@ def _activate( check_conditions=index == 1 or index == 2, jobs=act.jobs ) except Exception as err: + # A Stream call that the Worker can't serve fails the task, and so does a create + # or a describe in an outage, whatever the failure exception types are + 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 +709,10 @@ 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("resolve_stream_close"): + self._streams.resolve_close(job.resolve_stream_close) elif job.HasField("signal_workflow"): self._apply_signal_workflow(job.signal_workflow) elif job.HasField("initialize_workflow"): @@ -1848,7 +1866,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, @@ -3382,7 +3405,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 @@ -3424,7 +3449,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( @@ -4053,6 +4080,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 0000000000..d5284934fe --- /dev/null +++ b/temporalio/worker/_workflow_streams.py @@ -0,0 +1,414 @@ +"""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.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, + _operation, + _StoreCaller, +) +from temporalio.converter import StorageDriverWorkflowInfo +from temporalio.exceptions import StreamError +from temporalio.nexus.system.stream_service import StreamRef + +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] + """The Stream calls of one Workflow instance. + + An append and a close are commands of SDK Core, which makes the Store call and + gives the result in a job. Core has no command for a create or a describe, so + those run in a Local Activity of the SDK. + """ + + def __init__(self, instance: _WorkflowInstanceImpl) -> None: + self._instance = instance + # Each append and close whose job hasn't come, by seq + self._appends: dict[int, asyncio.Future[Any]] = {} + self._closes: dict[int, asyncio.Future[Any]] = {} + self.task_error: Exception | None = None + """The error of a call that must fail the Workflow Task, if one came.""" + + def start( + self, input: StartNexusOperationInput[Any, OutputT] + ) -> temporalio.workflow.NexusOperationHandle[OutputT]: + """Start a Stream operation and return its handle. + + The command of the call is added before this returns, so commands are in + the order of the calls. Cancelling the handle ends its wait immediately. + Core can't stop an append or a close, so those still run. + """ + 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 + # The terminal of each Stream operation gives its output type. + result_type: Any = input.output_type + request = temporalio.nexus.system._support.model_to_proto(model, *converters) + # The future of the job of the call, or the task of its Local Activity + result: asyncio.Future[Any] + if isinstance(request, proto.AppendRecordsRequest): + stream = self._stream(model.ref) + 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 = self._appends[seq] = instance.create_future() + elif isinstance(request, proto.CloseStreamRequest): + stream = self._stream(model.ref) + seq = instance._next_seq("stream_close") + close = instance._add_command().close_stream + close.seq = seq + close.stream.CopyFrom(stream) + result = self._closes[seq] = instance.create_future() + else: + # The Local Activity picks the Store of a ref with no Store name. A replay + # has its result, so a replay asks no selector for it. + result = self._schedule_store_call( + operation, model.ref.store or "", 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, model, request, result), + result_type, + *converters, + ) + + 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(lambda _: result.done() or result.cancel()) + return _StreamCall(task) + + def resolve_append( + self, job: temporalio.bridge.proto.workflow_activation.ResolveStreamAppend + ) -> None: + self._resolve(self._appends, job.seq, job.appended, job) + + def resolve_close( + self, job: temporalio.bridge.proto.workflow_activation.ResolveStreamClose + ) -> None: + self._resolve(self._closes, job.seq, None, job) + + def _resolve( + self, + calls: dict[int, asyncio.Future[Any]], + seq: int, + result: Any, + job: Any, + ) -> None: + future = calls.pop(seq, None) + if future is None: + raise RuntimeError(f"Failed finding Stream call for sequence {seq}") + # A cancelled call no longer waits, and Core still gives the result of its write. + if future.done(): + return + if job.HasField("failed"): + future.set_exception( + _stream_error_from_failure(job.failed) + or self._instance._context_free_failure_converter.from_failure( + job.failed, self._instance._context_free_payload_converter + ) + ) + else: + future.set_result(result) + + def _schedule_store_call( + self, operation: str, store: str, request: google.protobuf.message.Message + ) -> asyncio.Future[Any]: + """Schedule the SDK's Local Activity for a create or a describe.""" + instance = self._instance + # A Worker whose client has no Stream config has no such Local Activity, so the + # call would wait with no end. A replay takes the result from History. + if not instance._is_replaying and self._stream_config() is None: + raise self._fail_task( + ValueError( + "Client of this Worker has no stream_config, which every " + "Stream call requires." + ) + ) + activity = instance._outbound.start_local_activity( + StartLocalActivityInput( + activity=_STORE_CALL_ACTIVITY, + args=(store, operation, request.SerializeToString()), + 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, + model: Any, + request: google.protobuf.message.Message, + result: asyncio.Future[Any], + ) -> google.protobuf.message.Message: + """Return the response message of a call whose ``result`` is done.""" + if isinstance(request, proto.AppendRecordsRequest): + appended = result.result() + return proto.AppendRecordsResponse( + first_offset=appended.first_offset, last_offset=appended.last_offset + ) + if isinstance(request, proto.CloseStreamRequest): + result.result() + return proto.CloseStreamResponse() + 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 + if isinstance(request, proto.CreateStreamRequest): + # The created Stream takes the ref of its request. The name is the one in + # History, so a replay gives the same ref under any Stream config. + model.ref.store = answer["store"] + return proto.CreateStreamResponse(created=answer["created"]) + return proto.DescribeStreamResponse.FromString(answer) + + def _stream(self, ref: StreamRef[Any]) -> temporalio.api.stream.v1.StreamRef: + """Return the ref of a command, with the name of the Store that SDK Core calls. + + A ref with no Store name gets the Store that the config of the Worker's + client picks, and an empty name if that client has no Stream config. + """ + store = ref.store or "" + config = self._stream_config() + if config and not store: + info = self._instance._info + target = StorageDriverWorkflowInfo( + id=info.workflow_id, + run_id=info.run_id, + type=info.workflow_type, + namespace=info.namespace, + ) + try: + store = config._store_for(ref, target).name() + except Exception as err: + raise self._fail_task(err) + return temporalio.api.stream.v1.StreamRef(id=ref.id, store=store) + + def _fail_task(self, error: Exception) -> Exception: + """Make ``error`` the failure of the Workflow Task and return it. + + Workflow code that catches the error of a call that the Worker can't serve + would go on with no Stream call in History. So the task fails, whatever the + failure exception types of the Worker and of the Workflow are. + """ + 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"] + )() + + +class _StreamCall(temporalio.workflow.NexusOperationHandle[OutputT]): + """Handle of a Stream call, which a task of the Workflow instance runs.""" + + 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] + store: str, operation: str, request: bytes +) -> Any: + """Call a Stream Store of the Worker's client for a create or a describe of + Workflow code. ``store`` is the Store name of the call's ref, or empty. + + Returns the name of the Store that it called and ``created`` for a create, so + that History has the Store of the created Stream, and the encoded response for + a describe. + """ + 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.") + _, request_type, _ = _operation(operation) + stream_request: Any = request_type.FromString(request) + # The selector gets the Workflow as its target, as for an append of that Workflow. + target = StorageDriverWorkflowInfo( + id=info.workflow_id, + run_id=info.workflow_run_id, + type=info.workflow_type, + namespace=info.namespace, + ) + picked = stream_config._store_for( + StreamRef(id=stream_request.stream_id, store=store or None), target + ) + response = await _call_store( + picked, + stream_config._limits(), + client.data_converter.payload_codec, + operation, + stream_request, + ) + if isinstance(response, proto.CreateStreamResponse): + return {"store": picked.name(), "created": response.created} + return response.SerializeToString() + + +def _stream_error_from_failure( + failure: temporalio.api.failure.v1.Failure, +) -> StreamError | None: + """Return the Stream error of a failure, or ``None`` if it isn't one. + + The failure of a Stream call has a + ``temporal.api.stream.v1.StreamErrorDetails`` message in its details. A + reason that this SDK doesn't know becomes + ``STREAM_ERROR_REASON_UNSPECIFIED``. + """ + 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]: + """Return the Store names and the limits of a Stream config, which Core has + from the start of a worker. + """ + if stream_config is None: + return set(), None + return {store.name() for store in stream_config.stores}, stream_config._limits() + + +def _bridge_streams( # pyright: ignore[reportUnusedFunction] + stream_config: Callable[[], StreamConfig | None], +) -> temporalio.bridge.streams.WorkerStreams: + """Return what the bridge needs for the Stream Stores of a worker. + + ``stream_config`` gives the Stream config that the worker has at a call, + which is the one of another client after a client swap. + """ + + 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, + # Each caller finds its Store in the config that the worker has at the call. + 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: + """Raise if the new client of a worker has other Stream Stores or other + limits than the existing one. + """ + 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 d026e0a04b..4c8995cfb9 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, @@ -22,13 +28,24 @@ ReadRecordsRequest, ReadRecordsResponse, ) -from temporalio.client import StreamStore +from temporalio.client import ( + Client, + StreamConfig, + StreamSelectContext, + StreamStore, + WorkflowFailureError, + WorkflowHandle, + WorkflowHistory, +) from temporalio.converter import ( + DataConverter, PayloadCodec, SerializationContext, WithSerializationContext, ) from temporalio.testing import MemoryStreamStore +from temporalio.worker import Replayer, Worker +from tests.helpers import new_worker _T = TypeVar("_T") @@ -151,7 +168,7 @@ class FaultStore(StreamStore): def __init__(self, name: str = "memory", **options: Any) -> None: self.memory = MemoryStreamStore(name=name, **options) - self.requests: list[Message] = [] + self.requests: list[Any] = [] self.faults: dict[str, collections.deque[Fault]] = collections.defaultdict( collections.deque ) @@ -180,12 +197,126 @@ async def describe_stream( async def _call(self, method: str, request: Message) -> Any: self.requests.append(request) - call = lambda: getattr(self.memory, method)(request) + + async def call() -> Any: + return await getattr(self.memory, method)(request) + if self.faults[method]: return await self.faults[method].popleft()(call) 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, + store_selector: Callable[[StreamSelectContext], StreamStore] | None = None, + data_converter: DataConverter | None = None, + **limits: int, +) -> Client: + """Return a client on the connection of ``client`` with the given Stream Stores + and limits. + """ + config = client.config() + config["stream_config"] = StreamConfig( + stores, store_selector=store_selector, **limits + ) + if data_converter: + config["data_converter"] = data_converter + 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 1e64f989b9..ae9712a556 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -2,7 +2,9 @@ import asyncio import concurrent.futures +import copy import dataclasses +import pickle import pkgutil import random import subprocess @@ -23,10 +25,12 @@ import temporalio.nexus.system from temporalio.activity import WorkflowTaskAttempt 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, @@ -36,7 +40,7 @@ ) from temporalio.contrib.streams import as_producer, current_producer from temporalio.converter import StorageDriverActivityInfo -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, @@ -49,9 +53,11 @@ ) from temporalio.service import ServiceClient from temporalio.testing import ActivityEnvironment +from temporalio.worker._workflow_streams import _stream_error_from_failure from tests.helpers.streams import ( FaultStore, Hold, + core_failure, failure_note, run_with_virtual_clock, ) @@ -300,6 +306,53 @@ def test_a_limit_below_one_raises(limit: str) -> None: StreamConfig([FaultStore()], **limits) +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): """Answers each read with the next page of a generated Stream.""" diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py new file mode 100644 index 0000000000..2da70bb462 --- /dev/null +++ b/tests/nexus/test_streams_with_worker.py @@ -0,0 +1,645 @@ +"""Tests of Streams with a Worker on the test server.""" + +import dataclasses +import itertools +import random +from collections.abc import Sequence +from datetime import timedelta +from typing import Any + +import pytest +from google.protobuf.message import Message + +from temporalio import activity, workflow +from temporalio.api.enums.v1 import EventType, StreamErrorReason, TaskQueueType +from temporalio.api.sdk.v1.external_storage_pb2 import ExternalStorageReference +from temporalio.api.streamservice.v1 import ( + AppendRecordsRequest, + CloseStreamResponse, + CreateStreamRequest, + ReadRecordsRequest, +) +from temporalio.api.taskqueue.v1 import TaskQueue +from temporalio.api.workflowservice.v1 import DescribeTaskQueueRequest +from temporalio.client import Client, WorkflowFailureError +from temporalio.converter import ( + DataConverter, + ExternalStorage, +) +from temporalio.exceptions import ApplicationError, StreamError +from temporalio.nexus.system.stream_service import ( + StreamIdConflictPolicy, + StreamRef, + StreamStatus, +) +from temporalio.worker import ( + ActivityInboundInterceptor, + Interceptor, + Replayer, + Worker, +) +from tests.helpers import assert_eventually, assert_task_fail_eventually +from tests.helpers.streams import ( + ContextCodec, + FaultStore, + RunOptions, + answers, + failure_note, + loses_answer, + raises, + run, + stream_client, +) +from tests.test_extstore import InMemoryTestDriver + + +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 == "close": + await stream.close() + answers.append("closed") + else: + described = await stream.describe() + answers.append([described.status, (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) + + +def _without_writer(request: Message) -> Message: + """Return a request without what differs between two writers of the same call.""" + copy = type(request)() + copy.CopyFrom(request) + for name in ("producer", "request_id"): + if name in copy.DESCRIPTOR.fields_by_name: + copy.ClearField(name) + return copy + + +async def test_workflow_code_and_a_client_get_the_same_answers(client: Client) -> None: + for seed in range(8): + with failure_note(f"seed {seed}"): + rng = random.Random(seed) + calls: list[list[Any]] = [] + created: set[str] = set() + for _ in range(rng.randrange(4, 12)): + stream_id = f"s-{seed}-{rng.randrange(3)}" + match rng.choice(["create", "append", "append", "close", "describe"]): + # Each create of one run has the same request id, so a second create + # of a Stream is the first one again for a Workflow and not for a client. + case "create" if stream_id not in created: + created.add(stream_id) + calls.append(["create", stream_id, rng.randrange(3)]) + case "create": + calls.append(["describe", stream_id]) + case "append": + bodies = [ + rng.randrange(100) for _ in range(rng.randrange(1, 4)) + ] + calls.append(["append", stream_id, bodies]) + case operation: + calls.append([operation, stream_id]) + # The two Stores have one name and the same Stream ids, so a call is the same + # request in both. + for_client, for_workflow = FaultStore(), FaultStore() + from_client = await _answers(stream_client(client, for_client), calls) + workflow_client = stream_client(client, for_workflow) + ran = await run(workflow_client, RunOptions(_CallsWorkflow, [calls])) + assert ran.result == from_client + assert [_without_writer(request) for request in for_workflow.requests] == [ + _without_writer(request) for request in for_client.requests + ] + appends = [ + request.request_id + for request in for_workflow.requests + if isinstance(request, AppendRecordsRequest) + ] + assert all(appends) and len(set(appends)) == len(appends) + # A replay makes no call, with the Stores of the run and with none. + requests = list(for_workflow.requests) + for replay_client in (workflow_client, client): + await Replayer( + workflows=[_CallsWorkflow], + stream_config=replay_client._config["stream_config"], + ).replay_workflow(ran.history) + assert for_workflow.requests == requests + + +def _bodies(writer: str) -> list[Any]: + """Return the bodies that a writer appends. One is a value that a pass of external + storage would take for a reference into the storage of the Worker. + """ + claim = ExternalStorageReference( + driver_name="test-driver", claim_data={"key": "payload-0"} + ) + return [f"{writer} plain", {"writer": writer}, claim] + + +@activity.defn +async def _append_bodies(stream_id: str) -> None: + stream = activity.client().get_stream(StreamRef(id=stream_id)) + await stream.append(*_bodies("activity")) + + +@workflow.defn +class _BodiesWorkflow: + @workflow.run + async def run(self, stream_id: str) -> None: + await workflow.execute_activity( + _append_bodies, stream_id, start_to_close_timeout=timedelta(seconds=10) + ) + stream = workflow.get_stream(StreamRef(id=stream_id)) + await stream.append(*_bodies("workflow")) + + +async def test_a_body_reads_the_same_on_every_path(client: Client) -> None: + store, driver = FaultStore(), InMemoryTestDriver() + converter = dataclasses.replace( + DataConverter.default, + payload_codec=ContextCodec(), + external_storage=ExternalStorage(drivers=[driver], payload_size_threshold=0), + ) + client = stream_client(client, store, data_converter=converter) + stream = await client.create_stream(id="bodies") + await stream.append(*_bodies("client")) + options = RunOptions(_BodiesWorkflow, ["bodies"], activities=[_append_bodies]) + await run(client, options) + + expected = [*_bodies("client"), *_bodies("activity"), *_bodies("workflow")] + assert [record.body async for record in stream.read()] == expected + # The Store has each body as the codec gave it with no context, and the storage of + # the Worker has none of them. + stored = await store.memory.read_records(ReadRecordsRequest(stream_id="bodies")) + assert [dict(record.body.metadata) for record in stored.records] == [ + {"encoding": b"test/wrapped", "context": b"NoneType"} + ] * len(expected) + assert driver._storage and not any( + b" plain" in value for value in driver._storage.values() + ) + + +def _events(history: Any, event_type: EventType.ValueType) -> list[Any]: + return [event for event in history.events if event.event_type == event_type] + + +async def test_a_store_error_is_the_same_error_on_every_path(client: Client) -> None: + store = FaultStore() + client = stream_client(client, store) + stream = await client.create_stream(id="errors", body_type=int) + append: list[Any] = ["append", "errors", [1]] + appends = store.faults["append_records"] + unavailable = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE + + async def answers_on(path: str, calls: list[list[Any]], **options: Any) -> Any: + if path == "client": + return await _answers(client, calls) + args = [calls, path == "activity"] + run_options = RunOptions( + _CallsWorkflow, args, activities=[_calls_activity], **options + ) + return (await run(client, run_options)).result + + def append_requests() -> list[AppendRecordsRequest]: + requests = [r for r in store.requests if isinstance(r, AppendRecordsRequest)] + del store.requests[:] + return requests + + # Core tries an append again in an outage of the Store, with one request id, so the + # Store writes it once. Workflow code gets no error, and History has no failure. + outages = [ + [raises(StreamError("The Store is down", reason=unavailable))] * 2, + [loses_answer()], + [raises(ConnectionError("The connection is gone"))], + ] + for at, faults in enumerate(outages): + with failure_note(f"outage {at}"): + appends.extend(faults) + ran = await run(client, RunOptions(_CallsWorkflow, [[append]])) + offset = (at + 1).to_bytes(8, "big").hex() + assert ran.result == [[offset, offset]] + requests = append_requests() + assert len(requests) == len(faults) + 1 + assert len({request.request_id for request in requests}) == 1 + assert not _events(ran.history, EventType.EVENT_TYPE_WORKFLOW_TASK_FAILED) + # A client and an Activity get the outage as the error of their call. + for path in ("client", "activity"): + appends.append(raises(ConnectionError("The connection is gone"))) + [[error, reason, _]] = await answers_on(path, [append]) + assert (error, reason, len(append_requests())) == ("error", unavailable, 1) + + # An answer of the wrong message fails the call, and nothing tries it again. + corrupt = StreamErrorReason.STREAM_ERROR_REASON_STORE_CORRUPT + for path in ("client", "activity", "workflow"): + with failure_note(path): + appends.append(answers(CloseStreamResponse())) + [[error, reason, _]] = await answers_on(path, [append]) + assert (error, reason, len(append_requests())) == ("error", corrupt, 1) + + # A refusal is the same error for a client, an Activity and Workflow code. Workflow + # code gets it again in each task that replays the call. + await stream.close() + calls = [append, ["describe", "errors"], ["describe", "missing"]] + refused = await answers_on("client", calls) + assert [answer[:2] for answer in refused] == [ + ["error", StreamErrorReason.STREAM_ERROR_REASON_CLOSED], + [StreamStatus.StreamStatusClosed, (3).to_bytes(8, "big").hex()], + ["error", StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND], + ] + for path in ("activity", "workflow"): + with failure_note(path): + assert await answers_on(path, calls, cached=False, replay=True) == refused + + # An outage during a create fails the Workflow Task, also on a Worker that fails a + # Workflow for any exception. The create runs in the next task, with the Store back. + for failure_types in ([], [Exception]): + with failure_note(f"failure types {failure_types}"): + store.faults["create_stream"].append(raises(ConnectionError("down"))) + options = RunOptions( + _CallsWorkflow, + [[["create", f"after an outage {len(failure_types)}"]]], + worker={"workflow_failure_exception_types": failure_types}, + ) + ran = await run(client, options) + assert ran.result == [["memory", True]] + # History has nothing of the outage but the task failure. + events = [event.event_type for event in ran.history.events] + task_done = events.index(EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED) + assert set(events[1:task_done]) == { + EventType.EVENT_TYPE_WORKFLOW_TASK_SCHEDULED, + EventType.EVENT_TYPE_WORKFLOW_TASK_STARTED, + EventType.EVENT_TYPE_WORKFLOW_TASK_FAILED, + } + assert events[task_done + 1 :] == [ + EventType.EVENT_TYPE_MARKER_RECORDED, + EventType.EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED, + ] + + +@workflow.defn +class _CatchingWorkflow: + @workflow.run + async def run(self, call: list[Any], store: str | None) -> str: + try: + await _answers(workflow, [call], store) + except Exception: + pass + return "caught" + + +async def test_a_stream_call_with_no_store_fails_the_workflow_task( + client: Client, +) -> None: + async def task_fails(handle: Any, _worker: Any) -> None: + await assert_task_fail_eventually(handle) + await handle.terminate() + + cases = { + "no Stream config": (client, None), + "a ref of a Store that the Worker lacks": ( + stream_client(client, FaultStore()), + "other", + ), + } + calls: list[list[Any]] = [ + ["create", "s"], + ["append", "s", [1]], + ["close", "s"], + ["describe", "s"], + ] + # The task fails also on a Worker that fails a Workflow for any exception. + for (case, (worker_client, store)), call, failure_types in itertools.product( + cases.items(), calls, ([], [Exception]) + ): + with failure_note(f"{call[0]} with {case} and {failure_types}"): + options = RunOptions( + _CatchingWorkflow, + [call, store], + worker={"workflow_failure_exception_types": failure_types}, + during=task_fails, + ) + ran = await run(worker_client, options) + # The Workflow didn't go on after the error that it caught, and History + # has nothing of the call. + assert isinstance(ran.result, WorkflowFailureError) + assert not _events(ran.history, EventType.EVENT_TYPE_MARKER_RECORDED) + + +@workflow.defn +class _ClosingWorkflow: + @workflow.run + async def run(self, stream_id: str, how: str) -> None: + stream = await workflow.create_stream(id=stream_id, body_type=str) + if how == "async with": + async with stream: + await stream.append("body") + return + try: + await stream.append("body") + if how == "failure": + raise ApplicationError("The block failed") + if how == "cancel": + await workflow.wait_condition(lambda: False) + finally: + await stream.close() + + +async def test_a_close_of_workflow_code_closes_the_stream(client: Client) -> None: + for how in ("async with", "return", "failure", "cancel"): + with failure_note(how): + store = FaultStore() + stream_id = f"closed after a {how}" + + async def cancel_in_the_block(handle: Any, _worker: Any) -> None: + async def appended() -> None: + assert any( + isinstance(r, AppendRecordsRequest) for r in store.requests + ) + + await assert_eventually(appended) + await handle.cancel() + + options = RunOptions(_ClosingWorkflow, [stream_id, how]) + if how == "cancel": + options.during = cancel_in_the_block + ran = await run(stream_client(client, store), options) + assert (ran.result is None) == (how in ("async with", "return")) + page = await store.memory.read_records( + ReadRecordsRequest(stream_id=stream_id) + ) + assert (len(page.records), page.done) == (1, True) + + +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], [StreamStatus.StreamStatusOpen, ""]] + 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 + + +# 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 + targets: list[Any] = [] + + def pick_first(context: Any) -> FaultStore: + targets.append(context.target) + 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 [(type(r).__name__, r.stream_id) for r in first.requests] == [ + ("CreateStreamRequest", "own"), + ] + # After the swap, Core calls the Store objects of the new client. + assert [(type(r).__name__, r.stream_id) for r in new_first.requests] == [ + ("AppendRecordsRequest", "own"), + ] + assert [(type(r).__name__, r.stream_id) for r in new_second.requests] == [ + ("CreateStreamRequest", "shared"), + ("AppendRecordsRequest", "shared"), + ("AppendRecordsRequest", "shared"), + ] + assert not second.requests + # The selector of the Workflow's create got the Workflow as its target. + assert [type(t).__name__ for t in targets] == ["StorageDriverWorkflowInfo"] + + +async def test_an_append_over_a_limit_of_the_config_never_reaches_the_store( + client: Client, +) -> None: + too_large = StreamErrorReason.STREAM_ERROR_REASON_TOO_LARGE + default_bytes = 4 * 1024 * 1024 + for seed in range(12): + with failure_note(f"seed {seed}"): + rng = random.Random(seed) + # One seed in four has limits over the defaults, which only the config bounds. + larger = seed % 4 == 0 + record = rng.choice([1000, 3000, 1536 * 1024]) + batch = ( + default_bytes if larger else rng.choice([4000, 20_000, default_bytes]) + ) + count = 1200 if larger else rng.choice([1, 3, 1000]) + # The body sizes of each batch, and whether the batch is within every limit. + # A stored Record counts its Producer, so no size is within 500 bytes of a + # limit, and the test needs no size logic. + batches: list[tuple[list[int], bool]] = [] + if larger: + batches.append(([0] * 1100, True)) + for _ in range(6): + match rng.choice(["fits", "fits", "records", "record", "batch"]): + case "records": + batches.append(([0] * (count + 1), False)) + case "record" if record <= 3000: + batches.append(([2 * record], False)) + case "batch" if batch <= 20_000: + size = min(record, batch) - 500 + batches.append(([size] * (batch // size + 1), False)) + case _: + fits = [rng.randrange(40)] * rng.randrange(1, min(count, 3) + 1) + batches.append((fits, True)) + store = FaultStore() + streams = stream_client( + client, + store, + max_record_bytes=record, + max_batch_bytes=batch, + max_batch_records=count, + ) + + def calls(stream_id: str) -> list[list[Any]]: + appends = [["x" * size for size in sizes] for sizes, _ in batches] + return [["create", stream_id]] + [ + ["append", stream_id, bodies] for bodies in appends + ] + + from_client = await _answers(streams, calls(f"client {seed}")) + options = RunOptions( + _CallsWorkflow, [calls(f"workflow {seed}")], replay=True + ) + from_workflow = (await run(streams, options)).result + for answers in (from_client, from_workflow): + assert [ + "written" if answer[0] != "error" else answer[1] + for answer in answers[1:] + ] == ["written" if fits else too_large for _, fits in batches] + # The Store got the batches within the limits from each path, and no other. + assert [ + len(request.records) + for request in store.requests + if isinstance(request, AppendRecordsRequest) + ] == [len(sizes) for sizes, fits in batches if fits] * 2 + + +@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 = [r for r in store.requests if isinstance(r, CreateStreamRequest)] + assert len(creates) == 4 and len({create.request_id for create in creates}) == 1 diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py index 8874292be3..c397511b32 100644 --- a/tests/worker/test_workflow_streams.py +++ b/tests/worker/test_workflow_streams.py @@ -1,7 +1,14 @@ """Tests of the Stream calls of one Workflow instance, with no server.""" +import asyncio import dataclasses +import random +from collections.abc import Sequence +from dataclasses import dataclass from datetime import datetime, timedelta, timezone +from typing import Any + +from google.protobuf.message import Message import temporalio.api.common.v1 import temporalio.bridge.worker @@ -11,33 +18,72 @@ import temporalio.nexus.system import temporalio.worker from temporalio import workflow -from temporalio.api.common.v1 import Payload -from temporalio.api.failure.v1 import ApplicationFailureInfo, Failure +from temporalio.api.common.v1 import ActivityType, Payload +from temporalio.api.enums.v1 import ( + RetryState, + StreamErrorReason, + StreamStatus, + TimeoutType, +) +from temporalio.api.failure.v1 import ( + ActivityFailureInfo, + ApplicationFailureInfo, + Failure, + TimeoutFailureInfo, +) from temporalio.api.sdk.v1.external_storage_pb2 import ExternalStorageReference from temporalio.api.stream.v1 import StreamRecord, StreamRef -from temporalio.bridge.proto.activity_result import ActivityResolution +from temporalio.api.streamservice.v1 import ( + CreateStreamRequest, + DescribeStreamRequest, + 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, ResolveStreamClose, ResolveStreamRead, + StreamAppended, StreamPage, WorkflowActivation, WorkflowActivationJob, ) from temporalio.bridge.proto.workflow_commands import ( + ActivityCancellationType, AppendToStream, + CloseStream, CompleteWorkflowExecution, + RequestCancelLocalActivity, WorkflowCommand, ) from temporalio.bridge.proto.workflow_completion import ( Success, WorkflowActivationCompletion, ) -from temporalio.converter import ExternalStorage, WorkflowSerializationContext +from temporalio.client import StreamConfig, StreamSelectContext, StreamStore +from temporalio.converter import ( + ExternalStorage, + StorageDriverWorkflowInfo, + WorkflowSerializationContext, +) +from temporalio.exceptions import ApplicationError, StreamError +from temporalio.nexus.system.stream_service import StreamRef as ModelRef +from temporalio.testing import MemoryStreamStore from temporalio.worker._workflow import _CommandAwareDataConverter -from tests.helpers.streams import CodecCall, ContextCodec, wrapped +from temporalio.worker._workflow_instance import _WorkflowInstanceImpl +from tests.helpers.streams import ( + CodecCall, + ContextCodec, + core_failure, + failure_note, + wrapped, +) from tests.test_extstore import InMemoryTestDriver @@ -48,14 +94,21 @@ async def run(self) -> None: pass -def _new_instance(workflow_class: type) -> temporalio.worker.WorkflowInstance: +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) - return temporalio.worker.UnsandboxedWorkflowRunner().create_instance( + 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=interceptor_classes, defn=defn, info=workflow.Info( attempt=1, @@ -83,14 +136,27 @@ def _new_instance(workflow_class: type) -> temporalio.worker.WorkflowInstance: workflow_type=defn.name or "", ), randomness_seed=1, - extern_functions={}, + extern_functions={"__temporal_stream_config": lambda: stream_config}, disable_eager_activity_execution=False, - worker_level_failure_exception_types=[], + 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, +) -> 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) + return await asyncio.to_thread(instance.activate, activation) async def test_stream_payloads_take_the_codec_with_no_context_and_no_storage() -> None: @@ -198,3 +264,368 @@ async def test_stream_payloads_take_the_codec_with_no_context_and_no_storage() - assert activity.resolve_activity.result.completed.result == result assert driver._retrieve_calls == 1 assert calls == [("decode", None, 1)] * 4 + [("decode", context, 1)] + + +_REFUSALS = [ + StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND, + StreamErrorReason.STREAM_ERROR_REASON_ALREADY_EXISTS, + StreamErrorReason.STREAM_ERROR_REASON_CLOSED, + StreamErrorReason.STREAM_ERROR_REASON_FENCED, +] +_UNAVAILABLE = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE +_STORE_CALL = "__temporal_stream_store_call" + + +@dataclass +class _Call: + """One generated Stream call, and what Workflow code got for it.""" + + operation: str + """One of ``create``, ``append``, ``close`` and ``describe``.""" + stream: str + """The id of the Stream. A call on a Stream that an earlier phase created uses the + Stream of that create.""" + store: str | None = None + """The Store name that Workflow code gives, to a create or in a ref that it builds.""" + bodies: Sequence[int] = () + cancel: bool = False + refusal: StreamErrorReason.ValueType | None = None + """The reason of the failure that the test answers the call with, if any.""" + timeout: bool = False + """Whether the Local Activity of the call ends in a timeout.""" + unserved: bool = False + """Whether the Local Activity of the call fails since the Worker lacks the Store.""" + outcome: Any = None + + +class _Script: + """The calls of :py:class:`_ScriptWorkflow`, which makes the calls of one phase + together and then waits for all of them, and what its interceptor saw. + """ + + phases: list[list[_Call]] = [] + late_cancels = False + """Whether a cancel comes after the task of its call ran, and not before.""" + intercepted: list[tuple[str, Any]] = [] + local_activities: list[str] = [] + """The Activity of each Local Activity that the interceptor saw.""" + + +@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) + elif call.operation == "close": + await stream.close() + call.outcome = "closed" + else: + described = await stream.describe() + call.outcome = (described.status, 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): + """Logs the operation of the interceptor method of each Stream call, with its + request, and each Local Activity. + """ + + 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) -> Any: + _Script.intercepted.append(("create", request)) + return await super().start_create_stream(request) + + async def start_append_records(self, request: Any) -> Any: + _Script.intercepted.append(("append", request)) + return await super().start_append_records(request) + + async def start_close_stream(self, request: Any) -> Any: + _Script.intercepted.append(("close", request)) + return await super().start_close_stream(request) + + async def start_describe_stream(self, request: Any) -> Any: + _Script.intercepted.append(("describe", request)) + return await super().start_describe_stream(request) + + +def _plan( + call: _Call, seq: int, store: str, history_store: str +) -> tuple[WorkflowCommand, WorkflowActivationJob, Any]: + """Return the command that a call must send, the job that the test answers it + with, and what Workflow code must get for it. + + ``store`` is the Store name that the call must send, and ``history_store`` the + one that the result of a create has. + """ + converter = temporalio.converter.DefaultPayloadConverter() + stream = StreamRef(id=call.stream, store=store) + refused = None if call.refusal is None else core_failure(call.refusal) + command, job = WorkflowCommand(), WorkflowActivationJob() + outcome: Any + if call.operation == "append": + bodies = converter.to_payloads(call.bodies) + command.append_to_stream.CopyFrom( + AppendToStream(seq=seq, stream=stream, bodies=bodies) + ) + outcome = (b"first%d" % seq, b"last%d" % seq) + job.resolve_stream_append.seq = seq + if refused: + job.resolve_stream_append.failed.CopyFrom(refused) + else: + job.resolve_stream_append.appended.CopyFrom( + StreamAppended(first_offset=outcome[0], last_offset=outcome[1]) + ) + elif call.operation == "close": + command.close_stream.CopyFrom(CloseStream(seq=seq, stream=stream)) + outcome = "closed" + job.resolve_stream_close.seq = seq + if refused: + job.resolve_stream_close.failed.CopyFrom(refused) + else: + request: Message = DescribeStreamRequest(stream_id=call.stream) + described = DescribeStreamResponse( + status=StreamStatus.STREAM_STATUS_OPEN, last_offset=b"last%d" % seq + ) + answer: Any = described.SerializeToString() + outcome = (described.status, described.last_offset) + if call.operation == "create": + # Each create of a run chain has the first run id as its request id. + request = CreateStreamRequest(stream_id=call.stream, request_id="first-run") + answer = {"store": history_store, "created": seq % 2 == 0} + outcome = (history_store, seq % 2 == 0 or None) + activity = command.schedule_local_activity + activity.seq = seq + activity.activity_id = str(seq) + activity.activity_type = _STORE_CALL + operation = request.DESCRIPTOR.name.removesuffix("Request") + activity.arguments.extend( + converter.to_payloads([store, operation, request.SerializeToString()]) + ) + activity.schedule_to_close_timeout.FromSeconds(5) + temporalio.common.RetryPolicy(maximum_attempts=1).apply_to_proto( + activity.retry_policy + ) + activity.cancellation_type = ActivityCancellationType.TRY_CANCEL + 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 refused: + # Core gives the failure of an attempt of a Local Activity as it is. + result.failed.failure.CopyFrom(refused) + elif call.unserved: + error = ApplicationFailureInfo(type="ValueError") + result.failed.failure.CopyFrom( + Failure(message="No Stream Store", application_failure_info=error) + ) + elif call.timeout: + timeout = TimeoutFailureInfo( + timeout_type=TimeoutType.TIMEOUT_TYPE_SCHEDULE_TO_CLOSE + ) + result.failed.failure.CopyFrom( + Failure( + message="Local Activity timed out", + cause=Failure(timeout_failure_info=timeout), + activity_failure_info=ActivityFailureInfo( + activity_type=ActivityType(name=_STORE_CALL), + retry_state=RetryState.RETRY_STATE_CANCEL_REQUESTED, + ), + ) + ) + else: + result.completed.result.CopyFrom(converter.to_payload(answer)) + if call.cancel: + outcome = "cancelled" + elif call.refusal is not None: + outcome = call.refusal + return command, job, outcome + + +async def test_stream_calls_get_the_results_of_their_own_seq() -> None: + for seed in range(200): + with failure_note(f"seed {seed}"): + await _calls_script(random.Random(seed)) + + +async def _calls_script(rng: random.Random) -> None: + stores: list[StreamStore] = [MemoryStreamStore(name=name) for name in "ab"] + selects: list[StreamSelectContext] = [] + + def selector(context: StreamSelectContext) -> StreamStore: + selects.append(context) + if context.id == "fatal": + raise ApplicationError("The selector has no Store for this Stream") + return stores[int(context.id[1:]) % 2] + + config = rng.choice( + [None, StreamConfig(stores[:1]), StreamConfig(stores, store_selector=selector)] + ) + names = "a" if config and len(config.stores) == 1 else "ab" + # A live create or describe needs a Stream config of the Worker, and a replay + # needs none. + replaying = config is None or rng.random() < 0.3 + + # The Store name that History has for each Stream that a create of the script makes. + # It need not be the one that the config picks for the create. + created: dict[str, str] = {} + phases: list[list[_Call]] = [] + streams = 0 + for _ in range(rng.randrange(1, 5)): + phase: list[_Call] = [] + for _ in range(rng.randrange(1, 5)): + operation = rng.choice(["create", "append", "append", "close", "describe"]) + if operation != "create" and created and rng.random() < 0.5: + call = _Call(operation, rng.choice(sorted(created))) + else: + call = _Call(operation, f"s{streams}", rng.choice([None, *names])) + streams += 1 + if operation == "append": + call.bodies = [rng.randrange(100) for _ in range(rng.randrange(3))] + # The first call of a phase isn't cancelled, so each phase waits for a job. + call.cancel = bool(phase) and rng.random() < 0.3 + call.refusal = rng.choice([None, None, None, None, *_REFUSALS]) + phase.append(call) + phases.append(phase) + for call in phase: + if call.operation == "create" and not call.cancel and call.refusal is None: + created[call.stream] = rng.choice(names) + # The last phase can be one call that fails the Workflow Task. Its Local Activity + # ends in an outage or finds no Store, or the selector raises for its append. + fatal = rng.choice([None, None, "outage", "unserved", "selector"]) + if fatal == "selector" and not (config and config.store_selector): + fatal = None + if fatal == "selector": + phases.append([_Call("append", "fatal")]) + elif fatal: + last = _Call(rng.choice(["create", "describe"]), f"s{streams}") + last.unserved = fatal == "unserved" + last.timeout = fatal == "outage" and rng.random() < 0.5 + if fatal == "outage" and not last.timeout: + last.refusal = _UNAVAILABLE + phases.append([last]) + + _Script.phases, _Script.intercepted, _Script.local_activities = phases, [], [] + _Script.late_cancels = rng.random() < 0.5 + # The task also fails on a Worker that fails a Workflow for any exception. + failure_types = rng.choice([[], [Exception]]) + instance = _new_instance( + _ScriptWorkflow, config, [_RecordingInbound], failure_types + ) + target = StorageDriverWorkflowInfo( + namespace="ns", id="wf", run_id="run", type="_ScriptWorkflow" + ) + seqs = {"append": 0, "close": 0, "activity": 0} + jobs = [WorkflowActivationJob(initialize_workflow=InitializeWorkflow())] + outcomes: list[Any] = [] + expected_selects: list[StreamSelectContext] = [] + # The created Streams that Workflow code has, which have their Store name of History + usable: set[str] = set() + for phase in phases: + completion = await _activate(instance, *jobs, replaying=replaying) + if fatal == "selector" and phase is phases[-1]: + break + commands: list[WorkflowCommand] = [] + cancels: list[WorkflowCommand] = [] + jobs = [] + for call in phase: + by_core = call.operation in ("append", "close") + if call.stream in usable: + store = created[call.stream] + elif call.store or config is None or not by_core: + # The Local Activity of a create or a describe gets the ref's own Store + # name, and it asks the selector itself. + store = call.store or "" + elif config.store_selector is None: + store = "a" + else: + store = stores[int(call.stream[1:]) % 2].name() + expected_selects.append( + StreamSelectContext(id=call.stream, target=target) + ) + kind = call.operation if call.operation in seqs else "activity" + seqs[kind] += 1 + command, job, outcome = _plan( + call, seqs[kind], store, created.get(call.stream, "a") + ) + commands.append(command) + jobs.append(job) + outcomes.append(outcome) + if call.cancel and kind == "activity": + cancel = RequestCancelLocalActivity(seq=seqs[kind]) + cancels.append(WorkflowCommand(request_cancel_local_activity=cancel)) + # The commands are in the order of the calls, and a cancel sends a command only + # for a Local Activity. + assert list(completion.successful.commands) == commands + cancels + usable.update(call.stream for call in phase if call.operation == "create") + usable &= created.keys() + # Core gives the results in any order, also those of calls that were cancelled. + rng.shuffle(jobs) + else: + completion = await _activate(instance, *jobs, replaying=replaying) + if fatal: + assert completion.HasField("failed") + else: + [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] == outcomes + assert not instance._streams._appends and not instance._streams._closes + assert selects == expected_selects + # An interceptor sees each call in the method of its operation, and the ref of + # a create has the Store name of History once the create has its result. + assert [operation for operation, _ in _Script.intercepted] == [ + call.operation for call in calls + ] + # The Local Activity of a create or a describe goes through the interceptors too. + store_calls = [ + call for call in calls if call.operation in ("create", "describe") + ] + assert _Script.local_activities == [_STORE_CALL] * len(store_calls) + for call, (_, request) in zip(calls, _Script.intercepted): + if call.operation == "create" and call.stream in created: + assert request.ref.store == created[call.stream] + # An eviction ends each task of the instance, also the task of a call that waits. + evict = WorkflowActivationJob(remove_from_cache=RemoveFromCache()) + assert (await _activate(instance, evict)).HasField("successful") From 8f41de935113efc39728b0fd49def9246d827549 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Fri, 20 Nov 2026 21:58:19 -0700 Subject: [PATCH 05/50] Let Workflow code read a Stream A read of Workflow code is one command of Core with one job, as a Local Activity is, so no state of a read depends on where an activation ends. A replay reads the Records again from the Store, so a replay Worker gets the event loop that its Python Stores need. --- changelog/added/steady-stream-heron.md | 1 + temporalio/bridge/src/streams.rs | 8 +- temporalio/bridge/src/worker.rs | 46 ++- temporalio/bridge/streams.py | 1 + temporalio/bridge/worker.py | 2 + temporalio/client/_stream_store.py | 19 +- temporalio/worker/_replayer.py | 10 +- temporalio/worker/_worker.py | 19 +- temporalio/worker/_workflow.py | 16 + temporalio/worker/_workflow_instance.py | 2 + temporalio/worker/_workflow_streams.py | 118 +++++- temporalio/workflow/__init__.py | 2 + temporalio/workflow/_exceptions.py | 13 + tests/nexus/test_streams_with_worker.py | 505 ++++++++++++++++++++++-- tests/worker/test_workflow_streams.py | 296 +++++++++++++- 15 files changed, 977 insertions(+), 81 deletions(-) diff --git a/changelog/added/steady-stream-heron.md b/changelog/added/steady-stream-heron.md index 4f747e2f78..6076ebf9c0 100644 --- a/changelog/added/steady-stream-heron.md +++ b/changelog/added/steady-stream-heron.md @@ -1,3 +1,4 @@ Add experimental `temporalio.client.StreamStore`, the base class of a Stream Store, and `temporalio.testing.MemoryStreamStore`, a Store that keeps its Streams in memory for tests and local runs. Add experimental Streams for client and Activity code. `stream_config=StreamConfig(stores=[...])` of `Client.connect` gives a client its Stream Stores, and `Client.create_stream` and `Client.get_stream` return a `Stream` to append to, read, describe and close. A failed call raises `temporalio.exceptions.StreamError` with a `reason`. `max_record_bytes`, `max_batch_bytes` and `max_batch_records` of `StreamConfig` bound an append, and one over a limit fails before its Store gets it. A read of a Stream from `get_stream` needs `body_type=` or a `StreamRef` with a type argument, and raises `TypeError` with neither. `temporalio.contrib.streams.current_producer` gives the Producer of an Activity attempt, and `as_producer` gives back one that code stored. Add experimental Streams for Workflow code. `workflow.create_stream` and `workflow.get_stream` return a `Stream` to append to, describe and close on the Stream Stores of the Worker's client, and `Replayer(stream_config=...)` gives a replay its Stores. +Add experimental Stream reads for Workflow code. `Stream.read`, `read_pages` and `read_page` of a Workflow `Stream` give the Records as they come, a replay reads them again from the Store, and `temporalio.workflow.StreamReplayError` in the failure exception types of a Worker or a Workflow fails the Workflow when the Store no longer has them. The Worker option `stream_read_max_wait` bounds the wait of one Store call of a read. diff --git a/temporalio/bridge/src/streams.rs b/temporalio/bridge/src/streams.rs index 064141fa1f..59466ce3b5 100644 --- a/temporalio/bridge/src/streams.rs +++ b/temporalio/bridge/src/streams.rs @@ -6,6 +6,7 @@ use pyo3::prelude::*; use pyo3::sync::PyOnceLock; use pyo3::types::{IntoPyDict, PyBytes, PyType}; use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError}; +use std::time::Duration; use temporalio_sdk_core::StreamRuntimes; use temporalio_streams::proto::{ AppendRecordsRequest, AppendRecordsResponse, CloseStreamRequest, CloseStreamResponse, @@ -258,6 +259,7 @@ fn store_limits( pub(crate) struct WorkerStreams { limits: Option<(usize, usize, usize)>, stores: Vec<(String, Py)>, + read_max_wait_millis: Option, } impl WorkerStreams { @@ -276,7 +278,11 @@ impl WorkerStreams { let runtime = StreamRuntime::new(Arc::new(store), limits); (name, Arc::new(runtime)) }); - Ok(StreamRuntimes::new(runtimes)) + let mut runtimes = StreamRuntimes::new(runtimes); + if let Some(millis) = self.read_max_wait_millis { + runtimes.settings.read_max_wait = Duration::from_millis(millis); + } + Ok(runtimes) } } diff --git a/temporalio/bridge/src/worker.rs b/temporalio/bridge/src/worker.rs index 4c8de98da8..335fa0e8a1 100644 --- a/temporalio/bridge/src/worker.rs +++ b/temporalio/bridge/src/worker.rs @@ -5,7 +5,7 @@ use prost::Message; use pyo3::exceptions::{PyException, PyRuntimeError, PyValueError}; use pyo3::prelude::*; use pyo3::types::{PyBytes, PyTuple}; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::marker::PhantomData; use std::sync::{Arc, OnceLock}; use std::time::Duration; @@ -67,6 +67,8 @@ pub struct WorkerConfig { storage_drivers: HashSet, disable_payload_error_limit: bool, streams: WorkerStreams, + stream_replay_as_workflow_fail: bool, + stream_replay_as_workflow_fail_for_types: HashSet, } #[derive(FromPyObject)] @@ -524,7 +526,11 @@ pub fn new_replay_worker<'a>( runtime_ref .runtime .assert_same_process("create replay worker")?; - let event_loop_task_locals = Arc::new(OnceLock::new()); + // A replay Worker gets no `validate` call, and a replay reads its Python Stores on the + // loop that created it. + let event_loop_task_locals = Arc::new(OnceLock::from( + pyo3_async_runtimes::TaskLocals::with_running_loop(py)?.copy_context(py)?, + )); let config = convert_worker_config(config, event_loop_task_locals.clone())?; let (history_pusher, stream) = HistoryPusher::new(runtime_ref.runtime.clone()); let worker = WorkerRef { @@ -534,7 +540,7 @@ pub fn new_replay_worker<'a>( PyValueError::new_err(format!("Failed creating replay worker: {err}")) })?, )), - event_loop_task_locals: Default::default(), + event_loop_task_locals, runtime: runtime_ref.runtime.clone(), }; PyTuple::new( @@ -723,6 +729,22 @@ fn convert_worker_config( task_locals: Arc>, ) -> PyResult { let stream_runtimes = conf.streams.into_runtimes(&task_locals)?; + let mut failure_errors = HashSet::new(); + if conf.nondeterminism_as_workflow_fail { + failure_errors.insert(WorkflowErrorType::Nondeterminism); + } + if conf.stream_replay_as_workflow_fail { + failure_errors.insert(WorkflowErrorType::StreamReplay); + } + let mut type_failure_errors = HashMap::>::new(); + for workflow_type in conf.nondeterminism_as_workflow_fail_for_types { + let errors = type_failure_errors.entry(workflow_type).or_default(); + errors.insert(WorkflowErrorType::Nondeterminism); + } + for workflow_type in conf.stream_replay_as_workflow_fail_for_types { + let errors = type_failure_errors.entry(workflow_type).or_default(); + errors.insert(WorkflowErrorType::StreamReplay); + } 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() @@ -754,22 +776,8 @@ fn convert_worker_config( // auto-cancel-activity behavior of shutdown will not occur, so we // always set it even if 0. .graceful_shutdown_period(Duration::from_millis(conf.graceful_shutdown_period_millis)) - .workflow_failure_errors(if conf.nondeterminism_as_workflow_fail { - HashSet::from([WorkflowErrorType::Nondeterminism]) - } else { - HashSet::new() - }) - .workflow_types_to_failure_errors( - conf.nondeterminism_as_workflow_fail_for_types - .iter() - .map(|s| { - ( - s.to_owned(), - HashSet::from([WorkflowErrorType::Nondeterminism]), - ) - }) - .collect(), - ) + .workflow_failure_errors(failure_errors) + .workflow_types_to_failure_errors(type_failure_errors) .maybe_nexus_task_poller_behavior(conf.nexus_task_poller_behavior.map(Into::into)) .plugins( conf.plugins diff --git a/temporalio/bridge/streams.py b/temporalio/bridge/streams.py index dd14e62aa8..fba61eba35 100644 --- a/temporalio/bridge/streams.py +++ b/temporalio/bridge/streams.py @@ -38,6 +38,7 @@ class WorkerStreams: 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.""" + read_max_wait_millis: int | None async def call_stream_store( diff --git a/temporalio/bridge/worker.py b/temporalio/bridge/worker.py index 811fa0dfef..c5f6eb8a6c 100644 --- a/temporalio/bridge/worker.py +++ b/temporalio/bridge/worker.py @@ -65,6 +65,8 @@ class WorkerConfig: storage_drivers: set[str] disable_payload_error_limit: bool streams: temporalio.bridge.streams.WorkerStreams + stream_replay_as_workflow_fail: bool + stream_replay_as_workflow_fail_for_types: set[str] @dataclass diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 6855e781a4..18dadc94ef 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -291,6 +291,18 @@ class StreamConfig: the error. - A Worker reads the three limits when it starts. It refuses a new client with other limits, as it refuses one with other Store names. + - A read with no ``max_records`` gives at most 256 Records in a page, and a + read with no ``max_bytes`` at most 4 MiB of them. A page has at most 16 MiB + of Records, also for a larger ``max_bytes``. + - A read fails with ``STREAM_ERROR_REASON_UNSUPPORTED`` for a Record over + :py:attr:`max_record_bytes`. So a reader needs a limit at least as large as + that of each writer of its Stream. + - A read that waits holds its Workflow Task. A Signal that comes meanwhile + waits until the read has its page, or until the heartbeat of the task. + - A read of a Stream with no body type raises :exc:`TypeError` in the call, as + in client code. A body that isn't of the Stream's type fails the Workflow + Task, as an Activity result that can't be converted does. It fails the + Workflow if the failure exception types have the error of the conversion. .. warning:: This API is experimental and subject to change. @@ -315,9 +327,10 @@ class StreamConfig: """ max_record_bytes: int = 1536 * 1024 - """Maximum size in bytes of one Record of an append. Defaults to 1.5 MiB. - Must be greater than or equal to one. The size is that of the stored - Record, which counts its Producer. + """Maximum size in bytes of one Record of an append, and of one Record that a + read of Workflow code gives. Defaults to 1.5 MiB. Must be greater than or + equal to one. The size is that of the stored Record, which counts its + Producer. """ max_batch_bytes: int = 4 * 1024 * 1024 diff --git a/temporalio/worker/_replayer.py b/temporalio/worker/_replayer.py index 5cd4b5015b..d6072352ef 100644 --- a/temporalio/worker/_replayer.py +++ b/temporalio/worker/_replayer.py @@ -75,7 +75,9 @@ def __init__( ``stream_config`` is the Stream config of the client that the worker used. A replay takes the result of each append, close, create and - describe of a Stream from history, so it calls no Store for them. + describe of a Stream from history, so it calls no Store for them. It + reads the Records of each Stream read again from the Store, and fails if + the Store no longer has them. """ self._config = ReplayerConfig( workflows=list(workflows), @@ -318,6 +320,10 @@ def on_eviction_hook( # per workflow type nondeterminism_as_workflow_fail=workflow_worker.nondeterminism_as_workflow_fail(), nondeterminism_as_workflow_fail_for_types=workflow_worker.nondeterminism_as_workflow_fail_for_types(), + stream_replay_as_workflow_fail=workflow_worker.stream_replay_as_workflow_fail(), + stream_replay_as_workflow_fail_for_types=( + workflow_worker.stream_replay_as_workflow_fail_for_types() + ), # All values below are ignored but required by Core max_cached_workflows=2, tuner=temporalio.bridge.worker.TunerHolder( @@ -367,7 +373,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), + streams=_bridge_streams(lambda: stream_config, None), ), ) bridge_worker_scope = bridge_worker diff --git a/temporalio/worker/_worker.py b/temporalio/worker/_worker.py index cebe0d7f92..0087af1059 100644 --- a/temporalio/worker/_worker.py +++ b/temporalio/worker/_worker.py @@ -148,6 +148,7 @@ def __init__( nexus_task_poller_behavior: PollerBehavior | None = None, disable_payload_error_limit: bool = False, max_workflow_task_external_storage_concurrency: int = _DEFAULT_WORKFLOW_TASK_EXTERNAL_STORAGE_CONCURRENCY, + stream_read_max_wait: timedelta | None = None, ) -> None: """Create a worker to process workflows and/or activities. @@ -347,6 +348,10 @@ def __init__( Please report any issues you encounter with this setting or if you feel the default should be changed. WARNING: This setting is experimental. + stream_read_max_wait: Longest wait of one Store call of a Stream read + of Workflow code. A read that waits longer calls its Store again. + Defaults to 60 seconds. + WARNING: This setting is experimental. """ config = WorkerConfig( @@ -396,6 +401,7 @@ def __init__( nexus_task_poller_behavior=nexus_task_poller_behavior, disable_payload_error_limit=disable_payload_error_limit, max_workflow_task_external_storage_concurrency=max_workflow_task_external_storage_concurrency, + stream_read_max_wait=stream_read_max_wait, ) plugins_from_client = cast( @@ -721,7 +727,17 @@ 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"]), + streams=_bridge_streams( + lambda: self.client._config["stream_config"], + config.get("stream_read_max_wait"), + ), + stream_replay_as_workflow_fail=self._workflow_worker is not None + and self._workflow_worker.stream_replay_as_workflow_fail(), + stream_replay_as_workflow_fail_for_types=( + self._workflow_worker.stream_replay_as_workflow_fail_for_types() + if self._workflow_worker + else set() + ), ), ) @@ -1071,6 +1087,7 @@ class WorkerConfig(TypedDict, total=False): nexus_task_poller_behavior: PollerBehavior | None disable_payload_error_limit: bool max_workflow_task_external_storage_concurrency: int + stream_read_max_wait: timedelta | None def _poller_behavior_to_bridge( diff --git a/temporalio/worker/_workflow.py b/temporalio/worker/_workflow.py index 2c1922f293..58fd845371 100644 --- a/temporalio/worker/_workflow.py +++ b/temporalio/worker/_workflow.py @@ -868,6 +868,22 @@ def nondeterminism_as_workflow_fail_for_types(self) -> set[str]: ) } + def stream_replay_as_workflow_fail(self) -> bool: + return any( + issubclass(temporalio.workflow.StreamReplayError, typ) + for typ in self._workflow_failure_exception_types + ) + + def stream_replay_as_workflow_fail_for_types(self) -> set[str]: + return { + k + for k, v in self._workflows.items() + if any( + issubclass(temporalio.workflow.StreamReplayError, typ) + for typ in v.failure_exception_types + ) + } + class _DeadlockError(Exception): """Exception class for deadlocks. Contains functionality to swap the default traceback for another.""" diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index c640855226..847cfb8a98 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -713,6 +713,8 @@ def _apply( self._streams.resolve_append(job.resolve_stream_append) elif job.HasField("resolve_stream_close"): self._streams.resolve_close(job.resolve_stream_close) + elif job.HasField("resolve_stream_read"): + self._streams.resolve_read(job.resolve_stream_read) elif job.HasField("signal_workflow"): self._apply_signal_workflow(job.signal_workflow) elif job.HasField("initialize_workflow"): diff --git a/temporalio/worker/_workflow_streams.py b/temporalio/worker/_workflow_streams.py index d5284934fe..0edfd47471 100644 --- a/temporalio/worker/_workflow_streams.py +++ b/temporalio/worker/_workflow_streams.py @@ -4,7 +4,10 @@ import asyncio import functools +import typing from collections.abc import Callable, Generator +from dataclasses import dataclass +from datetime import timedelta from typing import TYPE_CHECKING, Any, cast import google.protobuf.json_format @@ -16,6 +19,7 @@ import temporalio.api.stream.v1 import temporalio.api.streamservice.v1 as proto import temporalio.bridge.proto.workflow_activation +import temporalio.bridge.proto.workflow_commands import temporalio.bridge.streams import temporalio.common import temporalio.exceptions @@ -41,12 +45,26 @@ _STORE_CALL_ACTIVITY = "__temporal_stream_store_call" +@dataclass +class _Read: + """The read of one ``read_page`` call.""" + + after: bytes + """The offset that the read started from.""" + + waiter: asyncio.Future[Any] + """Gets the page of the call.""" + + page_type: Any + """The type of the page that the call returns.""" + + class _WorkflowStreams: # pyright: ignore[reportUnusedClass] """The Stream calls of one Workflow instance. - An append and a close are commands of SDK Core, which makes the Store call and - gives the result in a job. Core has no command for a create or a describe, so - those run in a Local Activity of the SDK. + An append, a close and a read are commands of SDK Core, which makes the Store + calls and gives each result in a job. Core has no command for a create or a + describe, so those run in a Local Activity of the SDK. """ def __init__(self, instance: _WorkflowInstanceImpl) -> None: @@ -56,6 +74,8 @@ def __init__(self, instance: _WorkflowInstanceImpl) -> None: self._closes: dict[int, asyncio.Future[Any]] = {} self.task_error: Exception | None = None """The error of a call that must fail the Workflow Task, if one came.""" + # Each read whose job hasn't come, by seq. A cancelled read gets its one job too. + self._reads: dict[int, _Read] = {} def start( self, input: StartNexusOperationInput[Any, OutputT] @@ -64,7 +84,9 @@ def start( The command of the call is added before this returns, so commands are in the order of the calls. Cancelling the handle ends its wait immediately. - Core can't stop an append or a close, so those still run. + Core can't stop an append or a close, so those still run. A cancelled + read sends ``RequestCancelStreamRead``, and the job that still comes for + it is dropped. """ instance = self._instance instance._assert_not_read_only("start a Stream call") @@ -79,6 +101,8 @@ def start( request = temporalio.nexus.system._support.model_to_proto(model, *converters) # The future of the job of the call, or the task of its Local Activity result: asyncio.Future[Any] + # The seq of the call's read, or 0 for another operation + read_seq = 0 if isinstance(request, proto.AppendRecordsRequest): stream = self._stream(model.ref) seq = instance._next_seq("stream_append") @@ -94,6 +118,28 @@ def start( close.seq = seq close.stream.CopyFrom(stream) result = self._closes[seq] = instance.create_future() + elif isinstance(request, proto.ReadRecordsRequest): + # The converter refuses a body of no type, and the job of the page would + # then fail the Workflow Task. + if typing.get_args(result_type) == (object,): + raise TypeError( + "Cannot read a Stream with no body type. Give get_stream a " + "body_type, or a StreamRef with a type argument." + ) + stream = self._stream(model.ref) + read_seq = instance._next_seq("stream_read") + instance._add_command().read_stream.CopyFrom( + temporalio.bridge.proto.workflow_commands.ReadStream( + seq=read_seq, + stream=stream, + from_offset=request.from_offset, + wait=request.wait if request.HasField("wait") else None, + max_records=request.max_records, + max_bytes=request.max_bytes, + ) + ) + result = instance.create_future() + self._reads[read_seq] = _Read(request.from_offset, result, result_type) else: # The Local Activity picks the Store of a ref with no Store name. A replay # has its result, so a replay asks no selector for it. @@ -105,15 +151,25 @@ 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]) + if isinstance(request, proto.ReadRecordsRequest): + return result.result() return temporalio.nexus.system._support.model_from_proto( self._response(operation, model, request, result), result_type, *converters, ) + def stop(_: asyncio.Task[OutputT]) -> None: + if result.done(): + return + result.cancel() + # Only a read has a cancel command. An eviction sends no command. + if read_seq and not instance._deleting: + instance._add_command().request_cancel_stream_read.seq = read_seq + 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(lambda _: result.done() or result.cancel()) + task.add_done_callback(stop) return _StreamCall(task) def resolve_append( @@ -126,6 +182,36 @@ def resolve_close( ) -> None: self._resolve(self._closes, job.seq, None, job) + def resolve_read( + self, job: temporalio.bridge.proto.workflow_activation.ResolveStreamRead + ) -> None: + read = self._reads.pop(job.seq, None) + if read is None: + raise RuntimeError(f"Failed finding Stream read for sequence {job.seq}") + # The job of a cancelled call is dropped. A cancel job is dropped too if it comes first, + # as in a replay, since only the cancel of the call may end its wait. + if read.waiter.done() or job.HasField("cancelled"): + return + if job.HasField("failed"): + read.waiter.set_exception(self._error(job.failed)) + return + records = job.page.records + page = proto.ReadRecordsResponse( + records=records, + last_offset=records[-1].offset if records else read.after, + done=job.page.done, + ) + # A body that the converter refuses fails the Workflow Task, as a result of a + # Local Activity does. + read.waiter.set_result( + temporalio.nexus.system._support.model_from_proto( + page, + read.page_type, + self._instance._context_free_payload_converter, + self._instance._context_free_failure_converter, + ) + ) + def _resolve( self, calls: dict[int, asyncio.Future[Any]], @@ -140,15 +226,18 @@ def _resolve( if future.done(): return if job.HasField("failed"): - future.set_exception( - _stream_error_from_failure(job.failed) - or self._instance._context_free_failure_converter.from_failure( - job.failed, self._instance._context_free_payload_converter - ) - ) + future.set_exception(self._error(job.failed)) else: future.set_result(result) + 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, operation: str, store: str, request: google.protobuf.message.Message ) -> asyncio.Future[Any]: @@ -373,11 +462,13 @@ def _for_core( def _bridge_streams( # pyright: ignore[reportUnusedFunction] stream_config: Callable[[], StreamConfig | None], + read_max_wait: timedelta | None, ) -> temporalio.bridge.streams.WorkerStreams: """Return what the bridge needs for the Stream Stores of a worker. ``stream_config`` gives the Stream config that the worker has at a call, - which is the one of another client after a client swap. + which is the one of another client after a client swap. ``read_max_wait`` is + the longest wait of one Store call of a read, or ``None`` for Core's default. """ def store(name: str) -> StreamStore: @@ -393,6 +484,9 @@ def store(name: str) -> StreamStore: (name, _StoreCaller(functools.partial(store, name))) for name in sorted(names) ], + read_max_wait_millis=int(1000 * read_max_wait.total_seconds()) + if read_max_wait is not None + else None, ) diff --git a/temporalio/workflow/__init__.py b/temporalio/workflow/__init__.py index 60b02cc543..3ddb444b30 100644 --- a/temporalio/workflow/__init__.py +++ b/temporalio/workflow/__init__.py @@ -119,6 +119,7 @@ ContinueAsNewVersioningBehavior, NondeterminismError, ReadOnlyContextError, + StreamReplayError, VersioningIntent, _NotInWorkflowEventLoopError, ) @@ -246,6 +247,7 @@ "ContinueAsNewVersioningBehavior", "NondeterminismError", "ReadOnlyContextError", + "StreamReplayError", "VersioningIntent", "HandlerUnfinishedPolicy", "UnfinishedSignalHandlersWarning", diff --git a/temporalio/workflow/_exceptions.py b/temporalio/workflow/_exceptions.py index 2d34c2fedd..1542959878 100644 --- a/temporalio/workflow/_exceptions.py +++ b/temporalio/workflow/_exceptions.py @@ -9,6 +9,7 @@ __all__ = [ "NondeterminismError", "ReadOnlyContextError", + "StreamReplayError", "VersioningIntent", "ContinueAsNewVersioningBehavior", ] @@ -23,6 +24,18 @@ def __init__(self, message: str) -> None: self.message = message +class StreamReplayError(temporalio.exceptions.TemporalError): + """Error of a Workflow replay whose Stream Store no longer has the Records of + a read as the first run read them. + + SDK Core fails the Workflow Task with it. A Worker or a Workflow that has this + class in its failure exception types fails the Workflow instead. + + .. warning:: + This API is experimental and subject to change. + """ + + class ReadOnlyContextError(temporalio.exceptions.TemporalError): """Error thrown when trying to do mutable workflow calls in a read-only context like a query or update validator. diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py index 2da70bb462..49c1be9aa8 100644 --- a/tests/nexus/test_streams_with_worker.py +++ b/tests/nexus/test_streams_with_worker.py @@ -1,6 +1,8 @@ """Tests of Streams with a Worker on the test server.""" +import asyncio import dataclasses +import hashlib import itertools import random from collections.abc import Sequence @@ -21,7 +23,7 @@ ) from temporalio.api.taskqueue.v1 import TaskQueue from temporalio.api.workflowservice.v1 import DescribeTaskQueueRequest -from temporalio.client import Client, WorkflowFailureError +from temporalio.client import Client, StreamConfig, WorkflowFailureError from temporalio.converter import ( DataConverter, ExternalStorage, @@ -32,6 +34,7 @@ StreamRef, StreamStatus, ) +from temporalio.testing import MemoryStreamStore from temporalio.worker import ( ActivityInboundInterceptor, Interceptor, @@ -42,6 +45,7 @@ from tests.helpers.streams import ( ContextCodec, FaultStore, + Hold, RunOptions, answers, failure_note, @@ -83,6 +87,10 @@ async def _answers( elif operation == "close": await stream.close() answers.append("closed") + elif operation == "read": + page = await stream.read_page() + bodies = [record.body for record in page.records] + answers.append([bodies, (page.last_offset or b"").hex(), page.done]) else: described = await stream.describe() answers.append([described.status, (described.last_offset or b"").hex()]) @@ -107,39 +115,50 @@ async def run(self, calls: list[list[Any]], in_activity: bool = False) -> list[A return await _answers(workflow, calls) -def _without_writer(request: Message) -> Message: - """Return a request without what differs between two writers of the same call.""" - copy = type(request)() - copy.CopyFrom(request) - for name in ("producer", "request_id"): - if name in copy.DESCRIPTOR.fields_by_name: - copy.ClearField(name) - return copy +def _writes(store: FaultStore) -> list[Message]: + """Return each request of a Store but its reads, which Core pages in its own way, + without what differs between two writers of the same call. + """ + writes: list[Message] = [] + for request in store.requests: + if isinstance(request, ReadRecordsRequest): + continue + copy = type(request)() + copy.CopyFrom(request) + for name in ("producer", "request_id"): + if name in copy.DESCRIPTOR.fields_by_name: + copy.ClearField(name) + writes.append(copy) + return writes async def test_workflow_code_and_a_client_get_the_same_answers(client: Client) -> None: for seed in range(8): with failure_note(f"seed {seed}"): rng = random.Random(seed) - calls: list[list[Any]] = [] - created: set[str] = set() + # One run sends one request id with each of its creates, so a second create + # of a Stream would be the first one again for a Workflow and not for a client. + calls: list[list[Any]] = [ + ["create", f"s-{seed}-{number}", rng.randrange(3)] for number in (0, 1) + ] + operations = ["append", "append", "append", "close", "describe"] + # A replay needs a Store only for a read, so every other script has none. + reads = seed % 2 == 1 + if reads: + operations += ["read", "read"] for _ in range(rng.randrange(4, 12)): - stream_id = f"s-{seed}-{rng.randrange(3)}" - match rng.choice(["create", "append", "append", "close", "describe"]): - # Each create of one run has the same request id, so a second create - # of a Stream is the first one again for a Workflow and not for a client. - case "create" if stream_id not in created: - created.add(stream_id) - calls.append(["create", stream_id, rng.randrange(3)]) - case "create": - calls.append(["describe", stream_id]) - case "append": - bodies = [ - rng.randrange(100) for _ in range(rng.randrange(1, 4)) - ] - calls.append(["append", stream_id, bodies]) - case operation: - calls.append([operation, stream_id]) + # The third Stream is never created. + stream_id = f"s-{seed}-{rng.choice([0, 0, 0, 1, 1, 2])}" + operation = rng.choice(operations) + if operation == "append": + bodies = [rng.randrange(100) for _ in range(rng.randrange(1, 4))] + calls.append(["append", stream_id, bodies]) + else: + calls.append([operation, stream_id]) + if reads: + # Each script reads a closed Stream to its end, and another one. + calls += [[operation, f"s-{seed}-0"] for operation in ("close", "read")] + calls.append(["read", f"s-{seed}-1"]) # The two Stores have one name and the same Stream ids, so a call is the same # request in both. for_client, for_workflow = FaultStore(), FaultStore() @@ -147,23 +166,21 @@ async def test_workflow_code_and_a_client_get_the_same_answers(client: Client) - workflow_client = stream_client(client, for_workflow) ran = await run(workflow_client, RunOptions(_CallsWorkflow, [calls])) assert ran.result == from_client - assert [_without_writer(request) for request in for_workflow.requests] == [ - _without_writer(request) for request in for_client.requests - ] + assert _writes(for_workflow) == _writes(for_client) appends = [ request.request_id for request in for_workflow.requests if isinstance(request, AppendRecordsRequest) ] assert all(appends) and len(set(appends)) == len(appends) - # A replay makes no call, with the Stores of the run and with none. - requests = list(for_workflow.requests) - for replay_client in (workflow_client, client): + # A replay writes nothing, with the Stores of the run and with none. + written = _writes(for_workflow) + for replay_client in (workflow_client, client)[: 1 if reads else 2]: await Replayer( workflows=[_CallsWorkflow], stream_config=replay_client._config["stream_config"], ).replay_workflow(ran.history) - assert for_workflow.requests == requests + assert _writes(for_workflow) == written def _bodies(writer: str) -> list[Any]: @@ -176,6 +193,11 @@ def _bodies(writer: str) -> list[Any]: return [f"{writer} plain", {"writer": writer}, claim] +def _digest(bodies: Sequence[Any]) -> str: + """Return a digest of bodies, so that a Workflow result has no body in it.""" + return hashlib.sha256(repr(bodies).encode()).hexdigest() + + @activity.defn async def _append_bodies(stream_id: str) -> None: stream = activity.client().get_stream(StreamRef(id=stream_id)) @@ -185,12 +207,13 @@ async def _append_bodies(stream_id: str) -> None: @workflow.defn class _BodiesWorkflow: @workflow.run - async def run(self, stream_id: str) -> None: + async def run(self, stream_id: str) -> str: await workflow.execute_activity( _append_bodies, stream_id, start_to_close_timeout=timedelta(seconds=10) ) - stream = workflow.get_stream(StreamRef(id=stream_id)) + stream = workflow.get_stream(StreamRef[Any](id=stream_id)) await stream.append(*_bodies("workflow")) + return _digest([record.body async for record in stream.read()]) async def test_a_body_reads_the_same_on_every_path(client: Client) -> None: @@ -204,10 +227,11 @@ async def test_a_body_reads_the_same_on_every_path(client: Client) -> None: stream = await client.create_stream(id="bodies") await stream.append(*_bodies("client")) options = RunOptions(_BodiesWorkflow, ["bodies"], activities=[_append_bodies]) - await run(client, options) + ran = await run(client, options) expected = [*_bodies("client"), *_bodies("activity"), *_bodies("workflow")] assert [record.body async for record in stream.read()] == expected + assert ran.result == _digest(expected) # The Store has each body as the codec gave it with no context, and the storage of # the Worker has none of them. stored = await store.memory.read_records(ReadRecordsRequest(stream_id="bodies")) @@ -279,12 +303,18 @@ def append_requests() -> list[AppendRecordsRequest]: # A refusal is the same error for a client, an Activity and Workflow code. Workflow # code gets it again in each task that replays the call. await stream.close() - calls = [append, ["describe", "errors"], ["describe", "missing"]] + calls = [ + append, + ["describe", "errors"], + ["describe", "missing"], + ["read", "missing"], + ] refused = await answers_on("client", calls) assert [answer[:2] for answer in refused] == [ ["error", StreamErrorReason.STREAM_ERROR_REASON_CLOSED], [StreamStatus.StreamStatusClosed, (3).to_bytes(8, "big").hex()], ["error", StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND], + ["error", StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND], ] for path in ("activity", "workflow"): with failure_note(path): @@ -346,6 +376,7 @@ async def task_fails(handle: Any, _worker: Any) -> None: ["append", "s", [1]], ["close", "s"], ["describe", "s"], + ["read", "s"], ] # The task fails also on a Worker that fails a Workflow for any exception. for (case, (worker_client, store)), call, failure_types in itertools.product( @@ -556,6 +587,7 @@ async def test_an_append_over_a_limit_of_the_config_never_reaches_the_store( client: Client, ) -> None: too_large = StreamErrorReason.STREAM_ERROR_REASON_TOO_LARGE + unsupported = StreamErrorReason.STREAM_ERROR_REASON_UNSUPPORTED default_bytes = 4 * 1024 * 1024 for seed in range(12): with failure_note(f"seed {seed}"): @@ -601,10 +633,18 @@ def calls(stream_id: str) -> list[list[Any]]: ] from_client = await _answers(streams, calls(f"client {seed}")) - options = RunOptions( - _CallsWorkflow, [calls(f"workflow {seed}")], replay=True - ) + workflow_calls = calls(f"workflow {seed}") + if record <= 3000: + # A client with a larger limit writes a Record over the limit of the + # Worker, and a read of Workflow code refuses that Record. + writer = stream_client(client, store) + large = await writer.create_stream(id=f"large {seed}", body_type=str) + await large.append("x" * 2 * record) + workflow_calls.append(["read", f"large {seed}"]) + options = RunOptions(_CallsWorkflow, [workflow_calls], replay=True) from_workflow = (await run(streams, options)).result + if record <= 3000: + assert from_workflow.pop()[:2] == ["error", unsupported] for answers in (from_client, from_workflow): assert [ "written" if answer[0] != "error" else answer[1] @@ -615,6 +655,7 @@ def calls(stream_id: str) -> list[list[Any]]: len(request.records) for request in store.requests if isinstance(request, AppendRecordsRequest) + and request.stream_id != f"large {seed}" ] == [len(sizes) for sizes, fits in batches if fits] * 2 @@ -643,3 +684,385 @@ async def test_a_create_in_a_later_run_of_the_chain_is_the_same_create( assert ran.result is True creates = [r for r in store.requests if isinstance(r, CreateStreamRequest)] assert len(creates) == 4 and len({create.request_id for create in creates}) == 1 + + +_handled: dict[int, asyncio.Event] = {} +"""An event for each Record of the writing Activity, set once the Workflow handled it.""" + + +@activity.defn +async def _write_one_by_one(stream_id: str, count: int) -> None: + stream = activity.client().get_stream(StreamRef[str](id=stream_id)) + for number in range(count): + await stream.append(f"a body, number {number}") + # The next Record comes only once the Workflow has handled this one. + await _handled[number].wait() + await stream.close() + + +@activity.defn +async def _handle(number: int) -> None: + _handled[number].set() + + +@workflow.defn +class _ReadingWorkflow: + @workflow.run + async def run(self, stream_id: str, count: int) -> list[int]: + stream = await workflow.create_stream(id=stream_id, body_type=str) + writer = workflow.start_activity( + _write_one_by_one, + args=[stream_id, count], + start_to_close_timeout=timedelta(seconds=30), + ) + numbers: list[int] = [] + async for record in stream.read(wait=timedelta(seconds=30)): + number = int(record.body.rsplit(" ", 1)[1]) + await workflow.execute_activity( + _handle, number, start_to_close_timeout=timedelta(seconds=30) + ) + numbers.append(number) + await writer + return numbers + + +async def test_a_workflow_reads_the_records_of_an_activity_that_still_runs( + client: Client, +) -> None: + count = 5 + for cached in (True, False): + with failure_note(f"cached {cached}"): + _handled.clear() + _handled.update({number: asyncio.Event() for number in range(count)}) + options = RunOptions( + _ReadingWorkflow, + [f"read while written, cached {cached}", count], + activities=[_write_one_by_one, _handle], + cached=cached, + replay=True, + ) + ran = await run(stream_client(client, FaultStore()), options) + assert ran.result == list(range(count)) + assert not any( + b"a body" in event.SerializeToString() for event in ran.history.events + ) + + +@workflow.defn +class _EndingWorkflow: + """Starts a Stream call that nothing awaits, and ends in the way of ``how``.""" + + def __init__(self) -> None: + self._signals = 0 + + @workflow.signal + def go_on(self) -> None: + self._signals += 1 + + @workflow.run + async def run(self, stream_id: str, how: str) -> None: + if how == "continued": + return + stream = await workflow.create_stream(id=stream_id, body_type=int) + call: asyncio.Future[Any] + if how == "append": + call = asyncio.ensure_future(stream.append(1)) + elif how == "close": + call = asyncio.ensure_future(stream.close()) + elif how == "page": + await stream.append(1) + await stream.read_page(wait=timedelta(minutes=5)) + return + else: + call = asyncio.ensure_future(stream.read_page(wait=timedelta(minutes=5))) + await workflow.wait_condition(lambda: self._signals > 0) + # The task of the call makes its call in its first step. + await asyncio.sleep(0) + if how == "cancel the read": + call.cancel() + await workflow.wait_condition(lambda: self._signals > 1) + elif how == "continue as new": + workflow.continue_as_new(args=[stream_id, "continued"]) + + +async def _end_while_a_read_waits(client: Client, how: str) -> None: + """Run a Workflow whose read waits on a held Store call, end the read in the way + of ``how``, and check that the Store call was cancelled and that a replay passes. + """ + store, hold = FaultStore(), Hold() + store.faults["read_records"].append(hold) + + async def end(handle: Any, worker: Worker) -> None: + await hold.started.wait() + if how == "cancel": + await handle.cancel() + elif how == "shutdown": + await worker.shutdown() + else: + await handle.signal(_EndingWorkflow.go_on) + await asyncio.wait_for(hold.cancelled.wait(), 10) + if how == "shutdown": + await handle.terminate() + elif how == "cancel the read": + await handle.signal(_EndingWorkflow.go_on) + + # The read holds its Workflow Task until the heartbeat, so the task is short. + options = RunOptions( + _EndingWorkflow, + [f"ends by {how}", how], + task_timeout=timedelta(seconds=2), + during=end, + replay=True, + ) + ran = await run(stream_client(client, store), options) + assert (ran.result is None) == (how not in ("cancel", "shutdown")) + reads = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] + assert len(reads) == 1 + + +async def test_a_read_that_core_stops_leaves_no_store_task(client: Client) -> None: + # A cancel of the read, a terminal command, and the eviction of a Worker that shuts down + for how in ("cancel the read", "return", "shutdown"): + with failure_note(how): + await _end_while_a_read_waits(client, how) + + +@pytest.mark.parametrize( + "how", ["continue as new", "cancel", "page", "append", "close"] +) +async def test_a_workflow_that_ends_while_a_read_waits_leaves_nothing( + client: Client, how: str +) -> None: + # The return while a read waits is a case of the test above. + if how in ("continue as new", "cancel"): + await _end_while_a_read_waits(client, how) + return + # A read that gave a page, and an append or a close that nothing awaits, don't hold + # the last command, so the Workflow ends in the task of the call. + options = RunOptions(_EndingWorkflow, [f"ends after its {how}", how], replay=True) + ran = await run(stream_client(client, FaultStore()), options) + assert ran.result is None + assert len(_events(ran.history, EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED)) == 1 + + +@workflow.defn +class _LatePagesWorkflow: + """Reads Records that come in a later Workflow Task than the one of its reads.""" + + @workflow.run + async def run(self, how: str) -> list[list[str]]: + wait = timedelta(seconds=30) + s = workflow.get_stream(StreamRef[str](id=f"s of {how}")) + t = workflow.get_stream(StreamRef[str](id=f"t of {how}")) + if how == "a cancel": + # The page of `t` makes the Workflow cancel its read of `s`, whose reader then + # reads `u`. A replay gives the cancel job of `s` with that page, before the cancel. + u = workflow.get_stream(StreamRef[str](id=f"u of {how}")) + + async def read_s() -> None: + try: + await s.read_page(wait=wait) + except asyncio.CancelledError: + await u.read_page() + + reader = asyncio.ensure_future(read_s()) + # The task around this read lets the reader of `s` run first if its wait ended. + page = await asyncio.ensure_future(t.read_page(wait=wait)) + reader.cancel() + last = await t.read_page(from_offset=page.last_offset) + await reader + return [[r.body for r in page.records], [r.body for r in last.records]] + if how == "two readers": + # One reader takes a page of `s` and stops. The other waits for a page of + # `t`, and then reads `s` on from the offset of the first one. + first = asyncio.ensure_future(s.read_page(wait=wait)) + await t.read_page(wait=wait) + offset = (await first).last_offset + second = await s.read_page(from_offset=offset, wait=wait) + return [[r.body for r in page.records] for page in (await first, second)] + pages: list[list[str]] = [] + offset = None + while True: + page = await s.read_page(from_offset=offset, wait=wait) + pages.append([record.body for record in page.records]) + offset = page.last_offset + if page.done: + return pages + + +@pytest.mark.parametrize("how", ["a loop", "two readers", "a cancel"]) +async def test_a_replay_gives_a_read_the_pages_of_the_first_run( + client: Client, how: str +) -> None: + store = FaultStore() + client = stream_client(client, store) + s = await client.create_stream(id=f"s of {how}", body_type=str) + t = await client.create_stream(id=f"t of {how}", body_type=str) + await client.create_stream(id=f"u of {how}", body_type=str) + writes, expected = { + "a loop": ([(s, "a"), (s, "b")], ["a", "b"]), + "two readers": ([(s, "a"), (t, "x"), (s, "b")], ["a", "b"]), + "a cancel": ([(t, "x")], ["x"]), + }[how] + + async def write(handle: Any, _worker: Any) -> None: + async def second_task() -> None: + history = await handle.fetch_history() + started = EventType.EVENT_TYPE_WORKFLOW_TASK_STARTED + assert len(_events(history, started)) > 1 + + # The first task ends at its heartbeat with no page. The pages then come in several + # activations of the next task, which a replay with chunking on gives in one. + await assert_eventually(second_task) + for stream, body in writes: + await stream.append(body) + # The page of this Record gets an activation before the next Record comes. + await asyncio.sleep(0.3) + if how == "a loop": + await s.close() + + options = RunOptions( + _LatePagesWorkflow, + [how], + task_timeout=timedelta(seconds=2), + during=write, + replay=True, + ) + ran = await run(client, options) + assert [body for page in ran.result for body in page] == expected + events = [event.event_type for event in ran.history.events] + completed = events.index(EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED) + assert events[completed + 1] == EventType.EVENT_TYPE_WORKFLOW_TASK_SCHEDULED + + +@workflow.defn +class _ReadOnceWorkflow: + def __init__(self) -> None: + self._go_on = False + + @workflow.signal + def go_on(self) -> None: + self._go_on = True + + @workflow.run + async def run(self, stream_id: str) -> list[int]: + stream = workflow.get_stream(StreamRef[int](id=stream_id)) + bodies = [record.body async for record in stream.read()] + await workflow.wait_condition(lambda: self._go_on) + return bodies + + +@workflow.defn(failure_exception_types=[workflow.StreamReplayError]) +class _ReadOnceOptedInWorkflow(_ReadOnceWorkflow): + @workflow.run + async def run(self, stream_id: str) -> list[int]: + return await super().run(stream_id) + + +async def test_a_replay_reads_its_python_stores(client: Client) -> None: + store = FaultStore() + stream = await stream_client(client, store).create_stream( + id="replayed", body_type=int + ) + await stream.append(1, 2, 3) + + async def go_on(handle: Any, _worker: Any) -> None: + await handle.signal(_ReadOnceWorkflow.go_on) + + options = RunOptions(_ReadOnceWorkflow, ["replayed"], during=go_on) + ran = await run(stream_client(client, store), options) + assert ran.result == [1, 2, 3] + # A `Replayer` reads the Records again from the Store, and fails without them. + replayer = Replayer( + workflows=[_ReadOnceWorkflow], stream_config=StreamConfig([store]) + ) + reads = len(store.requests) + await replayer.replay_workflow(ran.history) + assert isinstance(store.requests[reads], ReadRecordsRequest) + store.memory = MemoryStreamStore() + with pytest.raises(RuntimeError): + await replayer.replay_workflow(ran.history) + + # A Worker with no cache replays the read in its second task. With the Records gone + # the task fails, or the Workflow with the opt-in of the Worker or of the Workflow. + cases: dict[str, tuple[type, list[type[BaseException]]]] = { + "no opt-in": (_ReadOnceWorkflow, []), + "the Worker option": (_ReadOnceWorkflow, [workflow.StreamReplayError]), + "the Workflow option": (_ReadOnceOptedInWorkflow, []), + } + for case, (workflow_class, failure_types) in cases.items(): + with failure_note(case): + store = FaultStore() + stream_id = f"gone with {case}" + stream = await stream_client(client, store).create_stream( + id=stream_id, body_type=int + ) + await stream.append(1, 2, 3) + + async def lose_the_records(handle: Any, _worker: Any) -> None: + async def has_read() -> None: + history = await handle.fetch_history() + assert _events(history, EventType.EVENT_TYPE_MARKER_RECORDED) + + await assert_eventually(has_read) + store.memory = MemoryStreamStore() + await handle.signal(_ReadOnceWorkflow.go_on) + if case == "no opt-in": + await assert_task_fail_eventually(handle) + await handle.terminate() + + options = RunOptions( + workflow_class, + [stream_id], + cached=False, + worker={"workflow_failure_exception_types": failure_types}, + during=lose_the_records, + ) + ran = await run(stream_client(client, store), options) + assert isinstance(ran.result, WorkflowFailureError) + if case != "no opt-in": + cause = ran.result.cause + assert isinstance(cause, ApplicationError) + assert cause.type == "StreamReplayError" + failed = _events(ran.history, EventType.EVENT_TYPE_WORKFLOW_TASK_FAILED) + assert not failed + + +@workflow.defn +class _ReadAllWorkflow: + @workflow.run + async def run(self, stream_id: str, limits: dict[str, int]) -> list[int]: + stream = workflow.get_stream(StreamRef[int](id=stream_id)) + records = stream.read( + wait=timedelta(minutes=5), + max_records=limits.get("max_records"), + max_bytes=limits.get("max_bytes"), + ) + return [record.body async for record in records] + + +async def test_a_workflow_read_asks_the_store_with_its_limits(client: Client) -> None: + store = FaultStore() + client = stream_client(client, store) + stream = await client.create_stream(id="paged", body_type=int) + await stream.append(1, 2, 3) + await stream.close() + # A read with no limit asks for 256 Records and 4 MiB. Each Store call waits for the + # longest wait of the Worker at most. + cases: list[tuple[dict[str, int], tuple[int, int, int]]] = [ + ({"max_records": 1, "max_bytes": 100}, (1, 100, 2)), + ({}, (256, 4 * 1024 * 1024, 2)), + ] + for limits, expected in cases: + with failure_note(f"limits {limits}"): + del store.requests[:] + options = RunOptions( + _ReadAllWorkflow, + ["paged", limits], + worker={"stream_read_max_wait": timedelta(seconds=2)}, + ) + assert (await run(client, options)).result == [1, 2, 3] + reads = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] + asked = [(r.max_records, r.max_bytes, r.wait.ToSeconds()) for r in reads] + # With one Record in a page, the read of each Record is one Store call. + assert asked == [expected] * (3 if limits else 1) diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py index c397511b32..17f554e6a6 100644 --- a/tests/worker/test_workflow_streams.py +++ b/tests/worker/test_workflow_streams.py @@ -8,6 +8,8 @@ from datetime import datetime, timedelta, timezone from typing import Any +from google.protobuf.duration_pb2 import Duration +from google.protobuf.empty_pb2 import Empty from google.protobuf.message import Message import temporalio.api.common.v1 @@ -49,6 +51,7 @@ ResolveStreamAppend, ResolveStreamClose, ResolveStreamRead, + SignalWorkflow, StreamAppended, StreamPage, WorkflowActivation, @@ -59,7 +62,9 @@ AppendToStream, CloseStream, CompleteWorkflowExecution, + ReadStream, RequestCancelLocalActivity, + RequestCancelStreamRead, WorkflowCommand, ) from temporalio.bridge.proto.workflow_completion import ( @@ -76,7 +81,10 @@ from temporalio.nexus.system.stream_service import StreamRef as ModelRef from temporalio.testing import MemoryStreamStore from temporalio.worker._workflow import _CommandAwareDataConverter -from temporalio.worker._workflow_instance import _WorkflowInstanceImpl +from temporalio.worker._workflow_instance import ( + _WorkflowInstanceImpl, + _WorkflowLogicFlag, # type: ignore[reportPrivateLocalImportUsage] +) from tests.helpers.streams import ( CodecCall, ContextCodec, @@ -152,10 +160,13 @@ 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) + activation = WorkflowActivation( + run_id="run", jobs=jobs, is_replaying=replaying, available_internal_flags=flags + ) return await asyncio.to_thread(instance.activate, activation) @@ -629,3 +640,284 @@ def selector(context: StreamSelectContext) -> StreamStore: # An eviction ends each task of the instance, also the task of a call that waits. evict = WorkflowActivationJob(remove_from_cache=RemoveFromCache()) assert (await _activate(instance, evict)).HasField("successful") + + +@dataclass +class _ReadCall: + """One generated reader, which reads pages of a Stream one after the other, and + what Workflow code got for each page. + """ + + stream: str + start: int + """The offset that the first page comes after. Zero is the start of the Stream.""" + wait: timedelta | None + max_records: int | None + max_bytes: int | None + pages: int + """The maximum number of pages that the reader asks for.""" + body_type: Any + """The body type of the reader's Stream, which is ``int``, ``Any`` or none.""" + outcome: list[Any] = dataclasses.field(default_factory=list) + + +class _ReadScript: + """The readers of :py:class:`_ReadsWorkflow`, and for each ``step`` Signal the + readers that its handler cancels and the ones that it starts. + """ + + calls: list[_ReadCall] = [] + steps: list[tuple[list[int], list[int]]] = [] + + +@workflow.defn +class _ReadsWorkflow: + def __init__(self) -> None: + self._readers: dict[int, asyncio.Future[None]] = {} + + @workflow.run + async def run(self) -> None: + await workflow.wait_condition(lambda: False) + + @workflow.signal + def step(self) -> None: + cancels, starts = _ReadScript.steps.pop(0) + for call in cancels: + self._readers[call].cancel() + for call in starts: + reader = self._read(_ReadScript.calls[call]) + self._readers[call] = asyncio.ensure_future(reader) + + async def _read(self, call: _ReadCall) -> None: + body_type: Any = call.body_type + ref: Any = ModelRef(id=call.stream, store="a") + if body_type: + ref = ModelRef[body_type](id=call.stream, store="a") + stream = workflow.get_stream(ref) + offset = _offset(call.start) or None + try: + for _ in range(call.pages): + page = await stream.read_page( + from_offset=offset, + wait=call.wait, + max_records=call.max_records, + max_bytes=call.max_bytes, + ) + bodies = [record.body for record in page.records] + offset = page.last_offset + call.outcome.append((bodies, offset or b"", page.done)) + if page.done: + return + except StreamError as err: + call.outcome.append(err.reason) + except TypeError: + call.outcome.append("TypeError") + except asyncio.CancelledError: + call.outcome.append("cancelled") + raise + + +def _offset(number: int) -> bytes: + return number.to_bytes(8, "big") if number else b"" + + +def _body(stream: str, number: int) -> Any: + """Return the body of a Record, which for some isn't the ``int`` of a reader.""" + return "text" if stream == "s1" and number % 3 == 0 else number + + +@dataclass +class _OpenRead: + """A read whose job hasn't come, and the reader that started it.""" + + stream: str + after: int + call: int + cancelled: bool = False + """Whether its reader was cancelled. SDK Core still gives the read its one job.""" + + +async def test_a_read_page_call_is_one_command_and_one_job() -> None: + single_batch = _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH + for seed in range(300): + # Signals run before the Stream jobs of their activation, or after all of them + # with the single-batch flag of the History. + for flags in ((), (single_batch,)): + # A replay sends the same commands as the first run. + replaying = seed % 2 == 1 + with failure_note(f"seed {seed}, flags {flags}, replaying {replaying}"): + await _reads_script(random.Random(seed), flags, replaying) + + +async def _reads_script( + rng: random.Random, flags: Sequence[int], replaying: bool +) -> None: + converter = temporalio.converter.DefaultPayloadConverter() + calls: list[_ReadCall] = [] + _ReadScript.calls, _ReadScript.steps = calls, [] + instance = _new_instance(_ReadsWorkflow) + initialize = WorkflowActivationJob(initialize_workflow=InitializeWorkflow()) + completion = await _activate(instance, initialize, flags=flags, replaying=replaying) + assert not completion.successful.commands + + reads: dict[int, _OpenRead] = {} + # The reader of each read whose cancel job came before its cancel, by seq + early: dict[int, int] = {} + # The offset that each reader is at + positions: list[int] = [] + outcomes: list[list[Any]] = [] + seqs = 0 + + def call_read(call: int, commands: list[WorkflowCommand]) -> None: + """Start the read of a reader's next page.""" + nonlocal seqs + reader, after = calls[call], positions[call] + if reader.body_type is None: + # A read with no body type raises in the call, before any command. + outcomes[call].append("TypeError") + return + seqs += 1 + reads[seqs] = _OpenRead(reader.stream, after, call) + # The command has the wait and the limits of the call, and none that the call lacks. + wait = None + if reader.wait is not None: + wait = Duration() + wait.FromTimedelta(reader.wait) + read = ReadStream( + seq=seqs, + stream=StreamRef(id=reader.stream, store="a"), + from_offset=_offset(after), + wait=wait, + max_records=reader.max_records or 0, + max_bytes=reader.max_bytes or 0, + ) + commands.append(WorkflowCommand(read_stream=read)) + + def cancel(seq: int) -> WorkflowCommand: + command = RequestCancelStreamRead(seq=seq) + return WorkflowCommand(request_cancel_stream_read=command) + + for step in range(rng.randrange(2, 7)): + # Each read gets one job, also a cancelled one, whose job has a cancel or the result + # that came before it. A replay can give a cancel job before the cancel. + jobs: list[ResolveStreamRead] = [] + for seq, read in reads.items(): + if rng.random() >= 0.6: + continue + records = [read.after + 1 + at for at in range(rng.randrange(4))] + page = StreamPage( + records=[ + StreamRecord( + offset=_offset(number), + body=converter.to_payload(_body(read.stream, number)), + ) + for number in records + ], + done=rng.random() < 0.3, + ) + job = ResolveStreamRead(seq=seq, page=page) + if rng.random() < 0.15: + not_found = StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND + job = ResolveStreamRead(seq=seq, failed=core_failure(not_found)) + elif rng.random() < (0.7 if read.cancelled else 0.2 * replaying): + job = ResolveStreamRead(seq=seq, cancelled=Empty()) + jobs.append(job) + rng.shuffle(jobs) + waiting = sorted( + [read.call for read in reads.values() if not read.cancelled] + + list(early.values()) + ) + cancels = [call for call in waiting if rng.random() < 0.25] + starts: list[int] = [] + for _ in range(rng.randrange(3)): + reader = _ReadCall( + stream=rng.choice(["s0", "s1"]), + start=rng.choice([0, 1, 2]), + wait=rng.choice([None, timedelta(0), timedelta(seconds=5)]), + max_records=rng.choice([None, 2]), + max_bytes=rng.choice([None, 100]), + pages=rng.randrange(1, 4), + body_type=rng.choice([int, int, int, Any, Any, None]), + ) + starts.append(len(calls)) + calls.append(reader) + outcomes.append([]) + positions.append(reader.start) + _ReadScript.steps.append((cancels, starts)) + + commands: list[WorkflowCommand] = [] + # The readers that got a job in this activation, in the order of the jobs + got: list[tuple[int, ResolveStreamRead]] = [] + # Whether a reader that waits gets a body that isn't of its type. The job converts + # the page, so this fails the Workflow Task, also if the reader is cancelled later. + refused = False + + def apply_jobs() -> None: + nonlocal refused + for job in jobs: + read = reads.pop(job.seq) + # A cancelled reader no longer waits, so its job is dropped, whatever it is. + if read.cancelled: + continue + # A cancel job doesn't end the wait of a reader. Only its cancel does. + if job.HasField("cancelled"): + early[job.seq] = read.call + continue + got.append((read.call, job)) + bodies = [converter.from_payload(r.body) for r in job.page.records] + typed = calls[read.call].body_type is int + refused = refused or (typed and "text" in bodies) + + def run_handler() -> None: + for call in starts: + call_read(call, commands) + for call in cancels: + outcomes[call].append("cancelled") + if any(of == call for of, _ in got): + # A cancel wins over a job that came for the reader in this + # activation, and a read that has its job gets no cancel command. + got[:] = [(of, job) for of, job in got if of != call] + continue + for seq, read in reads.items(): + if read.call == call and not read.cancelled: + read.cancelled = True + commands.append(cancel(seq)) + for seq in [seq for seq, of in early.items() if of == call]: + del early[seq] + commands.append(cancel(seq)) + + for part in (apply_jobs, run_handler) if flags else (run_handler, apply_jobs): + part() + for call, job in got: + reader = calls[call] + if job.HasField("failed"): + outcomes[call].append(StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND) + continue + bodies = [converter.from_payload(r.body) for r in job.page.records] + if bodies: + positions[call] = int.from_bytes(job.page.records[-1].offset, "big") + # A page with no Record has the offset of its call. + outcomes[call].append((bodies, _offset(positions[call]), job.page.done)) + if not job.page.done and len(outcomes[call]) < reader.pages: + call_read(call, commands) + + signal = SignalWorkflow(signal_name="step", originating_event_id=step + 1) + activation = [WorkflowActivationJob(signal_workflow=signal)] + if refused and flags: + # The jobs come first here, so the handler of the Signal would never start. + activation = [] + activation += [WorkflowActivationJob(resolve_stream_read=job) for job in jobs] + completion = await _activate( + instance, *activation, flags=flags, replaying=replaying + ) + if refused: + assert completion.HasField("failed") + break + assert list(completion.successful.commands) == commands + assert [call.outcome for call in calls] == outcomes + # Each read leaves with its job, also a cancelled one. + assert set(instance._streams._reads) == set(reads) + + # An eviction sends no command, also for the reads whose readers it cancels. + evict = WorkflowActivationJob(remove_from_cache=RemoveFromCache()) + assert not (await _activate(instance, evict)).successful.commands From 2d135631bea2682d2d133246be3123cba7206cb7 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Fri, 20 Nov 2026 22:07:50 -0700 Subject: [PATCH 06/50] Add BufferedAppender 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. --- changelog/added/steady-stream-heron.md | 1 + temporalio/contrib/streams/README.md | 60 +++++++ temporalio/contrib/streams/__init__.py | 10 +- temporalio/contrib/streams/_appender.py | 208 ++++++++++++++++++++++++ tests/contrib/streams/__init__.py | 0 tests/contrib/streams/test_appender.py | 163 +++++++++++++++++++ 6 files changed, 438 insertions(+), 4 deletions(-) create mode 100644 temporalio/contrib/streams/README.md create mode 100644 temporalio/contrib/streams/_appender.py create mode 100644 tests/contrib/streams/__init__.py create mode 100644 tests/contrib/streams/test_appender.py diff --git a/changelog/added/steady-stream-heron.md b/changelog/added/steady-stream-heron.md index 6076ebf9c0..cb91605935 100644 --- a/changelog/added/steady-stream-heron.md +++ b/changelog/added/steady-stream-heron.md @@ -2,3 +2,4 @@ Add experimental `temporalio.client.StreamStore`, the base class of a Stream Sto Add experimental Streams for client and Activity code. `stream_config=StreamConfig(stores=[...])` of `Client.connect` gives a client its Stream Stores, and `Client.create_stream` and `Client.get_stream` return a `Stream` to append to, read, describe and close. A failed call raises `temporalio.exceptions.StreamError` with a `reason`. `max_record_bytes`, `max_batch_bytes` and `max_batch_records` of `StreamConfig` bound an append, and one over a limit fails before its Store gets it. A read of a Stream from `get_stream` needs `body_type=` or a `StreamRef` with a type argument, and raises `TypeError` with neither. `temporalio.contrib.streams.current_producer` gives the Producer of an Activity attempt, and `as_producer` gives back one that code stored. Add experimental Streams for Workflow code. `workflow.create_stream` and `workflow.get_stream` return a `Stream` to append to, describe and close on the Stream Stores of the Worker's client, and `Replayer(stream_config=...)` gives a replay its Stores. Add experimental Stream reads for Workflow code. `Stream.read`, `read_pages` and `read_page` of a Workflow `Stream` give the Records as they come, a replay reads them again from the Store, and `temporalio.workflow.StreamReplayError` in the failure exception types of a Worker or a Workflow fails the Workflow when the Store no longer has them. The Worker option `stream_read_max_wait` bounds the wait of one Store call of a read. +Add experimental `temporalio.contrib.streams.BufferedAppender`, which batches the appends of one Stream in client and Activity code. `append` returns immediately, a batch waits at most `max_delay`, one write runs at a time, and `async with` or `flush()` writes what is left. diff --git a/temporalio/contrib/streams/README.md b/temporalio/contrib/streams/README.md new file mode 100644 index 0000000000..64ce9af567 --- /dev/null +++ b/temporalio/contrib/streams/README.md @@ -0,0 +1,60 @@ +# Streams helpers + +> This package is experimental. Its API can change in a later release. + +`temporalio.contrib.streams` has helpers on top of the Streams API of the SDK. A Stream is an +append-only log of Records in a Stream Store, such as Redis. A client gets its Stores from +`stream_config=StreamConfig(stores=[...])`, and `create_stream` and `get_stream` of a client or +of `temporalio.workflow` return a `Stream`. + +This isn't `temporalio.contrib.workflow_streams`, which keeps its events in a Workflow and +needs no Store. + +## `BufferedAppender` + +`BufferedAppender` batches the appends of one Stream. `append` returns immediately, and the +appender writes the buffered Records as one batch, at most `max_delay` after the first of them +(100 milliseconds by default). One write runs at a time, and the Records keep their order. + +```python +from temporalio.contrib.streams import BufferedAppender + +async with BufferedAppender(stream) as tokens: + async for token in model_tokens(): + tokens.append(token) +``` + +The end of the `async with` block writes the Records that are still in the buffer. Without +`async with`, `await tokens.flush()` does the same. If code appends faster than the Store takes +Records, the buffer grows with no bound, unless that code awaits `flush()` from time to time. A +batch over `max_batch_records` or `max_batch_bytes` of the client's `StreamConfig` then fails, +and `max_batch_records` of the appender keeps each batch under the first. + +An Activity that ends with Records in the buffer still writes them, up to `max_delay` later. +That write has the Producer of the ended attempt, it can come after a write of the next attempt, +and nobody gets its error. `async with`, or a `flush()` before the end, avoids it. + +After a batch fails, the appender writes nothing more, and each later `append` and `flush` +raises the error of that batch, or `RuntimeError` if the write of the batch was cancelled. +`unwritten` is the number of Records that it left behind. + +The appender is for client and Activity code. Workflow code passes its Records to one `append` +call of its Stream. + +## A stored Producer + +Each write has its Producer, which is the writer with its attempt. `current_producer()` gives +the Producer that an append or a close of the running Activity attempt sends by default. An +Activity that stores it, such as in its heartbeat details, gets it back as a proto message, and +`as_producer` turns that into a `Producer` again, which `append(..., producer=...)` takes. + +## Reads + +A read of a Stream from `get_stream(StreamRef(id=...))` raises `TypeError`, since such a ref has +no body type. Pass `body_type=`, or a ref with a type argument such as `StreamRef[str](id=...)`. +A Stream from `create_stream` reads any body with no type. + +In Workflow code, a read with no `max_records` gives at most 256 Records in a page, and a read +with no `max_bytes` at most 4 MiB of them. A page has at most 16 MiB of Records, also for a larger +`max_bytes`. A read fails for a Record over the `max_record_bytes` of the Worker's `StreamConfig`, +so a reader needs a limit at least as large as that of each writer of its Stream. diff --git a/temporalio/contrib/streams/__init__.py b/temporalio/contrib/streams/__init__.py index 7ddbe45e1e..fd05faea41 100644 --- a/temporalio/contrib/streams/__init__.py +++ b/temporalio/contrib/streams/__init__.py @@ -1,13 +1,15 @@ """Helpers on top of the Streams API. -: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. +: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__ = ["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..e18a494302 --- /dev/null +++ b/temporalio/contrib/streams/_appender.py @@ -0,0 +1,208 @@ +"""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 datetime import timedelta +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. The appender + writes the buffered Records as one batch, at most ``max_delay`` after the + first of them. One write runs at a time. Records appended during a write + wait for the next batch, and they keep their order. + + Use it in ``async with``, which writes the remaining Records at the end of + the block, or await :py:meth:`flush` before the code that appends ends. + Otherwise the appender writes the Records that it still holds up to + ``max_delay`` later. For an Activity that has ended, that write still has the + Producer of its attempt, it can come after a write of the next attempt, and + nobody gets its error. + + ``await flush()`` is the backpressure point. If code appends faster than the + Store takes Records, the buffer grows with no bound, unless that code awaits + ``flush()`` 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. If the write of the batch was cancelled, they raise + :exc:`RuntimeError`, and only a ``flush`` that waited for that write gets + the cancel. + + 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_delay: timedelta | None = None, + 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_delay: The longest time that a Record waits in the buffer before + its batch starts to write, while no write runs. ``None`` means + 100 milliseconds. + 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_delay = ( + timedelta(milliseconds=100) if max_delay is None else max_delay + ) + self._max_batch_records = max_batch_records + self._buffer: list[BodyT] = [] + # When the oldest Record came into an empty buffer + self._first_at = 0.0 + self._timer: asyncio.TimerHandle | None = None + self._writing: asyncio.Task[None] | None = None + self._appended = 0 + # Count of the Records that a batch wrote or that a failed batch left behind + 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 + if not self._buffer: + self._first_at = asyncio.get_running_loop().time() + 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 Exception: + if exc is None: + raise + + def _schedule(self) -> None: + """Start the next batch, immediately or when the delay of its first Record ends.""" + 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._timer: + self._timer = asyncio.get_running_loop().call_at( + self._first_at + self._max_delay.total_seconds(), self._start + ) + + def _start(self) -> None: + if self._timer: + self._timer.cancel() + self._timer = 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: + response = await self._stream.append(*batch) + self._last_offset = response.last_offset + except BaseException as err: + # The Records behind a batch that failed, or whose write was cancelled, are + # never written, so a reader sees no gap. + 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/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..ab8b6b00bd --- /dev/null +++ b/tests/contrib/streams/test_appender.py @@ -0,0 +1,163 @@ +"""Tests of the buffered appender, with no server.""" + +import asyncio +import random +from datetime import timedelta +from typing import Any + +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 failure_note, 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.""" + self.writes = 0 + self.overlaps = 0 + + async def append(self, *records: int) -> AppendRecordsResponse: + loop = asyncio.get_running_loop() + started = loop.time() + self.overlaps += self.writes + self.writes += 1 + 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.writes -= 1 + self.batches.append((started, loop.time(), records)) + + +def test_buffered_appender_writes_in_order_one_batch_at_a_time() -> None: + for seed in range(500): + with failure_note(f"seed {seed}"): + run_with_virtual_clock(_appends_script(random.Random(seed))) + + +async def _appends_script(rng: random.Random) -> None: + loop = asyncio.get_running_loop() + max_delay = rng.choice([None, 0.0, 0.02, 0.5]) + max_batch_records = rng.choice([None, None, 1, 2, 5]) + fails_at = rng.choice([None, None, rng.randrange(6)]) + write_time = rng.choice([0.0, 0.03, 0.3]) + cancelled = rng.random() < 0.3 + stream: Any = _FakeStream(write_time, fails_at, cancelled=cancelled) + appender = BufferedAppender[int]( + stream, + max_delay=None if max_delay is None else timedelta(seconds=max_delay), + max_batch_records=max_batch_records, + ) + delay = 0.1 if max_delay is None else max_delay + # Sleeps that end inside a delay, inside a write, and after both + sleeps = [0, delay / 3, delay, write_time / 3, write_time, delay + write_time + 1] + # The time that each appended Record came at, by the Record + arrived: list[float] = [] + # The time from the start of each flush to its end + flushes: list[tuple[float, float]] = [] + # The count of ended batches at the start of the flush that the block waits in + flushing: int | None = None + error: BaseException | None = None + try: + async with appender: + for _ in range(rng.randrange(1, 15)): + action = rng.choice(["append", "sleep"] * 3 + ["flush", "cancel"]) + called_at, appended = loop.time(), len(arrived) + if action == "append": + count = rng.randrange(1, 4) + appender.append(*range(appended, appended + count)) + arrived += [called_at] * count + elif action == "sleep": + await asyncio.sleep(rng.choice(sleeps)) + elif action == "flush": + flushes.append((called_at, float("inf"))) + flushing = len(stream.batches) + offset = await appender.flush() + flushing = None + flushes[-1] = (called_at, loop.time()) + # A flush writes each Record that came before it. + assert stream.written[:appended] == list(range(appended)) + assert int.from_bytes(offset or b"", "big") == len(stream.written) + else: + # A cancelled flush doesn't stop the write that it waits for. + flush = asyncio.ensure_future(appender.flush()) + await asyncio.sleep(rng.choice(sleeps[:4])) + flush.cancel() + flushes.append((called_at, loop.time())) + if rng.random() < 0.5: + # The timer alone writes what is left, with no flush. + await asyncio.sleep(1000) + assert stream.written == list(range(len(arrived))) or appender.unwritten + flushes.append((loop.time(), float("inf"))) + flushing = len(stream.batches) + except (StreamError, RuntimeError, asyncio.CancelledError) as err: + error = err + + # The written Records are the first of the appended ones, in their order. + assert stream.written == list(range(len(stream.written))) + assert stream.overlaps == 0 + assert len(stream.written) + appender.unwritten == len(arrived) + failed = fails_at is not None and len(stream.batches) > fails_at + assert (error is not None) == failed == bool(appender.unwritten) + if error: + # Nothing is written after the batch that failed, and each later call raises its + # error. After a cancelled write that is a `RuntimeError`, as nobody cancelled it. + assert len(stream.batches) == (fails_at or 0) + 1 + later = RuntimeError if cancelled else StreamError + with pytest.raises(later) as raised: + appender.append(0) + with pytest.raises(later) as again: + await appender.flush() + assert raised.value is again.value + # Only a flush that waited for the cancelled write got its cancel. + waited = flushing is not None and flushing <= (fails_at or 0) + if cancelled and waited: + assert isinstance(error, asyncio.CancelledError) + else: + assert error is raised.value + previous_end = float("-inf") + for started, ended, records in stream.batches: + assert 0 < len(records) <= (max_batch_records or len(records)) + due = arrived[records[0]] + delay + # A batch starts once the delay of its first Record ends, or when the write + # before it ends, if that is later. + assert started <= max(due, previous_end) + 1e-9 + # Only a flush starts a batch with no maximum earlier. + flushed = any(start <= started <= end for start, end in flushes) + assert max_batch_records or flushed or started >= due - 1e-9 + previous_end = ended + + +def test_async_with_keeps_the_error_of_its_block() -> None: + async def block() -> None: + stream: Any = _FakeStream(0.0, fails_at=0) + async with BufferedAppender[int](stream) as appender: + appender.append(1) + raise KeyError("The block failed") + + with pytest.raises(KeyError): + run_with_virtual_clock(block()) From b59a9ccb276c670a4705a90623eab119d549ddc7 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Sun, 22 Nov 2026 12:29:52 -0700 Subject: [PATCH 07/50] Decode a `StreamRef[T]` in a dataclass, a list and an optional A `StreamRef[T]` lost its type as a dataclass field and a list item, and came back as its proto message under `T | None`. Only `StreamRef` takes the two new decoding paths, since a change for any other type would alter the replay of existing Workflow Histories. --- temporalio/converter/_payload_converter.py | 95 +++++++++-- temporalio/nexus/system/__init__.py | 6 + tests/nexus/test_streams.py | 79 ++++++++++ tests/nexus/test_streams_with_worker.py | 83 ++++++++++ tests/test_converter.py | 173 ++++++++++++++++++++- 5 files changed, 420 insertions(+), 16 deletions(-) diff --git a/temporalio/converter/_payload_converter.py b/temporalio/converter/_payload_converter.py index ff7d477cc2..279d59ee72 100644 --- a/temporalio/converter/_payload_converter.py +++ b/temporalio/converter/_payload_converter.py @@ -584,6 +584,31 @@ def from_payload( raise RuntimeError("Failed parsing") from err +# Only these types decode by their type arguments and under `T | None`. Other types keep +# their decoding, because a change would alter the replay of existing Workflow Histories. +_typed_decode_types: set[type] = set() + + +def _is_typed_decode_type(hint: Any) -> bool: + """Return whether ``hint`` is a type of ``_typed_decode_types`` or an alias of one.""" + origin = typing.get_origin(hint) or hint + return any(origin is typed for typed in _typed_decode_types) + + +def _non_none_arg(hint: Any) -> Any: + """Return ``X`` for the hint ``X | None`` of a type of ``_typed_decode_types``, and + the hint itself for any other. + """ + origin = typing.get_origin(hint) + if origin is typing.Union or origin is UnionType: # type:ignore[reportDeprecated] + args = typing.get_args(hint) + if len(args) == 2 and type(None) in args: + arg = args[0] if args[1] is type(None) else args[1] + if _is_typed_decode_type(arg): + return arg + return hint + + class _TemporalTransferTypePayloadConverter(PayloadConverter, WithSerializationContext): """Payload converter wrapper for registered Temporal transfer type converters. @@ -591,7 +616,9 @@ class _TemporalTransferTypePayloadConverter(PayloadConverter, WithSerializationC transfer type value, then encoded by the wrapped payload converter. When decoding to a type with a registered transfer type converter, the wrapped converter first decodes the payload to the transfer type value and this wrapper - constructs the requested user-facing type from it. + constructs the requested user-facing type from it. For a type of + ``_typed_decode_types``, a hint of the type or ``None`` decodes the same way, and a + null payload gives ``None``. """ _inner_payload_converter: PayloadConverter @@ -627,21 +654,34 @@ def from_payloads( """See base class.""" if type_hints is None: return self._inner_payload_converter.from_payloads(payloads, None) + # A hint `T | None` of a type of `_typed_decode_types` takes the converter of `T`. + value_hints = [_non_none_arg(type_hint) for type_hint in type_hints] converters = [ - _get_transfer_type_converter(type_hint) for type_hint in type_hints - ] - inner_type_hints = [ - converter.transfer_type if converter is not None else type_hint - for converter, type_hint in zip(converters, type_hints) + _get_transfer_type_converter(value_hint) for value_hint in value_hints ] + inner_type_hints: list[Any] = [] + for converter, value_hint, type_hint in zip( + converters, value_hints, type_hints + ): + if converter is None: + inner_type_hints.append(type_hint) + elif value_hint is type_hint or converter.transfer_type is None: + inner_type_hints.append(converter.transfer_type) + else: + # A transfer type can be a value with no `|`, such as a string. + inner_type_hints.append( + typing.Optional[converter.transfer_type] # type:ignore[reportDeprecated] + ) values = self._inner_payload_converter.from_payloads( payloads, typing.cast("list[type]", inner_type_hints) ) return [ - converter.from_transfer_type(value, type_hint) - if converter is not None - else value - for value, converter, type_hint in zip(values, converters, type_hints) + value + if converter is None or (value is None and value_hint is not type_hint) + else converter.from_transfer_type(value, value_hint) + for value, converter, value_hint, type_hint in zip( + values, converters, value_hints, type_hints + ) ] def with_context(self, context: SerializationContext) -> Self: @@ -822,6 +862,19 @@ def _get_iso_datetime_parser() -> Callable[[str], datetime]: return datetime.fromisoformat +def _with_type_args(hint: Any, type_var_args: Mapping[Any, Any]) -> Any: + """Return a hint with each of its type variables replaced by its argument.""" + if not type_var_args: + return hint + if isinstance(hint, TypeVar): + return type_var_args.get(hint, hint) + # Only an alias takes arguments. A bare generic class keeps its own variables. + parameters = getattr(hint, "__parameters__", ()) + if parameters and typing.get_origin(hint) is not None: + return hint[tuple(type_var_args.get(param, param) for param in parameters)] + return hint + + def value_to_type( hint: type, value: Any, @@ -993,8 +1046,17 @@ def value_to_type( ret_dict = hint(**ret_dict) return ret_dict - # Dataclass - if dataclasses.is_dataclass(hint): + # Dataclass, also with type arguments such as ``Box[int]`` for a type of + # ``_typed_decode_types``. The class of such a hint is its origin, and its arguments + # stand for the type variables. + dataclass_type: Any = hint + type_var_args: dict[Any, Any] = {} + alias_origin = typing.get_origin(hint) + if _is_typed_decode_type(alias_origin) and dataclasses.is_dataclass(alias_origin): + dataclass_type = alias_origin + parameters = getattr(alias_origin, "__parameters__", ()) + type_var_args = dict(zip(parameters, type_args)) + if dataclasses.is_dataclass(dataclass_type): if not isinstance(value, dict): raise TypeError( f"Cannot convert to dataclass {hint}, value is {type(value)} not dict" @@ -1002,8 +1064,8 @@ def value_to_type( # Obtain dataclass fields and check that all dict fields are there and # that no required fields are missing. Unknown fields are silently # ignored. - fields = dataclasses.fields(hint) - field_hints = get_type_hints(hint) + fields = dataclasses.fields(dataclass_type) + field_hints = get_type_hints(dataclass_type) field_values = {} non_init_field_values = {} for field in fields: @@ -1016,7 +1078,9 @@ def value_to_type( # rejects this dataclass when trying union members try: converted = value_to_type( - field_hints[field.name], field_value, custom_converters + _with_type_args(field_hints[field.name], type_var_args), + field_value, + custom_converters, ) except Exception as err: raise TypeError( @@ -1029,6 +1093,7 @@ def value_to_type( # Simply instantiate the dataclass. This will fail as expected when # missing required fields. # TODO(cretz): Want way to convert snake case to camel case? + # Calling the hint lets an instance of ``Box[int]`` keep its type argument. obj = hint(**field_values) # init=False fields cannot be passed to __init__ but are serialized, so # restore them afterwards. object.__setattr__ also works on frozen diff --git a/temporalio/nexus/system/__init__.py b/temporalio/nexus/system/__init__.py index da102bd304..e2e2086a56 100644 --- a/temporalio/nexus/system/__init__.py +++ b/temporalio/nexus/system/__init__.py @@ -20,6 +20,7 @@ from temporalio.converter import BinaryProtoPayloadConverter, CompositePayloadConverter from temporalio.converter._payload_converter import ( _TemporalTransferTypePayloadConverter, + _typed_decode_types, ) TEMPORAL_SYSTEM_ENDPOINT = "__temporal_system" @@ -198,3 +199,8 @@ def _get_serialization_context( # pyright: ignore[reportUnusedFunction] # `temporalio.workflow` and the generated Workflow modules of a system service import each # other. It's loaded here last, so that any of those modules can be the first import. import temporalio.workflow # noqa: E402 # pyright: ignore[reportUnusedImport] +from temporalio.nexus.system.stream_service.models import StreamRef # noqa: E402 + +# Workflow code can decode a `StreamRef` only on an SDK with this rule, so the rule can't +# change a replay. Any import of the generated class runs this module first. +_typed_decode_types.add(StreamRef) diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index ae9712a556..6eba020b70 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -23,6 +23,7 @@ import temporalio.client import temporalio.converter import temporalio.nexus.system +import temporalio.workflow from temporalio.activity import WorkflowTaskAttempt from temporalio.api.enums.v1 import StreamErrorReason, StreamIdConflictPolicy from temporalio.api.failure.v1 import Failure @@ -559,6 +560,84 @@ def test_a_stored_producer_comes_back_as_a_producer() -> None: assert as_producer(producer) is producer +@dataclasses.dataclass +class _Turn: + text: str + + +def _refs(value: Any) -> list[Any]: + """Return each ``StreamRef`` of a value, in the order of its lists and fields.""" + if isinstance(value, StreamRef): + return [value] + if isinstance(value, list): + return [ref for item in value for ref in _refs(item)] + if dataclasses.is_dataclass(value): + fields = dataclasses.fields(value) + return _refs([getattr(value, field.name) for field in fields]) + return [] + + +def test_a_stream_ref_keeps_its_type_inside_a_value() -> None: + converter = temporalio.converter.DataConverter.default.payload_converter + config = StreamConfig([FaultStore()]) + client = Client(Mock(spec=ServiceClient), stream_config=config) + # mypy takes a type argument from a variable only on a value of type Any. + ref_type: Any = StreamRef + list_type: Any = list + for seed in range(60): + rng = random.Random(seed) + + def ref(typed: Any) -> Any: + store = rng.choice([None, "a", "b"]) + return typed(id=f"stream-{rng.randrange(1000)}", store=store) + + def shape( + kind: str, depth: int + ) -> tuple[Any, Callable[[], tuple[Any, list[Any]]]]: + """Return a hint with a ref in it, and a function that makes a value of + the hint with the body type of each of its refs, in their order. + """ + if kind == "argument" or depth == 0: + body = rng.choice([_Turn, str, int]) + return ref_type[body], lambda: (ref(ref_type[body]), [body]) + if kind == "untyped field": + # A ref with no type argument reads bodies of any type. + untyped = dataclasses.make_dataclass("Untyped", [("ref", StreamRef)]) + return untyped, lambda: (untyped(ref(StreamRef)), [object]) + kinds = ["argument", "untyped field", "field", "list", "optional"] + hint, make = shape(rng.choice(kinds), depth - 1) + if kind == "optional": + return hint | None, lambda: make() if rng.random() < 0.7 else (None, []) + if kind == "list": + + def make_list() -> tuple[Any, list[Any]]: + made = [make() for _ in range(rng.randrange(3))] + bodies = [body for _, bodies in made for body in bodies] + return [value for value, _ in made], bodies + + return list_type[hint], make_list + holder = dataclasses.make_dataclass("Holder", [("ref", hint)]) + + def make_field() -> tuple[Any, list[Any]]: + value, bodies = make() + return holder(value), bodies + + return holder, make_field + + # With a depth of 1, these are an argument or a result, a field with no type + # argument, a field, a list, and an argument or a result that can be None. + for top in ("argument", "untyped field", "field", "list", "optional"): + with failure_note(f"seed {seed}, {top}"): + hint, make = shape(top, rng.randrange(1, 4)) + value, bodies = make() + payloads = converter.to_payloads([value]) + [decoded] = converter.from_payloads(payloads, [hint]) + assert decoded == value + refs = _refs(decoded) + for get_stream in (client.get_stream, temporalio.workflow.get_stream): + assert [get_stream(ref).body_type for ref in refs] == bodies + + def test_each_stream_module_can_be_the_first_import() -> None: system = temporalio.nexus.system modules = [ diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py index 49c1be9aa8..3ff4435528 100644 --- a/tests/nexus/test_streams_with_worker.py +++ b/tests/nexus/test_streams_with_worker.py @@ -1066,3 +1066,86 @@ async def test_a_workflow_read_asks_the_store_with_its_limits(client: Client) -> asked = [(r.max_records, r.max_bytes, r.wait.ToSeconds()) for r in reads] # With one Record in a page, the read of each Record is one Store call. assert asked == [expected] * (3 if limits else 1) + + +@dataclasses.dataclass +class _Turn: + text: str + + +@dataclasses.dataclass +class _AgentInput: + turns: StreamRef[_Turn] | None = None + + +@dataclasses.dataclass +class _TurnsInput: + turns: StreamRef[_Turn] + texts: list[str] + + +@activity.defn +async def _append_turns(input: _TurnsInput) -> None: + stream = activity.client().get_stream(input.turns) + await stream.append(*(_Turn(text) for text in input.texts)) + + +@workflow.defn +class _AgentWorkflow: + def __init__(self) -> None: + self._turns: StreamRef[_Turn] | None = None + self._go_on = False + + @workflow.query + def turns(self) -> StreamRef[_Turn] | None: + return self._turns + + @workflow.signal + def go_on(self) -> None: + self._go_on = True + + @workflow.run + async def run(self, input: _AgentInput) -> list[str]: + self._turns = input.turns + await workflow.wait_condition(lambda: self._go_on) + if self._turns is None: + created = await workflow.create_stream(id="turns", body_type=_Turn) + self._turns = created.ref + await workflow.execute_activity( + _append_turns, + _TurnsInput(self._turns, ["a", "b"]), + start_to_close_timeout=timedelta(seconds=10), + ) + page = await workflow.get_stream(self._turns).read_page() + # Only a body that the read converted to its type has the attribute. + return [record.body.text for record in page.records] + + +async def test_a_stream_ref_keeps_its_type_through_a_workflow(client: Client) -> None: + streams = stream_client(client, MemoryStreamStore()) + ref: Any = None + # The first run gets no ref and creates the Stream. The second one gets that ref. + for texts in (["a", "b"], ["a", "b", "a", "b"]): + with failure_note(f"texts {texts}"): + + async def answer(handle: Any, _worker: Any) -> None: + nonlocal ref + assert await handle.query(_AgentWorkflow.turns) == ref + await handle.signal(_AgentWorkflow.go_on) + await handle.result() + ref = await handle.query(_AgentWorkflow.turns) + + options = RunOptions( + _AgentWorkflow, + [_AgentInput(ref)], + activities=[_append_turns], + during=answer, + replay=True, + ) + assert (await run(streams, options)).result == texts + assert ref == StreamRef(id="turns", store="memory") + # The ref of the query has the body type, so the read needs no `body_type=`. + page = await streams.get_stream(ref).read_page() + assert [record.body for record in page.records] == [ + _Turn(text) for text in texts + ] diff --git a/tests/test_converter.py b/tests/test_converter.py index b47cadbdd0..1e34c7de1d 100644 --- a/tests/test_converter.py +++ b/tests/test_converter.py @@ -4,11 +4,12 @@ import inspect import ipaddress import logging +import random import sys import traceback import typing from collections import deque -from collections.abc import Iterable, Mapping, MutableMapping, Sequence +from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence from dataclasses import dataclass from datetime import datetime, timedelta, timezone from enum import Enum, IntEnum, StrEnum @@ -59,6 +60,7 @@ ) from temporalio.converter._payload_converter import ( _TemporalTransferTypePayloadConverter, + _typed_decode_types, ) from temporalio.exceptions import ( ApplicationError, @@ -388,6 +390,28 @@ def from_transfer_type( ) +class TemporalTransferTypeJSONValueConverter( + TransferTypeConverter["TemporalTransferTypeJSONValue", dict[str, str]] +): + transfer_type = dict[str, str] + + def to_transfer_type(self, value: TemporalTransferTypeJSONValue) -> dict[str, str]: + return {"id": value.value} + + def from_transfer_type( + self, + value: dict[str, str], + type_hint: type[TemporalTransferTypeJSONValue], + ) -> TemporalTransferTypeJSONValue: + return TemporalTransferTypeJSONValue(value=value["id"]) + + +@transfer_type_convertible(TemporalTransferTypeJSONValueConverter) +@dataclass +class TemporalTransferTypeJSONValue: + value: str + + class CustomDefaultPayloadConverter(DefaultPayloadConverter): pass @@ -455,6 +479,54 @@ def test_temporal_transfer_type_payload_converter_with_generic_value( assert converter.from_payload(payload, type_hint) == value +def _decode_typed(monkeypatch: pytest.MonkeyPatch, *types: type) -> None: + """Let ``types`` decode by their type arguments and under ``T | None`` in one test.""" + monkeypatch.setattr( + "temporalio.converter._payload_converter._typed_decode_types", + _typed_decode_types | set(types), + ) + + +@pytest.mark.parametrize( + ("value", "type_hint"), + [ + (TemporalTransferTypeValue("workflow-id"), TemporalTransferTypeValue | None), + (None, TemporalTransferTypeValue | None), + ( + TemporalTransferTypeValueWithoutHint("workflow-id"), + TemporalTransferTypeValueWithoutHint | None, + ), + ( + TemporalTransferTypeGenericValue(123), + TemporalTransferTypeGenericValue[int] | None, + ), + (None, TemporalTransferTypeGenericValue[int] | None), + (TemporalTransferTypeValue("workflow-id"), None | TemporalTransferTypeValue), + (TemporalTransferTypeJSONValue("id"), TemporalTransferTypeJSONValue | None), + (None, TemporalTransferTypeJSONValue | None), + ], +) +def test_temporal_transfer_type_payload_converter_with_optional_hint( + value: Any, type_hint: Any, monkeypatch: pytest.MonkeyPatch +): + _decode_typed( + monkeypatch, + TemporalTransferTypeValue, + TemporalTransferTypeValueWithoutHint, + TemporalTransferTypeGenericValue, + TemporalTransferTypeJSONValue, + ) + converter = DataConverter.default.payload_converter + + payloads = [converter.to_payload(value)] + if value is None: + # A converter of another SDK can write None as a JSON null. + payloads.append(Payload(metadata={"encoding": b"json/plain"}, data=b"null")) + + for payload in payloads: + assert converter.from_payload(payload, type_hint) == value + + def test_transfer_type_convertible_rejects_existing_converter(): with pytest.raises(TypeError, match="already has a transfer type converter"): transfer_type_convertible(TemporalTransferTypeValueConverter)( @@ -564,6 +636,14 @@ class InitFalseIntDataClass: bar: int = dataclasses.field(default=0, init=False) +@dataclass +class GenericDataClass(Generic[T]): + value: T + items: list[T] = dataclasses.field(default_factory=list) + nested: GenericDataClass[T] | None = None + maybe: T | None = None + + class MyTypedDict(TypedDict): foo: str bar: MyDataClass @@ -605,6 +685,97 @@ def test_json_nested_frozenset_round_trip(): assert converter.from_payload(payload, set[frozenset[int]]) == value +K = TypeVar("K") + + +@dataclass +class GenericPairDataClass(Generic[K, T]): + key: K + value: T + + +def test_json_generic_dataclass_round_trip(monkeypatch: pytest.MonkeyPatch): + converter = JSONPlainPayloadConverter() + # mypy takes a type argument from a variable only on a value of type Any + generic_type: Any = GenericDataClass + pair_type: Any = GenericPairDataClass + + # A generic dataclass that isn't registered keeps its decoding, which the replay of + # an existing History needs. + payload = converter.to_payload(GenericDataClass(1)) + assert payload + with pytest.raises(TypeError): + converter.from_payload(payload, generic_type[int]) + generic_or_dict: Any = generic_type[int] | dict + assert converter.from_payload(payload, generic_or_dict) == { + "value": 1, + "items": [], + "nested": None, + "maybe": None, + } + + _decode_typed(monkeypatch, GenericDataClass, GenericPairDataClass) + + # Each type argument, with a function that makes a value of it + arguments: list[tuple[Any, Callable[[random.Random], Any]]] = [ + (int, lambda rng: rng.randrange(100)), + (str, lambda rng: f"text {rng.randrange(100)}"), + (list[int], lambda rng: [rng.randrange(100) for _ in range(rng.randrange(3))]), + ( + MyDataClass, + lambda rng: MyDataClass("foo", rng.randrange(100), SerializableEnum.FOO), + ), + ( + GenericDataClass[str], + lambda rng: GenericDataClass(f"text {rng.randrange(100)}"), + ), + ] + + def generic( + rng: random.Random, make: Callable[[random.Random], Any], depth: int + ) -> GenericDataClass[Any]: + return GenericDataClass( + value=make(rng), + items=[make(rng) for _ in range(rng.randrange(3))], + nested=generic(rng, make, depth - 1) + if depth and rng.random() < 0.7 + else None, + maybe=make(rng) if rng.random() < 0.5 else None, + ) + + for seed in range(200): + rng = random.Random(seed) + argument, make = rng.choice(arguments) + value = generic(rng, make, 2) + payload = converter.to_payload(value) + assert payload + decoded = converter.from_payload(payload, generic_type[argument]) + assert decoded == value, f"seed {seed}" + assert decoded.__orig_class__ == generic_type[argument], f"seed {seed}" + + # A value of another type argument fails or converts as it does for a field + # of that type in a plain dataclass. + other, _ = rng.choice(arguments) + plain = dataclasses.make_dataclass("Plain", [("value", other)]) + payload = converter.to_payload({"value": make(rng)}) + assert payload + outcomes: list[Any] = [] + for hint in (generic_type[other], plain): + try: + outcomes.append(converter.from_payload(payload, hint).value) + except Exception as err: + outcomes.append(type(err)) + assert outcomes[0] == outcomes[1], f"seed {seed}" + + # Each of two type arguments goes to its own parameter. + second, make_second = rng.choice(arguments) + pair = GenericPairDataClass(key=make(rng), value=make_second(rng)) + payload = converter.to_payload(pair) + assert payload + decoded = converter.from_payload(payload, pair_type[argument, second]) + assert decoded == pair, f"seed {seed}" + + def test_json_type_hints(): converter = JSONPlainPayloadConverter() From 0f50b4f1f7059a388f3ca33ccadf2664c284f242 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Sun, 22 Nov 2026 01:18:18 -0700 Subject: [PATCH 08/50] Turn workflow task chunking off for new Workflows A Stream read that waits past the heartbeat of its Workflow Task completes that task with no command, and with chunking a replay takes that task and the next one as one. Workflow code then gets two results in one activation that the first run gave in two, and can run in another order, as it can with Local Activities alone. Core records the choice in the first completed Workflow Task of a Workflow, so a Workflow that started before keeps chunking. --- .../changed/unhurried-replay-tortoise.md | 1 + temporalio/bridge/Cargo.toml | 2 + temporalio/worker/_workflow_streams.py | 4 +- tests/nexus/test_streams_with_worker.py | 78 ++++++++++++++++++- tests/worker/test_workflow_streams.py | 2 +- 5 files changed, 82 insertions(+), 5 deletions(-) create mode 100644 changelog/changed/unhurried-replay-tortoise.md diff --git a/changelog/changed/unhurried-replay-tortoise.md b/changelog/changed/unhurried-replay-tortoise.md new file mode 100644 index 0000000000..ae9c794997 --- /dev/null +++ b/changelog/changed/unhurried-replay-tortoise.md @@ -0,0 +1 @@ +A Workflow that starts on this version replays each Workflow Task separately, which keeps the grouping and the timestamps of the activations of its first run. A Workflow that started on an earlier version replays as before. diff --git a/temporalio/bridge/Cargo.toml b/temporalio/bridge/Cargo.toml index 10ffc2208c..19cb233335 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", + # With chunking, a replay can run Workflow code in another order than the first run. + "disable_workflow_task_chunking", ] } temporalio-streams = { version = "0.1.0", path = "./sdk-core/crates/streams" } tokio = "1.26" diff --git a/temporalio/worker/_workflow_streams.py b/temporalio/worker/_workflow_streams.py index 0edfd47471..e6461e815c 100644 --- a/temporalio/worker/_workflow_streams.py +++ b/temporalio/worker/_workflow_streams.py @@ -188,8 +188,8 @@ def resolve_read( read = self._reads.pop(job.seq, None) if read is None: raise RuntimeError(f"Failed finding Stream read for sequence {job.seq}") - # The job of a cancelled call is dropped. A cancel job is dropped too if it comes first, - # as in a replay, since only the cancel of the call may end its wait. + # The job of a cancelled call is dropped. So is a cancel job that comes first, as in a + # replay with legacy chunking, since only the cancel of the call may end its wait. if read.waiter.done() or job.HasField("cancelled"): return if job.HasField("failed"): diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py index 3ff4435528..61d137cbe6 100644 --- a/tests/nexus/test_streams_with_worker.py +++ b/tests/nexus/test_streams_with_worker.py @@ -856,7 +856,7 @@ async def run(self, how: str) -> list[list[str]]: t = workflow.get_stream(StreamRef[str](id=f"t of {how}")) if how == "a cancel": # The page of `t` makes the Workflow cancel its read of `s`, whose reader then - # reads `u`. A replay gives the cancel job of `s` with that page, before the cancel. + # reads `u`. A replay gives the cancel job of `s` after that cancel, as the first run. u = workflow.get_stream(StreamRef[str](id=f"u of {how}")) async def read_s() -> None: @@ -912,7 +912,7 @@ async def second_task() -> None: assert len(_events(history, started)) > 1 # The first task ends at its heartbeat with no page. The pages then come in several - # activations of the next task, which a replay with chunking on gives in one. + # activations of the next task, and a replay gives each page in its activation. await assert_eventually(second_task) for stream, body in writes: await stream.append(body) @@ -935,6 +935,80 @@ async def second_task() -> None: assert events[completed + 1] == EventType.EVENT_TYPE_WORKFLOW_TASK_SCHEDULED +@workflow.defn +class _TwoReadsWorkflow: + @workflow.run + async def run(self, first: str, second: str) -> list[list[str]]: + wait = timedelta(seconds=30) + streams = [workflow.get_stream(StreamRef[str](id=id)) for id in (first, second)] + pages = await asyncio.gather( + *(stream.read_page(wait=wait) for stream in streams) + ) + return [[record.body for record in page.records] for page in pages] + + +async def test_a_replay_gives_each_result_in_the_activation_of_the_first_run( + client: Client, +) -> None: + # A local import, so that the sandbox of each Workflow here doesn't import that module. + from tests.worker.test_workflow import CustomWorkflowRunner + + store, holds = FaultStore(), [Hold(), Hold()] + store.faults["read_records"].extend(holds) + client = stream_client(client, store) + for stream_id in ("first", "second"): + stream = await client.create_stream(id=stream_id, body_type=str) + await stream.append(stream_id) + live, replayed = CustomWorkflowRunner(), CustomWorkflowRunner() + + def read_results(runner: CustomWorkflowRunner) -> list[list[int]]: + """Return the seqs of the read results of each activation that has one.""" + activations = [ + [ + job.resolve_stream_read.seq + for job in activation.jobs + if job.HasField("resolve_stream_read") + ] + for activation, _ in runner._pairs + ] + return [seqs for seqs in activations if seqs] + + async def release(handle: Any, _worker: Any) -> None: + async def forced_task() -> None: + history = await handle.fetch_history() + started = EventType.EVENT_TYPE_WORKFLOW_TASK_STARTED + assert len(_events(history, started)) > 1 + + # Both reads wait past the heartbeat of the first task, which completes with no + # command. Legacy chunking takes that task and the next one as one in a replay. + await assert_eventually(forced_task) + for count, hold in enumerate(holds, 1): + hold.release() + + async def given() -> None: + assert len(read_results(live)) == count + + # This page gets its activation before the Store answers the other read. + await assert_eventually(given) + + options = RunOptions( + _TwoReadsWorkflow, + ["first", "second"], + task_timeout=timedelta(seconds=2), + worker={"workflow_runner": live}, + during=release, + ) + ran = await run(client, options) + assert ran.result == [["first"], ["second"]] + await Replayer( + workflows=[_TwoReadsWorkflow], + workflow_runner=replayed, + stream_config=client._config["stream_config"], + ).replay_workflow(ran.history) + assert len(read_results(live)) == 2 + assert read_results(replayed) == read_results(live) + + @workflow.defn class _ReadOnceWorkflow: def __init__(self) -> None: diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py index 17f554e6a6..9117662788 100644 --- a/tests/worker/test_workflow_streams.py +++ b/tests/worker/test_workflow_streams.py @@ -799,7 +799,7 @@ def cancel(seq: int) -> WorkflowCommand: for step in range(rng.randrange(2, 7)): # Each read gets one job, also a cancelled one, whose job has a cancel or the result - # that came before it. A replay can give a cancel job before the cancel. + # that came before it. A replay with legacy chunking gives a cancel job before the cancel. jobs: list[ResolveStreamRead] = [] for seq, read in reads.items(): if rng.random() >= 0.6: From cd7b431299cf6155c12e893d83efba0e779c30b6 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Mon, 23 Nov 2026 13:09:28 -0700 Subject: [PATCH 09/50] Drop the Workflow `producer` argument from the Stream docs The generated Workflow `append` and `close` take no `producer`. The `StreamConfig` docs say which Producer a Workflow write has, in place of a note on an argument that is gone. --- temporalio/client/_stream_store.py | 4 ++-- tests/nexus/test_streams.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 18dadc94ef..5e93660db0 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -279,8 +279,8 @@ class StreamConfig: - A create and a describe run in a Local Activity of the SDK. The Workflow and Activity interceptors of the Worker see it, as they see every Local Activity. - - The ``producer`` argument of ``append`` and ``close`` has no effect. The - Worker writes as the Producer of the Workflow run. + - An append and a close write as the Producer of the Workflow run, and the + Worker sets its Workflow Task attempt. - An append is at-least-once. If a Workflow Task fails after its append, the next attempt of the task writes the batch again. - An outage of the Store gives Workflow code no error. The Workflow Task diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index 6eba020b70..5ce5e55327 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -472,7 +472,7 @@ def text() -> str: def _default_producer(writer: _WriterInfo) -> Any: - """Return the Producer that a write of ``writer`` sends with no ``producer=``.""" + """Return the default Producer of a write of ``writer``.""" if writer.kind == "workflow": info = SimpleNamespace( namespace=writer.namespace, From f8aa8937c7c5442b6d92dbf1d0d4c2af11594e34 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Mon, 23 Nov 2026 15:38:24 -0700 Subject: [PATCH 10/50] Add the namespace to the Stream selector context Plain client code has no target, so its selector couldn't pick a Store by namespace. Each path passes the namespace of its client or Worker, as external storage does for `StorageDriverSelectContext`. --- temporalio/client/_stream_store.py | 13 +++++++++++-- temporalio/worker/_workflow_streams.py | 6 ++++-- tests/nexus/test_streams.py | 6 +++++- tests/nexus/test_streams_with_worker.py | 9 +++++---- tests/worker/test_workflow_streams.py | 2 +- 5 files changed, 26 insertions(+), 10 deletions(-) diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 5e93660db0..2fb54fdff6 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -261,6 +261,12 @@ class StreamSelectContext: """The Workflow or the Activity that makes the call, or ``None`` for other client code.""" + namespace: str | None = None + """The namespace of the client or Worker that makes the call. + + It is set even when :py:attr:`target` is ``None``, so that a selector can pick a + Store by namespace for plain client code too.""" + @dataclass(frozen=True) class StreamConfig: @@ -388,6 +394,7 @@ def _store_for( self, ref: StreamRef[Any], target: StorageDriverActivityInfo | StorageDriverWorkflowInfo | None, + namespace: str, ) -> StreamStore: """Return the Store of a call on ``ref``, raising :class:`ValueError` if there is none. @@ -396,7 +403,9 @@ def _store_for( return self._store(ref.store) if self.store_selector is None: return self.stores[0] - selected = self.store_selector(StreamSelectContext(id=ref.id, target=target)) + selected = self.store_selector( + StreamSelectContext(id=ref.id, target=target, namespace=namespace) + ) if not any(selected is store for store in self.stores): raise ValueError( "Store returned by store_selector is not registered in StreamConfig.stores" @@ -522,7 +531,7 @@ async def _call_stream_store( # pyright: ignore[reportUnusedFunction] "Client has no stream_config, which every Stream call requires." ) request = input.arg - store = stream_config._store_for(request.ref, _activity_target()) + store = stream_config._store_for(request.ref, _activity_target(), client.namespace) if isinstance(request, models.CreateStreamRequest): # The created Stream takes the ref of its request. request.ref.store = store.name() diff --git a/temporalio/worker/_workflow_streams.py b/temporalio/worker/_workflow_streams.py index e6461e815c..ee0a023ef3 100644 --- a/temporalio/worker/_workflow_streams.py +++ b/temporalio/worker/_workflow_streams.py @@ -332,7 +332,7 @@ def _stream(self, ref: StreamRef[Any]) -> temporalio.api.stream.v1.StreamRef: namespace=info.namespace, ) try: - store = config._store_for(ref, target).name() + store = config._store_for(ref, target, info.namespace).name() except Exception as err: raise self._fail_task(err) return temporalio.api.stream.v1.StreamRef(id=ref.id, store=store) @@ -403,7 +403,9 @@ async def _stream_store_call( # pyright: ignore[reportUnusedFunction] namespace=info.namespace, ) picked = stream_config._store_for( - StreamRef(id=stream_request.stream_id, store=store or None), target + StreamRef(id=stream_request.stream_id, store=store or None), + target, + client.namespace, ) response = await _call_store( picked, diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index 5ce5e55327..ecc3451295 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -286,7 +286,11 @@ async def run_call() -> Any: ) used_selector = has_selector and ref_store is None assert selects == ( - [StreamSelectContext(id=stream_id, target=target)] + [ + StreamSelectContext( + id=stream_id, target=target, namespace=client.namespace + ) + ] if used_selector else [] ) diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py index 61d137cbe6..16c10abdfe 100644 --- a/tests/nexus/test_streams_with_worker.py +++ b/tests/nexus/test_streams_with_worker.py @@ -523,10 +523,10 @@ async def test_a_worker_uses_the_stream_config_of_its_new_client( # 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 - targets: list[Any] = [] + selects: list[tuple[str, str | None]] = [] def pick_first(context: Any) -> FaultStore: - targets.append(context.target) + selects.append((type(context.target).__name__, context.namespace)) return first before = stream_client(client, first, second, store_selector=pick_first) @@ -579,8 +579,9 @@ async def created() -> None: ("AppendRecordsRequest", "shared"), ] assert not second.requests - # The selector of the Workflow's create got the Workflow as its target. - assert [type(t).__name__ for t in targets] == ["StorageDriverWorkflowInfo"] + # The selector of the Workflow's create got the Workflow as its target, and the + # namespace of the Worker. + assert selects == [("StorageDriverWorkflowInfo", client.namespace)] async def test_an_append_over_a_limit_of_the_config_never_reaches_the_store( diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py index 9117662788..dab4a2d5e1 100644 --- a/tests/worker/test_workflow_streams.py +++ b/tests/worker/test_workflow_streams.py @@ -593,7 +593,7 @@ def selector(context: StreamSelectContext) -> StreamStore: else: store = stores[int(call.stream[1:]) % 2].name() expected_selects.append( - StreamSelectContext(id=call.stream, target=target) + StreamSelectContext(id=call.stream, target=target, namespace="ns") ) kind = call.operation if call.operation in seqs else "activity" seqs[kind] += 1 From 183edbefdfbd523fb6850d20c1007204939d6967 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Mon, 23 Nov 2026 23:37:04 -0700 Subject: [PATCH 11/50] Pin Core with refs in the Stream requests Core's Stream crate takes a ref in each request and the request id of a create or an append next to it, keeps the Stream calls of a Workflow Task on the task's completion, and gives an Activity task the id of its scheduled event. The bridge builds on it with the next commit. --- temporalio/bridge/sdk-core | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index 4be3975489..e493487937 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit 4be3975489e9f258215b550795741c712c0c7f9f +Subproject commit e4934879378ea848d0031d9098e07b5164ab526a From 91855c907ec09892bec92b86ff64db68555da52f Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Mon, 23 Nov 2026 23:37:54 -0700 Subject: [PATCH 12/50] Pass the request id of a create and an append to a Store The Stream API has a ref in each request and keeps the request id of a call out of it. A Store gets the request id as an argument, which client code makes for each call and Core makes for each append of Workflow code. The bridge turns a call that can't reach Python into an error, since Core doesn't catch a panic of a Store. --- changelog/added/steady-stream-heron.md | 2 +- temporalio/bridge/src/streams.rs | 80 +++++++++++----- temporalio/bridge/streams.py | 10 +- temporalio/client/_stream_store.py | 121 ++++++++++++++++++------ temporalio/testing/_stream_store.py | 70 ++++++++------ temporalio/worker/_workflow_streams.py | 60 ++++++------ tests/helpers/streams.py | 29 ++++-- tests/nexus/test_streams.py | 41 ++++---- tests/nexus/test_streams_with_worker.py | 88 +++++++++++------ tests/testing/test_stream_store.py | 110 +++++++++++---------- tests/worker/test_workflow_streams.py | 29 +++--- 11 files changed, 407 insertions(+), 233 deletions(-) diff --git a/changelog/added/steady-stream-heron.md b/changelog/added/steady-stream-heron.md index cb91605935..1c4a5769ab 100644 --- a/changelog/added/steady-stream-heron.md +++ b/changelog/added/steady-stream-heron.md @@ -1,4 +1,4 @@ -Add experimental `temporalio.client.StreamStore`, the base class of a Stream Store, and `temporalio.testing.MemoryStreamStore`, a Store that keeps its Streams in memory for tests and local runs. +Add experimental `temporalio.client.StreamStore`, the base class of a Stream Store, and `temporalio.testing.MemoryStreamStore`, a Store that keeps its Streams in memory for tests and local runs. A Store gets the request id of each create and each append as `request_id`, and a create returns the ref of its request. Add experimental Streams for client and Activity code. `stream_config=StreamConfig(stores=[...])` of `Client.connect` gives a client its Stream Stores, and `Client.create_stream` and `Client.get_stream` return a `Stream` to append to, read, describe and close. A failed call raises `temporalio.exceptions.StreamError` with a `reason`. `max_record_bytes`, `max_batch_bytes` and `max_batch_records` of `StreamConfig` bound an append, and one over a limit fails before its Store gets it. A read of a Stream from `get_stream` needs `body_type=` or a `StreamRef` with a type argument, and raises `TypeError` with neither. `temporalio.contrib.streams.current_producer` gives the Producer of an Activity attempt, and `as_producer` gives back one that code stored. Add experimental Streams for Workflow code. `workflow.create_stream` and `workflow.get_stream` return a `Stream` to append to, describe and close on the Stream Stores of the Worker's client, and `Replayer(stream_config=...)` gives a replay its Stores. Add experimental Stream reads for Workflow code. `Stream.read`, `read_pages` and `read_page` of a Workflow `Stream` give the Records as they come, a replay reads them again from the Store, and `temporalio.workflow.StreamReplayError` in the failure exception types of a Worker or a Workflow fails the Workflow when the Store no longer has them. The Worker option `stream_read_max_wait` bounds the wait of one Store call of a read. diff --git a/temporalio/bridge/src/streams.rs b/temporalio/bridge/src/streams.rs index 59466ce3b5..2cd4631da9 100644 --- a/temporalio/bridge/src/streams.rs +++ b/temporalio/bridge/src/streams.rs @@ -15,8 +15,8 @@ use temporalio_streams::proto::{ }; use temporalio_streams::record::StoreLimits; use temporalio_streams::{ - AppendError, CloseError, CreateError, DescribeError, ReadError, Reason, StreamError, - StreamRuntime, StreamStore, WireReason, + AppendError, CloseError, CreateError, DescribeError, ReadError, StreamError, StreamRuntime, + StreamStore, WireReason, }; use crate::runtime; @@ -90,11 +90,14 @@ impl Drop for CallGuard<'_> { } impl PythonStore { + /// Calls the Store. `request_id` is that of a create or an append, and `None` for the other + /// operations. Core doesn't catch a panic of a Store, so every failure here is an error. async fn call( &self, operation: &'static str, request: Request, - ) -> Result>> + request_id: Option, + ) -> Result> where Request: Message, Response: Message + Default, @@ -110,20 +113,21 @@ impl PythonStore { state: state.clone(), task_locals, }; - let called = Python::attach(|py| { + let called = Python::try_attach(|py| { let on_task = OnTask { state: state.clone(), }; let request = PyBytes::new(py, &request.encode_to_vec()); - let coroutine = - (self.caller.bind(py)).call_method1("call", (operation, request, on_task))?; + 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 { - Ok(answer) => answer.await, - Err(err) => Err(err), + Some(Ok(answer)) => answer.await, + Some(Err(err)) => Err(err), + None => return Err(interpreter_gone(operation)), }; - Python::attach(|py| { + 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()) @@ -136,13 +140,21 @@ impl PythonStore { }), Err(err) => Err(store_error(py, err)), } - }) + }); + done.unwrap_or_else(|| Err(interpreter_gone(operation))) } } +/// Returns the error of a call that can't reach Python, since the interpreter is shutting down. +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" + )) +} + /// Returns the error of an operation for the exception of a Store. A `StreamError` is a refusal /// with its reason, and any other exception is an outage, which the caller can try again. -fn store_error(py: Python<'_>, err: PyErr) -> StreamError> { +fn store_error(py: Python<'_>, err: PyErr) -> StreamError { let refusal = || -> PyResult> { let value = err.value(py); if !value.is_instance(stream_error_type(py)?)? { @@ -166,50 +178,55 @@ impl StreamStore for PythonStore { fn create_stream( &self, request: CreateStreamRequest, + request_id: String, ) -> BoxFuture<'_, Result> { - Box::pin(self.call("CreateStream", request)) + 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)) + Box::pin(self.call("AppendRecords", request, Some(request_id))) } fn read_records( &self, request: ReadRecordsRequest, ) -> BoxFuture<'_, Result> { - Box::pin(self.call("ReadRecords", request)) + Box::pin(self.call("ReadRecords", request, None)) } fn close_stream( &self, request: CloseStreamRequest, ) -> BoxFuture<'_, Result> { - Box::pin(self.call("CloseStream", request)) + Box::pin(self.call("CloseStream", request, None)) } fn describe_stream( &self, request: DescribeStreamRequest, ) -> BoxFuture<'_, Result> { - Box::pin(self.call("DescribeStream", request)) + Box::pin(self.call("DescribeStream", request, None)) } } /// Calls the Python Store of `caller` for one Stream operation through a `StreamRuntime`, which -/// checks the request and the response. The awaitable raises `StreamError` for a failed call. The +/// checks the request and the response. A create and an append need their `request_id`, which +/// the other operations don't take. The awaitable raises `StreamError` for a failed call. The /// runtime has no limit of a batch, since the SDK that calls the Store has those in its Stream /// config. #[pyfunction] +#[pyo3(signature = (runtime_ref, caller, operation, request, request_id=None))] pub fn call_stream_store<'p>( py: Python<'p>, runtime_ref: &runtime::RuntimeRef, caller: Py, operation: &str, request: &Bound<'_, PyBytes>, + request_id: Option, ) -> PyResult> { let task_locals = pyo3_async_runtimes::TaskLocals::with_running_loop(py)?.copy_context(py)?; let store = PythonStore { @@ -217,12 +234,17 @@ pub fn call_stream_store<'p>( event_loop_task_locals: Arc::new(OnceLock::from(task_locals)), }; let stream_runtime = StreamRuntime::new(Arc::new(store), StoreLimits::UNBOUNDED); + let with_request_id = || { + request_id + .clone() + .ok_or_else(|| PyValueError::new_err(format!("A {operation} call needs a request id"))) + }; macro_rules! run { - ($method:ident) => {{ - let request = Message::decode(request.as_bytes()) + (|$request:ident| $call:expr) => {{ + let $request = Message::decode(request.as_bytes()) .map_err(|err| PyValueError::new_err(format!("Invalid proto: {err}")))?; runtime_ref.runtime.future_into_py(py, async move { - let response = stream_runtime.$method(request).await; + let response = $call.await; response .map(|response| response.encode_to_vec()) .map_err(|err| stream_error(err.reason.into(), err.message)) @@ -230,11 +252,17 @@ pub fn call_stream_store<'p>( }}; } match operation { - "CreateStream" => run!(create_stream), - "AppendRecords" => run!(append_records), - "ReadRecords" => run!(read_records), - "CloseStream" => run!(close_stream), - "DescribeStream" => run!(describe_stream), + "CreateStream" => { + let request_id = with_request_id()?; + run!(|decoded| stream_runtime.create_stream(decoded, request_id)) + } + "AppendRecords" => { + let request_id = with_request_id()?; + run!(|decoded| stream_runtime.append_records(decoded, request_id)) + } + "ReadRecords" => run!(|decoded| stream_runtime.read_records(decoded)), + "CloseStream" => run!(|decoded| stream_runtime.close_stream(decoded)), + "DescribeStream" => run!(|decoded| stream_runtime.describe_stream(decoded)), _ => Err(PyValueError::new_err(format!( "Unknown Stream operation: {operation}" ))), @@ -297,7 +325,7 @@ pub fn check_stream_append( let request = Message::decode(request.as_bytes()) .map_err(|err| PyValueError::new_err(format!("Invalid proto: {err}")))?; store_limits(limits)? - .check_append(&request) + .validate_append(&request) .map_err(|err| stream_error(err.reason.into(), err.message)) } diff --git a/temporalio/bridge/streams.py b/temporalio/bridge/streams.py index fba61eba35..5e870ec350 100644 --- a/temporalio/bridge/streams.py +++ b/temporalio/bridge/streams.py @@ -21,10 +21,14 @@ 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. """ ... @@ -46,12 +50,16 @@ async def call_stream_store( caller: StoreCaller, operation: str, request: bytes, + request_id: str | None = None, ) -> bytes: """Call a Stream Store through the Stream runtime of SDK Core, which checks the request and the response. + + A create and an append need their ``request_id``, and the other operations + take none. """ return await temporalio.bridge.temporal_sdk_bridge.call_stream_store( - runtime._ref, caller, operation, request + runtime._ref, caller, operation, request, request_id ) diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 2fb54fdff6..22aceb090f 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -4,6 +4,7 @@ import asyncio import logging +import uuid from abc import ABC, abstractmethod from collections.abc import Callable, Sequence from dataclasses import dataclass @@ -21,6 +22,7 @@ import temporalio.client import temporalio.nexus.system._support from temporalio.api.enums.v1 import StreamErrorReason +from temporalio.api.stream.v1 import StreamRef from temporalio.api.streamservice.v1 import ( AppendRecordsRequest, AppendRecordsResponse, @@ -40,7 +42,7 @@ ) from temporalio.converter._payload_converter import _get_transfer_type_converter from temporalio.exceptions import StreamError -from temporalio.nexus.system.stream_service import StreamRef, StreamService, models +from temporalio.nexus.system.stream_service import StreamService logger = logging.getLogger(__name__) @@ -57,8 +59,14 @@ class StreamStore(ABC): message of its operation and returns its response message, both from :py:mod:`temporalio.api.streamservice.v1`. A :py:class:`StreamConfig` registers a Store under its :py:meth:`name`, and the SDK sends each Stream call to the - Store of the call's ``StreamRef``. A request has the id of its Stream and never - a Store name, and no response has one. + Store of the call's ``StreamRef``. Each request has that ref. Only the SDK + reads the ``store`` of a ref, and a Store ignores it. + + A create and an append also take a ``request_id``, which is the same on each + try of one call. The SDK makes one for each call of client or Activity code, + and SDK Core makes one for each append of Workflow code. A create of Workflow + code has the first run id of its Workflow chain, so the create of a later run + of the chain is a retry of the create that made the Stream. These docs use the following terms. A batch is the Records of one append. A Producer is one writer of a Stream, which is a Workflow run, an Activity, a @@ -95,6 +103,8 @@ class StreamStore(ABC): * A create for an id with no Stream makes the Stream and returns ``created`` true. + * A create returns the ref as the request had it. The SDK sets the ``store`` + of that ref to the name of the Store before the caller gets it. * A create with the ``request_id`` of the create that made the Stream is a retry of it. A create with an empty ``request_id`` is never a retry. * A Store checks a create for an id that has a Stream in this order, and the @@ -190,7 +200,8 @@ class StreamStore(ABC): * For every call of client or Activity code, and for a create or a describe of Workflow code, the SDK checks the request of an append as SDK Core does for one of Workflow code, and no other request. It only checks that - a response is the response message of the operation. It sends one request + a response is the response message of the operation, and that the ref of + a create's response has the Stream id of the request. It sends one request for each call and tries nothing again, so a Store that needs more checks runs them itself. Such a Store then checks the appends, closes and reads of Workflow code a second time. @@ -215,17 +226,24 @@ def name(self) -> str: raise NotImplementedError @abstractmethod - async def create_stream(self, request: CreateStreamRequest) -> CreateStreamResponse: + async def create_stream( + self, request: CreateStreamRequest, *, request_id: str + ) -> CreateStreamResponse: """Create a Stream, or return the open one that already exists if the conflict policy of the request allows it. + + Each try of one create has the same ``request_id``. """ raise NotImplementedError @abstractmethod async def append_records( - self, request: AppendRecordsRequest + self, request: AppendRecordsRequest, *, request_id: str ) -> AppendRecordsResponse: - """Append one batch from one Producer.""" + """Append one batch from one Producer. + + Each try of one append has the same ``request_id``. + """ raise NotImplementedError @abstractmethod @@ -277,9 +295,6 @@ class StreamConfig: gets it, and refuses one over a limit with ``STREAM_ERROR_REASON_TOO_LARGE``. - A client interceptor that changes the ``StreamRef`` of a request must change it - in place, since a created Stream keeps the ref object of the request. - For the Stream calls of Workflow code: - A create and a describe run in a Local Activity of the SDK. The Workflow @@ -392,12 +407,12 @@ def _store(self, name: str) -> StreamStore: def _store_for( self, - ref: StreamRef[Any], + ref: StreamRef, target: StorageDriverActivityInfo | StorageDriverWorkflowInfo | None, namespace: str, ) -> StreamStore: - """Return the Store of a call on ``ref``, raising :class:`ValueError` if - there is none. + """Return the Store of a call on ``ref``, the ref of the call's request, + raising :class:`ValueError` if there is none. """ if ref.store: return self._store(ref.store) @@ -417,6 +432,22 @@ def _limits(self) -> tuple[int, int, int]: return self.max_record_bytes, self.max_batch_bytes, self.max_batch_records +def _request_ref(request: google.protobuf.message.Message) -> StreamRef: + """Return the ref of a Stream request, which is ``stream_ref`` in a create.""" + if isinstance(request, CreateStreamRequest): + return request.stream_ref + assert isinstance( + request, + ( + AppendRecordsRequest, + ReadRecordsRequest, + CloseStreamRequest, + DescribeStreamRequest, + ), + ) + return request.ref + + def _operation( name: str, ) -> tuple[ @@ -435,9 +466,13 @@ def _operation( async def _call_method( - store: StreamStore, operation: str, request: google.protobuf.message.Message + store: StreamStore, + operation: str, + request: google.protobuf.message.Message, + request_id: str | None, ) -> google.protobuf.message.Message: - """Call the method of ``store`` for a Stream operation. + """Call the method of ``store`` for a Stream operation. ``request_id`` is that + of a create or an append, and ``None`` for the other operations. Raises: StreamError: The Store refused the call. The reason is @@ -446,8 +481,12 @@ async def _call_method( returned something else than the response message of the operation. """ method, _, response_type = _operation(operation) + call = getattr(store, method) try: - response = await getattr(store, method)(request) + if request_id is None: + response = await call(request) + else: + response = await call(request, request_id=request_id) except StreamError: raise except Exception as err: @@ -471,14 +510,22 @@ async def _call_store( # pyright: ignore[reportUnusedFunction] codec: PayloadCodec | None, operation: str, request: google.protobuf.message.Message, + request_id: str | None, timeout: timedelta | None = None, ) -> google.protobuf.message.Message: """Call a Store for client code, which is :py:func:`_call_method` with the - payload codec, the check of an append and a timeout. + payload codec, the check of an append, the Store of a created Stream and a + timeout. The codec gets each body of an append and each Record of a read alone, with no serialization context, since the reader of a Record can be any code. ``limits`` - are those of the Stream config, from :py:meth:`StreamConfig._limits`. + are those of the Stream config, from :py:meth:`StreamConfig._limits`. The ref + of a create's response gets the name of ``store``. + + Raises: + StreamError: The call failed. The reason is + ``STREAM_ERROR_REASON_STORE_CORRUPT`` for a create's response whose ref + doesn't have the Stream id of the request. """ if codec and isinstance(request, AppendRecordsRequest): for appended in request.records: @@ -491,7 +538,7 @@ async def _call_store( # pyright: ignore[reportUnusedFunction] try: # A timeout of zero is no timeout, as for an RPC of the client. async with asyncio.timeout(timeout.total_seconds() if timeout else None): - response = await _call_method(store, operation, request) + response = await _call_method(store, operation, request, request_id) except TimeoutError as err: raise StreamError( f"The Stream Store '{store.name()}' didn't answer the {operation} call " @@ -502,6 +549,17 @@ async def _call_store( # pyright: ignore[reportUnusedFunction] for record in response.records: [body] = await codec.decode([record.body]) record.body.CopyFrom(body) + if isinstance(response, CreateStreamResponse): + assert isinstance(request, CreateStreamRequest) + if response.ref.id != request.stream_ref.id: + raise StreamError( + f"The Stream Store '{store.name()}' answered the {operation} call " + "without the Stream id of the request", + reason=StreamErrorReason.STREAM_ERROR_REASON_STORE_CORRUPT, + ) + # Each later call of the created Stream goes to this Store, whatever the + # selector picks then. + response.ref.store = store.name() return response @@ -530,22 +588,25 @@ async def _call_stream_store( # pyright: ignore[reportUnusedFunction] raise ValueError( "Client has no stream_config, which every Stream call requires." ) - request = input.arg - store = stream_config._store_for(request.ref, _activity_target(), client.namespace) - if isinstance(request, models.CreateStreamRequest): - # The created Stream takes the ref of its request. - request.ref.store = store.name() data_converter = client.data_converter converters = ( data_converter.payload_converter, data_converter.failure_converter, ) + request = temporalio.nexus.system._support.model_to_proto(input.arg, *converters) + store = stream_config._store_for( + _request_ref(request), _activity_target(), client.namespace + ) + request_id = None + if isinstance(request, (CreateStreamRequest, AppendRecordsRequest)): + request_id = str(uuid.uuid4()) response = await _call_store( store, stream_config._limits(), data_converter.payload_codec, input.operation, - temporalio.nexus.system._support.model_to_proto(request, *converters), + request, + request_id, input.rpc_timeout, ) # Each generated Stream call gives its result type. @@ -582,13 +643,15 @@ 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 and return its encoded response. - ``on_task`` gets the task of this call, so that the bridge can cancel it. - It raises :py:class:`asyncio.CancelledError` if the bridge has already - dropped the call. + ``request_id`` is that of a create or an append, and ``None`` for the other + operations. ``on_task`` gets the task of this call, so that the bridge can + cancel it. It raises :py:class:`asyncio.CancelledError` if the bridge has + already dropped the call. """ task = asyncio.current_task() assert task @@ -596,7 +659,7 @@ async def call( _, request_type, _ = _operation(operation) try: response = await _call_method( - self._store(), operation, request_type.FromString(request) + self._store(), operation, request_type.FromString(request), request_id ) except StreamError as err: unavailable = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE diff --git a/temporalio/testing/_stream_store.py b/temporalio/testing/_stream_store.py index 9d96b77412..156568ee90 100644 --- a/temporalio/testing/_stream_store.py +++ b/temporalio/testing/_stream_store.py @@ -107,18 +107,20 @@ def name(self) -> str: """See base class.""" return self._name - async def create_stream(self, request: CreateStreamRequest) -> CreateStreamResponse: + async def create_stream( + self, request: CreateStreamRequest, *, request_id: str + ) -> CreateStreamResponse: """See base class.""" return CreateStreamResponse.FromString( - await self._call("CreateStream", request) + await self._call("CreateStream", request, request_id) ) async def append_records( - self, request: AppendRecordsRequest + self, request: AppendRecordsRequest, *, request_id: str ) -> AppendRecordsResponse: """See base class.""" return AppendRecordsResponse.FromString( - await self._call("AppendRecords", request) + await self._call("AppendRecords", request, request_id) ) async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: @@ -138,11 +140,18 @@ async def describe_stream( ) async def _call( - self, operation: str, request: google.protobuf.message.Message + self, + operation: str, + request: google.protobuf.message.Message, + request_id: str | None = None, ) -> bytes: runtime = self._runtime or temporalio.runtime.Runtime.default() return await temporalio.bridge.streams.call_stream_store( - runtime._core_runtime, self._caller, operation, request.SerializeToString() + runtime._core_runtime, + self._caller, + operation, + request.SerializeToString(), + request_id, ) @@ -205,46 +214,47 @@ def __init__( def name(self) -> str: return self._name - async def create_stream(self, request: CreateStreamRequest) -> CreateStreamResponse: - if request.stream_id not in self._streams: - self._streams[request.stream_id] = _Stream( - request.request_id, self._idle_expiry() - ) - return CreateStreamResponse(created=True) - stream = self._stream(request.stream_id) + async def create_stream( + self, request: CreateStreamRequest, *, request_id: str + ) -> CreateStreamResponse: + stream_id = request.stream_ref.id + if stream_id not in self._streams: + self._streams[stream_id] = _Stream(request_id, self._idle_expiry()) + return CreateStreamResponse(ref=request.stream_ref, created=True) + stream = self._stream(stream_id) if stream.closed: raise StreamError( - f"The Stream '{request.stream_id}' is closed", + f"The Stream '{stream_id}' is closed", reason=StreamErrorReason.STREAM_ERROR_REASON_CLOSED, ) # An empty request id identifies no create, so it never matches. - if request.request_id and request.request_id == stream.request_id: - return CreateStreamResponse(created=True) + if request_id and request_id == stream.request_id: + return CreateStreamResponse(ref=request.stream_ref, created=True) use_existing = StreamIdConflictPolicy.STREAM_ID_CONFLICT_POLICY_USE_EXISTING if request.id_conflict_policy == use_existing: - return CreateStreamResponse(created=False) + return CreateStreamResponse(ref=request.stream_ref, created=False) raise StreamError( - f"The Stream '{request.stream_id}' already exists", + f"The Stream '{stream_id}' already exists", reason=StreamErrorReason.STREAM_ERROR_REASON_ALREADY_EXISTS, ) async def append_records( - self, request: AppendRecordsRequest + self, request: AppendRecordsRequest, *, request_id: str ) -> AppendRecordsResponse: - stream = self._stream(request.stream_id) + stream = self._stream(request.ref.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.request_id: + if request_id: for batch in writer.window: - if (batch.attempt, batch.request_id) == (attempt, request.request_id): + if (batch.attempt, batch.request_id) == (attempt, request_id): return batch.response if self._fence and attempt < writer.newest: - raise _fenced(request.stream_id) + raise _fenced(request.ref.id) if stream.closed: raise StreamError( - f"The Stream '{request.stream_id}' is closed", + f"The Stream '{request.ref.id}' is closed", reason=StreamErrorReason.STREAM_ERROR_REASON_CLOSED, ) first = len(stream.records) + 1 @@ -260,18 +270,18 @@ async def append_records( first_offset=first.to_bytes(8, "big"), last_offset=stream.last_offset ) writer.newest = attempt - writer.window.append(_Batch(attempt, request.request_id, response)) + writer.window.append(_Batch(attempt, request_id, response)) stream.writers[key] = writer stream.expires_at = self._idle_expiry() self._notify(stream) return response async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: - stream = self._stream(request.stream_id) + stream = self._stream(request.ref.id) if request.from_offset > stream.last_offset: raise StreamError( f"The from_offset of the read is past the newest offset of the " - f"Stream '{request.stream_id}'", + f"Stream '{request.ref.id}'", reason=StreamErrorReason.STREAM_ERROR_REASON_OFFSET_TOO_HIGH, ) start = bisect.bisect_right( @@ -295,12 +305,12 @@ async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse ) async def close_stream(self, request: CloseStreamRequest) -> CloseStreamResponse: - stream = self._stream(request.stream_id) + stream = self._stream(request.ref.id) if stream.closed: return CloseStreamResponse() writer = stream.writers.get(_producer_key(request.producer)) if self._fence and writer and _attempt(request.producer) < writer.newest: - raise _fenced(request.stream_id) + raise _fenced(request.ref.id) stream.closed = True stream.expires_at = self._now() + self._retention.total_seconds() self._notify(stream) @@ -309,7 +319,7 @@ async def close_stream(self, request: CloseStreamRequest) -> CloseStreamResponse async def describe_stream( self, request: DescribeStreamRequest ) -> DescribeStreamResponse: - stream = self._stream(request.stream_id) + stream = self._stream(request.ref.id) return DescribeStreamResponse( status=StreamStatus.STREAM_STATUS_CLOSED if stream.closed diff --git a/temporalio/worker/_workflow_streams.py b/temporalio/worker/_workflow_streams.py index ee0a023ef3..0cd76c500f 100644 --- a/temporalio/worker/_workflow_streams.py +++ b/temporalio/worker/_workflow_streams.py @@ -31,11 +31,11 @@ StreamStore, _call_store, _operation, + _request_ref, _StoreCaller, ) from temporalio.converter import StorageDriverWorkflowInfo from temporalio.exceptions import StreamError -from temporalio.nexus.system.stream_service import StreamRef from ._interceptor import StartLocalActivityInput, StartNexusOperationInput @@ -104,7 +104,7 @@ def start( # The seq of the call's read, or 0 for another operation read_seq = 0 if isinstance(request, proto.AppendRecordsRequest): - stream = self._stream(model.ref) + stream = self._stream(request.ref) seq = instance._next_seq("stream_append") append = instance._add_command().append_to_stream append.seq = seq @@ -112,7 +112,7 @@ def start( append.bodies.extend(record.body for record in request.records) result = self._appends[seq] = instance.create_future() elif isinstance(request, proto.CloseStreamRequest): - stream = self._stream(model.ref) + stream = self._stream(request.ref) seq = instance._next_seq("stream_close") close = instance._add_command().close_stream close.seq = seq @@ -126,7 +126,7 @@ def start( "Cannot read a Stream with no body type. Give get_stream a " "body_type, or a StreamRef with a type argument." ) - stream = self._stream(model.ref) + stream = self._stream(request.ref) read_seq = instance._next_seq("stream_read") instance._add_command().read_stream.CopyFrom( temporalio.bridge.proto.workflow_commands.ReadStream( @@ -142,10 +142,13 @@ def start( self._reads[read_seq] = _Read(request.from_offset, result, result_type) else: # The Local Activity picks the Store of a ref with no Store name. A replay - # has its result, so a replay asks no selector for it. - result = self._schedule_store_call( - operation, model.ref.store or "", request - ) + # has its result, so a replay asks no selector for it. Each run of a chain + # sends the same id, so a Store answers the create of a later run as the + # create that made the Stream. + request_id = None + if isinstance(request, proto.CreateStreamRequest): + request_id = instance._info.first_execution_run_id + result = self._schedule_store_call(operation, request, request_id) async def call() -> OutputT: # `asyncio.wait` ends at a cancel of this task. `await result` would pass the @@ -154,7 +157,7 @@ async def call() -> OutputT: if isinstance(request, proto.ReadRecordsRequest): return result.result() return temporalio.nexus.system._support.model_from_proto( - self._response(operation, model, request, result), + self._response(operation, request, result), result_type, *converters, ) @@ -239,7 +242,10 @@ def _error(self, failure: temporalio.api.failure.v1.Failure) -> BaseException: ) def _schedule_store_call( - self, operation: str, store: str, request: google.protobuf.message.Message + self, + operation: str, + request: google.protobuf.message.Message, + request_id: str | None, ) -> asyncio.Future[Any]: """Schedule the SDK's Local Activity for a create or a describe.""" instance = self._instance @@ -255,7 +261,7 @@ def _schedule_store_call( activity = instance._outbound.start_local_activity( StartLocalActivityInput( activity=_STORE_CALL_ACTIVITY, - args=(store, operation, request.SerializeToString()), + args=(operation, 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. @@ -278,7 +284,6 @@ def _schedule_store_call( def _response( self, operation: str, - model: Any, request: google.protobuf.message.Message, result: asyncio.Future[Any], ) -> google.protobuf.message.Message: @@ -308,20 +313,21 @@ def _response( outage.__cause__ = err raise self._fail_task(outage) raise error from err + # The ref of a create has the Store name of History, so a replay gives the same + # ref under any Stream config. if isinstance(request, proto.CreateStreamRequest): - # The created Stream takes the ref of its request. The name is the one in - # History, so a replay gives the same ref under any Stream config. - model.ref.store = answer["store"] - return proto.CreateStreamResponse(created=answer["created"]) + return proto.CreateStreamResponse.FromString(answer) return proto.DescribeStreamResponse.FromString(answer) - def _stream(self, ref: StreamRef[Any]) -> temporalio.api.stream.v1.StreamRef: + def _stream( + self, ref: temporalio.api.stream.v1.StreamRef + ) -> temporalio.api.stream.v1.StreamRef: """Return the ref of a command, with the name of the Store that SDK Core calls. A ref with no Store name gets the Store that the config of the Worker's client picks, and an empty name if that client has no Stream config. """ - store = ref.store or "" + store = ref.store config = self._stream_config() if config and not store: info = self._instance._info @@ -373,14 +379,13 @@ def cancel(self) -> bool: @temporalio.activity.defn(name=_STORE_CALL_ACTIVITY) async def _stream_store_call( # pyright: ignore[reportUnusedFunction] - store: str, operation: str, request: bytes -) -> Any: + operation: str, request: bytes, request_id: str | None +) -> bytes: """Call a Stream Store of the Worker's client for a create or a describe of - Workflow code. ``store`` is the Store name of the call's ref, or empty. + Workflow code. ``request_id`` is that of a create, and ``None`` for a describe. - Returns the name of the Store that it called and ``created`` for a create, so - that History has the Store of the created Stream, and the encoded response for - a describe. + Returns the encoded response. The ref of a create's response has the name of + the Store that it called, so History has the Store of the created Stream. """ info = temporalio.activity.info() if not info.is_local or operation not in ("CreateStream", "DescribeStream"): @@ -403,9 +408,7 @@ async def _stream_store_call( # pyright: ignore[reportUnusedFunction] namespace=info.namespace, ) picked = stream_config._store_for( - StreamRef(id=stream_request.stream_id, store=store or None), - target, - client.namespace, + _request_ref(stream_request), target, client.namespace ) response = await _call_store( picked, @@ -413,9 +416,8 @@ async def _stream_store_call( # pyright: ignore[reportUnusedFunction] client.data_converter.payload_codec, operation, stream_request, + request_id, ) - if isinstance(response, proto.CreateStreamResponse): - return {"store": picked.name(), "created": response.created} return response.SerializeToString() diff --git a/tests/helpers/streams.py b/tests/helpers/streams.py index 4c8995cfb9..484d0d2ff7 100644 --- a/tests/helpers/streams.py +++ b/tests/helpers/streams.py @@ -168,21 +168,30 @@ class FaultStore(StreamStore): def __init__(self, name: str = "memory", **options: Any) -> None: self.memory = MemoryStreamStore(name=name, **options) - self.requests: list[Any] = [] + self.calls: list[tuple[Any, str | None]] = [] + """Each request, with its request id, which is ``None`` for a read, a close + and a describe.""" self.faults: dict[str, collections.deque[Fault]] = collections.defaultdict( collections.deque ) + @property + def requests(self) -> list[Any]: + """Each request of :py:attr:`calls`.""" + return [request for request, _ in self.calls] + def name(self) -> str: return self.memory.name() - async def create_stream(self, request: CreateStreamRequest) -> CreateStreamResponse: - return await self._call("create_stream", request) + async def create_stream( + self, request: CreateStreamRequest, *, request_id: str + ) -> CreateStreamResponse: + return await self._call("create_stream", request, request_id) async def append_records( - self, request: AppendRecordsRequest + self, request: AppendRecordsRequest, *, request_id: str ) -> AppendRecordsResponse: - return await self._call("append_records", request) + return await self._call("append_records", request, request_id) async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: return await self._call("read_records", request) @@ -195,11 +204,15 @@ async def describe_stream( ) -> DescribeStreamResponse: return await self._call("describe_stream", request) - async def _call(self, method: str, request: Message) -> Any: - self.requests.append(request) + async def _call( + self, method: str, request: Message, request_id: str | None = None + ) -> Any: + self.calls.append((request, request_id)) async def call() -> Any: - return await getattr(self.memory, method)(request) + if request_id is None: + return await getattr(self.memory, method)(request) + return await getattr(self.memory, method)(request, request_id=request_id) if self.faults[method]: return await self.faults[method].popleft()(call) diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index ecc3451295..1873290eaa 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -33,6 +33,7 @@ Producer, StreamErrorDetails, ) +from temporalio.api.stream.v1 import StreamRef as RefProto from temporalio.client import ( Client, NexusOperationHandle, @@ -87,7 +88,9 @@ def intercept_client( class _RecordingOutbound(temporalio.client.OutboundInterceptor): - """Logs the Store name of each Stream request before and after its call.""" + """Logs the Store name of the ref of each Stream request before and after its + call. + """ def __init__( self, @@ -100,11 +103,12 @@ def __init__( async def start_nexus_operation( self, input: temporalio.client.StartNexusOperationInput ) -> NexusOperationHandle[Any]: - before = input.arg.ref.store + ref = getattr(input.arg, "stream_ref", None) or input.arg.ref + before = ref.store try: return await self.next.start_nexus_operation(input) finally: - self._stores.append((before, input.arg.ref.store)) + self._stores.append((before, ref.store)) def _producer_proto(producer: Any) -> Producer: @@ -181,7 +185,7 @@ def selector(context: StreamSelectContext) -> FaultStore: bodies = [rng.randrange(100) for _ in range(rng.randrange(3))] call = stream.append(*bodies) expected = proto.AppendRecordsRequest( - stream_id=stream.ref.id, + ref=RefProto(id=stream.ref.id, store=ref_store), producer=producers[in_activity], records=[ AppendRecord(body=to_payload(body)) for body in bodies @@ -189,11 +193,14 @@ def selector(context: StreamSelectContext) -> FaultStore: ) case "describe": call = stream.describe() - expected = proto.DescribeStreamRequest(stream_id=stream.ref.id) + expected = proto.DescribeStreamRequest( + ref=RefProto(id=stream.ref.id, store=ref_store) + ) case _: call = stream.close() expected = proto.CloseStreamRequest( - stream_id=stream.ref.id, producer=producers[in_activity] + ref=RefProto(id=stream.ref.id, store=ref_store), + producer=producers[in_activity], ) else: store = next((s for s in stores if s.name() == ref_store), None) @@ -202,6 +209,7 @@ def selector(context: StreamSelectContext) -> FaultStore: elif ref_store is None: store = stores[0] ref = StreamRef[int](id=stream_id, store=ref_store) + ref_proto = RefProto(id=stream_id, store=ref_store or "") match operation: case "create": policy = rng.choice(list(StreamIdConflictPolicy.values())) @@ -214,11 +222,11 @@ def selector(context: StreamSelectContext) -> FaultStore: body_type=int, ) expected = proto.CreateStreamRequest( - stream_id=stream_id, id_conflict_policy=policy + stream_ref=ref_proto, id_conflict_policy=policy ) case "read": expected = proto.ReadRecordsRequest( - stream_id=stream_id, + ref=ref_proto, from_offset=rng.randbytes(rng.randrange(3)), max_records=rng.choice([0, 1, 2**31 - 1]), max_bytes=rng.choice([0, 1, 2**62]), @@ -234,7 +242,7 @@ def selector(context: StreamSelectContext) -> FaultStore: ) case _: call = client.get_stream(ref).describe() - expected = proto.DescribeStreamRequest(stream_id=stream_id) + expected = proto.DescribeStreamRequest(ref=ref_proto) logs = [list(s.requests) for s in stores] del selects[:], ref_stores[:] @@ -263,19 +271,18 @@ async def run_call() -> Any: for other, log in zip(stores, logs): if other is not store: assert other.requests == log - [request] = store.requests[len(logs[stores.index(store)]) :] + [(request, request_id)] = store.calls[len(logs[stores.index(store)]) :] if isinstance( request, (proto.CreateStreamRequest, proto.AppendRecordsRequest) ): - assert request.request_id and request.request_id not in request_ids - request_ids.add(request.request_id) - request.request_id = "" + assert request_id and request_id not in request_ids + request_ids.add(request_id) + else: + assert request_id is None assert request == expected assert not service_client.mock_calls - # An interceptor sees the ref as the caller wrote it, and the Store's name in - # it after a create. - after = store.name() if operation == "create" else ref_store - assert ref_stores == [(ref_store, after)] + # An interceptor sees the ref as the caller wrote it, also after the call. + assert ref_stores == [(ref_store, ref_store)] target = None if in_activity: target = StorageDriverActivityInfo( diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py index 16c10abdfe..71afe5c090 100644 --- a/tests/nexus/test_streams_with_worker.py +++ b/tests/nexus/test_streams_with_worker.py @@ -15,10 +15,12 @@ from temporalio import activity, workflow from temporalio.api.enums.v1 import EventType, StreamErrorReason, TaskQueueType from temporalio.api.sdk.v1.external_storage_pb2 import ExternalStorageReference +from temporalio.api.stream.v1 import StreamRef as RefProto from temporalio.api.streamservice.v1 import ( AppendRecordsRequest, CloseStreamResponse, CreateStreamRequest, + CreateStreamResponse, ReadRecordsRequest, ) from temporalio.api.taskqueue.v1 import TaskQueue @@ -117,7 +119,8 @@ async def run(self, calls: list[list[Any]], in_activity: bool = False) -> list[A def _writes(store: FaultStore) -> list[Message]: """Return each request of a Store but its reads, which Core pages in its own way, - without what differs between two writers of the same call. + without what differs between two writers of the same call. That is the Producer, + and the Store name of the ref, which Workflow code fills in for a ref with none. """ writes: list[Message] = [] for request in store.requests: @@ -125,9 +128,10 @@ def _writes(store: FaultStore) -> list[Message]: continue copy = type(request)() copy.CopyFrom(request) - for name in ("producer", "request_id"): - if name in copy.DESCRIPTOR.fields_by_name: - copy.ClearField(name) + if "producer" in copy.DESCRIPTOR.fields_by_name: + copy.ClearField("producer") + ref = copy.stream_ref if isinstance(copy, CreateStreamRequest) else copy.ref + ref.ClearField("store") writes.append(copy) return writes @@ -168,8 +172,8 @@ async def test_workflow_code_and_a_client_get_the_same_answers(client: Client) - assert ran.result == from_client assert _writes(for_workflow) == _writes(for_client) appends = [ - request.request_id - for request in for_workflow.requests + request_id + for request, request_id in for_workflow.calls if isinstance(request, AppendRecordsRequest) ] assert all(appends) and len(set(appends)) == len(appends) @@ -234,7 +238,9 @@ async def test_a_body_reads_the_same_on_every_path(client: Client) -> None: assert ran.result == _digest(expected) # The Store has each body as the codec gave it with no context, and the storage of # the Worker has none of them. - stored = await store.memory.read_records(ReadRecordsRequest(stream_id="bodies")) + stored = await store.memory.read_records( + ReadRecordsRequest(ref=RefProto(id="bodies")) + ) assert [dict(record.body.metadata) for record in stored.records] == [ {"encoding": b"test/wrapped", "context": b"NoneType"} ] * len(expected) @@ -247,6 +253,16 @@ def _events(history: Any, event_type: EventType.ValueType) -> list[Any]: return [event for event in history.events if event.event_type == event_type] +def _stream_calls(history: Any) -> list[bytes]: + """Return the Stream calls that Core keeps on each completed Workflow Task.""" + completed = _events(history, EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED) + calls = [ + event.workflow_task_completed_event_attributes.sdk_metadata.core_stream_calls + for event in completed + ] + return [call for call in calls if call] + + async def test_a_store_error_is_the_same_error_on_every_path(client: Client) -> None: store = FaultStore() client = stream_client(client, store) @@ -264,10 +280,9 @@ async def answers_on(path: str, calls: list[list[Any]], **options: Any) -> Any: ) return (await run(client, run_options)).result - def append_requests() -> list[AppendRecordsRequest]: - requests = [r for r in store.requests if isinstance(r, AppendRecordsRequest)] - del store.requests[:] - return requests + def append_request_ids() -> list[str | None]: + calls, store.calls = store.calls, [] + return [i for r, i in calls if isinstance(r, AppendRecordsRequest)] # Core tries an append again in an outage of the Store, with one request id, so the # Store writes it once. Workflow code gets no error, and History has no failure. @@ -282,15 +297,15 @@ def append_requests() -> list[AppendRecordsRequest]: ran = await run(client, RunOptions(_CallsWorkflow, [[append]])) offset = (at + 1).to_bytes(8, "big").hex() assert ran.result == [[offset, offset]] - requests = append_requests() - assert len(requests) == len(faults) + 1 - assert len({request.request_id for request in requests}) == 1 + request_ids = append_request_ids() + assert len(request_ids) == len(faults) + 1 + assert len(set(request_ids)) == 1 assert not _events(ran.history, EventType.EVENT_TYPE_WORKFLOW_TASK_FAILED) # A client and an Activity get the outage as the error of their call. for path in ("client", "activity"): appends.append(raises(ConnectionError("The connection is gone"))) [[error, reason, _]] = await answers_on(path, [append]) - assert (error, reason, len(append_requests())) == ("error", unavailable, 1) + assert (error, reason, len(append_request_ids())) == ("error", unavailable, 1) # An answer of the wrong message fails the call, and nothing tries it again. corrupt = StreamErrorReason.STREAM_ERROR_REASON_STORE_CORRUPT @@ -298,7 +313,13 @@ def append_requests() -> list[AppendRecordsRequest]: with failure_note(path): appends.append(answers(CloseStreamResponse())) [[error, reason, _]] = await answers_on(path, [append]) - assert (error, reason, len(append_requests())) == ("error", corrupt, 1) + assert (error, reason, len(append_request_ids())) == ("error", corrupt, 1) + # So does a create that the Store answers with the ref of another Stream. + other = CreateStreamResponse(ref=RefProto(id="other"), created=True) + store.faults["create_stream"].append(answers(other)) + create = ["create", f"answered for another Stream in {path}"] + [[error, reason, _]] = await answers_on(path, [create]) + assert (error, reason) == ("error", corrupt) # A refusal is the same error for a client, an Activity and Workflow code. Workflow # code gets it again in each task that replays the call. @@ -394,6 +415,7 @@ async def task_fails(handle: Any, _worker: Any) -> None: # has nothing of the call. assert isinstance(ran.result, WorkflowFailureError) assert not _events(ran.history, EventType.EVENT_TYPE_MARKER_RECORDED) + assert not _stream_calls(ran.history) @workflow.defn @@ -436,7 +458,7 @@ async def appended() -> None: ran = await run(stream_client(client, store), options) assert (ran.result is None) == (how in ("async with", "return")) page = await store.memory.read_records( - ReadRecordsRequest(stream_id=stream_id) + ReadRecordsRequest(ref=RefProto(id=stream_id)) ) assert (len(page.records), page.done) == (1, True) @@ -511,6 +533,17 @@ async def run(self, own: str, shared: str) -> str | None: 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_ref.id if isinstance(r, CreateStreamRequest) else r.ref.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 @@ -566,14 +599,10 @@ async def created() -> None: # 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 [(type(r).__name__, r.stream_id) for r in first.requests] == [ - ("CreateStreamRequest", "own"), - ] + assert _calls(first) == [("CreateStreamRequest", "own")] # After the swap, Core calls the Store objects of the new client. - assert [(type(r).__name__, r.stream_id) for r in new_first.requests] == [ - ("AppendRecordsRequest", "own"), - ] - assert [(type(r).__name__, r.stream_id) for r in new_second.requests] == [ + assert _calls(new_first) == [("AppendRecordsRequest", "own")] + assert _calls(new_second) == [ ("CreateStreamRequest", "shared"), ("AppendRecordsRequest", "shared"), ("AppendRecordsRequest", "shared"), @@ -656,7 +685,7 @@ def calls(stream_id: str) -> list[list[Any]]: len(request.records) for request in store.requests if isinstance(request, AppendRecordsRequest) - and request.stream_id != f"large {seed}" + and request.ref.id != f"large {seed}" ] == [len(sizes) for sizes, fits in batches if fits] * 2 @@ -683,8 +712,8 @@ async def test_a_create_in_a_later_run_of_the_chain_is_the_same_create( ) # Each run makes its create twice, and the Store takes all four for one create. assert ran.result is True - creates = [r for r in store.requests if isinstance(r, CreateStreamRequest)] - assert len(creates) == 4 and len({create.request_id for create in creates}) == 1 + creates = [i for r, i in store.calls if isinstance(r, CreateStreamRequest)] + assert len(creates) == 4 and len(set(creates)) == 1 _handled: dict[int, asyncio.Event] = {} @@ -1076,8 +1105,7 @@ async def go_on(handle: Any, _worker: Any) -> None: async def lose_the_records(handle: Any, _worker: Any) -> None: async def has_read() -> None: - history = await handle.fetch_history() - assert _events(history, EventType.EVENT_TYPE_MARKER_RECORDED) + assert _stream_calls(await handle.fetch_history()) await assert_eventually(has_read) store.memory = MemoryStreamStore() @@ -1130,7 +1158,7 @@ async def test_a_workflow_read_asks_the_store_with_its_limits(client: Client) -> ] for limits, expected in cases: with failure_note(f"limits {limits}"): - del store.requests[:] + store.calls.clear() options = RunOptions( _ReadAllWorkflow, ["paged", limits], diff --git a/tests/testing/test_stream_store.py b/tests/testing/test_stream_store.py index a6f60c48e1..598a945694 100644 --- a/tests/testing/test_stream_store.py +++ b/tests/testing/test_stream_store.py @@ -25,6 +25,7 @@ LocalActivityAttempt, Producer, StreamRecord, + StreamRef, WorkflowTaskAttempt, ) from temporalio.api.streamservice.v1 import ( @@ -149,32 +150,34 @@ class _Model: fence: bool streams: dict[str, _ModelStream] = field(default_factory=dict) - def create(self, request: CreateStreamRequest) -> Any: - stream = self.streams.get(request.stream_id) + def create(self, request: CreateStreamRequest, request_id: str) -> Any: + stream = self.streams.get(request.stream_ref.id) if stream is None: - self.streams[request.stream_id] = _ModelStream(request.request_id) - return CreateStreamResponse(created=True) + self.streams[request.stream_ref.id] = _ModelStream(request_id) + return CreateStreamResponse(ref=request.stream_ref, created=True) if stream.closed: return _CLOSED - if request.request_id and request.request_id == stream.request_id: - return CreateStreamResponse(created=True) + if request_id and request_id == stream.request_id: + return CreateStreamResponse(ref=request.stream_ref, created=True) use_existing = StreamIdConflictPolicy.STREAM_ID_CONFLICT_POLICY_USE_EXISTING if request.id_conflict_policy == use_existing: - return CreateStreamResponse() + return CreateStreamResponse(ref=request.stream_ref) return StreamErrorReason.STREAM_ERROR_REASON_ALREADY_EXISTS - def append(self, request: AppendRecordsRequest, writer: _Writer) -> Any: + def append( + self, request: AppendRecordsRequest, writer: _Writer, request_id: str + ) -> Any: # SDK Core refuses a batch with no Record before the Store gets it. if not request.records: return StreamErrorReason.STREAM_ERROR_REASON_INVALID_ARGUMENT - stream = self.streams.get(request.stream_id) + stream = self.streams.get(request.ref.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.request_id and (batch.writer.rank, batch.request_id) == ( + if request_id and (batch.writer.rank, batch.request_id) == ( writer.rank, - request.request_id, + request_id, ): return batch.response if self.fence and stream.fenced(writer): @@ -189,11 +192,11 @@ def append(self, request: AppendRecordsRequest, writer: _Writer) -> Any: stream.records.append( StreamRecord(producer=request.producer, body=record.body, offset=offset) ) - stream.batches.append(_ModelBatch(writer, request.request_id, response)) + stream.batches.append(_ModelBatch(writer, request_id, response)) return response def close(self, request: CloseStreamRequest, writer: _Writer) -> Any: - stream = self.streams.get(request.stream_id) + stream = self.streams.get(request.ref.id) if stream is None: return _NOT_FOUND if not stream.closed and self.fence and stream.fenced(writer): @@ -202,7 +205,7 @@ def close(self, request: CloseStreamRequest, writer: _Writer) -> Any: return CloseStreamResponse() def read(self, request: ReadRecordsRequest) -> Any: - stream = self.streams.get(request.stream_id) + stream = self.streams.get(request.ref.id) if stream is None: return _NOT_FOUND start = int.from_bytes(request.from_offset, "big") @@ -243,10 +246,10 @@ async def _store_script(rng: random.Random, runtime: Runtime | None) -> None: store = MemoryStreamStore( resend_window=model.resend_window, fence=model.fence, runtime=runtime ) - appends: list[tuple[AppendRecordsRequest, _Writer]] = [] + appends: list[tuple[AppendRecordsRequest, _Writer, str]] = [] writers: list[_Writer] = [] for step in range(50): - stream_id = rng.choice("xy") + ref = StreamRef(id=rng.choice("xy"), store=rng.choice(["", "memory"])) # 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 @@ -256,41 +259,40 @@ async def _store_script(rng: random.Random, runtime: Runtime | None) -> None: match rng.choices(_OPERATIONS, _WEIGHTS)[0]: case "create": request = CreateStreamRequest( - stream_id=stream_id, - request_id=rng.choice(["", "r1", "r2"]), + stream_ref=ref, id_conflict_policy=rng.choice( list(StreamIdConflictPolicy.values()) ), ) - expected = model.create(request) - answer = await _answer(store.create_stream(request)) - case "append" | "again" as op: - request = AppendRecordsRequest( - stream_id=stream_id, - producer=writer.producer, - request_id=rng.choice(["", "r1", "r2", "r3"]), + 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(ref=ref, 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 = rng.choice(appends) + earlier, writer, request_id = rng.choice(appends) request.CopyFrom(earlier) del request.records[:] for _ in range(rng.randrange(3)): body = Payload(data=bytes([rng.randrange(256)])) request.records.append(AppendRecord(body=body)) - appends.append((request, writer)) - expected = model.append(request, writer) - answer = await _answer(store.append_records(request)) - case "close": - request = CloseStreamRequest( - stream_id=stream_id, producer=writer.producer + 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 "close": + request = CloseStreamRequest(ref=ref, producer=writer.producer) expected = model.close(request, writer) answer = await _answer(store.close_stream(request)) case _: request = ReadRecordsRequest( - stream_id=stream_id, + ref=ref, from_offset=rng.choice( [b"", *(i.to_bytes(8, "big") for i in range(1, 9))] ), @@ -311,14 +313,17 @@ def _streams(retention: int = 1, idle_ttl: int | None = None) -> _MemoryStreams: ) -def _client_append(stream_id: str) -> AppendRecordsRequest: - request = AppendRecordsRequest(stream_id=stream_id, records=[AppendRecord()]) +_S = StreamRef(id="s") + + +def _client_append() -> AppendRecordsRequest: + request = AppendRecordsRequest(ref=_S, records=[AppendRecord()]) request.producer.client.SetInParent() return request -def _client_close(stream_id: str) -> CloseStreamRequest: - request = CloseStreamRequest(stream_id=stream_id) +def _client_close() -> CloseStreamRequest: + request = CloseStreamRequest(ref=_S) request.producer.client.SetInParent() return request @@ -328,7 +333,7 @@ async def script(rng: random.Random) -> None: loop = asyncio.get_running_loop() retention, idle_ttl = rng.randrange(1, 50), rng.choice([None, 10, 30]) streams = _streams(retention, idle_ttl) - await streams.create_stream(CreateStreamRequest(stream_id="s")) + await streams.create_stream(CreateStreamRequest(stream_ref=_S), request_id="") closed = False expires_at = None if idle_ttl is None else loop.time() + idle_ttl for step in range(12): @@ -338,26 +343,29 @@ async def script(rng: random.Random) -> None: ["append", "append", "close", "read", "describe", "create"] ): case "append": - answer = await _answer(streams.append_records(_client_append("s"))) + append = streams.append_records(_client_append(), request_id="") + answer = await _answer(append) expected: Any = _CLOSED if closed else AppendRecordsResponse if not expired and not closed and idle_ttl is not None: expires_at = loop.time() + idle_ttl case "close": - answer = await _answer(streams.close_stream(_client_close("s"))) + answer = await _answer(streams.close_stream(_client_close())) expected = CloseStreamResponse if not expired and not closed: closed, expires_at = True, loop.time() + retention case "read": - read = ReadRecordsRequest(stream_id="s") + read = ReadRecordsRequest(ref=_S) answer = await _answer(streams.read_records(read)) expected = ReadRecordsResponse case "describe": - describe = DescribeStreamRequest(stream_id="s") + describe = DescribeStreamRequest(ref=_S) answer = await _answer(streams.describe_stream(describe)) expected = DescribeStreamResponse case _: - create = CreateStreamRequest(stream_id="s", request_id="other") - answer = await _answer(streams.create_stream(create)) + create = streams.create_stream( + CreateStreamRequest(stream_ref=_S), request_id="other" + ) + answer = await _answer(create) expected = ( _CLOSED if closed @@ -378,14 +386,14 @@ def test_a_read_waits_for_the_next_write_or_for_its_wait() -> None: async def script(rng: random.Random) -> None: loop = asyncio.get_running_loop() streams = _streams() - await streams.create_stream(CreateStreamRequest(stream_id="s")) - first = await streams.append_records(_client_append("s")) + await streams.create_stream(CreateStreamRequest(stream_ref=_S), request_id="") + first = await streams.append_records(_client_append(), request_id="") wait, write_in = rng.sample(range(1, 60), 2) write = rng.choice(["append", "close", None]) read = asyncio.ensure_future( streams.read_records( ReadRecordsRequest( - stream_id="s", + ref=_S, from_offset=first.last_offset, wait=Duration(seconds=wait), ) @@ -395,9 +403,9 @@ async def script(rng: random.Random) -> None: read.add_done_callback(lambda _: answered_at.append(loop.time())) await asyncio.sleep(write_in) if write == "append": - await streams.append_records(_client_append("s")) + await streams.append_records(_client_append(), request_id="") elif write == "close": - await streams.close_stream(_client_close("s")) + await streams.close_stream(_client_close()) page = await read in_time = write is not None and write_in < wait assert ( @@ -431,9 +439,9 @@ def store() -> MemoryStreamStore: def on_task(_task: asyncio.Task[Any]) -> None: raise asyncio.CancelledError - request = DescribeStreamRequest(stream_id="s").SerializeToString() + request = DescribeStreamRequest(ref=_S).SerializeToString() with pytest.raises(asyncio.CancelledError): - await _StoreCaller(store).call("DescribeStream", request, on_task) + await _StoreCaller(store).call("DescribeStream", request, None, on_task) assert not asked # Core drops this call after it made the task of the call and before the task ran, diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py index dab4a2d5e1..a2f78b5914 100644 --- a/tests/worker/test_workflow_streams.py +++ b/tests/worker/test_workflow_streams.py @@ -37,6 +37,7 @@ from temporalio.api.stream.v1 import StreamRecord, StreamRef from temporalio.api.streamservice.v1 import ( CreateStreamRequest, + CreateStreamResponse, DescribeStreamRequest, DescribeStreamResponse, ) @@ -383,9 +384,9 @@ def start_local_activity( _Script.local_activities.append(input.activity) return super().start_local_activity(input) - async def start_create_stream(self, request: Any) -> Any: + 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) + return await super().start_create_stream(request, output_type) async def start_append_records(self, request: Any) -> Any: _Script.intercepted.append(("append", request)) @@ -434,16 +435,20 @@ def _plan( if refused: job.resolve_stream_close.failed.CopyFrom(refused) else: - request: Message = DescribeStreamRequest(stream_id=call.stream) + request: Message = DescribeStreamRequest(ref=stream) + request_id = None described = DescribeStreamResponse( status=StreamStatus.STREAM_STATUS_OPEN, last_offset=b"last%d" % seq ) - answer: Any = described.SerializeToString() + answer: Message = described outcome = (described.status, described.last_offset) if call.operation == "create": # Each create of a run chain has the first run id as its request id. - request = CreateStreamRequest(stream_id=call.stream, request_id="first-run") - answer = {"store": history_store, "created": seq % 2 == 0} + request, request_id = CreateStreamRequest(stream_ref=stream), "first-run" + answer = CreateStreamResponse( + ref=StreamRef(id=call.stream, store=history_store), + created=seq % 2 == 0, + ) outcome = (history_store, seq % 2 == 0 or None) activity = command.schedule_local_activity activity.seq = seq @@ -451,7 +456,7 @@ def _plan( activity.activity_type = _STORE_CALL operation = request.DESCRIPTOR.name.removesuffix("Request") activity.arguments.extend( - converter.to_payloads([store, operation, request.SerializeToString()]) + converter.to_payloads([operation, request.SerializeToString(), request_id]) ) activity.schedule_to_close_timeout.FromSeconds(5) temporalio.common.RetryPolicy(maximum_attempts=1).apply_to_proto( @@ -486,7 +491,9 @@ def _plan( ) ) else: - result.completed.result.CopyFrom(converter.to_payload(answer)) + result.completed.result.CopyFrom( + converter.to_payload(answer.SerializeToString()) + ) if call.cancel: outcome = "cancelled" elif call.refusal is not None: @@ -625,7 +632,7 @@ def selector(context: StreamSelectContext) -> StreamStore: assert not instance._streams._appends and not instance._streams._closes assert selects == expected_selects # An interceptor sees each call in the method of its operation, and the ref of - # a create has the Store name of History once the create has its result. + # a create as Workflow code wrote it, also after its result. assert [operation for operation, _ in _Script.intercepted] == [ call.operation for call in calls ] @@ -635,8 +642,8 @@ def selector(context: StreamSelectContext) -> StreamStore: ] assert _Script.local_activities == [_STORE_CALL] * len(store_calls) for call, (_, request) in zip(calls, _Script.intercepted): - if call.operation == "create" and call.stream in created: - assert request.ref.store == created[call.stream] + if call.operation == "create": + assert request.stream_ref.store == call.store # An eviction ends each task of the instance, also the task of a call that waits. evict = WorkflowActivationJob(remove_from_cache=RemoveFromCache()) assert (await _activate(instance, evict)).HasField("successful") From d14f53178f8f27131669ae37ce67fbf705ad20f1 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Mon, 23 Nov 2026 23:38:06 -0700 Subject: [PATCH 13/50] Drop the Stream helpers that the generated code no longer calls The generated Stream code converts a ref itself and sends no request id, so `_support` has no use for these four helpers. --- temporalio/nexus/system/_support.py | 31 ----------------------------- 1 file changed, 31 deletions(-) diff --git a/temporalio/nexus/system/_support.py b/temporalio/nexus/system/_support.py index 90d7927878..5e16287bd8 100644 --- a/temporalio/nexus/system/_support.py +++ b/temporalio/nexus/system/_support.py @@ -1,7 +1,6 @@ import collections.abc import dataclasses import typing -import uuid from datetime import datetime, timedelta import google.protobuf.duration_pb2 @@ -26,7 +25,6 @@ ReadRecordsRequest, ReadRecordsResponse, StreamRecord, - StreamRef, Timestamp, ) @@ -74,25 +72,6 @@ def model_from_proto( return converter.from_transfer_type(proto, model_type) -def request_id() -> str: - from temporalio.workflow import in_workflow, info - - # Each run of a chain sends the same id, so a Store answers the create of a later run - # as the create that made the Stream. - if in_workflow(): - return info().first_execution_run_id - return str(uuid.uuid4()) - - -def append_request_id() -> str | None: - from temporalio.workflow import in_workflow - - # Core makes the request id of an append of Workflow code. - if in_workflow(): - return None - return str(uuid.uuid4()) - - def default_producer( nexus_client: "temporalio.client.NexusClient[typing.Any]", ) -> "Producer": @@ -200,16 +179,6 @@ def _timestamp(time: datetime) -> "Timestamp": return models.Timestamp(seconds=proto.seconds, nanos=proto.nanos) -def stream_ref_to_id(ref: "StreamRef[typing.Any]") -> str: - return ref.id - - -def stream_ref_from_id( - id: str, ref_type: "type[StreamRef[_BodyT]]" -) -> "StreamRef[_BodyT]": - return ref_type(id=id) - - def next_read_request( request: "ReadRecordsRequest[_BodyT]", response: "ReadRecordsResponse[_BodyT]" ) -> "ReadRecordsRequest[_BodyT] | None": From 5c144561dc72ef2df75468da20cdd86437ca3c07 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Mon, 23 Nov 2026 23:38:59 -0700 Subject: [PATCH 14/50] Give the Producer of a Workflow's Activity its scheduled event id A run can use an Activity id again, and the id of the scheduled event makes the two Activities separate Producers. Core reads it from the task token, and `activity.Info` keeps it in a private field next to the Workflow Task of a Local Activity. --- temporalio/activity.py | 5 ++++ temporalio/contrib/streams/_producer.py | 9 +++--- temporalio/nexus/system/_support.py | 3 ++ temporalio/worker/_activity.py | 1 + tests/nexus/test_streams.py | 14 ++++++++-- tests/nexus/test_streams_with_worker.py | 37 +++++++++++++++++++++++++ tests/testing/test_stream_store.py | 16 +++++++---- 7 files changed, 74 insertions(+), 11 deletions(-) diff --git a/temporalio/activity.py b/temporalio/activity.py index 5cc113b84b..3225f8d2fa 100644 --- a/temporalio/activity.py +++ b/temporalio/activity.py @@ -181,6 +181,11 @@ class Info: This API is experimental and unstable. """ + _scheduled_event_id: int = 0 + """ID of the ``ActivityTaskScheduled`` event of an Activity that a Workflow scheduled, for + the Producer of its Stream writes. 0 for other Activities, and when SDK Core couldn't read + it from the task token.""" + @property def in_workflow(self) -> bool: """Was this activity started by a workflow?""" diff --git a/temporalio/contrib/streams/_producer.py b/temporalio/contrib/streams/_producer.py index b54b67451f..2bdb6cbfae 100644 --- a/temporalio/contrib/streams/_producer.py +++ b/temporalio/contrib/streams/_producer.py @@ -20,10 +20,11 @@ def current_producer() -> Producer: 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, which is the - sequence number of the Activity in the run unless the Workflow set one. A - run can use an Activity id again after the first Activity with it has - ended. The second Activity is then a later attempt of the same Producer, so - a Store that fences refuses a late write of the first one. + sequence number of the Activity in the run unless the Workflow set one, and + the id of the Activity's ``ActivityTaskScheduled`` event. A run can use an + Activity id again after the first Activity with it has ended. The second + Activity is then a separate Producer, since its scheduled event is another + one. A Local Activity whose retry waits longer than its ``local_retry_threshold`` runs again under a new sequence number. Each such retry then writes as a new diff --git a/temporalio/nexus/system/_support.py b/temporalio/nexus/system/_support.py index 5e16287bd8..74ced10c89 100644 --- a/temporalio/nexus/system/_support.py +++ b/temporalio/nexus/system/_support.py @@ -144,6 +144,8 @@ def activity_producer(info: "temporalio.activity.Info") -> "Producer": attempt=info.attempt, ) if run_id: + # Zero is a task whose scheduled event Core couldn't read. + scheduled_event_id = info._scheduled_event_id or None # pyright: ignore[reportPrivateUsage] return models.Producer( kind=models.ProducerKindWorkflowActivity( models.WorkflowActivityProducer( @@ -151,6 +153,7 @@ def activity_producer(info: "temporalio.activity.Info") -> "Producer": workflow_id=workflow_id, run_id=run_id, activity_id=info.activity_id, + scheduled_event_id=scheduled_event_id, attempt=attempt, ) ) diff --git a/temporalio/worker/_activity.py b/temporalio/worker/_activity.py index 7c95449df8..b3af7d45e9 100644 --- a/temporalio/worker/_activity.py +++ b/temporalio/worker/_activity.py @@ -709,6 +709,7 @@ async def _execute_activity( ) if start.HasField("workflow_task") else None, + _scheduled_event_id=start.scheduled_event_id, ) if self._encode_headers: diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index 1873290eaa..130654c149 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -463,6 +463,8 @@ class _WriterInfo: time: datetime """The scheduled time of an Activity attempt, or the started time of a task.""" event_id: int + """The started event id of the task of a Local Activity, or the scheduled event id + of an Activity of a Workflow, which is zero when SDK Core couldn't read it.""" def _writer_info(rng: random.Random) -> _WriterInfo: @@ -470,15 +472,18 @@ def text() -> str: return "".join(rng.choice("ab:/ '\"é") for _ in range(rng.randrange(1, 5))) kinds = ["workflow", "local_activity", "workflow_activity", "standalone_activity"] + kind = rng.choice(kinds) return _WriterInfo( - kind=rng.choice(kinds), + kind=kind, namespace=text(), workflow_id=text(), run_id=text(), activity_id=text(), attempt=rng.randrange(1, 9), time=datetime.fromtimestamp(rng.randrange(10**9), timezone.utc), - event_id=rng.randrange(3, 99), + event_id=rng.choice([0, rng.randrange(3, 99)]) + if kind == "workflow_activity" + else rng.randrange(3, 99), ) @@ -509,6 +514,9 @@ def _default_producer(writer: _WriterInfo) -> Any: ) 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. @@ -535,6 +543,8 @@ def _expected_producer(writer: _WriterInfo) -> Producer: 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 diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py index 71afe5c090..f4577d6c35 100644 --- a/tests/nexus/test_streams_with_worker.py +++ b/tests/nexus/test_streams_with_worker.py @@ -249,6 +249,43 @@ async def test_a_body_reads_the_same_on_every_path(client: Client) -> None: ) +@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(ref=RefProto(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 + ] + + def _events(history: Any, event_type: EventType.ValueType) -> list[Any]: return [event for event in history.events if event.event_type == event_type] diff --git a/tests/testing/test_stream_store.py b/tests/testing/test_stream_store.py index 598a945694..6cf93144f6 100644 --- a/tests/testing/test_stream_store.py +++ b/tests/testing/test_stream_store.py @@ -93,7 +93,7 @@ class _Writer: """A generated Producer, with what a Store tells Producers and attempts apart by.""" producer: Producer - ids: tuple[str, ...] + 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.""" @@ -104,14 +104,20 @@ def _writer(rng: random.Random, same: _Writer | None = None) -> _Writer: producer = Producer() if same: producer.CopyFrom(same.producer) - name = same.ids[0] if same else rng.choice(list(Producer.DESCRIPTOR.fields_by_name)) + name = ( + str(same.ids[0]) + if same + else rng.choice(list(Producer.DESCRIPTOR.fields_by_name)) + ) kind = getattr(producer, name) kind.SetInParent() - ids = [name] + ids: list[str | int] = [name] for id_field in kind.DESCRIPTOR.fields: - if id_field.type == id_field.TYPE_STRING: + # 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("aab")) + 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"): From 56100c3382927f7d3804cb5fb5abff7224c0d1b1 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Mon, 23 Nov 2026 23:39:37 -0700 Subject: [PATCH 15/50] Continue a Workflow read from the last offset of its page Core gives each page the offset where the next read goes on, also a page with no Record, so Workflow code reads on from there as client code does. --- temporalio/worker/_workflow_streams.py | 10 +++------- tests/worker/test_workflow_streams.py | 11 +++++++---- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/temporalio/worker/_workflow_streams.py b/temporalio/worker/_workflow_streams.py index 0cd76c500f..555311446c 100644 --- a/temporalio/worker/_workflow_streams.py +++ b/temporalio/worker/_workflow_streams.py @@ -49,9 +49,6 @@ class _Read: """The read of one ``read_page`` call.""" - after: bytes - """The offset that the read started from.""" - waiter: asyncio.Future[Any] """Gets the page of the call.""" @@ -139,7 +136,7 @@ def start( ) ) result = instance.create_future() - self._reads[read_seq] = _Read(request.from_offset, result, result_type) + self._reads[read_seq] = _Read(result, result_type) else: # The Local Activity picks the Store of a ref with no Store name. A replay # has its result, so a replay asks no selector for it. Each run of a chain @@ -198,10 +195,9 @@ def resolve_read( if job.HasField("failed"): read.waiter.set_exception(self._error(job.failed)) return - records = job.page.records page = proto.ReadRecordsResponse( - records=records, - last_offset=records[-1].offset if records else read.after, + records=job.page.records, + last_offset=job.page.last_offset, done=job.page.done, ) # A body that the converter refuses fails the Workflow Task, as a result of a diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py index a2f78b5914..e33c586899 100644 --- a/tests/worker/test_workflow_streams.py +++ b/tests/worker/test_workflow_streams.py @@ -812,6 +812,9 @@ def cancel(seq: int) -> WorkflowCommand: if rng.random() >= 0.6: continue records = [read.after + 1 + at for at in range(rng.randrange(4))] + # The last_offset of a page can be past its last Record, also in a page with + # no Record. + last = (records[-1] if records else read.after) + rng.choice([0, 0, 1]) page = StreamPage( records=[ StreamRecord( @@ -820,6 +823,7 @@ def cancel(seq: int) -> WorkflowCommand: ) for number in records ], + last_offset=_offset(last), done=rng.random() < 0.3, ) job = ResolveStreamRead(seq=seq, page=page) @@ -901,10 +905,9 @@ def run_handler() -> None: outcomes[call].append(StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND) continue bodies = [converter.from_payload(r.body) for r in job.page.records] - if bodies: - positions[call] = int.from_bytes(job.page.records[-1].offset, "big") - # A page with no Record has the offset of its call. - outcomes[call].append((bodies, _offset(positions[call]), job.page.done)) + # The next page comes after the last_offset of this one. + positions[call] = int.from_bytes(job.page.last_offset, "big") + outcomes[call].append((bodies, job.page.last_offset, job.page.done)) if not job.page.done and len(outcomes[call]) < reader.pages: call_read(call, commands) From 3d2063b6854bde8e32f3a38536ef60c21eb1f3ed Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Tue, 24 Nov 2026 14:19:10 -0700 Subject: [PATCH 16/50] Give a page with no last_offset the offset where it ended A Store can leave the last_offset of a read page unset. Client and Activity code then get the offset of the last Record, or the from_offset of a page with no Record, as Workflow code does from Core. --- temporalio/client/_stream_store.py | 5 +++++ tests/nexus/test_streams.py | 23 ++++++++++++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 22aceb090f..11b6b8e974 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -545,6 +545,11 @@ async def _call_store( # pyright: ignore[reportUnusedFunction] "within its rpc_timeout", reason=StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE, ) from err + if isinstance(response, ReadRecordsResponse) and not response.last_offset: + assert isinstance(request, ReadRecordsRequest) + # The page shows where it ended, so a Store doesn't have to say it. + records = response.records + response.last_offset = records[-1].offset if records else request.from_offset if codec and isinstance(response, ReadRecordsResponse): for record in response.records: [body] = await codec.decode([record.body]) diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index 130654c149..89059304eb 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -9,7 +9,7 @@ import random import subprocess import sys -from collections.abc import Callable +from collections.abc import Awaitable, Callable from datetime import datetime, timedelta, timezone from types import SimpleNamespace from typing import Any, cast @@ -700,3 +700,24 @@ async def script() -> None: assert asyncio.all_tasks() == {asyncio.current_task()} run_with_virtual_clock(script()) + + +def test_a_page_with_no_last_offset_ends_at_its_last_record() -> None: + async def unset(call: Callable[[], Awaitable[Any]]) -> Any: + page = await call() + page.ClearField("last_offset") + return page + + async def script() -> None: + store = FaultStore() + client = Client(Mock(spec=ServiceClient), stream_config=StreamConfig([store])) + stream = await client.create_stream(id="s", body_type=int) + await stream.append(1, 2) + store.faults["read_records"].extend([unset, unset]) + page = await stream.read_page() + assert page.last_offset == page.records[-1].offset + # A page with no Record ends where its read started. + empty = await stream.read_page(from_offset=page.last_offset) + assert (empty.records, empty.last_offset) == ([], page.last_offset) + + run_with_virtual_clock(script()) From 98bedd9689ff69536f038ec3d7bc6679e7f593e9 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Tue, 24 Nov 2026 14:19:10 -0700 Subject: [PATCH 17/50] Shorten the docs of the Stream Store and its helpers The rules of each operation are now in the doc of its method. The test of a limit below one only repeated the check of the config, so it goes. --- temporalio/client/_stream_store.py | 265 ++++++++++-------------- temporalio/contrib/streams/_appender.py | 23 +- temporalio/contrib/streams/_producer.py | 16 +- temporalio/testing/_stream_store.py | 27 +-- tests/nexus/test_streams.py | 12 -- 5 files changed, 130 insertions(+), 213 deletions(-) diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 11b6b8e974..f4b6f17354 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -59,30 +59,18 @@ class StreamStore(ABC): message of its operation and returns its response message, both from :py:mod:`temporalio.api.streamservice.v1`. A :py:class:`StreamConfig` registers a Store under its :py:meth:`name`, and the SDK sends each Stream call to the - Store of the call's ``StreamRef``. Each request has that ref. Only the SDK - reads the ``store`` of a ref, and a Store ignores it. + Store of the call's ``StreamRef``. Only the SDK reads the ``store`` of a ref. - A create and an append also take a ``request_id``, which is the same on each - try of one call. The SDK makes one for each call of client or Activity code, - and SDK Core makes one for each append of Workflow code. A create of Workflow - code has the first run id of its Workflow chain, so the create of a later run - of the chain is a retry of the create that made the Stream. - - These docs use the following terms. A batch is the Records of one append. A - Producer is one writer of a Stream, which is a Workflow run, an Activity, a - Local Activity or a client. An attempt is the try of a Producer that made a - write, such as one Workflow Task or one attempt of an Activity. - - Callers rely on a Store to follow these rules. SDK Core reads a Stream for - Workflow code and reads it again in a replay, and both depend on the rules of - the log. + Callers rely on a Store to follow the rules below and those of each method. + SDK Core reads a Stream for Workflow code and reads it again in a replay, and + both depend on them. The log: - * The body of a Record is the payload that the append gave, which the payload - codec has already encoded. The Store keeps it as it is. - * A Store writes a batch whole or not at all. The Records of a batch are next - to each other in the Stream, in the order of the request. + * A Store keeps the body of a Record as the append gave it. The payload codec + has already encoded it. + * A Store writes a batch, which is the Records of one append, whole or not at + all. Its Records are next to each other, in the order of the request. * The offsets of a Stream sort bytewise in the order of its Records, and the offset of a Record is never empty. * Once a response returned an offset, no Record ever appears at or below it @@ -91,127 +79,37 @@ class StreamStore(ABC): Producers and attempts: - * Two Producers are the same when they have the same kind and the same ids of - that kind. The attempt isn't part of that. + * A Producer is one writer of a Stream, which is a Workflow run, an Activity, + a Local Activity or a client. Two Producers are the same when they have the + same kind and the same ids of that kind. + * An attempt is the try of a Producer that made a write, such as one Workflow + Task or one attempt of an Activity. * Fencing is optional. A Store that fences keeps the newest attempt of each - Producer that appended to a Stream, and refuses an append or a close of - that Producer from an earlier attempt. Only an append changes the newest - attempt, and a close doesn't. Every Record has its Producer and attempt - either way, so a reader can tell the attempts apart. - - A create: - - * A create for an id with no Stream makes the Stream and returns ``created`` - true. - * A create returns the ref as the request had it. The SDK sets the ``store`` - of that ref to the name of the Store before the caller gets it. - * A create with the ``request_id`` of the create that made the Stream is a - retry of it. A create with an empty ``request_id`` is never a retry. - * A Store checks a create for an id that has a Stream in this order, and the - first check that applies decides the answer: - - 1. The Stream expired, so the create fails with ``EXPIRED``. - 2. The Stream is closed, so the create fails with ``CLOSED``. - 3. The create is a retry, so it returns ``created`` true. - 4. The policy is ``USE_EXISTING``, so the create returns ``created`` - false, and the ``created`` of the caller's ``Stream`` is then ``None``. - With ``FAIL``, or with no policy, it fails with ``ALREADY_EXISTS``. - - An append: - - * A Store remembers the request ids of the recent batches of each Producer of - a Stream. How many is a setting of the Store, and it's at least the last - batch. An append with the Producer, the attempt and the ``request_id`` of a - remembered batch is a resend. An append with an empty ``request_id``, or - one that comes after more batches than the Store remembers, isn't one. A - Store that doesn't fence compares Producers and attempts for this rule too. - * A Store checks an append in this order, and the first check that applies - decides the answer: - - 1. The Stream doesn't exist or it expired, so the append fails with - ``NOT_FOUND`` or ``EXPIRED``. - 2. The append is a resend, so the Store writes nothing and returns the - offsets of the first write of that batch. It doesn't compare the - Records, and the Stream can be closed by then. - 3. The Store fences, and a later attempt of the Producer already wrote. - The append fails with ``FENCED``. - 4. The Stream is closed, so the append fails with ``CLOSED``. - - * An append returns the offsets of its first and its last Record. - - A close: - - * A Store checks a close in this order, and the first check that applies - decides the answer: - - 1. The Stream doesn't exist or it expired, so the close fails with - ``NOT_FOUND`` or ``EXPIRED``. - 2. The Stream is already closed, so the close succeeds. - 3. The Store fences, and a later attempt of the Producer already wrote. - The close fails with ``FENCED``. - - A read: - - * A read returns the Records after ``from_offset``, in the order of the - Stream. Each Record has its body and the Producer of its append. - * A page has at most ``max_records`` Records, and Records of at most - ``max_bytes`` in total, where zero is no limit. It always has its first - Record, even when that Record alone is over ``max_bytes``. - * The ``last_offset`` of a page is where the next read continues. It's never - below ``from_offset`` or the offset of a Record in the page, and it must not - skip a Record. - * A page is ``done`` when the Stream is closed and no Record comes after the - page. That holds for an empty page too. - * A read with nothing after ``from_offset`` answers once a Record comes, once - the Stream is closed, or once its ``wait`` is up. With no ``wait``, or one - of zero, it answers immediately. - * A Store takes every offset that a response returned as the ``from_offset`` - of a read. That's the offset of a Record, an offset of an append, and a - ``last_offset``. A read fails with ``OFFSET_TOO_HIGH`` only when - ``from_offset`` is past the end of the Stream. - - A describe returns the status of the Stream, and a ``last_offset`` that is - never below the offset of the newest Record. + Producer that appended to a Stream, and refuses an append or a close of an + earlier attempt of that Producer. Only an append changes the newest attempt. + Every Record has its Producer and attempt either way, so a reader can tell + the attempts apart. A method refuses a call by raising a :py:class:`temporalio.exceptions.StreamError` with the reason, such as - ``STREAM_ERROR_REASON_CLOSED`` for ``CLOSED`` above. Any other exception is an - outage of the Store, and the caller gets a ``StreamError`` with - ``STREAM_ERROR_REASON_STORE_UNAVAILABLE``. + ``STREAM_ERROR_REASON_CLOSED`` for ``CLOSED`` in these docs. Any other + exception is an outage of the Store, and the caller gets a ``StreamError`` + with ``STREAM_ERROR_REASON_STORE_UNAVAILABLE``. - The SDK calls a Store in these ways: + How the SDK calls a Store: * Calls run at the same time on the event loop, and a read can wait while appends run. - * The SDK cancels the task of a call. It does so at the ``rpc_timeout`` of a - client call, when Workflow code cancels a read, when a Workflow is evicted, - when a Worker shuts down, and at the deadline that SDK Core gives each try - of a call of Workflow code. - * A cancelled call may still have taken effect, and the Store must stay - usable after it. - * A resend can come while its first try still runs, and the Store still - writes the batch once. - - Who checks a call depends on the code that makes it: - - * For an append, a close or a read of Workflow code, SDK Core checks the - request before the Store gets it and the response before Workflow code - does, and it tries the call again during an outage. - * For every call of client or Activity code, and for a create or a describe - of Workflow code, the SDK checks the request of an append as SDK Core - does for one of Workflow code, and no other request. It only checks that - a response is the response message of the operation, and that the ref of - a create's response has the Stream id of the request. It sends one request - for each call and tries nothing again, so a Store that needs more checks - runs them itself. Such a Store then checks the appends, closes and reads - of Workflow code a second time. - - The limits of a batch are those of the :py:class:`StreamConfig` of the - caller. The SDK checks each append against them before the Store gets it, - in Workflow code as in client and Activity code. - - The ``rpc_metadata`` of a Stream call has no effect, since a call to a Store - is not an RPC of the Temporal server. + * The SDK can cancel the task of a call, for example at a timeout, at an + eviction or at a Worker shutdown. The call may still have taken effect, and + the Store must stay usable after it. + * A resend can come while its first try still runs, and the Store still writes + the batch once. + * SDK Core checks each append, close and read of Workflow code, and its + response, and tries the call again during an outage. For every other call + the SDK checks only an append, against the limits of the + :py:class:`StreamConfig`, and sends one request. A Store that needs more + checks runs them itself. .. warning:: This API is experimental and subject to change. @@ -229,10 +127,20 @@ def name(self) -> str: async def create_stream( self, request: CreateStreamRequest, *, request_id: str ) -> CreateStreamResponse: - """Create a Stream, or return the open one that already exists if the - conflict policy of the request allows it. + """Create a Stream, or return the open one if the conflict policy allows it. + + Each try of one create has the same ``request_id``. A create with the + ``request_id`` of the create that made the Stream is a retry of it, and a + create with an empty ``request_id`` never is. The response has the ref as + the request had it. - Each try of one create has the same ``request_id``. + A Store checks a create for an id that has a Stream in this order: + + 1. The Stream expired, so the create fails with ``EXPIRED``. + 2. The Stream is closed, so the create fails with ``CLOSED``. + 3. The create is a retry, so it returns ``created`` true. + 4. The policy is ``USE_EXISTING``, so it returns ``created`` false. With + ``FAIL``, or with no policy, it fails with ``ALREADY_EXISTS``. """ raise NotImplementedError @@ -242,25 +150,68 @@ async def append_records( ) -> AppendRecordsResponse: """Append one batch from one Producer. - Each try of one append has the same ``request_id``. + Each try of one append has the same ``request_id``. A Store remembers the + request ids of the recent batches of each Producer of a Stream, at least + the last one. An append with the Producer, the attempt and the + ``request_id`` of a remembered batch is a resend. An append with an empty + ``request_id`` never is. + + A Store checks an append in this order: + + 1. The Stream doesn't exist or it expired, so the append fails with + ``NOT_FOUND`` or ``EXPIRED``. + 2. The append is a resend, so the Store writes nothing and returns the + offsets of the first write. It doesn't compare the Records, and the + Stream can be closed by then. + 3. The Store fences, and a later attempt of the Producer already wrote, so + the append fails with ``FENCED``. + 4. The Stream is closed, so the append fails with ``CLOSED``. + + The response has the offsets of the first and the last Record. """ raise NotImplementedError @abstractmethod async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: - """Read one page of Records after ``from_offset``.""" + """Read one page of Records after ``from_offset``, in the order of the Stream. + + * A page has at most ``max_records`` Records, and Records of at most + ``max_bytes`` in total, where zero is no limit. It always has its first + Record, even when that Record alone is over ``max_bytes``. + * ``last_offset`` is where the next read continues. A Store doesn't have to + set it. If it's empty, the caller gets the offset of the last Record of + the page, or ``from_offset`` for a page with no Record. + * A page is ``done`` when the Stream is closed and no Record comes after + the page. + * A read with nothing after ``from_offset`` answers once a Record comes, + once the Stream is closed, or once its ``wait`` is up. + * Every offset that a response returned is a valid ``from_offset``. A read + fails with ``OFFSET_TOO_HIGH`` only when ``from_offset`` is past the end + of the Stream. + """ raise NotImplementedError @abstractmethod async def close_stream(self, request: CloseStreamRequest) -> CloseStreamResponse: - """Close a Stream.""" + """Close a Stream. + + A Store checks a close in this order: + + 1. The Stream doesn't exist or it expired, so the close fails with + ``NOT_FOUND`` or ``EXPIRED``. + 2. The Stream is already closed, so the close succeeds. + 3. The Store fences, and a later attempt of the Producer already wrote, so + the close fails with ``FENCED``. + """ raise NotImplementedError @abstractmethod async def describe_stream( self, request: DescribeStreamRequest ) -> DescribeStreamResponse: - """Return the status and the newest offset of a Stream.""" + """Return the status of a Stream, and a ``last_offset`` that is never below + the offset of its newest Record. + """ raise NotImplementedError @@ -293,37 +244,33 @@ class StreamConfig: The SDK checks each append against :py:attr:`max_record_bytes`, :py:attr:`max_batch_bytes` and :py:attr:`max_batch_records` before its Store gets it, and refuses one over a limit with - ``STREAM_ERROR_REASON_TOO_LARGE``. + ``STREAM_ERROR_REASON_TOO_LARGE``. The ``rpc_metadata`` of a Stream call has + no effect, since a call to a Store is not an RPC of the Temporal server. For the Stream calls of Workflow code: - - A create and a describe run in a Local Activity of the SDK. The Workflow - and Activity interceptors of the Worker see it, as they see every Local - Activity. - - An append and a close write as the Producer of the Workflow run, and the - Worker sets its Workflow Task attempt. + - SDK Core makes each append, close and read. A create and a describe run in + a Local Activity of the SDK, which the interceptors of the Worker see as + any other Local Activity. - An append is at-least-once. If a Workflow Task fails after its append, the next attempt of the task writes the batch again. - An outage of the Store gives Workflow code no error. The Workflow Task fails, and the server tries it again. - A call that Workflow code doesn't await before the Workflow ends may not happen. A Workflow that needs its close awaits it, as ``async with`` does. - - A call with no Store fails the Workflow Task, also when Workflow code catches - the error. - - A Worker reads the three limits when it starts. It refuses a new client with - other limits, as it refuses one with other Store names. - - A read with no ``max_records`` gives at most 256 Records in a page, and a - read with no ``max_bytes`` at most 4 MiB of them. A page has at most 16 MiB - of Records, also for a larger ``max_bytes``. + - A call with no Store fails the Workflow Task, also when Workflow code + catches the error. + - A Worker reads the three limits when it starts. It refuses a new client + with other limits, as it refuses one with other Store names. + - A page of a read has at most 256 Records and 4 MiB of Records by default, + and never more than 16 MiB. - A read fails with ``STREAM_ERROR_REASON_UNSUPPORTED`` for a Record over - :py:attr:`max_record_bytes`. So a reader needs a limit at least as large as - that of each writer of its Stream. + :py:attr:`max_record_bytes`. So a reader needs a limit at least as large + as that of each writer of its Stream. - A read that waits holds its Workflow Task. A Signal that comes meanwhile waits until the read has its page, or until the heartbeat of the task. - - A read of a Stream with no body type raises :exc:`TypeError` in the call, as - in client code. A body that isn't of the Stream's type fails the Workflow - Task, as an Activity result that can't be converted does. It fails the - Workflow if the failure exception types have the error of the conversion. + - A body that isn't of the Stream's type fails the Workflow Task, as an + Activity result that can't be converted does. .. warning:: This API is experimental and subject to change. diff --git a/temporalio/contrib/streams/_appender.py b/temporalio/contrib/streams/_appender.py index e18a494302..ba720f00b7 100644 --- a/temporalio/contrib/streams/_appender.py +++ b/temporalio/contrib/streams/_appender.py @@ -25,25 +25,20 @@ class BufferedAppender(Generic[BodyT]): 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. The appender writes the buffered Records as one batch, at most ``max_delay`` after the - first of them. One write runs at a time. Records appended during a write - wait for the next batch, and they keep their order. + first of them. One write runs at a time, and the Records keep their order. - Use it in ``async with``, which writes the remaining Records at the end of - the block, or await :py:meth:`flush` before the code that appends ends. - Otherwise the appender writes the Records that it still holds up to - ``max_delay`` later. For an Activity that has ended, that write still has the - Producer of its attempt, it can come after a write of the next attempt, and - nobody gets its error. + Use it in ``async with``, or await :py:meth:`flush` before the code that + appends ends. Otherwise the last Records are written up to ``max_delay`` + later, 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. If code appends faster than the - Store takes Records, the buffer grows with no bound, unless that code awaits - ``flush()`` from time to time. + ``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. If the write of the batch was cancelled, they raise - :exc:`RuntimeError`, and only a ``flush`` that waited for that write gets - the cancel. + 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. diff --git a/temporalio/contrib/streams/_producer.py b/temporalio/contrib/streams/_producer.py index 2bdb6cbfae..90bbf59617 100644 --- a/temporalio/contrib/streams/_producer.py +++ b/temporalio/contrib/streams/_producer.py @@ -19,16 +19,12 @@ def current_producer() -> Producer: An append or a close 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, which is the - sequence number of the Activity in the run unless the Workflow set one, and - the id of the Activity's ``ActivityTaskScheduled`` event. A run can use an - Activity id again after the first Activity with it has ended. The second - Activity is then a separate Producer, since its scheduled event is another - one. - - A Local Activity whose retry waits longer than its ``local_retry_threshold`` - runs again under a new sequence number. Each such retry then writes as a new - Producer, unless the Workflow set ``activity_id``. + 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 whose retry + waits longer than its ``local_retry_threshold`` runs under a new sequence + number, and then writes as a new Producer unless the Workflow set + ``activity_id``. Raises: RuntimeError: The caller isn't an Activity. diff --git a/temporalio/testing/_stream_store.py b/temporalio/testing/_stream_store.py index 156568ee90..fd74937688 100644 --- a/temporalio/testing/_stream_store.py +++ b/temporalio/testing/_stream_store.py @@ -45,15 +45,13 @@ class MemoryStreamStore(StreamStore): """Stream Store that keeps its Streams in the memory of this process. - It's for tests and local runs. It loses its Streams when the process ends, - and a client and a Worker see the same Streams only through the same - instance, in one event loop. + It's for tests and local runs. A client and a Worker see the same Streams + only through the same instance, in one event loop. The Store runs the checks of SDK Core on each request and on each response, also for a call of client or Activity code. So a call fails on it as it fails - on a Store package that runs those checks. An append, a close or a read of - Workflow code is then checked twice, by the Worker and by the Store. The - Store has no limit of a batch, since the limits are those of the + on a Store package that runs those checks. The Store has no limit of a batch, + since the limits are those of the :py:class:`temporalio.client.StreamConfig` of the caller. .. warning:: @@ -383,18 +381,11 @@ def _attempt(producer: Producer) -> _Attempt: """Return a value that orders the attempts of one Producer, as the attempt key of SDK Core does. - Its fields are these, in the order that two attempts compare by them: - - 1. The started event id of the Workflow Task - 2. The attempt number of that Workflow Task - 3. The seconds of the task's started time - 4. The nanoseconds of the task's started time - 5. The seconds of the Activity attempt's scheduled time - 6. The nanoseconds of the Activity attempt's scheduled time - 7. The attempt number of the Activity or the Local Activity - - 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. + 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 diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index 89059304eb..f99f33eabb 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -306,18 +306,6 @@ async def run_call() -> Any: created.append((result, store)) -@pytest.mark.parametrize( - "limit", ["max_record_bytes", "max_batch_bytes", "max_batch_records"] -) -def test_a_limit_below_one_raises(limit: str) -> None: - limits: Any = {limit: 0} - with pytest.raises( - ValueError, - match=rf"^StreamConfig\.{limit} must be greater than or equal to one\.$", - ): - StreamConfig([FaultStore()], **limits) - - async def test_a_stream_error_keeps_its_reason_on_every_path() -> None: converter = temporalio.converter.DataConverter.default for number in [*StreamErrorReason.values(), 99]: From ca55fc5b2039b0c2713940202e4d9dff9344505e Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Tue, 24 Nov 2026 15:53:53 -0700 Subject: [PATCH 18/50] Pin Core with the read limit of the Workflow Stream calls The pinned Core has no cancel of a read, and gives each read a time limit in its Workflow Task. The bridge sets that limit as `read_time` in place of `read_max_wait`. --- temporalio/bridge/sdk-core | 2 +- temporalio/bridge/src/streams.rs | 6 +++--- temporalio/bridge/streams.py | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index e493487937..78aff2d25e 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit e4934879378ea848d0031d9098e07b5164ab526a +Subproject commit 78aff2d25ed211de7e7263e49a8e14bb3dd05fdb diff --git a/temporalio/bridge/src/streams.rs b/temporalio/bridge/src/streams.rs index 2cd4631da9..5f5f77a09e 100644 --- a/temporalio/bridge/src/streams.rs +++ b/temporalio/bridge/src/streams.rs @@ -287,7 +287,7 @@ fn store_limits( pub(crate) struct WorkerStreams { limits: Option<(usize, usize, usize)>, stores: Vec<(String, Py)>, - read_max_wait_millis: Option, + read_time_millis: Option, } impl WorkerStreams { @@ -307,8 +307,8 @@ impl WorkerStreams { (name, Arc::new(runtime)) }); let mut runtimes = StreamRuntimes::new(runtimes); - if let Some(millis) = self.read_max_wait_millis { - runtimes.settings.read_max_wait = Duration::from_millis(millis); + if let Some(millis) = self.read_time_millis { + runtimes.settings.read_time = Some(Duration::from_millis(millis)); } Ok(runtimes) } diff --git a/temporalio/bridge/streams.py b/temporalio/bridge/streams.py index 5e870ec350..1c6823b507 100644 --- a/temporalio/bridge/streams.py +++ b/temporalio/bridge/streams.py @@ -42,7 +42,7 @@ class WorkerStreams: 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.""" - read_max_wait_millis: int | None + read_time_millis: int | None async def call_stream_store( From 215dc6d8ff13f4aa4d555693610de2c17ea8bf64 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Tue, 24 Nov 2026 15:53:53 -0700 Subject: [PATCH 19/50] Regenerate the bridge protos and the payload visitor at the new Core This is the output of `poe gen-protos` at the Core pin. The Stream commands and jobs come back with no cancel of a read, and each Stream result of a task completion has its activation index. --- temporalio/bridge/_visitor.py | 111 +++++++++ .../proto/activity_task/activity_task_pb2.py | 24 +- .../proto/activity_task/activity_task_pb2.pyi | 8 + .../proto/workflow_activation/__init__.py | 10 + .../workflow_activation_pb2.py | 119 +++++---- .../workflow_activation_pb2.pyi | 233 ++++++++---------- .../proto/workflow_commands/__init__.py | 6 + .../workflow_commands_pb2.py | 143 ++++++----- .../workflow_commands_pb2.pyi | 196 ++++----------- 9 files changed, 442 insertions(+), 408 deletions(-) diff --git a/temporalio/bridge/_visitor.py b/temporalio/bridge/_visitor.py index ead09a986f..4b02edbc65 100644 --- a/temporalio/bridge/_visitor.py +++ b/temporalio/bridge/_visitor.py @@ -308,6 +308,38 @@ async def _visit_coresdk_workflow_activation_ResolveNexusOperation( if o.HasField("result"): await self._visit_coresdk_nexus_NexusOperationResult(fs, o.result) + async def _visit_temporal_api_stream_v1_StreamRecord( + self, fs: VisitorFunctions, o: Any + ): + if o.HasField("body"): + await self._visit_temporal_api_common_v1_Payload(fs, o.body) + + async def _visit_coresdk_workflow_activation_StreamPage( + self, fs: VisitorFunctions, o: Any + ): + for v in o.records: + await self._visit_temporal_api_stream_v1_StreamRecord(fs, v) + + async def _visit_coresdk_workflow_activation_ResolveStreamRead( + self, fs: VisitorFunctions, o: Any + ): + if o.HasField("page"): + await self._visit_coresdk_workflow_activation_StreamPage(fs, o.page) + elif o.HasField("failed"): + await self._visit_temporal_api_failure_v1_Failure(fs, o.failed) + + async def _visit_coresdk_workflow_activation_ResolveStreamAppend( + self, fs: VisitorFunctions, o: Any + ): + if o.HasField("failed"): + await self._visit_temporal_api_failure_v1_Failure(fs, o.failed) + + async def _visit_coresdk_workflow_activation_ResolveStreamClose( + self, fs: VisitorFunctions, o: Any + ): + if o.HasField("failed"): + await self._visit_temporal_api_failure_v1_Failure(fs, o.failed) + async def _visit_coresdk_workflow_activation_WorkflowActivationJob( self, fs: VisitorFunctions, o: Any ): @@ -353,6 +385,18 @@ async def _visit_coresdk_workflow_activation_WorkflowActivationJob( await self._visit_coresdk_workflow_activation_ResolveNexusOperation( fs, o.resolve_nexus_operation ) + elif o.HasField("resolve_stream_read"): + await self._visit_coresdk_workflow_activation_ResolveStreamRead( + fs, o.resolve_stream_read + ) + elif o.HasField("resolve_stream_append"): + await self._visit_coresdk_workflow_activation_ResolveStreamAppend( + fs, o.resolve_stream_append + ) + elif o.HasField("resolve_stream_close"): + await self._visit_coresdk_workflow_activation_ResolveStreamClose( + fs, o.resolve_stream_close + ) async def _visit_coresdk_workflow_activation_WorkflowActivation( self, fs: VisitorFunctions, o: Any @@ -492,6 +536,11 @@ async def _visit_coresdk_workflow_commands_ScheduleNexusOperation( if o.HasField("input"): await self._visit_nexus_operation_input_payload(fs, o.input) + async def _visit_coresdk_workflow_commands_AppendToStream( + self, fs: VisitorFunctions, o: Any + ): + await self._visit_payload_container(fs, o.bodies) + async def _visit_coresdk_workflow_commands_WorkflowCommand( self, fs: VisitorFunctions, o: Any ): @@ -551,6 +600,10 @@ async def _visit_coresdk_workflow_commands_WorkflowCommand( await self._visit_coresdk_workflow_commands_ScheduleNexusOperation( fs, o.schedule_nexus_operation ) + elif o.HasField("append_to_stream"): + await self._visit_coresdk_workflow_commands_AppendToStream( + fs, o.append_to_stream + ) async def _visit_coresdk_workflow_completion_Success( self, fs: VisitorFunctions, o: Any @@ -639,6 +692,64 @@ async def _visit_temporal_api_notificationservice_v1_OnCompleteResponse( ) -> None: pass + async def _visit_temporal_api_streamservice_v1_CreateStreamRequest( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_streamservice_v1_CreateStreamResponse( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_stream_v1_AppendRecord( + self, fs: VisitorFunctions, o: Any + ): + if o.HasField("body"): + await self._visit_temporal_api_common_v1_Payload(fs, o.body) + + async def _visit_temporal_api_streamservice_v1_AppendRecordsRequest( + self, fs: VisitorFunctions, o: Any + ): + for v in o.records: + await self._visit_temporal_api_stream_v1_AppendRecord(fs, v) + + async def _visit_temporal_api_streamservice_v1_AppendRecordsResponse( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_streamservice_v1_CloseStreamRequest( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_streamservice_v1_CloseStreamResponse( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_streamservice_v1_ReadRecordsRequest( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_streamservice_v1_ReadRecordsResponse( + self, fs: VisitorFunctions, o: Any + ): + for v in o.records: + await self._visit_temporal_api_stream_v1_StreamRecord(fs, v) + + async def _visit_temporal_api_streamservice_v1_DescribeStreamRequest( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_streamservice_v1_DescribeStreamResponse( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + async def _visit_temporal_api_common_v1_Header(self, fs: VisitorFunctions, o: Any): for v in o.fields.values(): await self._visit_temporal_api_common_v1_Payload(fs, v) diff --git a/temporalio/bridge/proto/activity_task/activity_task_pb2.py b/temporalio/bridge/proto/activity_task/activity_task_pb2.py index 25233f5241..fd2ce8c211 100644 --- a/temporalio/bridge/proto/activity_task/activity_task_pb2.py +++ b/temporalio/bridge/proto/activity_task/activity_task_pb2.py @@ -27,7 +27,7 @@ ) DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n3temporal/sdk/core/activity_task/activity_task.proto\x12\x15\x63oresdk.activity_task\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a$temporal/api/common/v1/message.proto\x1a#temporal/api/nexus/v1/message.proto\x1a%temporal/sdk/core/common/common.proto"\x8d\x01\n\x0c\x41\x63tivityTask\x12\x12\n\ntask_token\x18\x01 \x01(\x0c\x12-\n\x05start\x18\x03 \x01(\x0b\x32\x1c.coresdk.activity_task.StartH\x00\x12/\n\x06\x63\x61ncel\x18\x04 \x01(\x0b\x32\x1d.coresdk.activity_task.CancelH\x00\x42\t\n\x07variant"\xdb\x08\n\x05Start\x12\x1a\n\x12workflow_namespace\x18\x01 \x01(\t\x12\x15\n\rworkflow_type\x18\x02 \x01(\t\x12\x45\n\x12workflow_execution\x18\x03 \x01(\x0b\x32).temporal.api.common.v1.WorkflowExecution\x12\x13\n\x0b\x61\x63tivity_id\x18\x04 \x01(\t\x12\x15\n\ractivity_type\x18\x05 \x01(\t\x12\x45\n\rheader_fields\x18\x06 \x03(\x0b\x32..coresdk.activity_task.Start.HeaderFieldsEntry\x12.\n\x05input\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12:\n\x11heartbeat_details\x18\x08 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x32\n\x0escheduled_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x42\n\x1e\x63urrent_attempt_scheduled_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x30\n\x0cstarted_time\x18\x0b \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07\x61ttempt\x18\x0c \x01(\r\x12<\n\x19schedule_to_close_timeout\x18\r \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\x0e \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x34\n\x11heartbeat_timeout\x18\x0f \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x10 \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x32\n\x08priority\x18\x12 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12\x10\n\x08is_local\x18\x11 \x01(\x08\x12\x0e\n\x06run_id\x18\x13 \x01(\t\x12\x65\n&propagated_nexus_serialization_context\x18\x14 \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x12\x41\n\rworkflow_task\x18\x15 \x01(\x0b\x32*.coresdk.activity_task.WorkflowTaskAttempt\x1aT\n\x11HeaderFieldsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x80\x02\n\x13WorkflowTaskAttempt\x12\x18\n\x10started_event_id\x18\x01 \x01(\x03\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\r\x12\x30\n\x0cstarted_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12!\n\x19previous_started_event_id\x18\x04 \x01(\x03\x12\x14\n\x0c\x66\x61iled_tasks\x18\x05 \x03(\x03\x12\x18\n\x10previous_attempt\x18\x06 \x01(\r\x12\x39\n\x15previous_started_time\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"\x8a\x01\n\x06\x43\x61ncel\x12;\n\x06reason\x18\x01 \x01(\x0e\x32+.coresdk.activity_task.ActivityCancelReason\x12\x43\n\x07\x64\x65tails\x18\x02 \x01(\x0b\x32\x32.coresdk.activity_task.ActivityCancellationDetails"\xa0\x01\n\x1b\x41\x63tivityCancellationDetails\x12\x14\n\x0cis_not_found\x18\x01 \x01(\x08\x12\x14\n\x0cis_cancelled\x18\x02 \x01(\x08\x12\x11\n\tis_paused\x18\x03 \x01(\x08\x12\x14\n\x0cis_timed_out\x18\x04 \x01(\x08\x12\x1a\n\x12is_worker_shutdown\x18\x05 \x01(\x08\x12\x10\n\x08is_reset\x18\x06 \x01(\x08*o\n\x14\x41\x63tivityCancelReason\x12\r\n\tNOT_FOUND\x10\x00\x12\r\n\tCANCELLED\x10\x01\x12\r\n\tTIMED_OUT\x10\x02\x12\x13\n\x0fWORKER_SHUTDOWN\x10\x03\x12\n\n\x06PAUSED\x10\x04\x12\t\n\x05RESET\x10\x05\x42\x32\xea\x02/Temporalio::Internal::Bridge::Api::ActivityTaskb\x06proto3' + b'\n3temporal/sdk/core/activity_task/activity_task.proto\x12\x15\x63oresdk.activity_task\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a$temporal/api/common/v1/message.proto\x1a#temporal/api/nexus/v1/message.proto\x1a%temporal/sdk/core/common/common.proto"\x8d\x01\n\x0c\x41\x63tivityTask\x12\x12\n\ntask_token\x18\x01 \x01(\x0c\x12-\n\x05start\x18\x03 \x01(\x0b\x32\x1c.coresdk.activity_task.StartH\x00\x12/\n\x06\x63\x61ncel\x18\x04 \x01(\x0b\x32\x1d.coresdk.activity_task.CancelH\x00\x42\t\n\x07variant"\xf7\x08\n\x05Start\x12\x1a\n\x12workflow_namespace\x18\x01 \x01(\t\x12\x15\n\rworkflow_type\x18\x02 \x01(\t\x12\x45\n\x12workflow_execution\x18\x03 \x01(\x0b\x32).temporal.api.common.v1.WorkflowExecution\x12\x13\n\x0b\x61\x63tivity_id\x18\x04 \x01(\t\x12\x15\n\ractivity_type\x18\x05 \x01(\t\x12\x45\n\rheader_fields\x18\x06 \x03(\x0b\x32..coresdk.activity_task.Start.HeaderFieldsEntry\x12.\n\x05input\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12:\n\x11heartbeat_details\x18\x08 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x32\n\x0escheduled_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x42\n\x1e\x63urrent_attempt_scheduled_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x30\n\x0cstarted_time\x18\x0b \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07\x61ttempt\x18\x0c \x01(\r\x12<\n\x19schedule_to_close_timeout\x18\r \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\x0e \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x34\n\x11heartbeat_timeout\x18\x0f \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x10 \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x32\n\x08priority\x18\x12 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12\x10\n\x08is_local\x18\x11 \x01(\x08\x12\x0e\n\x06run_id\x18\x13 \x01(\t\x12\x65\n&propagated_nexus_serialization_context\x18\x14 \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x12\x41\n\rworkflow_task\x18\x15 \x01(\x0b\x32*.coresdk.activity_task.WorkflowTaskAttempt\x12\x1a\n\x12scheduled_event_id\x18\x16 \x01(\x03\x1aT\n\x11HeaderFieldsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x80\x02\n\x13WorkflowTaskAttempt\x12\x18\n\x10started_event_id\x18\x01 \x01(\x03\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\r\x12\x30\n\x0cstarted_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12!\n\x19previous_started_event_id\x18\x04 \x01(\x03\x12\x14\n\x0c\x66\x61iled_tasks\x18\x05 \x03(\x03\x12\x18\n\x10previous_attempt\x18\x06 \x01(\r\x12\x39\n\x15previous_started_time\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"\x8a\x01\n\x06\x43\x61ncel\x12;\n\x06reason\x18\x01 \x01(\x0e\x32+.coresdk.activity_task.ActivityCancelReason\x12\x43\n\x07\x64\x65tails\x18\x02 \x01(\x0b\x32\x32.coresdk.activity_task.ActivityCancellationDetails"\xa0\x01\n\x1b\x41\x63tivityCancellationDetails\x12\x14\n\x0cis_not_found\x18\x01 \x01(\x08\x12\x14\n\x0cis_cancelled\x18\x02 \x01(\x08\x12\x11\n\tis_paused\x18\x03 \x01(\x08\x12\x14\n\x0cis_timed_out\x18\x04 \x01(\x08\x12\x1a\n\x12is_worker_shutdown\x18\x05 \x01(\x08\x12\x10\n\x08is_reset\x18\x06 \x01(\x08*o\n\x14\x41\x63tivityCancelReason\x12\r\n\tNOT_FOUND\x10\x00\x12\r\n\tCANCELLED\x10\x01\x12\r\n\tTIMED_OUT\x10\x02\x12\x13\n\x0fWORKER_SHUTDOWN\x10\x03\x12\n\n\x06PAUSED\x10\x04\x12\t\n\x05RESET\x10\x05\x42\x32\xea\x02/Temporalio::Internal::Bridge::Api::ActivityTaskb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -39,18 +39,18 @@ ) _START_HEADERFIELDSENTRY._options = None _START_HEADERFIELDSENTRY._serialized_options = b"8\001" - _ACTIVITYCANCELREASON._serialized_start = 2082 - _ACTIVITYCANCELREASON._serialized_end = 2193 + _ACTIVITYCANCELREASON._serialized_start = 2110 + _ACTIVITYCANCELREASON._serialized_end = 2221 _ACTIVITYTASK._serialized_start = 258 _ACTIVITYTASK._serialized_end = 399 _START._serialized_start = 402 - _START._serialized_end = 1517 - _START_HEADERFIELDSENTRY._serialized_start = 1433 - _START_HEADERFIELDSENTRY._serialized_end = 1517 - _WORKFLOWTASKATTEMPT._serialized_start = 1520 - _WORKFLOWTASKATTEMPT._serialized_end = 1776 - _CANCEL._serialized_start = 1779 - _CANCEL._serialized_end = 1917 - _ACTIVITYCANCELLATIONDETAILS._serialized_start = 1920 - _ACTIVITYCANCELLATIONDETAILS._serialized_end = 2080 + _START._serialized_end = 1545 + _START_HEADERFIELDSENTRY._serialized_start = 1461 + _START_HEADERFIELDSENTRY._serialized_end = 1545 + _WORKFLOWTASKATTEMPT._serialized_start = 1548 + _WORKFLOWTASKATTEMPT._serialized_end = 1804 + _CANCEL._serialized_start = 1807 + _CANCEL._serialized_end = 1945 + _ACTIVITYCANCELLATIONDETAILS._serialized_start = 1948 + _ACTIVITYCANCELLATIONDETAILS._serialized_end = 2108 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/activity_task/activity_task_pb2.pyi b/temporalio/bridge/proto/activity_task/activity_task_pb2.pyi index 345b0a6b1e..63b1711bf8 100644 --- a/temporalio/bridge/proto/activity_task/activity_task_pb2.pyi +++ b/temporalio/bridge/proto/activity_task/activity_task_pb2.pyi @@ -167,6 +167,7 @@ class Start(google.protobuf.message.Message): RUN_ID_FIELD_NUMBER: builtins.int PROPAGATED_NEXUS_SERIALIZATION_CONTEXT_FIELD_NUMBER: builtins.int WORKFLOW_TASK_FIELD_NUMBER: builtins.int + SCHEDULED_EVENT_ID_FIELD_NUMBER: builtins.int workflow_namespace: builtins.str """The namespace the workflow lives in""" workflow_type: builtins.str @@ -182,6 +183,10 @@ class Start(google.protobuf.message.Message): """ run_id: builtins.str """Run ID of this activity execution. Only set for standalone activities.""" + scheduled_event_id: builtins.int + """For an activity that a workflow scheduled, the event id of its ActivityTaskScheduled event. + 0 for a local activity, for a standalone activity, and when Core can't read it. + """ @property def workflow_execution( self, @@ -294,6 +299,7 @@ class Start(google.protobuf.message.Message): propagated_nexus_serialization_context: temporalio.api.nexus.v1.message_pb2.PropagatedSerializationContext | None = ..., workflow_task: global___WorkflowTaskAttempt | None = ..., + scheduled_event_id: builtins.int = ..., ) -> None: ... def HasField( self, @@ -353,6 +359,8 @@ class Start(google.protobuf.message.Message): b"run_id", "schedule_to_close_timeout", b"schedule_to_close_timeout", + "scheduled_event_id", + b"scheduled_event_id", "scheduled_time", b"scheduled_time", "start_to_close_timeout", diff --git a/temporalio/bridge/proto/workflow_activation/__init__.py b/temporalio/bridge/proto/workflow_activation/__init__.py index 5c178e2185..6db42d326e 100644 --- a/temporalio/bridge/proto/workflow_activation/__init__.py +++ b/temporalio/bridge/proto/workflow_activation/__init__.py @@ -16,7 +16,12 @@ ResolveNexusOperationStart, ResolveRequestCancelExternalWorkflow, ResolveSignalExternalWorkflow, + ResolveStreamAppend, + ResolveStreamClose, + ResolveStreamRead, SignalWorkflow, + StreamAppended, + StreamPage, UpdateRandomSeed, WorkflowActivation, WorkflowActivationJob, @@ -40,7 +45,12 @@ "ResolveNexusOperationStart", "ResolveRequestCancelExternalWorkflow", "ResolveSignalExternalWorkflow", + "ResolveStreamAppend", + "ResolveStreamClose", + "ResolveStreamRead", "SignalWorkflow", + "StreamAppended", + "StreamPage", "UpdateRandomSeed", "WorkflowActivation", "WorkflowActivationJob", diff --git a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py index 589119c72b..cfa0eacff1 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py @@ -32,6 +32,9 @@ from temporalio.api.nexus.v1 import ( message_pb2 as temporal_dot_api_dot_nexus_dot_v1_dot_message__pb2, ) +from temporalio.api.stream.v1 import ( + message_pb2 as temporal_dot_api_dot_stream_dot_v1_dot_message__pb2, +) from temporalio.api.update.v1 import ( message_pb2 as temporal_dot_api_dot_update_dot_v1_dot_message__pb2, ) @@ -49,7 +52,7 @@ ) DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n?temporal/sdk/core/workflow_activation/workflow_activation.proto\x12\x1b\x63oresdk.workflow_activation\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a%temporal/api/failure/v1/message.proto\x1a#temporal/api/nexus/v1/message.proto\x1a$temporal/api/update/v1/message.proto\x1a$temporal/api/common/v1/message.proto\x1a(temporal/api/enums/v1/failed_cause.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a\x37temporal/sdk/core/activity_result/activity_result.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a%temporal/sdk/core/common/common.proto\x1a#temporal/sdk/core/nexus/nexus.proto"\xa2\x04\n\x12WorkflowActivation\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x14\n\x0cis_replaying\x18\x03 \x01(\x08\x12\x16\n\x0ehistory_length\x18\x04 \x01(\r\x12@\n\x04jobs\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.WorkflowActivationJob\x12 \n\x18\x61vailable_internal_flags\x18\x06 \x03(\r\x12\x1a\n\x12history_size_bytes\x18\x07 \x01(\x04\x12!\n\x19\x63ontinue_as_new_suggested\x18\x08 \x01(\x08\x12T\n#deployment_version_for_current_task\x18\t \x01(\x0b\x32\'.coresdk.common.WorkerDeploymentVersion\x12\x18\n\x10last_sdk_version\x18\n \x01(\t\x12Z\n\x1fsuggest_continue_as_new_reasons\x18\x0b \x03(\x0e\x32\x31.temporal.api.enums.v1.SuggestContinueAsNewReason\x12\x30\n(target_worker_deployment_version_changed\x18\x0c \x01(\x08"\xe0\n\n\x15WorkflowActivationJob\x12N\n\x13initialize_workflow\x18\x01 \x01(\x0b\x32/.coresdk.workflow_activation.InitializeWorkflowH\x00\x12<\n\nfire_timer\x18\x02 \x01(\x0b\x32&.coresdk.workflow_activation.FireTimerH\x00\x12K\n\x12update_random_seed\x18\x04 \x01(\x0b\x32-.coresdk.workflow_activation.UpdateRandomSeedH\x00\x12\x44\n\x0equery_workflow\x18\x05 \x01(\x0b\x32*.coresdk.workflow_activation.QueryWorkflowH\x00\x12\x46\n\x0f\x63\x61ncel_workflow\x18\x06 \x01(\x0b\x32+.coresdk.workflow_activation.CancelWorkflowH\x00\x12\x46\n\x0fsignal_workflow\x18\x07 \x01(\x0b\x32+.coresdk.workflow_activation.SignalWorkflowH\x00\x12H\n\x10resolve_activity\x18\x08 \x01(\x0b\x32,.coresdk.workflow_activation.ResolveActivityH\x00\x12G\n\x10notify_has_patch\x18\t \x01(\x0b\x32+.coresdk.workflow_activation.NotifyHasPatchH\x00\x12q\n&resolve_child_workflow_execution_start\x18\n \x01(\x0b\x32?.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartH\x00\x12\x66\n resolve_child_workflow_execution\x18\x0b \x01(\x0b\x32:.coresdk.workflow_activation.ResolveChildWorkflowExecutionH\x00\x12\x66\n resolve_signal_external_workflow\x18\x0c \x01(\x0b\x32:.coresdk.workflow_activation.ResolveSignalExternalWorkflowH\x00\x12u\n(resolve_request_cancel_external_workflow\x18\r \x01(\x0b\x32\x41.coresdk.workflow_activation.ResolveRequestCancelExternalWorkflowH\x00\x12:\n\tdo_update\x18\x0e \x01(\x0b\x32%.coresdk.workflow_activation.DoUpdateH\x00\x12`\n\x1dresolve_nexus_operation_start\x18\x0f \x01(\x0b\x32\x37.coresdk.workflow_activation.ResolveNexusOperationStartH\x00\x12U\n\x17resolve_nexus_operation\x18\x10 \x01(\x0b\x32\x32.coresdk.workflow_activation.ResolveNexusOperationH\x00\x12I\n\x11remove_from_cache\x18\x32 \x01(\x0b\x32,.coresdk.workflow_activation.RemoveFromCacheH\x00\x42\t\n\x07variant"\xe3\x0b\n\x12InitializeWorkflow\x12\x15\n\rworkflow_type\x18\x01 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x17\n\x0frandomness_seed\x18\x04 \x01(\x04\x12M\n\x07headers\x18\x05 \x03(\x0b\x32<.coresdk.workflow_activation.InitializeWorkflow.HeadersEntry\x12\x10\n\x08identity\x18\x06 \x01(\t\x12I\n\x14parent_workflow_info\x18\x07 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecution\x12=\n\x1aworkflow_execution_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14workflow_run_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\'\n\x1f\x63ontinued_from_execution_run_id\x18\x0b \x01(\t\x12J\n\x13\x63ontinued_initiator\x18\x0c \x01(\x0e\x32-.temporal.api.enums.v1.ContinueAsNewInitiator\x12;\n\x11\x63ontinued_failure\x18\r \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12@\n\x16last_completion_result\x18\x0e \x01(\x0b\x32 .temporal.api.common.v1.Payloads\x12\x1e\n\x16\x66irst_execution_run_id\x18\x0f \x01(\t\x12\x39\n\x0cretry_policy\x18\x10 \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x0f\n\x07\x61ttempt\x18\x11 \x01(\x05\x12\x15\n\rcron_schedule\x18\x12 \x01(\t\x12\x46\n"workflow_execution_expiration_time\x18\x13 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x45\n"cron_schedule_to_schedule_interval\x18\x14 \x01(\x0b\x32\x19.google.protobuf.Duration\x12*\n\x04memo\x18\x15 \x01(\x0b\x32\x1c.temporal.api.common.v1.Memo\x12\x43\n\x11search_attributes\x18\x16 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12.\n\nstart_time\x18\x17 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12@\n\rroot_workflow\x18\x18 \x01(\x0b\x32).temporal.api.common.v1.WorkflowExecution\x12\x32\n\x08priority\x18\x19 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12!\n\x19original_execution_run_id\x18\x1a \x01(\t\x12\x65\n&propagated_nexus_serialization_context\x18\x1b \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x18\n\tFireTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r"m\n\x0fResolveActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12;\n\x06result\x18\x02 \x01(\x0b\x32+.coresdk.activity_result.ActivityResolution\x12\x10\n\x08is_local\x18\x03 \x01(\x08"\xd1\x02\n"ResolveChildWorkflowExecutionStart\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12[\n\tsucceeded\x18\x02 \x01(\x0b\x32\x46.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartSuccessH\x00\x12X\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32\x46.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartFailureH\x00\x12]\n\tcancelled\x18\x04 \x01(\x0b\x32H.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartCancelledH\x00\x42\x08\n\x06status";\n)ResolveChildWorkflowExecutionStartSuccess\x12\x0e\n\x06run_id\x18\x01 \x01(\t"\xa6\x01\n)ResolveChildWorkflowExecutionStartFailure\x12\x13\n\x0bworkflow_id\x18\x01 \x01(\t\x12\x15\n\rworkflow_type\x18\x02 \x01(\t\x12M\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32>.coresdk.child_workflow.StartChildWorkflowExecutionFailedCause"`\n+ResolveChildWorkflowExecutionStartCancelled\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"i\n\x1dResolveChildWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12;\n\x06result\x18\x02 \x01(\x0b\x32+.coresdk.child_workflow.ChildWorkflowResult"+\n\x10UpdateRandomSeed\x12\x17\n\x0frandomness_seed\x18\x01 \x01(\x04"\x84\x02\n\rQueryWorkflow\x12\x10\n\x08query_id\x18\x01 \x01(\t\x12\x12\n\nquery_type\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12H\n\x07headers\x18\x05 \x03(\x0b\x32\x37.coresdk.workflow_activation.QueryWorkflow.HeadersEntry\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01" \n\x0e\x43\x61ncelWorkflow\x12\x0e\n\x06reason\x18\x01 \x01(\t"\xa1\x02\n\x0eSignalWorkflow\x12\x13\n\x0bsignal_name\x18\x01 \x01(\t\x12.\n\x05input\x18\x02 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x10\n\x08identity\x18\x03 \x01(\t\x12I\n\x07headers\x18\x05 \x03(\x0b\x32\x38.coresdk.workflow_activation.SignalWorkflow.HeadersEntry\x12\x1c\n\x14originating_event_id\x18\x06 \x01(\x03\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01""\n\x0eNotifyHasPatch\x12\x10\n\x08patch_id\x18\x01 \x01(\t"\xb1\x01\n\x1dResolveSignalExternalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x07\x66\x61ilure\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12P\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32\x41.temporal.api.enums.v1.SignalExternalWorkflowExecutionFailedCause"\xb8\x01\n$ResolveRequestCancelExternalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x07\x66\x61ilure\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12P\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32\x41.temporal.api.enums.v1.CancelExternalWorkflowExecutionFailedCause"\xb2\x03\n\x08\x44oUpdate\x12\n\n\x02id\x18\x01 \x01(\t\x12\x1c\n\x14protocol_instance_id\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12.\n\x05input\x18\x04 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x43\n\x07headers\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.DoUpdate.HeadersEntry\x12*\n\x04meta\x18\x06 \x01(\x0b\x32\x1c.temporal.api.update.v1.Meta\x12\x15\n\rrun_validator\x18\x07 \x01(\x08\x12\x65\n&propagated_nexus_serialization_context\x18\x08 \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x9a\x01\n\x1aResolveNexusOperationStart\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x19\n\x0foperation_token\x18\x02 \x01(\tH\x00\x12\x16\n\x0cstarted_sync\x18\x03 \x01(\x08H\x00\x12\x32\n\x06\x66\x61iled\x18\x04 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status"Y\n\x15ResolveNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x33\n\x06result\x18\x02 \x01(\x0b\x32#.coresdk.nexus.NexusOperationResult"\xe0\x02\n\x0fRemoveFromCache\x12\x0f\n\x07message\x18\x01 \x01(\t\x12K\n\x06reason\x18\x02 \x01(\x0e\x32;.coresdk.workflow_activation.RemoveFromCache.EvictionReason"\xee\x01\n\x0e\x45victionReason\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nCACHE_FULL\x10\x01\x12\x0e\n\nCACHE_MISS\x10\x02\x12\x12\n\x0eNONDETERMINISM\x10\x03\x12\r\n\tLANG_FAIL\x10\x04\x12\x12\n\x0eLANG_REQUESTED\x10\x05\x12\x12\n\x0eTASK_NOT_FOUND\x10\x06\x12\x15\n\x11UNHANDLED_COMMAND\x10\x07\x12\t\n\x05\x46\x41TAL\x10\x08\x12\x1f\n\x1bPAGINATION_OR_HISTORY_FETCH\x10\t\x12\x1d\n\x19WORKFLOW_EXECUTION_ENDING\x10\nB8\xea\x02\x35Temporalio::Internal::Bridge::Api::WorkflowActivationb\x06proto3' + b'\n?temporal/sdk/core/workflow_activation/workflow_activation.proto\x12\x1b\x63oresdk.workflow_activation\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a%temporal/api/failure/v1/message.proto\x1a#temporal/api/nexus/v1/message.proto\x1a$temporal/api/update/v1/message.proto\x1a$temporal/api/common/v1/message.proto\x1a$temporal/api/stream/v1/message.proto\x1a(temporal/api/enums/v1/failed_cause.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a\x37temporal/sdk/core/activity_result/activity_result.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a%temporal/sdk/core/common/common.proto\x1a#temporal/sdk/core/nexus/nexus.proto"\xa2\x04\n\x12WorkflowActivation\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x14\n\x0cis_replaying\x18\x03 \x01(\x08\x12\x16\n\x0ehistory_length\x18\x04 \x01(\r\x12@\n\x04jobs\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.WorkflowActivationJob\x12 \n\x18\x61vailable_internal_flags\x18\x06 \x03(\r\x12\x1a\n\x12history_size_bytes\x18\x07 \x01(\x04\x12!\n\x19\x63ontinue_as_new_suggested\x18\x08 \x01(\x08\x12T\n#deployment_version_for_current_task\x18\t \x01(\x0b\x32\'.coresdk.common.WorkerDeploymentVersion\x12\x18\n\x10last_sdk_version\x18\n \x01(\t\x12Z\n\x1fsuggest_continue_as_new_reasons\x18\x0b \x03(\x0e\x32\x31.temporal.api.enums.v1.SuggestContinueAsNewReason\x12\x30\n(target_worker_deployment_version_changed\x18\x0c \x01(\x08"\xd3\x0c\n\x15WorkflowActivationJob\x12N\n\x13initialize_workflow\x18\x01 \x01(\x0b\x32/.coresdk.workflow_activation.InitializeWorkflowH\x00\x12<\n\nfire_timer\x18\x02 \x01(\x0b\x32&.coresdk.workflow_activation.FireTimerH\x00\x12K\n\x12update_random_seed\x18\x04 \x01(\x0b\x32-.coresdk.workflow_activation.UpdateRandomSeedH\x00\x12\x44\n\x0equery_workflow\x18\x05 \x01(\x0b\x32*.coresdk.workflow_activation.QueryWorkflowH\x00\x12\x46\n\x0f\x63\x61ncel_workflow\x18\x06 \x01(\x0b\x32+.coresdk.workflow_activation.CancelWorkflowH\x00\x12\x46\n\x0fsignal_workflow\x18\x07 \x01(\x0b\x32+.coresdk.workflow_activation.SignalWorkflowH\x00\x12H\n\x10resolve_activity\x18\x08 \x01(\x0b\x32,.coresdk.workflow_activation.ResolveActivityH\x00\x12G\n\x10notify_has_patch\x18\t \x01(\x0b\x32+.coresdk.workflow_activation.NotifyHasPatchH\x00\x12q\n&resolve_child_workflow_execution_start\x18\n \x01(\x0b\x32?.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartH\x00\x12\x66\n resolve_child_workflow_execution\x18\x0b \x01(\x0b\x32:.coresdk.workflow_activation.ResolveChildWorkflowExecutionH\x00\x12\x66\n resolve_signal_external_workflow\x18\x0c \x01(\x0b\x32:.coresdk.workflow_activation.ResolveSignalExternalWorkflowH\x00\x12u\n(resolve_request_cancel_external_workflow\x18\r \x01(\x0b\x32\x41.coresdk.workflow_activation.ResolveRequestCancelExternalWorkflowH\x00\x12:\n\tdo_update\x18\x0e \x01(\x0b\x32%.coresdk.workflow_activation.DoUpdateH\x00\x12`\n\x1dresolve_nexus_operation_start\x18\x0f \x01(\x0b\x32\x37.coresdk.workflow_activation.ResolveNexusOperationStartH\x00\x12U\n\x17resolve_nexus_operation\x18\x10 \x01(\x0b\x32\x32.coresdk.workflow_activation.ResolveNexusOperationH\x00\x12M\n\x13resolve_stream_read\x18\x11 \x01(\x0b\x32..coresdk.workflow_activation.ResolveStreamReadH\x00\x12Q\n\x15resolve_stream_append\x18\x12 \x01(\x0b\x32\x30.coresdk.workflow_activation.ResolveStreamAppendH\x00\x12O\n\x14resolve_stream_close\x18\x13 \x01(\x0b\x32/.coresdk.workflow_activation.ResolveStreamCloseH\x00\x12I\n\x11remove_from_cache\x18\x32 \x01(\x0b\x32,.coresdk.workflow_activation.RemoveFromCacheH\x00\x42\t\n\x07variant"\xe3\x0b\n\x12InitializeWorkflow\x12\x15\n\rworkflow_type\x18\x01 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x17\n\x0frandomness_seed\x18\x04 \x01(\x04\x12M\n\x07headers\x18\x05 \x03(\x0b\x32<.coresdk.workflow_activation.InitializeWorkflow.HeadersEntry\x12\x10\n\x08identity\x18\x06 \x01(\t\x12I\n\x14parent_workflow_info\x18\x07 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecution\x12=\n\x1aworkflow_execution_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14workflow_run_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\'\n\x1f\x63ontinued_from_execution_run_id\x18\x0b \x01(\t\x12J\n\x13\x63ontinued_initiator\x18\x0c \x01(\x0e\x32-.temporal.api.enums.v1.ContinueAsNewInitiator\x12;\n\x11\x63ontinued_failure\x18\r \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12@\n\x16last_completion_result\x18\x0e \x01(\x0b\x32 .temporal.api.common.v1.Payloads\x12\x1e\n\x16\x66irst_execution_run_id\x18\x0f \x01(\t\x12\x39\n\x0cretry_policy\x18\x10 \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x0f\n\x07\x61ttempt\x18\x11 \x01(\x05\x12\x15\n\rcron_schedule\x18\x12 \x01(\t\x12\x46\n"workflow_execution_expiration_time\x18\x13 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x45\n"cron_schedule_to_schedule_interval\x18\x14 \x01(\x0b\x32\x19.google.protobuf.Duration\x12*\n\x04memo\x18\x15 \x01(\x0b\x32\x1c.temporal.api.common.v1.Memo\x12\x43\n\x11search_attributes\x18\x16 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12.\n\nstart_time\x18\x17 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12@\n\rroot_workflow\x18\x18 \x01(\x0b\x32).temporal.api.common.v1.WorkflowExecution\x12\x32\n\x08priority\x18\x19 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12!\n\x19original_execution_run_id\x18\x1a \x01(\t\x12\x65\n&propagated_nexus_serialization_context\x18\x1b \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x18\n\tFireTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r"m\n\x0fResolveActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12;\n\x06result\x18\x02 \x01(\x0b\x32+.coresdk.activity_result.ActivityResolution\x12\x10\n\x08is_local\x18\x03 \x01(\x08"\xd1\x02\n"ResolveChildWorkflowExecutionStart\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12[\n\tsucceeded\x18\x02 \x01(\x0b\x32\x46.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartSuccessH\x00\x12X\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32\x46.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartFailureH\x00\x12]\n\tcancelled\x18\x04 \x01(\x0b\x32H.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartCancelledH\x00\x42\x08\n\x06status";\n)ResolveChildWorkflowExecutionStartSuccess\x12\x0e\n\x06run_id\x18\x01 \x01(\t"\xa6\x01\n)ResolveChildWorkflowExecutionStartFailure\x12\x13\n\x0bworkflow_id\x18\x01 \x01(\t\x12\x15\n\rworkflow_type\x18\x02 \x01(\t\x12M\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32>.coresdk.child_workflow.StartChildWorkflowExecutionFailedCause"`\n+ResolveChildWorkflowExecutionStartCancelled\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"i\n\x1dResolveChildWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12;\n\x06result\x18\x02 \x01(\x0b\x32+.coresdk.child_workflow.ChildWorkflowResult"+\n\x10UpdateRandomSeed\x12\x17\n\x0frandomness_seed\x18\x01 \x01(\x04"\x84\x02\n\rQueryWorkflow\x12\x10\n\x08query_id\x18\x01 \x01(\t\x12\x12\n\nquery_type\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12H\n\x07headers\x18\x05 \x03(\x0b\x32\x37.coresdk.workflow_activation.QueryWorkflow.HeadersEntry\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01" \n\x0e\x43\x61ncelWorkflow\x12\x0e\n\x06reason\x18\x01 \x01(\t"\xa1\x02\n\x0eSignalWorkflow\x12\x13\n\x0bsignal_name\x18\x01 \x01(\t\x12.\n\x05input\x18\x02 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x10\n\x08identity\x18\x03 \x01(\t\x12I\n\x07headers\x18\x05 \x03(\x0b\x32\x38.coresdk.workflow_activation.SignalWorkflow.HeadersEntry\x12\x1c\n\x14originating_event_id\x18\x06 \x01(\x03\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01""\n\x0eNotifyHasPatch\x12\x10\n\x08patch_id\x18\x01 \x01(\t"\xb1\x01\n\x1dResolveSignalExternalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x07\x66\x61ilure\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12P\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32\x41.temporal.api.enums.v1.SignalExternalWorkflowExecutionFailedCause"\xb8\x01\n$ResolveRequestCancelExternalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x07\x66\x61ilure\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12P\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32\x41.temporal.api.enums.v1.CancelExternalWorkflowExecutionFailedCause"\xb2\x03\n\x08\x44oUpdate\x12\n\n\x02id\x18\x01 \x01(\t\x12\x1c\n\x14protocol_instance_id\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12.\n\x05input\x18\x04 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x43\n\x07headers\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.DoUpdate.HeadersEntry\x12*\n\x04meta\x18\x06 \x01(\x0b\x32\x1c.temporal.api.update.v1.Meta\x12\x15\n\rrun_validator\x18\x07 \x01(\x08\x12\x65\n&propagated_nexus_serialization_context\x18\x08 \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x9a\x01\n\x1aResolveNexusOperationStart\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x19\n\x0foperation_token\x18\x02 \x01(\tH\x00\x12\x16\n\x0cstarted_sync\x18\x03 \x01(\x08H\x00\x12\x32\n\x06\x66\x61iled\x18\x04 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status"Y\n\x15ResolveNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x33\n\x06result\x18\x02 \x01(\x0b\x32#.coresdk.nexus.NexusOperationResult"\xe0\x02\n\x0fRemoveFromCache\x12\x0f\n\x07message\x18\x01 \x01(\t\x12K\n\x06reason\x18\x02 \x01(\x0e\x32;.coresdk.workflow_activation.RemoveFromCache.EvictionReason"\xee\x01\n\x0e\x45victionReason\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nCACHE_FULL\x10\x01\x12\x0e\n\nCACHE_MISS\x10\x02\x12\x12\n\x0eNONDETERMINISM\x10\x03\x12\r\n\tLANG_FAIL\x10\x04\x12\x12\n\x0eLANG_REQUESTED\x10\x05\x12\x12\n\x0eTASK_NOT_FOUND\x10\x06\x12\x15\n\x11UNHANDLED_COMMAND\x10\x07\x12\t\n\x05\x46\x41TAL\x10\x08\x12\x1f\n\x1bPAGINATION_OR_HISTORY_FETCH\x10\t\x12\x1d\n\x19WORKFLOW_EXECUTION_ENDING\x10\n"\xa1\x01\n\x13ResolveStreamAppend\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12?\n\x08\x61ppended\x18\x02 \x01(\x0b\x32+.coresdk.workflow_activation.StreamAppendedH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status";\n\x0eStreamAppended\x12\x14\n\x0c\x66irst_offset\x18\x01 \x01(\x0c\x12\x13\n\x0blast_offset\x18\x02 \x01(\x0c"S\n\x12ResolveStreamClose\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x30\n\x06\x66\x61iled\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"\x97\x01\n\x11ResolveStreamRead\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x37\n\x04page\x18\x02 \x01(\x0b\x32\'.coresdk.workflow_activation.StreamPageH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status"f\n\nStreamPage\x12\x35\n\x07records\x18\x01 \x03(\x0b\x32$.temporal.api.stream.v1.StreamRecord\x12\x0c\n\x04\x64one\x18\x02 \x01(\x08\x12\x13\n\x0blast_offset\x18\x03 \x01(\x0c\x42\x38\xea\x02\x35Temporalio::Internal::Bridge::Api::WorkflowActivationb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -67,56 +70,66 @@ _SIGNALWORKFLOW_HEADERSENTRY._serialized_options = b"8\001" _DOUPDATE_HEADERSENTRY._options = None _DOUPDATE_HEADERSENTRY._serialized_options = b"8\001" - _WORKFLOWACTIVATION._serialized_start = 611 - _WORKFLOWACTIVATION._serialized_end = 1157 - _WORKFLOWACTIVATIONJOB._serialized_start = 1160 - _WORKFLOWACTIVATIONJOB._serialized_end = 2536 - _INITIALIZEWORKFLOW._serialized_start = 2539 - _INITIALIZEWORKFLOW._serialized_end = 4046 - _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_start = 3967 - _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_end = 4046 - _FIRETIMER._serialized_start = 4048 - _FIRETIMER._serialized_end = 4072 - _RESOLVEACTIVITY._serialized_start = 4074 - _RESOLVEACTIVITY._serialized_end = 4183 - _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_start = 4186 - _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_end = 4523 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_start = 4525 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_end = 4584 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_start = 4587 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_end = 4753 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_start = 4755 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_end = 4851 - _RESOLVECHILDWORKFLOWEXECUTION._serialized_start = 4853 - _RESOLVECHILDWORKFLOWEXECUTION._serialized_end = 4958 - _UPDATERANDOMSEED._serialized_start = 4960 - _UPDATERANDOMSEED._serialized_end = 5003 - _QUERYWORKFLOW._serialized_start = 5006 - _QUERYWORKFLOW._serialized_end = 5266 - _QUERYWORKFLOW_HEADERSENTRY._serialized_start = 3967 - _QUERYWORKFLOW_HEADERSENTRY._serialized_end = 4046 - _CANCELWORKFLOW._serialized_start = 5268 - _CANCELWORKFLOW._serialized_end = 5300 - _SIGNALWORKFLOW._serialized_start = 5303 - _SIGNALWORKFLOW._serialized_end = 5592 - _SIGNALWORKFLOW_HEADERSENTRY._serialized_start = 3967 - _SIGNALWORKFLOW_HEADERSENTRY._serialized_end = 4046 - _NOTIFYHASPATCH._serialized_start = 5594 - _NOTIFYHASPATCH._serialized_end = 5628 - _RESOLVESIGNALEXTERNALWORKFLOW._serialized_start = 5631 - _RESOLVESIGNALEXTERNALWORKFLOW._serialized_end = 5808 - _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_start = 5811 - _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_end = 5995 - _DOUPDATE._serialized_start = 5998 - _DOUPDATE._serialized_end = 6432 - _DOUPDATE_HEADERSENTRY._serialized_start = 3967 - _DOUPDATE_HEADERSENTRY._serialized_end = 4046 - _RESOLVENEXUSOPERATIONSTART._serialized_start = 6435 - _RESOLVENEXUSOPERATIONSTART._serialized_end = 6589 - _RESOLVENEXUSOPERATION._serialized_start = 6591 - _RESOLVENEXUSOPERATION._serialized_end = 6680 - _REMOVEFROMCACHE._serialized_start = 6683 - _REMOVEFROMCACHE._serialized_end = 7035 - _REMOVEFROMCACHE_EVICTIONREASON._serialized_start = 6797 - _REMOVEFROMCACHE_EVICTIONREASON._serialized_end = 7035 + _WORKFLOWACTIVATION._serialized_start = 649 + _WORKFLOWACTIVATION._serialized_end = 1195 + _WORKFLOWACTIVATIONJOB._serialized_start = 1198 + _WORKFLOWACTIVATIONJOB._serialized_end = 2817 + _INITIALIZEWORKFLOW._serialized_start = 2820 + _INITIALIZEWORKFLOW._serialized_end = 4327 + _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_start = 4248 + _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_end = 4327 + _FIRETIMER._serialized_start = 4329 + _FIRETIMER._serialized_end = 4353 + _RESOLVEACTIVITY._serialized_start = 4355 + _RESOLVEACTIVITY._serialized_end = 4464 + _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_start = 4467 + _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_end = 4804 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_start = 4806 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_end = 4865 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_start = 4868 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_end = 5034 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_start = 5036 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_end = 5132 + _RESOLVECHILDWORKFLOWEXECUTION._serialized_start = 5134 + _RESOLVECHILDWORKFLOWEXECUTION._serialized_end = 5239 + _UPDATERANDOMSEED._serialized_start = 5241 + _UPDATERANDOMSEED._serialized_end = 5284 + _QUERYWORKFLOW._serialized_start = 5287 + _QUERYWORKFLOW._serialized_end = 5547 + _QUERYWORKFLOW_HEADERSENTRY._serialized_start = 4248 + _QUERYWORKFLOW_HEADERSENTRY._serialized_end = 4327 + _CANCELWORKFLOW._serialized_start = 5549 + _CANCELWORKFLOW._serialized_end = 5581 + _SIGNALWORKFLOW._serialized_start = 5584 + _SIGNALWORKFLOW._serialized_end = 5873 + _SIGNALWORKFLOW_HEADERSENTRY._serialized_start = 4248 + _SIGNALWORKFLOW_HEADERSENTRY._serialized_end = 4327 + _NOTIFYHASPATCH._serialized_start = 5875 + _NOTIFYHASPATCH._serialized_end = 5909 + _RESOLVESIGNALEXTERNALWORKFLOW._serialized_start = 5912 + _RESOLVESIGNALEXTERNALWORKFLOW._serialized_end = 6089 + _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_start = 6092 + _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_end = 6276 + _DOUPDATE._serialized_start = 6279 + _DOUPDATE._serialized_end = 6713 + _DOUPDATE_HEADERSENTRY._serialized_start = 4248 + _DOUPDATE_HEADERSENTRY._serialized_end = 4327 + _RESOLVENEXUSOPERATIONSTART._serialized_start = 6716 + _RESOLVENEXUSOPERATIONSTART._serialized_end = 6870 + _RESOLVENEXUSOPERATION._serialized_start = 6872 + _RESOLVENEXUSOPERATION._serialized_end = 6961 + _REMOVEFROMCACHE._serialized_start = 6964 + _REMOVEFROMCACHE._serialized_end = 7316 + _REMOVEFROMCACHE_EVICTIONREASON._serialized_start = 7078 + _REMOVEFROMCACHE_EVICTIONREASON._serialized_end = 7316 + _RESOLVESTREAMAPPEND._serialized_start = 7319 + _RESOLVESTREAMAPPEND._serialized_end = 7480 + _STREAMAPPENDED._serialized_start = 7482 + _STREAMAPPENDED._serialized_end = 7541 + _RESOLVESTREAMCLOSE._serialized_start = 7543 + _RESOLVESTREAMCLOSE._serialized_end = 7626 + _RESOLVESTREAMREAD._serialized_start = 7629 + _RESOLVESTREAMREAD._serialized_end = 7780 + _STREAMPAGE._serialized_start = 7782 + _STREAMPAGE._serialized_end = 7884 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi index 20df9b2d5a..baf4ceea26 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi @@ -13,7 +13,6 @@ import typing import google.protobuf.descriptor import google.protobuf.duration_pb2 -import google.protobuf.empty_pb2 import google.protobuf.internal.containers import google.protobuf.internal.enum_type_wrapper import google.protobuf.message @@ -67,10 +66,9 @@ class WorkflowActivation(google.protobuf.message.Message): in that same activation (prime example: cancelling not-wait-for-cancel activities). So, we do this to ensure the LA resolution happens after that cancel (or whatever else it may be) as it normally would have when executing. - * The results of Stream calls go after the local activity resolutions, because a replay also - scans ahead for their marker. Appends go first, then closes, then reads, and each kind is in - `seq` order. When a replay gives the results of several activations in one, the Stream results - keep the order of those activations, after all local activity resolutions. + * Stream results go after the local activity resolutions, because a replay scans ahead for them + too. Appends go first, then closes, then reads, each in `seq` order. If a replay gives several + activations in one, the Stream results keep the order of those activations. * Queries always go last (and, in fact, always come in their own activation) * Evictions also always come in their own activation @@ -1685,129 +1683,16 @@ class RemoveFromCache(google.protobuf.message.Message): global___RemoveFromCache = RemoveFromCache -@typing.final -class ResolveStreamRead(google.protobuf.message.Message): - """The result of a `ReadStream`. A read gets at most one, and a read that lang cancelled gets one - too. It gets none only in the four cases that `ReadStream` lists. The activation rules of - `ResolveStreamAppend` apply to it too. - """ - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - SEQ_FIELD_NUMBER: builtins.int - PAGE_FIELD_NUMBER: builtins.int - FAILED_FIELD_NUMBER: builtins.int - CANCELLED_FIELD_NUMBER: builtins.int - seq: builtins.int - """The `seq` of the `ReadStream`.""" - @property - def page(self) -> global___StreamPage: ... - @property - def failed(self) -> temporalio.api.failure.v1.message_pb2.Failure: - """The failure of the read. It has the parts of the `failed` of a `ResolveStreamAppend`.""" - - @property - def cancelled(self) -> google.protobuf.empty_pb2.Empty: - """Core got a `RequestCancelStreamRead` for the read before lang got a job for it. The job - comes in the next activation after the cancel, or in the next Workflow Task if the task - in hand completes first. `RequestCancelStreamRead` says when a replay gives it. - """ - - def __init__( - self, - *, - seq: builtins.int = ..., - page: global___StreamPage | None = ..., - failed: temporalio.api.failure.v1.message_pb2.Failure | None = ..., - cancelled: google.protobuf.empty_pb2.Empty | None = ..., - ) -> None: ... - def HasField( - self, - field_name: typing.Literal[ - "cancelled", - b"cancelled", - "failed", - b"failed", - "page", - b"page", - "status", - b"status", - ], - ) -> builtins.bool: ... - def ClearField( - self, - field_name: typing.Literal[ - "cancelled", - b"cancelled", - "failed", - b"failed", - "page", - b"page", - "seq", - b"seq", - "status", - b"status", - ], - ) -> None: ... - def WhichOneof( - self, oneof_group: typing.Literal["status", b"status"] - ) -> typing.Literal["page", "failed", "cancelled"] | None: ... - -global___ResolveStreamRead = ResolveStreamRead - -@typing.final -class StreamPage(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - RECORDS_FIELD_NUMBER: builtins.int - DONE_FIELD_NUMBER: builtins.int - done: builtins.bool - """True if the Stream is closed and has no Record after this page. It's false if the page has - no Record because none came within the `wait` of the read. - """ - @property - def records( - self, - ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ - temporalio.api.stream.v1.message_pb2.StreamRecord - ]: - """The Records of the page, in the order of the Stream. It's empty if no Record came within the - `wait` of the read, or if the Stream is closed and has no Record after the `from_offset` of - the read. - """ - - def __init__( - self, - *, - records: collections.abc.Iterable[ - temporalio.api.stream.v1.message_pb2.StreamRecord - ] - | None = ..., - done: builtins.bool = ..., - ) -> None: ... - def ClearField( - self, field_name: typing.Literal["done", b"done", "records", b"records"] - ) -> None: ... - -global___StreamPage = StreamPage - @typing.final class ResolveStreamAppend(google.protobuf.message.Message): - """The result of an `AppendToStream`. Core gives each result in the next activation after the - Store answers, so each result can cost an activation. - - A replay gives each result in the same activation as the first run only if History has the flag - that turns workflow task chunking off. Without the flag, a replay keeps the order of the results - of a task, but it can give a result in another activation in two cases. - * A Workflow Task completes with no command, and the first activation of the next task has a - result. A replay takes the two tasks as one, and can give the results of the first two - activations of the second task in one. - * A Workflow Task starts with an Update that Workflow code rejects, which leaves no event. When - such a replay has no other job to give, it gives the results of History in one activation, in - the order of the first run, up to the first one whose call Workflow code hasn't made yet. - A task with only Stream calls replays in the same activations as a task with only Local - Activities. In a task with both, a result waits for each result of the other kind that the first - run gave before it, so its activations can differ from those of Local Activities alone. + """The result of an `AppendToStream`. Core gives it in the next activation after the Store answers. + History keeps the index of that activation with the result, counted as for the marker of a local + activity, so a replay gives both kinds of result in the order of the first run. A result that + arrives while the task completes comes in the first activation of the next task. + + As for a local activity, a replay gives the result in the same activation as the first run only + if workflow task chunking is off. With chunking, a replay can give the jobs of several + activations in one, in their order. """ DESCRIPTOR: google.protobuf.descriptor.Descriptor @@ -1821,12 +1706,9 @@ class ResolveStreamAppend(google.protobuf.message.Message): def appended(self) -> global___StreamAppended: ... @property def failed(self) -> temporalio.api.failure.v1.message_pb2.Failure: - """The failure of the append. It has these parts. - * An `ApplicationFailureInfo` whose type is `stream_` plus the reason of the Stream error - in snake case, such as `stream_closed`. Its `non_retryable` is set. - * In its details, one `binary/protobuf` payload of a - `temporalio.api.stream.v1.StreamErrorDetails`. - * A message of at most 4096 bytes. + """An `ApplicationFailureInfo` of the type `stream_`, such as `stream_closed`, with + `non_retryable` set. Its details have one `binary/protobuf` payload of a + `temporalio.api.stream.v1.StreamErrorDetails`. """ def __init__( @@ -1914,3 +1796,90 @@ class ResolveStreamClose(google.protobuf.message.Message): ) -> None: ... global___ResolveStreamClose = ResolveStreamClose + +@typing.final +class ResolveStreamRead(google.protobuf.message.Message): + """The result of a `ReadStream`. Each read gets exactly one, unless Core drops the read (see + `ReadStream`). The activation rules of `ResolveStreamAppend` apply to it too. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + PAGE_FIELD_NUMBER: builtins.int + FAILED_FIELD_NUMBER: builtins.int + seq: builtins.int + """The `seq` of the `ReadStream`.""" + @property + def page(self) -> global___StreamPage: ... + @property + def failed(self) -> temporalio.api.failure.v1.message_pb2.Failure: + """The failure of the read. It has the parts of the `failed` of a `ResolveStreamAppend`.""" + + def __init__( + self, + *, + seq: builtins.int = ..., + page: global___StreamPage | None = ..., + failed: temporalio.api.failure.v1.message_pb2.Failure | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "failed", b"failed", "page", b"page", "status", b"status" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "failed", b"failed", "page", b"page", "seq", b"seq", "status", b"status" + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["status", b"status"] + ) -> typing.Literal["page", "failed"] | None: ... + +global___ResolveStreamRead = ResolveStreamRead + +@typing.final +class StreamPage(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RECORDS_FIELD_NUMBER: builtins.int + DONE_FIELD_NUMBER: builtins.int + LAST_OFFSET_FIELD_NUMBER: builtins.int + done: builtins.bool + """True if the Stream is closed and has no Record after this page.""" + last_offset: builtins.bytes + """The offset where the page ends, also for a page with no Record. The next read can pass it as + its `from_offset`. + """ + @property + def records( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + temporalio.api.stream.v1.message_pb2.StreamRecord + ]: + """The Records of the page, in the order of the Stream. It's empty if the Stream is closed and + has no Record after the `from_offset` of the read, or if no Record came while the read + waited. + """ + + def __init__( + self, + *, + records: collections.abc.Iterable[ + temporalio.api.stream.v1.message_pb2.StreamRecord + ] + | None = ..., + done: builtins.bool = ..., + last_offset: builtins.bytes = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "done", b"done", "last_offset", b"last_offset", "records", b"records" + ], + ) -> None: ... + +global___StreamPage = StreamPage diff --git a/temporalio/bridge/proto/workflow_commands/__init__.py b/temporalio/bridge/proto/workflow_commands/__init__.py index f599917afa..771fb22db3 100644 --- a/temporalio/bridge/proto/workflow_commands/__init__.py +++ b/temporalio/bridge/proto/workflow_commands/__init__.py @@ -1,15 +1,18 @@ from .workflow_commands_pb2 import ( ActivityCancellationType, + AppendToStream, CancelChildWorkflowExecution, CancelSignalWorkflow, CancelTimer, CancelWorkflowExecution, + CloseStream, CompleteWorkflowExecution, ContinueAsNewWorkflowExecution, FailWorkflowExecution, ModifyWorkflowProperties, QueryResult, QuerySuccess, + ReadStream, RequestCancelActivity, RequestCancelExternalWorkflowExecution, RequestCancelLocalActivity, @@ -28,16 +31,19 @@ __all__ = [ "ActivityCancellationType", + "AppendToStream", "CancelChildWorkflowExecution", "CancelSignalWorkflow", "CancelTimer", "CancelWorkflowExecution", + "CloseStream", "CompleteWorkflowExecution", "ContinueAsNewWorkflowExecution", "FailWorkflowExecution", "ModifyWorkflowProperties", "QueryResult", "QuerySuccess", + "ReadStream", "RequestCancelActivity", "RequestCancelExternalWorkflowExecution", "RequestCancelLocalActivity", diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py index 3573f36b11..8222089545 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py @@ -32,6 +32,9 @@ from temporalio.api.sdk.v1 import ( user_metadata_pb2 as temporal_dot_api_dot_sdk_dot_v1_dot_user__metadata__pb2, ) +from temporalio.api.stream.v1 import ( + message_pb2 as temporal_dot_api_dot_stream_dot_v1_dot_message__pb2, +) from temporalio.api.workflow.v1 import ( message_pb2 as temporal_dot_api_dot_workflow_dot_v1_dot_message__pb2, ) @@ -46,7 +49,7 @@ ) DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n;temporal/sdk/core/workflow_commands/workflow_commands.proto\x12\x19\x63oresdk.workflow_commands\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a$temporal/api/common/v1/message.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a%temporal/api/failure/v1/message.proto\x1a\'temporal/api/sdk/v1/user_metadata.proto\x1a,temporal/api/sdk/v1/event_group_marker.proto\x1a&temporal/api/workflow/v1/message.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a#temporal/sdk/core/nexus/nexus.proto\x1a%temporal/sdk/core/common/common.proto"\xa9\x10\n\x0fWorkflowCommand\x12\x38\n\ruser_metadata\x18\x64 \x01(\x0b\x32!.temporal.api.sdk.v1.UserMetadata\x12\x42\n\x13\x65vent_group_markers\x18\x65 \x03(\x0b\x32%.temporal.api.sdk.v1.EventGroupMarker\x12<\n\x0bstart_timer\x18\x01 \x01(\x0b\x32%.coresdk.workflow_commands.StartTimerH\x00\x12H\n\x11schedule_activity\x18\x02 \x01(\x0b\x32+.coresdk.workflow_commands.ScheduleActivityH\x00\x12\x42\n\x10respond_to_query\x18\x03 \x01(\x0b\x32&.coresdk.workflow_commands.QueryResultH\x00\x12S\n\x17request_cancel_activity\x18\x04 \x01(\x0b\x32\x30.coresdk.workflow_commands.RequestCancelActivityH\x00\x12>\n\x0c\x63\x61ncel_timer\x18\x05 \x01(\x0b\x32&.coresdk.workflow_commands.CancelTimerH\x00\x12[\n\x1b\x63omplete_workflow_execution\x18\x06 \x01(\x0b\x32\x34.coresdk.workflow_commands.CompleteWorkflowExecutionH\x00\x12S\n\x17\x66\x61il_workflow_execution\x18\x07 \x01(\x0b\x32\x30.coresdk.workflow_commands.FailWorkflowExecutionH\x00\x12g\n"continue_as_new_workflow_execution\x18\x08 \x01(\x0b\x32\x39.coresdk.workflow_commands.ContinueAsNewWorkflowExecutionH\x00\x12W\n\x19\x63\x61ncel_workflow_execution\x18\t \x01(\x0b\x32\x32.coresdk.workflow_commands.CancelWorkflowExecutionH\x00\x12\x45\n\x10set_patch_marker\x18\n \x01(\x0b\x32).coresdk.workflow_commands.SetPatchMarkerH\x00\x12`\n\x1estart_child_workflow_execution\x18\x0b \x01(\x0b\x32\x36.coresdk.workflow_commands.StartChildWorkflowExecutionH\x00\x12\x62\n\x1f\x63\x61ncel_child_workflow_execution\x18\x0c \x01(\x0b\x32\x37.coresdk.workflow_commands.CancelChildWorkflowExecutionH\x00\x12w\n*request_cancel_external_workflow_execution\x18\r \x01(\x0b\x32\x41.coresdk.workflow_commands.RequestCancelExternalWorkflowExecutionH\x00\x12h\n"signal_external_workflow_execution\x18\x0e \x01(\x0b\x32:.coresdk.workflow_commands.SignalExternalWorkflowExecutionH\x00\x12Q\n\x16\x63\x61ncel_signal_workflow\x18\x0f \x01(\x0b\x32/.coresdk.workflow_commands.CancelSignalWorkflowH\x00\x12S\n\x17schedule_local_activity\x18\x10 \x01(\x0b\x32\x30.coresdk.workflow_commands.ScheduleLocalActivityH\x00\x12^\n\x1drequest_cancel_local_activity\x18\x11 \x01(\x0b\x32\x35.coresdk.workflow_commands.RequestCancelLocalActivityH\x00\x12\x66\n!upsert_workflow_search_attributes\x18\x12 \x01(\x0b\x32\x39.coresdk.workflow_commands.UpsertWorkflowSearchAttributesH\x00\x12Y\n\x1amodify_workflow_properties\x18\x13 \x01(\x0b\x32\x33.coresdk.workflow_commands.ModifyWorkflowPropertiesH\x00\x12\x44\n\x0fupdate_response\x18\x14 \x01(\x0b\x32).coresdk.workflow_commands.UpdateResponseH\x00\x12U\n\x18schedule_nexus_operation\x18\x15 \x01(\x0b\x32\x31.coresdk.workflow_commands.ScheduleNexusOperationH\x00\x12`\n\x1erequest_cancel_nexus_operation\x18\x16 \x01(\x0b\x32\x36.coresdk.workflow_commands.RequestCancelNexusOperationH\x00\x42\t\n\x07variant"S\n\nStartTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x38\n\x15start_to_fire_timeout\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration"\x1a\n\x0b\x43\x61ncelTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r"\xb8\x06\n\x10ScheduleActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x15\n\ractivity_type\x18\x03 \x01(\t\x12\x12\n\ntask_queue\x18\x05 \x01(\t\x12I\n\x07headers\x18\x06 \x03(\x0b\x32\x38.coresdk.workflow_commands.ScheduleActivity.HeadersEntry\x12\x32\n\targuments\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x34\n\x11heartbeat_timeout\x18\x0b \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x0c \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12N\n\x11\x63\x61ncellation_type\x18\r \x01(\x0e\x32\x33.coresdk.workflow_commands.ActivityCancellationType\x12\x1e\n\x16\x64o_not_eagerly_execute\x18\x0e \x01(\x08\x12;\n\x11versioning_intent\x18\x0f \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12\x32\n\x08priority\x18\x10 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x93\x06\n\x15ScheduleLocalActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x15\n\ractivity_type\x18\x03 \x01(\t\x12\x0f\n\x07\x61ttempt\x18\x04 \x01(\r\x12:\n\x16original_schedule_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12N\n\x07headers\x18\x06 \x03(\x0b\x32=.coresdk.workflow_commands.ScheduleLocalActivity.HeadersEntry\x12\x32\n\targuments\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x0b \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x38\n\x15local_retry_threshold\x18\x0c \x01(\x0b\x32\x19.google.protobuf.Duration\x12N\n\x11\x63\x61ncellation_type\x18\r \x01(\x0e\x32\x33.coresdk.workflow_commands.ActivityCancellationType\x12#\n\x1binclude_arguments_in_marker\x18\x0e \x01(\x08\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"$\n\x15RequestCancelActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r")\n\x1aRequestCancelLocalActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r"\x9c\x01\n\x0bQueryResult\x12\x10\n\x08query_id\x18\x01 \x01(\t\x12<\n\tsucceeded\x18\x02 \x01(\x0b\x32\'.coresdk.workflow_commands.QuerySuccessH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\t\n\x07variant"A\n\x0cQuerySuccess\x12\x31\n\x08response\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"L\n\x19\x43ompleteWorkflowExecution\x12/\n\x06result\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"J\n\x15\x46\x61ilWorkflowExecution\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"\x92\x07\n\x1e\x43ontinueAsNewWorkflowExecution\x12\x15\n\rworkflow_type\x18\x01 \x01(\t\x12\x12\n\ntask_queue\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x37\n\x14workflow_run_timeout\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12Q\n\x04memo\x18\x06 \x03(\x0b\x32\x43.coresdk.workflow_commands.ContinueAsNewWorkflowExecution.MemoEntry\x12W\n\x07headers\x18\x07 \x03(\x0b\x32\x46.coresdk.workflow_commands.ContinueAsNewWorkflowExecution.HeadersEntry\x12\x43\n\x11search_attributes\x18\x08 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12\x39\n\x0cretry_policy\x18\t \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12;\n\x11versioning_intent\x18\n \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12[\n\x1binitial_versioning_behavior\x18\x0b \x01(\x0e\x32\x36.temporal.api.enums.v1.ContinueAsNewVersioningBehavior\x12\x39\n\x16\x62\x61\x63koff_start_interval\x18\x0c \x01(\x0b\x32\x19.google.protobuf.Duration\x1aL\n\tMemoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"L\n\x17\x43\x61ncelWorkflowExecution\x12\x31\n\x07\x64\x65tails\x18\x01 \x01(\x0b\x32 .temporal.api.common.v1.Payloads"6\n\x0eSetPatchMarker\x12\x10\n\x08patch_id\x18\x01 \x01(\t\x12\x12\n\ndeprecated\x18\x02 \x01(\x08"\xe1\t\n\x1bStartChildWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x11\n\tnamespace\x18\x02 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x03 \x01(\t\x12\x15\n\rworkflow_type\x18\x04 \x01(\t\x12\x12\n\ntask_queue\x18\x05 \x01(\t\x12.\n\x05input\x18\x06 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12=\n\x1aworkflow_execution_timeout\x18\x07 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14workflow_run_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x46\n\x13parent_close_policy\x18\n \x01(\x0e\x32).coresdk.child_workflow.ParentClosePolicy\x12N\n\x18workflow_id_reuse_policy\x18\x0c \x01(\x0e\x32,.temporal.api.enums.v1.WorkflowIdReusePolicy\x12\x39\n\x0cretry_policy\x18\r \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x15\n\rcron_schedule\x18\x0e \x01(\t\x12T\n\x07headers\x18\x0f \x03(\x0b\x32\x43.coresdk.workflow_commands.StartChildWorkflowExecution.HeadersEntry\x12N\n\x04memo\x18\x10 \x03(\x0b\x32@.coresdk.workflow_commands.StartChildWorkflowExecution.MemoEntry\x12\x43\n\x11search_attributes\x18\x11 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12P\n\x11\x63\x61ncellation_type\x18\x12 \x01(\x0e\x32\x35.coresdk.child_workflow.ChildWorkflowCancellationType\x12;\n\x11versioning_intent\x18\x13 \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12\x32\n\x08priority\x18\x14 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12I\n\x13versioning_override\x18\x15 \x01(\x0b\x32,.temporal.api.workflow.v1.VersioningOverride\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x1aL\n\tMemoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"J\n\x1c\x43\x61ncelChildWorkflowExecution\x12\x1a\n\x12\x63hild_workflow_seq\x18\x01 \x01(\r\x12\x0e\n\x06reason\x18\x02 \x01(\t"\x8e\x01\n&RequestCancelExternalWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12G\n\x12workflow_execution\x18\x02 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecution\x12\x0e\n\x06reason\x18\x03 \x01(\t"\x8f\x03\n\x1fSignalExternalWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12I\n\x12workflow_execution\x18\x02 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecutionH\x00\x12\x1b\n\x11\x63hild_workflow_id\x18\x03 \x01(\tH\x00\x12\x13\n\x0bsignal_name\x18\x04 \x01(\t\x12-\n\x04\x61rgs\x18\x05 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12X\n\x07headers\x18\x06 \x03(\x0b\x32G.coresdk.workflow_commands.SignalExternalWorkflowExecution.HeadersEntry\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x42\x08\n\x06target"#\n\x14\x43\x61ncelSignalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r"e\n\x1eUpsertWorkflowSearchAttributes\x12\x43\n\x11search_attributes\x18\x01 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes"O\n\x18ModifyWorkflowProperties\x12\x33\n\rupserted_memo\x18\x01 \x01(\x0b\x32\x1c.temporal.api.common.v1.Memo"\xd2\x01\n\x0eUpdateResponse\x12\x1c\n\x14protocol_instance_id\x18\x01 \x01(\t\x12*\n\x08\x61\x63\x63\x65pted\x18\x02 \x01(\x0b\x32\x16.google.protobuf.EmptyH\x00\x12\x34\n\x08rejected\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x12\x34\n\tcompleted\x18\x04 \x01(\x0b\x32\x1f.temporal.api.common.v1.PayloadH\x00\x42\n\n\x08response"\x9a\x04\n\x16ScheduleNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x10\n\x08\x65ndpoint\x18\x02 \x01(\t\x12\x0f\n\x07service\x18\x03 \x01(\t\x12\x11\n\toperation\x18\x04 \x01(\t\x12.\n\x05input\x18\x05 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x06 \x01(\x0b\x32\x19.google.protobuf.Duration\x12X\n\x0cnexus_header\x18\x07 \x03(\x0b\x32\x42.coresdk.workflow_commands.ScheduleNexusOperation.NexusHeaderEntry\x12H\n\x11\x63\x61ncellation_type\x18\x08 \x01(\x0e\x32-.coresdk.nexus.NexusOperationCancellationType\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x1a\x32\n\x10NexusHeaderEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"*\n\x1bRequestCancelNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r*X\n\x18\x41\x63tivityCancellationType\x12\x0e\n\nTRY_CANCEL\x10\x00\x12\x1f\n\x1bWAIT_CANCELLATION_COMPLETED\x10\x01\x12\x0b\n\x07\x41\x42\x41NDON\x10\x02\x42\x36\xea\x02\x33Temporalio::Internal::Bridge::Api::WorkflowCommandsb\x06proto3' + b'\n;temporal/sdk/core/workflow_commands/workflow_commands.proto\x12\x19\x63oresdk.workflow_commands\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a$temporal/api/common/v1/message.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a%temporal/api/failure/v1/message.proto\x1a\'temporal/api/sdk/v1/user_metadata.proto\x1a,temporal/api/sdk/v1/event_group_marker.proto\x1a$temporal/api/stream/v1/message.proto\x1a&temporal/api/workflow/v1/message.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a#temporal/sdk/core/nexus/nexus.proto\x1a%temporal/sdk/core/common/common.proto"\xee\x11\n\x0fWorkflowCommand\x12\x38\n\ruser_metadata\x18\x64 \x01(\x0b\x32!.temporal.api.sdk.v1.UserMetadata\x12\x42\n\x13\x65vent_group_markers\x18\x65 \x03(\x0b\x32%.temporal.api.sdk.v1.EventGroupMarker\x12<\n\x0bstart_timer\x18\x01 \x01(\x0b\x32%.coresdk.workflow_commands.StartTimerH\x00\x12H\n\x11schedule_activity\x18\x02 \x01(\x0b\x32+.coresdk.workflow_commands.ScheduleActivityH\x00\x12\x42\n\x10respond_to_query\x18\x03 \x01(\x0b\x32&.coresdk.workflow_commands.QueryResultH\x00\x12S\n\x17request_cancel_activity\x18\x04 \x01(\x0b\x32\x30.coresdk.workflow_commands.RequestCancelActivityH\x00\x12>\n\x0c\x63\x61ncel_timer\x18\x05 \x01(\x0b\x32&.coresdk.workflow_commands.CancelTimerH\x00\x12[\n\x1b\x63omplete_workflow_execution\x18\x06 \x01(\x0b\x32\x34.coresdk.workflow_commands.CompleteWorkflowExecutionH\x00\x12S\n\x17\x66\x61il_workflow_execution\x18\x07 \x01(\x0b\x32\x30.coresdk.workflow_commands.FailWorkflowExecutionH\x00\x12g\n"continue_as_new_workflow_execution\x18\x08 \x01(\x0b\x32\x39.coresdk.workflow_commands.ContinueAsNewWorkflowExecutionH\x00\x12W\n\x19\x63\x61ncel_workflow_execution\x18\t \x01(\x0b\x32\x32.coresdk.workflow_commands.CancelWorkflowExecutionH\x00\x12\x45\n\x10set_patch_marker\x18\n \x01(\x0b\x32).coresdk.workflow_commands.SetPatchMarkerH\x00\x12`\n\x1estart_child_workflow_execution\x18\x0b \x01(\x0b\x32\x36.coresdk.workflow_commands.StartChildWorkflowExecutionH\x00\x12\x62\n\x1f\x63\x61ncel_child_workflow_execution\x18\x0c \x01(\x0b\x32\x37.coresdk.workflow_commands.CancelChildWorkflowExecutionH\x00\x12w\n*request_cancel_external_workflow_execution\x18\r \x01(\x0b\x32\x41.coresdk.workflow_commands.RequestCancelExternalWorkflowExecutionH\x00\x12h\n"signal_external_workflow_execution\x18\x0e \x01(\x0b\x32:.coresdk.workflow_commands.SignalExternalWorkflowExecutionH\x00\x12Q\n\x16\x63\x61ncel_signal_workflow\x18\x0f \x01(\x0b\x32/.coresdk.workflow_commands.CancelSignalWorkflowH\x00\x12S\n\x17schedule_local_activity\x18\x10 \x01(\x0b\x32\x30.coresdk.workflow_commands.ScheduleLocalActivityH\x00\x12^\n\x1drequest_cancel_local_activity\x18\x11 \x01(\x0b\x32\x35.coresdk.workflow_commands.RequestCancelLocalActivityH\x00\x12\x66\n!upsert_workflow_search_attributes\x18\x12 \x01(\x0b\x32\x39.coresdk.workflow_commands.UpsertWorkflowSearchAttributesH\x00\x12Y\n\x1amodify_workflow_properties\x18\x13 \x01(\x0b\x32\x33.coresdk.workflow_commands.ModifyWorkflowPropertiesH\x00\x12\x44\n\x0fupdate_response\x18\x14 \x01(\x0b\x32).coresdk.workflow_commands.UpdateResponseH\x00\x12U\n\x18schedule_nexus_operation\x18\x15 \x01(\x0b\x32\x31.coresdk.workflow_commands.ScheduleNexusOperationH\x00\x12`\n\x1erequest_cancel_nexus_operation\x18\x16 \x01(\x0b\x32\x36.coresdk.workflow_commands.RequestCancelNexusOperationH\x00\x12<\n\x0bread_stream\x18\x17 \x01(\x0b\x32%.coresdk.workflow_commands.ReadStreamH\x00\x12\x45\n\x10\x61ppend_to_stream\x18\x19 \x01(\x0b\x32).coresdk.workflow_commands.AppendToStreamH\x00\x12>\n\x0c\x63lose_stream\x18\x1a \x01(\x0b\x32&.coresdk.workflow_commands.CloseStreamH\x00\x42\t\n\x07variant"S\n\nStartTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x38\n\x15start_to_fire_timeout\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration"\x1a\n\x0b\x43\x61ncelTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r"\xb8\x06\n\x10ScheduleActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x15\n\ractivity_type\x18\x03 \x01(\t\x12\x12\n\ntask_queue\x18\x05 \x01(\t\x12I\n\x07headers\x18\x06 \x03(\x0b\x32\x38.coresdk.workflow_commands.ScheduleActivity.HeadersEntry\x12\x32\n\targuments\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x34\n\x11heartbeat_timeout\x18\x0b \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x0c \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12N\n\x11\x63\x61ncellation_type\x18\r \x01(\x0e\x32\x33.coresdk.workflow_commands.ActivityCancellationType\x12\x1e\n\x16\x64o_not_eagerly_execute\x18\x0e \x01(\x08\x12;\n\x11versioning_intent\x18\x0f \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12\x32\n\x08priority\x18\x10 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x93\x06\n\x15ScheduleLocalActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x15\n\ractivity_type\x18\x03 \x01(\t\x12\x0f\n\x07\x61ttempt\x18\x04 \x01(\r\x12:\n\x16original_schedule_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12N\n\x07headers\x18\x06 \x03(\x0b\x32=.coresdk.workflow_commands.ScheduleLocalActivity.HeadersEntry\x12\x32\n\targuments\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x0b \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x38\n\x15local_retry_threshold\x18\x0c \x01(\x0b\x32\x19.google.protobuf.Duration\x12N\n\x11\x63\x61ncellation_type\x18\r \x01(\x0e\x32\x33.coresdk.workflow_commands.ActivityCancellationType\x12#\n\x1binclude_arguments_in_marker\x18\x0e \x01(\x08\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"$\n\x15RequestCancelActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r")\n\x1aRequestCancelLocalActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r"\x9c\x01\n\x0bQueryResult\x12\x10\n\x08query_id\x18\x01 \x01(\t\x12<\n\tsucceeded\x18\x02 \x01(\x0b\x32\'.coresdk.workflow_commands.QuerySuccessH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\t\n\x07variant"A\n\x0cQuerySuccess\x12\x31\n\x08response\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"L\n\x19\x43ompleteWorkflowExecution\x12/\n\x06result\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"J\n\x15\x46\x61ilWorkflowExecution\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"\x92\x07\n\x1e\x43ontinueAsNewWorkflowExecution\x12\x15\n\rworkflow_type\x18\x01 \x01(\t\x12\x12\n\ntask_queue\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x37\n\x14workflow_run_timeout\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12Q\n\x04memo\x18\x06 \x03(\x0b\x32\x43.coresdk.workflow_commands.ContinueAsNewWorkflowExecution.MemoEntry\x12W\n\x07headers\x18\x07 \x03(\x0b\x32\x46.coresdk.workflow_commands.ContinueAsNewWorkflowExecution.HeadersEntry\x12\x43\n\x11search_attributes\x18\x08 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12\x39\n\x0cretry_policy\x18\t \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12;\n\x11versioning_intent\x18\n \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12[\n\x1binitial_versioning_behavior\x18\x0b \x01(\x0e\x32\x36.temporal.api.enums.v1.ContinueAsNewVersioningBehavior\x12\x39\n\x16\x62\x61\x63koff_start_interval\x18\x0c \x01(\x0b\x32\x19.google.protobuf.Duration\x1aL\n\tMemoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"L\n\x17\x43\x61ncelWorkflowExecution\x12\x31\n\x07\x64\x65tails\x18\x01 \x01(\x0b\x32 .temporal.api.common.v1.Payloads"6\n\x0eSetPatchMarker\x12\x10\n\x08patch_id\x18\x01 \x01(\t\x12\x12\n\ndeprecated\x18\x02 \x01(\x08"\xe1\t\n\x1bStartChildWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x11\n\tnamespace\x18\x02 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x03 \x01(\t\x12\x15\n\rworkflow_type\x18\x04 \x01(\t\x12\x12\n\ntask_queue\x18\x05 \x01(\t\x12.\n\x05input\x18\x06 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12=\n\x1aworkflow_execution_timeout\x18\x07 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14workflow_run_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x46\n\x13parent_close_policy\x18\n \x01(\x0e\x32).coresdk.child_workflow.ParentClosePolicy\x12N\n\x18workflow_id_reuse_policy\x18\x0c \x01(\x0e\x32,.temporal.api.enums.v1.WorkflowIdReusePolicy\x12\x39\n\x0cretry_policy\x18\r \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x15\n\rcron_schedule\x18\x0e \x01(\t\x12T\n\x07headers\x18\x0f \x03(\x0b\x32\x43.coresdk.workflow_commands.StartChildWorkflowExecution.HeadersEntry\x12N\n\x04memo\x18\x10 \x03(\x0b\x32@.coresdk.workflow_commands.StartChildWorkflowExecution.MemoEntry\x12\x43\n\x11search_attributes\x18\x11 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12P\n\x11\x63\x61ncellation_type\x18\x12 \x01(\x0e\x32\x35.coresdk.child_workflow.ChildWorkflowCancellationType\x12;\n\x11versioning_intent\x18\x13 \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12\x32\n\x08priority\x18\x14 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12I\n\x13versioning_override\x18\x15 \x01(\x0b\x32,.temporal.api.workflow.v1.VersioningOverride\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x1aL\n\tMemoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"J\n\x1c\x43\x61ncelChildWorkflowExecution\x12\x1a\n\x12\x63hild_workflow_seq\x18\x01 \x01(\r\x12\x0e\n\x06reason\x18\x02 \x01(\t"\x8e\x01\n&RequestCancelExternalWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12G\n\x12workflow_execution\x18\x02 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecution\x12\x0e\n\x06reason\x18\x03 \x01(\t"\x8f\x03\n\x1fSignalExternalWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12I\n\x12workflow_execution\x18\x02 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecutionH\x00\x12\x1b\n\x11\x63hild_workflow_id\x18\x03 \x01(\tH\x00\x12\x13\n\x0bsignal_name\x18\x04 \x01(\t\x12-\n\x04\x61rgs\x18\x05 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12X\n\x07headers\x18\x06 \x03(\x0b\x32G.coresdk.workflow_commands.SignalExternalWorkflowExecution.HeadersEntry\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x42\x08\n\x06target"#\n\x14\x43\x61ncelSignalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r"e\n\x1eUpsertWorkflowSearchAttributes\x12\x43\n\x11search_attributes\x18\x01 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes"O\n\x18ModifyWorkflowProperties\x12\x33\n\rupserted_memo\x18\x01 \x01(\x0b\x32\x1c.temporal.api.common.v1.Memo"\xd2\x01\n\x0eUpdateResponse\x12\x1c\n\x14protocol_instance_id\x18\x01 \x01(\t\x12*\n\x08\x61\x63\x63\x65pted\x18\x02 \x01(\x0b\x32\x16.google.protobuf.EmptyH\x00\x12\x34\n\x08rejected\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x12\x34\n\tcompleted\x18\x04 \x01(\x0b\x32\x1f.temporal.api.common.v1.PayloadH\x00\x42\n\n\x08response"\x9a\x04\n\x16ScheduleNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x10\n\x08\x65ndpoint\x18\x02 \x01(\t\x12\x0f\n\x07service\x18\x03 \x01(\t\x12\x11\n\toperation\x18\x04 \x01(\t\x12.\n\x05input\x18\x05 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x06 \x01(\x0b\x32\x19.google.protobuf.Duration\x12X\n\x0cnexus_header\x18\x07 \x03(\x0b\x32\x42.coresdk.workflow_commands.ScheduleNexusOperation.NexusHeaderEntry\x12H\n\x11\x63\x61ncellation_type\x18\x08 \x01(\x0e\x32-.coresdk.nexus.NexusOperationCancellationType\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x1a\x32\n\x10NexusHeaderEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"*\n\x1bRequestCancelNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r"\x81\x01\n\x0e\x41ppendToStream\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x06stream\x18\x02 \x01(\x0b\x32!.temporal.api.stream.v1.StreamRef\x12/\n\x06\x62odies\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload"M\n\x0b\x43loseStream\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x06stream\x18\x02 \x01(\x0b\x32!.temporal.api.stream.v1.StreamRef"\xb2\x01\n\nReadStream\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x06stream\x18\x02 \x01(\x0b\x32!.temporal.api.stream.v1.StreamRef\x12\x13\n\x0b\x66rom_offset\x18\x03 \x01(\x0c\x12\'\n\x04wait\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x13\n\x0bmax_records\x18\x05 \x01(\x05\x12\x11\n\tmax_bytes\x18\x06 \x01(\x03*X\n\x18\x41\x63tivityCancellationType\x12\x0e\n\nTRY_CANCEL\x10\x00\x12\x1f\n\x1bWAIT_CANCELLATION_COMPLETED\x10\x01\x12\x0b\n\x07\x41\x42\x41NDON\x10\x02\x42\x36\xea\x02\x33Temporalio::Internal::Bridge::Api::WorkflowCommandsb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -72,70 +75,76 @@ _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_options = b"8\001" _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._options = None _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_options = b"8\001" - _ACTIVITYCANCELLATIONTYPE._serialized_start = 8785 - _ACTIVITYCANCELLATIONTYPE._serialized_end = 8873 - _WORKFLOWCOMMAND._serialized_start = 558 - _WORKFLOWCOMMAND._serialized_end = 2647 - _STARTTIMER._serialized_start = 2649 - _STARTTIMER._serialized_end = 2732 - _CANCELTIMER._serialized_start = 2734 - _CANCELTIMER._serialized_end = 2760 - _SCHEDULEACTIVITY._serialized_start = 2763 - _SCHEDULEACTIVITY._serialized_end = 3587 - _SCHEDULEACTIVITY_HEADERSENTRY._serialized_start = 3508 - _SCHEDULEACTIVITY_HEADERSENTRY._serialized_end = 3587 - _SCHEDULELOCALACTIVITY._serialized_start = 3590 - _SCHEDULELOCALACTIVITY._serialized_end = 4377 - _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_start = 3508 - _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_end = 3587 - _REQUESTCANCELACTIVITY._serialized_start = 4379 - _REQUESTCANCELACTIVITY._serialized_end = 4415 - _REQUESTCANCELLOCALACTIVITY._serialized_start = 4417 - _REQUESTCANCELLOCALACTIVITY._serialized_end = 4458 - _QUERYRESULT._serialized_start = 4461 - _QUERYRESULT._serialized_end = 4617 - _QUERYSUCCESS._serialized_start = 4619 - _QUERYSUCCESS._serialized_end = 4684 - _COMPLETEWORKFLOWEXECUTION._serialized_start = 4686 - _COMPLETEWORKFLOWEXECUTION._serialized_end = 4762 - _FAILWORKFLOWEXECUTION._serialized_start = 4764 - _FAILWORKFLOWEXECUTION._serialized_end = 4838 - _CONTINUEASNEWWORKFLOWEXECUTION._serialized_start = 4841 - _CONTINUEASNEWWORKFLOWEXECUTION._serialized_end = 5755 - _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5598 - _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5674 - _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3508 - _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3587 - _CANCELWORKFLOWEXECUTION._serialized_start = 5757 - _CANCELWORKFLOWEXECUTION._serialized_end = 5833 - _SETPATCHMARKER._serialized_start = 5835 - _SETPATCHMARKER._serialized_end = 5889 - _STARTCHILDWORKFLOWEXECUTION._serialized_start = 5892 - _STARTCHILDWORKFLOWEXECUTION._serialized_end = 7141 - _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3508 - _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3587 - _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5598 - _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5674 - _CANCELCHILDWORKFLOWEXECUTION._serialized_start = 7143 - _CANCELCHILDWORKFLOWEXECUTION._serialized_end = 7217 - _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_start = 7220 - _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_end = 7362 - _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_start = 7365 - _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_end = 7764 - _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3508 - _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3587 - _CANCELSIGNALWORKFLOW._serialized_start = 7766 - _CANCELSIGNALWORKFLOW._serialized_end = 7801 - _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_start = 7803 - _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_end = 7904 - _MODIFYWORKFLOWPROPERTIES._serialized_start = 7906 - _MODIFYWORKFLOWPROPERTIES._serialized_end = 7985 - _UPDATERESPONSE._serialized_start = 7988 - _UPDATERESPONSE._serialized_end = 8198 - _SCHEDULENEXUSOPERATION._serialized_start = 8201 - _SCHEDULENEXUSOPERATION._serialized_end = 8739 - _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_start = 8689 - _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_end = 8739 - _REQUESTCANCELNEXUSOPERATION._serialized_start = 8741 - _REQUESTCANCELNEXUSOPERATION._serialized_end = 8783 + _ACTIVITYCANCELLATIONTYPE._serialized_start = 9412 + _ACTIVITYCANCELLATIONTYPE._serialized_end = 9500 + _WORKFLOWCOMMAND._serialized_start = 596 + _WORKFLOWCOMMAND._serialized_end = 2882 + _STARTTIMER._serialized_start = 2884 + _STARTTIMER._serialized_end = 2967 + _CANCELTIMER._serialized_start = 2969 + _CANCELTIMER._serialized_end = 2995 + _SCHEDULEACTIVITY._serialized_start = 2998 + _SCHEDULEACTIVITY._serialized_end = 3822 + _SCHEDULEACTIVITY_HEADERSENTRY._serialized_start = 3743 + _SCHEDULEACTIVITY_HEADERSENTRY._serialized_end = 3822 + _SCHEDULELOCALACTIVITY._serialized_start = 3825 + _SCHEDULELOCALACTIVITY._serialized_end = 4612 + _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_start = 3743 + _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_end = 3822 + _REQUESTCANCELACTIVITY._serialized_start = 4614 + _REQUESTCANCELACTIVITY._serialized_end = 4650 + _REQUESTCANCELLOCALACTIVITY._serialized_start = 4652 + _REQUESTCANCELLOCALACTIVITY._serialized_end = 4693 + _QUERYRESULT._serialized_start = 4696 + _QUERYRESULT._serialized_end = 4852 + _QUERYSUCCESS._serialized_start = 4854 + _QUERYSUCCESS._serialized_end = 4919 + _COMPLETEWORKFLOWEXECUTION._serialized_start = 4921 + _COMPLETEWORKFLOWEXECUTION._serialized_end = 4997 + _FAILWORKFLOWEXECUTION._serialized_start = 4999 + _FAILWORKFLOWEXECUTION._serialized_end = 5073 + _CONTINUEASNEWWORKFLOWEXECUTION._serialized_start = 5076 + _CONTINUEASNEWWORKFLOWEXECUTION._serialized_end = 5990 + _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5833 + _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5909 + _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3743 + _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3822 + _CANCELWORKFLOWEXECUTION._serialized_start = 5992 + _CANCELWORKFLOWEXECUTION._serialized_end = 6068 + _SETPATCHMARKER._serialized_start = 6070 + _SETPATCHMARKER._serialized_end = 6124 + _STARTCHILDWORKFLOWEXECUTION._serialized_start = 6127 + _STARTCHILDWORKFLOWEXECUTION._serialized_end = 7376 + _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3743 + _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3822 + _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5833 + _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5909 + _CANCELCHILDWORKFLOWEXECUTION._serialized_start = 7378 + _CANCELCHILDWORKFLOWEXECUTION._serialized_end = 7452 + _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_start = 7455 + _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_end = 7597 + _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_start = 7600 + _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_end = 7999 + _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3743 + _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3822 + _CANCELSIGNALWORKFLOW._serialized_start = 8001 + _CANCELSIGNALWORKFLOW._serialized_end = 8036 + _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_start = 8038 + _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_end = 8139 + _MODIFYWORKFLOWPROPERTIES._serialized_start = 8141 + _MODIFYWORKFLOWPROPERTIES._serialized_end = 8220 + _UPDATERESPONSE._serialized_start = 8223 + _UPDATERESPONSE._serialized_end = 8433 + _SCHEDULENEXUSOPERATION._serialized_start = 8436 + _SCHEDULENEXUSOPERATION._serialized_end = 8974 + _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_start = 8924 + _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_end = 8974 + _REQUESTCANCELNEXUSOPERATION._serialized_start = 8976 + _REQUESTCANCELNEXUSOPERATION._serialized_end = 9018 + _APPENDTOSTREAM._serialized_start = 9021 + _APPENDTOSTREAM._serialized_end = 9150 + _CLOSESTREAM._serialized_start = 9152 + _CLOSESTREAM._serialized_end = 9229 + _READSTREAM._serialized_start = 9232 + _READSTREAM._serialized_end = 9410 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi index af36b1712d..7b4c01eadc 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi @@ -107,7 +107,6 @@ class WorkflowCommand(google.protobuf.message.Message): SCHEDULE_NEXUS_OPERATION_FIELD_NUMBER: builtins.int REQUEST_CANCEL_NEXUS_OPERATION_FIELD_NUMBER: builtins.int READ_STREAM_FIELD_NUMBER: builtins.int - REQUEST_CANCEL_STREAM_READ_FIELD_NUMBER: builtins.int APPEND_TO_STREAM_FIELD_NUMBER: builtins.int CLOSE_STREAM_FIELD_NUMBER: builtins.int @property @@ -189,8 +188,6 @@ class WorkflowCommand(google.protobuf.message.Message): @property def read_stream(self) -> global___ReadStream: ... @property - def request_cancel_stream_read(self) -> global___RequestCancelStreamRead: ... - @property def append_to_stream(self) -> global___AppendToStream: ... @property def close_stream(self) -> global___CloseStream: ... @@ -233,7 +230,6 @@ class WorkflowCommand(google.protobuf.message.Message): request_cancel_nexus_operation: global___RequestCancelNexusOperation | None = ..., read_stream: global___ReadStream | None = ..., - request_cancel_stream_read: global___RequestCancelStreamRead | None = ..., append_to_stream: global___AppendToStream | None = ..., close_stream: global___CloseStream | None = ..., ) -> None: ... @@ -270,8 +266,6 @@ class WorkflowCommand(google.protobuf.message.Message): b"request_cancel_local_activity", "request_cancel_nexus_operation", b"request_cancel_nexus_operation", - "request_cancel_stream_read", - b"request_cancel_stream_read", "respond_to_query", b"respond_to_query", "schedule_activity", @@ -333,8 +327,6 @@ class WorkflowCommand(google.protobuf.message.Message): b"request_cancel_local_activity", "request_cancel_nexus_operation", b"request_cancel_nexus_operation", - "request_cancel_stream_read", - b"request_cancel_stream_read", "respond_to_query", b"respond_to_query", "schedule_activity", @@ -388,7 +380,6 @@ class WorkflowCommand(google.protobuf.message.Message): "schedule_nexus_operation", "request_cancel_nexus_operation", "read_stream", - "request_cancel_stream_read", "append_to_stream", "close_stream", ] @@ -1971,40 +1962,26 @@ global___RequestCancelNexusOperation = RequestCancelNexusOperation @typing.final class AppendToStream(google.protobuf.message.Message): - """Appends Records to a Stream as the Workflow's Producer. Core makes the request id of the append - and sends the result in a `ResolveStreamAppend` job. + """Appends Records to a Stream as the Workflow's Producer. Core calls the Store while the Workflow + Task is open, and sends the result in a `ResolveStreamAppend` job. As for a Local Activity, Core + keeps the task open while an append runs. An append has no event, so History keeps its result in + the `stream_calls` of the `sdk_metadata` of the task's completion. - An append is at-least-once. A later attempt of the Workflow Task writes it again, on this Worker - or on another one. + An append is at-least-once. If History has no result of it, a later attempt of the Workflow Task + writes the batch again. No command cancels an append, so lang must accept the job of an append that nothing awaits. - When lang sends the Workflow's last command, Core drops each append that has no result, as it - does for a Local Activity. Such an append may or may not have reached the Store, and lang gets - no job for it. + Core drops an append that has no result when lang sends the Workflow's last command. Core sends the appends and the closes of one Stream to the Store one at a time, in the order of - their commands. A close gets its place in that order only when History has its intent. So an - append that lang sends after a `CloseStream`, but before History has the task of that close, is - written before the close. - - Core fails the Workflow Task in each of these cases, and gives lang no failure of the append. - * `seq` is 0, or isn't above the `seq` of the append before it. - * `stream` is unset, its id is empty or longer than 4096 bytes, or its Store name is longer than - 4096 bytes. - * The Worker has no Stream runtime for the Store of `stream`. - * The append must wait for the task's heartbeat to try again, because the Store answered - `StoreUnavailable`, gave no answer or panicked. The failure message then starts with - `StreamStoreUnavailable:`. - - An append with no `bodies`, or with a batch over the limits of its Store, doesn't fail the - Workflow Task. Lang gets a `failed` job for it. - - In a replay, Core compares the `seq` and the `stream` of the command with History, but not the - `bodies`. A `stream` with no Store name matches any Store in History. An append with no result - in History runs again after the replay, as a later attempt, so a reader can see its batch twice. - - If lang completes the Workflow Task while an append has no result in a marker, Core forces a new - task, unless the completion has the Workflow's last command. + their commands. + + A bad `seq` or `stream`, or a Store that the Worker has no runtime for, fails the Workflow Task. + So does a Store that is still unavailable at the task's heartbeat. The failure message then + starts with `StreamStoreUnavailable:`. An empty batch, or one over the limits of its Store, + gives lang a `failed` job. + + A replay compares the `seq` and the `stream` of the command with History, not the `bodies`. """ DESCRIPTOR: google.protobuf.descriptor.Descriptor @@ -2044,19 +2021,15 @@ global___AppendToStream = AppendToStream @typing.final class CloseStream(google.protobuf.message.Message): - """Closes a Stream. The Workflow Task that sends the command records only the intent to close. - Core closes the Stream when History has that task, and sends the result in a - `ResolveStreamClose` job of a later task. So a close needs at least one more Workflow Task. - - These rules of `AppendToStream` apply to a close too. - * No command cancels it. - * Core drops it if it has no result when lang sends the Workflow's last command. - * The same cases fail the Workflow Task. - * A replay compares the command with History in the same way. - * If lang completes the task while the close has no result in a marker, Core forces a new task. - - Workflow code that needs its close must await the result before its last command. A close whose - intent is in History with no result runs again after a replay. + """Closes a Stream. The Workflow Task of the command records only the intent to close. Core closes + the Stream once History has that task, so a task that fails closes nothing, and its retry can + still append. The result comes in a `ResolveStreamClose` job of a later task. + + An append that lang sends in the same task is written before the close. + + The rules of `AppendToStream` about cancellation, the Workflow's last command, task failures and + replay apply to a close too. So Workflow code that needs its close must await the result before + its last command. """ DESCRIPTOR: google.protobuf.descriptor.Descriptor @@ -2084,47 +2057,33 @@ global___CloseStream = CloseStream @typing.final class ReadStream(google.protobuf.message.Message): - """Reads the next page of a Stream. The result comes in one `ResolveStreamRead` job, which has a - page, a failure or a cancel. Core asks the Store when the command comes, unless the Workflow - replays. A replay gives the read the result that History has for it. - - The page has the Records after `from_offset`, in the order of the Stream: - * the Records that the Stream has, or the first ones that come within `wait` - * no Records and `done`, if the Stream is closed and has none after `from_offset` - * no Records, if none came within `wait` - - To read on, lang sends a new `ReadStream` whose `from_offset` is the offset of the last Record - that it got. A page with no Record gives no offset, so the next read starts at the `from_offset` - of this one. - - What a read costs: - * Each page takes a command, an activation and an entry in the marker of its Workflow Task. - * A read holds its Workflow Task open while it waits for the Store, as a Local Activity does. A - Signal, a timer or an Activity result reaches Workflow code in the next task. The task in hand - completes once Workflow code sends a command for the server while only reads hold the task, - and at the latest at its heartbeat. A read that still waits adds the three events of a forced - Workflow Task at each heartbeat. - * One Workflow Task gives at most 16 MiB of Records, and its marker holds at most 1 MiB of them - for reads with `records_in_history`. A page that doesn't fit comes in the next task, which - Core forces. - * Without `records_in_history`, History has the count and a digest of the Records of each page. - A replay reads each page from the Store again, within the timeout of its Workflow Task. A - query of a run that isn't cached replays too. Once the Store no longer has the same Records, - each replay fails, also the one for a query of a closed Workflow. - - A read gets no job at the Workflow's last command, at a failed Workflow Task, at an eviction and - at the shutdown of the Worker. After the last three the Workflow replays. The replay gives each - read the result that History has for it. A read with no result in History runs again once the - replay is over, unless Workflow code cancelled it. Such a read gets its `cancelled` job then. - - Core fails the Workflow Task, and gives lang no failure of the read, in the cases that - `AppendToStream` lists and in these: - * `from_offset` is longer than 1024 bytes. - * `wait` is negative, or has its nanoseconds out of range. - * `max_records` or `max_bytes` is negative. - - In a replay, Core compares the `seq`, the `stream` and the `from_offset` of the command with - History. + """Reads one page of a Stream, which has the Records after `from_offset`. The result comes in one + `ResolveStreamRead` job, by the activation rules of `ResolveStreamAppend`. To read on, lang sends + a new `ReadStream` from the `last_offset` of the page. + + A read has a time limit in each Workflow Task (`StreamSettings::read_time`), which is always + before the heartbeat of the task. So a read alone never keeps a task open with heartbeats. At + the limit, a read with no answer gives a page with no Record whose `last_offset` is its + `from_offset`. It fails with `STREAM_ERROR_REASON_STORE_UNAVAILABLE` only if its last try failed + or got no answer. + + Core keeps the Workflow Task while a read has no answer, as for an append, with one difference. + A command or a message for the server doesn't wait for a read. Core then completes the task and + asks for a new one, and the page comes in a later task. + + No command cancels a read, so lang must accept the job of a read that nothing awaits. Core drops + a read that has no result when lang sends the Workflow's last command. + + History keeps the offsets, the count and a digest of each page, not its Records. A replay reads + the page from the Store again, and fails if the Records are gone or differ. That includes the + replay for a query of a closed Workflow. + + One Workflow Task gives at most 16 MiB of Records. A page that doesn't fit comes in the next + task. + + A negative `wait`, `max_records` or `max_bytes`, or a `from_offset` over 1024 bytes, fails the + Workflow Task, as the cases of `AppendToStream` do. A replay compares the `seq`, the `stream` + and the `from_offset` of the command with History. """ DESCRIPTOR: google.protobuf.descriptor.Descriptor @@ -2133,7 +2092,6 @@ class ReadStream(google.protobuf.message.Message): STREAM_FIELD_NUMBER: builtins.int FROM_OFFSET_FIELD_NUMBER: builtins.int WAIT_FIELD_NUMBER: builtins.int - RECORDS_IN_HISTORY_FIELD_NUMBER: builtins.int MAX_RECORDS_FIELD_NUMBER: builtins.int MAX_BYTES_FIELD_NUMBER: builtins.int seq: builtins.int @@ -2142,17 +2100,11 @@ class ReadStream(google.protobuf.message.Message): """The page has the Records after this offset. If it's empty, the page starts at the beginning of the Stream. """ - records_in_history: builtins.bool - """If set, the marker of the task holds the Records of the page, so a replay doesn't read the - Store. A marker can't hold a Record whose Producer and body have more than 1.5 MiB, so the - read fails with `stream_unsupported` for one. - """ max_records: builtins.int """The maximum number of Records in the page, which is 256 if this is zero.""" max_bytes: builtins.int """The maximum size of the Records in the page, which is 4 MiB if this is zero. Core asks the - Store for at most 16 MiB, and for at most 1 MiB with `records_in_history`. One larger Record - still comes as a page, unless the read fails for it with `records_in_history`. + Store for at most 16 MiB. One larger Record still comes as a page. """ @property def stream(self) -> temporalio.api.stream.v1.message_pb2.StreamRef: ... @@ -2169,7 +2121,6 @@ class ReadStream(google.protobuf.message.Message): stream: temporalio.api.stream.v1.message_pb2.StreamRef | None = ..., from_offset: builtins.bytes = ..., wait: google.protobuf.duration_pb2.Duration | None = ..., - records_in_history: builtins.bool = ..., max_records: builtins.int = ..., max_bytes: builtins.int = ..., ) -> None: ... @@ -2185,8 +2136,6 @@ class ReadStream(google.protobuf.message.Message): b"max_bytes", "max_records", b"max_records", - "records_in_history", - b"records_in_history", "seq", b"seq", "stream", @@ -2197,44 +2146,3 @@ class ReadStream(google.protobuf.message.Message): ) -> None: ... global___ReadStream = ReadStream - -@typing.final -class RequestCancelStreamRead(google.protobuf.message.Message): - """Cancels a read, as `RequestCancelLocalActivity` cancels a Local Activity whose cancellation type - is `TRY_CANCEL`. The read still gets its one `ResolveStreamRead` job. Once Core has the cancel, - that job has `cancelled`, unless lang already got the job of the read. Core drops a page or a - failure of the read that lang didn't get, and the next read from the same `from_offset` gives - the Records of a dropped page. - - If the activation that lang answers with the cancel has a job of the read, that job stays as it - is. So an SDK that runs Workflow code between the jobs of one activation can give that code a - page of a read that it already cancelled, in the first run and in a replay. - - A cancel costs an activation and an entry in the marker of its Workflow Task, for the - `cancelled` job. If the task completes at its heartbeat before that job, the cancel also costs - the events of a forced Workflow Task. - - A `ReadStream` and its cancel in one completion, in that order, make no Store call. - - In a replay, the job is the one that History has. A replay of a History without the flag that - turns workflow task chunking off can give the `cancelled` job before lang sends the cancel, in - the activation of the job that made Workflow code cancel. A read with a cancel and no result in - History gets its `cancelled` job once the replay is over. - - Core ignores the cancel of a read that got its job, and the cancel of a `seq` that lang skipped. - The cancel of a `seq` above that of the last read is a nondeterminism error. - """ - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - SEQ_FIELD_NUMBER: builtins.int - seq: builtins.int - """The `seq` of the `ReadStream` to cancel.""" - def __init__( - self, - *, - seq: builtins.int = ..., - ) -> None: ... - def ClearField(self, field_name: typing.Literal["seq", b"seq"]) -> None: ... - -global___RequestCancelStreamRead = RequestCancelStreamRead From 7d83f9b8c3d70bb31724b71abe193d34ef6f78b2 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Tue, 24 Nov 2026 16:08:25 -0700 Subject: [PATCH 20/50] Use the read limit of Core for the Workflow Stream reads Core has no cancel of a read. A cancelled read sends no command, and the job that still comes for it is dropped. The Worker option `stream_read_time` sets the read limit of a Workflow Task, in place of `stream_read_max_wait`. --- changelog/added/steady-stream-heron.md | 2 +- temporalio/client/_stream_store.py | 7 +- temporalio/worker/_worker.py | 17 +- temporalio/worker/_workflow_streams.py | 31 ++-- tests/nexus/test_streams_with_worker.py | 214 ++++++++++++------------ tests/worker/test_workflow_streams.py | 38 +---- 6 files changed, 144 insertions(+), 165 deletions(-) diff --git a/changelog/added/steady-stream-heron.md b/changelog/added/steady-stream-heron.md index 1c4a5769ab..c5ea12e810 100644 --- a/changelog/added/steady-stream-heron.md +++ b/changelog/added/steady-stream-heron.md @@ -1,5 +1,5 @@ Add experimental `temporalio.client.StreamStore`, the base class of a Stream Store, and `temporalio.testing.MemoryStreamStore`, a Store that keeps its Streams in memory for tests and local runs. A Store gets the request id of each create and each append as `request_id`, and a create returns the ref of its request. Add experimental Streams for client and Activity code. `stream_config=StreamConfig(stores=[...])` of `Client.connect` gives a client its Stream Stores, and `Client.create_stream` and `Client.get_stream` return a `Stream` to append to, read, describe and close. A failed call raises `temporalio.exceptions.StreamError` with a `reason`. `max_record_bytes`, `max_batch_bytes` and `max_batch_records` of `StreamConfig` bound an append, and one over a limit fails before its Store gets it. A read of a Stream from `get_stream` needs `body_type=` or a `StreamRef` with a type argument, and raises `TypeError` with neither. `temporalio.contrib.streams.current_producer` gives the Producer of an Activity attempt, and `as_producer` gives back one that code stored. Add experimental Streams for Workflow code. `workflow.create_stream` and `workflow.get_stream` return a `Stream` to append to, describe and close on the Stream Stores of the Worker's client, and `Replayer(stream_config=...)` gives a replay its Stores. -Add experimental Stream reads for Workflow code. `Stream.read`, `read_pages` and `read_page` of a Workflow `Stream` give the Records as they come, a replay reads them again from the Store, and `temporalio.workflow.StreamReplayError` in the failure exception types of a Worker or a Workflow fails the Workflow when the Store no longer has them. The Worker option `stream_read_max_wait` bounds the wait of one Store call of a read. +Add experimental Stream reads for Workflow code. `Stream.read`, `read_pages` and `read_page` of a Workflow `Stream` give the Records as they come, a replay reads them again from the Store, and `temporalio.workflow.StreamReplayError` in the failure exception types of a Worker or a Workflow fails the Workflow when the Store no longer has them. The Worker option `stream_read_time` sets how long the reads of a Workflow Task can wait, and a read with no answer at that limit gives a page with no Record. Add experimental `temporalio.contrib.streams.BufferedAppender`, which batches the appends of one Stream in client and Activity code. `append` returns immediately, a batch waits at most `max_delay`, one write runs at a time, and `async with` or `flush()` writes what is left. diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index f4b6f17354..9f58e122e1 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -267,8 +267,11 @@ class StreamConfig: - A read fails with ``STREAM_ERROR_REASON_UNSUPPORTED`` for a Record over :py:attr:`max_record_bytes`. So a reader needs a limit at least as large as that of each writer of its Stream. - - A read that waits holds its Workflow Task. A Signal that comes meanwhile - waits until the read has its page, or until the heartbeat of the task. + - A read that waits holds its Workflow Task, up to the read limit of the + task, which the Worker option ``stream_read_time`` sets. A Signal that + comes meanwhile waits until the read has its page, or until that limit. At + the limit, a read with no answer gives a page with no Record. A command + for the server doesn't wait for a read. - A body that isn't of the Stream's type fails the Workflow Task, as an Activity result that can't be converted does. diff --git a/temporalio/worker/_worker.py b/temporalio/worker/_worker.py index 0087af1059..a206c395ac 100644 --- a/temporalio/worker/_worker.py +++ b/temporalio/worker/_worker.py @@ -148,7 +148,7 @@ def __init__( nexus_task_poller_behavior: PollerBehavior | None = None, disable_payload_error_limit: bool = False, max_workflow_task_external_storage_concurrency: int = _DEFAULT_WORKFLOW_TASK_EXTERNAL_STORAGE_CONCURRENCY, - stream_read_max_wait: timedelta | None = None, + stream_read_time: timedelta | None = None, ) -> None: """Create a worker to process workflows and/or activities. @@ -348,9 +348,12 @@ def __init__( Please report any issues you encounter with this setting or if you feel the default should be changed. WARNING: This setting is experimental. - stream_read_max_wait: Longest wait of one Store call of a Stream read - of Workflow code. A read that waits longer calls its Store again. - Defaults to 60 seconds. + stream_read_time: How long the Stream reads of a Workflow Task can + wait, from the start of the task. At that limit, a read with no + answer gives a page with no Record. Defaults to half the Workflow + Task timeout. The limit is always before the heartbeat of the task, + so a read alone never makes the Worker send a heartbeat. Appends + and closes have no such limit. WARNING: This setting is experimental. """ @@ -401,7 +404,7 @@ def __init__( nexus_task_poller_behavior=nexus_task_poller_behavior, disable_payload_error_limit=disable_payload_error_limit, max_workflow_task_external_storage_concurrency=max_workflow_task_external_storage_concurrency, - stream_read_max_wait=stream_read_max_wait, + stream_read_time=stream_read_time, ) plugins_from_client = cast( @@ -729,7 +732,7 @@ def check_activity(activity: str): ), streams=_bridge_streams( lambda: self.client._config["stream_config"], - config.get("stream_read_max_wait"), + config.get("stream_read_time"), ), stream_replay_as_workflow_fail=self._workflow_worker is not None and self._workflow_worker.stream_replay_as_workflow_fail(), @@ -1087,7 +1090,7 @@ class WorkerConfig(TypedDict, total=False): nexus_task_poller_behavior: PollerBehavior | None disable_payload_error_limit: bool max_workflow_task_external_storage_concurrency: int - stream_read_max_wait: timedelta | None + stream_read_time: timedelta | None def _poller_behavior_to_bridge( diff --git a/temporalio/worker/_workflow_streams.py b/temporalio/worker/_workflow_streams.py index 555311446c..2a7f623de4 100644 --- a/temporalio/worker/_workflow_streams.py +++ b/temporalio/worker/_workflow_streams.py @@ -81,9 +81,8 @@ def start( The command of the call is added before this returns, so commands are in the order of the calls. Cancelling the handle ends its wait immediately. - Core can't stop an append or a close, so those still run. A cancelled - read sends ``RequestCancelStreamRead``, and the job that still comes for - it is dropped. + Core can't stop an append, a close or a read, so those still run, and the + job that still comes for the call is dropped. """ instance = self._instance instance._assert_not_read_only("start a Stream call") @@ -98,8 +97,6 @@ def start( request = temporalio.nexus.system._support.model_to_proto(model, *converters) # The future of the job of the call, or the task of its Local Activity result: asyncio.Future[Any] - # The seq of the call's read, or 0 for another operation - read_seq = 0 if isinstance(request, proto.AppendRecordsRequest): stream = self._stream(request.ref) seq = instance._next_seq("stream_append") @@ -124,10 +121,10 @@ def start( "body_type, or a StreamRef with a type argument." ) stream = self._stream(request.ref) - read_seq = instance._next_seq("stream_read") + seq = instance._next_seq("stream_read") instance._add_command().read_stream.CopyFrom( temporalio.bridge.proto.workflow_commands.ReadStream( - seq=read_seq, + seq=seq, stream=stream, from_offset=request.from_offset, wait=request.wait if request.HasField("wait") else None, @@ -136,7 +133,7 @@ def start( ) ) result = instance.create_future() - self._reads[read_seq] = _Read(result, result_type) + self._reads[seq] = _Read(result, result_type) else: # The Local Activity picks the Store of a ref with no Store name. A replay # has its result, so a replay asks no selector for it. Each run of a chain @@ -163,9 +160,6 @@ def stop(_: asyncio.Task[OutputT]) -> None: if result.done(): return result.cancel() - # Only a read has a cancel command. An eviction sends no command. - if read_seq and not instance._deleting: - instance._add_command().request_cancel_stream_read.seq = read_seq task = instance.create_task(call(), name=f"stream: {operation}") # A callback also runs for a task that is cancelled before its first step. @@ -188,9 +182,8 @@ def resolve_read( read = self._reads.pop(job.seq, None) if read is None: raise RuntimeError(f"Failed finding Stream read for sequence {job.seq}") - # The job of a cancelled call is dropped. So is a cancel job that comes first, as in a - # replay with legacy chunking, since only the cancel of the call may end its wait. - if read.waiter.done() or job.HasField("cancelled"): + # The job of a cancelled call is dropped. + if read.waiter.done(): return if job.HasField("failed"): read.waiter.set_exception(self._error(job.failed)) @@ -462,13 +455,13 @@ def _for_core( def _bridge_streams( # pyright: ignore[reportUnusedFunction] stream_config: Callable[[], StreamConfig | None], - read_max_wait: timedelta | None, + read_time: timedelta | None, ) -> temporalio.bridge.streams.WorkerStreams: """Return what the bridge needs for the Stream Stores of a worker. ``stream_config`` gives the Stream config that the worker has at a call, - which is the one of another client after a client swap. ``read_max_wait`` is - the longest wait of one Store call of a read, or ``None`` for Core's default. + which is the one of another client after a client swap. ``read_time`` is how + long the reads of a Workflow Task can wait, or ``None`` for Core's default. """ def store(name: str) -> StreamStore: @@ -484,8 +477,8 @@ def store(name: str) -> StreamStore: (name, _StoreCaller(functools.partial(store, name))) for name in sorted(names) ], - read_max_wait_millis=int(1000 * read_max_wait.total_seconds()) - if read_max_wait is not None + read_time_millis=int(1000 * read_time.total_seconds()) + if read_time is not None else None, ) diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py index f4577d6c35..1fade52336 100644 --- a/tests/nexus/test_streams_with_worker.py +++ b/tests/nexus/test_streams_with_worker.py @@ -14,6 +14,7 @@ from temporalio import activity, workflow from temporalio.api.enums.v1 import EventType, StreamErrorReason, TaskQueueType +from temporalio.api.sdk.v1 import WorkflowTaskStreamCalls from temporalio.api.sdk.v1.external_storage_pb2 import ExternalStorageReference from temporalio.api.stream.v1 import StreamRef as RefProto from temporalio.api.streamservice.v1 import ( @@ -290,14 +291,14 @@ def _events(history: Any, event_type: EventType.ValueType) -> list[Any]: return [event for event in history.events if event.event_type == event_type] -def _stream_calls(history: Any) -> list[bytes]: +def _stream_calls(history: Any) -> list[WorkflowTaskStreamCalls]: """Return the Stream calls that Core keeps on each completed Workflow Task.""" completed = _events(history, EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED) calls = [ - event.workflow_task_completed_event_attributes.sdk_metadata.core_stream_calls + event.workflow_task_completed_event_attributes.sdk_metadata.stream_calls for event in completed ] - return [call for call in calls if call] + return [call for call in calls if call.ByteSize()] async def test_a_store_error_is_the_same_error_on_every_path(client: Client) -> None: @@ -828,82 +829,58 @@ def go_on(self) -> None: @workflow.run async def run(self, stream_id: str, how: str) -> None: - if how == "continued": - return stream = await workflow.create_stream(id=stream_id, body_type=int) - call: asyncio.Future[Any] if how == "append": - call = asyncio.ensure_future(stream.append(1)) + asyncio.ensure_future(stream.append(1)) elif how == "close": - call = asyncio.ensure_future(stream.close()) + asyncio.ensure_future(stream.close()) elif how == "page": await stream.append(1) await stream.read_page(wait=timedelta(minutes=5)) return else: - call = asyncio.ensure_future(stream.read_page(wait=timedelta(minutes=5))) + asyncio.ensure_future(stream.read_page(wait=timedelta(minutes=5))) await workflow.wait_condition(lambda: self._signals > 0) # The task of the call makes its call in its first step. await asyncio.sleep(0) - if how == "cancel the read": - call.cancel() - await workflow.wait_condition(lambda: self._signals > 1) - elif how == "continue as new": - workflow.continue_as_new(args=[stream_id, "continued"]) - - -async def _end_while_a_read_waits(client: Client, how: str) -> None: - """Run a Workflow whose read waits on a held Store call, end the read in the way - of ``how``, and check that the Store call was cancelled and that a replay passes. - """ - store, hold = FaultStore(), Hold() - store.faults["read_records"].append(hold) - - async def end(handle: Any, worker: Worker) -> None: - await hold.started.wait() - if how == "cancel": - await handle.cancel() - elif how == "shutdown": - await worker.shutdown() - else: - await handle.signal(_EndingWorkflow.go_on) - await asyncio.wait_for(hold.cancelled.wait(), 10) - if how == "shutdown": - await handle.terminate() - elif how == "cancel the read": - await handle.signal(_EndingWorkflow.go_on) - - # The read holds its Workflow Task until the heartbeat, so the task is short. - options = RunOptions( - _EndingWorkflow, - [f"ends by {how}", how], - task_timeout=timedelta(seconds=2), - during=end, - replay=True, - ) - ran = await run(stream_client(client, store), options) - assert (ran.result is None) == (how not in ("cancel", "shutdown")) - reads = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] - assert len(reads) == 1 async def test_a_read_that_core_stops_leaves_no_store_task(client: Client) -> None: - # A cancel of the read, a terminal command, and the eviction of a Worker that shuts down - for how in ("cancel the read", "return", "shutdown"): + # The read limit of the task stops a held Store call, also while the Worker shuts + # down, since the shutdown waits for the task. + for how in ("read limit", "shutdown"): with failure_note(how): - await _end_while_a_read_waits(client, how) + store, hold = FaultStore(), Hold() + store.faults["read_records"].append(hold) + async def end(handle: Any, worker: Worker) -> None: + await hold.started.wait() + if how == "shutdown": + await worker.shutdown() + else: + await handle.signal(_EndingWorkflow.go_on) + await asyncio.wait_for(hold.cancelled.wait(), 10) + if how == "shutdown": + await handle.terminate() -@pytest.mark.parametrize( - "how", ["continue as new", "cancel", "page", "append", "close"] -) -async def test_a_workflow_that_ends_while_a_read_waits_leaves_nothing( + # A task timeout of 2 seconds gives a read limit of 1 second. + options = RunOptions( + _EndingWorkflow, + [f"ends by {how}", how], + task_timeout=timedelta(seconds=2), + during=end, + replay=True, + ) + ran = await run(stream_client(client, store), options) + assert (ran.result is None) == (how == "read limit") + reads = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] + assert len(reads) == 1 + + +@pytest.mark.parametrize("how", ["page", "append", "close"]) +async def test_a_stream_call_does_not_hold_the_last_command( client: Client, how: str ) -> None: - # The return while a read waits is a case of the test above. - if how in ("continue as new", "cancel"): - await _end_while_a_read_waits(client, how) - return # A read that gave a page, and an append or a close that nothing awaits, don't hold # the last command, so the Workflow ends in the task of the call. options = RunOptions(_EndingWorkflow, [f"ends after its {how}", how], replay=True) @@ -918,46 +895,38 @@ class _LatePagesWorkflow: @workflow.run async def run(self, how: str) -> list[list[str]]: - wait = timedelta(seconds=30) s = workflow.get_stream(StreamRef[str](id=f"s of {how}")) t = workflow.get_stream(StreamRef[str](id=f"t of {how}")) - if how == "a cancel": - # The page of `t` makes the Workflow cancel its read of `s`, whose reader then - # reads `u`. A replay gives the cancel job of `s` after that cancel, as the first run. - u = workflow.get_stream(StreamRef[str](id=f"u of {how}")) - - async def read_s() -> None: - try: - await s.read_page(wait=wait) - except asyncio.CancelledError: - await u.read_page() - - reader = asyncio.ensure_future(read_s()) - # The task around this read lets the reader of `s` run first if its wait ended. - page = await asyncio.ensure_future(t.read_page(wait=wait)) - reader.cancel() - last = await t.read_page(from_offset=page.last_offset) - await reader - return [[r.body for r in page.records], [r.body for r in last.records]] if how == "two readers": # One reader takes a page of `s` and stops. The other waits for a page of # `t`, and then reads `s` on from the offset of the first one. - first = asyncio.ensure_future(s.read_page(wait=wait)) - await t.read_page(wait=wait) + first = asyncio.ensure_future(self._page(s)) + await self._page(t) offset = (await first).last_offset - second = await s.read_page(from_offset=offset, wait=wait) + second = await self._page(s, offset) return [[r.body for r in page.records] for page in (await first, second)] pages: list[list[str]] = [] offset = None while True: - page = await s.read_page(from_offset=offset, wait=wait) + page = await s.read_page(from_offset=offset, wait=timedelta(seconds=30)) pages.append([record.body for record in page.records]) offset = page.last_offset if page.done: return pages + async def _page(self, stream: Any, offset: bytes | None = None) -> Any: + """Return the first page of ``stream`` after ``offset`` that has a Record.""" + while True: + # At the read limit of its task, a read gives a page with no Record. + page = await stream.read_page( + from_offset=offset, wait=timedelta(seconds=30) + ) + if page.records: + return page + offset = page.last_offset + -@pytest.mark.parametrize("how", ["a loop", "two readers", "a cancel"]) +@pytest.mark.parametrize("how", ["a loop", "two readers"]) async def test_a_replay_gives_a_read_the_pages_of_the_first_run( client: Client, how: str ) -> None: @@ -965,11 +934,9 @@ async def test_a_replay_gives_a_read_the_pages_of_the_first_run( client = stream_client(client, store) s = await client.create_stream(id=f"s of {how}", body_type=str) t = await client.create_stream(id=f"t of {how}", body_type=str) - await client.create_stream(id=f"u of {how}", body_type=str) writes, expected = { "a loop": ([(s, "a"), (s, "b")], ["a", "b"]), "two readers": ([(s, "a"), (t, "x"), (s, "b")], ["a", "b"]), - "a cancel": ([(t, "x")], ["x"]), }[how] async def write(handle: Any, _worker: Any) -> None: @@ -978,8 +945,9 @@ async def second_task() -> None: started = EventType.EVENT_TYPE_WORKFLOW_TASK_STARTED assert len(_events(history, started)) > 1 - # The first task ends at its heartbeat with no page. The pages then come in several - # activations of the next task, and a replay gives each page in its activation. + # The reads of the first task end at its read limit with no Record. The pages + # then come in several activations of a later task, and a replay gives each + # page in its activation. await assert_eventually(second_task) for stream, body in writes: await stream.append(body) @@ -1040,15 +1008,10 @@ def read_results(runner: CustomWorkflowRunner) -> list[list[int]]: ] return [seqs for seqs in activations if seqs] - async def release(handle: Any, _worker: Any) -> None: - async def forced_task() -> None: - history = await handle.fetch_history() - started = EventType.EVENT_TYPE_WORKFLOW_TASK_STARTED - assert len(_events(history, started)) > 1 - - # Both reads wait past the heartbeat of the first task, which completes with no - # command. Legacy chunking takes that task and the next one as one in a replay. - await assert_eventually(forced_task) + async def release(_handle: Any, _worker: Any) -> None: + # Both reads wait in the first task, and each page comes before its read limit. + for hold in holds: + await hold.started.wait() for count, hold in enumerate(holds, 1): hold.release() @@ -1061,7 +1024,6 @@ async def given() -> None: options = RunOptions( _TwoReadsWorkflow, ["first", "second"], - task_timeout=timedelta(seconds=2), worker={"workflow_runner": live}, during=release, ) @@ -1187,25 +1149,67 @@ async def test_a_workflow_read_asks_the_store_with_its_limits(client: Client) -> stream = await client.create_stream(id="paged", body_type=int) await stream.append(1, 2, 3) await stream.close() - # A read with no limit asks for 256 Records and 4 MiB. Each Store call waits for the - # longest wait of the Worker at most. - cases: list[tuple[dict[str, int], tuple[int, int, int]]] = [ - ({"max_records": 1, "max_bytes": 100}, (1, 100, 2)), - ({}, (256, 4 * 1024 * 1024, 2)), + # A read with no limit asks for 256 Records and 4 MiB. A Store call waits no longer + # than the read time of the Worker, which is shorter than the wait of the read. + cases: list[tuple[dict[str, int], tuple[int, int]]] = [ + ({"max_records": 1, "max_bytes": 100}, (1, 100)), + ({}, (256, 4 * 1024 * 1024)), ] + read_time = timedelta(seconds=2) for limits, expected in cases: with failure_note(f"limits {limits}"): store.calls.clear() options = RunOptions( _ReadAllWorkflow, ["paged", limits], - worker={"stream_read_max_wait": timedelta(seconds=2)}, + worker={"stream_read_time": read_time}, ) assert (await run(client, options)).result == [1, 2, 3] reads = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] - asked = [(r.max_records, r.max_bytes, r.wait.ToSeconds()) for r in reads] + asked = [(r.max_records, r.max_bytes) for r in reads] # With one Record in a page, the read of each Record is one Store call. assert asked == [expected] * (3 if limits else 1) + waits = [r.wait.ToTimedelta() for r in reads] + assert timedelta(0) < waits[0] and max(waits) <= read_time + + +@workflow.defn +class _QuietReadWorkflow: + @workflow.run + async def run(self, stream_id: str) -> list[int]: + stream = workflow.get_stream(StreamRef[int](id=stream_id)) + return [record.body async for record in stream.read(wait=timedelta(minutes=5))] + + +async def test_a_workflow_read_waits_on_a_quiet_stream_across_read_limits( + client: Client, +) -> None: + store = FaultStore() + client = stream_client(client, store) + stream = await client.create_stream(id="quiet", body_type=int) + + async def write(handle: Any, _worker: Any) -> None: + async def limit_passed() -> None: + history = await handle.fetch_history() + completed = EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED + assert len(_events(history, completed)) > 1 + + # On a quiet Stream, the read gets pages with no Record, and goes on in the next + # Workflow Task from the same offset. + await assert_eventually(limit_passed) + quiet = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] + assert len(quiet) > 1 and not any(r.from_offset for r in quiet) + await stream.append(1, 2) + await stream.close() + + options = RunOptions( + _QuietReadWorkflow, + ["quiet"], + worker={"stream_read_time": timedelta(milliseconds=300)}, + during=write, + replay=True, + ) + assert (await run(client, options)).result == [1, 2] @dataclasses.dataclass diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py index e33c586899..8b699f92e5 100644 --- a/tests/worker/test_workflow_streams.py +++ b/tests/worker/test_workflow_streams.py @@ -9,7 +9,6 @@ from typing import Any from google.protobuf.duration_pb2 import Duration -from google.protobuf.empty_pb2 import Empty from google.protobuf.message import Message import temporalio.api.common.v1 @@ -65,7 +64,6 @@ CompleteWorkflowExecution, ReadStream, RequestCancelLocalActivity, - RequestCancelStreamRead, WorkflowCommand, ) from temporalio.bridge.proto.workflow_completion import ( @@ -768,8 +766,6 @@ async def _reads_script( assert not completion.successful.commands reads: dict[int, _OpenRead] = {} - # The reader of each read whose cancel job came before its cancel, by seq - early: dict[int, int] = {} # The offset that each reader is at positions: list[int] = [] outcomes: list[list[Any]] = [] @@ -800,13 +796,8 @@ def call_read(call: int, commands: list[WorkflowCommand]) -> None: ) commands.append(WorkflowCommand(read_stream=read)) - def cancel(seq: int) -> WorkflowCommand: - command = RequestCancelStreamRead(seq=seq) - return WorkflowCommand(request_cancel_stream_read=command) - for step in range(rng.randrange(2, 7)): - # Each read gets one job, also a cancelled one, whose job has a cancel or the result - # that came before it. A replay with legacy chunking gives a cancel job before the cancel. + # Each read gets one job, also one whose reader was cancelled. jobs: list[ResolveStreamRead] = [] for seq, read in reads.items(): if rng.random() >= 0.6: @@ -830,14 +821,9 @@ def cancel(seq: int) -> WorkflowCommand: if rng.random() < 0.15: not_found = StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND job = ResolveStreamRead(seq=seq, failed=core_failure(not_found)) - elif rng.random() < (0.7 if read.cancelled else 0.2 * replaying): - job = ResolveStreamRead(seq=seq, cancelled=Empty()) jobs.append(job) rng.shuffle(jobs) - waiting = sorted( - [read.call for read in reads.values() if not read.cancelled] - + list(early.values()) - ) + waiting = sorted(read.call for read in reads.values() if not read.cancelled) cancels = [call for call in waiting if rng.random() < 0.25] starts: list[int] = [] for _ in range(rng.randrange(3)): @@ -870,10 +856,6 @@ def apply_jobs() -> None: # A cancelled reader no longer waits, so its job is dropped, whatever it is. if read.cancelled: continue - # A cancel job doesn't end the wait of a reader. Only its cancel does. - if job.HasField("cancelled"): - early[job.seq] = read.call - continue got.append((read.call, job)) bodies = [converter.from_payload(r.body) for r in job.page.records] typed = calls[read.call].body_type is int @@ -884,18 +866,12 @@ def run_handler() -> None: call_read(call, commands) for call in cancels: outcomes[call].append("cancelled") - if any(of == call for of, _ in got): - # A cancel wins over a job that came for the reader in this - # activation, and a read that has its job gets no cancel command. - got[:] = [(of, job) for of, job in got if of != call] - continue - for seq, read in reads.items(): - if read.call == call and not read.cancelled: + # A cancel wins over a job that came for the reader in this activation. + got[:] = [(of, job) for of, job in got if of != call] + # No command cancels a read. + for read in reads.values(): + if read.call == call: read.cancelled = True - commands.append(cancel(seq)) - for seq in [seq for seq, of in early.items() if of == call]: - del early[seq] - commands.append(cancel(seq)) for part in (apply_jobs, run_handler) if flags else (run_handler, apply_jobs): part() From f20654f634f374a1518be5b8ef8938cb7ada5dae Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Tue, 24 Nov 2026 16:50:40 -0700 Subject: [PATCH 21/50] Pin Core with a read that doesn't wait kept at the read limit At the read limit, a read with no wait goes on without holding the task until the Store answers. The generated bridge protos change only in the doc of `ReadStream`. --- .../proto/workflow_commands/workflow_commands_pb2.pyi | 8 +++++--- temporalio/bridge/sdk-core | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi index 7b4c01eadc..0833fb5442 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi @@ -2063,9 +2063,11 @@ class ReadStream(google.protobuf.message.Message): A read has a time limit in each Workflow Task (`StreamSettings::read_time`), which is always before the heartbeat of the task. So a read alone never keeps a task open with heartbeats. At - the limit, a read with no answer gives a page with no Record whose `last_offset` is its - `from_offset`. It fails with `STREAM_ERROR_REASON_STORE_UNAVAILABLE` only if its last try failed - or got no answer. + the limit, a read with no answer fails with `STREAM_ERROR_REASON_STORE_UNAVAILABLE` if its last + try failed or got no answer. Otherwise a read with a `wait` gives a page with no Record whose + `last_offset` is its `from_offset`, and a read with no `wait` goes on until the Store answers, + since only the Store can say that the Stream has no Record. From the limit on, no read keeps + the task open. Core keeps the Workflow Task while a read has no answer, as for an append, with one difference. A command or a message for the server doesn't wait for a read. Core then completes the task and diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index 78aff2d25e..4125c6382c 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit 78aff2d25ed211de7e7263e49a8e14bb3dd05fdb +Subproject commit 4125c6382c0d0bce189f7b97187f7adbdc7f031d From 86615b2e49188201ca3fdb855d94533c3b908976 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Tue, 24 Nov 2026 16:56:04 -0700 Subject: [PATCH 22/50] Say that a read with no wait goes on at the read limit At the read limit, a read with a wait gives a page with no Record, and a read with no wait goes on without holding the task. A test checks that such a read gets the page of a slow Store. --- changelog/added/steady-stream-heron.md | 2 +- temporalio/client/_stream_store.py | 11 ++++----- temporalio/worker/_worker.py | 11 ++++----- tests/nexus/test_streams_with_worker.py | 30 +++++++++++++++++++++++++ 4 files changed, 43 insertions(+), 11 deletions(-) diff --git a/changelog/added/steady-stream-heron.md b/changelog/added/steady-stream-heron.md index c5ea12e810..f5cd83fdca 100644 --- a/changelog/added/steady-stream-heron.md +++ b/changelog/added/steady-stream-heron.md @@ -1,5 +1,5 @@ Add experimental `temporalio.client.StreamStore`, the base class of a Stream Store, and `temporalio.testing.MemoryStreamStore`, a Store that keeps its Streams in memory for tests and local runs. A Store gets the request id of each create and each append as `request_id`, and a create returns the ref of its request. Add experimental Streams for client and Activity code. `stream_config=StreamConfig(stores=[...])` of `Client.connect` gives a client its Stream Stores, and `Client.create_stream` and `Client.get_stream` return a `Stream` to append to, read, describe and close. A failed call raises `temporalio.exceptions.StreamError` with a `reason`. `max_record_bytes`, `max_batch_bytes` and `max_batch_records` of `StreamConfig` bound an append, and one over a limit fails before its Store gets it. A read of a Stream from `get_stream` needs `body_type=` or a `StreamRef` with a type argument, and raises `TypeError` with neither. `temporalio.contrib.streams.current_producer` gives the Producer of an Activity attempt, and `as_producer` gives back one that code stored. Add experimental Streams for Workflow code. `workflow.create_stream` and `workflow.get_stream` return a `Stream` to append to, describe and close on the Stream Stores of the Worker's client, and `Replayer(stream_config=...)` gives a replay its Stores. -Add experimental Stream reads for Workflow code. `Stream.read`, `read_pages` and `read_page` of a Workflow `Stream` give the Records as they come, a replay reads them again from the Store, and `temporalio.workflow.StreamReplayError` in the failure exception types of a Worker or a Workflow fails the Workflow when the Store no longer has them. The Worker option `stream_read_time` sets how long the reads of a Workflow Task can wait, and a read with no answer at that limit gives a page with no Record. +Add experimental Stream reads for Workflow code. `Stream.read`, `read_pages` and `read_page` of a Workflow `Stream` give the Records as they come, a replay reads them again from the Store, and `temporalio.workflow.StreamReplayError` in the failure exception types of a Worker or a Workflow fails the Workflow when the Store no longer has them. The Worker option `stream_read_time` sets how long the reads of a Workflow Task can wait, and a read with a wait gives a page with no Record at that limit. Add experimental `temporalio.contrib.streams.BufferedAppender`, which batches the appends of one Stream in client and Activity code. `append` returns immediately, a batch waits at most `max_delay`, one write runs at a time, and `async with` or `flush()` writes what is left. diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 9f58e122e1..3680fad49b 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -267,11 +267,12 @@ class StreamConfig: - A read fails with ``STREAM_ERROR_REASON_UNSUPPORTED`` for a Record over :py:attr:`max_record_bytes`. So a reader needs a limit at least as large as that of each writer of its Stream. - - A read that waits holds its Workflow Task, up to the read limit of the - task, which the Worker option ``stream_read_time`` sets. A Signal that - comes meanwhile waits until the read has its page, or until that limit. At - the limit, a read with no answer gives a page with no Record. A command - for the server doesn't wait for a read. + - A read holds its Workflow Task, up to the read limit of the task, which + the Worker option ``stream_read_time`` sets. A Signal that comes meanwhile + waits until the read has its page, or until that limit. At the limit, a + read with a wait gives a page with no Record, and a read with no wait + goes on without holding the task until the Store answers. A command for + the server doesn't wait for a read. - A body that isn't of the Stream's type fails the Workflow Task, as an Activity result that can't be converted does. diff --git a/temporalio/worker/_worker.py b/temporalio/worker/_worker.py index a206c395ac..b04737f3f7 100644 --- a/temporalio/worker/_worker.py +++ b/temporalio/worker/_worker.py @@ -349,11 +349,12 @@ def __init__( feel the default should be changed. WARNING: This setting is experimental. stream_read_time: How long the Stream reads of a Workflow Task can - wait, from the start of the task. At that limit, a read with no - answer gives a page with no Record. Defaults to half the Workflow - Task timeout. The limit is always before the heartbeat of the task, - so a read alone never makes the Worker send a heartbeat. Appends - and closes have no such limit. + wait, from the start of the task. At that limit, a read with a wait + gives a page with no Record, and a read with no wait goes on + without holding the task until the Store answers. Defaults to half + the Workflow Task timeout. The limit is always before the heartbeat + of the task, so a read alone never makes the Worker send a + heartbeat. Appends and closes have no such limit. WARNING: This setting is experimental. """ diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py index 1fade52336..e191d89897 100644 --- a/tests/nexus/test_streams_with_worker.py +++ b/tests/nexus/test_streams_with_worker.py @@ -1212,6 +1212,36 @@ async def limit_passed() -> None: assert (await run(client, options)).result == [1, 2] +async def test_a_workflow_read_with_no_wait_outlives_the_read_limit( + client: Client, +) -> None: + store, hold = FaultStore(), Hold() + stream = await stream_client(client, store).create_stream(id="slow", body_type=int) + await stream.append(1, 2, 3) + store.faults["read_records"].append(hold) + + async def release(handle: Any, _worker: Any) -> None: + async def task_completed() -> None: + history = await handle.fetch_history() + completed = EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED + assert _events(history, completed) + + # The task completes at its read limit, and the Store still holds the read. + await assert_eventually(task_completed) + hold.release() + await handle.signal(_ReadOnceWorkflow.go_on) + + options = RunOptions( + _ReadOnceWorkflow, + ["slow"], + task_timeout=timedelta(seconds=2), + during=release, + replay=True, + ) + assert (await run(stream_client(client, store), options)).result == [1, 2, 3] + assert not hold.cancelled.is_set() + + @dataclasses.dataclass class _Turn: text: str From 2491c9b18fe57e240a370b019488696e6ac5f8c5 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Wed, 25 Nov 2026 12:16:36 -0700 Subject: [PATCH 23/50] Pin Core with Stream markers and a Store that gets the Stream id The bridge gives a Python Store the Store requests and has no close. The runtime of a Python Store takes the SDK requests that it builds from those, and asks the Store for no Record more. The bridge protos and the payload visitor are regenerated. --- temporalio/bridge/_visitor.py | 48 ++--- .../bridge/proto/external_data/__init__.py | 19 +- .../proto/external_data/external_data_pb2.py | 16 +- .../proto/external_data/external_data_pb2.pyi | 185 +++++------------- .../proto/workflow_activation/__init__.py | 2 - .../workflow_activation_pb2.py | 118 ++++++----- .../workflow_activation_pb2.pyi | 96 +++------ .../proto/workflow_commands/__init__.py | 2 - .../workflow_commands_pb2.py | 150 +++++++------- .../workflow_commands_pb2.pyi | 174 ++++++++-------- temporalio/bridge/sdk-core | 2 +- temporalio/bridge/src/streams.rs | 78 +++++--- 12 files changed, 390 insertions(+), 500 deletions(-) diff --git a/temporalio/bridge/_visitor.py b/temporalio/bridge/_visitor.py index 4b02edbc65..ab059e9642 100644 --- a/temporalio/bridge/_visitor.py +++ b/temporalio/bridge/_visitor.py @@ -308,6 +308,12 @@ async def _visit_coresdk_workflow_activation_ResolveNexusOperation( if o.HasField("result"): await self._visit_coresdk_nexus_NexusOperationResult(fs, o.result) + async def _visit_coresdk_workflow_activation_ResolveStreamAppend( + self, fs: VisitorFunctions, o: Any + ): + if o.HasField("failed"): + await self._visit_temporal_api_failure_v1_Failure(fs, o.failed) + async def _visit_temporal_api_stream_v1_StreamRecord( self, fs: VisitorFunctions, o: Any ): @@ -328,18 +334,6 @@ async def _visit_coresdk_workflow_activation_ResolveStreamRead( elif o.HasField("failed"): await self._visit_temporal_api_failure_v1_Failure(fs, o.failed) - async def _visit_coresdk_workflow_activation_ResolveStreamAppend( - self, fs: VisitorFunctions, o: Any - ): - if o.HasField("failed"): - await self._visit_temporal_api_failure_v1_Failure(fs, o.failed) - - async def _visit_coresdk_workflow_activation_ResolveStreamClose( - self, fs: VisitorFunctions, o: Any - ): - if o.HasField("failed"): - await self._visit_temporal_api_failure_v1_Failure(fs, o.failed) - async def _visit_coresdk_workflow_activation_WorkflowActivationJob( self, fs: VisitorFunctions, o: Any ): @@ -385,17 +379,13 @@ async def _visit_coresdk_workflow_activation_WorkflowActivationJob( await self._visit_coresdk_workflow_activation_ResolveNexusOperation( fs, o.resolve_nexus_operation ) - elif o.HasField("resolve_stream_read"): - await self._visit_coresdk_workflow_activation_ResolveStreamRead( - fs, o.resolve_stream_read - ) elif o.HasField("resolve_stream_append"): await self._visit_coresdk_workflow_activation_ResolveStreamAppend( fs, o.resolve_stream_append ) - elif o.HasField("resolve_stream_close"): - await self._visit_coresdk_workflow_activation_ResolveStreamClose( - fs, o.resolve_stream_close + elif o.HasField("resolve_stream_read"): + await self._visit_coresdk_workflow_activation_ResolveStreamRead( + fs, o.resolve_stream_read ) async def _visit_coresdk_workflow_activation_WorkflowActivation( @@ -692,12 +682,12 @@ async def _visit_temporal_api_notificationservice_v1_OnCompleteResponse( ) -> None: pass - async def _visit_temporal_api_streamservice_v1_CreateStreamRequest( + async def _visit_temporal_api_sdk_v1_CreateStreamRequest( self, fs: VisitorFunctions, o: Any ) -> None: pass - async def _visit_temporal_api_streamservice_v1_CreateStreamResponse( + async def _visit_temporal_api_sdk_v1_CreateStreamResponse( self, fs: VisitorFunctions, o: Any ) -> None: pass @@ -708,7 +698,7 @@ async def _visit_temporal_api_stream_v1_AppendRecord( if o.HasField("body"): await self._visit_temporal_api_common_v1_Payload(fs, o.body) - async def _visit_temporal_api_streamservice_v1_AppendRecordsRequest( + async def _visit_temporal_api_sdk_v1_AppendRecordsRequest( self, fs: VisitorFunctions, o: Any ): for v in o.records: @@ -719,17 +709,7 @@ async def _visit_temporal_api_streamservice_v1_AppendRecordsResponse( ) -> None: pass - async def _visit_temporal_api_streamservice_v1_CloseStreamRequest( - self, fs: VisitorFunctions, o: Any - ) -> None: - pass - - async def _visit_temporal_api_streamservice_v1_CloseStreamResponse( - self, fs: VisitorFunctions, o: Any - ) -> None: - pass - - async def _visit_temporal_api_streamservice_v1_ReadRecordsRequest( + async def _visit_temporal_api_sdk_v1_ReadRecordsRequest( self, fs: VisitorFunctions, o: Any ) -> None: pass @@ -740,7 +720,7 @@ async def _visit_temporal_api_streamservice_v1_ReadRecordsResponse( for v in o.records: await self._visit_temporal_api_stream_v1_StreamRecord(fs, v) - async def _visit_temporal_api_streamservice_v1_DescribeStreamRequest( + async def _visit_temporal_api_sdk_v1_DescribeStreamRequest( self, fs: VisitorFunctions, o: Any ) -> None: pass diff --git a/temporalio/bridge/proto/external_data/__init__.py b/temporalio/bridge/proto/external_data/__init__.py index 836e97ef43..ef6671d8e6 100644 --- a/temporalio/bridge/proto/external_data/__init__.py +++ b/temporalio/bridge/proto/external_data/__init__.py @@ -1,6 +1,23 @@ -from .external_data_pb2 import LocalActivityMarkerData, PatchedMarkerData +from .external_data_pb2 import ( + LocalActivityMarkerData, + PatchedMarkerData, + StreamAppendMarkerData, + StreamAppendOffsets, + StreamAppendResult, + StreamFailure, + StreamReadMarkerData, + StreamReadPage, + StreamReadResult, +) __all__ = [ "LocalActivityMarkerData", "PatchedMarkerData", + "StreamAppendMarkerData", + "StreamAppendOffsets", + "StreamAppendResult", + "StreamFailure", + "StreamReadMarkerData", + "StreamReadPage", + "StreamReadResult", ] diff --git a/temporalio/bridge/proto/external_data/external_data_pb2.py b/temporalio/bridge/proto/external_data/external_data_pb2.py index 4bda6f5144..02f99d0120 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.py +++ b/temporalio/bridge/proto/external_data/external_data_pb2.py @@ -17,7 +17,7 @@ from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n3temporal/sdk/core/external_data/external_data.proto\x12\x15\x63oresdk.external_data\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xb2\x02\n\x17LocalActivityMarkerData\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x03 \x01(\t\x12\x15\n\ractivity_type\x18\x04 \x01(\t\x12\x31\n\rcomplete_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12*\n\x07\x62\x61\x63koff\x18\x06 \x01(\x0b\x32\x19.google.protobuf.Duration\x12:\n\x16original_schedule_time\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x1d\n\x10\x61\x63tivation_index\x18\x08 \x01(\x04H\x00\x88\x01\x01\x42\x13\n\x11_activation_index"3\n\x11PatchedMarkerData\x12\n\n\x02id\x18\x01 \x01(\t\x12\x12\n\ndeprecated\x18\x02 \x01(\x08\x42\x32\xea\x02/Temporalio::Internal::Bridge::Api::ExternalDatab\x06proto3' + b'\n3temporal/sdk/core/external_data/external_data.proto\x12\x15\x63oresdk.external_data\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xb2\x02\n\x17LocalActivityMarkerData\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x03 \x01(\t\x12\x15\n\ractivity_type\x18\x04 \x01(\t\x12\x31\n\rcomplete_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12*\n\x07\x62\x61\x63koff\x18\x06 \x01(\x0b\x32\x19.google.protobuf.Duration\x12:\n\x16original_schedule_time\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x1d\n\x10\x61\x63tivation_index\x18\x08 \x01(\x04H\x00\x88\x01\x01\x42\x13\n\x11_activation_index"3\n\x11PatchedMarkerData\x12\n\n\x02id\x18\x01 \x01(\t\x12\x12\n\ndeprecated\x18\x02 \x01(\x08"T\n\x16StreamAppendMarkerData\x12:\n\x07\x61ppends\x18\x01 \x03(\x0b\x32).coresdk.external_data.StreamAppendResult"\xe0\x01\n\x12StreamAppendResult\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x11\n\tstream_id\x18\x02 \x01(\t\x12\r\n\x05store\x18\x03 \x01(\t\x12\x18\n\x10\x61\x63tivation_index\x18\x04 \x01(\x04\x12>\n\x08\x61ppended\x18\x05 \x01(\x0b\x32*.coresdk.external_data.StreamAppendOffsetsH\x00\x12\x37\n\x07\x66\x61ilure\x18\x06 \x01(\x0b\x32$.coresdk.external_data.StreamFailureH\x00\x42\x08\n\x06result"@\n\x13StreamAppendOffsets\x12\x14\n\x0c\x66irst_offset\x18\x01 \x01(\x0c\x12\x13\n\x0blast_offset\x18\x02 \x01(\x0c"0\n\rStreamFailure\x12\x0e\n\x06reason\x18\x01 \x01(\t\x12\x0f\n\x07message\x18\x02 \x01(\t"N\n\x14StreamReadMarkerData\x12\x36\n\x05reads\x18\x01 \x03(\x0b\x32\'.coresdk.external_data.StreamReadResult"\xea\x01\n\x10StreamReadResult\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x11\n\tstream_id\x18\x02 \x01(\t\x12\r\n\x05store\x18\x03 \x01(\t\x12\x18\n\x10\x61\x63tivation_index\x18\x04 \x01(\x04\x12\x13\n\x0b\x66rom_offset\x18\x05 \x01(\x0c\x12\x35\n\x04page\x18\x06 \x01(\x0b\x32%.coresdk.external_data.StreamReadPageH\x00\x12\x37\n\x07\x66\x61ilure\x18\x07 \x01(\x0b\x32$.coresdk.external_data.StreamFailureH\x00\x42\x08\n\x06result"s\n\x0eStreamReadPage\x12\x14\n\x0crecord_count\x18\x01 \x01(\r\x12\x0e\n\x06\x64igest\x18\x02 \x01(\x0c\x12\x14\n\x0crecord_bytes\x18\x03 \x01(\x04\x12\x13\n\x0blast_offset\x18\x04 \x01(\x0c\x12\x10\n\x08wait_cut\x18\x05 \x01(\x08\x42\x32\xea\x02/Temporalio::Internal::Bridge::Api::ExternalDatab\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -31,4 +31,18 @@ _LOCALACTIVITYMARKERDATA._serialized_end = 450 _PATCHEDMARKERDATA._serialized_start = 452 _PATCHEDMARKERDATA._serialized_end = 503 + _STREAMAPPENDMARKERDATA._serialized_start = 505 + _STREAMAPPENDMARKERDATA._serialized_end = 589 + _STREAMAPPENDRESULT._serialized_start = 592 + _STREAMAPPENDRESULT._serialized_end = 816 + _STREAMAPPENDOFFSETS._serialized_start = 818 + _STREAMAPPENDOFFSETS._serialized_end = 882 + _STREAMFAILURE._serialized_start = 884 + _STREAMFAILURE._serialized_end = 932 + _STREAMREADMARKERDATA._serialized_start = 934 + _STREAMREADMARKERDATA._serialized_end = 1012 + _STREAMREADRESULT._serialized_start = 1015 + _STREAMREADRESULT._serialized_end = 1249 + _STREAMREADPAGE._serialized_start = 1251 + _STREAMREADPAGE._serialized_end = 1366 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/external_data/external_data_pb2.pyi b/temporalio/bridge/proto/external_data/external_data_pb2.pyi index c1b7256169..aedfbbb389 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.pyi +++ b/temporalio/bridge/proto/external_data/external_data_pb2.pyi @@ -9,7 +9,6 @@ import typing import google.protobuf.descriptor import google.protobuf.duration_pb2 -import google.protobuf.empty_pb2 import google.protobuf.internal.containers import google.protobuf.message import google.protobuf.timestamp_pb2 @@ -144,16 +143,12 @@ class PatchedMarkerData(google.protobuf.message.Message): global___PatchedMarkerData = PatchedMarkerData @typing.final -class StreamMarkerData(google.protobuf.message.Message): - """The data of a `core_stream` marker. Core records one in each Workflow Task in which Workflow - code got a Stream result or asked for a close. The marker has these details. - * `data` holds this message as JSON, with each `bytes` field in lower-case hex. - * `records` has the body of each Record of the reads with `records_in_history`, one payload for - each. They're in the order of `reads`, and those of one read in the order of its Stream. It's - absent if the marker has no such Record. - * `record_info` has one `binary/plain` payload with the rest of each of those Records, in the - same order. Each is its `temporalio.api.stream.v1.StreamRecord` with no body, with its length - before it as a varint. It's absent if `records` is. +class StreamAppendMarkerData(google.protobuf.message.Message): + """The data of a `core_stream_append` marker, which the marker's `data` detail holds as JSON with + each `bytes` field in lower-case hex. Core records one marker for each activation that gives + Workflow code the result of an append. A completion that leaves an append open in a task with + no such marker records one with no entry, so that a replay with chunking on keeps the task + apart from the next one. Every later version of Core must read the markers in History, so these rules apply to each message of the marker. @@ -164,85 +159,21 @@ class StreamMarkerData(google.protobuf.message.Message): DESCRIPTOR: google.protobuf.descriptor.Descriptor - CLOSE_INTENTS_FIELD_NUMBER: builtins.int APPENDS_FIELD_NUMBER: builtins.int - CLOSES_FIELD_NUMBER: builtins.int - READS_FIELD_NUMBER: builtins.int - @property - def close_intents( - self, - ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ - global___StreamCloseIntent - ]: ... @property def appends( self, ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ global___StreamAppendResult ]: ... - @property - def closes( - self, - ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ - global___StreamCloseResult - ]: ... - @property - def reads( - self, - ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ - global___StreamReadResult - ]: ... def __init__( self, *, - close_intents: collections.abc.Iterable[global___StreamCloseIntent] - | None = ..., appends: collections.abc.Iterable[global___StreamAppendResult] | None = ..., - closes: collections.abc.Iterable[global___StreamCloseResult] | None = ..., - reads: collections.abc.Iterable[global___StreamReadResult] | None = ..., - ) -> None: ... - def ClearField( - self, - field_name: typing.Literal[ - "appends", - b"appends", - "close_intents", - b"close_intents", - "closes", - b"closes", - "reads", - b"reads", - ], - ) -> None: ... - -global___StreamMarkerData = StreamMarkerData - -@typing.final -class StreamCloseIntent(google.protobuf.message.Message): - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - SEQ_FIELD_NUMBER: builtins.int - STREAM_ID_FIELD_NUMBER: builtins.int - STORE_FIELD_NUMBER: builtins.int - seq: builtins.int - stream_id: builtins.str - store: builtins.str - """The Store name of the Stream's ref.""" - def __init__( - self, - *, - seq: builtins.int = ..., - stream_id: builtins.str = ..., - store: builtins.str = ..., - ) -> None: ... - def ClearField( - self, - field_name: typing.Literal[ - "seq", b"seq", "store", b"store", "stream_id", b"stream_id" - ], ) -> None: ... + def ClearField(self, field_name: typing.Literal["appends", b"appends"]) -> None: ... -global___StreamCloseIntent = StreamCloseIntent +global___StreamAppendMarkerData = StreamAppendMarkerData @typing.final class StreamAppendResult(google.protobuf.message.Message): @@ -338,7 +269,7 @@ class StreamFailure(google.protobuf.message.Message): MESSAGE_FIELD_NUMBER: builtins.int reason: builtins.str """The name of the `temporalio.api.enums.v1.StreamErrorReason`, such as - `STREAM_ERROR_REASON_CLOSED`. History stores the name, so a reason must never change its name. + `STREAM_ERROR_REASON_FENCED`. History stores the name, so a reason must never change its name. """ message: builtins.str """The message of the failure, of at most 4096 bytes.""" @@ -355,42 +286,30 @@ class StreamFailure(google.protobuf.message.Message): global___StreamFailure = StreamFailure @typing.final -class StreamCloseResult(google.protobuf.message.Message): +class StreamReadMarkerData(google.protobuf.message.Message): + """The data of a `core_stream_read` marker. Core records one in each activation in which Workflow + code got the page of a read, and one with no entry by the rule of `StreamAppendMarkerData`. The + marker keeps the offsets, the count and a digest of each page, never its Records. A replay reads + the Records from the Store again. The JSON rules of `StreamAppendMarkerData` apply. + """ + DESCRIPTOR: google.protobuf.descriptor.Descriptor - SEQ_FIELD_NUMBER: builtins.int - ACTIVATION_INDEX_FIELD_NUMBER: builtins.int - FAILURE_FIELD_NUMBER: builtins.int - seq: builtins.int - activation_index: builtins.int - """The index of the activation, within its Workflow Task, in which Workflow code got the result.""" + READS_FIELD_NUMBER: builtins.int @property - def failure(self) -> global___StreamFailure: - """Unset if the Stream is closed.""" - + def reads( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___StreamReadResult + ]: ... def __init__( self, *, - seq: builtins.int = ..., - activation_index: builtins.int = ..., - failure: global___StreamFailure | None = ..., - ) -> None: ... - def HasField( - self, field_name: typing.Literal["failure", b"failure"] - ) -> builtins.bool: ... - def ClearField( - self, - field_name: typing.Literal[ - "activation_index", - b"activation_index", - "failure", - b"failure", - "seq", - b"seq", - ], + reads: collections.abc.Iterable[global___StreamReadResult] | None = ..., ) -> None: ... + def ClearField(self, field_name: typing.Literal["reads", b"reads"]) -> None: ... -global___StreamCloseResult = StreamCloseResult +global___StreamReadMarkerData = StreamReadMarkerData @typing.final class StreamReadResult(google.protobuf.message.Message): @@ -403,7 +322,6 @@ class StreamReadResult(google.protobuf.message.Message): FROM_OFFSET_FIELD_NUMBER: builtins.int PAGE_FIELD_NUMBER: builtins.int FAILURE_FIELD_NUMBER: builtins.int - CANCELLED_FIELD_NUMBER: builtins.int seq: builtins.int stream_id: builtins.str store: builtins.str @@ -411,15 +329,11 @@ class StreamReadResult(google.protobuf.message.Message): activation_index: builtins.int """The index of the activation, within its Workflow Task, in which Workflow code got the result.""" from_offset: builtins.bytes - """The `from_offset` of the read. A replay reads the Records of a page after it.""" + """The `from_offset` of the read. A replay reads the Records of the page after it.""" @property def page(self) -> global___StreamReadPage: ... @property def failure(self) -> global___StreamFailure: ... - @property - def cancelled(self) -> google.protobuf.empty_pb2.Empty: - """Workflow code cancelled the read before it got the job of the read.""" - def __init__( self, *, @@ -430,19 +344,11 @@ class StreamReadResult(google.protobuf.message.Message): from_offset: builtins.bytes = ..., page: global___StreamReadPage | None = ..., failure: global___StreamFailure | None = ..., - cancelled: google.protobuf.empty_pb2.Empty | None = ..., ) -> None: ... def HasField( self, field_name: typing.Literal[ - "cancelled", - b"cancelled", - "failure", - b"failure", - "page", - b"page", - "result", - b"result", + "failure", b"failure", "page", b"page", "result", b"result" ], ) -> builtins.bool: ... def ClearField( @@ -450,8 +356,6 @@ class StreamReadResult(google.protobuf.message.Message): field_name: typing.Literal[ "activation_index", b"activation_index", - "cancelled", - b"cancelled", "failure", b"failure", "from_offset", @@ -470,53 +374,58 @@ class StreamReadResult(google.protobuf.message.Message): ) -> None: ... def WhichOneof( self, oneof_group: typing.Literal["result", b"result"] - ) -> typing.Literal["page", "failure", "cancelled"] | None: ... + ) -> typing.Literal["page", "failure"] | None: ... global___StreamReadResult = StreamReadResult @typing.final class StreamReadPage(google.protobuf.message.Message): - """A page that a read gave Workflow code.""" + """A page that a read gave Workflow code, without its Records.""" DESCRIPTOR: google.protobuf.descriptor.Descriptor RECORD_COUNT_FIELD_NUMBER: builtins.int - DONE_FIELD_NUMBER: builtins.int DIGEST_FIELD_NUMBER: builtins.int RECORD_BYTES_FIELD_NUMBER: builtins.int + LAST_OFFSET_FIELD_NUMBER: builtins.int + WAIT_CUT_FIELD_NUMBER: builtins.int record_count: builtins.int - """The number of Records in the page.""" - done: builtins.bool - """True if the Stream was closed and had no Record after this page.""" digest: builtins.bytes - """The first 16 bytes of the SHA-256 of the Records. It's empty for a read with - `records_in_history`, whose Records are in the details of the marker, or if the page has no - Record. + """The first 16 bytes of a SHA-256 over the Records, in an encoding that Core owns. It's empty if + the page has no Record. """ record_bytes: builtins.int - """The bytes of the Records, each as a page of a read encodes it, with the tag and the length of - its field. That is the measure of the `max_bytes` of a read. It's set when `digest` is, so a - replay knows how much it reads. + """The size of the Records, as the `max_bytes` of a read measures it. A replay asks the Store for + this much. """ + last_offset: builtins.bytes + """The `last_offset` that Workflow code got. A replay gives the same value, since another read of + the Store can end at another offset. + """ + wait_cut: builtins.bool + """The `wait_cut` that Workflow code got with the page.""" def __init__( self, *, record_count: builtins.int = ..., - done: builtins.bool = ..., digest: builtins.bytes = ..., record_bytes: builtins.int = ..., + last_offset: builtins.bytes = ..., + wait_cut: builtins.bool = ..., ) -> None: ... def ClearField( self, field_name: typing.Literal[ "digest", b"digest", - "done", - b"done", + "last_offset", + b"last_offset", "record_bytes", b"record_bytes", "record_count", b"record_count", + "wait_cut", + b"wait_cut", ], ) -> None: ... diff --git a/temporalio/bridge/proto/workflow_activation/__init__.py b/temporalio/bridge/proto/workflow_activation/__init__.py index 6db42d326e..decfcf1474 100644 --- a/temporalio/bridge/proto/workflow_activation/__init__.py +++ b/temporalio/bridge/proto/workflow_activation/__init__.py @@ -17,7 +17,6 @@ ResolveRequestCancelExternalWorkflow, ResolveSignalExternalWorkflow, ResolveStreamAppend, - ResolveStreamClose, ResolveStreamRead, SignalWorkflow, StreamAppended, @@ -46,7 +45,6 @@ "ResolveRequestCancelExternalWorkflow", "ResolveSignalExternalWorkflow", "ResolveStreamAppend", - "ResolveStreamClose", "ResolveStreamRead", "SignalWorkflow", "StreamAppended", diff --git a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py index cfa0eacff1..1794fc18e9 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py @@ -52,7 +52,7 @@ ) DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n?temporal/sdk/core/workflow_activation/workflow_activation.proto\x12\x1b\x63oresdk.workflow_activation\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a%temporal/api/failure/v1/message.proto\x1a#temporal/api/nexus/v1/message.proto\x1a$temporal/api/update/v1/message.proto\x1a$temporal/api/common/v1/message.proto\x1a$temporal/api/stream/v1/message.proto\x1a(temporal/api/enums/v1/failed_cause.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a\x37temporal/sdk/core/activity_result/activity_result.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a%temporal/sdk/core/common/common.proto\x1a#temporal/sdk/core/nexus/nexus.proto"\xa2\x04\n\x12WorkflowActivation\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x14\n\x0cis_replaying\x18\x03 \x01(\x08\x12\x16\n\x0ehistory_length\x18\x04 \x01(\r\x12@\n\x04jobs\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.WorkflowActivationJob\x12 \n\x18\x61vailable_internal_flags\x18\x06 \x03(\r\x12\x1a\n\x12history_size_bytes\x18\x07 \x01(\x04\x12!\n\x19\x63ontinue_as_new_suggested\x18\x08 \x01(\x08\x12T\n#deployment_version_for_current_task\x18\t \x01(\x0b\x32\'.coresdk.common.WorkerDeploymentVersion\x12\x18\n\x10last_sdk_version\x18\n \x01(\t\x12Z\n\x1fsuggest_continue_as_new_reasons\x18\x0b \x03(\x0e\x32\x31.temporal.api.enums.v1.SuggestContinueAsNewReason\x12\x30\n(target_worker_deployment_version_changed\x18\x0c \x01(\x08"\xd3\x0c\n\x15WorkflowActivationJob\x12N\n\x13initialize_workflow\x18\x01 \x01(\x0b\x32/.coresdk.workflow_activation.InitializeWorkflowH\x00\x12<\n\nfire_timer\x18\x02 \x01(\x0b\x32&.coresdk.workflow_activation.FireTimerH\x00\x12K\n\x12update_random_seed\x18\x04 \x01(\x0b\x32-.coresdk.workflow_activation.UpdateRandomSeedH\x00\x12\x44\n\x0equery_workflow\x18\x05 \x01(\x0b\x32*.coresdk.workflow_activation.QueryWorkflowH\x00\x12\x46\n\x0f\x63\x61ncel_workflow\x18\x06 \x01(\x0b\x32+.coresdk.workflow_activation.CancelWorkflowH\x00\x12\x46\n\x0fsignal_workflow\x18\x07 \x01(\x0b\x32+.coresdk.workflow_activation.SignalWorkflowH\x00\x12H\n\x10resolve_activity\x18\x08 \x01(\x0b\x32,.coresdk.workflow_activation.ResolveActivityH\x00\x12G\n\x10notify_has_patch\x18\t \x01(\x0b\x32+.coresdk.workflow_activation.NotifyHasPatchH\x00\x12q\n&resolve_child_workflow_execution_start\x18\n \x01(\x0b\x32?.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartH\x00\x12\x66\n resolve_child_workflow_execution\x18\x0b \x01(\x0b\x32:.coresdk.workflow_activation.ResolveChildWorkflowExecutionH\x00\x12\x66\n resolve_signal_external_workflow\x18\x0c \x01(\x0b\x32:.coresdk.workflow_activation.ResolveSignalExternalWorkflowH\x00\x12u\n(resolve_request_cancel_external_workflow\x18\r \x01(\x0b\x32\x41.coresdk.workflow_activation.ResolveRequestCancelExternalWorkflowH\x00\x12:\n\tdo_update\x18\x0e \x01(\x0b\x32%.coresdk.workflow_activation.DoUpdateH\x00\x12`\n\x1dresolve_nexus_operation_start\x18\x0f \x01(\x0b\x32\x37.coresdk.workflow_activation.ResolveNexusOperationStartH\x00\x12U\n\x17resolve_nexus_operation\x18\x10 \x01(\x0b\x32\x32.coresdk.workflow_activation.ResolveNexusOperationH\x00\x12M\n\x13resolve_stream_read\x18\x11 \x01(\x0b\x32..coresdk.workflow_activation.ResolveStreamReadH\x00\x12Q\n\x15resolve_stream_append\x18\x12 \x01(\x0b\x32\x30.coresdk.workflow_activation.ResolveStreamAppendH\x00\x12O\n\x14resolve_stream_close\x18\x13 \x01(\x0b\x32/.coresdk.workflow_activation.ResolveStreamCloseH\x00\x12I\n\x11remove_from_cache\x18\x32 \x01(\x0b\x32,.coresdk.workflow_activation.RemoveFromCacheH\x00\x42\t\n\x07variant"\xe3\x0b\n\x12InitializeWorkflow\x12\x15\n\rworkflow_type\x18\x01 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x17\n\x0frandomness_seed\x18\x04 \x01(\x04\x12M\n\x07headers\x18\x05 \x03(\x0b\x32<.coresdk.workflow_activation.InitializeWorkflow.HeadersEntry\x12\x10\n\x08identity\x18\x06 \x01(\t\x12I\n\x14parent_workflow_info\x18\x07 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecution\x12=\n\x1aworkflow_execution_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14workflow_run_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\'\n\x1f\x63ontinued_from_execution_run_id\x18\x0b \x01(\t\x12J\n\x13\x63ontinued_initiator\x18\x0c \x01(\x0e\x32-.temporal.api.enums.v1.ContinueAsNewInitiator\x12;\n\x11\x63ontinued_failure\x18\r \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12@\n\x16last_completion_result\x18\x0e \x01(\x0b\x32 .temporal.api.common.v1.Payloads\x12\x1e\n\x16\x66irst_execution_run_id\x18\x0f \x01(\t\x12\x39\n\x0cretry_policy\x18\x10 \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x0f\n\x07\x61ttempt\x18\x11 \x01(\x05\x12\x15\n\rcron_schedule\x18\x12 \x01(\t\x12\x46\n"workflow_execution_expiration_time\x18\x13 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x45\n"cron_schedule_to_schedule_interval\x18\x14 \x01(\x0b\x32\x19.google.protobuf.Duration\x12*\n\x04memo\x18\x15 \x01(\x0b\x32\x1c.temporal.api.common.v1.Memo\x12\x43\n\x11search_attributes\x18\x16 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12.\n\nstart_time\x18\x17 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12@\n\rroot_workflow\x18\x18 \x01(\x0b\x32).temporal.api.common.v1.WorkflowExecution\x12\x32\n\x08priority\x18\x19 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12!\n\x19original_execution_run_id\x18\x1a \x01(\t\x12\x65\n&propagated_nexus_serialization_context\x18\x1b \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x18\n\tFireTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r"m\n\x0fResolveActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12;\n\x06result\x18\x02 \x01(\x0b\x32+.coresdk.activity_result.ActivityResolution\x12\x10\n\x08is_local\x18\x03 \x01(\x08"\xd1\x02\n"ResolveChildWorkflowExecutionStart\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12[\n\tsucceeded\x18\x02 \x01(\x0b\x32\x46.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartSuccessH\x00\x12X\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32\x46.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartFailureH\x00\x12]\n\tcancelled\x18\x04 \x01(\x0b\x32H.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartCancelledH\x00\x42\x08\n\x06status";\n)ResolveChildWorkflowExecutionStartSuccess\x12\x0e\n\x06run_id\x18\x01 \x01(\t"\xa6\x01\n)ResolveChildWorkflowExecutionStartFailure\x12\x13\n\x0bworkflow_id\x18\x01 \x01(\t\x12\x15\n\rworkflow_type\x18\x02 \x01(\t\x12M\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32>.coresdk.child_workflow.StartChildWorkflowExecutionFailedCause"`\n+ResolveChildWorkflowExecutionStartCancelled\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"i\n\x1dResolveChildWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12;\n\x06result\x18\x02 \x01(\x0b\x32+.coresdk.child_workflow.ChildWorkflowResult"+\n\x10UpdateRandomSeed\x12\x17\n\x0frandomness_seed\x18\x01 \x01(\x04"\x84\x02\n\rQueryWorkflow\x12\x10\n\x08query_id\x18\x01 \x01(\t\x12\x12\n\nquery_type\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12H\n\x07headers\x18\x05 \x03(\x0b\x32\x37.coresdk.workflow_activation.QueryWorkflow.HeadersEntry\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01" \n\x0e\x43\x61ncelWorkflow\x12\x0e\n\x06reason\x18\x01 \x01(\t"\xa1\x02\n\x0eSignalWorkflow\x12\x13\n\x0bsignal_name\x18\x01 \x01(\t\x12.\n\x05input\x18\x02 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x10\n\x08identity\x18\x03 \x01(\t\x12I\n\x07headers\x18\x05 \x03(\x0b\x32\x38.coresdk.workflow_activation.SignalWorkflow.HeadersEntry\x12\x1c\n\x14originating_event_id\x18\x06 \x01(\x03\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01""\n\x0eNotifyHasPatch\x12\x10\n\x08patch_id\x18\x01 \x01(\t"\xb1\x01\n\x1dResolveSignalExternalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x07\x66\x61ilure\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12P\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32\x41.temporal.api.enums.v1.SignalExternalWorkflowExecutionFailedCause"\xb8\x01\n$ResolveRequestCancelExternalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x07\x66\x61ilure\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12P\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32\x41.temporal.api.enums.v1.CancelExternalWorkflowExecutionFailedCause"\xb2\x03\n\x08\x44oUpdate\x12\n\n\x02id\x18\x01 \x01(\t\x12\x1c\n\x14protocol_instance_id\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12.\n\x05input\x18\x04 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x43\n\x07headers\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.DoUpdate.HeadersEntry\x12*\n\x04meta\x18\x06 \x01(\x0b\x32\x1c.temporal.api.update.v1.Meta\x12\x15\n\rrun_validator\x18\x07 \x01(\x08\x12\x65\n&propagated_nexus_serialization_context\x18\x08 \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x9a\x01\n\x1aResolveNexusOperationStart\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x19\n\x0foperation_token\x18\x02 \x01(\tH\x00\x12\x16\n\x0cstarted_sync\x18\x03 \x01(\x08H\x00\x12\x32\n\x06\x66\x61iled\x18\x04 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status"Y\n\x15ResolveNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x33\n\x06result\x18\x02 \x01(\x0b\x32#.coresdk.nexus.NexusOperationResult"\xe0\x02\n\x0fRemoveFromCache\x12\x0f\n\x07message\x18\x01 \x01(\t\x12K\n\x06reason\x18\x02 \x01(\x0e\x32;.coresdk.workflow_activation.RemoveFromCache.EvictionReason"\xee\x01\n\x0e\x45victionReason\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nCACHE_FULL\x10\x01\x12\x0e\n\nCACHE_MISS\x10\x02\x12\x12\n\x0eNONDETERMINISM\x10\x03\x12\r\n\tLANG_FAIL\x10\x04\x12\x12\n\x0eLANG_REQUESTED\x10\x05\x12\x12\n\x0eTASK_NOT_FOUND\x10\x06\x12\x15\n\x11UNHANDLED_COMMAND\x10\x07\x12\t\n\x05\x46\x41TAL\x10\x08\x12\x1f\n\x1bPAGINATION_OR_HISTORY_FETCH\x10\t\x12\x1d\n\x19WORKFLOW_EXECUTION_ENDING\x10\n"\xa1\x01\n\x13ResolveStreamAppend\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12?\n\x08\x61ppended\x18\x02 \x01(\x0b\x32+.coresdk.workflow_activation.StreamAppendedH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status";\n\x0eStreamAppended\x12\x14\n\x0c\x66irst_offset\x18\x01 \x01(\x0c\x12\x13\n\x0blast_offset\x18\x02 \x01(\x0c"S\n\x12ResolveStreamClose\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x30\n\x06\x66\x61iled\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"\x97\x01\n\x11ResolveStreamRead\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x37\n\x04page\x18\x02 \x01(\x0b\x32\'.coresdk.workflow_activation.StreamPageH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status"f\n\nStreamPage\x12\x35\n\x07records\x18\x01 \x03(\x0b\x32$.temporal.api.stream.v1.StreamRecord\x12\x0c\n\x04\x64one\x18\x02 \x01(\x08\x12\x13\n\x0blast_offset\x18\x03 \x01(\x0c\x42\x38\xea\x02\x35Temporalio::Internal::Bridge::Api::WorkflowActivationb\x06proto3' + b'\n?temporal/sdk/core/workflow_activation/workflow_activation.proto\x12\x1b\x63oresdk.workflow_activation\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a%temporal/api/failure/v1/message.proto\x1a#temporal/api/nexus/v1/message.proto\x1a$temporal/api/update/v1/message.proto\x1a$temporal/api/common/v1/message.proto\x1a(temporal/api/enums/v1/failed_cause.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a$temporal/api/stream/v1/message.proto\x1a\x37temporal/sdk/core/activity_result/activity_result.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a%temporal/sdk/core/common/common.proto\x1a#temporal/sdk/core/nexus/nexus.proto"\xa2\x04\n\x12WorkflowActivation\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x14\n\x0cis_replaying\x18\x03 \x01(\x08\x12\x16\n\x0ehistory_length\x18\x04 \x01(\r\x12@\n\x04jobs\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.WorkflowActivationJob\x12 \n\x18\x61vailable_internal_flags\x18\x06 \x03(\r\x12\x1a\n\x12history_size_bytes\x18\x07 \x01(\x04\x12!\n\x19\x63ontinue_as_new_suggested\x18\x08 \x01(\x08\x12T\n#deployment_version_for_current_task\x18\t \x01(\x0b\x32\'.coresdk.common.WorkerDeploymentVersion\x12\x18\n\x10last_sdk_version\x18\n \x01(\t\x12Z\n\x1fsuggest_continue_as_new_reasons\x18\x0b \x03(\x0e\x32\x31.temporal.api.enums.v1.SuggestContinueAsNewReason\x12\x30\n(target_worker_deployment_version_changed\x18\x0c \x01(\x08"\x82\x0c\n\x15WorkflowActivationJob\x12N\n\x13initialize_workflow\x18\x01 \x01(\x0b\x32/.coresdk.workflow_activation.InitializeWorkflowH\x00\x12<\n\nfire_timer\x18\x02 \x01(\x0b\x32&.coresdk.workflow_activation.FireTimerH\x00\x12K\n\x12update_random_seed\x18\x04 \x01(\x0b\x32-.coresdk.workflow_activation.UpdateRandomSeedH\x00\x12\x44\n\x0equery_workflow\x18\x05 \x01(\x0b\x32*.coresdk.workflow_activation.QueryWorkflowH\x00\x12\x46\n\x0f\x63\x61ncel_workflow\x18\x06 \x01(\x0b\x32+.coresdk.workflow_activation.CancelWorkflowH\x00\x12\x46\n\x0fsignal_workflow\x18\x07 \x01(\x0b\x32+.coresdk.workflow_activation.SignalWorkflowH\x00\x12H\n\x10resolve_activity\x18\x08 \x01(\x0b\x32,.coresdk.workflow_activation.ResolveActivityH\x00\x12G\n\x10notify_has_patch\x18\t \x01(\x0b\x32+.coresdk.workflow_activation.NotifyHasPatchH\x00\x12q\n&resolve_child_workflow_execution_start\x18\n \x01(\x0b\x32?.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartH\x00\x12\x66\n resolve_child_workflow_execution\x18\x0b \x01(\x0b\x32:.coresdk.workflow_activation.ResolveChildWorkflowExecutionH\x00\x12\x66\n resolve_signal_external_workflow\x18\x0c \x01(\x0b\x32:.coresdk.workflow_activation.ResolveSignalExternalWorkflowH\x00\x12u\n(resolve_request_cancel_external_workflow\x18\r \x01(\x0b\x32\x41.coresdk.workflow_activation.ResolveRequestCancelExternalWorkflowH\x00\x12:\n\tdo_update\x18\x0e \x01(\x0b\x32%.coresdk.workflow_activation.DoUpdateH\x00\x12`\n\x1dresolve_nexus_operation_start\x18\x0f \x01(\x0b\x32\x37.coresdk.workflow_activation.ResolveNexusOperationStartH\x00\x12U\n\x17resolve_nexus_operation\x18\x10 \x01(\x0b\x32\x32.coresdk.workflow_activation.ResolveNexusOperationH\x00\x12Q\n\x15resolve_stream_append\x18\x11 \x01(\x0b\x32\x30.coresdk.workflow_activation.ResolveStreamAppendH\x00\x12M\n\x13resolve_stream_read\x18\x12 \x01(\x0b\x32..coresdk.workflow_activation.ResolveStreamReadH\x00\x12I\n\x11remove_from_cache\x18\x32 \x01(\x0b\x32,.coresdk.workflow_activation.RemoveFromCacheH\x00\x42\t\n\x07variant"\xe3\x0b\n\x12InitializeWorkflow\x12\x15\n\rworkflow_type\x18\x01 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x17\n\x0frandomness_seed\x18\x04 \x01(\x04\x12M\n\x07headers\x18\x05 \x03(\x0b\x32<.coresdk.workflow_activation.InitializeWorkflow.HeadersEntry\x12\x10\n\x08identity\x18\x06 \x01(\t\x12I\n\x14parent_workflow_info\x18\x07 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecution\x12=\n\x1aworkflow_execution_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14workflow_run_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\'\n\x1f\x63ontinued_from_execution_run_id\x18\x0b \x01(\t\x12J\n\x13\x63ontinued_initiator\x18\x0c \x01(\x0e\x32-.temporal.api.enums.v1.ContinueAsNewInitiator\x12;\n\x11\x63ontinued_failure\x18\r \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12@\n\x16last_completion_result\x18\x0e \x01(\x0b\x32 .temporal.api.common.v1.Payloads\x12\x1e\n\x16\x66irst_execution_run_id\x18\x0f \x01(\t\x12\x39\n\x0cretry_policy\x18\x10 \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x0f\n\x07\x61ttempt\x18\x11 \x01(\x05\x12\x15\n\rcron_schedule\x18\x12 \x01(\t\x12\x46\n"workflow_execution_expiration_time\x18\x13 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x45\n"cron_schedule_to_schedule_interval\x18\x14 \x01(\x0b\x32\x19.google.protobuf.Duration\x12*\n\x04memo\x18\x15 \x01(\x0b\x32\x1c.temporal.api.common.v1.Memo\x12\x43\n\x11search_attributes\x18\x16 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12.\n\nstart_time\x18\x17 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12@\n\rroot_workflow\x18\x18 \x01(\x0b\x32).temporal.api.common.v1.WorkflowExecution\x12\x32\n\x08priority\x18\x19 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12!\n\x19original_execution_run_id\x18\x1a \x01(\t\x12\x65\n&propagated_nexus_serialization_context\x18\x1b \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x18\n\tFireTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r"m\n\x0fResolveActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12;\n\x06result\x18\x02 \x01(\x0b\x32+.coresdk.activity_result.ActivityResolution\x12\x10\n\x08is_local\x18\x03 \x01(\x08"\xd1\x02\n"ResolveChildWorkflowExecutionStart\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12[\n\tsucceeded\x18\x02 \x01(\x0b\x32\x46.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartSuccessH\x00\x12X\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32\x46.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartFailureH\x00\x12]\n\tcancelled\x18\x04 \x01(\x0b\x32H.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartCancelledH\x00\x42\x08\n\x06status";\n)ResolveChildWorkflowExecutionStartSuccess\x12\x0e\n\x06run_id\x18\x01 \x01(\t"\xa6\x01\n)ResolveChildWorkflowExecutionStartFailure\x12\x13\n\x0bworkflow_id\x18\x01 \x01(\t\x12\x15\n\rworkflow_type\x18\x02 \x01(\t\x12M\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32>.coresdk.child_workflow.StartChildWorkflowExecutionFailedCause"`\n+ResolveChildWorkflowExecutionStartCancelled\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"i\n\x1dResolveChildWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12;\n\x06result\x18\x02 \x01(\x0b\x32+.coresdk.child_workflow.ChildWorkflowResult"+\n\x10UpdateRandomSeed\x12\x17\n\x0frandomness_seed\x18\x01 \x01(\x04"\x84\x02\n\rQueryWorkflow\x12\x10\n\x08query_id\x18\x01 \x01(\t\x12\x12\n\nquery_type\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12H\n\x07headers\x18\x05 \x03(\x0b\x32\x37.coresdk.workflow_activation.QueryWorkflow.HeadersEntry\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01" \n\x0e\x43\x61ncelWorkflow\x12\x0e\n\x06reason\x18\x01 \x01(\t"\xa1\x02\n\x0eSignalWorkflow\x12\x13\n\x0bsignal_name\x18\x01 \x01(\t\x12.\n\x05input\x18\x02 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x10\n\x08identity\x18\x03 \x01(\t\x12I\n\x07headers\x18\x05 \x03(\x0b\x32\x38.coresdk.workflow_activation.SignalWorkflow.HeadersEntry\x12\x1c\n\x14originating_event_id\x18\x06 \x01(\x03\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01""\n\x0eNotifyHasPatch\x12\x10\n\x08patch_id\x18\x01 \x01(\t"\xb1\x01\n\x1dResolveSignalExternalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x07\x66\x61ilure\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12P\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32\x41.temporal.api.enums.v1.SignalExternalWorkflowExecutionFailedCause"\xb8\x01\n$ResolveRequestCancelExternalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x07\x66\x61ilure\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12P\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32\x41.temporal.api.enums.v1.CancelExternalWorkflowExecutionFailedCause"\xb2\x03\n\x08\x44oUpdate\x12\n\n\x02id\x18\x01 \x01(\t\x12\x1c\n\x14protocol_instance_id\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12.\n\x05input\x18\x04 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x43\n\x07headers\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.DoUpdate.HeadersEntry\x12*\n\x04meta\x18\x06 \x01(\x0b\x32\x1c.temporal.api.update.v1.Meta\x12\x15\n\rrun_validator\x18\x07 \x01(\x08\x12\x65\n&propagated_nexus_serialization_context\x18\x08 \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x9a\x01\n\x1aResolveNexusOperationStart\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x19\n\x0foperation_token\x18\x02 \x01(\tH\x00\x12\x16\n\x0cstarted_sync\x18\x03 \x01(\x08H\x00\x12\x32\n\x06\x66\x61iled\x18\x04 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status"Y\n\x15ResolveNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x33\n\x06result\x18\x02 \x01(\x0b\x32#.coresdk.nexus.NexusOperationResult"\xe0\x02\n\x0fRemoveFromCache\x12\x0f\n\x07message\x18\x01 \x01(\t\x12K\n\x06reason\x18\x02 \x01(\x0e\x32;.coresdk.workflow_activation.RemoveFromCache.EvictionReason"\xee\x01\n\x0e\x45victionReason\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nCACHE_FULL\x10\x01\x12\x0e\n\nCACHE_MISS\x10\x02\x12\x12\n\x0eNONDETERMINISM\x10\x03\x12\r\n\tLANG_FAIL\x10\x04\x12\x12\n\x0eLANG_REQUESTED\x10\x05\x12\x12\n\x0eTASK_NOT_FOUND\x10\x06\x12\x15\n\x11UNHANDLED_COMMAND\x10\x07\x12\t\n\x05\x46\x41TAL\x10\x08\x12\x1f\n\x1bPAGINATION_OR_HISTORY_FETCH\x10\t\x12\x1d\n\x19WORKFLOW_EXECUTION_ENDING\x10\n"\xa1\x01\n\x13ResolveStreamAppend\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12?\n\x08\x61ppended\x18\x02 \x01(\x0b\x32+.coresdk.workflow_activation.StreamAppendedH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status";\n\x0eStreamAppended\x12\x14\n\x0c\x66irst_offset\x18\x01 \x01(\x0c\x12\x13\n\x0blast_offset\x18\x02 \x01(\x0c"\x97\x01\n\x11ResolveStreamRead\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x37\n\x04page\x18\x02 \x01(\x0b\x32\'.coresdk.workflow_activation.StreamPageH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status"j\n\nStreamPage\x12\x35\n\x07records\x18\x01 \x03(\x0b\x32$.temporal.api.stream.v1.StreamRecord\x12\x13\n\x0blast_offset\x18\x02 \x01(\x0c\x12\x10\n\x08wait_cut\x18\x03 \x01(\x08\x42\x38\xea\x02\x35Temporalio::Internal::Bridge::Api::WorkflowActivationb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -73,63 +73,61 @@ _WORKFLOWACTIVATION._serialized_start = 649 _WORKFLOWACTIVATION._serialized_end = 1195 _WORKFLOWACTIVATIONJOB._serialized_start = 1198 - _WORKFLOWACTIVATIONJOB._serialized_end = 2817 - _INITIALIZEWORKFLOW._serialized_start = 2820 - _INITIALIZEWORKFLOW._serialized_end = 4327 - _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_start = 4248 - _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_end = 4327 - _FIRETIMER._serialized_start = 4329 - _FIRETIMER._serialized_end = 4353 - _RESOLVEACTIVITY._serialized_start = 4355 - _RESOLVEACTIVITY._serialized_end = 4464 - _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_start = 4467 - _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_end = 4804 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_start = 4806 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_end = 4865 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_start = 4868 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_end = 5034 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_start = 5036 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_end = 5132 - _RESOLVECHILDWORKFLOWEXECUTION._serialized_start = 5134 - _RESOLVECHILDWORKFLOWEXECUTION._serialized_end = 5239 - _UPDATERANDOMSEED._serialized_start = 5241 - _UPDATERANDOMSEED._serialized_end = 5284 - _QUERYWORKFLOW._serialized_start = 5287 - _QUERYWORKFLOW._serialized_end = 5547 - _QUERYWORKFLOW_HEADERSENTRY._serialized_start = 4248 - _QUERYWORKFLOW_HEADERSENTRY._serialized_end = 4327 - _CANCELWORKFLOW._serialized_start = 5549 - _CANCELWORKFLOW._serialized_end = 5581 - _SIGNALWORKFLOW._serialized_start = 5584 - _SIGNALWORKFLOW._serialized_end = 5873 - _SIGNALWORKFLOW_HEADERSENTRY._serialized_start = 4248 - _SIGNALWORKFLOW_HEADERSENTRY._serialized_end = 4327 - _NOTIFYHASPATCH._serialized_start = 5875 - _NOTIFYHASPATCH._serialized_end = 5909 - _RESOLVESIGNALEXTERNALWORKFLOW._serialized_start = 5912 - _RESOLVESIGNALEXTERNALWORKFLOW._serialized_end = 6089 - _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_start = 6092 - _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_end = 6276 - _DOUPDATE._serialized_start = 6279 - _DOUPDATE._serialized_end = 6713 - _DOUPDATE_HEADERSENTRY._serialized_start = 4248 - _DOUPDATE_HEADERSENTRY._serialized_end = 4327 - _RESOLVENEXUSOPERATIONSTART._serialized_start = 6716 - _RESOLVENEXUSOPERATIONSTART._serialized_end = 6870 - _RESOLVENEXUSOPERATION._serialized_start = 6872 - _RESOLVENEXUSOPERATION._serialized_end = 6961 - _REMOVEFROMCACHE._serialized_start = 6964 - _REMOVEFROMCACHE._serialized_end = 7316 - _REMOVEFROMCACHE_EVICTIONREASON._serialized_start = 7078 - _REMOVEFROMCACHE_EVICTIONREASON._serialized_end = 7316 - _RESOLVESTREAMAPPEND._serialized_start = 7319 - _RESOLVESTREAMAPPEND._serialized_end = 7480 - _STREAMAPPENDED._serialized_start = 7482 - _STREAMAPPENDED._serialized_end = 7541 - _RESOLVESTREAMCLOSE._serialized_start = 7543 - _RESOLVESTREAMCLOSE._serialized_end = 7626 - _RESOLVESTREAMREAD._serialized_start = 7629 - _RESOLVESTREAMREAD._serialized_end = 7780 - _STREAMPAGE._serialized_start = 7782 - _STREAMPAGE._serialized_end = 7884 + _WORKFLOWACTIVATIONJOB._serialized_end = 2736 + _INITIALIZEWORKFLOW._serialized_start = 2739 + _INITIALIZEWORKFLOW._serialized_end = 4246 + _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_start = 4167 + _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_end = 4246 + _FIRETIMER._serialized_start = 4248 + _FIRETIMER._serialized_end = 4272 + _RESOLVEACTIVITY._serialized_start = 4274 + _RESOLVEACTIVITY._serialized_end = 4383 + _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_start = 4386 + _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_end = 4723 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_start = 4725 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_end = 4784 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_start = 4787 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_end = 4953 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_start = 4955 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_end = 5051 + _RESOLVECHILDWORKFLOWEXECUTION._serialized_start = 5053 + _RESOLVECHILDWORKFLOWEXECUTION._serialized_end = 5158 + _UPDATERANDOMSEED._serialized_start = 5160 + _UPDATERANDOMSEED._serialized_end = 5203 + _QUERYWORKFLOW._serialized_start = 5206 + _QUERYWORKFLOW._serialized_end = 5466 + _QUERYWORKFLOW_HEADERSENTRY._serialized_start = 4167 + _QUERYWORKFLOW_HEADERSENTRY._serialized_end = 4246 + _CANCELWORKFLOW._serialized_start = 5468 + _CANCELWORKFLOW._serialized_end = 5500 + _SIGNALWORKFLOW._serialized_start = 5503 + _SIGNALWORKFLOW._serialized_end = 5792 + _SIGNALWORKFLOW_HEADERSENTRY._serialized_start = 4167 + _SIGNALWORKFLOW_HEADERSENTRY._serialized_end = 4246 + _NOTIFYHASPATCH._serialized_start = 5794 + _NOTIFYHASPATCH._serialized_end = 5828 + _RESOLVESIGNALEXTERNALWORKFLOW._serialized_start = 5831 + _RESOLVESIGNALEXTERNALWORKFLOW._serialized_end = 6008 + _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_start = 6011 + _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_end = 6195 + _DOUPDATE._serialized_start = 6198 + _DOUPDATE._serialized_end = 6632 + _DOUPDATE_HEADERSENTRY._serialized_start = 4167 + _DOUPDATE_HEADERSENTRY._serialized_end = 4246 + _RESOLVENEXUSOPERATIONSTART._serialized_start = 6635 + _RESOLVENEXUSOPERATIONSTART._serialized_end = 6789 + _RESOLVENEXUSOPERATION._serialized_start = 6791 + _RESOLVENEXUSOPERATION._serialized_end = 6880 + _REMOVEFROMCACHE._serialized_start = 6883 + _REMOVEFROMCACHE._serialized_end = 7235 + _REMOVEFROMCACHE_EVICTIONREASON._serialized_start = 6997 + _REMOVEFROMCACHE_EVICTIONREASON._serialized_end = 7235 + _RESOLVESTREAMAPPEND._serialized_start = 7238 + _RESOLVESTREAMAPPEND._serialized_end = 7399 + _STREAMAPPENDED._serialized_start = 7401 + _STREAMAPPENDED._serialized_end = 7460 + _RESOLVESTREAMREAD._serialized_start = 7463 + _RESOLVESTREAMREAD._serialized_end = 7614 + _STREAMPAGE._serialized_start = 7616 + _STREAMPAGE._serialized_end = 7722 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi index baf4ceea26..36336887a3 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi @@ -67,8 +67,8 @@ class WorkflowActivation(google.protobuf.message.Message): this to ensure the LA resolution happens after that cancel (or whatever else it may be) as it normally would have when executing. * Stream results go after the local activity resolutions, because a replay scans ahead for them - too. Appends go first, then closes, then reads, each in `seq` order. If a replay gives several - activations in one, the Stream results keep the order of those activations. + too. Appends go before reads, each in `seq` order. If a replay gives several activations in + one, the Stream results keep the order of those activations. * Queries always go last (and, in fact, always come in their own activation) * Evictions also always come in their own activation @@ -254,9 +254,8 @@ class WorkflowActivationJob(google.protobuf.message.Message): DO_UPDATE_FIELD_NUMBER: builtins.int RESOLVE_NEXUS_OPERATION_START_FIELD_NUMBER: builtins.int RESOLVE_NEXUS_OPERATION_FIELD_NUMBER: builtins.int - RESOLVE_STREAM_READ_FIELD_NUMBER: builtins.int RESOLVE_STREAM_APPEND_FIELD_NUMBER: builtins.int - RESOLVE_STREAM_CLOSE_FIELD_NUMBER: builtins.int + RESOLVE_STREAM_READ_FIELD_NUMBER: builtins.int REMOVE_FROM_CACHE_FIELD_NUMBER: builtins.int @property def initialize_workflow(self) -> global___InitializeWorkflow: @@ -331,17 +330,13 @@ class WorkflowActivationJob(google.protobuf.message.Message): def resolve_nexus_operation(self) -> global___ResolveNexusOperation: """A nexus operation resolved.""" - @property - def resolve_stream_read(self) -> global___ResolveStreamRead: - """A read of a Stream finished.""" - @property def resolve_stream_append(self) -> global___ResolveStreamAppend: """An append to a Stream finished.""" @property - def resolve_stream_close(self) -> global___ResolveStreamClose: - """A close of a Stream finished.""" + def resolve_stream_read(self) -> global___ResolveStreamRead: + """A read of a Stream finished.""" @property def remove_from_cache(self) -> global___RemoveFromCache: @@ -372,9 +367,8 @@ class WorkflowActivationJob(google.protobuf.message.Message): do_update: global___DoUpdate | None = ..., resolve_nexus_operation_start: global___ResolveNexusOperationStart | None = ..., resolve_nexus_operation: global___ResolveNexusOperation | None = ..., - resolve_stream_read: global___ResolveStreamRead | None = ..., resolve_stream_append: global___ResolveStreamAppend | None = ..., - resolve_stream_close: global___ResolveStreamClose | None = ..., + resolve_stream_read: global___ResolveStreamRead | None = ..., remove_from_cache: global___RemoveFromCache | None = ..., ) -> None: ... def HasField( @@ -410,8 +404,6 @@ class WorkflowActivationJob(google.protobuf.message.Message): b"resolve_signal_external_workflow", "resolve_stream_append", b"resolve_stream_append", - "resolve_stream_close", - b"resolve_stream_close", "resolve_stream_read", b"resolve_stream_read", "signal_workflow", @@ -455,8 +447,6 @@ class WorkflowActivationJob(google.protobuf.message.Message): b"resolve_signal_external_workflow", "resolve_stream_append", b"resolve_stream_append", - "resolve_stream_close", - b"resolve_stream_close", "resolve_stream_read", b"resolve_stream_read", "signal_workflow", @@ -486,9 +476,8 @@ class WorkflowActivationJob(google.protobuf.message.Message): "do_update", "resolve_nexus_operation_start", "resolve_nexus_operation", - "resolve_stream_read", "resolve_stream_append", - "resolve_stream_close", + "resolve_stream_read", "remove_from_cache", ] | None @@ -1685,13 +1674,13 @@ global___RemoveFromCache = RemoveFromCache @typing.final class ResolveStreamAppend(google.protobuf.message.Message): - """The result of an `AppendToStream`. Core gives it in the next activation after the Store answers. - History keeps the index of that activation with the result, counted as for the marker of a local - activity, so a replay gives both kinds of result in the order of the first run. A result that - arrives while the task completes comes in the first activation of the next task. + """The result of an `AppendToStream`. Core gives it in the next activation after the Store answers, + or in the first activation of the next task if it arrives while the task completes. - As for a local activity, a replay gives the result in the same activation as the first run only - if workflow task chunking is off. With chunking, a replay can give the jobs of several + The `core_stream_append` marker of that activation records the result with the activation's + index, on the same counter as local activity markers, so a replay gives both kinds of result in + the order of the first run. As for a local activity, the replay uses the same activation as the + first run only if workflow task chunking is off. With chunking, it can give the jobs of several activations in one, in their order. """ @@ -1706,7 +1695,7 @@ class ResolveStreamAppend(google.protobuf.message.Message): def appended(self) -> global___StreamAppended: ... @property def failed(self) -> temporalio.api.failure.v1.message_pb2.Failure: - """An `ApplicationFailureInfo` of the type `stream_`, such as `stream_closed`, with + """An `ApplicationFailureInfo` of the type `stream_`, such as `stream_fenced`, with `non_retryable` set. Its details have one `binary/protobuf` payload of a `temporalio.api.stream.v1.StreamErrorDetails`. """ @@ -1766,41 +1755,11 @@ class StreamAppended(google.protobuf.message.Message): global___StreamAppended = StreamAppended -@typing.final -class ResolveStreamClose(google.protobuf.message.Message): - """The result of a `CloseStream`. The activation rules of `ResolveStreamAppend` apply to it too.""" - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - SEQ_FIELD_NUMBER: builtins.int - FAILED_FIELD_NUMBER: builtins.int - seq: builtins.int - """The `seq` of the `CloseStream`.""" - @property - def failed(self) -> temporalio.api.failure.v1.message_pb2.Failure: - """Unset if the Stream is closed, also when it was already closed. When set, it has the same - parts as the `failed` of a `ResolveStreamAppend`. - """ - - def __init__( - self, - *, - seq: builtins.int = ..., - failed: temporalio.api.failure.v1.message_pb2.Failure | None = ..., - ) -> None: ... - def HasField( - self, field_name: typing.Literal["failed", b"failed"] - ) -> builtins.bool: ... - def ClearField( - self, field_name: typing.Literal["failed", b"failed", "seq", b"seq"] - ) -> None: ... - -global___ResolveStreamClose = ResolveStreamClose - @typing.final class ResolveStreamRead(google.protobuf.message.Message): """The result of a `ReadStream`. Each read gets exactly one, unless Core drops the read (see - `ReadStream`). The activation rules of `ResolveStreamAppend` apply to it too. + `ReadStream`). The activation rules of `ResolveStreamAppend` apply to it too, with the + `core_stream_read` marker in place of the `core_stream_append` one. """ DESCRIPTOR: google.protobuf.descriptor.Descriptor @@ -1846,23 +1805,25 @@ class StreamPage(google.protobuf.message.Message): DESCRIPTOR: google.protobuf.descriptor.Descriptor RECORDS_FIELD_NUMBER: builtins.int - DONE_FIELD_NUMBER: builtins.int LAST_OFFSET_FIELD_NUMBER: builtins.int - done: builtins.bool - """True if the Stream is closed and has no Record after this page.""" + WAIT_CUT_FIELD_NUMBER: builtins.int last_offset: builtins.bytes """The offset where the page ends, also for a page with no Record. The next read can pass it as its `from_offset`. """ + wait_cut: builtins.bool + """True if the page has no Record because the read time of the Workflow Task ended the wait + before the `wait` of the read. A reader that waits for a Record can read again from + `last_offset`. It's false for a page that ends a whole wait. + """ @property def records( self, ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ temporalio.api.stream.v1.message_pb2.StreamRecord ]: - """The Records of the page, in the order of the Stream. It's empty if the Stream is closed and - has no Record after the `from_offset` of the read, or if no Record came while the read - waited. + """The Records of the page, in the order of the Stream. It's empty if no Record came while the + read waited. """ def __init__( @@ -1872,13 +1833,18 @@ class StreamPage(google.protobuf.message.Message): temporalio.api.stream.v1.message_pb2.StreamRecord ] | None = ..., - done: builtins.bool = ..., last_offset: builtins.bytes = ..., + wait_cut: builtins.bool = ..., ) -> None: ... def ClearField( self, field_name: typing.Literal[ - "done", b"done", "last_offset", b"last_offset", "records", b"records" + "last_offset", + b"last_offset", + "records", + b"records", + "wait_cut", + b"wait_cut", ], ) -> None: ... diff --git a/temporalio/bridge/proto/workflow_commands/__init__.py b/temporalio/bridge/proto/workflow_commands/__init__.py index 771fb22db3..280eb77ab2 100644 --- a/temporalio/bridge/proto/workflow_commands/__init__.py +++ b/temporalio/bridge/proto/workflow_commands/__init__.py @@ -5,7 +5,6 @@ CancelSignalWorkflow, CancelTimer, CancelWorkflowExecution, - CloseStream, CompleteWorkflowExecution, ContinueAsNewWorkflowExecution, FailWorkflowExecution, @@ -36,7 +35,6 @@ "CancelSignalWorkflow", "CancelTimer", "CancelWorkflowExecution", - "CloseStream", "CompleteWorkflowExecution", "ContinueAsNewWorkflowExecution", "FailWorkflowExecution", diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py index 8222089545..047d40dc0c 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py @@ -30,10 +30,10 @@ event_group_marker_pb2 as temporal_dot_api_dot_sdk_dot_v1_dot_event__group__marker__pb2, ) from temporalio.api.sdk.v1 import ( - user_metadata_pb2 as temporal_dot_api_dot_sdk_dot_v1_dot_user__metadata__pb2, + stream_pb2 as temporal_dot_api_dot_sdk_dot_v1_dot_stream__pb2, ) -from temporalio.api.stream.v1 import ( - message_pb2 as temporal_dot_api_dot_stream_dot_v1_dot_message__pb2, +from temporalio.api.sdk.v1 import ( + user_metadata_pb2 as temporal_dot_api_dot_sdk_dot_v1_dot_user__metadata__pb2, ) from temporalio.api.workflow.v1 import ( message_pb2 as temporal_dot_api_dot_workflow_dot_v1_dot_message__pb2, @@ -49,7 +49,7 @@ ) DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n;temporal/sdk/core/workflow_commands/workflow_commands.proto\x12\x19\x63oresdk.workflow_commands\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a$temporal/api/common/v1/message.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a%temporal/api/failure/v1/message.proto\x1a\'temporal/api/sdk/v1/user_metadata.proto\x1a,temporal/api/sdk/v1/event_group_marker.proto\x1a$temporal/api/stream/v1/message.proto\x1a&temporal/api/workflow/v1/message.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a#temporal/sdk/core/nexus/nexus.proto\x1a%temporal/sdk/core/common/common.proto"\xee\x11\n\x0fWorkflowCommand\x12\x38\n\ruser_metadata\x18\x64 \x01(\x0b\x32!.temporal.api.sdk.v1.UserMetadata\x12\x42\n\x13\x65vent_group_markers\x18\x65 \x03(\x0b\x32%.temporal.api.sdk.v1.EventGroupMarker\x12<\n\x0bstart_timer\x18\x01 \x01(\x0b\x32%.coresdk.workflow_commands.StartTimerH\x00\x12H\n\x11schedule_activity\x18\x02 \x01(\x0b\x32+.coresdk.workflow_commands.ScheduleActivityH\x00\x12\x42\n\x10respond_to_query\x18\x03 \x01(\x0b\x32&.coresdk.workflow_commands.QueryResultH\x00\x12S\n\x17request_cancel_activity\x18\x04 \x01(\x0b\x32\x30.coresdk.workflow_commands.RequestCancelActivityH\x00\x12>\n\x0c\x63\x61ncel_timer\x18\x05 \x01(\x0b\x32&.coresdk.workflow_commands.CancelTimerH\x00\x12[\n\x1b\x63omplete_workflow_execution\x18\x06 \x01(\x0b\x32\x34.coresdk.workflow_commands.CompleteWorkflowExecutionH\x00\x12S\n\x17\x66\x61il_workflow_execution\x18\x07 \x01(\x0b\x32\x30.coresdk.workflow_commands.FailWorkflowExecutionH\x00\x12g\n"continue_as_new_workflow_execution\x18\x08 \x01(\x0b\x32\x39.coresdk.workflow_commands.ContinueAsNewWorkflowExecutionH\x00\x12W\n\x19\x63\x61ncel_workflow_execution\x18\t \x01(\x0b\x32\x32.coresdk.workflow_commands.CancelWorkflowExecutionH\x00\x12\x45\n\x10set_patch_marker\x18\n \x01(\x0b\x32).coresdk.workflow_commands.SetPatchMarkerH\x00\x12`\n\x1estart_child_workflow_execution\x18\x0b \x01(\x0b\x32\x36.coresdk.workflow_commands.StartChildWorkflowExecutionH\x00\x12\x62\n\x1f\x63\x61ncel_child_workflow_execution\x18\x0c \x01(\x0b\x32\x37.coresdk.workflow_commands.CancelChildWorkflowExecutionH\x00\x12w\n*request_cancel_external_workflow_execution\x18\r \x01(\x0b\x32\x41.coresdk.workflow_commands.RequestCancelExternalWorkflowExecutionH\x00\x12h\n"signal_external_workflow_execution\x18\x0e \x01(\x0b\x32:.coresdk.workflow_commands.SignalExternalWorkflowExecutionH\x00\x12Q\n\x16\x63\x61ncel_signal_workflow\x18\x0f \x01(\x0b\x32/.coresdk.workflow_commands.CancelSignalWorkflowH\x00\x12S\n\x17schedule_local_activity\x18\x10 \x01(\x0b\x32\x30.coresdk.workflow_commands.ScheduleLocalActivityH\x00\x12^\n\x1drequest_cancel_local_activity\x18\x11 \x01(\x0b\x32\x35.coresdk.workflow_commands.RequestCancelLocalActivityH\x00\x12\x66\n!upsert_workflow_search_attributes\x18\x12 \x01(\x0b\x32\x39.coresdk.workflow_commands.UpsertWorkflowSearchAttributesH\x00\x12Y\n\x1amodify_workflow_properties\x18\x13 \x01(\x0b\x32\x33.coresdk.workflow_commands.ModifyWorkflowPropertiesH\x00\x12\x44\n\x0fupdate_response\x18\x14 \x01(\x0b\x32).coresdk.workflow_commands.UpdateResponseH\x00\x12U\n\x18schedule_nexus_operation\x18\x15 \x01(\x0b\x32\x31.coresdk.workflow_commands.ScheduleNexusOperationH\x00\x12`\n\x1erequest_cancel_nexus_operation\x18\x16 \x01(\x0b\x32\x36.coresdk.workflow_commands.RequestCancelNexusOperationH\x00\x12<\n\x0bread_stream\x18\x17 \x01(\x0b\x32%.coresdk.workflow_commands.ReadStreamH\x00\x12\x45\n\x10\x61ppend_to_stream\x18\x19 \x01(\x0b\x32).coresdk.workflow_commands.AppendToStreamH\x00\x12>\n\x0c\x63lose_stream\x18\x1a \x01(\x0b\x32&.coresdk.workflow_commands.CloseStreamH\x00\x42\t\n\x07variant"S\n\nStartTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x38\n\x15start_to_fire_timeout\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration"\x1a\n\x0b\x43\x61ncelTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r"\xb8\x06\n\x10ScheduleActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x15\n\ractivity_type\x18\x03 \x01(\t\x12\x12\n\ntask_queue\x18\x05 \x01(\t\x12I\n\x07headers\x18\x06 \x03(\x0b\x32\x38.coresdk.workflow_commands.ScheduleActivity.HeadersEntry\x12\x32\n\targuments\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x34\n\x11heartbeat_timeout\x18\x0b \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x0c \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12N\n\x11\x63\x61ncellation_type\x18\r \x01(\x0e\x32\x33.coresdk.workflow_commands.ActivityCancellationType\x12\x1e\n\x16\x64o_not_eagerly_execute\x18\x0e \x01(\x08\x12;\n\x11versioning_intent\x18\x0f \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12\x32\n\x08priority\x18\x10 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x93\x06\n\x15ScheduleLocalActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x15\n\ractivity_type\x18\x03 \x01(\t\x12\x0f\n\x07\x61ttempt\x18\x04 \x01(\r\x12:\n\x16original_schedule_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12N\n\x07headers\x18\x06 \x03(\x0b\x32=.coresdk.workflow_commands.ScheduleLocalActivity.HeadersEntry\x12\x32\n\targuments\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x0b \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x38\n\x15local_retry_threshold\x18\x0c \x01(\x0b\x32\x19.google.protobuf.Duration\x12N\n\x11\x63\x61ncellation_type\x18\r \x01(\x0e\x32\x33.coresdk.workflow_commands.ActivityCancellationType\x12#\n\x1binclude_arguments_in_marker\x18\x0e \x01(\x08\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"$\n\x15RequestCancelActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r")\n\x1aRequestCancelLocalActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r"\x9c\x01\n\x0bQueryResult\x12\x10\n\x08query_id\x18\x01 \x01(\t\x12<\n\tsucceeded\x18\x02 \x01(\x0b\x32\'.coresdk.workflow_commands.QuerySuccessH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\t\n\x07variant"A\n\x0cQuerySuccess\x12\x31\n\x08response\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"L\n\x19\x43ompleteWorkflowExecution\x12/\n\x06result\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"J\n\x15\x46\x61ilWorkflowExecution\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"\x92\x07\n\x1e\x43ontinueAsNewWorkflowExecution\x12\x15\n\rworkflow_type\x18\x01 \x01(\t\x12\x12\n\ntask_queue\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x37\n\x14workflow_run_timeout\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12Q\n\x04memo\x18\x06 \x03(\x0b\x32\x43.coresdk.workflow_commands.ContinueAsNewWorkflowExecution.MemoEntry\x12W\n\x07headers\x18\x07 \x03(\x0b\x32\x46.coresdk.workflow_commands.ContinueAsNewWorkflowExecution.HeadersEntry\x12\x43\n\x11search_attributes\x18\x08 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12\x39\n\x0cretry_policy\x18\t \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12;\n\x11versioning_intent\x18\n \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12[\n\x1binitial_versioning_behavior\x18\x0b \x01(\x0e\x32\x36.temporal.api.enums.v1.ContinueAsNewVersioningBehavior\x12\x39\n\x16\x62\x61\x63koff_start_interval\x18\x0c \x01(\x0b\x32\x19.google.protobuf.Duration\x1aL\n\tMemoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"L\n\x17\x43\x61ncelWorkflowExecution\x12\x31\n\x07\x64\x65tails\x18\x01 \x01(\x0b\x32 .temporal.api.common.v1.Payloads"6\n\x0eSetPatchMarker\x12\x10\n\x08patch_id\x18\x01 \x01(\t\x12\x12\n\ndeprecated\x18\x02 \x01(\x08"\xe1\t\n\x1bStartChildWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x11\n\tnamespace\x18\x02 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x03 \x01(\t\x12\x15\n\rworkflow_type\x18\x04 \x01(\t\x12\x12\n\ntask_queue\x18\x05 \x01(\t\x12.\n\x05input\x18\x06 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12=\n\x1aworkflow_execution_timeout\x18\x07 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14workflow_run_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x46\n\x13parent_close_policy\x18\n \x01(\x0e\x32).coresdk.child_workflow.ParentClosePolicy\x12N\n\x18workflow_id_reuse_policy\x18\x0c \x01(\x0e\x32,.temporal.api.enums.v1.WorkflowIdReusePolicy\x12\x39\n\x0cretry_policy\x18\r \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x15\n\rcron_schedule\x18\x0e \x01(\t\x12T\n\x07headers\x18\x0f \x03(\x0b\x32\x43.coresdk.workflow_commands.StartChildWorkflowExecution.HeadersEntry\x12N\n\x04memo\x18\x10 \x03(\x0b\x32@.coresdk.workflow_commands.StartChildWorkflowExecution.MemoEntry\x12\x43\n\x11search_attributes\x18\x11 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12P\n\x11\x63\x61ncellation_type\x18\x12 \x01(\x0e\x32\x35.coresdk.child_workflow.ChildWorkflowCancellationType\x12;\n\x11versioning_intent\x18\x13 \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12\x32\n\x08priority\x18\x14 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12I\n\x13versioning_override\x18\x15 \x01(\x0b\x32,.temporal.api.workflow.v1.VersioningOverride\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x1aL\n\tMemoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"J\n\x1c\x43\x61ncelChildWorkflowExecution\x12\x1a\n\x12\x63hild_workflow_seq\x18\x01 \x01(\r\x12\x0e\n\x06reason\x18\x02 \x01(\t"\x8e\x01\n&RequestCancelExternalWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12G\n\x12workflow_execution\x18\x02 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecution\x12\x0e\n\x06reason\x18\x03 \x01(\t"\x8f\x03\n\x1fSignalExternalWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12I\n\x12workflow_execution\x18\x02 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecutionH\x00\x12\x1b\n\x11\x63hild_workflow_id\x18\x03 \x01(\tH\x00\x12\x13\n\x0bsignal_name\x18\x04 \x01(\t\x12-\n\x04\x61rgs\x18\x05 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12X\n\x07headers\x18\x06 \x03(\x0b\x32G.coresdk.workflow_commands.SignalExternalWorkflowExecution.HeadersEntry\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x42\x08\n\x06target"#\n\x14\x43\x61ncelSignalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r"e\n\x1eUpsertWorkflowSearchAttributes\x12\x43\n\x11search_attributes\x18\x01 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes"O\n\x18ModifyWorkflowProperties\x12\x33\n\rupserted_memo\x18\x01 \x01(\x0b\x32\x1c.temporal.api.common.v1.Memo"\xd2\x01\n\x0eUpdateResponse\x12\x1c\n\x14protocol_instance_id\x18\x01 \x01(\t\x12*\n\x08\x61\x63\x63\x65pted\x18\x02 \x01(\x0b\x32\x16.google.protobuf.EmptyH\x00\x12\x34\n\x08rejected\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x12\x34\n\tcompleted\x18\x04 \x01(\x0b\x32\x1f.temporal.api.common.v1.PayloadH\x00\x42\n\n\x08response"\x9a\x04\n\x16ScheduleNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x10\n\x08\x65ndpoint\x18\x02 \x01(\t\x12\x0f\n\x07service\x18\x03 \x01(\t\x12\x11\n\toperation\x18\x04 \x01(\t\x12.\n\x05input\x18\x05 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x06 \x01(\x0b\x32\x19.google.protobuf.Duration\x12X\n\x0cnexus_header\x18\x07 \x03(\x0b\x32\x42.coresdk.workflow_commands.ScheduleNexusOperation.NexusHeaderEntry\x12H\n\x11\x63\x61ncellation_type\x18\x08 \x01(\x0e\x32-.coresdk.nexus.NexusOperationCancellationType\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x1a\x32\n\x10NexusHeaderEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"*\n\x1bRequestCancelNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r"\x81\x01\n\x0e\x41ppendToStream\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x06stream\x18\x02 \x01(\x0b\x32!.temporal.api.stream.v1.StreamRef\x12/\n\x06\x62odies\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload"M\n\x0b\x43loseStream\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x06stream\x18\x02 \x01(\x0b\x32!.temporal.api.stream.v1.StreamRef"\xb2\x01\n\nReadStream\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x06stream\x18\x02 \x01(\x0b\x32!.temporal.api.stream.v1.StreamRef\x12\x13\n\x0b\x66rom_offset\x18\x03 \x01(\x0c\x12\'\n\x04wait\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x13\n\x0bmax_records\x18\x05 \x01(\x05\x12\x11\n\tmax_bytes\x18\x06 \x01(\x03*X\n\x18\x41\x63tivityCancellationType\x12\x0e\n\nTRY_CANCEL\x10\x00\x12\x1f\n\x1bWAIT_CANCELLATION_COMPLETED\x10\x01\x12\x0b\n\x07\x41\x42\x41NDON\x10\x02\x42\x36\xea\x02\x33Temporalio::Internal::Bridge::Api::WorkflowCommandsb\x06proto3' + b'\n;temporal/sdk/core/workflow_commands/workflow_commands.proto\x12\x19\x63oresdk.workflow_commands\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a$temporal/api/common/v1/message.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a%temporal/api/failure/v1/message.proto\x1a\'temporal/api/sdk/v1/user_metadata.proto\x1a,temporal/api/sdk/v1/event_group_marker.proto\x1a temporal/api/sdk/v1/stream.proto\x1a&temporal/api/workflow/v1/message.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a#temporal/sdk/core/nexus/nexus.proto\x1a%temporal/sdk/core/common/common.proto"\xae\x11\n\x0fWorkflowCommand\x12\x38\n\ruser_metadata\x18\x64 \x01(\x0b\x32!.temporal.api.sdk.v1.UserMetadata\x12\x42\n\x13\x65vent_group_markers\x18\x65 \x03(\x0b\x32%.temporal.api.sdk.v1.EventGroupMarker\x12<\n\x0bstart_timer\x18\x01 \x01(\x0b\x32%.coresdk.workflow_commands.StartTimerH\x00\x12H\n\x11schedule_activity\x18\x02 \x01(\x0b\x32+.coresdk.workflow_commands.ScheduleActivityH\x00\x12\x42\n\x10respond_to_query\x18\x03 \x01(\x0b\x32&.coresdk.workflow_commands.QueryResultH\x00\x12S\n\x17request_cancel_activity\x18\x04 \x01(\x0b\x32\x30.coresdk.workflow_commands.RequestCancelActivityH\x00\x12>\n\x0c\x63\x61ncel_timer\x18\x05 \x01(\x0b\x32&.coresdk.workflow_commands.CancelTimerH\x00\x12[\n\x1b\x63omplete_workflow_execution\x18\x06 \x01(\x0b\x32\x34.coresdk.workflow_commands.CompleteWorkflowExecutionH\x00\x12S\n\x17\x66\x61il_workflow_execution\x18\x07 \x01(\x0b\x32\x30.coresdk.workflow_commands.FailWorkflowExecutionH\x00\x12g\n"continue_as_new_workflow_execution\x18\x08 \x01(\x0b\x32\x39.coresdk.workflow_commands.ContinueAsNewWorkflowExecutionH\x00\x12W\n\x19\x63\x61ncel_workflow_execution\x18\t \x01(\x0b\x32\x32.coresdk.workflow_commands.CancelWorkflowExecutionH\x00\x12\x45\n\x10set_patch_marker\x18\n \x01(\x0b\x32).coresdk.workflow_commands.SetPatchMarkerH\x00\x12`\n\x1estart_child_workflow_execution\x18\x0b \x01(\x0b\x32\x36.coresdk.workflow_commands.StartChildWorkflowExecutionH\x00\x12\x62\n\x1f\x63\x61ncel_child_workflow_execution\x18\x0c \x01(\x0b\x32\x37.coresdk.workflow_commands.CancelChildWorkflowExecutionH\x00\x12w\n*request_cancel_external_workflow_execution\x18\r \x01(\x0b\x32\x41.coresdk.workflow_commands.RequestCancelExternalWorkflowExecutionH\x00\x12h\n"signal_external_workflow_execution\x18\x0e \x01(\x0b\x32:.coresdk.workflow_commands.SignalExternalWorkflowExecutionH\x00\x12Q\n\x16\x63\x61ncel_signal_workflow\x18\x0f \x01(\x0b\x32/.coresdk.workflow_commands.CancelSignalWorkflowH\x00\x12S\n\x17schedule_local_activity\x18\x10 \x01(\x0b\x32\x30.coresdk.workflow_commands.ScheduleLocalActivityH\x00\x12^\n\x1drequest_cancel_local_activity\x18\x11 \x01(\x0b\x32\x35.coresdk.workflow_commands.RequestCancelLocalActivityH\x00\x12\x66\n!upsert_workflow_search_attributes\x18\x12 \x01(\x0b\x32\x39.coresdk.workflow_commands.UpsertWorkflowSearchAttributesH\x00\x12Y\n\x1amodify_workflow_properties\x18\x13 \x01(\x0b\x32\x33.coresdk.workflow_commands.ModifyWorkflowPropertiesH\x00\x12\x44\n\x0fupdate_response\x18\x14 \x01(\x0b\x32).coresdk.workflow_commands.UpdateResponseH\x00\x12U\n\x18schedule_nexus_operation\x18\x15 \x01(\x0b\x32\x31.coresdk.workflow_commands.ScheduleNexusOperationH\x00\x12`\n\x1erequest_cancel_nexus_operation\x18\x16 \x01(\x0b\x32\x36.coresdk.workflow_commands.RequestCancelNexusOperationH\x00\x12\x45\n\x10\x61ppend_to_stream\x18\x17 \x01(\x0b\x32).coresdk.workflow_commands.AppendToStreamH\x00\x12<\n\x0bread_stream\x18\x18 \x01(\x0b\x32%.coresdk.workflow_commands.ReadStreamH\x00\x42\t\n\x07variant"S\n\nStartTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x38\n\x15start_to_fire_timeout\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration"\x1a\n\x0b\x43\x61ncelTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r"\xb8\x06\n\x10ScheduleActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x15\n\ractivity_type\x18\x03 \x01(\t\x12\x12\n\ntask_queue\x18\x05 \x01(\t\x12I\n\x07headers\x18\x06 \x03(\x0b\x32\x38.coresdk.workflow_commands.ScheduleActivity.HeadersEntry\x12\x32\n\targuments\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x34\n\x11heartbeat_timeout\x18\x0b \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x0c \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12N\n\x11\x63\x61ncellation_type\x18\r \x01(\x0e\x32\x33.coresdk.workflow_commands.ActivityCancellationType\x12\x1e\n\x16\x64o_not_eagerly_execute\x18\x0e \x01(\x08\x12;\n\x11versioning_intent\x18\x0f \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12\x32\n\x08priority\x18\x10 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x93\x06\n\x15ScheduleLocalActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x15\n\ractivity_type\x18\x03 \x01(\t\x12\x0f\n\x07\x61ttempt\x18\x04 \x01(\r\x12:\n\x16original_schedule_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12N\n\x07headers\x18\x06 \x03(\x0b\x32=.coresdk.workflow_commands.ScheduleLocalActivity.HeadersEntry\x12\x32\n\targuments\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x0b \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x38\n\x15local_retry_threshold\x18\x0c \x01(\x0b\x32\x19.google.protobuf.Duration\x12N\n\x11\x63\x61ncellation_type\x18\r \x01(\x0e\x32\x33.coresdk.workflow_commands.ActivityCancellationType\x12#\n\x1binclude_arguments_in_marker\x18\x0e \x01(\x08\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"$\n\x15RequestCancelActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r")\n\x1aRequestCancelLocalActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r"\x9c\x01\n\x0bQueryResult\x12\x10\n\x08query_id\x18\x01 \x01(\t\x12<\n\tsucceeded\x18\x02 \x01(\x0b\x32\'.coresdk.workflow_commands.QuerySuccessH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\t\n\x07variant"A\n\x0cQuerySuccess\x12\x31\n\x08response\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"L\n\x19\x43ompleteWorkflowExecution\x12/\n\x06result\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"J\n\x15\x46\x61ilWorkflowExecution\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"\x92\x07\n\x1e\x43ontinueAsNewWorkflowExecution\x12\x15\n\rworkflow_type\x18\x01 \x01(\t\x12\x12\n\ntask_queue\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x37\n\x14workflow_run_timeout\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12Q\n\x04memo\x18\x06 \x03(\x0b\x32\x43.coresdk.workflow_commands.ContinueAsNewWorkflowExecution.MemoEntry\x12W\n\x07headers\x18\x07 \x03(\x0b\x32\x46.coresdk.workflow_commands.ContinueAsNewWorkflowExecution.HeadersEntry\x12\x43\n\x11search_attributes\x18\x08 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12\x39\n\x0cretry_policy\x18\t \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12;\n\x11versioning_intent\x18\n \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12[\n\x1binitial_versioning_behavior\x18\x0b \x01(\x0e\x32\x36.temporal.api.enums.v1.ContinueAsNewVersioningBehavior\x12\x39\n\x16\x62\x61\x63koff_start_interval\x18\x0c \x01(\x0b\x32\x19.google.protobuf.Duration\x1aL\n\tMemoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"L\n\x17\x43\x61ncelWorkflowExecution\x12\x31\n\x07\x64\x65tails\x18\x01 \x01(\x0b\x32 .temporal.api.common.v1.Payloads"6\n\x0eSetPatchMarker\x12\x10\n\x08patch_id\x18\x01 \x01(\t\x12\x12\n\ndeprecated\x18\x02 \x01(\x08"\xe1\t\n\x1bStartChildWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x11\n\tnamespace\x18\x02 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x03 \x01(\t\x12\x15\n\rworkflow_type\x18\x04 \x01(\t\x12\x12\n\ntask_queue\x18\x05 \x01(\t\x12.\n\x05input\x18\x06 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12=\n\x1aworkflow_execution_timeout\x18\x07 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14workflow_run_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x46\n\x13parent_close_policy\x18\n \x01(\x0e\x32).coresdk.child_workflow.ParentClosePolicy\x12N\n\x18workflow_id_reuse_policy\x18\x0c \x01(\x0e\x32,.temporal.api.enums.v1.WorkflowIdReusePolicy\x12\x39\n\x0cretry_policy\x18\r \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x15\n\rcron_schedule\x18\x0e \x01(\t\x12T\n\x07headers\x18\x0f \x03(\x0b\x32\x43.coresdk.workflow_commands.StartChildWorkflowExecution.HeadersEntry\x12N\n\x04memo\x18\x10 \x03(\x0b\x32@.coresdk.workflow_commands.StartChildWorkflowExecution.MemoEntry\x12\x43\n\x11search_attributes\x18\x11 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12P\n\x11\x63\x61ncellation_type\x18\x12 \x01(\x0e\x32\x35.coresdk.child_workflow.ChildWorkflowCancellationType\x12;\n\x11versioning_intent\x18\x13 \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12\x32\n\x08priority\x18\x14 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12I\n\x13versioning_override\x18\x15 \x01(\x0b\x32,.temporal.api.workflow.v1.VersioningOverride\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x1aL\n\tMemoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"J\n\x1c\x43\x61ncelChildWorkflowExecution\x12\x1a\n\x12\x63hild_workflow_seq\x18\x01 \x01(\r\x12\x0e\n\x06reason\x18\x02 \x01(\t"\x8e\x01\n&RequestCancelExternalWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12G\n\x12workflow_execution\x18\x02 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecution\x12\x0e\n\x06reason\x18\x03 \x01(\t"\x8f\x03\n\x1fSignalExternalWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12I\n\x12workflow_execution\x18\x02 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecutionH\x00\x12\x1b\n\x11\x63hild_workflow_id\x18\x03 \x01(\tH\x00\x12\x13\n\x0bsignal_name\x18\x04 \x01(\t\x12-\n\x04\x61rgs\x18\x05 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12X\n\x07headers\x18\x06 \x03(\x0b\x32G.coresdk.workflow_commands.SignalExternalWorkflowExecution.HeadersEntry\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x42\x08\n\x06target"#\n\x14\x43\x61ncelSignalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r"e\n\x1eUpsertWorkflowSearchAttributes\x12\x43\n\x11search_attributes\x18\x01 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes"O\n\x18ModifyWorkflowProperties\x12\x33\n\rupserted_memo\x18\x01 \x01(\x0b\x32\x1c.temporal.api.common.v1.Memo"\xd2\x01\n\x0eUpdateResponse\x12\x1c\n\x14protocol_instance_id\x18\x01 \x01(\t\x12*\n\x08\x61\x63\x63\x65pted\x18\x02 \x01(\x0b\x32\x16.google.protobuf.EmptyH\x00\x12\x34\n\x08rejected\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x12\x34\n\tcompleted\x18\x04 \x01(\x0b\x32\x1f.temporal.api.common.v1.PayloadH\x00\x42\n\n\x08response"\x9a\x04\n\x16ScheduleNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x10\n\x08\x65ndpoint\x18\x02 \x01(\t\x12\x0f\n\x07service\x18\x03 \x01(\t\x12\x11\n\toperation\x18\x04 \x01(\t\x12.\n\x05input\x18\x05 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x06 \x01(\x0b\x32\x19.google.protobuf.Duration\x12X\n\x0cnexus_header\x18\x07 \x03(\x0b\x32\x42.coresdk.workflow_commands.ScheduleNexusOperation.NexusHeaderEntry\x12H\n\x11\x63\x61ncellation_type\x18\x08 \x01(\x0e\x32-.coresdk.nexus.NexusOperationCancellationType\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x1a\x32\n\x10NexusHeaderEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"*\n\x1bRequestCancelNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r"~\n\x0e\x41ppendToStream\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12.\n\x06stream\x18\x02 \x01(\x0b\x32\x1e.temporal.api.sdk.v1.StreamRef\x12/\n\x06\x62odies\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload"\xaf\x01\n\nReadStream\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12.\n\x06stream\x18\x02 \x01(\x0b\x32\x1e.temporal.api.sdk.v1.StreamRef\x12\x13\n\x0b\x66rom_offset\x18\x03 \x01(\x0c\x12\'\n\x04wait\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x13\n\x0bmax_records\x18\x05 \x01(\x05\x12\x11\n\tmax_bytes\x18\x06 \x01(\x03*X\n\x18\x41\x63tivityCancellationType\x12\x0e\n\nTRY_CANCEL\x10\x00\x12\x1f\n\x1bWAIT_CANCELLATION_COMPLETED\x10\x01\x12\x0b\n\x07\x41\x42\x41NDON\x10\x02\x42\x36\xea\x02\x33Temporalio::Internal::Bridge::Api::WorkflowCommandsb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -75,76 +75,74 @@ _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_options = b"8\001" _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._options = None _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_options = b"8\001" - _ACTIVITYCANCELLATIONTYPE._serialized_start = 9412 - _ACTIVITYCANCELLATIONTYPE._serialized_end = 9500 - _WORKFLOWCOMMAND._serialized_start = 596 - _WORKFLOWCOMMAND._serialized_end = 2882 - _STARTTIMER._serialized_start = 2884 - _STARTTIMER._serialized_end = 2967 - _CANCELTIMER._serialized_start = 2969 - _CANCELTIMER._serialized_end = 2995 - _SCHEDULEACTIVITY._serialized_start = 2998 - _SCHEDULEACTIVITY._serialized_end = 3822 - _SCHEDULEACTIVITY_HEADERSENTRY._serialized_start = 3743 - _SCHEDULEACTIVITY_HEADERSENTRY._serialized_end = 3822 - _SCHEDULELOCALACTIVITY._serialized_start = 3825 - _SCHEDULELOCALACTIVITY._serialized_end = 4612 - _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_start = 3743 - _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_end = 3822 - _REQUESTCANCELACTIVITY._serialized_start = 4614 - _REQUESTCANCELACTIVITY._serialized_end = 4650 - _REQUESTCANCELLOCALACTIVITY._serialized_start = 4652 - _REQUESTCANCELLOCALACTIVITY._serialized_end = 4693 - _QUERYRESULT._serialized_start = 4696 - _QUERYRESULT._serialized_end = 4852 - _QUERYSUCCESS._serialized_start = 4854 - _QUERYSUCCESS._serialized_end = 4919 - _COMPLETEWORKFLOWEXECUTION._serialized_start = 4921 - _COMPLETEWORKFLOWEXECUTION._serialized_end = 4997 - _FAILWORKFLOWEXECUTION._serialized_start = 4999 - _FAILWORKFLOWEXECUTION._serialized_end = 5073 - _CONTINUEASNEWWORKFLOWEXECUTION._serialized_start = 5076 - _CONTINUEASNEWWORKFLOWEXECUTION._serialized_end = 5990 - _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5833 - _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5909 - _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3743 - _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3822 - _CANCELWORKFLOWEXECUTION._serialized_start = 5992 - _CANCELWORKFLOWEXECUTION._serialized_end = 6068 - _SETPATCHMARKER._serialized_start = 6070 - _SETPATCHMARKER._serialized_end = 6124 - _STARTCHILDWORKFLOWEXECUTION._serialized_start = 6127 - _STARTCHILDWORKFLOWEXECUTION._serialized_end = 7376 - _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3743 - _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3822 - _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5833 - _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5909 - _CANCELCHILDWORKFLOWEXECUTION._serialized_start = 7378 - _CANCELCHILDWORKFLOWEXECUTION._serialized_end = 7452 - _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_start = 7455 - _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_end = 7597 - _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_start = 7600 - _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_end = 7999 - _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3743 - _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3822 - _CANCELSIGNALWORKFLOW._serialized_start = 8001 - _CANCELSIGNALWORKFLOW._serialized_end = 8036 - _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_start = 8038 - _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_end = 8139 - _MODIFYWORKFLOWPROPERTIES._serialized_start = 8141 - _MODIFYWORKFLOWPROPERTIES._serialized_end = 8220 - _UPDATERESPONSE._serialized_start = 8223 - _UPDATERESPONSE._serialized_end = 8433 - _SCHEDULENEXUSOPERATION._serialized_start = 8436 - _SCHEDULENEXUSOPERATION._serialized_end = 8974 - _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_start = 8924 - _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_end = 8974 - _REQUESTCANCELNEXUSOPERATION._serialized_start = 8976 - _REQUESTCANCELNEXUSOPERATION._serialized_end = 9018 - _APPENDTOSTREAM._serialized_start = 9021 - _APPENDTOSTREAM._serialized_end = 9150 - _CLOSESTREAM._serialized_start = 9152 - _CLOSESTREAM._serialized_end = 9229 - _READSTREAM._serialized_start = 9232 - _READSTREAM._serialized_end = 9410 + _ACTIVITYCANCELLATIONTYPE._serialized_start = 9258 + _ACTIVITYCANCELLATIONTYPE._serialized_end = 9346 + _WORKFLOWCOMMAND._serialized_start = 592 + _WORKFLOWCOMMAND._serialized_end = 2814 + _STARTTIMER._serialized_start = 2816 + _STARTTIMER._serialized_end = 2899 + _CANCELTIMER._serialized_start = 2901 + _CANCELTIMER._serialized_end = 2927 + _SCHEDULEACTIVITY._serialized_start = 2930 + _SCHEDULEACTIVITY._serialized_end = 3754 + _SCHEDULEACTIVITY_HEADERSENTRY._serialized_start = 3675 + _SCHEDULEACTIVITY_HEADERSENTRY._serialized_end = 3754 + _SCHEDULELOCALACTIVITY._serialized_start = 3757 + _SCHEDULELOCALACTIVITY._serialized_end = 4544 + _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_start = 3675 + _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_end = 3754 + _REQUESTCANCELACTIVITY._serialized_start = 4546 + _REQUESTCANCELACTIVITY._serialized_end = 4582 + _REQUESTCANCELLOCALACTIVITY._serialized_start = 4584 + _REQUESTCANCELLOCALACTIVITY._serialized_end = 4625 + _QUERYRESULT._serialized_start = 4628 + _QUERYRESULT._serialized_end = 4784 + _QUERYSUCCESS._serialized_start = 4786 + _QUERYSUCCESS._serialized_end = 4851 + _COMPLETEWORKFLOWEXECUTION._serialized_start = 4853 + _COMPLETEWORKFLOWEXECUTION._serialized_end = 4929 + _FAILWORKFLOWEXECUTION._serialized_start = 4931 + _FAILWORKFLOWEXECUTION._serialized_end = 5005 + _CONTINUEASNEWWORKFLOWEXECUTION._serialized_start = 5008 + _CONTINUEASNEWWORKFLOWEXECUTION._serialized_end = 5922 + _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5765 + _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5841 + _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3675 + _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3754 + _CANCELWORKFLOWEXECUTION._serialized_start = 5924 + _CANCELWORKFLOWEXECUTION._serialized_end = 6000 + _SETPATCHMARKER._serialized_start = 6002 + _SETPATCHMARKER._serialized_end = 6056 + _STARTCHILDWORKFLOWEXECUTION._serialized_start = 6059 + _STARTCHILDWORKFLOWEXECUTION._serialized_end = 7308 + _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3675 + _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3754 + _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5765 + _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5841 + _CANCELCHILDWORKFLOWEXECUTION._serialized_start = 7310 + _CANCELCHILDWORKFLOWEXECUTION._serialized_end = 7384 + _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_start = 7387 + _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_end = 7529 + _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_start = 7532 + _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_end = 7931 + _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3675 + _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3754 + _CANCELSIGNALWORKFLOW._serialized_start = 7933 + _CANCELSIGNALWORKFLOW._serialized_end = 7968 + _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_start = 7970 + _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_end = 8071 + _MODIFYWORKFLOWPROPERTIES._serialized_start = 8073 + _MODIFYWORKFLOWPROPERTIES._serialized_end = 8152 + _UPDATERESPONSE._serialized_start = 8155 + _UPDATERESPONSE._serialized_end = 8365 + _SCHEDULENEXUSOPERATION._serialized_start = 8368 + _SCHEDULENEXUSOPERATION._serialized_end = 8906 + _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_start = 8856 + _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_end = 8906 + _REQUESTCANCELNEXUSOPERATION._serialized_start = 8908 + _REQUESTCANCELNEXUSOPERATION._serialized_end = 8950 + _APPENDTOSTREAM._serialized_start = 8952 + _APPENDTOSTREAM._serialized_end = 9078 + _READSTREAM._serialized_start = 9081 + _READSTREAM._serialized_end = 9256 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi index 0833fb5442..2ceb177cf7 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi @@ -24,8 +24,8 @@ import temporalio.api.common.v1.message_pb2 import temporalio.api.enums.v1.workflow_pb2 import temporalio.api.failure.v1.message_pb2 import temporalio.api.sdk.v1.event_group_marker_pb2 +import temporalio.api.sdk.v1.stream_pb2 import temporalio.api.sdk.v1.user_metadata_pb2 -import temporalio.api.stream.v1.message_pb2 import temporalio.api.workflow.v1.message_pb2 import temporalio.bridge.proto.child_workflow.child_workflow_pb2 import temporalio.bridge.proto.common.common_pb2 @@ -106,9 +106,8 @@ class WorkflowCommand(google.protobuf.message.Message): UPDATE_RESPONSE_FIELD_NUMBER: builtins.int SCHEDULE_NEXUS_OPERATION_FIELD_NUMBER: builtins.int REQUEST_CANCEL_NEXUS_OPERATION_FIELD_NUMBER: builtins.int - READ_STREAM_FIELD_NUMBER: builtins.int APPEND_TO_STREAM_FIELD_NUMBER: builtins.int - CLOSE_STREAM_FIELD_NUMBER: builtins.int + READ_STREAM_FIELD_NUMBER: builtins.int @property def user_metadata(self) -> temporalio.api.sdk.v1.user_metadata_pb2.UserMetadata: """User metadata that may or may not be persisted into history depending on the command type. @@ -186,11 +185,9 @@ class WorkflowCommand(google.protobuf.message.Message): self, ) -> global___RequestCancelNexusOperation: ... @property - def read_stream(self) -> global___ReadStream: ... - @property def append_to_stream(self) -> global___AppendToStream: ... @property - def close_stream(self) -> global___CloseStream: ... + def read_stream(self) -> global___ReadStream: ... def __init__( self, *, @@ -229,9 +226,8 @@ class WorkflowCommand(google.protobuf.message.Message): schedule_nexus_operation: global___ScheduleNexusOperation | None = ..., request_cancel_nexus_operation: global___RequestCancelNexusOperation | None = ..., - read_stream: global___ReadStream | None = ..., append_to_stream: global___AppendToStream | None = ..., - close_stream: global___CloseStream | None = ..., + read_stream: global___ReadStream | None = ..., ) -> None: ... def HasField( self, @@ -246,8 +242,6 @@ class WorkflowCommand(google.protobuf.message.Message): b"cancel_timer", "cancel_workflow_execution", b"cancel_workflow_execution", - "close_stream", - b"close_stream", "complete_workflow_execution", b"complete_workflow_execution", "continue_as_new_workflow_execution", @@ -305,8 +299,6 @@ class WorkflowCommand(google.protobuf.message.Message): b"cancel_timer", "cancel_workflow_execution", b"cancel_workflow_execution", - "close_stream", - b"close_stream", "complete_workflow_execution", b"complete_workflow_execution", "continue_as_new_workflow_execution", @@ -379,9 +371,8 @@ class WorkflowCommand(google.protobuf.message.Message): "update_response", "schedule_nexus_operation", "request_cancel_nexus_operation", - "read_stream", "append_to_stream", - "close_stream", + "read_stream", ] | None ): ... @@ -1963,25 +1954,19 @@ global___RequestCancelNexusOperation = RequestCancelNexusOperation @typing.final class AppendToStream(google.protobuf.message.Message): """Appends Records to a Stream as the Workflow's Producer. Core calls the Store while the Workflow - Task is open, and sends the result in a `ResolveStreamAppend` job. As for a Local Activity, Core - keeps the task open while an append runs. An append has no event, so History keeps its result in - the `stream_calls` of the `sdk_metadata` of the task's completion. - - An append is at-least-once. If History has no result of it, a later attempt of the Workflow Task - writes the batch again. - - No command cancels an append, so lang must accept the job of an append that nothing awaits. - Core drops an append that has no result when lang sends the Workflow's last command. - - Core sends the appends and the closes of one Stream to the Store one at a time, in the order of - their commands. - - A bad `seq` or `stream`, or a Store that the Worker has no runtime for, fails the Workflow Task. - So does a Store that is still unavailable at the task's heartbeat. The failure message then - starts with `StreamStoreUnavailable:`. An empty batch, or one over the limits of its Store, - gives lang a `failed` job. - - A replay compares the `seq` and the `stream` of the command with History, not the `bodies`. + Task is open, keeps the task open as it does for a Local Activity, and sends the result in a + `ResolveStreamAppend` job. + + * An append is at-least-once. If History has no result for it, a later attempt of the Workflow + Task writes the batch again. + * No command cancels an append. Lang must accept the result of an append that nothing awaits, + and Core drops an append that has no result at the Workflow's last command. + * The appends of one Stream go to the Store one at a time, in the order of their commands. + * A bad `seq` or `stream`, or a Store that the Worker has no runtime for, fails the Workflow + Task. So does a Store that is still unavailable at the task's heartbeat, with a failure + message that starts with `StreamStoreUnavailable:`. + * An empty batch, or one over the limits of its Store, gives lang a `failed` job. + * A replay compares the `seq` and the `stream` of the command with History, not the `bodies`. """ DESCRIPTOR: google.protobuf.descriptor.Descriptor @@ -1992,7 +1977,7 @@ class AppendToStream(google.protobuf.message.Message): seq: builtins.int """Lang's incremental sequence number for appends, starting at 1.""" @property - def stream(self) -> temporalio.api.stream.v1.message_pb2.StreamRef: ... + def stream(self) -> temporalio.api.sdk.v1.stream_pb2.StreamRef: ... @property def bodies( self, @@ -2003,7 +1988,7 @@ class AppendToStream(google.protobuf.message.Message): self, *, seq: builtins.int = ..., - stream: temporalio.api.stream.v1.message_pb2.StreamRef | None = ..., + stream: temporalio.api.sdk.v1.stream_pb2.StreamRef | None = ..., bodies: collections.abc.Iterable[temporalio.api.common.v1.message_pb2.Payload] | None = ..., ) -> None: ... @@ -2019,73 +2004,68 @@ class AppendToStream(google.protobuf.message.Message): global___AppendToStream = AppendToStream -@typing.final -class CloseStream(google.protobuf.message.Message): - """Closes a Stream. The Workflow Task of the command records only the intent to close. Core closes - the Stream once History has that task, so a task that fails closes nothing, and its retry can - still append. The result comes in a `ResolveStreamClose` job of a later task. - - An append that lang sends in the same task is written before the close. - - The rules of `AppendToStream` about cancellation, the Workflow's last command, task failures and - replay apply to a close too. So Workflow code that needs its close must await the result before - its last command. - """ - - DESCRIPTOR: google.protobuf.descriptor.Descriptor - - SEQ_FIELD_NUMBER: builtins.int - STREAM_FIELD_NUMBER: builtins.int - seq: builtins.int - """Lang's incremental sequence number for closes, starting at 1.""" - @property - def stream(self) -> temporalio.api.stream.v1.message_pb2.StreamRef: ... - def __init__( - self, - *, - seq: builtins.int = ..., - stream: temporalio.api.stream.v1.message_pb2.StreamRef | None = ..., - ) -> None: ... - def HasField( - self, field_name: typing.Literal["stream", b"stream"] - ) -> builtins.bool: ... - def ClearField( - self, field_name: typing.Literal["seq", b"seq", "stream", b"stream"] - ) -> None: ... - -global___CloseStream = CloseStream - @typing.final class ReadStream(google.protobuf.message.Message): - """Reads one page of a Stream, which has the Records after `from_offset`. The result comes in one + """Reads one page of a Stream, with the Records after `from_offset`. The result comes in one `ResolveStreamRead` job, by the activation rules of `ResolveStreamAppend`. To read on, lang sends - a new `ReadStream` from the `last_offset` of the page. - - A read has a time limit in each Workflow Task (`StreamSettings::read_time`), which is always - before the heartbeat of the task. So a read alone never keeps a task open with heartbeats. At - the limit, a read with no answer fails with `STREAM_ERROR_REASON_STORE_UNAVAILABLE` if its last - try failed or got no answer. Otherwise a read with a `wait` gives a page with no Record whose - `last_offset` is its `from_offset`, and a read with no `wait` goes on until the Store answers, - since only the Store can say that the Stream has no Record. From the limit on, no read keeps - the task open. - - Core keeps the Workflow Task while a read has no answer, as for an append, with one difference. - A command or a message for the server doesn't wait for a read. Core then completes the task and - asks for a new one, and the page comes in a later task. + a new `ReadStream` from the `last_offset` of the page. A Stream has no end that a read reports, + so the application's own last Record tells a reader to stop. + + A page is one answer of the Store. It has the Records that the Store has at once, up to + `max_records` and `max_bytes`, and Core never waits to fill it. A read with no Record after + `from_offset` waits up to `wait`, but at most the read time that its Workflow Task has left + (`StreamSettings::read_time`, half the task timeout by default, from the end of a replay). If + the Store answers with no Record before the wait is up, Core asks again from that answer's + `last_offset`, at most once per 100 ms. A page with no Record has the `last_offset` of the + Store's answer, which is `from_offset` if the Store moved past nothing. Its `wait_cut` is true if + the read time ended the wait before `wait`. + + At the read limit a read with a `wait` gives a page with no Record and `wait_cut`. A read with no + `wait` goes on, since only the Store can say that the Stream has no Record after its offset. + Before the limit Core keeps the task open while a read runs, unless the task has a command or a + message for the server. + + Before the task completes, each read that had no answer in it gets a check, which is one Store + call with no wait and a short deadline (`StreamSettings::read_check_deadline`). A command waits + for the check and no longer. If the check gets Records, the task gives them, or holds them for + the first activation of the next task if it has a command. If it gets no Record, a read with a + `wait` stops and starts again when the next task opens, and a read with no `wait` gives the page + with no Record. After the read limit each new read of the task is a check. So a read on an idle + Stream never makes a new task, and a drain with no `wait` ends in its task. + + Core asks for a new task when it knows that the Stream has Records for an open read. It knows + that when the Store gave Records after the page that the read continues from, or when the task + holds back the read's page. It also asks for a new task when the read result budget of the task + holds back a read. A query answer and the heartbeat of a Local Activity or an append ask for a + new task whatever the reads say. + + A Store outage fails the Workflow Task, as for an append, and never reaches lang as a read + result. That's the case if a check fails or gets no answer by its deadline, or if a read has had + no answer since a failed try at the read limit, at the completion or at the heartbeat. The + failure message then starts with `StreamStoreUnavailable:`. + + One Workflow Task gives at most 16 MiB of Records. A page that doesn't fit comes in the first + activation of the next task. Once a task gave `StreamSettings::max_task_read_results` read + results, 256 by default, its new reads get no check and start when the next task opens, which + Core asks for at once. No command cancels a read, so lang must accept the job of a read that nothing awaits. Core drops a read that has no result when lang sends the Workflow's last command. - History keeps the offsets, the count and a digest of each page, not its Records. A replay reads - the page from the Store again, and fails if the Records are gone or differ. That includes the - replay for a query of a closed Workflow. - - One Workflow Task gives at most 16 MiB of Records. A page that doesn't fit comes in the next - task. - - A negative `wait`, `max_records` or `max_bytes`, or a `from_offset` over 1024 bytes, fails the - Workflow Task, as the cases of `AppendToStream` do. A replay compares the `seq`, the `stream` - and the `from_offset` of the command with History. + The `core_stream_read` marker of the activation that gets the page keeps its offsets, the count + and a digest of its Records, and never the Records. A replay, also the replay for a query of a + closed Workflow, reads the page from the Store again, and fails if the Records are gone or + differ. So the Retention of the Stream must cover the life of the Workflow and the time in which + it gets queries. A replay reads the Records of all the read markers of History again, so a + reader should continue as new before those pass the 16 MiB that a Worker reads in one task. A + Worker with no runtime for the Store of a marker can't replay, and fails the task, or gives the + error as the answer of a legacy query. + + A replay compares the `seq`, the `stream` and the `from_offset` of the command with History, and + not the `max_records`, the `max_bytes` or the `wait`. It accepts a marker with no entry after any + task. After a replay Core doesn't know which Streams have Records after the pages of History, so + it learns that from the next answer of the Store. A negative `wait`, `max_records` or + `max_bytes`, a `from_offset` over 1024 bytes, or a bad `seq` or `stream` fails the Workflow Task. """ DESCRIPTOR: google.protobuf.descriptor.Descriptor @@ -2109,7 +2089,7 @@ class ReadStream(google.protobuf.message.Message): Store for at most 16 MiB. One larger Record still comes as a page. """ @property - def stream(self) -> temporalio.api.stream.v1.message_pb2.StreamRef: ... + def stream(self) -> temporalio.api.sdk.v1.stream_pb2.StreamRef: ... @property def wait(self) -> google.protobuf.duration_pb2.Duration: """How long the read waits for a Record if the Stream has none after `from_offset`. If it's @@ -2120,7 +2100,7 @@ class ReadStream(google.protobuf.message.Message): self, *, seq: builtins.int = ..., - stream: temporalio.api.stream.v1.message_pb2.StreamRef | None = ..., + stream: temporalio.api.sdk.v1.stream_pb2.StreamRef | None = ..., from_offset: builtins.bytes = ..., wait: google.protobuf.duration_pb2.Duration | None = ..., max_records: builtins.int = ..., diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index 4125c6382c..7903bf16cc 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit 4125c6382c0d0bce189f7b97187f7adbdc7f031d +Subproject commit 7903bf16ccfeded019b6d91806dbaaba6bc97c55 diff --git a/temporalio/bridge/src/streams.rs b/temporalio/bridge/src/streams.rs index 5f5f77a09e..dd149c94db 100644 --- a/temporalio/bridge/src/streams.rs +++ b/temporalio/bridge/src/streams.rs @@ -9,14 +9,14 @@ use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError}; use std::time::Duration; use temporalio_sdk_core::StreamRuntimes; use temporalio_streams::proto::{ - AppendRecordsRequest, AppendRecordsResponse, CloseStreamRequest, CloseStreamResponse, - CreateStreamRequest, CreateStreamResponse, DescribeStreamRequest, DescribeStreamResponse, - ReadRecordsRequest, ReadRecordsResponse, StreamErrorReason, + sdk, AppendRecordsRequest, AppendRecordsResponse, CreateStreamRequest, CreateStreamResponse, + DescribeStreamRequest, DescribeStreamResponse, ReadRecordsRequest, ReadRecordsResponse, + StreamErrorReason, }; use temporalio_streams::record::StoreLimits; use temporalio_streams::{ - AppendError, CloseError, CreateError, DescribeError, ReadError, StreamError, StreamRuntime, - StreamStore, WireReason, + AppendError, CreateError, DescribeError, ReadError, StreamError, StreamRuntime, StreamStore, + WireReason, }; use crate::runtime; @@ -198,13 +198,6 @@ impl StreamStore for PythonStore { Box::pin(self.call("ReadRecords", request, None)) } - fn close_stream( - &self, - request: CloseStreamRequest, - ) -> BoxFuture<'_, Result> { - Box::pin(self.call("CloseStream", request, None)) - } - fn describe_stream( &self, request: DescribeStreamRequest, @@ -214,10 +207,11 @@ impl StreamStore for PythonStore { } /// Calls the Python Store of `caller` for one Stream operation through a `StreamRuntime`, which -/// checks the request and the response. A create and an append need their `request_id`, which -/// the other operations don't take. The awaitable raises `StreamError` for a failed call. The -/// runtime has no limit of a batch, since the SDK that calls the Store has those in its Stream -/// config. +/// checks the request and the response. The request and the response are those of a Store, with +/// the Stream id, so a Store can run the checks of the runtime around itself. A create and an +/// append need their `request_id`, which the other operations don't take. The awaitable raises +/// `StreamError` for a failed call. The runtime has no limit of a batch, since the SDK that calls +/// the Store has those in its Stream config. #[pyfunction] #[pyo3(signature = (runtime_ref, caller, operation, request, request_id=None))] pub fn call_stream_store<'p>( @@ -240,8 +234,8 @@ pub fn call_stream_store<'p>( .ok_or_else(|| PyValueError::new_err(format!("A {operation} call needs a request id"))) }; macro_rules! run { - (|$request:ident| $call:expr) => {{ - let $request = Message::decode(request.as_bytes()) + (|$request:ident: $type:ty| $call:expr) => {{ + let $request: $type = Message::decode(request.as_bytes()) .map_err(|err| PyValueError::new_err(format!("Invalid proto: {err}")))?; runtime_ref.runtime.future_into_py(py, async move { let response = $call.await; @@ -254,21 +248,59 @@ pub fn call_stream_store<'p>( match operation { "CreateStream" => { let request_id = with_request_id()?; - run!(|decoded| stream_runtime.create_stream(decoded, request_id)) + run!(|decoded: CreateStreamRequest| async { + let request = sdk::CreateStreamRequest { + stream_ref: Some(stream_ref(decoded.stream_id)), + id_conflict_policy: decoded.id_conflict_policy, + }; + let response = stream_runtime.create_stream(request, request_id).await?; + Ok::<_, CreateError>(CreateStreamResponse { + created: response.created, + }) + }) } "AppendRecords" => { let request_id = with_request_id()?; - run!(|decoded| stream_runtime.append_records(decoded, request_id)) + run!(|decoded: AppendRecordsRequest| { + let request = sdk::AppendRecordsRequest { + r#ref: Some(stream_ref(decoded.stream_id)), + producer: decoded.producer, + records: decoded.records, + }; + stream_runtime.append_records(request, request_id) + }) } - "ReadRecords" => run!(|decoded| stream_runtime.read_records(decoded)), - "CloseStream" => run!(|decoded| stream_runtime.close_stream(decoded)), - "DescribeStream" => run!(|decoded| stream_runtime.describe_stream(decoded)), + "ReadRecords" => run!(|decoded: ReadRecordsRequest| { + let request = sdk::ReadRecordsRequest { + r#ref: Some(stream_ref(decoded.stream_id)), + from_offset: decoded.from_offset, + max_records: decoded.max_records, + max_bytes: decoded.max_bytes, + wait: decoded.wait, + }; + stream_runtime.read_records(request) + }), + "DescribeStream" => run!(|decoded: DescribeStreamRequest| { + let request = sdk::DescribeStreamRequest { + r#ref: Some(stream_ref(decoded.stream_id)), + }; + stream_runtime.describe_stream(request) + }), _ => Err(PyValueError::new_err(format!( "Unknown Stream operation: {operation}" ))), } } +/// Returns the ref that the runtime takes for a Store request's Stream id. The runtime gives the +/// Store only the id, so the ref needs no Store name. +fn stream_ref(id: String) -> sdk::StreamRef { + sdk::StreamRef { + id, + store: String::new(), + } +} + /// Returns the limits of a Stream config, which Python gives as its `max_record_bytes`, /// `max_batch_bytes` and `max_batch_records`. fn store_limits( From 3e34ca720c68789d309b5d507d08596a94b804c6 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Wed, 25 Nov 2026 12:40:03 -0700 Subject: [PATCH 24/50] Give a Stream Store the Store requests, with no close A Store takes and returns the messages of temporalio.api.streamservice.v1, and the SDK builds them from its requests with a ref. A read ends at its first page with no Record, and the memory Store counts Retention from the create and each append that writes a batch. --- changelog/added/steady-stream-heron.md | 6 +- temporalio/client/_stream_store.py | 255 ++++++++++++++---------- temporalio/contrib/streams/README.md | 14 +- temporalio/contrib/streams/_producer.py | 2 +- temporalio/nexus/system/_support.py | 5 +- temporalio/testing/_stream_store.py | 95 +++------ temporalio/worker/_worker.py | 2 +- tests/helpers/streams.py | 9 +- tests/nexus/test_streams.py | 132 ++++++------ tests/nexus/test_streams_with_worker.py | 21 +- tests/testing/test_stream_store.py | 146 ++++++-------- 11 files changed, 330 insertions(+), 357 deletions(-) diff --git a/changelog/added/steady-stream-heron.md b/changelog/added/steady-stream-heron.md index f5cd83fdca..8ab949fcc4 100644 --- a/changelog/added/steady-stream-heron.md +++ b/changelog/added/steady-stream-heron.md @@ -1,5 +1,5 @@ -Add experimental `temporalio.client.StreamStore`, the base class of a Stream Store, and `temporalio.testing.MemoryStreamStore`, a Store that keeps its Streams in memory for tests and local runs. A Store gets the request id of each create and each append as `request_id`, and a create returns the ref of its request. -Add experimental Streams for client and Activity code. `stream_config=StreamConfig(stores=[...])` of `Client.connect` gives a client its Stream Stores, and `Client.create_stream` and `Client.get_stream` return a `Stream` to append to, read, describe and close. A failed call raises `temporalio.exceptions.StreamError` with a `reason`. `max_record_bytes`, `max_batch_bytes` and `max_batch_records` of `StreamConfig` bound an append, and one over a limit fails before its Store gets it. A read of a Stream from `get_stream` needs `body_type=` or a `StreamRef` with a type argument, and raises `TypeError` with neither. `temporalio.contrib.streams.current_producer` gives the Producer of an Activity attempt, and `as_producer` gives back one that code stored. -Add experimental Streams for Workflow code. `workflow.create_stream` and `workflow.get_stream` return a `Stream` to append to, describe and close on the Stream Stores of the Worker's client, and `Replayer(stream_config=...)` gives a replay its Stores. +Add experimental `temporalio.client.StreamStore`, the base class of a Stream Store, and `temporalio.testing.MemoryStreamStore`, a Store that keeps its Streams in memory for tests and local runs. A Store gets the requests of `temporalio.api.streamservice.v1`, which have the Stream id, and the request id of each create and each append as `request_id`. A create returns only `created`, and the SDK gives the caller the ref with the name of the Store. A Stream has no close, and it expires when the Retention of its Store has passed since its create or its last append that wrote a batch. +Add experimental Streams for client and Activity code. `stream_config=StreamConfig(stores=[...])` of `Client.connect` gives a client its Stream Stores, and `Client.create_stream` and `Client.get_stream` return a `Stream` to append to, read and describe. A failed call raises `temporalio.exceptions.StreamError` with a `reason`. `max_record_bytes`, `max_batch_bytes` and `max_batch_records` of `StreamConfig` bound an append, and one over a limit fails before its Store gets it. A read of a Stream from `get_stream` needs `body_type=` or a `StreamRef` with a type argument, and raises `TypeError` with neither. `Stream.read` stops at the first page with no Record, so a read with no wait reads to the newest Record, and a read with a wait stops once no Record came within the wait. `temporalio.contrib.streams.current_producer` gives the Producer of an Activity attempt, and `as_producer` gives back one that code stored. +Add experimental Streams for Workflow code. `workflow.create_stream` and `workflow.get_stream` return a `Stream` to append to, read and describe on the Stream Stores of the Worker's client, and `Replayer(stream_config=...)` gives a replay its Stores. The SDK chooses the Store of each call before the call starts, also in a replay. Add experimental Stream reads for Workflow code. `Stream.read`, `read_pages` and `read_page` of a Workflow `Stream` give the Records as they come, a replay reads them again from the Store, and `temporalio.workflow.StreamReplayError` in the failure exception types of a Worker or a Workflow fails the Workflow when the Store no longer has them. The Worker option `stream_read_time` sets how long the reads of a Workflow Task can wait, and a read with a wait gives a page with no Record at that limit. Add experimental `temporalio.contrib.streams.BufferedAppender`, which batches the appends of one Stream in client and Activity code. `append` returns immediately, a batch waits at most `max_delay`, one write runs at a time, and `async with` or `flush()` writes what is left. diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 3680fad49b..db764f294d 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -15,6 +15,7 @@ import nexusrpc import temporalio.activity +import temporalio.api.sdk.v1 as sdk import temporalio.bridge.streams # pydoctor reads this module before the client package, for the worker modules that @@ -22,12 +23,9 @@ import temporalio.client import temporalio.nexus.system._support from temporalio.api.enums.v1 import StreamErrorReason -from temporalio.api.stream.v1 import StreamRef from temporalio.api.streamservice.v1 import ( AppendRecordsRequest, AppendRecordsResponse, - CloseStreamRequest, - CloseStreamResponse, CreateStreamRequest, CreateStreamResponse, DescribeStreamRequest, @@ -57,14 +55,25 @@ class StreamStore(ABC): A Store serves the operations of the Nexus service ``temporal.api.streamservice.v1.StreamService``. Each method takes the request message of its operation and returns its response message, both from - :py:mod:`temporalio.api.streamservice.v1`. A :py:class:`StreamConfig` registers - a Store under its :py:meth:`name`, and the SDK sends each Stream call to the - Store of the call's ``StreamRef``. Only the SDK reads the ``store`` of a ref. + :py:mod:`temporalio.api.streamservice.v1`. A request has the id of its Stream + and no ``StreamRef``. A :py:class:`StreamConfig` registers a Store under its + :py:meth:`name`, and the SDK sends each Stream call to the Store of the call's + ``StreamRef``. The SDK gives the ref of a created Stream the name of its Store, + so only the SDK reads and sets the ``store`` of a ref. Callers rely on a Store to follow the rules below and those of each method. SDK Core reads a Stream for Workflow code and reads it again in a replay, and both depend on them. + Retention: + + * A Stream expires when its Retention has passed since its create or since + the last append that wrote a batch. Retention is a setting of the Store. + * A Store answers a call for an expired Stream with ``EXPIRED``, and no longer + keeps its Records. + * A Stream has no end that a Store records. A reader learns the end from the + application's own last Record. + The log: * A Store keeps the body of a Record as the append gave it. The payload codec @@ -85,14 +94,13 @@ class StreamStore(ABC): * An attempt is the try of a Producer that made a write, such as one Workflow Task or one attempt of an Activity. * Fencing is optional. A Store that fences keeps the newest attempt of each - Producer that appended to a Stream, and refuses an append or a close of an - earlier attempt of that Producer. Only an append changes the newest attempt. - Every Record has its Producer and attempt either way, so a reader can tell - the attempts apart. + Producer that appended to a Stream, and refuses an append of an earlier + attempt of that Producer. Every Record has its Producer and attempt either + way, so a reader can tell the attempts apart. A method refuses a call by raising a :py:class:`temporalio.exceptions.StreamError` with the reason, such as - ``STREAM_ERROR_REASON_CLOSED`` for ``CLOSED`` in these docs. Any other + ``STREAM_ERROR_REASON_EXPIRED`` for ``EXPIRED`` in these docs. Any other exception is an outage of the Store, and the caller gets a ``StreamError`` with ``STREAM_ERROR_REASON_STORE_UNAVAILABLE``. @@ -105,8 +113,8 @@ class StreamStore(ABC): the Store must stay usable after it. * A resend can come while its first try still runs, and the Store still writes the batch once. - * SDK Core checks each append, close and read of Workflow code, and its - response, and tries the call again during an outage. For every other call + * SDK Core checks each append and read of Workflow code, and its response, + and tries the call again during an outage. For every other call the SDK checks only an append, against the limits of the :py:class:`StreamConfig`, and sends one request. A Store that needs more checks runs them itself. @@ -127,20 +135,23 @@ def name(self) -> str: async def create_stream( self, request: CreateStreamRequest, *, request_id: str ) -> CreateStreamResponse: - """Create a Stream, or return the open one if the conflict policy allows it. + """Create a Stream, or find the one that has the id if the conflict policy + allows it. Each try of one create has the same ``request_id``. A create with the ``request_id`` of the create that made the Stream is a retry of it, and a - create with an empty ``request_id`` never is. The response has the ref as - the request had it. + create with an empty ``request_id`` never is. The response has only + ``created``. A Store checks a create for an id that has a Stream in this order: 1. The Stream expired, so the create fails with ``EXPIRED``. - 2. The Stream is closed, so the create fails with ``CLOSED``. - 3. The create is a retry, so it returns ``created`` true. - 4. The policy is ``USE_EXISTING``, so it returns ``created`` false. With + 2. The create is a retry, so it returns ``created`` true. + 3. The policy is ``USE_EXISTING``, so it returns ``created`` false. With ``FAIL``, or with no policy, it fails with ``ALREADY_EXISTS``. + + A create that makes the Stream starts its Retention. A create of a Stream + that exists doesn't start it again. """ raise NotImplementedError @@ -161,13 +172,13 @@ async def append_records( 1. The Stream doesn't exist or it expired, so the append fails with ``NOT_FOUND`` or ``EXPIRED``. 2. The append is a resend, so the Store writes nothing and returns the - offsets of the first write. It doesn't compare the Records, and the - Stream can be closed by then. + offsets of the first write. It doesn't compare the Records. 3. The Store fences, and a later attempt of the Producer already wrote, so the append fails with ``FENCED``. - 4. The Stream is closed, so the append fails with ``CLOSED``. - The response has the offsets of the first and the last Record. + The response has the offsets of the first and the last Record. An append + that writes its batch starts the Retention of the Stream again, and a + resend doesn't. """ raise NotImplementedError @@ -181,36 +192,20 @@ async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse * ``last_offset`` is where the next read continues. A Store doesn't have to set it. If it's empty, the caller gets the offset of the last Record of the page, or ``from_offset`` for a page with no Record. - * A page is ``done`` when the Stream is closed and no Record comes after - the page. - * A read with nothing after ``from_offset`` answers once a Record comes, - once the Stream is closed, or once its ``wait`` is up. + * A read with nothing after ``from_offset`` answers once a Record comes or + once its ``wait`` is up. With no ``wait``, it answers at once. * Every offset that a response returned is a valid ``from_offset``. A read fails with ``OFFSET_TOO_HIGH`` only when ``from_offset`` is past the end of the Stream. """ raise NotImplementedError - @abstractmethod - async def close_stream(self, request: CloseStreamRequest) -> CloseStreamResponse: - """Close a Stream. - - A Store checks a close in this order: - - 1. The Stream doesn't exist or it expired, so the close fails with - ``NOT_FOUND`` or ``EXPIRED``. - 2. The Stream is already closed, so the close succeeds. - 3. The Store fences, and a later attempt of the Producer already wrote, so - the close fails with ``FENCED``. - """ - raise NotImplementedError - @abstractmethod async def describe_stream( self, request: DescribeStreamRequest ) -> DescribeStreamResponse: - """Return the status of a Stream, and a ``last_offset`` that is never below - the offset of its newest Record. + """Return a ``last_offset`` that is never below the offset of the newest + Record of a Stream. """ raise NotImplementedError @@ -247,17 +242,22 @@ class StreamConfig: ``STREAM_ERROR_REASON_TOO_LARGE``. The ``rpc_metadata`` of a Stream call has no effect, since a call to a Store is not an RPC of the Temporal server. + A Stream has no close. It expires when the Retention of its Store has passed + since its create or since the last append that wrote a batch. A reader learns + the end of a Stream from the application's own last Record. + For the Stream calls of Workflow code: - - SDK Core makes each append, close and read. A create and a describe run in - a Local Activity of the SDK, which the interceptors of the Worker see as + - The SDK chooses the Store of each call before the call starts, also in a + replay. SDK Core makes each append and read. A create and a describe run + in a Local Activity of the SDK, which the interceptors of the Worker see as any other Local Activity. - An append is at-least-once. If a Workflow Task fails after its append, the next attempt of the task writes the batch again. - An outage of the Store gives Workflow code no error. The Workflow Task fails, and the server tries it again. - A call that Workflow code doesn't await before the Workflow ends may not - happen. A Workflow that needs its close awaits it, as ``async with`` does. + happen. - A call with no Store fails the Workflow Task, also when Workflow code catches the error. - A Worker reads the three limits when it starts. It refuses a new client @@ -267,12 +267,18 @@ class StreamConfig: - A read fails with ``STREAM_ERROR_REASON_UNSUPPORTED`` for a Record over :py:attr:`max_record_bytes`. So a reader needs a limit at least as large as that of each writer of its Stream. - - A read holds its Workflow Task, up to the read limit of the task, which - the Worker option ``stream_read_time`` sets. A Signal that comes meanwhile - waits until the read has its page, or until that limit. At the limit, a - read with a wait gives a page with no Record, and a read with no wait - goes on without holding the task until the Store answers. A command for - the server doesn't wait for a read. + - A read with no Record to give waits up to its ``wait``, but at most to the + read limit of its Workflow Task, which the Worker option + ``stream_read_time`` sets. It then gives a page with no Record. A read + with no wait goes on until the Store answers. + - A read holds its Workflow Task up to the read limit. A Signal that comes + meanwhile waits until the read has its page, or until that limit. A + command for the server doesn't wait for a read. + - A read asks for a new Workflow Task only when SDK Core knows that the + Stream has more Records for it, so a read of an idle Stream makes no task. + - A replay reads the Records of each read from the Store again. So the + Retention of a Stream must cover the life of each Workflow that reads it, + and the time in which that Workflow gets queries. - A body that isn't of the Stream's type fails the Workflow Task, as an Activity result that can't be converted does. @@ -358,7 +364,7 @@ def _store(self, name: str) -> StreamStore: def _store_for( self, - ref: StreamRef, + ref: sdk.StreamRef, target: StorageDriverActivityInfo | StorageDriverWorkflowInfo | None, namespace: str, ) -> StreamStore: @@ -383,37 +389,77 @@ def _limits(self) -> tuple[int, int, int]: return self.max_record_bytes, self.max_batch_bytes, self.max_batch_records -def _request_ref(request: google.protobuf.message.Message) -> StreamRef: - """Return the ref of a Stream request, which is ``stream_ref`` in a create.""" - if isinstance(request, CreateStreamRequest): +def _request_ref(request: google.protobuf.message.Message) -> sdk.StreamRef: + """Return the ref of an SDK Stream request, which is ``stream_ref`` in a create.""" + if isinstance(request, sdk.CreateStreamRequest): return request.stream_ref assert isinstance( request, - ( - AppendRecordsRequest, - ReadRecordsRequest, - CloseStreamRequest, - DescribeStreamRequest, - ), + (sdk.AppendRecordsRequest, sdk.ReadRecordsRequest, sdk.DescribeStreamRequest), ) return request.ref -def _operation( - name: str, -) -> tuple[ - str, type[google.protobuf.message.Message], type[google.protobuf.message.Message] -]: +_Message = type[google.protobuf.message.Message] + +_STORE_OPERATIONS: dict[str, tuple[str, _Message, _Message]] = { + "CreateStream": ("create_stream", CreateStreamRequest, CreateStreamResponse), + "AppendRecords": ("append_records", AppendRecordsRequest, AppendRecordsResponse), + "ReadRecords": ("read_records", ReadRecordsRequest, ReadRecordsResponse), + "DescribeStream": ( + "describe_stream", + DescribeStreamRequest, + DescribeStreamResponse, + ), +} + + +def _store_operation(name: str) -> tuple[str, _Message, _Message]: """Return the :py:class:`StreamStore` method of a Stream operation, with the - classes of its request message and of its response message. + classes of its Store request and of its Store response. + """ + return _STORE_OPERATIONS[name] + + +def _sdk_request_type( # pyright: ignore[reportUnusedFunction] + name: str, +) -> _Message: + """Return the class of the SDK request of a Stream operation, which has the + ref of its Stream. """ operation = _STREAM_SERVICE.operation_definitions[name] - request, response = ( - _get_transfer_type_converter(model) - for model in (operation.input_type, operation.output_type) - ) - assert request and request.transfer_type and response and response.transfer_type - return operation.method_name, request.transfer_type, response.transfer_type + 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: + """Return the Store request of an SDK request, which has the id of the Stream + of the request's ref. + """ + stream_id = _request_ref(request).id + if isinstance(request, sdk.CreateStreamRequest): + return CreateStreamRequest( + stream_id=stream_id, id_conflict_policy=request.id_conflict_policy + ) + if isinstance(request, sdk.AppendRecordsRequest): + append = AppendRecordsRequest(stream_id=stream_id, records=request.records) + if request.HasField("producer"): + append.producer.CopyFrom(request.producer) + return append + if isinstance(request, sdk.ReadRecordsRequest): + read = ReadRecordsRequest( + stream_id=stream_id, + from_offset=request.from_offset, + max_records=request.max_records, + max_bytes=request.max_bytes, + ) + if request.HasField("wait"): + read.wait.CopyFrom(request.wait) + return read + return DescribeStreamRequest(stream_id=stream_id) async def _call_method( @@ -431,7 +477,7 @@ async def _call_method( other exception, and ``STREAM_ERROR_REASON_STORE_CORRUPT`` if it returned something else than the response message of the operation. """ - method, _, response_type = _operation(operation) + method, _, response_type = _store_operation(operation) call = getattr(store, method) try: if request_id is None: @@ -465,31 +511,33 @@ async def _call_store( # pyright: ignore[reportUnusedFunction] timeout: timedelta | None = None, ) -> google.protobuf.message.Message: """Call a Store for client code, which is :py:func:`_call_method` with the - payload codec, the check of an append, the Store of a created Stream and a - timeout. + Store request of an SDK request, the payload codec, the check of an append, + the ref of a created Stream and a timeout. - The codec gets each body of an append and each Record of a read alone, with no + ``request`` is the SDK request, with its ref, and the response of a create is + the SDK response, with the ref. The other responses are those of the Store. The + codec gets each body of an append and each Record of a read alone, with no serialization context, since the reader of a Record can be any code. ``limits`` - are those of the Stream config, from :py:meth:`StreamConfig._limits`. The ref - of a create's response gets the name of ``store``. + are those of the Stream config, from :py:meth:`StreamConfig._limits`. Raises: - StreamError: The call failed. The reason is - ``STREAM_ERROR_REASON_STORE_CORRUPT`` for a create's response whose ref - doesn't have the Stream id of the request. + StreamError: The call failed. """ - if codec and isinstance(request, AppendRecordsRequest): - for appended in request.records: - [body] = await codec.encode([appended.body]) - appended.body.CopyFrom(body) - if isinstance(request, AppendRecordsRequest): + store_request = _store_request(request) + if isinstance(store_request, AppendRecordsRequest): + if codec: + for appended in store_request.records: + [body] = await codec.encode([appended.body]) + appended.body.CopyFrom(body) # SDK Core checks an append of Workflow code the same way, so each path refuses # the same batch before its Store gets it. - temporalio.bridge.streams.check_append(limits, request.SerializeToString()) + temporalio.bridge.streams.check_append( + limits, store_request.SerializeToString() + ) try: # A timeout of zero is no timeout, as for an RPC of the client. async with asyncio.timeout(timeout.total_seconds() if timeout else None): - response = await _call_method(store, operation, request, request_id) + response = await _call_method(store, operation, store_request, request_id) except TimeoutError as err: raise StreamError( f"The Stream Store '{store.name()}' didn't answer the {operation} call " @@ -497,25 +545,21 @@ async def _call_store( # pyright: ignore[reportUnusedFunction] reason=StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE, ) from err if isinstance(response, ReadRecordsResponse) and not response.last_offset: - assert isinstance(request, ReadRecordsRequest) + assert isinstance(store_request, ReadRecordsRequest) # The page shows where it ended, so a Store doesn't have to say it. records = response.records - response.last_offset = records[-1].offset if records else request.from_offset + response.last_offset = ( + records[-1].offset if records else store_request.from_offset + ) if codec and isinstance(response, ReadRecordsResponse): for record in response.records: [body] = await codec.decode([record.body]) record.body.CopyFrom(body) if isinstance(response, CreateStreamResponse): - assert isinstance(request, CreateStreamRequest) - if response.ref.id != request.stream_ref.id: - raise StreamError( - f"The Stream Store '{store.name()}' answered the {operation} call " - "without the Stream id of the request", - reason=StreamErrorReason.STREAM_ERROR_REASON_STORE_CORRUPT, - ) # Each later call of the created Stream goes to this Store, whatever the # selector picks then. - response.ref.store = store.name() + ref = sdk.StreamRef(id=_request_ref(request).id, store=store.name()) + return sdk.CreateStreamResponse(ref=ref, created=response.created) return response @@ -554,7 +598,7 @@ async def _call_stream_store( # pyright: ignore[reportUnusedFunction] _request_ref(request), _activity_target(), client.namespace ) request_id = None - if isinstance(request, (CreateStreamRequest, AppendRecordsRequest)): + if isinstance(request, (sdk.CreateStreamRequest, sdk.AppendRecordsRequest)): request_id = str(uuid.uuid4()) response = await _call_store( store, @@ -584,11 +628,10 @@ async def _call_stream_store( # pyright: ignore[reportUnusedFunction] class _StoreCaller: # pyright: ignore[reportUnusedClass] - """The caller of a Stream Store for the bridge, which gives and takes encoded - messages. + """The caller of a Stream Store for the bridge, which gives and takes the + encoded Store messages. - SDK Core calls :py:meth:`call` for each append, close and read of Workflow - code. + SDK Core calls :py:meth:`call` for each append and read of Workflow code. """ def __init__(self, store: Callable[[], StreamStore]) -> None: @@ -612,7 +655,7 @@ async def call( task = asyncio.current_task() assert task on_task(task) - _, request_type, _ = _operation(operation) + _, request_type, _ = _store_operation(operation) try: response = await _call_method( self._store(), operation, request_type.FromString(request), request_id diff --git a/temporalio/contrib/streams/README.md b/temporalio/contrib/streams/README.md index 64ce9af567..5a77afa3d2 100644 --- a/temporalio/contrib/streams/README.md +++ b/temporalio/contrib/streams/README.md @@ -44,7 +44,7 @@ call of its Stream. ## A stored Producer Each write has its Producer, which is the writer with its attempt. `current_producer()` gives -the Producer that an append or a close of the running Activity attempt sends by default. An +the Producer that an append of the running Activity attempt sends by default. An Activity that stores it, such as in its heartbeat details, gets it back as a proto message, and `as_producer` turns that into a `Producer` again, which `append(..., producer=...)` takes. @@ -54,6 +54,18 @@ A read of a Stream from `get_stream(StreamRef(id=...))` raises `TypeError`, sinc no body type. Pass `body_type=`, or a ref with a type argument such as `StreamRef[str](id=...)`. A Stream from `create_stream` reads any body with no type. +A Stream has no end that a read reports, so a reader stops at the application's own last Record. +`read()` stops at the first page with no Record. With no `wait` it reads to the newest Record, and +with a `wait` it stops once no Record came within the wait. It reads a page only when the caller +asks for the next Record, so a reader that stops at its last Record leaves no read open. + +In Workflow code, a read with no Record to give waits up to its `wait`, but at most to the read +limit of its Workflow Task (the Worker option `stream_read_time`), and then gives a page with no +Record. A read asks for a new Workflow Task only when the Stream has more Records for it, so a +read of an idle Stream makes no task. A replay reads the Records again from the Store, so the +Retention of the Stream must cover the life of the Workflow and the time in which it gets +queries. + In Workflow code, a read with no `max_records` gives at most 256 Records in a page, and a read with no `max_bytes` at most 4 MiB of them. A page has at most 16 MiB of Records, also for a larger `max_bytes`. A read fails for a Record over the `max_record_bytes` of the Worker's `StreamConfig`, diff --git a/temporalio/contrib/streams/_producer.py b/temporalio/contrib/streams/_producer.py index 90bbf59617..c8d89c0c9c 100644 --- a/temporalio/contrib/streams/_producer.py +++ b/temporalio/contrib/streams/_producer.py @@ -16,7 +16,7 @@ def current_producer() -> Producer: """Return the Producer of the running attempt of an Activity. - An append or a close of that attempt sends it by default. Code that stores + 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 diff --git a/temporalio/nexus/system/_support.py b/temporalio/nexus/system/_support.py index 74ced10c89..058b662bb0 100644 --- a/temporalio/nexus/system/_support.py +++ b/temporalio/nexus/system/_support.py @@ -185,8 +185,9 @@ def _timestamp(time: datetime) -> "Timestamp": def next_read_request( request: "ReadRecordsRequest[_BodyT]", response: "ReadRecordsResponse[_BodyT]" ) -> "ReadRecordsRequest[_BodyT] | None": - # A read with no wait, or a wait of zero, ends at its first page with no Record. - if response.done or (not request.wait and not response.records): + # A Stream has no end that a read reports. A page with no Record says that no + # Record came within the wait, or at once with no wait, so the read stops there. + if not response.records: return None return dataclasses.replace( request, from_offset=response.last_offset or request.from_offset diff --git a/temporalio/testing/_stream_store.py b/temporalio/testing/_stream_store.py index fd74937688..c4f9156bb7 100644 --- a/temporalio/testing/_stream_store.py +++ b/temporalio/testing/_stream_store.py @@ -12,11 +12,7 @@ import temporalio.bridge.streams import temporalio.runtime -from temporalio.api.enums.v1 import ( - StreamErrorReason, - StreamIdConflictPolicy, - StreamStatus, -) +from temporalio.api.enums.v1 import StreamErrorReason, StreamIdConflictPolicy from temporalio.api.stream.v1 import ( ActivityAttempt, LocalActivityAttempt, @@ -27,8 +23,6 @@ from temporalio.api.streamservice.v1 import ( AppendRecordsRequest, AppendRecordsResponse, - CloseStreamRequest, - CloseStreamResponse, CreateStreamRequest, CreateStreamResponse, DescribeStreamRequest, @@ -63,7 +57,6 @@ def __init__( *, name: str = "memory", retention: timedelta | None = None, - producer_idle_ttl: timedelta | None = None, resend_window: int | None = None, fence: bool = False, runtime: temporalio.runtime.Runtime | None = None, @@ -73,18 +66,16 @@ def __init__( Args: name: The name of the Store in a :py:class:`temporalio.client.StreamConfig`. - retention: How long after its close a Stream expires. Defaults to 7 - days. - producer_idle_ttl: How long after its last write an open Stream - expires. If unset, an open Stream doesn't expire. + 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, and so does its close of - an open Stream. + its Producer has written to the Stream. runtime: The runtime whose threads run the checks of SDK Core. Defaults to :py:meth:`temporalio.runtime.Runtime.default`. """ @@ -95,7 +86,6 @@ def __init__( streams = _MemoryStreams( name, retention=timedelta(days=7) if retention is None else retention, - producer_idle_ttl=producer_idle_ttl, resend_window=16 if resend_window is None else resend_window, fence=fence, ) @@ -125,10 +115,6 @@ async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse """See base class.""" return ReadRecordsResponse.FromString(await self._call("ReadRecords", request)) - async def close_stream(self, request: CloseStreamRequest) -> CloseStreamResponse: - """See base class.""" - return CloseStreamResponse.FromString(await self._call("CloseStream", request)) - async def describe_stream( self, request: DescribeStreamRequest ) -> DescribeStreamResponse: @@ -176,14 +162,13 @@ class _Stream: request_id: str """The request id of the create that made the Stream.""" - expires_at: float | None - """The time of the event loop at which the Stream expires, if it does.""" + 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) - closed: bool = False changed: asyncio.Event = field(default_factory=asyncio.Event) - """Set at the next append or close, which then puts a new event here.""" + """Set at the next append that writes, which then puts a new event here.""" @property def last_offset(self) -> bytes: @@ -198,13 +183,11 @@ def __init__( name: str, *, retention: timedelta, - producer_idle_ttl: timedelta | None, resend_window: int, fence: bool, ) -> None: self._name = name self._retention = retention - self._producer_idle_ttl = producer_idle_ttl self._resend_window = resend_window self._fence = fence self._streams: dict[str, _Stream] = {} @@ -215,22 +198,17 @@ def name(self) -> str: async def create_stream( self, request: CreateStreamRequest, *, request_id: str ) -> CreateStreamResponse: - stream_id = request.stream_ref.id + stream_id = request.stream_id if stream_id not in self._streams: - self._streams[stream_id] = _Stream(request_id, self._idle_expiry()) - return CreateStreamResponse(ref=request.stream_ref, created=True) + self._streams[stream_id] = _Stream(request_id, self._expiry()) + return CreateStreamResponse(created=True) stream = self._stream(stream_id) - if stream.closed: - raise StreamError( - f"The Stream '{stream_id}' is closed", - reason=StreamErrorReason.STREAM_ERROR_REASON_CLOSED, - ) # An empty request id identifies no create, so it never matches. if request_id and request_id == stream.request_id: - return CreateStreamResponse(ref=request.stream_ref, created=True) + return CreateStreamResponse(created=True) use_existing = StreamIdConflictPolicy.STREAM_ID_CONFLICT_POLICY_USE_EXISTING if request.id_conflict_policy == use_existing: - return CreateStreamResponse(ref=request.stream_ref, created=False) + return CreateStreamResponse(created=False) raise StreamError( f"The Stream '{stream_id}' already exists", reason=StreamErrorReason.STREAM_ERROR_REASON_ALREADY_EXISTS, @@ -239,7 +217,7 @@ async def create_stream( async def append_records( self, request: AppendRecordsRequest, *, request_id: str ) -> AppendRecordsResponse: - stream = self._stream(request.ref.id) + stream = self._stream(request.stream_id) key, attempt = _producer_key(request.producer), _attempt(request.producer) writer = stream.writers.get(key) if writer is None: @@ -249,12 +227,7 @@ async def append_records( if (batch.attempt, batch.request_id) == (attempt, request_id): return batch.response if self._fence and attempt < writer.newest: - raise _fenced(request.ref.id) - if stream.closed: - raise StreamError( - f"The Stream '{request.ref.id}' is closed", - reason=StreamErrorReason.STREAM_ERROR_REASON_CLOSED, - ) + raise _fenced(request.stream_id) first = len(stream.records) + 1 stream.records.extend( StreamRecord( @@ -270,23 +243,23 @@ async def append_records( writer.newest = attempt writer.window.append(_Batch(attempt, request_id, response)) stream.writers[key] = writer - stream.expires_at = self._idle_expiry() + stream.expires_at = self._expiry() self._notify(stream) return response async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: - stream = self._stream(request.ref.id) + stream = self._stream(request.stream_id) if request.from_offset > stream.last_offset: raise StreamError( f"The from_offset of the read is past the newest offset of the " - f"Stream '{request.ref.id}'", + f"Stream '{request.stream_id}'", reason=StreamErrorReason.STREAM_ERROR_REASON_OFFSET_TOO_HIGH, ) start = bisect.bisect_right( stream.records, request.from_offset, key=lambda record: record.offset ) wait = request.wait.ToTimedelta().total_seconds() - if start == len(stream.records) and not stream.closed and wait > 0: + if start == len(stream.records) and wait > 0: try: async with asyncio.timeout(wait): await stream.changed.wait() @@ -299,31 +272,13 @@ async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse return ReadRecordsResponse( records=records, last_offset=records[-1].offset if records else request.from_offset, - done=stream.closed and end == len(stream.records), ) - async def close_stream(self, request: CloseStreamRequest) -> CloseStreamResponse: - stream = self._stream(request.ref.id) - if stream.closed: - return CloseStreamResponse() - writer = stream.writers.get(_producer_key(request.producer)) - if self._fence and writer and _attempt(request.producer) < writer.newest: - raise _fenced(request.ref.id) - stream.closed = True - stream.expires_at = self._now() + self._retention.total_seconds() - self._notify(stream) - return CloseStreamResponse() - async def describe_stream( self, request: DescribeStreamRequest ) -> DescribeStreamResponse: - stream = self._stream(request.ref.id) - return DescribeStreamResponse( - status=StreamStatus.STREAM_STATUS_CLOSED - if stream.closed - else StreamStatus.STREAM_STATUS_OPEN, - last_offset=stream.last_offset, - ) + 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) @@ -332,7 +287,7 @@ def _stream(self, stream_id: str) -> _Stream: f"The Stream '{stream_id}' doesn't exist", reason=StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND, ) - if stream.expires_at is not None and self._now() >= stream.expires_at: + if self._now() >= stream.expires_at: raise StreamError( f"The Stream '{stream_id}' expired", reason=StreamErrorReason.STREAM_ERROR_REASON_EXPIRED, @@ -342,10 +297,8 @@ def _stream(self, stream_id: str) -> _Stream: def _now(self) -> float: return asyncio.get_running_loop().time() - def _idle_expiry(self) -> float | None: - if self._producer_idle_ttl is None: - return None - return self._now() + self._producer_idle_ttl.total_seconds() + def _expiry(self) -> float: + return self._now() + self._retention.total_seconds() def _notify(self, stream: _Stream) -> None: stream.changed.set() diff --git a/temporalio/worker/_worker.py b/temporalio/worker/_worker.py index b04737f3f7..c03112daef 100644 --- a/temporalio/worker/_worker.py +++ b/temporalio/worker/_worker.py @@ -354,7 +354,7 @@ def __init__( without holding the task until the Store answers. Defaults to half the Workflow Task timeout. The limit is always before the heartbeat of the task, so a read alone never makes the Worker send a - heartbeat. Appends and closes have no such limit. + heartbeat. Appends have no such limit. WARNING: This setting is experimental. """ diff --git a/tests/helpers/streams.py b/tests/helpers/streams.py index 484d0d2ff7..266419cec6 100644 --- a/tests/helpers/streams.py +++ b/tests/helpers/streams.py @@ -19,8 +19,6 @@ from temporalio.api.streamservice.v1 import ( AppendRecordsRequest, AppendRecordsResponse, - CloseStreamRequest, - CloseStreamResponse, CreateStreamRequest, CreateStreamResponse, DescribeStreamRequest, @@ -169,8 +167,8 @@ class FaultStore(StreamStore): def __init__(self, name: str = "memory", **options: Any) -> None: self.memory = MemoryStreamStore(name=name, **options) self.calls: list[tuple[Any, str | None]] = [] - """Each request, with its request id, which is ``None`` for a read, a close - and a describe.""" + """Each request, with its request id, which is ``None`` for a read and a + describe.""" self.faults: dict[str, collections.deque[Fault]] = collections.defaultdict( collections.deque ) @@ -196,9 +194,6 @@ async def append_records( async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: return await self._call("read_records", request) - async def close_stream(self, request: CloseStreamRequest) -> CloseStreamResponse: - return await self._call("close_stream", request) - async def describe_stream( self, request: DescribeStreamRequest ) -> DescribeStreamResponse: diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index f99f33eabb..37692b6b19 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -33,7 +33,6 @@ Producer, StreamErrorDetails, ) -from temporalio.api.stream.v1 import StreamRef as RefProto from temporalio.client import ( Client, NexusOperationHandle, @@ -180,28 +179,19 @@ def selector(context: StreamSelectContext) -> FaultStore: # A created Stream stays on its Store, whatever the selector picks at this call. stream, store = rng.choice(created) ref_store = stream.ref.store - match rng.choice(["append", "describe", "close"]): - case "append": - bodies = [rng.randrange(100) for _ in range(rng.randrange(3))] - call = stream.append(*bodies) - expected = proto.AppendRecordsRequest( - ref=RefProto(id=stream.ref.id, store=ref_store), - producer=producers[in_activity], - records=[ - AppendRecord(body=to_payload(body)) for body in bodies - ], - ) - case "describe": - call = stream.describe() - expected = proto.DescribeStreamRequest( - ref=RefProto(id=stream.ref.id, store=ref_store) - ) - case _: - call = stream.close() - expected = proto.CloseStreamRequest( - ref=RefProto(id=stream.ref.id, store=ref_store), - producer=producers[in_activity], - ) + if rng.random() < 0.5: + bodies = [rng.randrange(100) for _ in range(rng.randrange(3))] + call = stream.append(*bodies) + expected = proto.AppendRecordsRequest( + stream_id=stream.ref.id, + producer=producers[in_activity], + records=[ + AppendRecord(body=to_payload(body)) for body in bodies + ], + ) + else: + call = stream.describe() + expected = proto.DescribeStreamRequest(stream_id=stream.ref.id) else: store = next((s for s in stores if s.name() == ref_store), None) if ref_store is None and has_selector: @@ -209,7 +199,6 @@ def selector(context: StreamSelectContext) -> FaultStore: elif ref_store is None: store = stores[0] ref = StreamRef[int](id=stream_id, store=ref_store) - ref_proto = RefProto(id=stream_id, store=ref_store or "") match operation: case "create": policy = rng.choice(list(StreamIdConflictPolicy.values())) @@ -222,11 +211,11 @@ def selector(context: StreamSelectContext) -> FaultStore: body_type=int, ) expected = proto.CreateStreamRequest( - stream_ref=ref_proto, id_conflict_policy=policy + stream_id=stream_id, id_conflict_policy=policy ) case "read": expected = proto.ReadRecordsRequest( - ref=ref_proto, + stream_id=stream_id, from_offset=rng.randbytes(rng.randrange(3)), max_records=rng.choice([0, 1, 2**31 - 1]), max_bytes=rng.choice([0, 1, 2**62]), @@ -242,7 +231,7 @@ def selector(context: StreamSelectContext) -> FaultStore: ) case _: call = client.get_stream(ref).describe() - expected = proto.DescribeStreamRequest(ref=ref_proto) + expected = proto.DescribeStreamRequest(stream_id=stream_id) logs = [list(s.requests) for s in stores] del selects[:], ref_stores[:] @@ -357,84 +346,81 @@ class _FakeReads(temporalio.client.OutboundInterceptor): """Answers each read with the next page of a generated Stream.""" def __init__( - self, - next: temporalio.client.OutboundInterceptor, - rng: random.Random, - records: int, - closed: bool, + self, next: temporalio.client.OutboundInterceptor, rng: random.Random ) -> None: super().__init__(next) self._rng = rng - self._records = records - self._closed = closed - self._requests = 0 + self.records = 0 + """The number of Records of the Stream, which a test can raise.""" + self.starts: list[int] = [] + """The Record after which each read started, in the order of the reads.""" async def start_nexus_operation( self, input: temporalio.client.StartNexusOperationInput ) -> NexusOperationHandle[Any]: request: ReadRecordsRequest[int] = input.arg - # A read that goes on at an end, or that doesn't move on, would never stop. - self._requests += 1 - assert self._requests <= self._records + 3 start = int.from_bytes(request.from_offset or b"", "big") - # A Store answers with no Record only at the end of the Stream. + self.starts.append(start) size = self._rng.randrange(1, 4) - end = min(self._records, start + size) + # A read with a wait can see no Record come within its wait, also when more + # come later. With no wait, a Store answers with no Record only at the end. + if request.wait and self._rng.random() < 0.2: + size = 0 + end = min(self.records, start + size) page = ReadRecordsResponse( records=[ StreamRecord(body=at, offset=at.to_bytes(8, "big")) for at in range(start + 1, end + 1) ], - last_offset=end.to_bytes(8, "big") if end else None, - done=self._closed and end == self._records, + last_offset=request.from_offset or None, ) + if page.records: + page.last_offset = page.records[-1].offset handle: NexusOperationHandle[Any] = NexusOperationHandle(Mock(), input.id) handle._known_outcome = page return handle -async def test_a_polled_read_gives_each_record_once_in_order() -> None: +async def test_a_read_gives_each_record_once_and_ends_at_a_page_with_no_record() -> ( + None +): for seed in range(300): with failure_note(f"seed {seed}"): await _read_script(random.Random(seed)) async def _read_script(rng: random.Random) -> None: - records, closed = rng.randrange(12), rng.random() < 0.5 - wait = rng.choice([None, timedelta(0), timedelta(seconds=5)]) - client = Client( - Mock(spec=ServiceClient), - interceptors=[ - _Interceptor(lambda next: _FakeReads(next, rng, records, closed)) - ], - ) + fake: list[_FakeReads] = [] + + def outbound(next: temporalio.client.OutboundInterceptor) -> _FakeReads: + fake.append(_FakeReads(next, rng)) + return fake[0] + + client = Client(Mock(spec=ServiceClient), interceptors=[_Interceptor(outbound)]) stream = client.get_stream(StreamRef[int](id="s")) - # A Stream that stays open has no last page for a read that waits, so the loop - # of such a read stops at a Record. - waits_forever = bool(wait) and not closed - stop_at = rng.randrange(1, records + 1) if records else 0 + [reads] = fake + wait = rng.choice([None, timedelta(0), timedelta(seconds=5)]) got: list[int] = [] - first = stream.read(wait=wait) - if stop_at: - async for record in first: + for _ in range(rng.randrange(1, 4)): + # More Records come after each read, and a reader picks up where it stopped. + reads.records += rng.randrange(6) + offset = got[-1].to_bytes(8, "big") if got else None + stop_at = rng.choice([None, *range(len(got) + 1, reads.records + 1)]) + first_read = len(reads.starts) + async for record in stream.read(from_offset=offset, wait=wait): got.append(record.body) if len(got) == stop_at: break - assert got == list(range(1, stop_at + 1)) - if waits_forever: - assert first.next_request is not None - return - resumed = first.next_request - if resumed is not None: - rest = stream.read( - from_offset=resumed.from_offset, - max_records=resumed.max_records, - wait=resumed.wait, - max_bytes=resumed.max_bytes, - ) - got.extend([record.body async for record in rest]) - assert rest.next_request is None - assert got == list(range(1, records + 1)) + assert got == list(range(1, len(got) + 1)) + if stop_at is not None and len(got) == stop_at: + # The read stops at the caller's last Record, so no read starts after it. + assert all(start < stop_at for start in reads.starts[first_read:]) + else: + # Each read stops at its first page with no Record, which a read with no + # wait gives only at the end. + assert reads.starts[-1] == len(got) + if not wait: + assert len(got) == reads.records @dataclasses.dataclass(frozen=True) diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py index e191d89897..4d6c5058b5 100644 --- a/tests/nexus/test_streams_with_worker.py +++ b/tests/nexus/test_streams_with_worker.py @@ -309,14 +309,16 @@ async def test_a_store_error_is_the_same_error_on_every_path(client: Client) -> appends = store.faults["append_records"] unavailable = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE - async def answers_on(path: str, calls: list[list[Any]], **options: Any) -> Any: + async def answers_on( + path: str, calls: list[list[Any]], on: Client = client, **options: Any + ) -> Any: if path == "client": - return await _answers(client, calls) + return await _answers(on, calls) args = [calls, path == "activity"] run_options = RunOptions( _CallsWorkflow, args, activities=[_calls_activity], **options ) - return (await run(client, run_options)).result + return (await run(on, run_options)).result def append_request_ids() -> list[str | None]: calls, store.calls = store.calls, [] @@ -379,6 +381,19 @@ def append_request_ids() -> list[str | None]: with failure_note(path): assert await answers_on(path, calls, cached=False, replay=True) == refused + # When its Retention has passed since its last append, a Stream refuses each call + # as expired, on each path. + expiring = stream_client(client, FaultStore(retention=timedelta(seconds=2))) + stream = await expiring.create_stream(id="expires", body_type=int) + await stream.append(1) + await asyncio.sleep(2.5) + expired = StreamErrorReason.STREAM_ERROR_REASON_EXPIRED + calls = [["append", "expires", [2]], ["describe", "expires"], ["read", "expires"]] + for path in ("client", "activity", "workflow"): + with failure_note(f"expired, {path}"): + answered = await answers_on(path, calls, on=expiring, replay=True) + assert [answer[:2] for answer in answered] == [["error", expired]] * 3 + # An outage during a create fails the Workflow Task, also on a Worker that fails a # Workflow for any exception. The create runs in the next task, with the Store back. for failure_types in ([], [Exception]): diff --git a/tests/testing/test_stream_store.py b/tests/testing/test_stream_store.py index 6cf93144f6..a97233acc0 100644 --- a/tests/testing/test_stream_store.py +++ b/tests/testing/test_stream_store.py @@ -25,14 +25,11 @@ LocalActivityAttempt, Producer, StreamRecord, - StreamRef, WorkflowTaskAttempt, ) from temporalio.api.streamservice.v1 import ( AppendRecordsRequest, AppendRecordsResponse, - CloseStreamRequest, - CloseStreamResponse, CreateStreamRequest, CreateStreamResponse, DescribeStreamRequest, @@ -50,7 +47,6 @@ _NOT_FOUND = StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND _EXPIRED = StreamErrorReason.STREAM_ERROR_REASON_EXPIRED -_CLOSED = StreamErrorReason.STREAM_ERROR_REASON_CLOSED _FENCED = StreamErrorReason.STREAM_ERROR_REASON_FENCED # Attempts of each attempt message, earliest first. Where a later attempt wins by one field, @@ -137,7 +133,6 @@ class _ModelBatch: @dataclass class _ModelStream: request_id: str - closed: bool = False records: list[StreamRecord] = field(default_factory=list) batches: list[_ModelBatch] = field(default_factory=list) @@ -157,17 +152,15 @@ class _Model: streams: dict[str, _ModelStream] = field(default_factory=dict) def create(self, request: CreateStreamRequest, request_id: str) -> Any: - stream = self.streams.get(request.stream_ref.id) + stream = self.streams.get(request.stream_id) if stream is None: - self.streams[request.stream_ref.id] = _ModelStream(request_id) - return CreateStreamResponse(ref=request.stream_ref, created=True) - if stream.closed: - return _CLOSED + self.streams[request.stream_id] = _ModelStream(request_id) + return CreateStreamResponse(created=True) if request_id and request_id == stream.request_id: - return CreateStreamResponse(ref=request.stream_ref, created=True) + return CreateStreamResponse(created=True) use_existing = StreamIdConflictPolicy.STREAM_ID_CONFLICT_POLICY_USE_EXISTING if request.id_conflict_policy == use_existing: - return CreateStreamResponse(ref=request.stream_ref) + return CreateStreamResponse() return StreamErrorReason.STREAM_ERROR_REASON_ALREADY_EXISTS def append( @@ -176,7 +169,7 @@ def append( # SDK Core refuses a batch with no Record before the Store gets it. if not request.records: return StreamErrorReason.STREAM_ERROR_REASON_INVALID_ARGUMENT - stream = self.streams.get(request.ref.id) + 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] @@ -188,8 +181,6 @@ def append( return batch.response if self.fence and stream.fenced(writer): return _FENCED - if stream.closed: - return _CLOSED response = AppendRecordsResponse() for record in request.records: offset = (len(stream.records) + 1).to_bytes(8, "big") @@ -201,17 +192,8 @@ def append( stream.batches.append(_ModelBatch(writer, request_id, response)) return response - def close(self, request: CloseStreamRequest, writer: _Writer) -> Any: - stream = self.streams.get(request.ref.id) - if stream is None: - return _NOT_FOUND - if not stream.closed and self.fence and stream.fenced(writer): - return _FENCED - stream.closed = True - return CloseStreamResponse() - def read(self, request: ReadRecordsRequest) -> Any: - stream = self.streams.get(request.ref.id) + stream = self.streams.get(request.stream_id) if stream is None: return _NOT_FOUND start = int.from_bytes(request.from_offset, "big") @@ -221,12 +203,11 @@ def read(self, request: ReadRecordsRequest) -> Any: return ReadRecordsResponse( records=records, last_offset=records[-1].offset if records else request.from_offset, - done=stream.closed and start + len(records) == len(stream.records), ) -_OPERATIONS = ["create", "append", "again", "close", "read"] -_WEIGHTS = [3, 10, 6, 1, 4] +_OPERATIONS = ["create", "append", "again", "read"] +_WEIGHTS = [3, 10, 6, 4] async def _answer(call: Awaitable[Message]) -> Any: @@ -255,7 +236,7 @@ async def _store_script(rng: random.Random, runtime: Runtime | None) -> None: appends: list[tuple[AppendRecordsRequest, _Writer, str]] = [] writers: list[_Writer] = [] for step in range(50): - ref = StreamRef(id=rng.choice("xy"), store=rng.choice(["", "memory"])) + 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 @@ -265,7 +246,7 @@ async def _store_script(rng: random.Random, runtime: Runtime | None) -> None: match rng.choices(_OPERATIONS, _WEIGHTS)[0]: case "create": request = CreateStreamRequest( - stream_ref=ref, + stream_id=stream_id, id_conflict_policy=rng.choice( list(StreamIdConflictPolicy.values()) ), @@ -276,7 +257,9 @@ async def _store_script(rng: random.Random, runtime: Runtime | None) -> None: store.create_stream(request, request_id=request_id) ) case "append" | "again" as op: - request = AppendRecordsRequest(ref=ref, producer=writer.producer) + 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 @@ -292,13 +275,9 @@ async def _store_script(rng: random.Random, runtime: Runtime | None) -> None: answer = await _answer( store.append_records(request, request_id=request_id) ) - case "close": - request = CloseStreamRequest(ref=ref, producer=writer.producer) - expected = model.close(request, writer) - answer = await _answer(store.close_stream(request)) case _: request = ReadRecordsRequest( - ref=ref, + stream_id=stream_id, from_offset=rng.choice( [b"", *(i.to_bytes(8, "big") for i in range(1, 9))] ), @@ -309,74 +288,64 @@ async def _store_script(rng: random.Random, runtime: Runtime | None) -> None: assert answer == expected, f"step {step}: {request}" -def _streams(retention: int = 1, idle_ttl: int | None = None) -> _MemoryStreams: +def _streams(retention: int = 1) -> _MemoryStreams: return _MemoryStreams( - "memory", - retention=timedelta(seconds=retention), - producer_idle_ttl=None if idle_ttl is None else timedelta(seconds=idle_ttl), - resend_window=1, - fence=False, + "memory", retention=timedelta(seconds=retention), resend_window=1, fence=False ) -_S = StreamRef(id="s") +_S = "s" def _client_append() -> AppendRecordsRequest: - request = AppendRecordsRequest(ref=_S, records=[AppendRecord()]) - request.producer.client.SetInParent() - return request - - -def _client_close() -> CloseStreamRequest: - request = CloseStreamRequest(ref=_S) + request = AppendRecordsRequest(stream_id=_S, records=[AppendRecord()]) request.producer.client.SetInParent() return request -def test_a_stream_expires_after_its_retention_or_its_idle_ttl() -> None: +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, idle_ttl = rng.randrange(1, 50), rng.choice([None, 10, 30]) - streams = _streams(retention, idle_ttl) - await streams.create_stream(CreateStreamRequest(stream_ref=_S), request_id="") - closed = False - expires_at = None if idle_ttl is None else loop.time() + idle_ttl + 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 = expires_at is not None and loop.time() >= expires_at - match rng.choice( - ["append", "append", "close", "read", "describe", "create"] - ): + expired = loop.time() >= expires_at + match rng.choice(["append", "append", "read", "describe", "create"]): case "append": - append = streams.append_records(_client_append(), request_id="") + request_id = rng.choice(["", "r"]) + append = streams.append_records( + _client_append(), request_id=request_id + ) answer = await _answer(append) - expected: Any = _CLOSED if closed else AppendRecordsResponse - if not expired and not closed and idle_ttl is not None: - expires_at = loop.time() + idle_ttl - case "close": - answer = await _answer(streams.close_stream(_client_close())) - expected = CloseStreamResponse - if not expired and not closed: - closed, expires_at = True, loop.time() + retention + 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(ref=_S) + read = ReadRecordsRequest(stream_id=_S) answer = await _answer(streams.read_records(read)) expected = ReadRecordsResponse case "describe": - describe = DescribeStreamRequest(ref=_S) + describe = DescribeStreamRequest(stream_id=_S) answer = await _answer(streams.describe_stream(describe)) expected = DescribeStreamResponse case _: - create = streams.create_stream( - CreateStreamRequest(stream_ref=_S), request_id="other" + use_existing = ( + StreamIdConflictPolicy.STREAM_ID_CONFLICT_POLICY_USE_EXISTING + ) + create = CreateStreamRequest( + stream_id=_S, id_conflict_policy=use_existing ) - answer = await _answer(create) - expected = ( - _CLOSED - if closed - else StreamErrorReason.STREAM_ERROR_REASON_ALREADY_EXISTS + 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, ( @@ -391,15 +360,15 @@ async def script(rng: random.Random) -> None: def test_a_read_waits_for_the_next_write_or_for_its_wait() -> None: async def script(rng: random.Random) -> None: loop = asyncio.get_running_loop() - streams = _streams() - await streams.create_stream(CreateStreamRequest(stream_ref=_S), request_id="") + streams = _streams(retention=100) + await streams.create_stream(CreateStreamRequest(stream_id=_S), request_id="") first = await streams.append_records(_client_append(), request_id="") wait, write_in = rng.sample(range(1, 60), 2) - write = rng.choice(["append", "close", None]) + write = rng.random() < 0.5 read = asyncio.ensure_future( streams.read_records( ReadRecordsRequest( - ref=_S, + stream_id=_S, from_offset=first.last_offset, wait=Duration(seconds=wait), ) @@ -408,16 +377,15 @@ async def script(rng: random.Random) -> None: answered_at: list[float] = [] read.add_done_callback(lambda _: answered_at.append(loop.time())) await asyncio.sleep(write_in) - if write == "append": + if write: await streams.append_records(_client_append(), request_id="") - elif write == "close": - await streams.close_stream(_client_close()) page = await read - in_time = write is not None and write_in < wait + in_time = write and write_in < wait assert ( answered_at == [float(write_in if in_time else wait)] - and len(page.records) == (in_time and write == "append") - and page.done == (in_time and write == "close") + and len(page.records) == in_time + and page.last_offset + == (page.records[-1].offset if in_time else first.last_offset) ), f"{page} at {answered_at}" for seed in range(200): @@ -445,7 +413,7 @@ def store() -> MemoryStreamStore: def on_task(_task: asyncio.Task[Any]) -> None: raise asyncio.CancelledError - request = DescribeStreamRequest(ref=_S).SerializeToString() + request = DescribeStreamRequest(stream_id=_S).SerializeToString() with pytest.raises(asyncio.CancelledError): await _StoreCaller(store).call("DescribeStream", request, None, on_task) assert not asked From 611e470fef3c11ec990c63342977c40a9cfe0ccd Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Wed, 25 Nov 2026 12:40:25 -0700 Subject: [PATCH 25/50] Choose the Store of a Workflow Stream call before Core Workflow code gets the Store of each call before any command or Local Activity, also in a replay, and the Store starts the call through an internal hook. Its default sends a Core command for an append or a read, and runs the Local Activity with the chosen Store for a create or a describe. Only a ref with no Store name asks the selector. --- changelog/added/steady-stream-heron.md | 2 +- temporalio/client/_stream_store.py | 63 ++++- temporalio/worker/_command_aware_visitor.py | 6 - temporalio/worker/_replayer.py | 12 +- temporalio/worker/_workflow_instance.py | 2 - temporalio/worker/_workflow_streams.py | 257 +++++++++--------- tests/nexus/test_streams_with_worker.py | 275 +++++++++----------- tests/worker/test_workflow_streams.py | 241 ++++++++++++----- 8 files changed, 466 insertions(+), 392 deletions(-) diff --git a/changelog/added/steady-stream-heron.md b/changelog/added/steady-stream-heron.md index 8ab949fcc4..e25fdfe107 100644 --- a/changelog/added/steady-stream-heron.md +++ b/changelog/added/steady-stream-heron.md @@ -1,5 +1,5 @@ Add experimental `temporalio.client.StreamStore`, the base class of a Stream Store, and `temporalio.testing.MemoryStreamStore`, a Store that keeps its Streams in memory for tests and local runs. A Store gets the requests of `temporalio.api.streamservice.v1`, which have the Stream id, and the request id of each create and each append as `request_id`. A create returns only `created`, and the SDK gives the caller the ref with the name of the Store. A Stream has no close, and it expires when the Retention of its Store has passed since its create or its last append that wrote a batch. Add experimental Streams for client and Activity code. `stream_config=StreamConfig(stores=[...])` of `Client.connect` gives a client its Stream Stores, and `Client.create_stream` and `Client.get_stream` return a `Stream` to append to, read and describe. A failed call raises `temporalio.exceptions.StreamError` with a `reason`. `max_record_bytes`, `max_batch_bytes` and `max_batch_records` of `StreamConfig` bound an append, and one over a limit fails before its Store gets it. A read of a Stream from `get_stream` needs `body_type=` or a `StreamRef` with a type argument, and raises `TypeError` with neither. `Stream.read` stops at the first page with no Record, so a read with no wait reads to the newest Record, and a read with a wait stops once no Record came within the wait. `temporalio.contrib.streams.current_producer` gives the Producer of an Activity attempt, and `as_producer` gives back one that code stored. -Add experimental Streams for Workflow code. `workflow.create_stream` and `workflow.get_stream` return a `Stream` to append to, read and describe on the Stream Stores of the Worker's client, and `Replayer(stream_config=...)` gives a replay its Stores. The SDK chooses the Store of each call before the call starts, also in a replay. +Add experimental Streams for Workflow code. `workflow.create_stream` and `workflow.get_stream` return a `Stream` to append to, read and describe on the Stream Stores of the Worker's client, and `Replayer(stream_config=...)` gives a replay its Stores. The SDK chooses the Store of each call before the call starts, also in a replay. It calls the `store_selector` only for a ref with no Store name, in Workflow code for each such call, also for a create and a describe, and again in a replay. So the selector must return the same Store for the same call, must not block or do I/O, and must be safe to call from more than one thread. Add experimental Stream reads for Workflow code. `Stream.read`, `read_pages` and `read_page` of a Workflow `Stream` give the Records as they come, a replay reads them again from the Store, and `temporalio.workflow.StreamReplayError` in the failure exception types of a Worker or a Workflow fails the Workflow when the Store no longer has them. The Worker option `stream_read_time` sets how long the reads of a Workflow Task can wait, and a read with a wait gives a page with no Record at that limit. Add experimental `temporalio.contrib.streams.BufferedAppender`, which batches the appends of one Stream in client and Activity code. `append` returns immediately, a batch waits at most `max_delay`, one write runs at a time, and `async with` or `flush()` writes what is left. diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index db764f294d..4f7e1e70d5 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -7,9 +7,9 @@ import uuid from abc import ABC, abstractmethod from collections.abc import Callable, Sequence -from dataclasses import dataclass +from dataclasses import dataclass, field from datetime import timedelta -from typing import Any +from typing import TYPE_CHECKING, Any import google.protobuf.message import nexusrpc @@ -42,6 +42,9 @@ from temporalio.exceptions import StreamError from temporalio.nexus.system.stream_service import StreamService +if TYPE_CHECKING: + import temporalio.worker._workflow_streams + logger = logging.getLogger(__name__) _definition = nexusrpc.get_service_definition(StreamService) @@ -126,8 +129,9 @@ class StreamStore(ABC): @abstractmethod def name(self) -> str: """Return the name that a :py:class:`StreamConfig` registers this Store - under. A Store may take its name as an argument, so that two instances of - one Store class can be in one config. + under. It must return the same name every time. A Store may take its name + as an argument, so that two instances of one Store class can be in one + config. """ raise NotImplementedError @@ -209,6 +213,26 @@ async def describe_stream( """ raise NotImplementedError + def _start_workflow_call( + self, + streams: temporalio.worker._workflow_streams._WorkflowStreams, + operation: str, + request: google.protobuf.message.Message, + result_type: Any, + ) -> asyncio.Future[Any]: + """Start a Stream call of Workflow code on this Store, and return the + future of its result. + + ``request`` is the SDK request of the call, with its ref, and + ``result_type`` is the type of the call's result. The SDK calls this in the + event loop of the Workflow, once per call, after it chose this Store and + before any command of the call. A replay calls it again, so it must take + the path of the first run for the same call. The default makes an append + or a read a command of SDK Core, and runs a create or a describe in a + Local Activity of the SDK. + """ + return streams._start_by_default(self, operation, request, result_type) + @dataclass(frozen=True) class StreamSelectContext: @@ -299,9 +323,12 @@ class StreamConfig: Required when more than one Store is registered. When ``None``, the one Store takes each such call. - A Workflow replay calls the selector again, so it must return the same Store - for the same call. A created Stream has the name of its Store in its ref, so - its calls don't depend on the selector. + The SDK calls the selector only for a ref with no Store name. In Workflow + code it calls it for each such Stream call, also for a create and a + describe, and again in a replay. So the selector must return the same Store + for the same call, must not block or do I/O, and must be safe to call from + more than one thread. A created Stream has the name of its Store in its ref, + so its calls don't depend on the selector. """ max_record_bytes: int = 1536 * 1024 @@ -321,6 +348,13 @@ class StreamConfig: greater than or equal to one. """ + _by_name: dict[str, StreamStore] = field( + init=False, repr=False, compare=False, default_factory=dict + ) + """Each Store of :py:attr:`stores` by its name. :py:meth:`__post_init__` + fills it once, so a Store that changes its name later can't change a lookup. + """ + def __post_init__(self) -> None: """Validate the Stores and the limits. @@ -341,26 +375,27 @@ def __post_init__(self) -> None: "StreamConfig.store_selector must be specified if multiple Stores " "are registered." ) - names: set[str] = set() + 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 names: + if name in by_name: raise ValueError( f"StreamConfig.stores contains multiple Stores with name '{name}'. " "Each Store must have a unique name." ) - names.add(name) + by_name[name] = store + object.__setattr__(self, "_by_name", by_name) def _store(self, name: str) -> StreamStore: """Return the Store with a name, raising :class:`ValueError` if none has it.""" - for store in self.stores: - if store.name() == name: - return store - raise ValueError(f"No Stream Store found with name '{name}'") + store = self._by_name.get(name) + if store is None: + raise ValueError(f"No Stream Store found with name '{name}'") + return store def _store_for( self, diff --git a/temporalio/worker/_command_aware_visitor.py b/temporalio/worker/_command_aware_visitor.py index 16ae76ec3e..68f4459011 100644 --- a/temporalio/worker/_command_aware_visitor.py +++ b/temporalio/worker/_command_aware_visitor.py @@ -18,7 +18,6 @@ ResolveRequestCancelExternalWorkflow, ResolveSignalExternalWorkflow, ResolveStreamAppend, - ResolveStreamClose, ResolveStreamRead, ) from temporalio.bridge.proto.workflow_commands.workflow_commands_pb2 import ( @@ -235,11 +234,6 @@ async def _visit_coresdk_workflow_activation_ResolveStreamAppend( ) -> None: pass - async def _visit_coresdk_workflow_activation_ResolveStreamClose( - self, fs: VisitorFunctions, o: ResolveStreamClose - ) -> None: - pass - async def _visit_stream_payloads( self, fs: VisitorFunctions, seq: int, payloads: Iterable[Payload] ) -> None: diff --git a/temporalio/worker/_replayer.py b/temporalio/worker/_replayer.py index d6072352ef..edb89d59c0 100644 --- a/temporalio/worker/_replayer.py +++ b/temporalio/worker/_replayer.py @@ -74,10 +74,14 @@ def __init__( Users are encouraged to provide their own if needing more control. ``stream_config`` is the Stream config of the client that the worker - used. A replay takes the result of each append, close, create and - describe of a Stream from history, so it calls no Store for them. It - reads the Records of each Stream read again from the Store, and fails if - the Store no longer has them. + used. A replay chooses the Store of each Stream call again, so a + Workflow with Stream calls needs a config with the same Store names and + the same selector. A replay takes the result of each append, create and + describe of a Stream from history, so it calls no Store for them, and a + Store of the same name, for example a + :py:class:`temporalio.testing.MemoryStreamStore`, can stand in. It reads + the Records of each Stream read again from the Store, and fails if the + Store no longer has them. """ self._config = ReplayerConfig( workflows=list(workflows), diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index 847cfb8a98..033d981e29 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -711,8 +711,6 @@ def _apply( ) elif job.HasField("resolve_stream_append"): self._streams.resolve_append(job.resolve_stream_append) - elif job.HasField("resolve_stream_close"): - self._streams.resolve_close(job.resolve_stream_close) elif job.HasField("resolve_stream_read"): self._streams.resolve_read(job.resolve_stream_read) elif job.HasField("signal_workflow"): diff --git a/temporalio/worker/_workflow_streams.py b/temporalio/worker/_workflow_streams.py index 2a7f623de4..9cb98f2700 100644 --- a/temporalio/worker/_workflow_streams.py +++ b/temporalio/worker/_workflow_streams.py @@ -16,6 +16,7 @@ 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 @@ -30,8 +31,8 @@ StreamConfig, StreamStore, _call_store, - _operation, _request_ref, + _sdk_request_type, _StoreCaller, ) from temporalio.converter import StorageDriverWorkflowInfo @@ -59,16 +60,16 @@ class _Read: class _WorkflowStreams: # pyright: ignore[reportUnusedClass] """The Stream calls of one Workflow instance. - An append, a close and a read are commands of SDK Core, which makes the Store - calls and gives each result in a job. Core has no command for a create or a - describe, so those run in a Local Activity of the SDK. + Each call first gets its Store, and the Store starts the call. By default an + append and a read are commands of SDK Core, which makes the Store calls and + gives each result in a job. Core has no command for a create or a describe, so + those run in a Local Activity of the SDK. """ def __init__(self, instance: _WorkflowInstanceImpl) -> None: self._instance = instance - # Each append and close whose job hasn't come, by seq + # Each append whose job hasn't come, by seq self._appends: dict[int, asyncio.Future[Any]] = {} - self._closes: dict[int, asyncio.Future[Any]] = {} self.task_error: Exception | None = None """The error of a call that must fail the Workflow Task, if one came.""" # Each read whose job hasn't come, by seq. A cancelled read gets its one job too. @@ -81,8 +82,8 @@ def start( The command of the call is added before this returns, so commands are in the order of the calls. Cancelling the handle ends its wait immediately. - Core can't stop an append, a close or a read, so those still run, and the - job that still comes for the call is dropped. + Core can't stop an append or a read, so those still run, and the job that + still comes for the call is dropped. """ instance = self._instance instance._assert_not_read_only("start a Stream call") @@ -95,60 +96,25 @@ def start( # The terminal of each Stream operation gives its output type. result_type: Any = input.output_type request = temporalio.nexus.system._support.model_to_proto(model, *converters) - # The future of the job of the call, or the task of its Local Activity - result: asyncio.Future[Any] - if isinstance(request, proto.AppendRecordsRequest): - stream = self._stream(request.ref) - 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 = self._appends[seq] = instance.create_future() - elif isinstance(request, proto.CloseStreamRequest): - stream = self._stream(request.ref) - seq = instance._next_seq("stream_close") - close = instance._add_command().close_stream - close.seq = seq - close.stream.CopyFrom(stream) - result = self._closes[seq] = instance.create_future() - elif isinstance(request, proto.ReadRecordsRequest): - # The converter refuses a body of no type, and the job of the page would - # then fail the Workflow Task. - if typing.get_args(result_type) == (object,): - raise TypeError( - "Cannot read a Stream with no body type. Give get_stream a " - "body_type, or a StreamRef with a type argument." - ) - stream = self._stream(request.ref) - seq = instance._next_seq("stream_read") - instance._add_command().read_stream.CopyFrom( - temporalio.bridge.proto.workflow_commands.ReadStream( - seq=seq, - stream=stream, - from_offset=request.from_offset, - wait=request.wait if request.HasField("wait") else None, - max_records=request.max_records, - max_bytes=request.max_bytes, - ) + # The converter refuses a body of no type, and the job of the page would then + # fail the Workflow Task. + if isinstance(request, sdk.ReadRecordsRequest) and typing.get_args( + result_type + ) == (object,): + raise TypeError( + "Cannot read a Stream with no body type. Give get_stream a " + "body_type, or a StreamRef with a type argument." ) - result = instance.create_future() - self._reads[seq] = _Read(result, result_type) - else: - # The Local Activity picks the Store of a ref with no Store name. A replay - # has its result, so a replay asks no selector for it. Each run of a chain - # sends the same id, so a Store answers the create of a later run as the - # create that made the Stream. - request_id = None - if isinstance(request, proto.CreateStreamRequest): - request_id = instance._info.first_execution_run_id - result = self._schedule_store_call(operation, request, request_id) + # The future of the job of the call, or the task of its Local Activity + result = self._store(_request_ref(request))._start_workflow_call( + self, operation, request, result_type + ) 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]) - if isinstance(request, proto.ReadRecordsRequest): + if isinstance(request, sdk.ReadRecordsRequest): return result.result() return temporalio.nexus.system._support.model_from_proto( self._response(operation, request, result), @@ -166,15 +132,86 @@ def stop(_: asyncio.Task[OutputT]) -> None: task.add_done_callback(stop) return _StreamCall(task) + def _store(self, ref: sdk.StreamRef) -> StreamStore: + """Return the Store of a call on ``ref``, from the Stream config of the + Worker's client. A call with no Store fails the Workflow Task. + """ + 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." + ) + ) + info = self._instance._info + target = StorageDriverWorkflowInfo( + id=info.workflow_id, + run_id=info.run_id, + type=info.workflow_type, + namespace=info.namespace, + ) + try: + return config._store_for(ref, target, info.namespace) + except Exception as err: + raise self._fail_task(err) + + def _start_by_default( + self, + store: StreamStore, + operation: str, + request: google.protobuf.message.Message, + result_type: Any, + ) -> asyncio.Future[Any]: + """Start a call on ``store`` as a command of SDK Core, or in the SDK's + Local Activity for a create or a describe. This is the default of + :py:meth:`StreamStore._start_workflow_call`. + """ + instance = self._instance + stream = sdk.StreamRef(id=_request_ref(request).id, store=store.name()) + 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 = self._appends[seq] = instance.create_future() + return result + if isinstance(request, sdk.ReadRecordsRequest): + seq = instance._next_seq("stream_read") + instance._add_command().read_stream.CopyFrom( + temporalio.bridge.proto.workflow_commands.ReadStream( + seq=seq, + stream=stream, + from_offset=request.from_offset, + wait=request.wait if request.HasField("wait") else None, + max_records=request.max_records, + max_bytes=request.max_bytes, + ) + ) + result = instance.create_future() + self._reads[seq] = _Read(result, result_type) + return result + # Each run of a chain sends the same id, so a Store answers the create of a + # later run as the create that made the Stream. + request_id = None + if isinstance(request, sdk.CreateStreamRequest): + request_id = instance._info.first_execution_run_id + return self._schedule_store_call(store, operation, request, request_id) + def resolve_append( self, job: temporalio.bridge.proto.workflow_activation.ResolveStreamAppend ) -> None: - self._resolve(self._appends, job.seq, job.appended, job) - - def resolve_close( - self, job: temporalio.bridge.proto.workflow_activation.ResolveStreamClose - ) -> None: - self._resolve(self._closes, job.seq, None, job) + future = self._appends.pop(job.seq, None) + if future is None: + raise RuntimeError(f"Failed finding Stream append for sequence {job.seq}") + # A cancelled call waits no more, and Core still gives the result of its write. + if future.done(): + return + if job.HasField("failed"): + future.set_exception(self._error(job.failed)) + else: + future.set_result(job.appended) def resolve_read( self, job: temporalio.bridge.proto.workflow_activation.ResolveStreamRead @@ -189,9 +226,7 @@ def resolve_read( read.waiter.set_exception(self._error(job.failed)) return page = proto.ReadRecordsResponse( - records=job.page.records, - last_offset=job.page.last_offset, - done=job.page.done, + records=job.page.records, last_offset=job.page.last_offset ) # A body that the converter refuses fails the Workflow Task, as a result of a # Local Activity does. @@ -204,24 +239,6 @@ def resolve_read( ) ) - def _resolve( - self, - calls: dict[int, asyncio.Future[Any]], - seq: int, - result: Any, - job: Any, - ) -> None: - future = calls.pop(seq, None) - if future is None: - raise RuntimeError(f"Failed finding Stream call for sequence {seq}") - # A cancelled call no longer waits, and Core still gives the result of its write. - if future.done(): - return - if job.HasField("failed"): - future.set_exception(self._error(job.failed)) - else: - future.set_result(result) - def _error(self, failure: temporalio.api.failure.v1.Failure) -> BaseException: instance = self._instance return _stream_error_from_failure(failure) or ( @@ -232,25 +249,19 @@ def _error(self, failure: temporalio.api.failure.v1.Failure) -> BaseException: def _schedule_store_call( self, + store: StreamStore, operation: str, request: google.protobuf.message.Message, request_id: str | None, ) -> asyncio.Future[Any]: - """Schedule the SDK's Local Activity for a create or a describe.""" + """Schedule the SDK's Local Activity for a create or a describe on + ``store``. + """ instance = self._instance - # A Worker whose client has no Stream config has no such Local Activity, so the - # call would wait with no end. A replay takes the result from History. - if not instance._is_replaying and self._stream_config() is None: - raise self._fail_task( - ValueError( - "Client of this Worker has no stream_config, which every " - "Stream call requires." - ) - ) activity = instance._outbound.start_local_activity( StartLocalActivityInput( activity=_STORE_CALL_ACTIVITY, - args=(operation, request.SerializeToString(), request_id), + args=(operation, store.name(), 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. @@ -277,14 +288,11 @@ def _response( result: asyncio.Future[Any], ) -> google.protobuf.message.Message: """Return the response message of a call whose ``result`` is done.""" - if isinstance(request, proto.AppendRecordsRequest): + if isinstance(request, sdk.AppendRecordsRequest): appended = result.result() return proto.AppendRecordsResponse( first_offset=appended.first_offset, last_offset=appended.last_offset ) - if isinstance(request, proto.CloseStreamRequest): - result.result() - return proto.CloseStreamResponse() try: answer = result.result() except temporalio.exceptions.FailureError as err: @@ -304,34 +312,10 @@ def _response( raise error from err # The ref of a create has the Store name of History, so a replay gives the same # ref under any Stream config. - if isinstance(request, proto.CreateStreamRequest): - return proto.CreateStreamResponse.FromString(answer) + if isinstance(request, sdk.CreateStreamRequest): + return sdk.CreateStreamResponse.FromString(answer) return proto.DescribeStreamResponse.FromString(answer) - def _stream( - self, ref: temporalio.api.stream.v1.StreamRef - ) -> temporalio.api.stream.v1.StreamRef: - """Return the ref of a command, with the name of the Store that SDK Core calls. - - A ref with no Store name gets the Store that the config of the Worker's - client picks, and an empty name if that client has no Stream config. - """ - store = ref.store - config = self._stream_config() - if config and not store: - info = self._instance._info - target = StorageDriverWorkflowInfo( - id=info.workflow_id, - run_id=info.run_id, - type=info.workflow_type, - namespace=info.namespace, - ) - try: - store = config._store_for(ref, target, info.namespace).name() - except Exception as err: - raise self._fail_task(err) - return temporalio.api.stream.v1.StreamRef(id=ref.id, store=store) - def _fail_task(self, error: Exception) -> Exception: """Make ``error`` the failure of the Workflow Task and return it. @@ -368,10 +352,12 @@ def cancel(self) -> bool: @temporalio.activity.defn(name=_STORE_CALL_ACTIVITY) async def _stream_store_call( # pyright: ignore[reportUnusedFunction] - operation: str, request: bytes, request_id: str | None + operation: str, store: str, request: bytes, request_id: str | None ) -> bytes: - """Call a Stream Store of the Worker's client for a create or a describe of - Workflow code. ``request_id`` is that of a create, and ``None`` for a describe. + """Call the Stream Store named ``store`` of the Worker's client for a create + or a describe of Workflow code, which chose that Store. ``request`` is the + encoded SDK request. ``request_id`` is that of a create, and ``None`` for a + describe. Returns the encoded response. The ref of a create's response has the name of the Store that it called, so History has the Store of the created Stream. @@ -387,20 +373,9 @@ async def _stream_store_call( # pyright: ignore[reportUnusedFunction] stream_config = client._config["stream_config"] if stream_config is None: raise ValueError("Client of this Worker has no stream_config.") - _, request_type, _ = _operation(operation) - stream_request: Any = request_type.FromString(request) - # The selector gets the Workflow as its target, as for an append of that Workflow. - target = StorageDriverWorkflowInfo( - id=info.workflow_id, - run_id=info.workflow_run_id, - type=info.workflow_type, - namespace=info.namespace, - ) - picked = stream_config._store_for( - _request_ref(stream_request), target, client.namespace - ) + stream_request = _sdk_request_type(operation).FromString(request) response = await _call_store( - picked, + stream_config._store(store), stream_config._limits(), client.data_converter.payload_codec, operation, @@ -450,7 +425,7 @@ def _for_core( """ if stream_config is None: return set(), None - return {store.name() for store in stream_config.stores}, stream_config._limits() + return set(stream_config._by_name), stream_config._limits() def _bridge_streams( # pyright: ignore[reportUnusedFunction] diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py index 4d6c5058b5..bdaab7a369 100644 --- a/tests/nexus/test_streams_with_worker.py +++ b/tests/nexus/test_streams_with_worker.py @@ -14,14 +14,11 @@ from temporalio import activity, workflow from temporalio.api.enums.v1 import EventType, StreamErrorReason, TaskQueueType -from temporalio.api.sdk.v1 import WorkflowTaskStreamCalls from temporalio.api.sdk.v1.external_storage_pb2 import ExternalStorageReference -from temporalio.api.stream.v1 import StreamRef as RefProto from temporalio.api.streamservice.v1 import ( AppendRecordsRequest, - CloseStreamResponse, CreateStreamRequest, - CreateStreamResponse, + DescribeStreamResponse, ReadRecordsRequest, ) from temporalio.api.taskqueue.v1 import TaskQueue @@ -32,11 +29,7 @@ ExternalStorage, ) from temporalio.exceptions import ApplicationError, StreamError -from temporalio.nexus.system.stream_service import ( - StreamIdConflictPolicy, - StreamRef, - StreamStatus, -) +from temporalio.nexus.system.stream_service import StreamIdConflictPolicy, StreamRef from temporalio.testing import MemoryStreamStore from temporalio.worker import ( ActivityInboundInterceptor, @@ -87,16 +80,13 @@ async def _answers( answers.append( [appended.first_offset.hex(), appended.last_offset.hex()] ) - elif operation == "close": - await stream.close() - answers.append("closed") elif operation == "read": page = await stream.read_page() bodies = [record.body for record in page.records] - answers.append([bodies, (page.last_offset or b"").hex(), page.done]) + answers.append([bodies, (page.last_offset or b"").hex()]) else: described = await stream.describe() - answers.append([described.status, (described.last_offset or b"").hex()]) + answers.append([(described.last_offset or b"").hex()]) except StreamError as err: answers.append(["error", err.reason, err.message]) return answers @@ -120,8 +110,7 @@ async def run(self, calls: list[list[Any]], in_activity: bool = False) -> list[A def _writes(store: FaultStore) -> list[Message]: """Return each request of a Store but its reads, which Core pages in its own way, - without what differs between two writers of the same call. That is the Producer, - and the Store name of the ref, which Workflow code fills in for a ref with none. + without the Producer, which differs between two writers of the same call. """ writes: list[Message] = [] for request in store.requests: @@ -131,8 +120,6 @@ def _writes(store: FaultStore) -> list[Message]: copy.CopyFrom(request) if "producer" in copy.DESCRIPTOR.fields_by_name: copy.ClearField("producer") - ref = copy.stream_ref if isinstance(copy, CreateStreamRequest) else copy.ref - ref.ClearField("store") writes.append(copy) return writes @@ -146,8 +133,7 @@ async def test_workflow_code_and_a_client_get_the_same_answers(client: Client) - calls: list[list[Any]] = [ ["create", f"s-{seed}-{number}", rng.randrange(3)] for number in (0, 1) ] - operations = ["append", "append", "append", "close", "describe"] - # A replay needs a Store only for a read, so every other script has none. + operations = ["append", "append", "append", "describe"] reads = seed % 2 == 1 if reads: operations += ["read", "read"] @@ -161,9 +147,7 @@ async def test_workflow_code_and_a_client_get_the_same_answers(client: Client) - else: calls.append([operation, stream_id]) if reads: - # Each script reads a closed Stream to its end, and another one. - calls += [[operation, f"s-{seed}-0"] for operation in ("close", "read")] - calls.append(["read", f"s-{seed}-1"]) + calls += [["read", f"s-{seed}-0"], ["read", f"s-{seed}-1"]] # The two Stores have one name and the same Stream ids, so a call is the same # request in both. for_client, for_workflow = FaultStore(), FaultStore() @@ -178,14 +162,16 @@ async def test_workflow_code_and_a_client_get_the_same_answers(client: Client) - if isinstance(request, AppendRecordsRequest) ] assert all(appends) and len(set(appends)) == len(appends) - # A replay writes nothing, with the Stores of the run and with none. + # A replay with the Stores of the run writes nothing. A replay chooses the + # Store of each call again, so one with no Stream config fails. written = _writes(for_workflow) - for replay_client in (workflow_client, client)[: 1 if reads else 2]: - await Replayer( - workflows=[_CallsWorkflow], - stream_config=replay_client._config["stream_config"], - ).replay_workflow(ran.history) + await Replayer( + workflows=[_CallsWorkflow], + stream_config=workflow_client._config["stream_config"], + ).replay_workflow(ran.history) assert _writes(for_workflow) == written + with pytest.raises(Exception, match="no stream_config"): + await Replayer(workflows=[_CallsWorkflow]).replay_workflow(ran.history) def _bodies(writer: str) -> list[Any]: @@ -239,9 +225,7 @@ async def test_a_body_reads_the_same_on_every_path(client: Client) -> None: assert ran.result == _digest(expected) # The Store has each body as the codec gave it with no context, and the storage of # the Worker has none of them. - stored = await store.memory.read_records( - ReadRecordsRequest(ref=RefProto(id="bodies")) - ) + stored = await store.memory.read_records(ReadRecordsRequest(stream_id="bodies")) assert [dict(record.body.metadata) for record in stored.records] == [ {"encoding": b"test/wrapped", "context": b"NoneType"} ] * len(expected) @@ -278,9 +262,7 @@ async def test_two_activities_with_one_id_write_as_two_producers( 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(ref=RefProto(id="one id")) - ) + 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 @@ -291,20 +273,21 @@ def _events(history: Any, event_type: EventType.ValueType) -> list[Any]: return [event for event in history.events if event.event_type == event_type] -def _stream_calls(history: Any) -> list[WorkflowTaskStreamCalls]: - """Return the Stream calls that Core keeps on each completed Workflow Task.""" - completed = _events(history, EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED) - calls = [ - event.workflow_task_completed_event_attributes.sdk_metadata.stream_calls - for event in completed +def _stream_markers(history: Any, kind: str) -> list[Any]: + """Return the markers in which Core records the Stream calls of ``kind``, which + is ``append`` or ``read``. + """ + return [ + event + for event in _events(history, EventType.EVENT_TYPE_MARKER_RECORDED) + if event.marker_recorded_event_attributes.marker_name == f"core_stream_{kind}" ] - return [call for call in calls if call.ByteSize()] async def test_a_store_error_is_the_same_error_on_every_path(client: Client) -> None: store = FaultStore() client = stream_client(client, store) - stream = await client.create_stream(id="errors", body_type=int) + await client.create_stream(id="errors", body_type=int) append: list[Any] = ["append", "errors", [1]] appends = store.faults["append_records"] unavailable = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE @@ -351,31 +334,25 @@ def append_request_ids() -> list[str | None]: corrupt = StreamErrorReason.STREAM_ERROR_REASON_STORE_CORRUPT for path in ("client", "activity", "workflow"): with failure_note(path): - appends.append(answers(CloseStreamResponse())) + appends.append(answers(DescribeStreamResponse())) [[error, reason, _]] = await answers_on(path, [append]) assert (error, reason, len(append_request_ids())) == ("error", corrupt, 1) - # So does a create that the Store answers with the ref of another Stream. - other = CreateStreamResponse(ref=RefProto(id="other"), created=True) - store.faults["create_stream"].append(answers(other)) - create = ["create", f"answered for another Stream in {path}"] - [[error, reason, _]] = await answers_on(path, [create]) - assert (error, reason) == ("error", corrupt) # A refusal is the same error for a client, an Activity and Workflow code. Workflow # code gets it again in each task that replays the call. - await stream.close() - calls = [ - append, + not_found = StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND + calls: list[list[Any]] = [ + ["append", "missing", [1]], ["describe", "errors"], ["describe", "missing"], ["read", "missing"], ] refused = await answers_on("client", calls) assert [answer[:2] for answer in refused] == [ - ["error", StreamErrorReason.STREAM_ERROR_REASON_CLOSED], - [StreamStatus.StreamStatusClosed, (3).to_bytes(8, "big").hex()], - ["error", StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND], - ["error", StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND], + ["error", not_found], + [(3).to_bytes(8, "big").hex()], + ["error", not_found], + ["error", not_found], ] for path in ("activity", "workflow"): with failure_note(path): @@ -448,7 +425,6 @@ async def task_fails(handle: Any, _worker: Any) -> None: calls: list[list[Any]] = [ ["create", "s"], ["append", "s", [1]], - ["close", "s"], ["describe", "s"], ["read", "s"], ] @@ -468,52 +444,6 @@ async def task_fails(handle: Any, _worker: Any) -> None: # has nothing of the call. assert isinstance(ran.result, WorkflowFailureError) assert not _events(ran.history, EventType.EVENT_TYPE_MARKER_RECORDED) - assert not _stream_calls(ran.history) - - -@workflow.defn -class _ClosingWorkflow: - @workflow.run - async def run(self, stream_id: str, how: str) -> None: - stream = await workflow.create_stream(id=stream_id, body_type=str) - if how == "async with": - async with stream: - await stream.append("body") - return - try: - await stream.append("body") - if how == "failure": - raise ApplicationError("The block failed") - if how == "cancel": - await workflow.wait_condition(lambda: False) - finally: - await stream.close() - - -async def test_a_close_of_workflow_code_closes_the_stream(client: Client) -> None: - for how in ("async with", "return", "failure", "cancel"): - with failure_note(how): - store = FaultStore() - stream_id = f"closed after a {how}" - - async def cancel_in_the_block(handle: Any, _worker: Any) -> None: - async def appended() -> None: - assert any( - isinstance(r, AppendRecordsRequest) for r in store.requests - ) - - await assert_eventually(appended) - await handle.cancel() - - options = RunOptions(_ClosingWorkflow, [stream_id, how]) - if how == "cancel": - options.during = cancel_in_the_block - ran = await run(stream_client(client, store), options) - assert (ran.result is None) == (how in ("async with", "return")) - page = await store.memory.read_records( - ReadRecordsRequest(ref=RefProto(id=stream_id)) - ) - assert (len(page.records), page.done) == (1, True) class _ActivityTypes(Interceptor): @@ -553,7 +483,7 @@ async def activity_pollers(handle: Any, worker: Worker) -> None: during=activity_pollers, ) ran = await run(client, options) - assert ran.result == [["memory", True], [StreamStatus.StreamStatusOpen, ""]] + assert ran.result == [["memory", True], [""]] assert interceptor.types == ["__temporal_stream_store_call"] * 2 assert not pollers @@ -588,13 +518,7 @@ async def run(self, own: str, shared: str) -> str | None: 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_ref.id if isinstance(r, CreateStreamRequest) else r.ref.id, - ) - for r in store.requests - ] + 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 @@ -738,7 +662,7 @@ def calls(stream_id: str) -> list[list[Any]]: len(request.records) for request in store.requests if isinstance(request, AppendRecordsRequest) - and request.ref.id != f"large {seed}" + and request.stream_id != f"large {seed}" ] == [len(sizes) for sizes, fits in batches if fits] * 2 @@ -775,12 +699,16 @@ async def test_a_create_in_a_later_run_of_the_chain_is_the_same_create( @activity.defn async def _write_one_by_one(stream_id: str, count: int) -> None: - stream = activity.client().get_stream(StreamRef[str](id=stream_id)) + client = activity.client() + stream = client.get_stream(StreamRef[str](id=stream_id)) + workflow_id = activity.info().workflow_id or "" for number in range(count): await stream.append(f"a body, number {number}") + # A read makes no Workflow Task for a Record that SDK Core doesn't know of, so + # the writer signals the Workflow. + await client.get_workflow_handle(workflow_id).signal(_ReadingWorkflow.wake) # The next Record comes only once the Workflow has handled this one. await _handled[number].wait() - await stream.close() @activity.defn @@ -790,6 +718,10 @@ async def _handle(number: int) -> None: @workflow.defn class _ReadingWorkflow: + @workflow.signal + def wake(self) -> None: + pass + @workflow.run async def run(self, stream_id: str, count: int) -> list[int]: stream = await workflow.create_stream(id=stream_id, body_type=str) @@ -805,6 +737,9 @@ async def run(self, stream_id: str, count: int) -> list[int]: _handle, number, start_to_close_timeout=timedelta(seconds=30) ) numbers.append(number) + # A Stream has no end, so the reader stops at the writer's last Record. + if number == count - 1: + break await writer return numbers @@ -847,8 +782,6 @@ async def run(self, stream_id: str, how: str) -> None: stream = await workflow.create_stream(id=stream_id, body_type=int) if how == "append": asyncio.ensure_future(stream.append(1)) - elif how == "close": - asyncio.ensure_future(stream.close()) elif how == "page": await stream.append(1) await stream.read_page(wait=timedelta(minutes=5)) @@ -892,11 +825,11 @@ async def end(handle: Any, worker: Worker) -> None: assert len(reads) == 1 -@pytest.mark.parametrize("how", ["page", "append", "close"]) +@pytest.mark.parametrize("how", ["page", "append"]) async def test_a_stream_call_does_not_hold_the_last_command( client: Client, how: str ) -> None: - # A read that gave a page, and an append or a close that nothing awaits, don't hold + # A read that gave a page, and an append that nothing awaits, don't hold # the last command, so the Workflow ends in the task of the call. options = RunOptions(_EndingWorkflow, [f"ends after its {how}", how], replay=True) ran = await run(stream_client(client, FaultStore()), options) @@ -908,6 +841,10 @@ async def test_a_stream_call_does_not_hold_the_last_command( class _LatePagesWorkflow: """Reads Records that come in a later Workflow Task than the one of its reads.""" + @workflow.signal + def wake(self) -> None: + pass + @workflow.run async def run(self, how: str) -> list[list[str]]: s = workflow.get_stream(StreamRef[str](id=f"s of {how}")) @@ -926,7 +863,8 @@ async def run(self, how: str) -> list[list[str]]: page = await s.read_page(from_offset=offset, wait=timedelta(seconds=30)) pages.append([record.body for record in page.records]) offset = page.last_offset - if page.done: + # A Stream has no end, so the loop stops at the writer's last Record. + if "b" in pages[-1]: return pages async def _page(self, stream: Any, offset: bytes | None = None) -> Any: @@ -955,21 +893,21 @@ async def test_a_replay_gives_a_read_the_pages_of_the_first_run( }[how] async def write(handle: Any, _worker: Any) -> None: - async def second_task() -> None: + async def first_task() -> None: history = await handle.fetch_history() - started = EventType.EVENT_TYPE_WORKFLOW_TASK_STARTED - assert len(_events(history, started)) > 1 + completed = EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED + assert _events(history, completed) - # The reads of the first task end at its read limit with no Record. The pages - # then come in several activations of a later task, and a replay gives each + # The reads of the first task end with no Record, and a read of an idle Stream + # makes no task. A Signal opens the next task, whose reads start again. The + # pages then come in several activations of that task, and a replay gives each # page in its activation. - await assert_eventually(second_task) + await assert_eventually(first_task) + await handle.signal(_LatePagesWorkflow.wake) for stream, body in writes: await stream.append(body) # The page of this Record gets an activation before the next Record comes. await asyncio.sleep(0.3) - if how == "a loop": - await s.close() options = RunOptions( _LatePagesWorkflow, @@ -982,7 +920,9 @@ async def second_task() -> None: assert [body for page in ran.result for body in page] == expected events = [event.event_type for event in ran.history.events] completed = events.index(EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED) - assert events[completed + 1] == EventType.EVENT_TYPE_WORKFLOW_TASK_SCHEDULED + marker = EventType.EVENT_TYPE_MARKER_RECORDED + later = [event for event in events[completed + 1 :] if event != marker] + assert later[0] == EventType.EVENT_TYPE_WORKFLOW_EXECUTION_SIGNALED @workflow.defn @@ -1119,7 +1059,8 @@ async def go_on(handle: Any, _worker: Any) -> None: async def lose_the_records(handle: Any, _worker: Any) -> None: async def has_read() -> None: - assert _stream_calls(await handle.fetch_history()) + history = await handle.fetch_history() + assert _stream_markers(history, "read") await assert_eventually(has_read) store.memory = MemoryStreamStore() @@ -1155,7 +1096,13 @@ async def run(self, stream_id: str, limits: dict[str, int]) -> list[int]: max_records=limits.get("max_records"), max_bytes=limits.get("max_bytes"), ) - return [record.body async for record in records] + bodies: list[int] = [] + async for record in records: + bodies.append(record.body) + # A Stream has no end, so the reader stops at the writer's last Record. + if record.body == 3: + break + return bodies async def test_a_workflow_read_asks_the_store_with_its_limits(client: Client) -> None: @@ -1163,12 +1110,19 @@ async def test_a_workflow_read_asks_the_store_with_its_limits(client: Client) -> client = stream_client(client, store) stream = await client.create_stream(id="paged", body_type=int) await stream.append(1, 2, 3) - await stream.close() - # A read with no limit asks for 256 Records and 4 MiB. A Store call waits no longer - # than the read time of the Worker, which is shorter than the wait of the read. + + # A read with no limit asks for 256 Records and 4 MiB. The Store gets room for one + # Record more, so that SDK Core knows when the Stream has more. That Record has at + # most the Record size of the config and an offset of 1024 bytes, each in its field. + # A Store call waits no longer than the read time of the Worker, which is shorter + # than the wait of the read. + def field(size: int) -> int: + return 1 + (size.bit_length() + 6) // 7 + size + + one_more = field(StreamConfig([store]).max_record_bytes + field(1024)) cases: list[tuple[dict[str, int], tuple[int, int]]] = [ - ({"max_records": 1, "max_bytes": 100}, (1, 100)), - ({}, (256, 4 * 1024 * 1024)), + ({"max_records": 1, "max_bytes": 100}, (2, 100 + one_more)), + ({}, (257, 4 * 1024 * 1024 + one_more)), ] read_time = timedelta(seconds=2) for limits, expected in cases: @@ -1190,32 +1144,46 @@ async def test_a_workflow_read_asks_the_store_with_its_limits(client: Client) -> @workflow.defn class _QuietReadWorkflow: + @workflow.signal + def wake(self) -> None: + pass + @workflow.run async def run(self, stream_id: str) -> list[int]: stream = workflow.get_stream(StreamRef[int](id=stream_id)) - return [record.body async for record in stream.read(wait=timedelta(minutes=5))] + bodies: list[int] = [] + offset = None + # The writer's last Record is 2, since a Stream has no end. + while 2 not in bodies: + page = await stream.read_page(from_offset=offset, wait=timedelta(minutes=5)) + bodies.extend(record.body for record in page.records) + offset = page.last_offset + return bodies -async def test_a_workflow_read_waits_on_a_quiet_stream_across_read_limits( +async def test_a_workflow_read_of_a_quiet_stream_makes_no_workflow_task( client: Client, ) -> None: store = FaultStore() client = stream_client(client, store) stream = await client.create_stream(id="quiet", body_type=int) + completed = EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED async def write(handle: Any, _worker: Any) -> None: - async def limit_passed() -> None: - history = await handle.fetch_history() - completed = EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED - assert len(_events(history, completed)) > 1 - - # On a quiet Stream, the read gets pages with no Record, and goes on in the next - # Workflow Task from the same offset. - await assert_eventually(limit_passed) + async def first_task() -> None: + assert _events(await handle.fetch_history(), completed) + + # On a quiet Stream, the reads get pages with no Record until the read limit, + # and the task then completes with no new task, over several read limits. + await assert_eventually(first_task) + await asyncio.sleep(1) + history = await handle.fetch_history() + assert len(_events(history, EventType.EVENT_TYPE_WORKFLOW_TASK_STARTED)) == 1 quiet = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] - assert len(quiet) > 1 and not any(r.from_offset for r in quiet) + assert quiet and not any(r.from_offset for r in quiet) + # The read starts again from the same offset in the task of a Signal. await stream.append(1, 2) - await stream.close() + await handle.signal(_QuietReadWorkflow.wake) options = RunOptions( _QuietReadWorkflow, @@ -1227,7 +1195,7 @@ async def limit_passed() -> None: assert (await run(client, options)).result == [1, 2] -async def test_a_workflow_read_with_no_wait_outlives_the_read_limit( +async def test_a_workflow_read_with_no_wait_reads_again_in_the_next_task( client: Client, ) -> None: store, hold = FaultStore(), Hold() @@ -1241,9 +1209,11 @@ async def task_completed() -> None: completed = EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED assert _events(history, completed) - # The task completes at its read limit, and the Store still holds the read. + # The read goes on at the read limit, since only the Store can say that the + # Stream has no Record. The task then completes, which stops the held read, + # and the read starts again in the task of the Signal. await assert_eventually(task_completed) - hold.release() + await asyncio.wait_for(hold.cancelled.wait(), 10) await handle.signal(_ReadOnceWorkflow.go_on) options = RunOptions( @@ -1254,7 +1224,8 @@ async def task_completed() -> None: replay=True, ) assert (await run(stream_client(client, store), options)).result == [1, 2, 3] - assert not hold.cancelled.is_set() + reads = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] + assert len([r for r in reads if not r.from_offset]) >= 2 @dataclasses.dataclass diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py index 8b699f92e5..5dd9fff964 100644 --- a/tests/worker/test_workflow_streams.py +++ b/tests/worker/test_workflow_streams.py @@ -20,26 +20,22 @@ import temporalio.worker from temporalio import workflow from temporalio.api.common.v1 import ActivityType, Payload -from temporalio.api.enums.v1 import ( - RetryState, - StreamErrorReason, - StreamStatus, - TimeoutType, -) +from temporalio.api.enums.v1 import RetryState, StreamErrorReason, TimeoutType from temporalio.api.failure.v1 import ( ActivityFailureInfo, ApplicationFailureInfo, Failure, TimeoutFailureInfo, ) -from temporalio.api.sdk.v1.external_storage_pb2 import ExternalStorageReference -from temporalio.api.stream.v1 import StreamRecord, StreamRef -from temporalio.api.streamservice.v1 import ( +from temporalio.api.sdk.v1 import ( CreateStreamRequest, CreateStreamResponse, DescribeStreamRequest, - DescribeStreamResponse, + StreamRef, ) +from temporalio.api.sdk.v1.external_storage_pb2 import ExternalStorageReference +from temporalio.api.stream.v1 import StreamRecord +from temporalio.api.streamservice.v1 import DescribeStreamResponse from temporalio.bridge.proto.activity_result import ( ActivityResolution, ) @@ -49,7 +45,6 @@ RemoveFromCache, ResolveActivity, ResolveStreamAppend, - ResolveStreamClose, ResolveStreamRead, SignalWorkflow, StreamAppended, @@ -60,7 +55,6 @@ from temporalio.bridge.proto.workflow_commands import ( ActivityCancellationType, AppendToStream, - CloseStream, CompleteWorkflowExecution, ReadStream, RequestCancelLocalActivity, @@ -221,9 +215,9 @@ async def test_stream_payloads_take_the_codec_with_no_context_and_no_storage() - envelope = to_payload("envelope") envelope.metadata[temporalio.nexus.system._SYSTEM_PAYLOAD_METADATA_KEY] = b"true" failure = Failure( - message="The Stream is closed", + message="A later attempt has written to the Stream", application_failure_info=ApplicationFailureInfo( - type="stream_closed", + type="stream_fenced", details=temporalio.api.common.v1.Payloads(payloads=[wrapped(result)]), ), ) @@ -247,9 +241,6 @@ async def test_stream_payloads_take_the_codec_with_no_context_and_no_storage() - WorkflowActivationJob( resolve_stream_append=ResolveStreamAppend(seq=1, failed=failure) ), - WorkflowActivationJob( - resolve_stream_close=ResolveStreamClose(seq=1, failed=failure) - ), WorkflowActivationJob( resolve_activity=ResolveActivity( seq=1, @@ -262,7 +253,7 @@ async def test_stream_payloads_take_the_codec_with_no_context_and_no_storage() - await temporalio.bridge.worker.decode_activation( activation, command_aware, decode_headers=True, storage_concurrency_limit=1 ) - read, failed_read, appended, closed, activity = activation.jobs + read, failed_read, appended, activity = activation.jobs assert [record.body for record in read.resolve_stream_read.page.records] == [ *bodies, claim, @@ -270,7 +261,6 @@ async def test_stream_payloads_take_the_codec_with_no_context_and_no_storage() - ] assert failed_read.resolve_stream_read.failed == failure assert appended.resolve_stream_append.failed == failure - assert closed.resolve_stream_close.failed == failure assert activity.resolve_activity.result.completed.result == result assert driver._retrieve_calls == 1 assert calls == [("decode", None, 1)] * 4 + [("decode", context, 1)] @@ -279,7 +269,7 @@ async def test_stream_payloads_take_the_codec_with_no_context_and_no_storage() - _REFUSALS = [ StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND, StreamErrorReason.STREAM_ERROR_REASON_ALREADY_EXISTS, - StreamErrorReason.STREAM_ERROR_REASON_CLOSED, + StreamErrorReason.STREAM_ERROR_REASON_EXPIRED, StreamErrorReason.STREAM_ERROR_REASON_FENCED, ] _UNAVAILABLE = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE @@ -291,7 +281,7 @@ class _Call: """One generated Stream call, and what Workflow code got for it.""" operation: str - """One of ``create``, ``append``, ``close`` and ``describe``.""" + """One of ``create``, ``append`` and ``describe``.""" stream: str """The id of the Stream. A call on a Stream that an earlier phase created uses the Stream of that create.""" @@ -353,12 +343,9 @@ async def _call(self, streams: dict[str, Any], call: _Call) -> None: if call.operation == "append": appended = await stream.append(*call.bodies) call.outcome = (appended.first_offset, appended.last_offset) - elif call.operation == "close": - await stream.close() - call.outcome = "closed" else: described = await stream.describe() - call.outcome = (described.status, described.last_offset) + call.outcome = described.last_offset except StreamError as err: call.outcome = err.reason except asyncio.CancelledError: @@ -390,31 +377,28 @@ async def start_append_records(self, request: Any) -> Any: _Script.intercepted.append(("append", request)) return await super().start_append_records(request) - async def start_close_stream(self, request: Any) -> Any: - _Script.intercepted.append(("close", request)) - return await super().start_close_stream(request) - async def start_describe_stream(self, request: Any) -> Any: _Script.intercepted.append(("describe", request)) return await super().start_describe_stream(request) def _plan( - call: _Call, seq: int, store: str, history_store: str + call: _Call, seq: int, ref_store: str, store: str, history_store: str ) -> tuple[WorkflowCommand, WorkflowActivationJob, Any]: """Return the command that a call must send, the job that the test answers it with, and what Workflow code must get for it. - ``store`` is the Store name that the call must send, and ``history_store`` the + ``ref_store`` is the Store name of the ref that Workflow code passes, ``store`` + the name of the Store that the SDK chose for the call, and ``history_store`` the one that the result of a create has. """ converter = temporalio.converter.DefaultPayloadConverter() - stream = StreamRef(id=call.stream, store=store) refused = None if call.refusal is None else core_failure(call.refusal) command, job = WorkflowCommand(), WorkflowActivationJob() outcome: Any if call.operation == "append": bodies = converter.to_payloads(call.bodies) + stream = StreamRef(id=call.stream, store=store) command.append_to_stream.CopyFrom( AppendToStream(seq=seq, stream=stream, bodies=bodies) ) @@ -426,23 +410,18 @@ def _plan( job.resolve_stream_append.appended.CopyFrom( StreamAppended(first_offset=outcome[0], last_offset=outcome[1]) ) - elif call.operation == "close": - command.close_stream.CopyFrom(CloseStream(seq=seq, stream=stream)) - outcome = "closed" - job.resolve_stream_close.seq = seq - if refused: - job.resolve_stream_close.failed.CopyFrom(refused) else: - request: Message = DescribeStreamRequest(ref=stream) + # The request of the Local Activity has the ref of Workflow code, and the + # Activity gets the name of the chosen Store next to it. + ref = StreamRef(id=call.stream, store=ref_store) + request: Message = DescribeStreamRequest(ref=ref) request_id = None - described = DescribeStreamResponse( - status=StreamStatus.STREAM_STATUS_OPEN, last_offset=b"last%d" % seq - ) + described = DescribeStreamResponse(last_offset=b"last%d" % seq) answer: Message = described - outcome = (described.status, described.last_offset) + outcome = described.last_offset if call.operation == "create": # Each create of a run chain has the first run id as its request id. - request, request_id = CreateStreamRequest(stream_ref=stream), "first-run" + request, request_id = CreateStreamRequest(stream_ref=ref), "first-run" answer = CreateStreamResponse( ref=StreamRef(id=call.stream, store=history_store), created=seq % 2 == 0, @@ -454,7 +433,9 @@ def _plan( activity.activity_type = _STORE_CALL operation = request.DESCRIPTOR.name.removesuffix("Request") activity.arguments.extend( - converter.to_payloads([operation, request.SerializeToString(), request_id]) + converter.to_payloads( + [operation, store, request.SerializeToString(), request_id] + ) ) activity.schedule_to_close_timeout.FromSeconds(5) temporalio.common.RetryPolicy(maximum_attempts=1).apply_to_proto( @@ -516,12 +497,11 @@ def selector(context: StreamSelectContext) -> StreamStore: return stores[int(context.id[1:]) % 2] config = rng.choice( - [None, StreamConfig(stores[:1]), StreamConfig(stores, store_selector=selector)] + [StreamConfig(stores[:1]), StreamConfig(stores, store_selector=selector)] ) - names = "a" if config and len(config.stores) == 1 else "ab" - # A live create or describe needs a Stream config of the Worker, and a replay - # needs none. - replaying = config is None or rng.random() < 0.3 + names = "a" if len(config.stores) == 1 else "ab" + # A replay chooses the Store of each call again, as the first run did. + replaying = rng.random() < 0.3 # The Store name that History has for each Stream that a create of the script makes. # It need not be the one that the config picks for the create. @@ -531,7 +511,7 @@ def selector(context: StreamSelectContext) -> StreamStore: for _ in range(rng.randrange(1, 5)): phase: list[_Call] = [] for _ in range(rng.randrange(1, 5)): - operation = rng.choice(["create", "append", "append", "close", "describe"]) + operation = rng.choice(["create", "append", "append", "describe"]) if operation != "create" and created and rng.random() < 0.5: call = _Call(operation, rng.choice(sorted(created))) else: @@ -548,12 +528,12 @@ def selector(context: StreamSelectContext) -> StreamStore: if call.operation == "create" and not call.cancel and call.refusal is None: created[call.stream] = rng.choice(names) # The last phase can be one call that fails the Workflow Task. Its Local Activity - # ends in an outage or finds no Store, or the selector raises for its append. + # ends in an outage or finds no Store, or the selector raises for the call. fatal = rng.choice([None, None, "outage", "unserved", "selector"]) - if fatal == "selector" and not (config and config.store_selector): + if fatal == "selector" and not config.store_selector: fatal = None if fatal == "selector": - phases.append([_Call("append", "fatal")]) + phases.append([_Call(rng.choice(["create", "append", "describe"]), "fatal")]) elif fatal: last = _Call(rng.choice(["create", "describe"]), f"s{streams}") last.unserved = fatal == "unserved" @@ -572,7 +552,7 @@ def selector(context: StreamSelectContext) -> StreamStore: target = StorageDriverWorkflowInfo( namespace="ns", id="wf", run_id="run", type="_ScriptWorkflow" ) - seqs = {"append": 0, "close": 0, "activity": 0} + seqs = {"append": 0, "activity": 0} jobs = [WorkflowActivationJob(initialize_workflow=InitializeWorkflow())] outcomes: list[Any] = [] expected_selects: list[StreamSelectContext] = [] @@ -586,24 +566,23 @@ def selector(context: StreamSelectContext) -> StreamStore: cancels: list[WorkflowCommand] = [] jobs = [] for call in phase: - by_core = call.operation in ("append", "close") + # Each call gets its Store in Workflow code, and only a ref with no Store + # name asks the selector. if call.stream in usable: - store = created[call.stream] - elif call.store or config is None or not by_core: - # The Local Activity of a create or a describe gets the ref's own Store - # name, and it asks the selector itself. - store = call.store or "" + ref_store = store = created[call.stream] + elif call.store: + ref_store = store = call.store elif config.store_selector is None: - store = "a" + ref_store, store = "", "a" else: - store = stores[int(call.stream[1:]) % 2].name() + ref_store, store = "", stores[int(call.stream[1:]) % 2].name() expected_selects.append( StreamSelectContext(id=call.stream, target=target, namespace="ns") ) kind = call.operation if call.operation in seqs else "activity" seqs[kind] += 1 command, job, outcome = _plan( - call, seqs[kind], store, created.get(call.stream, "a") + call, seqs[kind], ref_store, store, created.get(call.stream, "a") ) commands.append(command) jobs.append(job) @@ -627,7 +606,7 @@ def selector(context: StreamSelectContext) -> StreamStore: assert command.HasField("complete_workflow_execution") calls = [call for phase in phases for call in phase] assert [call.outcome for call in calls] == outcomes - assert not instance._streams._appends and not instance._streams._closes + assert not instance._streams._appends assert selects == expected_selects # An interceptor sees each call in the method of its operation, and the ref of # a create as Workflow code wrote it, also after its result. @@ -647,6 +626,125 @@ def selector(context: StreamSelectContext) -> StreamStore: assert (await _activate(instance, evict)).HasField("successful") +class _OwnPath: + """The calls of :py:class:`_EachCallWorkflow`, and what its Stores saw.""" + + operations: list[str] = [] + selects: list[str] = [] + """The Stream id of each selector call.""" + started: list[tuple[str, int]] = [] + """Each call that :py:class:`_OwnPathStore` started, with the number of selector + calls before it.""" + + +class _OwnPathStore(MemoryStreamStore): + """A Store that runs each Stream call of Workflow code itself, with no command + and no Local Activity, as a Store that SDK Core doesn't call would. + """ + + def _start_workflow_call( + self, streams: Any, operation: str, request: Message, result_type: Any + ) -> asyncio.Future[Any]: + _OwnPath.started.append((operation, len(_OwnPath.selects))) + return asyncio.get_running_loop().create_future() + + +@workflow.defn +class _EachCallWorkflow: + @workflow.run + async def run(self) -> None: + calls: list[Any] = [] + for at, operation in enumerate(_OwnPath.operations): + stream = workflow.get_stream(ModelRef[int](id=f"s{at}")) + if operation == "create": + calls.append(workflow.create_stream(id=f"s{at}", body_type=int)) + elif operation == "append": + calls.append(stream.append(at)) + elif operation == "read": + calls.append(stream.read_page()) + else: + calls.append(stream.describe()) + if len(calls) == 1: + # The run gets the error of its one call, so no task holds an error that + # no one reads. + await calls[0] + return + tasks = [asyncio.ensure_future(call) for call in calls] + # Each task makes its call in its first step. + await asyncio.sleep(0) + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + + +async def test_the_store_of_a_call_is_chosen_once_and_runs_the_call() -> None: + operations = ["create", "append", "read", "describe"] + # The variant of the command that the default path sends for each operation + variants = { + "create": "schedule_local_activity", + "append": "append_to_stream", + "read": "read_stream", + "describe": "schedule_local_activity", + } + own, default = _OwnPathStore(name="own"), MemoryStreamStore(name="default") + for owned in range(2 ** len(operations)): + # Bit `at` of `owned` gives call `at` to the Store that runs it itself. + on_own = [bool(owned >> at & 1) for at in range(len(operations))] + + def selector(context: StreamSelectContext) -> StreamStore: + _OwnPath.selects.append(context.id) + return own if on_own[int(context.id[1:])] else default + + config = StreamConfig([own, default], store_selector=selector) + _OwnPath.operations = operations + for replaying in (False, True): + with failure_note(f"owned {on_own}, replaying {replaying}"): + _OwnPath.selects, _OwnPath.started = [], [] + instance = _new_instance(_EachCallWorkflow, config) + initialize = WorkflowActivationJob( + initialize_workflow=InitializeWorkflow() + ) + completion = await _activate(instance, initialize, replaying=replaying) + # The selector runs once for each call, before the Store starts it. + ids = [f"s{at}" for at in range(len(operations))] + assert _OwnPath.selects == ids + assert _OwnPath.started == [ + (f"{name.capitalize()}{suffix}", at + 1) + for at, (name, suffix, mine) in enumerate( + zip( + operations, + ["Stream", "Records", "Records", "Stream"], + on_own, + ) + ) + if mine + ] + # A call on the Store that runs it itself sends no command. A cancel + # sends a command only for a Local Activity of the default path. + sent = [ + variants[name] for name, mine in zip(operations, on_own) if not mine + ] + cancels = [ + "request_cancel_local_activity" + for variant in sent + if variant == "schedule_local_activity" + ] + assert [ + command.WhichOneof("variant") + for command in completion.successful.commands + ] == [*sent, *cancels, "complete_workflow_execution"] + + +async def test_a_stream_call_with_no_stream_config_fails_the_task() -> None: + for operation in ["create", "append", "read", "describe"]: + _OwnPath.operations = [operation] + for replaying in (False, True): + instance = _new_instance(_EachCallWorkflow) + initialize = WorkflowActivationJob(initialize_workflow=InitializeWorkflow()) + completion = await _activate(instance, initialize, replaying=replaying) + assert "no stream_config" in completion.failed.failure.message, operation + + @dataclass class _ReadCall: """One generated reader, which reads pages of a Stream one after the other, and @@ -710,9 +808,7 @@ async def _read(self, call: _ReadCall) -> None: ) bodies = [record.body for record in page.records] offset = page.last_offset - call.outcome.append((bodies, offset or b"", page.done)) - if page.done: - return + call.outcome.append((bodies, offset or b"")) except StreamError as err: call.outcome.append(err.reason) except TypeError: @@ -760,7 +856,9 @@ async def _reads_script( converter = temporalio.converter.DefaultPayloadConverter() calls: list[_ReadCall] = [] _ReadScript.calls, _ReadScript.steps = calls, [] - instance = _new_instance(_ReadsWorkflow) + instance = _new_instance( + _ReadsWorkflow, StreamConfig([MemoryStreamStore(name="a")]) + ) initialize = WorkflowActivationJob(initialize_workflow=InitializeWorkflow()) completion = await _activate(instance, initialize, flags=flags, replaying=replaying) assert not completion.successful.commands @@ -815,7 +913,6 @@ def call_read(call: int, commands: list[WorkflowCommand]) -> None: for number in records ], last_offset=_offset(last), - done=rng.random() < 0.3, ) job = ResolveStreamRead(seq=seq, page=page) if rng.random() < 0.15: @@ -883,8 +980,8 @@ def run_handler() -> None: bodies = [converter.from_payload(r.body) for r in job.page.records] # The next page comes after the last_offset of this one. positions[call] = int.from_bytes(job.page.last_offset, "big") - outcomes[call].append((bodies, job.page.last_offset, job.page.done)) - if not job.page.done and len(outcomes[call]) < reader.pages: + outcomes[call].append((bodies, job.page.last_offset)) + if len(outcomes[call]) < reader.pages: call_read(call, commands) signal = SignalWorkflow(signal_name="step", originating_event_id=step + 1) From 8cf4cc88a820a64af984c30a29ea356e6e3fcfba Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Wed, 25 Nov 2026 14:45:03 -0700 Subject: [PATCH 26/50] Read again after a page whose wait the read limit cut A Workflow read() or read_pages() reads again from a page with no Record whose wait_cut says that the read limit of the task ended the wait. A Store outage at a read fails the Workflow Task, and the docs and tests follow the read checks of the pinned Core. --- changelog/added/steady-stream-heron.md | 2 +- temporalio/client/_stream_store.py | 28 ++++-- temporalio/contrib/streams/README.md | 18 ++-- temporalio/nexus/system/_support.py | 13 ++- temporalio/worker/_worker.py | 14 +-- temporalio/worker/_workflow_streams.py | 16 ++-- tests/nexus/test_streams_with_worker.py | 116 ++++++++++++++++++++++-- tests/testing/test_stream_store.py | 29 ++++++ tests/worker/test_workflow_streams.py | 77 ++++++++++++++++ 9 files changed, 276 insertions(+), 37 deletions(-) diff --git a/changelog/added/steady-stream-heron.md b/changelog/added/steady-stream-heron.md index e25fdfe107..b06de02410 100644 --- a/changelog/added/steady-stream-heron.md +++ b/changelog/added/steady-stream-heron.md @@ -1,5 +1,5 @@ Add experimental `temporalio.client.StreamStore`, the base class of a Stream Store, and `temporalio.testing.MemoryStreamStore`, a Store that keeps its Streams in memory for tests and local runs. A Store gets the requests of `temporalio.api.streamservice.v1`, which have the Stream id, and the request id of each create and each append as `request_id`. A create returns only `created`, and the SDK gives the caller the ref with the name of the Store. A Stream has no close, and it expires when the Retention of its Store has passed since its create or its last append that wrote a batch. Add experimental Streams for client and Activity code. `stream_config=StreamConfig(stores=[...])` of `Client.connect` gives a client its Stream Stores, and `Client.create_stream` and `Client.get_stream` return a `Stream` to append to, read and describe. A failed call raises `temporalio.exceptions.StreamError` with a `reason`. `max_record_bytes`, `max_batch_bytes` and `max_batch_records` of `StreamConfig` bound an append, and one over a limit fails before its Store gets it. A read of a Stream from `get_stream` needs `body_type=` or a `StreamRef` with a type argument, and raises `TypeError` with neither. `Stream.read` stops at the first page with no Record, so a read with no wait reads to the newest Record, and a read with a wait stops once no Record came within the wait. `temporalio.contrib.streams.current_producer` gives the Producer of an Activity attempt, and `as_producer` gives back one that code stored. Add experimental Streams for Workflow code. `workflow.create_stream` and `workflow.get_stream` return a `Stream` to append to, read and describe on the Stream Stores of the Worker's client, and `Replayer(stream_config=...)` gives a replay its Stores. The SDK chooses the Store of each call before the call starts, also in a replay. It calls the `store_selector` only for a ref with no Store name, in Workflow code for each such call, also for a create and a describe, and again in a replay. So the selector must return the same Store for the same call, must not block or do I/O, and must be safe to call from more than one thread. -Add experimental Stream reads for Workflow code. `Stream.read`, `read_pages` and `read_page` of a Workflow `Stream` give the Records as they come, a replay reads them again from the Store, and `temporalio.workflow.StreamReplayError` in the failure exception types of a Worker or a Workflow fails the Workflow when the Store no longer has them. The Worker option `stream_read_time` sets how long the reads of a Workflow Task can wait, and a read with a wait gives a page with no Record at that limit. +Add experimental Stream reads for Workflow code. `Stream.read`, `read_pages` and `read_page` of a Workflow `Stream` give the Records as they come, a replay reads them again from the Store, and `temporalio.workflow.StreamReplayError` in the failure exception types of a Worker or a Workflow fails the Workflow when the Store no longer has them. The Worker option `stream_read_time` sets how long the reads of a Workflow Task can wait, and a read with a wait gives a page with no Record at that limit, after which `read` and `read_pages` read again with the whole wait, so with a wait that the limit cuts they go on until a Record comes. A read with no wait gives the answer of the Store, which can be a page with no Record, and an outage of the Store at a read fails the Workflow Task. Add experimental `temporalio.contrib.streams.BufferedAppender`, which batches the appends of one Stream in client and Activity code. `append` returns immediately, a batch waits at most `max_delay`, one write runs at a time, and `async with` or `flush()` writes what is left. diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 4f7e1e70d5..8a15e2e1a8 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -278,8 +278,8 @@ class StreamConfig: any other Local Activity. - An append is at-least-once. If a Workflow Task fails after its append, the next attempt of the task writes the batch again. - - An outage of the Store gives Workflow code no error. The Workflow Task - fails, and the server tries it again. + - An outage of the Store gives Workflow code no error, also at a read. The + Workflow Task fails, and the server tries it again. - A call that Workflow code doesn't await before the Workflow ends may not happen. - A call with no Store fails the Workflow Task, also when Workflow code @@ -291,15 +291,25 @@ class StreamConfig: - A read fails with ``STREAM_ERROR_REASON_UNSUPPORTED`` for a Record over :py:attr:`max_record_bytes`. So a reader needs a limit at least as large as that of each writer of its Stream. - - A read with no Record to give waits up to its ``wait``, but at most to the - read limit of its Workflow Task, which the Worker option - ``stream_read_time`` sets. It then gives a page with no Record. A read - with no wait goes on until the Store answers. + - A read with no wait gives the answer of the Store, which can be a page with + no Record. + - A read with a ``wait`` and no Record to give waits up to its ``wait``, but + at most to the read limit of its Workflow Task, which the Worker option + ``stream_read_time`` sets. At that limit ``read_page`` gives a page with no + Record. ``read_pages`` yields that page and reads again from its offset, + and so does ``read``. Each read waits its whole ``wait`` again. So with a + ``wait`` that the read limit cuts, they go on until a Record comes, also + over more than one Workflow Task. To stop at a time, call ``read_page`` + in a loop that checks ``workflow.now()``. - A read holds its Workflow Task up to the read limit. A Signal that comes meanwhile waits until the read has its page, or until that limit. A - command for the server doesn't wait for a read. - - A read asks for a new Workflow Task only when SDK Core knows that the - Stream has more Records for it, so a read of an idle Stream makes no task. + command for the server waits only for one Store call with no wait for each + read, of at most 1 s. + - A read with a ``wait`` that has no Record when its Workflow Task completes + starts again in the next task. It asks for that task only when SDK Core + knows that the Stream has more Records for it, so a read of an idle Stream + makes no task. A Workflow Task gives at most 256 read results, and later + reads start in the next task. - A replay reads the Records of each read from the Store again. So the Retention of a Stream must cover the life of each Workflow that reads it, and the time in which that Workflow gets queries. diff --git a/temporalio/contrib/streams/README.md b/temporalio/contrib/streams/README.md index 5a77afa3d2..df60f3ed60 100644 --- a/temporalio/contrib/streams/README.md +++ b/temporalio/contrib/streams/README.md @@ -59,12 +59,18 @@ A Stream has no end that a read reports, so a reader stops at the application's with a `wait` it stops once no Record came within the wait. It reads a page only when the caller asks for the next Record, so a reader that stops at its last Record leaves no read open. -In Workflow code, a read with no Record to give waits up to its `wait`, but at most to the read -limit of its Workflow Task (the Worker option `stream_read_time`), and then gives a page with no -Record. A read asks for a new Workflow Task only when the Stream has more Records for it, so a -read of an idle Stream makes no task. A replay reads the Records again from the Store, so the -Retention of the Stream must cover the life of the Workflow and the time in which it gets -queries. +In Workflow code, a read with no `wait` gives the answer of the Store, which can be a page with no +Record. A read with a `wait` and no Record to give waits up to its `wait`, but at most to the read +limit of its Workflow Task (the Worker option `stream_read_time`). At that limit `read_page` gives +a page with no Record. `read_pages()` yields that page and reads again from its offset, and so +does `read()`. Each read waits its whole `wait` again, so with a `wait` that the read limit cuts, +they go on until a Record comes, also over more than one Workflow Task. To stop at a time, call +`read_page` in a loop that checks `workflow.now()`. A read with a `wait` that has no Record when +its task completes starts again in the next task. It asks for a new Workflow Task only when the +Stream has more Records for it, so a read of an idle Stream makes no task. An outage of the Store +fails the Workflow Task, and Workflow code gets no error. A replay reads the Records again from the +Store, so the Retention of the Stream must cover the life of the Workflow and the time in which it +gets queries. In Workflow code, a read with no `max_records` gives at most 256 Records in a page, and a read with no `max_bytes` at most 4 MiB of them. A page has at most 16 MiB of Records, also for a larger diff --git a/temporalio/nexus/system/_support.py b/temporalio/nexus/system/_support.py index 058b662bb0..2fa673b60b 100644 --- a/temporalio/nexus/system/_support.py +++ b/temporalio/nexus/system/_support.py @@ -182,12 +182,23 @@ def _timestamp(time: datetime) -> "Timestamp": return models.Timestamp(seconds=proto.seconds, nanos=proto.nanos) +class WaitCutRecords(list[typing.Any]): + """The Records of a page of Workflow code that has no Record because the read + limit of its Workflow Task ended the wait before the ``wait`` of the read. + + The page model has no field for that, and this list is equal to ``[]``. The + poll helpers read it before the caller gets the page, so a copy of the list + that the caller makes can't change the next read. + """ + + def next_read_request( request: "ReadRecordsRequest[_BodyT]", response: "ReadRecordsResponse[_BodyT]" ) -> "ReadRecordsRequest[_BodyT] | None": # A Stream has no end that a read reports. A page with no Record says that no # Record came within the wait, or at once with no wait, so the read stops there. - if not response.records: + # The read limit of a Workflow Task is not the end of the wait, so it reads again. + if not response.records and not isinstance(response.records, WaitCutRecords): return None return dataclasses.replace( request, from_offset=response.last_offset or request.from_offset diff --git a/temporalio/worker/_worker.py b/temporalio/worker/_worker.py index c03112daef..c2781460da 100644 --- a/temporalio/worker/_worker.py +++ b/temporalio/worker/_worker.py @@ -349,12 +349,14 @@ def __init__( feel the default should be changed. WARNING: This setting is experimental. stream_read_time: How long the Stream reads of a Workflow Task can - wait, from the start of the task. At that limit, a read with a wait - gives a page with no Record, and a read with no wait goes on - without holding the task until the Store answers. Defaults to half - the Workflow Task timeout. The limit is always before the heartbeat - of the task, so a read alone never makes the Worker send a - heartbeat. Appends have no such limit. + wait, from the start of the task or the end of its replay. At that + limit, a read with a wait gives a page with no Record, after which + ``read`` and ``read_pages`` read again with the whole wait. So with + a longer wait they go on until a Record comes. A read with no wait + goes on without holding the task until the Store answers. Defaults + to half the Workflow Task timeout. The limit is always before the + heartbeat of the task, so a read alone never makes the Worker send + a heartbeat. Appends have no such limit. WARNING: This setting is experimental. """ diff --git a/temporalio/worker/_workflow_streams.py b/temporalio/worker/_workflow_streams.py index 9cb98f2700..1995d2357e 100644 --- a/temporalio/worker/_workflow_streams.py +++ b/temporalio/worker/_workflow_streams.py @@ -230,14 +230,16 @@ def resolve_read( ) # A body that the converter refuses fails the Workflow Task, as a result of a # Local Activity does. - read.waiter.set_result( - temporalio.nexus.system._support.model_from_proto( - page, - read.page_type, - self._instance._context_free_payload_converter, - self._instance._context_free_failure_converter, - ) + model = temporalio.nexus.system._support.model_from_proto( + page, + read.page_type, + self._instance._context_free_payload_converter, + self._instance._context_free_failure_converter, ) + if job.page.wait_cut and not model.records: + # So `read` and `read_pages` read again where a whole wait would end them. + model.records = temporalio.nexus.system._support.WaitCutRecords() + read.waiter.set_result(model) def _error(self, failure: temporalio.api.failure.v1.Failure) -> BaseException: instance = self._instance diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py index bdaab7a369..d0742fe8ad 100644 --- a/tests/nexus/test_streams_with_worker.py +++ b/tests/nexus/test_streams_with_worker.py @@ -397,6 +397,53 @@ def append_request_ids() -> list[str | None]: ] +class _DownReadsStore(FaultStore): + """A Store whose reads fail as an outage until :py:attr:`up` is true.""" + + def __init__(self) -> None: + super().__init__() + self.up = False + + async def read_records(self, request: ReadRecordsRequest) -> Any: + if not self.up: + self.calls.append((request, None)) + raise ConnectionError("The connection is gone") + return await super().read_records(request) + + +async def test_a_store_outage_at_a_workflow_read_fails_the_workflow_task( + client: Client, +) -> None: + store = _DownReadsStore() + client = stream_client(client, store) + await (await client.create_stream(id="down", body_type=int)).append(1) + + async def back_after_a_task_failure(handle: Any, _worker: Any) -> None: + await assert_task_fail_eventually(handle) + store.up = True + + # SDK Core tries the read again up to the read limit, and then fails the task, as + # for an append. Workflow code gets no error, also on a Worker that fails a + # Workflow for any exception, and the read runs in the next task. + for failure_types in ([], [Exception]): + with failure_note(f"failure types {failure_types}"): + store.up = False + options = RunOptions( + _CallsWorkflow, + [[["read", "down"]]], + task_timeout=timedelta(seconds=2), + worker={"workflow_failure_exception_types": failure_types}, + during=back_after_a_task_failure, + ) + ran = await run(client, options) + assert ran.result == [[[1], (1).to_bytes(8, "big").hex()]] + failed = _events(ran.history, EventType.EVENT_TYPE_WORKFLOW_TASK_FAILED) + assert failed + for event in failed: + message = event.workflow_task_failed_event_attributes.failure.message + assert message.startswith("StreamStoreUnavailable:"), message + + @workflow.defn class _CatchingWorkflow: @workflow.run @@ -909,10 +956,12 @@ async def first_task() -> None: # The page of this Record gets an activation before the next Record comes. await asyncio.sleep(0.3) + # The default read limit is half the task timeout, so a read with no Record + # is cut at 3 s, and a slow host still doesn't time out the task. options = RunOptions( _LatePagesWorkflow, [how], - task_timeout=timedelta(seconds=2), + task_timeout=timedelta(seconds=6), during=write, replay=True, ) @@ -1111,11 +1160,11 @@ async def test_a_workflow_read_asks_the_store_with_its_limits(client: Client) -> stream = await client.create_stream(id="paged", body_type=int) await stream.append(1, 2, 3) - # A read with no limit asks for 256 Records and 4 MiB. The Store gets room for one - # Record more, so that SDK Core knows when the Stream has more. That Record has at - # most the Record size of the config and an offset of 1024 bytes, each in its field. - # A Store call waits no longer than the read time of the Worker, which is shorter - # than the wait of the read. + # A read with no limit asks for 256 Records and 4 MiB. SDK Core asks the Store for + # room for one Record more, since it acts on whether the Stream has more. That + # Record has at most the Record size of the config and an offset of 1024 bytes, + # each in its field. A Store call waits no longer than the read time of the + # Worker, which is shorter than the wait of the read. def field(size: int) -> int: return 1 + (size.bit_length() + 6) // 7 + size @@ -1133,13 +1182,22 @@ def field(size: int) -> int: ["paged", limits], worker={"stream_read_time": read_time}, ) - assert (await run(client, options)).result == [1, 2, 3] + ran = await run(client, options) + assert ran.result == [1, 2, 3] reads = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] asked = [(r.max_records, r.max_bytes) for r in reads] # With one Record in a page, the read of each Record is one Store call. assert asked == [expected] * (3 if limits else 1) waits = [r.wait.ToTimedelta() for r in reads] assert timedelta(0) < waits[0] and max(waits) <= read_time + # A replay asks for the Records that History recorded, and no more. + store.calls.clear() + await Replayer( + workflows=[_ReadAllWorkflow], + stream_config=client._config["stream_config"], + ).replay_workflow(ran.history) + replayed = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] + assert [r.max_records for r in replayed] == ([1] * 3 if limits else [3]) @workflow.defn @@ -1195,6 +1253,50 @@ async def first_task() -> None: assert (await run(client, options)).result == [1, 2] +@workflow.defn +class _FirstRecordWorkflow: + @workflow.signal + def wake(self) -> None: + pass + + @workflow.run + async def run(self, stream_id: str) -> list[int]: + stream = workflow.get_stream(StreamRef[int](id=stream_id)) + async for record in stream.read(wait=timedelta(seconds=5)): + return [record.body] + return [] + + +async def test_a_workflow_read_goes_on_after_the_read_limit_cut_its_wait( + client: Client, +) -> None: + store = FaultStore() + client = stream_client(client, store) + stream = await client.create_stream(id="cut", body_type=int) + + async def write(handle: Any, _worker: Any) -> None: + async def cut_page() -> None: + history = await handle.fetch_history() + markers = _stream_markers(history, "read") + assert any(b'"wait_cut":true' in m.SerializeToString() for m in markers) + assert _events(history, EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED) + + # The read limit cuts the wait of 5 s at 1 s. The iterator reads again, and + # that read waits for the next task, which a Signal opens. + await assert_eventually(cut_page) + await stream.append(1) + await handle.signal(_FirstRecordWorkflow.wake) + + options = RunOptions( + _FirstRecordWorkflow, + ["cut"], + worker={"stream_read_time": timedelta(seconds=1)}, + during=write, + replay=True, + ) + assert (await run(client, options)).result == [1] + + async def test_a_workflow_read_with_no_wait_reads_again_in_the_next_task( client: Client, ) -> None: diff --git a/tests/testing/test_stream_store.py b/tests/testing/test_stream_store.py index a97233acc0..059deac265 100644 --- a/tests/testing/test_stream_store.py +++ b/tests/testing/test_stream_store.py @@ -393,6 +393,35 @@ async def script(rng: random.Random) -> None: run_with_virtual_clock(script(random.Random(seed))) +async def test_a_store_call_of_the_bridge_gives_the_store_the_caps_of_the_read() -> ( + None +): + asked: list[ReadRecordsRequest] = [] + + class Asked(_MemoryStreams): + async def read_records( + self, request: ReadRecordsRequest + ) -> ReadRecordsResponse: + asked.append(request) + return await super().read_records(request) + + streams = Asked("memory", retention=timedelta(days=1), resend_window=1, fence=False) + await streams.create_stream(CreateStreamRequest(stream_id=_S), request_id="c") + await streams.append_records(_client_append(), request_id="a") + await streams.append_records(_client_append(), request_id="b") + read = ReadRecordsRequest(stream_id=_S, max_records=1, max_bytes=100) + answer = await call_stream_store( + Runtime.default()._core_runtime, + _StoreCaller(lambda: streams), + "ReadRecords", + read.SerializeToString(), + ) + # Only SDK Core asks for one Record more, since only it acts on whether the + # Stream has more after the page. Client and Activity code don't. + assert asked == [read] + assert len(ReadRecordsResponse.FromString(answer).records) == 1 + + async def test_a_dropped_store_call_never_reaches_the_store() -> None: asked: list[str] = [] diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py index 5dd9fff964..6c8e330ae5 100644 --- a/tests/worker/test_workflow_streams.py +++ b/tests/worker/test_workflow_streams.py @@ -1004,3 +1004,80 @@ def run_handler() -> None: # An eviction sends no command, also for the reads whose readers it cancels. evict = WorkflowActivationJob(remove_from_cache=RemoveFromCache()) assert not (await _activate(instance, evict)).successful.commands + + +@workflow.defn +class _ReadToTheEndWorkflow: + @workflow.run + async def run(self, how: str) -> list[Any]: + stream = workflow.get_stream(ModelRef[int](id="s", store="a")) + wait = timedelta(seconds=5) + if how == "read_page": + page = await stream.read_page(wait=wait) + return [page.records, page.last_offset] + if how == "read": + return [record.body async for record in stream.read(wait=wait)] + pages = stream.read_pages(wait=wait) + return [[record.body for record in page.records] async for page in pages] + + +async def test_a_read_goes_on_after_a_page_that_the_read_limit_cut() -> None: + converter = temporalio.converter.DefaultPayloadConverter() + + def read(seq: int, after: int) -> WorkflowCommand: + command = ReadStream( + seq=seq, + stream=StreamRef(id="s", store="a"), + from_offset=_offset(after), + wait=Duration(seconds=5), + ) + return WorkflowCommand(read_stream=command) + + def page( + seq: int, records: Sequence[int], last: int, wait_cut: bool = False + ) -> WorkflowActivationJob: + stream_page = StreamPage( + records=[ + StreamRecord(offset=_offset(number), body=converter.to_payload(number)) + for number in records + ], + last_offset=_offset(last), + wait_cut=wait_cut, + ) + job = ResolveStreamRead(seq=seq, page=stream_page) + return WorkflowActivationJob(resolve_stream_read=job) + + def start(how: str) -> WorkflowActivationJob: + arguments = [converter.to_payload(how)] + return WorkflowActivationJob( + initialize_workflow=InitializeWorkflow(arguments=arguments) + ) + + def result(completion: WorkflowActivationCompletion) -> Any: + [complete] = completion.successful.commands + return converter.from_payload(complete.complete_workflow_execution.result) + + config = StreamConfig([MemoryStreamStore(name="a")]) + # A single read gives the cut page as it is, with no Record. + instance = _new_instance(_ReadToTheEndWorkflow, config) + completion = await _activate(instance, start("read_page")) + assert list(completion.successful.commands) == [read(1, 0)] + assert result(await _activate(instance, page(1, [], 0, wait_cut=True))) == [ + [], + None, + ] + + for how in ("read", "read_pages"): + with failure_note(how): + instance = _new_instance(_ReadToTheEndWorkflow, config) + completion = await _activate(instance, start(how)) + assert list(completion.successful.commands) == [read(1, 0)] + completion = await _activate(instance, page(1, [1], 1)) + assert list(completion.successful.commands) == [read(2, 1)] + # The read limit of the task ended this wait, so the reader reads again. + completion = await _activate(instance, page(2, [], 1, wait_cut=True)) + assert list(completion.successful.commands) == [read(3, 1)] + # A page with no Record after the whole wait ends the reader. + completion = await _activate(instance, page(3, [], 1)) + expected = [1] if how == "read" else [[1], [], []] + assert result(completion) == expected From 0811eff608ba327d4dbb4e9204610bb3a2b75c10 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Wed, 25 Nov 2026 17:32:07 -0700 Subject: [PATCH 27/50] Pin Core to the Streams stack with main merged Each Streams PR of Core now has upstream main merged in. The bridge lock adds nexus-rpc and percent-encoding, which main's Core needs. The proto regen changes nothing. --- temporalio/bridge/Cargo.lock | 49 ++++++++++++++++++++++++++++++++++++ temporalio/bridge/sdk-core | 2 +- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/temporalio/bridge/Cargo.lock b/temporalio/bridge/Cargo.lock index d64fad2906..120dfe8236 100644 --- a/temporalio/bridge/Cargo.lock +++ b/temporalio/bridge/Cargo.lock @@ -1383,6 +1383,29 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" +[[package]] +name = "nexus-rpc" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6bd72bb0b8a558f1ad4e6502a47d6db0c07b93902a11d7f806f8791b6b14f7b" +dependencies = [ + "nexus-rpc-macros", + "serde", + "thiserror", +] + +[[package]] +name = "nexus-rpc-macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be6dc5d7783ce0428a2baf74d82bd816f8e9fb30543ff07a9e0e0556e6839dd9" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "nix" version = "0.32.0" @@ -1727,6 +1750,15 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -2742,6 +2774,7 @@ dependencies = [ "derive_more", "erased-serde", "futures", + "nexus-rpc", "parking_lot", "prost", "prost-wkt-types", @@ -2772,6 +2805,7 @@ dependencies = [ "http", "pbjson", "pbjson-build", + "percent-encoding", "prost", "prost-wkt-types", "serde", @@ -2981,6 +3015,18 @@ dependencies = [ "serde_core", ] +[[package]] +name = "toml_edit" +version = "0.25.19+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + [[package]] name = "toml_parser" version = "1.1.6+spec-1.1.0" @@ -3681,6 +3727,9 @@ name = "winnow" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] [[package]] name = "wit-bindgen" diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index 7903bf16cc..e6da892e30 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit 7903bf16ccfeded019b6d91806dbaaba6bc97c55 +Subproject commit e6da892e30d597ad236f1dd6db6e3bb40690b098 From 804dd7e1f4437eea4d3fd4365c34db3ebef8bbf9 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Wed, 25 Nov 2026 17:48:52 -0700 Subject: [PATCH 28/50] Start a Workflow Stream call by the name of its Store A plain function of the SDK takes the name of the chosen Store and starts the call. An append or a read goes to Core, and a create or a describe runs as the SDK's Local Activity. The Store has no hook for it. --- temporalio/client/_stream_store.py | 25 +----- temporalio/worker/_workflow_streams.py | 111 ++++++++++++------------ tests/worker/test_workflow_streams.py | 113 +++++++++++-------------- 3 files changed, 106 insertions(+), 143 deletions(-) diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 8a15e2e1a8..bd1c77383d 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -9,7 +9,7 @@ from collections.abc import Callable, Sequence from dataclasses import dataclass, field from datetime import timedelta -from typing import TYPE_CHECKING, Any +from typing import Any import google.protobuf.message import nexusrpc @@ -42,9 +42,6 @@ from temporalio.exceptions import StreamError from temporalio.nexus.system.stream_service import StreamService -if TYPE_CHECKING: - import temporalio.worker._workflow_streams - logger = logging.getLogger(__name__) _definition = nexusrpc.get_service_definition(StreamService) @@ -213,26 +210,6 @@ async def describe_stream( """ raise NotImplementedError - def _start_workflow_call( - self, - streams: temporalio.worker._workflow_streams._WorkflowStreams, - operation: str, - request: google.protobuf.message.Message, - result_type: Any, - ) -> asyncio.Future[Any]: - """Start a Stream call of Workflow code on this Store, and return the - future of its result. - - ``request`` is the SDK request of the call, with its ref, and - ``result_type`` is the type of the call's result. The SDK calls this in the - event loop of the Workflow, once per call, after it chose this Store and - before any command of the call. A replay calls it again, so it must take - the path of the first run for the same call. The default makes an append - or a read a command of SDK Core, and runs a create or a describe in a - Local Activity of the SDK. - """ - return streams._start_by_default(self, operation, request, result_type) - @dataclass(frozen=True) class StreamSelectContext: diff --git a/temporalio/worker/_workflow_streams.py b/temporalio/worker/_workflow_streams.py index 1995d2357e..50b0ad16f0 100644 --- a/temporalio/worker/_workflow_streams.py +++ b/temporalio/worker/_workflow_streams.py @@ -60,10 +60,10 @@ class _Read: class _WorkflowStreams: # pyright: ignore[reportUnusedClass] """The Stream calls of one Workflow instance. - Each call first gets its Store, and the Store starts the call. By default an - append and a read are commands of SDK Core, which makes the Store calls and - gives each result in a job. Core has no command for a create or a describe, so - those run in a Local Activity of the SDK. + Each call first gets its Store, and :py:func:`_start_call` then starts it on + that Store. An append and a read are commands of SDK Core, which makes the + Store calls and gives each result in a job. Core has no command for a create or + a describe, so those run in a Local Activity of the SDK. """ def __init__(self, instance: _WorkflowInstanceImpl) -> None: @@ -105,10 +105,9 @@ def start( "Cannot read a Stream with no body type. Give get_stream a " "body_type, or a StreamRef with a type argument." ) + store = self._store(_request_ref(request)).name() # The future of the job of the call, or the task of its Local Activity - result = self._store(_request_ref(request))._start_workflow_call( - self, operation, request, result_type - ) + result = _start_call(self, store, operation, request, result_type) async def call() -> OutputT: # `asyncio.wait` ends at a cancel of this task. `await result` would pass the @@ -156,49 +155,6 @@ def _store(self, ref: sdk.StreamRef) -> StreamStore: except Exception as err: raise self._fail_task(err) - def _start_by_default( - self, - store: StreamStore, - operation: str, - request: google.protobuf.message.Message, - result_type: Any, - ) -> asyncio.Future[Any]: - """Start a call on ``store`` as a command of SDK Core, or in the SDK's - Local Activity for a create or a describe. This is the default of - :py:meth:`StreamStore._start_workflow_call`. - """ - instance = self._instance - stream = sdk.StreamRef(id=_request_ref(request).id, store=store.name()) - 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 = self._appends[seq] = instance.create_future() - return result - if isinstance(request, sdk.ReadRecordsRequest): - seq = instance._next_seq("stream_read") - instance._add_command().read_stream.CopyFrom( - temporalio.bridge.proto.workflow_commands.ReadStream( - seq=seq, - stream=stream, - from_offset=request.from_offset, - wait=request.wait if request.HasField("wait") else None, - max_records=request.max_records, - max_bytes=request.max_bytes, - ) - ) - result = instance.create_future() - self._reads[seq] = _Read(result, result_type) - return result - # Each run of a chain sends the same id, so a Store answers the create of a - # later run as the create that made the Stream. - request_id = None - if isinstance(request, sdk.CreateStreamRequest): - request_id = instance._info.first_execution_run_id - return self._schedule_store_call(store, operation, request, request_id) - def resolve_append( self, job: temporalio.bridge.proto.workflow_activation.ResolveStreamAppend ) -> None: @@ -251,19 +207,19 @@ def _error(self, failure: temporalio.api.failure.v1.Failure) -> BaseException: def _schedule_store_call( self, - store: StreamStore, + store: str, operation: str, request: google.protobuf.message.Message, request_id: str | None, ) -> asyncio.Future[Any]: - """Schedule the SDK's Local Activity for a create or a describe on - ``store``. + """Schedule the SDK's Local Activity for a create or a describe on the + Store named ``store``. """ instance = self._instance activity = instance._outbound.start_local_activity( StartLocalActivityInput( activity=_STORE_CALL_ACTIVITY, - args=(operation, store.name(), request.SerializeToString(), request_id), + 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. @@ -335,6 +291,53 @@ def _stream_config(self) -> StreamConfig | None: )() +def _start_call( + streams: _WorkflowStreams, + store: str, + operation: str, + request: google.protobuf.message.Message, + result_type: Any, +) -> asyncio.Future[Any]: + """Start a Stream call of Workflow code on the Store named ``store``, and return + the future of its result. + + An append or a read is a command of SDK Core. A create or a describe runs in + the SDK's Local Activity. ``request`` is the SDK request of the call, with its + ref, and ``result_type`` is the type of the call's result. + """ + 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 + if isinstance(request, sdk.ReadRecordsRequest): + seq = instance._next_seq("stream_read") + instance._add_command().read_stream.CopyFrom( + temporalio.bridge.proto.workflow_commands.ReadStream( + seq=seq, + stream=stream, + from_offset=request.from_offset, + wait=request.wait if request.HasField("wait") else None, + max_records=request.max_records, + max_bytes=request.max_bytes, + ) + ) + result = instance.create_future() + streams._reads[seq] = _Read(result, result_type) + return result + # Each run of a chain sends the same id, so a Store answers the create of a + # later run as the create that made the Stream. + 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]): """Handle of a Stream call, which a task of the Workflow instance runs.""" diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py index 6c8e330ae5..a636b892ae 100644 --- a/tests/worker/test_workflow_streams.py +++ b/tests/worker/test_workflow_streams.py @@ -626,27 +626,13 @@ def selector(context: StreamSelectContext) -> StreamStore: assert (await _activate(instance, evict)).HasField("successful") -class _OwnPath: - """The calls of :py:class:`_EachCallWorkflow`, and what its Stores saw.""" +class _EachCall: + """The calls of :py:class:`_EachCallWorkflow`, and what its selector saw.""" operations: list[str] = [] - selects: list[str] = [] - """The Stream id of each selector call.""" - started: list[tuple[str, int]] = [] - """Each call that :py:class:`_OwnPathStore` started, with the number of selector - calls before it.""" - - -class _OwnPathStore(MemoryStreamStore): - """A Store that runs each Stream call of Workflow code itself, with no command - and no Local Activity, as a Store that SDK Core doesn't call would. - """ - - def _start_workflow_call( - self, streams: Any, operation: str, request: Message, result_type: Any - ) -> asyncio.Future[Any]: - _OwnPath.started.append((operation, len(_OwnPath.selects))) - return asyncio.get_running_loop().create_future() + instance: _WorkflowInstanceImpl | None = None + selects: list[tuple[str, int]] = [] + """The Stream id of each selector call, with the number of commands before it.""" @workflow.defn @@ -654,7 +640,7 @@ class _EachCallWorkflow: @workflow.run async def run(self) -> None: calls: list[Any] = [] - for at, operation in enumerate(_OwnPath.operations): + for at, operation in enumerate(_EachCall.operations): stream = workflow.get_stream(ModelRef[int](id=f"s{at}")) if operation == "create": calls.append(workflow.create_stream(id=f"s{at}", body_type=int)) @@ -677,67 +663,64 @@ async def run(self) -> None: await asyncio.gather(*tasks, return_exceptions=True) -async def test_the_store_of_a_call_is_chosen_once_and_runs_the_call() -> None: +async def test_the_store_of_a_call_is_chosen_before_its_command() -> None: operations = ["create", "append", "read", "describe"] - # The variant of the command that the default path sends for each operation - variants = { - "create": "schedule_local_activity", - "append": "append_to_stream", - "read": "read_stream", - "describe": "schedule_local_activity", - } - own, default = _OwnPathStore(name="own"), MemoryStreamStore(name="default") - for owned in range(2 ** len(operations)): - # Bit `at` of `owned` gives call `at` to the Store that runs it itself. - on_own = [bool(owned >> at & 1) for at in range(len(operations))] + converter = temporalio.converter.DefaultPayloadConverter() + + def store_of(command: WorkflowCommand) -> str: + variant = command.WhichOneof("variant") + if variant == "append_to_stream": + return command.append_to_stream.stream.store + if variant == "read_stream": + return command.read_stream.stream.store + # The Local Activity of a create or a describe has the Store name second. + [_, store, *_] = command.schedule_local_activity.arguments + return converter.from_payload(store, str) + + a, b = MemoryStreamStore(name="a"), MemoryStreamStore(name="b") + for mask in range(2 ** len(operations)): + # Bit `at` of `mask` gives call `at` to Store b. + on_b = [bool(mask >> at & 1) for at in range(len(operations))] def selector(context: StreamSelectContext) -> StreamStore: - _OwnPath.selects.append(context.id) - return own if on_own[int(context.id[1:])] else default + assert _EachCall.instance + sent = _EachCall.instance._current_completion.successful.commands + _EachCall.selects.append((context.id, len(sent))) + return b if on_b[int(context.id[1:])] else a - config = StreamConfig([own, default], store_selector=selector) - _OwnPath.operations = operations + config = StreamConfig([a, b], store_selector=selector) + _EachCall.operations = operations for replaying in (False, True): - with failure_note(f"owned {on_own}, replaying {replaying}"): - _OwnPath.selects, _OwnPath.started = [], [] - instance = _new_instance(_EachCallWorkflow, config) + with failure_note(f"on b {on_b}, replaying {replaying}"): + _EachCall.selects = [] + instance = _EachCall.instance = _new_instance(_EachCallWorkflow, config) initialize = WorkflowActivationJob( initialize_workflow=InitializeWorkflow() ) completion = await _activate(instance, initialize, replaying=replaying) - # The selector runs once for each call, before the Store starts it. - ids = [f"s{at}" for at in range(len(operations))] - assert _OwnPath.selects == ids - assert _OwnPath.started == [ - (f"{name.capitalize()}{suffix}", at + 1) - for at, (name, suffix, mine) in enumerate( - zip( - operations, - ["Stream", "Records", "Records", "Stream"], - on_own, - ) - ) - if mine + # The selector runs once for each call, before the command of the call. + assert _EachCall.selects == [ + (f"s{at}", at) for at in range(len(operations)) ] - # A call on the Store that runs it itself sends no command. A cancel - # sends a command only for a Local Activity of the default path. - sent = [ - variants[name] for name, mine in zip(operations, on_own) if not mine + commands = completion.successful.commands + assert [command.WhichOneof("variant") for command in commands] == [ + "schedule_local_activity", + "append_to_stream", + "read_stream", + "schedule_local_activity", + # A cancel sends a command only for a Local Activity. + "request_cancel_local_activity", + "request_cancel_local_activity", + "complete_workflow_execution", ] - cancels = [ - "request_cancel_local_activity" - for variant in sent - if variant == "schedule_local_activity" + assert [store_of(command) for command in commands[:4]] == [ + "b" if mine else "a" for mine in on_b ] - assert [ - command.WhichOneof("variant") - for command in completion.successful.commands - ] == [*sent, *cancels, "complete_workflow_execution"] async def test_a_stream_call_with_no_stream_config_fails_the_task() -> None: for operation in ["create", "append", "read", "describe"]: - _OwnPath.operations = [operation] + _EachCall.operations = [operation] for replaying in (False, True): instance = _new_instance(_EachCallWorkflow) initialize = WorkflowActivationJob(initialize_workflow=InitializeWorkflow()) From 15f578ae57cb0c9c1eb67cba2b06147acf13f6d6 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Wed, 25 Nov 2026 17:52:12 -0700 Subject: [PATCH 29/50] Read on after a Workflow page with no Record In Workflow code, read() and read_pages() never end at a page with no Record, so Workflow code decides when to stop. Client and Activity readers still stop there, and read_page() gives the page as it is. --- changelog/added/steady-stream-heron.md | 2 +- temporalio/client/_stream_store.py | 14 ++++--- temporalio/contrib/streams/README.md | 27 ++++++++------ temporalio/nexus/system/_support.py | 21 ++++------- temporalio/worker/_worker.py | 10 ++--- temporalio/worker/_workflow_streams.py | 16 ++++---- tests/nexus/test_streams_with_worker.py | 17 +++++++-- tests/worker/test_workflow_streams.py | 49 +++++++++++++++---------- 8 files changed, 88 insertions(+), 68 deletions(-) diff --git a/changelog/added/steady-stream-heron.md b/changelog/added/steady-stream-heron.md index b06de02410..12bd4733ff 100644 --- a/changelog/added/steady-stream-heron.md +++ b/changelog/added/steady-stream-heron.md @@ -1,5 +1,5 @@ Add experimental `temporalio.client.StreamStore`, the base class of a Stream Store, and `temporalio.testing.MemoryStreamStore`, a Store that keeps its Streams in memory for tests and local runs. A Store gets the requests of `temporalio.api.streamservice.v1`, which have the Stream id, and the request id of each create and each append as `request_id`. A create returns only `created`, and the SDK gives the caller the ref with the name of the Store. A Stream has no close, and it expires when the Retention of its Store has passed since its create or its last append that wrote a batch. Add experimental Streams for client and Activity code. `stream_config=StreamConfig(stores=[...])` of `Client.connect` gives a client its Stream Stores, and `Client.create_stream` and `Client.get_stream` return a `Stream` to append to, read and describe. A failed call raises `temporalio.exceptions.StreamError` with a `reason`. `max_record_bytes`, `max_batch_bytes` and `max_batch_records` of `StreamConfig` bound an append, and one over a limit fails before its Store gets it. A read of a Stream from `get_stream` needs `body_type=` or a `StreamRef` with a type argument, and raises `TypeError` with neither. `Stream.read` stops at the first page with no Record, so a read with no wait reads to the newest Record, and a read with a wait stops once no Record came within the wait. `temporalio.contrib.streams.current_producer` gives the Producer of an Activity attempt, and `as_producer` gives back one that code stored. Add experimental Streams for Workflow code. `workflow.create_stream` and `workflow.get_stream` return a `Stream` to append to, read and describe on the Stream Stores of the Worker's client, and `Replayer(stream_config=...)` gives a replay its Stores. The SDK chooses the Store of each call before the call starts, also in a replay. It calls the `store_selector` only for a ref with no Store name, in Workflow code for each such call, also for a create and a describe, and again in a replay. So the selector must return the same Store for the same call, must not block or do I/O, and must be safe to call from more than one thread. -Add experimental Stream reads for Workflow code. `Stream.read`, `read_pages` and `read_page` of a Workflow `Stream` give the Records as they come, a replay reads them again from the Store, and `temporalio.workflow.StreamReplayError` in the failure exception types of a Worker or a Workflow fails the Workflow when the Store no longer has them. The Worker option `stream_read_time` sets how long the reads of a Workflow Task can wait, and a read with a wait gives a page with no Record at that limit, after which `read` and `read_pages` read again with the whole wait, so with a wait that the limit cuts they go on until a Record comes. A read with no wait gives the answer of the Store, which can be a page with no Record, and an outage of the Store at a read fails the Workflow Task. +Add experimental Stream reads for Workflow code. `Stream.read`, `read_pages` and `read_page` of a Workflow `Stream` give the Records as they come, a replay reads them again from the Store, and `temporalio.workflow.StreamReplayError` in the failure exception types of a Worker or a Workflow fails the Workflow when the Store no longer has them. The Worker option `stream_read_time` sets how long the reads of a Workflow Task can wait, and a read with a wait gives a page with no Record at that limit. In Workflow code, `read` and `read_pages` never end at a page with no Record and read again, also in later Workflow Tasks, so Workflow code decides when to stop. Each page is a read result in History, so an iterator needs a long wait. A read with no wait gives the answer of the Store, which can be a page with no Record, and an outage of the Store at a read fails the Workflow Task. Add experimental `temporalio.contrib.streams.BufferedAppender`, which batches the appends of one Stream in client and Activity code. `append` returns immediately, a batch waits at most `max_delay`, one write runs at a time, and `async with` or `flush()` writes what is left. diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index bd1c77383d..7f78bce934 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -273,11 +273,15 @@ class StreamConfig: - A read with a ``wait`` and no Record to give waits up to its ``wait``, but at most to the read limit of its Workflow Task, which the Worker option ``stream_read_time`` sets. At that limit ``read_page`` gives a page with no - Record. ``read_pages`` yields that page and reads again from its offset, - and so does ``read``. Each read waits its whole ``wait`` again. So with a - ``wait`` that the read limit cuts, they go on until a Record comes, also - over more than one Workflow Task. To stop at a time, call ``read_page`` - in a loop that checks ``workflow.now()``. + Record. + - ``read`` and ``read_pages`` never end at a page with no Record. + ``read_pages`` yields that page, and both read again from its offset. So + they go on until a Record comes, also over more than one Workflow Task. + Workflow code decides when to stop, for example with a ``break``, its own + timer, a Signal or an Activity. Each page is a read result in History. With + no ``wait`` or a short one, an iterator on a Stream with no new Record + gets page after page with no Record, and History grows fast. So give an + iterator a long ``wait``. - A read holds its Workflow Task up to the read limit. A Signal that comes meanwhile waits until the read has its page, or until that limit. A command for the server waits only for one Store call with no wait for each diff --git a/temporalio/contrib/streams/README.md b/temporalio/contrib/streams/README.md index df60f3ed60..aa224a0dea 100644 --- a/temporalio/contrib/streams/README.md +++ b/temporalio/contrib/streams/README.md @@ -55,22 +55,25 @@ no body type. Pass `body_type=`, or a ref with a type argument such as `StreamRe A Stream from `create_stream` reads any body with no type. A Stream has no end that a read reports, so a reader stops at the application's own last Record. -`read()` stops at the first page with no Record. With no `wait` it reads to the newest Record, and -with a `wait` it stops once no Record came within the wait. It reads a page only when the caller -asks for the next Record, so a reader that stops at its last Record leaves no read open. +In client and Activity code, `read()` stops at the first page with no Record. With no `wait` it +reads to the newest Record, and with a `wait` it stops once no Record came within the wait. It +reads a page only when the caller asks for the next Record, so a reader that stops at its last +Record leaves no read open. In Workflow code, a read with no `wait` gives the answer of the Store, which can be a page with no Record. A read with a `wait` and no Record to give waits up to its `wait`, but at most to the read limit of its Workflow Task (the Worker option `stream_read_time`). At that limit `read_page` gives -a page with no Record. `read_pages()` yields that page and reads again from its offset, and so -does `read()`. Each read waits its whole `wait` again, so with a `wait` that the read limit cuts, -they go on until a Record comes, also over more than one Workflow Task. To stop at a time, call -`read_page` in a loop that checks `workflow.now()`. A read with a `wait` that has no Record when -its task completes starts again in the next task. It asks for a new Workflow Task only when the -Stream has more Records for it, so a read of an idle Stream makes no task. An outage of the Store -fails the Workflow Task, and Workflow code gets no error. A replay reads the Records again from the -Store, so the Retention of the Stream must cover the life of the Workflow and the time in which it -gets queries. +a page with no Record. `read()` and `read_pages()` never end at a page with no Record. +`read_pages()` yields that page, and both read again from its offset. So they go on until a Record +comes, also over more than one Workflow Task. Workflow code decides when to stop, for example with +a `break`, its own timer, a Signal or an Activity. Each page is a read result in History, so give +an iterator a long `wait`. With no `wait` or a short one, an iterator on a Stream with no new +Record gets page after page with no Record, and History grows fast. A read with a `wait` that has +no Record when its task completes starts again in the next task. It asks for a new Workflow Task +only when the Stream has more Records for it, so a read of an idle Stream makes no task. An outage +of the Store fails the Workflow Task, and Workflow code gets no error. A replay reads the Records +again from the Store, so the Retention of the Stream must cover the life of the Workflow and the +time in which it gets queries. In Workflow code, a read with no `max_records` gives at most 256 Records in a page, and a read with no `max_bytes` at most 4 MiB of them. A page has at most 16 MiB of Records, also for a larger diff --git a/temporalio/nexus/system/_support.py b/temporalio/nexus/system/_support.py index 2fa673b60b..12b7cc57a5 100644 --- a/temporalio/nexus/system/_support.py +++ b/temporalio/nexus/system/_support.py @@ -182,23 +182,16 @@ def _timestamp(time: datetime) -> "Timestamp": return models.Timestamp(seconds=proto.seconds, nanos=proto.nanos) -class WaitCutRecords(list[typing.Any]): - """The Records of a page of Workflow code that has no Record because the read - limit of its Workflow Task ended the wait before the ``wait`` of the read. - - The page model has no field for that, and this list is equal to ``[]``. The - poll helpers read it before the caller gets the page, so a copy of the list - that the caller makes can't change the next read. - """ - - def next_read_request( request: "ReadRecordsRequest[_BodyT]", response: "ReadRecordsResponse[_BodyT]" ) -> "ReadRecordsRequest[_BodyT] | None": - # A Stream has no end that a read reports. A page with no Record says that no - # Record came within the wait, or at once with no wait, so the read stops there. - # The read limit of a Workflow Task is not the end of the wait, so it reads again. - if not response.records and not isinstance(response.records, WaitCutRecords): + from temporalio.workflow import in_workflow + + # A Stream has no end that a read reports. In client and Activity code, a page + # with no Record says that no Record came within the wait, or at once with no + # wait, so the read stops there. Workflow code decides itself when it stops, + # since a read that waits goes on in later Workflow Tasks. + if not response.records and not in_workflow(): return None return dataclasses.replace( request, from_offset=response.last_offset or request.from_offset diff --git a/temporalio/worker/_worker.py b/temporalio/worker/_worker.py index c2781460da..c0552bb234 100644 --- a/temporalio/worker/_worker.py +++ b/temporalio/worker/_worker.py @@ -350,11 +350,11 @@ def __init__( WARNING: This setting is experimental. stream_read_time: How long the Stream reads of a Workflow Task can wait, from the start of the task or the end of its replay. At that - limit, a read with a wait gives a page with no Record, after which - ``read`` and ``read_pages`` read again with the whole wait. So with - a longer wait they go on until a Record comes. A read with no wait - goes on without holding the task until the Store answers. Defaults - to half the Workflow Task timeout. The limit is always before the + limit, a read with a wait gives a page with no Record. ``read`` and + ``read_pages`` never end at a page with no Record, and read again + with the whole wait, also in a later task. A read with no wait goes + on without holding the task until the Store answers. Defaults to + half the Workflow Task timeout. The limit is always before the heartbeat of the task, so a read alone never makes the Worker send a heartbeat. Appends have no such limit. WARNING: This setting is experimental. diff --git a/temporalio/worker/_workflow_streams.py b/temporalio/worker/_workflow_streams.py index 50b0ad16f0..7795afcd81 100644 --- a/temporalio/worker/_workflow_streams.py +++ b/temporalio/worker/_workflow_streams.py @@ -186,16 +186,14 @@ def resolve_read( ) # A body that the converter refuses fails the Workflow Task, as a result of a # Local Activity does. - model = temporalio.nexus.system._support.model_from_proto( - page, - read.page_type, - self._instance._context_free_payload_converter, - self._instance._context_free_failure_converter, + read.waiter.set_result( + temporalio.nexus.system._support.model_from_proto( + page, + read.page_type, + self._instance._context_free_payload_converter, + self._instance._context_free_failure_converter, + ) ) - if job.page.wait_cut and not model.records: - # So `read` and `read_pages` read again where a whole wait would end them. - model.records = temporalio.nexus.system._support.WaitCutRecords() - read.waiter.set_result(model) def _error(self, failure: temporalio.api.failure.v1.Failure) -> BaseException: instance = self._instance diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py index d0742fe8ad..e3f4d49af7 100644 --- a/tests/nexus/test_streams_with_worker.py +++ b/tests/nexus/test_streams_with_worker.py @@ -204,7 +204,13 @@ async def run(self, stream_id: str) -> str: ) stream = workflow.get_stream(StreamRef[Any](id=stream_id)) await stream.append(*_bodies("workflow")) - return _digest([record.body async for record in stream.read()]) + bodies: list[Any] = [] + async for record in stream.read(): + bodies.append(record.body) + # A Stream has no end, so the reader stops at the Records of the 3 writers. + if len(bodies) == 3 * len(_bodies("workflow")): + break + return _digest(bodies) async def test_a_body_reads_the_same_on_every_path(client: Client) -> None: @@ -1054,7 +1060,12 @@ def go_on(self) -> None: @workflow.run async def run(self, stream_id: str) -> list[int]: stream = workflow.get_stream(StreamRef[int](id=stream_id)) - bodies = [record.body async for record in stream.read()] + bodies: list[int] = [] + async for record in stream.read(): + bodies.append(record.body) + # A Stream has no end, so the reader stops at the writer's last Record. + if record.body == 3: + break await workflow.wait_condition(lambda: self._go_on) return bodies @@ -1264,7 +1275,7 @@ async def run(self, stream_id: str) -> list[int]: stream = workflow.get_stream(StreamRef[int](id=stream_id)) async for record in stream.read(wait=timedelta(seconds=5)): return [record.body] - return [] + raise AssertionError("A Workflow reader never ends by itself") async def test_a_workflow_read_goes_on_after_the_read_limit_cut_its_wait( diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py index a636b892ae..dd2ee8d08b 100644 --- a/tests/worker/test_workflow_streams.py +++ b/tests/worker/test_workflow_streams.py @@ -990,7 +990,7 @@ def run_handler() -> None: @workflow.defn -class _ReadToTheEndWorkflow: +class _ReadToTwoWorkflow: @workflow.run async def run(self, how: str) -> list[Any]: stream = workflow.get_stream(ModelRef[int](id="s", store="a")) @@ -998,13 +998,22 @@ async def run(self, how: str) -> list[Any]: if how == "read_page": page = await stream.read_page(wait=wait) return [page.records, page.last_offset] + # A Stream has no end, so the reader stops at the writer's last Record, 2. + found: list[Any] = [] if how == "read": - return [record.body async for record in stream.read(wait=wait)] - pages = stream.read_pages(wait=wait) - return [[record.body for record in page.records] async for page in pages] - - -async def test_a_read_goes_on_after_a_page_that_the_read_limit_cut() -> None: + async for record in stream.read(wait=wait): + found.append(record.body) + if record.body == 2: + break + return found + async for page in stream.read_pages(wait=wait): + found.append([record.body for record in page.records]) + if 2 in found[-1]: + break + return found + + +async def test_a_read_goes_on_after_a_page_with_no_record() -> None: converter = temporalio.converter.DefaultPayloadConverter() def read(seq: int, after: int) -> WorkflowCommand: @@ -1041,26 +1050,28 @@ def result(completion: WorkflowActivationCompletion) -> Any: return converter.from_payload(complete.complete_workflow_execution.result) config = StreamConfig([MemoryStreamStore(name="a")]) - # A single read gives the cut page as it is, with no Record. - instance = _new_instance(_ReadToTheEndWorkflow, config) - completion = await _activate(instance, start("read_page")) - assert list(completion.successful.commands) == [read(1, 0)] - assert result(await _activate(instance, page(1, [], 0, wait_cut=True))) == [ - [], - None, - ] + # A single read gives a page with no Record as it is, also a cut one. + for wait_cut in (True, False): + with failure_note(f"wait_cut {wait_cut}"): + instance = _new_instance(_ReadToTwoWorkflow, config) + completion = await _activate(instance, start("read_page")) + assert list(completion.successful.commands) == [read(1, 0)] + completion = await _activate(instance, page(1, [], 0, wait_cut=wait_cut)) + assert result(completion) == [[], None] for how in ("read", "read_pages"): with failure_note(how): - instance = _new_instance(_ReadToTheEndWorkflow, config) + instance = _new_instance(_ReadToTwoWorkflow, config) completion = await _activate(instance, start(how)) assert list(completion.successful.commands) == [read(1, 0)] completion = await _activate(instance, page(1, [1], 1)) assert list(completion.successful.commands) == [read(2, 1)] - # The read limit of the task ended this wait, so the reader reads again. + # A page with no Record doesn't end the reader, whether the read limit of + # the task cut its wait or the whole wait passed. completion = await _activate(instance, page(2, [], 1, wait_cut=True)) assert list(completion.successful.commands) == [read(3, 1)] - # A page with no Record after the whole wait ends the reader. completion = await _activate(instance, page(3, [], 1)) - expected = [1] if how == "read" else [[1], [], []] + assert list(completion.successful.commands) == [read(4, 1)] + completion = await _activate(instance, page(4, [2], 2)) + expected = [1, 2] if how == "read" else [[1], [], [], [2]] assert result(completion) == expected From ddecff2d33f5fc16481619c337808659f6c2ebf2 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Wed, 25 Nov 2026 17:52:28 -0700 Subject: [PATCH 30/50] Say that a replay fails when the Store of a call changes SDK Core fails the replay with a nondeterminism error when a replayed append or read goes to another Store than the one in History. A test replays an append with a selector that picks another Store. --- changelog/added/steady-stream-heron.md | 2 +- temporalio/client/_stream_store.py | 7 +++-- tests/nexus/test_streams_with_worker.py | 34 +++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/changelog/added/steady-stream-heron.md b/changelog/added/steady-stream-heron.md index 12bd4733ff..a9ad31308a 100644 --- a/changelog/added/steady-stream-heron.md +++ b/changelog/added/steady-stream-heron.md @@ -1,5 +1,5 @@ Add experimental `temporalio.client.StreamStore`, the base class of a Stream Store, and `temporalio.testing.MemoryStreamStore`, a Store that keeps its Streams in memory for tests and local runs. A Store gets the requests of `temporalio.api.streamservice.v1`, which have the Stream id, and the request id of each create and each append as `request_id`. A create returns only `created`, and the SDK gives the caller the ref with the name of the Store. A Stream has no close, and it expires when the Retention of its Store has passed since its create or its last append that wrote a batch. Add experimental Streams for client and Activity code. `stream_config=StreamConfig(stores=[...])` of `Client.connect` gives a client its Stream Stores, and `Client.create_stream` and `Client.get_stream` return a `Stream` to append to, read and describe. A failed call raises `temporalio.exceptions.StreamError` with a `reason`. `max_record_bytes`, `max_batch_bytes` and `max_batch_records` of `StreamConfig` bound an append, and one over a limit fails before its Store gets it. A read of a Stream from `get_stream` needs `body_type=` or a `StreamRef` with a type argument, and raises `TypeError` with neither. `Stream.read` stops at the first page with no Record, so a read with no wait reads to the newest Record, and a read with a wait stops once no Record came within the wait. `temporalio.contrib.streams.current_producer` gives the Producer of an Activity attempt, and `as_producer` gives back one that code stored. -Add experimental Streams for Workflow code. `workflow.create_stream` and `workflow.get_stream` return a `Stream` to append to, read and describe on the Stream Stores of the Worker's client, and `Replayer(stream_config=...)` gives a replay its Stores. The SDK chooses the Store of each call before the call starts, also in a replay. It calls the `store_selector` only for a ref with no Store name, in Workflow code for each such call, also for a create and a describe, and again in a replay. So the selector must return the same Store for the same call, must not block or do I/O, and must be safe to call from more than one thread. +Add experimental Streams for Workflow code. `workflow.create_stream` and `workflow.get_stream` return a `Stream` to append to, read and describe on the Stream Stores of the Worker's client, and `Replayer(stream_config=...)` gives a replay its Stores. The SDK chooses the Store of each call before the call starts, also in a replay. It calls the `store_selector` only for a ref with no Store name, in Workflow code for each such call, also for a create and a describe, and again in a replay. So the selector must return the same Store for the same call, must not block or do I/O, and must be safe to call from more than one thread. SDK Core fails a replay with a nondeterminism error when a replayed append or read goes to another Store than the one in History. Add experimental Stream reads for Workflow code. `Stream.read`, `read_pages` and `read_page` of a Workflow `Stream` give the Records as they come, a replay reads them again from the Store, and `temporalio.workflow.StreamReplayError` in the failure exception types of a Worker or a Workflow fails the Workflow when the Store no longer has them. The Worker option `stream_read_time` sets how long the reads of a Workflow Task can wait, and a read with a wait gives a page with no Record at that limit. In Workflow code, `read` and `read_pages` never end at a page with no Record and read again, also in later Workflow Tasks, so Workflow code decides when to stop. Each page is a read result in History, so an iterator needs a long wait. A read with no wait gives the answer of the Store, which can be a page with no Record, and an outage of the Store at a read fails the Workflow Task. Add experimental `temporalio.contrib.streams.BufferedAppender`, which batches the appends of one Stream in client and Activity code. `append` returns immediately, a batch waits at most `max_delay`, one write runs at a time, and `async with` or `flush()` writes what is left. diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 7f78bce934..4e5a4fdc39 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -318,8 +318,11 @@ class StreamConfig: code it calls it for each such Stream call, also for a create and a describe, and again in a replay. So the selector must return the same Store for the same call, must not block or do I/O, and must be safe to call from - more than one thread. A created Stream has the name of its Store in its ref, - so its calls don't depend on the selector. + more than one thread. SDK Core fails a replay with a nondeterminism error + when a replayed append or read goes to another Store than the one in + History. A replayed create or describe gives the result that History has. A + created Stream has the name of its Store in its ref, so its calls don't + depend on the selector. """ max_record_bytes: int = 1536 * 1024 diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py index e3f4d49af7..7e171fcb0c 100644 --- a/tests/nexus/test_streams_with_worker.py +++ b/tests/nexus/test_streams_with_worker.py @@ -643,6 +643,40 @@ async def created() -> None: assert selects == [("StorageDriverWorkflowInfo", 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) + + async def test_an_append_over_a_limit_of_the_config_never_reaches_the_store( client: Client, ) -> None: From 09f6dda9fe528eade376df085e9228acefa93119 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Wed, 25 Nov 2026 19:09:32 -0700 Subject: [PATCH 31/50] Give read iterators a default wait and read on everywhere Client, Activity and Workflow iterators read on after a page with no Record. With no wait, their reads after the first page wait up to 1 minute, so an idle Stream gets no read loop. A client read's wait ends before its rpc_timeout, and a Store never gets a zero wait. --- changelog/added/steady-stream-heron.md | 4 +- temporalio/client/_stream_store.py | 55 +++++++++--- temporalio/contrib/streams/README.md | 29 +++--- temporalio/nexus/system/_support.py | 21 +++-- temporalio/worker/_worker.py | 4 +- tests/nexus/test_streams.py | 113 ++++++++++++++++++++---- tests/nexus/test_streams_with_worker.py | 47 +++++++++- tests/worker/test_workflow_streams.py | 32 +++++-- 8 files changed, 248 insertions(+), 57 deletions(-) diff --git a/changelog/added/steady-stream-heron.md b/changelog/added/steady-stream-heron.md index a9ad31308a..ffe007056e 100644 --- a/changelog/added/steady-stream-heron.md +++ b/changelog/added/steady-stream-heron.md @@ -1,5 +1,5 @@ Add experimental `temporalio.client.StreamStore`, the base class of a Stream Store, and `temporalio.testing.MemoryStreamStore`, a Store that keeps its Streams in memory for tests and local runs. A Store gets the requests of `temporalio.api.streamservice.v1`, which have the Stream id, and the request id of each create and each append as `request_id`. A create returns only `created`, and the SDK gives the caller the ref with the name of the Store. A Stream has no close, and it expires when the Retention of its Store has passed since its create or its last append that wrote a batch. -Add experimental Streams for client and Activity code. `stream_config=StreamConfig(stores=[...])` of `Client.connect` gives a client its Stream Stores, and `Client.create_stream` and `Client.get_stream` return a `Stream` to append to, read and describe. A failed call raises `temporalio.exceptions.StreamError` with a `reason`. `max_record_bytes`, `max_batch_bytes` and `max_batch_records` of `StreamConfig` bound an append, and one over a limit fails before its Store gets it. A read of a Stream from `get_stream` needs `body_type=` or a `StreamRef` with a type argument, and raises `TypeError` with neither. `Stream.read` stops at the first page with no Record, so a read with no wait reads to the newest Record, and a read with a wait stops once no Record came within the wait. `temporalio.contrib.streams.current_producer` gives the Producer of an Activity attempt, and `as_producer` gives back one that code stored. +Add experimental Streams for client and Activity code. `stream_config=StreamConfig(stores=[...])` of `Client.connect` gives a client its Stream Stores, and `Client.create_stream` and `Client.get_stream` return a `Stream` to append to, read and describe. A failed call raises `temporalio.exceptions.StreamError` with a `reason`. `max_record_bytes`, `max_batch_bytes` and `max_batch_records` of `StreamConfig` bound an append, and one over a limit fails before its Store gets it. A read of a Stream from `get_stream` needs `body_type=` or a `StreamRef` with a type argument, and raises `TypeError` with neither. `Stream.read` and `read_pages` never end at a page with no Record and read again, so the caller decides when to stop, for example with a `break`. With no `wait`, the first read of an iterator gives the answer of the Store at once, and each later read waits up to 1 minute, so an iterator on an idle Stream doesn't call its Store in a loop. A `wait` that the caller gives holds for each read, and a `wait` of zero is no wait at all. `read_page` has no default wait. The wait of a read ends shortly before its `rpc_timeout`, so that the Store can answer in time. `temporalio.contrib.streams.current_producer` gives the Producer of an Activity attempt, and `as_producer` gives back one that code stored. Add experimental Streams for Workflow code. `workflow.create_stream` and `workflow.get_stream` return a `Stream` to append to, read and describe on the Stream Stores of the Worker's client, and `Replayer(stream_config=...)` gives a replay its Stores. The SDK chooses the Store of each call before the call starts, also in a replay. It calls the `store_selector` only for a ref with no Store name, in Workflow code for each such call, also for a create and a describe, and again in a replay. So the selector must return the same Store for the same call, must not block or do I/O, and must be safe to call from more than one thread. SDK Core fails a replay with a nondeterminism error when a replayed append or read goes to another Store than the one in History. -Add experimental Stream reads for Workflow code. `Stream.read`, `read_pages` and `read_page` of a Workflow `Stream` give the Records as they come, a replay reads them again from the Store, and `temporalio.workflow.StreamReplayError` in the failure exception types of a Worker or a Workflow fails the Workflow when the Store no longer has them. The Worker option `stream_read_time` sets how long the reads of a Workflow Task can wait, and a read with a wait gives a page with no Record at that limit. In Workflow code, `read` and `read_pages` never end at a page with no Record and read again, also in later Workflow Tasks, so Workflow code decides when to stop. Each page is a read result in History, so an iterator needs a long wait. A read with no wait gives the answer of the Store, which can be a page with no Record, and an outage of the Store at a read fails the Workflow Task. +Add experimental Stream reads for Workflow code. `Stream.read`, `read_pages` and `read_page` of a Workflow `Stream` give the Records as they come, a replay reads them again from the Store, and `temporalio.workflow.StreamReplayError` in the failure exception types of a Worker or a Workflow fails the Workflow when the Store no longer has them. The Worker option `stream_read_time` sets how long the reads of a Workflow Task can wait, and a read with a wait gives a page with no Record at that limit. In Workflow code, `read` and `read_pages` never end at a page with no Record and read again, also in later Workflow Tasks, so Workflow code decides when to stop. Each page is a read result in History. With the default wait of 1 minute, an iterator on an idle Stream gets few pages with no Record and makes no new Workflow Task, and with a `wait` of zero it reads again at once. A read with no wait gives the answer of the Store, which can be a page with no Record, and an outage of the Store at a read fails the Workflow Task. Add experimental `temporalio.contrib.streams.BufferedAppender`, which batches the appends of one Stream in client and Activity code. `append` returns immediately, a batch waits at most `max_delay`, one write runs at a time, and `async with` or `flush()` writes what is left. diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 4e5a4fdc39..45fe522f8d 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -48,6 +48,10 @@ assert _definition _STREAM_SERVICE: nexusrpc.ServiceDefinition = _definition +_READ_ANSWER_TIME = timedelta(seconds=1) +"""The time that a client read leaves its Store to answer before the +``rpc_timeout``. A tenth of a shorter timeout is used instead.""" + class StreamStore(ABC): """Base class of a Stream Store, which keeps the Records of Streams. @@ -194,7 +198,10 @@ async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse set it. If it's empty, the caller gets the offset of the last Record of the page, or ``from_offset`` for a page with no Record. * A read with nothing after ``from_offset`` answers once a Record comes or - once its ``wait`` is up. With no ``wait``, it answers at once. + once its ``wait`` is up. With no ``wait``, it answers at once. The SDK + never sends a ``wait`` of zero, and sends no ``wait`` instead. A Store + that answers at once with no Record despite a ``wait`` makes an iterator + of the caller read again and again. * Every offset that a response returned is a valid ``from_offset``. A read fails with ``OFFSET_TOO_HIGH`` only when ``from_offset`` is past the end of the Stream. @@ -247,6 +254,23 @@ class StreamConfig: since its create or since the last append that wrote a batch. A reader learns the end of a Stream from the application's own last Record. + ``read`` and ``read_pages`` never end at a page with no Record, in client, + Activity and Workflow code. ``read_pages`` yields that page, and both read + again from its offset. The caller decides when to stop, for example with a + ``break`` or its own timeout. With no ``wait``, the first read of an iterator + gives the answer of the Store at once, and each later read waits up to 1 + minute for a new Record. So an iterator on an idle Stream doesn't call its + Store in a loop. After the first page, the ``next_request`` of ``read`` has + that wait. A ``wait`` of zero is no wait at all, also for the later + reads, so such an iterator on an idle Stream reads again at once, page after + page. ``read_page`` has no default wait. + + In client and Activity code, the wait of a read ends shortly before its + ``rpc_timeout``, so that the Store can answer in time. A read holds an + Activity up to its wait, so an Activity that heartbeats between Records needs + a ``wait`` shorter than its heartbeat timeout, or a heartbeat from another + task. + For the Stream calls of Workflow code: - The SDK chooses the Store of each call before the call starts, also in a @@ -274,14 +298,13 @@ class StreamConfig: at most to the read limit of its Workflow Task, which the Worker option ``stream_read_time`` sets. At that limit ``read_page`` gives a page with no Record. - - ``read`` and ``read_pages`` never end at a page with no Record. - ``read_pages`` yields that page, and both read again from its offset. So - they go on until a Record comes, also over more than one Workflow Task. - Workflow code decides when to stop, for example with a ``break``, its own - timer, a Signal or an Activity. Each page is a read result in History. With - no ``wait`` or a short one, an iterator on a Stream with no new Record - gets page after page with no Record, and History grows fast. So give an - iterator a long ``wait``. + - ``read`` and ``read_pages`` go on until a Record comes, also over more + than one Workflow Task. Workflow code decides when to stop, for example + with a ``break``, its own timer, a Signal or an Activity. Each page is a + read result in History. With a ``wait`` of zero or a short one, an + iterator on a Stream with no new Record gets page after page with no + Record, and History grows fast. With the default wait, an idle Stream + gives an iterator few such pages and no new Workflow Task. - A read holds its Workflow Task up to the read limit. A Signal that comes meanwhile waits until the read has its page, or until that limit. A command for the server waits only for one Store call with no wait for each @@ -485,7 +508,8 @@ def _store_request( max_records=request.max_records, max_bytes=request.max_bytes, ) - if request.HasField("wait"): + # A Store may take a zero wait as one with no end, such as Redis BLOCK 0. + if request.HasField("wait") and (request.wait.seconds or request.wait.nanos): read.wait.CopyFrom(request.wait) return read return DescribeStreamRequest(stream_id=stream_id) @@ -553,6 +577,17 @@ async def _call_store( # pyright: ignore[reportUnusedFunction] StreamError: The call failed. """ store_request = _store_request(request) + if ( + isinstance(store_request, ReadRecordsRequest) + and store_request.HasField("wait") + and timeout is not None + and timeout > timedelta(0) + ): + # A wait is only a bound, and a Store that waits all of it must still answer + # before the timeout fails the read. + longest = timeout - min(_READ_ANSWER_TIME, timeout / 10) + if store_request.wait.ToTimedelta() > longest: + store_request.wait.FromTimedelta(longest) if isinstance(store_request, AppendRecordsRequest): if codec: for appended in store_request.records: diff --git a/temporalio/contrib/streams/README.md b/temporalio/contrib/streams/README.md index aa224a0dea..1390463258 100644 --- a/temporalio/contrib/streams/README.md +++ b/temporalio/contrib/streams/README.md @@ -55,20 +55,29 @@ no body type. Pass `body_type=`, or a ref with a type argument such as `StreamRe A Stream from `create_stream` reads any body with no type. A Stream has no end that a read reports, so a reader stops at the application's own last Record. -In client and Activity code, `read()` stops at the first page with no Record. With no `wait` it -reads to the newest Record, and with a `wait` it stops once no Record came within the wait. It -reads a page only when the caller asks for the next Record, so a reader that stops at its last -Record leaves no read open. +`read()` and `read_pages()` never end at a page with no Record, in client, Activity and Workflow +code. `read_pages()` yields that page, and both read again from its offset. The caller decides +when to stop, for example with a `break` or its own timeout. An iterator reads a page only when the +caller asks for the next Record, so a reader that stops at its last Record leaves no read open. + +With no `wait`, the first read of an iterator gives the answer of the Store at once, and each later +read waits up to 1 minute for a new Record. So an iterator on an idle Stream doesn't call its Store +in a loop. A `wait` that the caller gives holds for each read. A `wait` of zero is no wait at all, +so such an iterator on an idle Stream reads again at once, page after page. `read_page()` has no +default wait. + +In client and Activity code, the wait of a read ends shortly before its `rpc_timeout`, so that the +Store can answer in time. A read holds an Activity up to its wait, so an Activity that heartbeats +between Records needs a `wait` shorter than its heartbeat timeout, or a heartbeat from another +task. In Workflow code, a read with no `wait` gives the answer of the Store, which can be a page with no Record. A read with a `wait` and no Record to give waits up to its `wait`, but at most to the read limit of its Workflow Task (the Worker option `stream_read_time`). At that limit `read_page` gives -a page with no Record. `read()` and `read_pages()` never end at a page with no Record. -`read_pages()` yields that page, and both read again from its offset. So they go on until a Record -comes, also over more than one Workflow Task. Workflow code decides when to stop, for example with -a `break`, its own timer, a Signal or an Activity. Each page is a read result in History, so give -an iterator a long `wait`. With no `wait` or a short one, an iterator on a Stream with no new -Record gets page after page with no Record, and History grows fast. A read with a `wait` that has +a page with no Record. An iterator goes on until a Record comes, also over more than one Workflow +Task, and Workflow code can stop it with its own timer, a Signal or an Activity. Each page is a read +result in History. With a `wait` of zero or a short one, an iterator on a Stream with no new Record +gets page after page with no Record, and History grows fast. A read with a `wait` that has no Record when its task completes starts again in the next task. It asks for a new Workflow Task only when the Stream has more Records for it, so a read of an idle Stream makes no task. An outage of the Store fails the Workflow Task, and Workflow code gets no error. A replay reads the Records diff --git a/temporalio/nexus/system/_support.py b/temporalio/nexus/system/_support.py index 12b7cc57a5..12a924fdcd 100644 --- a/temporalio/nexus/system/_support.py +++ b/temporalio/nexus/system/_support.py @@ -182,19 +182,22 @@ def _timestamp(time: datetime) -> "Timestamp": return models.Timestamp(seconds=proto.seconds, nanos=proto.nanos) +DEFAULT_READ_WAIT = timedelta(minutes=1) +"""The ``wait`` of each read of ``read`` and ``read_pages`` after their first page, +when the caller gave no ``wait``.""" + + def next_read_request( request: "ReadRecordsRequest[_BodyT]", response: "ReadRecordsResponse[_BodyT]" ) -> "ReadRecordsRequest[_BodyT] | None": - from temporalio.workflow import in_workflow - - # A Stream has no end that a read reports. In client and Activity code, a page - # with no Record says that no Record came within the wait, or at once with no - # wait, so the read stops there. Workflow code decides itself when it stops, - # since a read that waits goes on in later Workflow Tasks. - if not response.records and not in_workflow(): - return None + # A Stream has no end that a read reports, so an iterator reads on after a page + # with no Record, and the caller decides when to stop. A read with no wait would + # call the Store in a loop on an idle Stream, so it waits unless told otherwise. + # A wait of zero is the caller's choice of no wait. return dataclasses.replace( - request, from_offset=response.last_offset or request.from_offset + request, + from_offset=response.last_offset or request.from_offset, + wait=DEFAULT_READ_WAIT if request.wait is None else request.wait, ) diff --git a/temporalio/worker/_worker.py b/temporalio/worker/_worker.py index c0552bb234..a16b08e4ef 100644 --- a/temporalio/worker/_worker.py +++ b/temporalio/worker/_worker.py @@ -352,7 +352,9 @@ def __init__( wait, from the start of the task or the end of its replay. At that limit, a read with a wait gives a page with no Record. ``read`` and ``read_pages`` never end at a page with no Record, and read again - with the whole wait, also in a later task. A read with no wait goes + with the whole wait, also in a later task. With no wait given, + their reads after the first page wait up to 1 minute, cut at this + limit. A read with no wait, such as ``read_page`` with none, goes on without holding the task until the Store answers. Defaults to half the Workflow Task timeout. The limit is always before the heartbeat of the task, so a read alone never makes the Worker send diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index 37692b6b19..004a8de3bf 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -54,6 +54,7 @@ ) from temporalio.service import ServiceClient from temporalio.testing import ActivityEnvironment +from temporalio.testing._stream_store import _MemoryStreams from temporalio.worker._workflow_streams import _stream_error_from_failure from tests.helpers.streams import ( FaultStore, @@ -221,7 +222,8 @@ def selector(context: StreamSelectContext) -> FaultStore: max_bytes=rng.choice([0, 1, 2**62]), ) wait = rng.choice([None, 0, 1, 30 * 24 * 3600]) - if wait is not None: + # A Store gets no wait for a wait of zero. + if wait: expected.wait.FromSeconds(wait) call = client.get_stream(ref).read_page( from_offset=expected.from_offset or None, @@ -354,6 +356,8 @@ def __init__( """The number of Records of the Stream, which a test can raise.""" self.starts: list[int] = [] """The Record after which each read started, in the order of the reads.""" + self.waits: list[timedelta | None] = [] + """The wait of each read, in the order of the reads.""" async def start_nexus_operation( self, input: temporalio.client.StartNexusOperationInput @@ -361,6 +365,7 @@ async def start_nexus_operation( request: ReadRecordsRequest[int] = input.arg start = int.from_bytes(request.from_offset or b"", "big") self.starts.append(start) + self.waits.append(request.wait) size = self._rng.randrange(1, 4) # A read with a wait can see no Record come within its wait, also when more # come later. With no wait, a Store answers with no Record only at the end. @@ -381,9 +386,7 @@ async def start_nexus_operation( return handle -async def test_a_read_gives_each_record_once_and_ends_at_a_page_with_no_record() -> ( - None -): +async def test_a_read_gives_each_record_once_past_pages_with_no_record() -> None: for seed in range(300): with failure_note(f"seed {seed}"): await _read_script(random.Random(seed)) @@ -401,26 +404,27 @@ def outbound(next: temporalio.client.OutboundInterceptor) -> _FakeReads: [reads] = fake wait = rng.choice([None, timedelta(0), timedelta(seconds=5)]) got: list[int] = [] + later = _support.DEFAULT_READ_WAIT if wait is None else wait for _ in range(rng.randrange(1, 4)): # More Records come after each read, and a reader picks up where it stopped. - reads.records += rng.randrange(6) + reads.records += rng.randrange(1, 6) offset = got[-1].to_bytes(8, "big") if got else None - stop_at = rng.choice([None, *range(len(got) + 1, reads.records + 1)]) + # A Stream has no end, so the reader stops at a Record that it knows of. + stop_at = rng.randrange(len(got) + 1, reads.records + 1) first_read = len(reads.starts) async for record in stream.read(from_offset=offset, wait=wait): got.append(record.body) if len(got) == stop_at: break - assert got == list(range(1, len(got) + 1)) - if stop_at is not None and len(got) == stop_at: - # The read stops at the caller's last Record, so no read starts after it. - assert all(start < stop_at for start in reads.starts[first_read:]) - else: - # Each read stops at its first page with no Record, which a read with no - # wait gives only at the end. - assert reads.starts[-1] == len(got) - if not wait: - assert len(got) == reads.records + # A page with no Record before the caller's last Record doesn't end the read. + assert got == list(range(1, stop_at + 1)) + # The read stops at the caller's last Record, so no read starts after it. + assert all(start < stop_at for start in reads.starts[first_read:]) + # The first read has the caller's wait. A later one has it too, or the + # default wait when the caller gave none. + assert reads.waits[first_read:] == [wait] + [later] * ( + len(reads.waits) - first_read - 1 + ) @dataclasses.dataclass(frozen=True) @@ -676,6 +680,83 @@ async def script() -> None: run_with_virtual_clock(script()) +def test_a_client_iterator_on_an_idle_stream_waits_between_reads() -> None: + # The Streams of a MemoryStreamStore with no call through the threads of Core, so + # the virtual clock doesn't jump past a wait while an append is on its way. + class ReadLog(_MemoryStreams): + def __init__(self) -> None: + super().__init__( + "memory", retention=timedelta(days=1), resend_window=16, fence=False + ) + self.reads: list[proto.ReadRecordsRequest] = [] + + async def read_records( + self, request: proto.ReadRecordsRequest + ) -> proto.ReadRecordsResponse: + self.reads.append(request) + return await super().read_records(request) + + def waits(store: ReadLog) -> list[timedelta | None]: + return [ + request.wait.ToTimedelta() if request.HasField("wait") else None + for request in store.reads + ] + + async def script() -> None: + loop = asyncio.get_running_loop() + store = ReadLog() + client = Client(Mock(spec=ServiceClient), stream_config=StreamConfig([store])) + stream = await client.create_stream(id="s", body_type=int) + minute = _support.DEFAULT_READ_WAIT + ten, nine = timedelta(seconds=10), timedelta(seconds=9) + # With no wait, the first read answers at once and each later one waits the + # default wait. A wait of zero is the caller's choice to read in a loop, and + # the Store gets no wait for it. A wait ends before the rpc_timeout, so the + # Store answers in time. + cases: list[tuple[timedelta | None, timedelta | None, list[Any]]] = [ + (None, None, [None, minute, minute, minute, minute]), + (ten, None, [ten] * 5), + (timedelta(0), None, [None] * 5), + (None, ten, [None, nine, nine, nine, nine]), + (minute, ten, [nine] * 5), + (timedelta(seconds=5), ten, [timedelta(seconds=5)] * 5), + # A Store has a tenth of a short timeout to answer, and a timeout of + # zero is no timeout. + (ten, timedelta(seconds=2), [timedelta(seconds=1.8)] * 5), + (ten, timedelta(0), [ten] * 5), + ] + for wait, rpc_timeout, expected in cases: + with failure_note(f"wait {wait}, rpc_timeout {rpc_timeout}"): + store.reads.clear() + start = loop.time() + pages = stream.read_pages(wait=wait, rpc_timeout=rpc_timeout) + for _ in expected: + assert not (await anext(pages)).records + await pages.aclose() + assert waits(store) == expected + assert loop.time() - start == pytest.approx( + sum(w.total_seconds() for w in expected if w) + ) + + # A Record that comes during a wait ends it at once, and the caller stops. + async def append_later() -> None: + await asyncio.sleep(90) + await stream.append(1) + + store.reads.clear() + start = loop.time() + appending = asyncio.create_task(append_later()) + async with asyncio.timeout(600): + async for record in stream.read(): + assert record.body == 1 + break + await appending + assert loop.time() - start == pytest.approx(90) + assert waits(store) == [None, minute, minute] + + run_with_virtual_clock(script()) + + def test_a_page_with_no_last_offset_ends_at_its_last_record() -> None: async def unset(call: Callable[[], Awaitable[Any]]) -> Any: page = await call() diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py index 7e171fcb0c..b6a2a001a6 100644 --- a/tests/nexus/test_streams_with_worker.py +++ b/tests/nexus/test_streams_with_worker.py @@ -227,7 +227,10 @@ async def test_a_body_reads_the_same_on_every_path(client: Client) -> None: ran = await run(client, options) expected = [*_bodies("client"), *_bodies("activity"), *_bodies("workflow")] - assert [record.body async for record in stream.read()] == expected + # A Stream has no end, so the reader takes the Records that it knows of. + records = stream.read() + async with asyncio.timeout(10): + assert [(await anext(records)).body for _ in expected] == expected assert ran.result == _digest(expected) # The Store has each body as the codec gave it with no context, and the storage of # the Worker has none of them. @@ -1305,9 +1308,10 @@ def wake(self) -> None: pass @workflow.run - async def run(self, stream_id: str) -> list[int]: + async def run(self, stream_id: str, seconds: float | None = 5) -> list[int]: stream = workflow.get_stream(StreamRef[int](id=stream_id)) - async for record in stream.read(wait=timedelta(seconds=5)): + wait = None if seconds is None else timedelta(seconds=seconds) + async for record in stream.read(wait=wait): return [record.body] raise AssertionError("A Workflow reader never ends by itself") @@ -1342,6 +1346,43 @@ async def cut_page() -> None: assert (await run(client, options)).result == [1] +async def test_a_workflow_iterator_with_no_wait_parks_on_an_idle_stream( + client: Client, +) -> None: + store = FaultStore() + client = stream_client(client, store) + stream = await client.create_stream(id="idle", body_type=int) + + async def write(handle: Any, _worker: Any) -> None: + async def first_task() -> None: + completed = EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED + assert _events(await handle.fetch_history(), completed) + + # The first read gives the empty answer of the Store at once. The later ones + # have the default wait. The read limit cuts a few of them, then one parks, + # so the idle Stream makes no new task over several read limits. + await assert_eventually(first_task) + await asyncio.sleep(4) + history = await handle.fetch_history() + tasks = _events(history, EventType.EVENT_TYPE_WORKFLOW_TASK_STARTED) + markers = _stream_markers(history, "read") + assert len(tasks) == 1, len(tasks) + assert 2 <= len(markers) <= 6, len(markers) + await stream.append(1) + await handle.signal(_FirstRecordWorkflow.wake) + + options = RunOptions( + _FirstRecordWorkflow, + ["idle", None], + task_timeout=timedelta(seconds=10), + worker={"stream_read_time": timedelta(seconds=1)}, + during=write, + replay=True, + ) + ran = await asyncio.wait_for(run(client, options), 30) + assert ran.result == [1] + + async def test_a_workflow_read_with_no_wait_reads_again_in_the_next_task( client: Client, ) -> None: diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py index dd2ee8d08b..72c7ec8e90 100644 --- a/tests/worker/test_workflow_streams.py +++ b/tests/worker/test_workflow_streams.py @@ -71,6 +71,7 @@ WorkflowSerializationContext, ) from temporalio.exceptions import ApplicationError, StreamError +from temporalio.nexus.system import _support from temporalio.nexus.system.stream_service import StreamRef as ModelRef from temporalio.testing import MemoryStreamStore from temporalio.worker._workflow import _CommandAwareDataConverter @@ -992,9 +993,9 @@ def run_handler() -> None: @workflow.defn class _ReadToTwoWorkflow: @workflow.run - async def run(self, how: str) -> list[Any]: + async def run(self, how: str, seconds: float | None = 5) -> list[Any]: stream = workflow.get_stream(ModelRef[int](id="s", store="a")) - wait = timedelta(seconds=5) + wait = None if seconds is None else timedelta(seconds=seconds) if how == "read_page": page = await stream.read_page(wait=wait) return [page.records, page.last_offset] @@ -1016,12 +1017,12 @@ async def run(self, how: str) -> list[Any]: async def test_a_read_goes_on_after_a_page_with_no_record() -> None: converter = temporalio.converter.DefaultPayloadConverter() - def read(seq: int, after: int) -> WorkflowCommand: + def read(seq: int, after: int, seconds: int | None = 5) -> WorkflowCommand: command = ReadStream( seq=seq, stream=StreamRef(id="s", store="a"), from_offset=_offset(after), - wait=Duration(seconds=5), + wait=None if seconds is None else Duration(seconds=seconds), ) return WorkflowCommand(read_stream=command) @@ -1039,8 +1040,8 @@ def page( job = ResolveStreamRead(seq=seq, page=stream_page) return WorkflowActivationJob(resolve_stream_read=job) - def start(how: str) -> WorkflowActivationJob: - arguments = [converter.to_payload(how)] + def start(how: str, seconds: int | None = 5) -> WorkflowActivationJob: + arguments = [converter.to_payload(how), converter.to_payload(seconds)] return WorkflowActivationJob( initialize_workflow=InitializeWorkflow(arguments=arguments) ) @@ -1075,3 +1076,22 @@ def result(completion: WorkflowActivationCompletion) -> Any: completion = await _activate(instance, page(4, [2], 2)) expected = [1, 2] if how == "read" else [[1], [], [], [2]] assert result(completion) == expected + + # The first read of an iterator has the caller's wait. A later read has it too, + # or the default of 1 minute when the caller gave none. A wait of zero stays. + default = int(_support.DEFAULT_READ_WAIT.total_seconds()) + cases: list[tuple[int | None, int | None]] = [(None, default), (0, 0), (5, 5)] + for how in ("read", "read_pages"): + for given, later in cases: + with failure_note(f"{how} with wait {given}"): + instance = _new_instance(_ReadToTwoWorkflow, config) + completion = await _activate(instance, start(how, given)) + assert list(completion.successful.commands) == [read(1, 0, given)] + completion = await _activate(instance, page(1, [1], 1)) + assert list(completion.successful.commands) == [read(2, 1, later)] + completion = await _activate(instance, page(2, [], 1)) + assert list(completion.successful.commands) == [read(3, 1, later)] + # A single read has no default wait. + instance = _new_instance(_ReadToTwoWorkflow, config) + completion = await _activate(instance, start("read_page", None)) + assert list(completion.successful.commands) == [read(1, 0, None)] From 07359ad1410d82eaf3db2b7e15cee818c5a3979d Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Wed, 25 Nov 2026 21:10:46 -0700 Subject: [PATCH 32/50] Pin Core to the Streams stack after the tie rule Core points to the head of sdk-rust#1833. The regenerated stubs have the new proto comments on the job order and on the read settings that became constants. --- .../workflow_activation_pb2.pyi | 9 +++++---- .../workflow_commands/workflow_commands_pb2.pyi | 17 ++++++++--------- temporalio/bridge/sdk-core | 2 +- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi index 36336887a3..e8ae986228 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi @@ -50,7 +50,7 @@ class WorkflowActivation(google.protobuf.message.Message): 3. random-seed-updates 4. signals/updates 5. all others - 6. local activity resolutions, then Stream results + 6. Stream results and local activity resolutions 7. queries 8. evictions @@ -66,9 +66,10 @@ class WorkflowActivation(google.protobuf.message.Message): in that same activation (prime example: cancelling not-wait-for-cancel activities). So, we do this to ensure the LA resolution happens after that cancel (or whatever else it may be) as it normally would have when executing. - * Stream results go after the local activity resolutions, because a replay scans ahead for them - too. Appends go before reads, each in `seq` order. If a replay gives several activations in - one, the Stream results keep the order of those activations. + * Stream results go with the local activity resolutions, because a replay scans ahead for them + too. In one activation of the first run, the Stream results go first, appends before reads, + each in `seq` order, and then the local activity resolutions. If a replay gives several + activations in one, the results keep the order of those activations. * Queries always go last (and, in fact, always come in their own activation) * Evictions also always come in their own activation diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi index 2ceb177cf7..bca15d66b0 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi @@ -2026,12 +2026,12 @@ class ReadStream(google.protobuf.message.Message): message for the server. Before the task completes, each read that had no answer in it gets a check, which is one Store - call with no wait and a short deadline (`StreamSettings::read_check_deadline`). A command waits - for the check and no longer. If the check gets Records, the task gives them, or holds them for - the first activation of the next task if it has a command. If it gets no Record, a read with a - `wait` stops and starts again when the next task opens, and a read with no `wait` gives the page - with no Record. After the read limit each new read of the task is a check. So a read on an idle - Stream never makes a new task, and a drain with no `wait` ends in its task. + call with no wait and a short deadline of 1 s. A command waits for the check and no longer. If + the check gets Records, the task gives them, or holds them for the first activation of the next + task if it has a command. If it gets no Record, a read with a `wait` stops and starts again when + the next task opens, and a read with no `wait` gives the page with no Record. After the read + limit each new read of the task is a check. So a read on an idle Stream never makes a new task, + and a drain with no `wait` ends in its task. Core asks for a new task when it knows that the Stream has Records for an open read. It knows that when the Store gave Records after the page that the read continues from, or when the task @@ -2045,9 +2045,8 @@ class ReadStream(google.protobuf.message.Message): failure message then starts with `StreamStoreUnavailable:`. One Workflow Task gives at most 16 MiB of Records. A page that doesn't fit comes in the first - activation of the next task. Once a task gave `StreamSettings::max_task_read_results` read - results, 256 by default, its new reads get no check and start when the next task opens, which - Core asks for at once. + activation of the next task. Once a task gave 256 read results, its new reads get no check and + start when the next task opens, which Core asks for at once. No command cancels a read, so lang must accept the job of a read that nothing awaits. Core drops a read that has no result when lang sends the Workflow's last command. diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index e6da892e30..e702c1ef12 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit e6da892e30d597ad236f1dd6db6e3bb40690b098 +Subproject commit e702c1ef1289a9de8f016af741c8bf315b4e97d8 From b67926b68704abf62c9d63c88fdd05ee1b608cc7 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Wed, 25 Nov 2026 21:21:06 -0700 Subject: [PATCH 33/50] Say in the StreamStore docs that a refusal message goes in a marker Core fails the Workflow Task when the data of a Stream marker passes 1 MiB, so many long Store messages in one activation can fail it. --- temporalio/client/_stream_store.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 45fe522f8d..fbdd5652fb 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -106,7 +106,11 @@ class StreamStore(ABC): :py:class:`temporalio.exceptions.StreamError` with the reason, such as ``STREAM_ERROR_REASON_EXPIRED`` for ``EXPIRED`` in these docs. Any other exception is an outage of the Store, and the caller gets a ``StreamError`` - with ``STREAM_ERROR_REASON_STORE_UNAVAILABLE``. + with ``STREAM_ERROR_REASON_STORE_UNAVAILABLE``. A refusal of an append or a + read of Workflow code puts its message, cut to 4 KiB, in a Stream marker + whose data has at most 1 MiB. So a Store keeps its messages short, since + many long ones in one activation fail the Workflow Task with + ``StreamMarkerTooLarge``. How the SDK calls a Store: From 0f050a826fe058fe70b75988ce71da6a83151ed4 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Thu, 26 Nov 2026 09:51:23 -0700 Subject: [PATCH 34/50] Pin Core to the Store name rule of sdk-rust#1833 The pin moves to the head of temporalio/sdk-rust#1833. The regen changes only comments of the generated Stream protos. --- .../proto/external_data/external_data_pb2.pyi | 28 ++++++++----------- .../workflow_activation_pb2.pyi | 13 ++++++--- .../workflow_commands_pb2.pyi | 5 ++++ temporalio/bridge/sdk-core | 2 +- 4 files changed, 27 insertions(+), 21 deletions(-) diff --git a/temporalio/bridge/proto/external_data/external_data_pb2.pyi b/temporalio/bridge/proto/external_data/external_data_pb2.pyi index aedfbbb389..3c0227af1d 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.pyi +++ b/temporalio/bridge/proto/external_data/external_data_pb2.pyi @@ -144,17 +144,8 @@ global___PatchedMarkerData = PatchedMarkerData @typing.final class StreamAppendMarkerData(google.protobuf.message.Message): - """The data of a `core_stream_append` marker, which the marker's `data` detail holds as JSON with - each `bytes` field in lower-case hex. Core records one marker for each activation that gives - Workflow code the result of an append. A completion that leaves an append open in a task with - no such marker records one with no entry, so that a replay with chunking on keeps the task - apart from the next one. - - Every later version of Core must read the markers in History, so these rules apply to each - message of the marker. - * A field never changes its name, because the name is its key in the JSON. - * A new field is `optional`, because older markers don't have it. - * A new `repeated` field gets `#[serde(default)]` in `build.rs`, for the same reason. + """The data of a `core_stream_append` marker, as JSON with `bytes` fields in lower-case hex. An + empty marker keeps a task with an open append apart from the next task when chunking is on. """ DESCRIPTOR: google.protobuf.descriptor.Descriptor @@ -188,7 +179,9 @@ class StreamAppendResult(google.protobuf.message.Message): seq: builtins.int stream_id: builtins.str store: builtins.str - """The Store name of the Stream's ref.""" + """The name of the Store that the append used. For a ref with no Store name, it is the name of + the Worker's only Stream runtime. + """ activation_index: builtins.int """The index of the activation, within its Workflow Task, in which Workflow code got the result.""" @property @@ -288,9 +281,10 @@ global___StreamFailure = StreamFailure @typing.final class StreamReadMarkerData(google.protobuf.message.Message): """The data of a `core_stream_read` marker. Core records one in each activation in which Workflow - code got the page of a read, and one with no entry by the rule of `StreamAppendMarkerData`. The - marker keeps the offsets, the count and a digest of each page, never its Records. A replay reads - the Records from the Store again. The JSON rules of `StreamAppendMarkerData` apply. + code got the page of a read. An empty marker keeps a task with an open read and no open append + apart from the next task when chunking is on. The marker keeps the offsets, the count and a + digest of each page, never its Records. A replay reads the Records from the Store again. Its + JSON has `bytes` fields in lower-case hex, as for appends. """ DESCRIPTOR: google.protobuf.descriptor.Descriptor @@ -325,7 +319,9 @@ class StreamReadResult(google.protobuf.message.Message): seq: builtins.int stream_id: builtins.str store: builtins.str - """The Store name of the Stream's ref.""" + """The name of the Store that the read used. For a ref with no Store name, it is the name of the + Worker's only Stream runtime. + """ activation_index: builtins.int """The index of the activation, within its Workflow Task, in which Workflow code got the result.""" from_offset: builtins.bytes diff --git a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi index e8ae986228..e7aa6a04fb 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi @@ -66,10 +66,15 @@ class WorkflowActivation(google.protobuf.message.Message): in that same activation (prime example: cancelling not-wait-for-cancel activities). So, we do this to ensure the LA resolution happens after that cancel (or whatever else it may be) as it normally would have when executing. - * Stream results go with the local activity resolutions, because a replay scans ahead for them - too. In one activation of the first run, the Stream results go first, appends before reads, - each in `seq` order, and then the local activity resolutions. If a replay gives several - activations in one, the results keep the order of those activations. + * Stream results go with the local activity resolutions, for the same reason. Core records a + Stream result in a `core_stream_append` or `core_stream_read` marker, which History has after + the `WorkflowTaskCompleted` event of its task. A replay must give the result before it reaches + that event, so it scans ahead in History for the marker, as for a local activity marker. Each + result in the marker has the index of the activation that got it, so the replay gives it in + that same activation. In one activation, the Stream results go first, appends before reads, + each in `seq` order, and then the local activity resolutions. A replay with workflow task + chunking on can give several activations of the first run as one. Then the results go in the + order of those activations. * Queries always go last (and, in fact, always come in their own activation) * Evictions also always come in their own activation diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi index bca15d66b0..1533a5c3e5 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi @@ -1962,6 +1962,8 @@ class AppendToStream(google.protobuf.message.Message): * No command cancels an append. Lang must accept the result of an append that nothing awaits, and Core drops an append that has no result at the Workflow's last command. * The appends of one Stream go to the Store one at a time, in the order of their commands. + * A `stream` with no Store name is on the Store of the Worker's only Stream runtime, also in a + replay. If the Worker has none or several, the Workflow Task fails. * A bad `seq` or `stream`, or a Store that the Worker has no runtime for, fails the Workflow Task. So does a Store that is still unavailable at the task's heartbeat, with a failure message that starts with `StreamStoreUnavailable:`. @@ -2060,6 +2062,9 @@ class ReadStream(google.protobuf.message.Message): Worker with no runtime for the Store of a marker can't replay, and fails the task, or gives the error as the answer of a legacy query. + A `stream` with no Store name is on the Store of the Worker's only Stream runtime, as for an + append. + A replay compares the `seq`, the `stream` and the `from_offset` of the command with History, and not the `max_records`, the `max_bytes` or the `wait`. It accepts a marker with no entry after any task. After a replay Core doesn't know which Streams have Records after the pages of History, so diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index c4cc36a265..44b83f3434 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit c4cc36a265c2b15b03db798c87185b58143fc305 +Subproject commit 44b83f34349fa1067cf0db1135ee894d5938fc99 From 54156642728b57887bc62ba70a5266ab37f36d28 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Thu, 26 Nov 2026 09:52:53 -0700 Subject: [PATCH 35/50] Document and test the Store of a ref with no Store name The SDK picks that Store in Python and gives Core its name. Tests cover one Store with no selector, and two Stores that need a selector. --- temporalio/client/_stream_store.py | 4 +- tests/worker/test_workflow_streams.py | 68 ++++++++++++++++++++++----- 2 files changed, 58 insertions(+), 14 deletions(-) diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index fbdd5652fb..3dcee7c047 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -339,7 +339,9 @@ class StreamConfig: return one of :py:attr:`stores`. Required when more than one Store is registered. When ``None``, the one - Store takes each such call. + Store takes each such call. In Workflow code, the SDK gives SDK Core the + name of the Store that it picks, so Core never gets a ref with no Store + name. The SDK calls the selector only for a ref with no Store name. In Workflow code it calls it for each such Stream call, also for a create and a diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py index 72c7ec8e90..a8bde15eb8 100644 --- a/tests/worker/test_workflow_streams.py +++ b/tests/worker/test_workflow_streams.py @@ -8,6 +8,7 @@ from datetime import datetime, timedelta, timezone from typing import Any +import pytest from google.protobuf.duration_pb2 import Duration from google.protobuf.message import Message @@ -664,20 +665,20 @@ async def run(self) -> None: await asyncio.gather(*tasks, return_exceptions=True) -async def test_the_store_of_a_call_is_chosen_before_its_command() -> None: - operations = ["create", "append", "read", "describe"] - converter = temporalio.converter.DefaultPayloadConverter() +def _store_of(command: WorkflowCommand) -> str: + """Return the Store name that the command of a Stream call has.""" + variant = command.WhichOneof("variant") + if variant == "append_to_stream": + return command.append_to_stream.stream.store + if variant == "read_stream": + return command.read_stream.stream.store + # The Local Activity of a create or a describe has the Store name second. + [_, store, *_] = command.schedule_local_activity.arguments + return temporalio.converter.DefaultPayloadConverter().from_payload(store, str) - def store_of(command: WorkflowCommand) -> str: - variant = command.WhichOneof("variant") - if variant == "append_to_stream": - return command.append_to_stream.stream.store - if variant == "read_stream": - return command.read_stream.stream.store - # The Local Activity of a create or a describe has the Store name second. - [_, store, *_] = command.schedule_local_activity.arguments - return converter.from_payload(store, str) +async def test_the_store_of_a_call_is_chosen_before_its_command() -> None: + operations = ["create", "append", "read", "describe"] a, b = MemoryStreamStore(name="a"), MemoryStreamStore(name="b") for mask in range(2 ** len(operations)): # Bit `at` of `mask` gives call `at` to Store b. @@ -714,11 +715,52 @@ def selector(context: StreamSelectContext) -> StreamStore: "request_cancel_local_activity", "complete_workflow_execution", ] - assert [store_of(command) for command in commands[:4]] == [ + assert [_store_of(command) for command in commands[:4]] == [ "b" if mine else "a" for mine in on_b ] +# SDK Core uses the only Store of a Worker for a ref with no Store name. The SDK +# picks that Store itself, so each command has its name. +async def test_a_ref_with_no_store_name_goes_to_the_only_store() -> None: + operations = ["create", "append", "read", "describe"] + config = StreamConfig([MemoryStreamStore(name="only")]) + _EachCall.operations = operations + for replaying in (False, True): + with failure_note(f"replaying {replaying}"): + instance = _new_instance(_EachCallWorkflow, config) + initialize = WorkflowActivationJob(initialize_workflow=InitializeWorkflow()) + completion = await _activate(instance, initialize, replaying=replaying) + commands = completion.successful.commands[: len(operations)] + assert [command.WhichOneof("variant") for command in commands] == [ + "schedule_local_activity", + "append_to_stream", + "read_stream", + "schedule_local_activity", + ] + stores = [_store_of(command) for command in commands] + assert stores == ["only"] * len(operations) + + +async def test_a_ref_with_no_store_name_needs_a_selector_for_two_stores() -> None: + a, b = MemoryStreamStore(name="a"), MemoryStreamStore(name="b") + with pytest.raises(ValueError, match="store_selector must be specified"): + StreamConfig([a, b]) + unregistered = MemoryStreamStore(name="c") + config = StreamConfig([a, b], store_selector=lambda _: unregistered) + for operation in ["create", "append", "read", "describe"]: + _EachCall.operations = [operation] + for replaying in (False, True): + with failure_note(f"{operation}, replaying {replaying}"): + instance = _new_instance(_EachCallWorkflow, config) + initialize = WorkflowActivationJob( + initialize_workflow=InitializeWorkflow() + ) + completion = await _activate(instance, initialize, replaying=replaying) + message = completion.failed.failure.message + assert "not registered in StreamConfig.stores" in message + + async def test_a_stream_call_with_no_stream_config_fails_the_task() -> None: for operation in ["create", "append", "read", "describe"]: _EachCall.operations = [operation] From 37aec862549e212ff4ff883ec8d1a06bce1a372c Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Thu, 26 Nov 2026 12:42:53 -0700 Subject: [PATCH 36/50] Pin Core to the default Stream runtime of sdk-rust#1833 The pin moves to the head of temporalio/sdk-rust#1833. The regen changes only comments of the generated Stream protos. --- .../bridge/proto/external_data/external_data_pb2.pyi | 8 ++++---- .../proto/workflow_commands/workflow_commands_pb2.pyi | 9 +++++---- temporalio/bridge/sdk-core | 2 +- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/temporalio/bridge/proto/external_data/external_data_pb2.pyi b/temporalio/bridge/proto/external_data/external_data_pb2.pyi index 3c0227af1d..2534fde7af 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.pyi +++ b/temporalio/bridge/proto/external_data/external_data_pb2.pyi @@ -179,8 +179,8 @@ class StreamAppendResult(google.protobuf.message.Message): seq: builtins.int stream_id: builtins.str store: builtins.str - """The name of the Store that the append used. For a ref with no Store name, it is the name of - the Worker's only Stream runtime. + """The name of the Store that the append used. For a ref with no Store name, it is the empty + name if the Worker has a Stream runtime under it, else the name of its only runtime. """ activation_index: builtins.int """The index of the activation, within its Workflow Task, in which Workflow code got the result.""" @@ -319,8 +319,8 @@ class StreamReadResult(google.protobuf.message.Message): seq: builtins.int stream_id: builtins.str store: builtins.str - """The name of the Store that the read used. For a ref with no Store name, it is the name of the - Worker's only Stream runtime. + """The name of the Store that the read used. For a ref with no Store name, it is the empty name + if the Worker has a Stream runtime under it, else the name of its only runtime. """ activation_index: builtins.int """The index of the activation, within its Workflow Task, in which Workflow code got the result.""" diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi index 1533a5c3e5..2e8fd0661e 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi @@ -1962,8 +1962,9 @@ class AppendToStream(google.protobuf.message.Message): * No command cancels an append. Lang must accept the result of an append that nothing awaits, and Core drops an append that has no result at the Workflow's last command. * The appends of one Stream go to the Store one at a time, in the order of their commands. - * A `stream` with no Store name is on the Store of the Worker's only Stream runtime, also in a - replay. If the Worker has none or several, the Workflow Task fails. + * A `stream` with no Store name is on the Store of the Worker's Stream runtime under the empty + name, else of its only Stream runtime, also in a replay. If the Worker has neither, the + Workflow Task fails. * A bad `seq` or `stream`, or a Store that the Worker has no runtime for, fails the Workflow Task. So does a Store that is still unavailable at the task's heartbeat, with a failure message that starts with `StreamStoreUnavailable:`. @@ -2062,8 +2063,8 @@ class ReadStream(google.protobuf.message.Message): Worker with no runtime for the Store of a marker can't replay, and fails the task, or gives the error as the answer of a legacy query. - A `stream` with no Store name is on the Store of the Worker's only Stream runtime, as for an - append. + A `stream` with no Store name is on the Store of the Worker's Stream runtime under the empty + name, else of its only Stream runtime, as for an append. A replay compares the `seq`, the `stream` and the `from_offset` of the command with History, and not the `max_records`, the `max_bytes` or the `wait`. It accepts a marker with no entry after any diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index 44b83f3434..57a5d1c893 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit 44b83f34349fa1067cf0db1135ee894d5938fc99 +Subproject commit 57a5d1c89380529ce3cc29a458fd3c8df0556207 From 7b31d3e8fee7dcadae8a5818a1c6fb6dfeadb854 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Thu, 26 Nov 2026 13:17:59 -0700 Subject: [PATCH 37/50] Pin Core to the one-name runtime check of sdk-rust#1833 The pin moves to the head of temporalio/sdk-rust#1833, where a Worker with one Stream runtime under two names fails to start. The regen changes no generated file. --- temporalio/bridge/sdk-core | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index 57a5d1c893..816a90e0df 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit 57a5d1c89380529ce3cc29a458fd3c8df0556207 +Subproject commit 816a90e0df94154fa0683b52587ccb72e86bec26 From 2db60b4b19a11021e85b2cf7115ce52264f59828 Mon Sep 17 00:00:00 2001 From: Mohammad Dashti Date: Thu, 26 Nov 2026 22:22:51 -0700 Subject: [PATCH 38/50] Finalize async generators when the virtual-clock test loop exits --- tests/helpers/streams.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/tests/helpers/streams.py b/tests/helpers/streams.py index 266419cec6..674ee63c3b 100644 --- a/tests/helpers/streams.py +++ b/tests/helpers/streams.py @@ -364,8 +364,5 @@ def time(self) -> float: def run_with_virtual_clock(main: Coroutine[Any, Any, _T]) -> _T: """Run ``main`` on a new :py:class:`VirtualClockLoop` and return its result.""" - loop = VirtualClockLoop() - try: - return loop.run_until_complete(main) - finally: - loop.close() + with asyncio.Runner(loop_factory=VirtualClockLoop) as runner: + return runner.run(main) From 7d6a549a314d08bc3ef5bd924547e082c1807737 Mon Sep 17 00:00:00 2001 From: Mohammad Dashti Date: Fri, 27 Nov 2026 02:14:26 -0700 Subject: [PATCH 39/50] Document Stream replay and verify poll cancellation --- changelog/fixed/patient-poll.md | 1 + temporalio/bridge/src/streams.rs | 11 +- temporalio/client/_stream_store.py | 16 +-- temporalio/contrib/streams/README.md | 137 ++++++++++----------- temporalio/contrib/streams/_appender.py | 7 +- temporalio/converter/_payload_converter.py | 12 +- temporalio/nexus/system/_support.py | 8 +- temporalio/worker/_workflow_streams.py | 13 +- tests/nexus/test_streams.py | 35 ++++++ 9 files changed, 115 insertions(+), 125 deletions(-) create mode 100644 changelog/fixed/patient-poll.md diff --git a/changelog/fixed/patient-poll.md b/changelog/fixed/patient-poll.md new file mode 100644 index 0000000000..9eb729fb75 --- /dev/null +++ b/changelog/fixed/patient-poll.md @@ -0,0 +1 @@ +Client and Activity Stream polling yields to asyncio between empty pages, including when the caller sets a zero wait. diff --git a/temporalio/bridge/src/streams.rs b/temporalio/bridge/src/streams.rs index dd149c94db..e5c9b8edc7 100644 --- a/temporalio/bridge/src/streams.rs +++ b/temporalio/bridge/src/streams.rs @@ -28,20 +28,14 @@ struct PythonStore { event_loop_task_locals: Arc>, } -/// The state of one call of a Python Store, which the call's guard and its `OnTask` share. enum CallState { - /// Python hasn't started the task of the call. Pending, - /// The Python task that runs the call. Running(Py), - /// The caller dropped the call before its answer. Dropped, - /// The call has its answer. Done, } -// Nothing calls into Python while it holds this lock, since `OnTask` takes it with the GIL held -// and the guard needs the GIL only after it let the lock go. +// 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) } @@ -90,8 +84,7 @@ impl Drop for CallGuard<'_> { } impl PythonStore { - /// Calls the Store. `request_id` is that of a create or an append, and `None` for the other - /// operations. Core doesn't catch a panic of a Store, so every failure here is an error. + // Core doesn't catch Store panics, so failures must return errors. async fn call( &self, operation: &'static str, diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 3dcee7c047..c188f8a7bc 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -196,7 +196,7 @@ async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse """Read one page of Records after ``from_offset``, in the order of the Stream. * A page has at most ``max_records`` Records, and Records of at most - ``max_bytes`` in total, where zero is no limit. It always has its first + ``max_bytes`` in total. Zero uses the Store's default. A page has its first Record, even when that Record alone is over ``max_bytes``. * ``last_offset`` is where the next read continues. A Store doesn't have to set it. If it's empty, the caller gets the offset of the last Record of @@ -269,8 +269,8 @@ class StreamConfig: reads, so such an iterator on an idle Stream reads again at once, page after page. ``read_page`` has no default wait. - In client and Activity code, the wait of a read ends shortly before its - ``rpc_timeout``, so that the Store can answer in time. A read holds an + In client and Activity code, a positive ``rpc_timeout`` caps the read's wait + below that timeout, so the Store has time to answer. A read holds an Activity up to its wait, so an Activity that heartbeats between Records needs a ``wait`` shorter than its heartbeat timeout, or a heartbeat from another task. @@ -293,9 +293,10 @@ class StreamConfig: with other limits, as it refuses one with other Store names. - A page of a read has at most 256 Records and 4 MiB of Records by default, and never more than 16 MiB. - - A read fails with ``STREAM_ERROR_REASON_UNSUPPORTED`` for a Record over - :py:attr:`max_record_bytes`. So a reader needs a limit at least as large - as that of each writer of its Stream. + - A live read fails with ``STREAM_ERROR_REASON_UNSUPPORTED`` for a Record + over :py:attr:`max_record_bytes`. A reader needs a limit at least as large + as each writer's limit. Replay accepts recorded successes under smaller + limits, so a configuration change cannot alter a recorded result. - A read with no wait gives the answer of the Store, which can be a page with no Record. - A read with a ``wait`` and no Record to give waits up to its ``wait``, but @@ -355,8 +356,7 @@ class StreamConfig: """ max_record_bytes: int = 1536 * 1024 - """Maximum size in bytes of one Record of an append, and of one Record that a - read of Workflow code gives. Defaults to 1.5 MiB. Must be greater than or + """Maximum size in bytes of one Record of an append or a live Workflow read. Defaults to 1.5 MiB. Must be greater than or equal to one. The size is that of the stored Record, which counts its Producer. """ diff --git a/temporalio/contrib/streams/README.md b/temporalio/contrib/streams/README.md index 1390463258..0f8628d027 100644 --- a/temporalio/contrib/streams/README.md +++ b/temporalio/contrib/streams/README.md @@ -1,20 +1,17 @@ -# Streams helpers +# Stream helpers -> This package is experimental. Its API can change in a later release. +> This package is experimental. Its API can change. -`temporalio.contrib.streams` has helpers on top of the Streams API of the SDK. A Stream is an -append-only log of Records in a Stream Store, such as Redis. A client gets its Stores from -`stream_config=StreamConfig(stores=[...])`, and `create_stream` and `get_stream` of a client or -of `temporalio.workflow` return a `Stream`. +`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`. -This isn't `temporalio.contrib.workflow_streams`, which keeps its events in a Workflow and -needs no Store. +`temporalio.contrib.workflow_streams` is a separate API that stores events in +Workflow state. ## `BufferedAppender` -`BufferedAppender` batches the appends of one Stream. `append` returns immediately, and the -appender writes the buffered Records as one batch, at most `max_delay` after the first of them -(100 milliseconds by default). One write runs at a time, and the Records keep their order. +Use `BufferedAppender` in client or Activity code to combine frequent appends. ```python from temporalio.contrib.streams import BufferedAppender @@ -24,67 +21,57 @@ async with BufferedAppender(stream) as tokens: tokens.append(token) ``` -The end of the `async with` block writes the Records that are still in the buffer. Without -`async with`, `await tokens.flush()` does the same. If code appends faster than the Store takes -Records, the buffer grows with no bound, unless that code awaits `flush()` from time to time. A -batch over `max_batch_records` or `max_batch_bytes` of the client's `StreamConfig` then fails, -and `max_batch_records` of the appender keeps each batch under the first. - -An Activity that ends with Records in the buffer still writes them, up to `max_delay` later. -That write has the Producer of the ended attempt, it can come after a write of the next attempt, -and nobody gets its error. `async with`, or a `flush()` before the end, avoids it. - -After a batch fails, the appender writes nothing more, and each later `append` and `flush` -raises the error of that batch, or `RuntimeError` if the write of the batch was cancelled. -`unwritten` is the number of Records that it left behind. - -The appender is for client and Activity code. Workflow code passes its Records to one `append` -call of its Stream. - -## A stored Producer - -Each write has its Producer, which is the writer with its attempt. `current_producer()` gives -the Producer that an append of the running Activity attempt sends by default. An -Activity that stores it, such as in its heartbeat details, gets it back as a proto message, and -`as_producer` turns that into a `Producer` again, which `append(..., producer=...)` takes. - -## Reads - -A read of a Stream from `get_stream(StreamRef(id=...))` raises `TypeError`, since such a ref has -no body type. Pass `body_type=`, or a ref with a type argument such as `StreamRef[str](id=...)`. -A Stream from `create_stream` reads any body with no type. - -A Stream has no end that a read reports, so a reader stops at the application's own last Record. -`read()` and `read_pages()` never end at a page with no Record, in client, Activity and Workflow -code. `read_pages()` yields that page, and both read again from its offset. The caller decides -when to stop, for example with a `break` or its own timeout. An iterator reads a page only when the -caller asks for the next Record, so a reader that stops at its last Record leaves no read open. - -With no `wait`, the first read of an iterator gives the answer of the Store at once, and each later -read waits up to 1 minute for a new Record. So an iterator on an idle Stream doesn't call its Store -in a loop. A `wait` that the caller gives holds for each read. A `wait` of zero is no wait at all, -so such an iterator on an idle Stream reads again at once, page after page. `read_page()` has no -default wait. - -In client and Activity code, the wait of a read ends shortly before its `rpc_timeout`, so that the -Store can answer in time. A read holds an Activity up to its wait, so an Activity that heartbeats -between Records needs a `wait` shorter than its heartbeat timeout, or a heartbeat from another -task. - -In Workflow code, a read with no `wait` gives the answer of the Store, which can be a page with no -Record. A read with a `wait` and no Record to give waits up to its `wait`, but at most to the read -limit of its Workflow Task (the Worker option `stream_read_time`). At that limit `read_page` gives -a page with no Record. An iterator goes on until a Record comes, also over more than one Workflow -Task, and Workflow code can stop it with its own timer, a Signal or an Activity. Each page is a read -result in History. With a `wait` of zero or a short one, an iterator on a Stream with no new Record -gets page after page with no Record, and History grows fast. A read with a `wait` that has -no Record when its task completes starts again in the next task. It asks for a new Workflow Task -only when the Stream has more Records for it, so a read of an idle Stream makes no task. An outage -of the Store fails the Workflow Task, and Workflow code gets no error. A replay reads the Records -again from the Store, so the Retention of the Stream must cover the life of the Workflow and the -time in which it gets queries. - -In Workflow code, a read with no `max_records` gives at most 256 Records in a page, and a read -with no `max_bytes` at most 4 MiB of them. A page has at most 16 MiB of Records, also for a larger -`max_bytes`. A read fails for a Record over the `max_record_bytes` of the Worker's `StreamConfig`, -so a reader needs a limit at least as large as that of each writer of its Stream. +`append` returns immediately. The appender starts a batch within `max_delay` +when no write is active. The default is 100 milliseconds. Writes are sequential. + +`async with` flushes before exit. Without it, call `await tokens.flush()` before +the Activity ends. Otherwise a delayed write can follow a later Activity attempt, +and its error has no caller. + +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. + +Workflow reads can span Workflow Tasks. `stream_read_time` bounds how long a +read keeps its task open. Each page adds a result to History. Short waits on an +idle Stream can make History grow quickly. Store outages fail the Workflow Task +without returning an error to Workflow code. + +Live Workflow pages default to 256 Records and 4 MiB, with a 16 MiB cap. A live +read fails if a Record exceeds the Worker's `max_record_bytes`. Replay preserves +recorded successes under smaller limits. + +Replay reads Records from the Store again. Retention must cover every replay +and query. Values in Workflow state do not remove this Store dependency. diff --git a/temporalio/contrib/streams/_appender.py b/temporalio/contrib/streams/_appender.py index ba720f00b7..b476266fc1 100644 --- a/temporalio/contrib/streams/_appender.py +++ b/temporalio/contrib/streams/_appender.py @@ -84,12 +84,11 @@ def __init__( ) self._max_batch_records = max_batch_records self._buffer: list[BodyT] = [] - # When the oldest Record came into an empty buffer self._first_at = 0.0 self._timer: asyncio.TimerHandle | None = None self._writing: asyncio.Task[None] | None = None self._appended = 0 - # Count of the Records that a batch wrote or that a failed batch left behind + # 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 @@ -160,7 +159,6 @@ async def __aexit__( raise def _schedule(self) -> None: - """Start the next batch, immediately or when the delay of its first Record ends.""" if self._writing or not self._buffer: return if self._max_batch_records and len(self._buffer) >= self._max_batch_records: @@ -183,8 +181,7 @@ async def _write(self, batch: list[BodyT]) -> None: response = await self._stream.append(*batch) self._last_offset = response.last_offset except BaseException as err: - # The Records behind a batch that failed, or whose write was cancelled, are - # never written, so a reader sees no gap. + # 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() diff --git a/temporalio/converter/_payload_converter.py b/temporalio/converter/_payload_converter.py index 279d59ee72..b3d898a16e 100644 --- a/temporalio/converter/_payload_converter.py +++ b/temporalio/converter/_payload_converter.py @@ -584,21 +584,16 @@ def from_payload( raise RuntimeError("Failed parsing") from err -# Only these types decode by their type arguments and under `T | None`. Other types keep -# their decoding, because a change would alter the replay of existing Workflow Histories. +# Restrict new decoding rules to new types to preserve existing Workflow histories. _typed_decode_types: set[type] = set() def _is_typed_decode_type(hint: Any) -> bool: - """Return whether ``hint`` is a type of ``_typed_decode_types`` or an alias of one.""" origin = typing.get_origin(hint) or hint return any(origin is typed for typed in _typed_decode_types) def _non_none_arg(hint: Any) -> Any: - """Return ``X`` for the hint ``X | None`` of a type of ``_typed_decode_types``, and - the hint itself for any other. - """ origin = typing.get_origin(hint) if origin is typing.Union or origin is UnionType: # type:ignore[reportDeprecated] args = typing.get_args(hint) @@ -654,7 +649,6 @@ def from_payloads( """See base class.""" if type_hints is None: return self._inner_payload_converter.from_payloads(payloads, None) - # A hint `T | None` of a type of `_typed_decode_types` takes the converter of `T`. value_hints = [_non_none_arg(type_hint) for type_hint in type_hints] converters = [ _get_transfer_type_converter(value_hint) for value_hint in value_hints @@ -863,7 +857,6 @@ def _get_iso_datetime_parser() -> Callable[[str], datetime]: def _with_type_args(hint: Any, type_var_args: Mapping[Any, Any]) -> Any: - """Return a hint with each of its type variables replaced by its argument.""" if not type_var_args: return hint if isinstance(hint, TypeVar): @@ -1046,9 +1039,6 @@ def value_to_type( ret_dict = hint(**ret_dict) return ret_dict - # Dataclass, also with type arguments such as ``Box[int]`` for a type of - # ``_typed_decode_types``. The class of such a hint is its origin, and its arguments - # stand for the type variables. dataclass_type: Any = hint type_var_args: dict[Any, Any] = {} alias_origin = typing.get_origin(hint) diff --git a/temporalio/nexus/system/_support.py b/temporalio/nexus/system/_support.py index 12a924fdcd..009c562bc1 100644 --- a/temporalio/nexus/system/_support.py +++ b/temporalio/nexus/system/_support.py @@ -183,17 +183,13 @@ def _timestamp(time: datetime) -> "Timestamp": DEFAULT_READ_WAIT = timedelta(minutes=1) -"""The ``wait`` of each read of ``read`` and ``read_pages`` after their first page, -when the caller gave no ``wait``.""" +"""Default wait after the first page of ``read`` and ``read_pages``.""" def next_read_request( request: "ReadRecordsRequest[_BodyT]", response: "ReadRecordsResponse[_BodyT]" ) -> "ReadRecordsRequest[_BodyT] | None": - # A Stream has no end that a read reports, so an iterator reads on after a page - # with no Record, and the caller decides when to stop. A read with no wait would - # call the Store in a loop on an idle Stream, so it waits unless told otherwise. - # A wait of zero is the caller's choice of no wait. + # Empty pages don't end a Stream. The default wait avoids busy polling. return dataclasses.replace( request, from_offset=response.last_offset or request.from_offset, diff --git a/temporalio/worker/_workflow_streams.py b/temporalio/worker/_workflow_streams.py index 7795afcd81..4f1b196b55 100644 --- a/temporalio/worker/_workflow_streams.py +++ b/temporalio/worker/_workflow_streams.py @@ -48,13 +48,8 @@ @dataclass class _Read: - """The read of one ``read_page`` call.""" - waiter: asyncio.Future[Any] - """Gets the page of the call.""" - page_type: Any - """The type of the page that the call returns.""" class _WorkflowStreams: # pyright: ignore[reportUnusedClass] @@ -68,11 +63,10 @@ class _WorkflowStreams: # pyright: ignore[reportUnusedClass] def __init__(self, instance: _WorkflowInstanceImpl) -> None: self._instance = instance - # Each append whose job hasn't come, by seq self._appends: dict[int, asyncio.Future[Any]] = {} self.task_error: Exception | None = None """The error of a call that must fail the Workflow Task, if one came.""" - # Each read whose job hasn't come, by seq. A cancelled read gets its one job too. + # Cancelled reads still receive one result from Core. self._reads: dict[int, _Read] = {} def start( @@ -93,7 +87,6 @@ def start( instance._context_free_failure_converter, ) model = input.input - # The terminal of each Stream operation gives its output type. result_type: Any = input.output_type request = temporalio.nexus.system._support.model_to_proto(model, *converters) # The converter refuses a body of no type, and the job of the page would then @@ -106,7 +99,6 @@ def start( "body_type, or a StreamRef with a type argument." ) store = self._store(_request_ref(request)).name() - # The future of the job of the call, or the task of its Local Activity result = _start_call(self, store, operation, request, result_type) async def call() -> OutputT: @@ -175,7 +167,6 @@ def resolve_read( read = self._reads.pop(job.seq, None) if read is None: raise RuntimeError(f"Failed finding Stream read for sequence {job.seq}") - # The job of a cancelled call is dropped. if read.waiter.done(): return if job.HasField("failed"): @@ -450,7 +441,7 @@ def store(name: str) -> StreamStore: names, limits = _for_core(stream_config()) return temporalio.bridge.streams.WorkerStreams( limits=limits, - # Each caller finds its Store in the config that the worker has at the call. + # Client swaps must affect later Store calls. stores=[ (name, _StoreCaller(functools.partial(store, name))) for name in sorted(names) diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index 004a8de3bf..cd9ce0f815 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -776,3 +776,38 @@ async def script() -> None: assert (empty.records, empty.last_offset) == ([], page.last_offset) run_with_virtual_clock(script()) + + +@pytest.mark.parametrize("by_page", [False, True]) +async def test_zero_wait_poll_can_be_cancelled_after_an_empty_page( + by_page: bool, +) -> None: + class IdleStore(_MemoryStreams): + reads: int = 0 + + async def read_records( + self, request: proto.ReadRecordsRequest + ) -> proto.ReadRecordsResponse: + assert not request.HasField("wait") + self.reads += 1 + assert self.reads == 1, "another poll ran before the pending cancellation" + return proto.ReadRecordsResponse() + + store = IdleStore( + "memory", retention=timedelta(days=1), resend_window=16, fence=False + ) + client = Client(Mock(spec=ServiceClient), stream_config=StreamConfig([store])) + stream = await client.create_stream(id="s", body_type=int) + + async def consume() -> None: + if by_page: + async for page in stream.read_pages(wait=timedelta(0)): + assert not page.records + else: + _ = await anext(stream.read(wait=timedelta(0))) + + task = asyncio.create_task(consume()) + _ = asyncio.get_running_loop().call_soon(task.cancel) + with pytest.raises(asyncio.CancelledError): + await task + assert store.reads == 1 From d2fa862ecb8afd6c838722e49b303fb2c3f4ac1a Mon Sep 17 00:00:00 2001 From: Mohammad Dashti Date: Fri, 27 Nov 2026 02:24:42 -0700 Subject: [PATCH 40/50] Pin replay-compatible Core and clarify Stream contracts --- changelog/fixed/blockier-mathias.md | 2 + scripts/gen_nexus_system_api.py | 3 +- temporalio/api/sdk/v1/stream_pb2.pyi | 2 + .../proto/external_data/external_data_pb2.pyi | 4 +- .../workflow_activation_pb2.pyi | 11 +- .../workflow_commands_pb2.pyi | 121 ++++++------------ temporalio/bridge/sdk-core | 2 +- temporalio/bridge/src/lib.rs | 1 - temporalio/bridge/src/streams.rs | 19 +-- temporalio/client/_client.py | 1 - temporalio/client/_stream_store.py | 26 +--- .../client/_resources/stream.py | 14 +- .../workflow/_resources/stream.py | 14 +- temporalio/worker/_workflow_streams.py | 13 -- 14 files changed, 70 insertions(+), 163 deletions(-) create mode 100644 changelog/fixed/blockier-mathias.md diff --git a/changelog/fixed/blockier-mathias.md b/changelog/fixed/blockier-mathias.md new file mode 100644 index 0000000000..8863932c02 --- /dev/null +++ b/changelog/fixed/blockier-mathias.md @@ -0,0 +1,2 @@ +Core: A Workflow Stream read returns an unsupported-read error for a single Record over 16 MiB. New read markers preserve the Producer's optional timestamps and signed values during replay. Workers can still replay the original marker format, including previously delivered oversized Records. Older Workers cannot interpret the new digest format. +Core: Workflow replay now skips timed-out tasks consistently when a History page ends at the task start. diff --git a/scripts/gen_nexus_system_api.py b/scripts/gen_nexus_system_api.py index 4212ea775d..cb308ebeff 100644 --- a/scripts/gen_nexus_system_api.py +++ b/scripts/gen_nexus_system_api.py @@ -26,8 +26,7 @@ notification_output_dir = base_dir / "temporalio" / "nexus" / "notifications" stream_output_dir = base_dir / "temporalio" / "nexus" / "system" / "stream_service" workflow_init_path = base_dir / "temporalio" / "workflow" / "__init__.py" -# Empty-page polls need the cancellation fix before its nexgen release. -NEX_GEN_REVISION = "cb6dccfa158bab4c0662b85a31d3da63d0b8179b" +NEX_GEN_REVISION = "09bdf2a6b9c690a92f65e3964d58d5db9b2c0a32" proto_files = [ gen_protos.api_proto_dir / "temporal" diff --git a/temporalio/api/sdk/v1/stream_pb2.pyi b/temporalio/api/sdk/v1/stream_pb2.pyi index b9640b060b..a2be9f27b5 100644 --- a/temporalio/api/sdk/v1/stream_pb2.pyi +++ b/temporalio/api/sdk/v1/stream_pb2.pyi @@ -174,7 +174,9 @@ class ReadRecordsRequest(google.protobuf.message.Message): aip.dev/not-precedent: "from" marks the start of a range of offsets. --) """ max_records: builtins.int + """Zero uses the configured default.""" max_bytes: builtins.int + """One Record can exceed this target unless an SDK hard limit rejects it.""" @property def ref(self) -> global___StreamRef: """Required.""" diff --git a/temporalio/bridge/proto/external_data/external_data_pb2.pyi b/temporalio/bridge/proto/external_data/external_data_pb2.pyi index 2534fde7af..9925078f9c 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.pyi +++ b/temporalio/bridge/proto/external_data/external_data_pb2.pyi @@ -387,8 +387,8 @@ class StreamReadPage(google.protobuf.message.Message): WAIT_CUT_FIELD_NUMBER: builtins.int record_count: builtins.int digest: builtins.bytes - """The first 16 bytes of a SHA-256 over the Records, in an encoding that Core owns. It's empty if - the page has no Record. + """The first 16 bytes of SHA-256 over the Records in a Core-owned encoding. New markers prefix + these bytes with version 1. Original markers contain just the legacy hash. Empty for no Records. """ record_bytes: builtins.int """The size of the Records, as the `max_bytes` of a read measures it. A replay asks the Store for diff --git a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi index e7aa6a04fb..27ca55f056 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi @@ -1680,14 +1680,9 @@ global___RemoveFromCache = RemoveFromCache @typing.final class ResolveStreamAppend(google.protobuf.message.Message): - """The result of an `AppendToStream`. Core gives it in the next activation after the Store answers, - or in the first activation of the next task if it arrives while the task completes. - - The `core_stream_append` marker of that activation records the result with the activation's - index, on the same counter as local activity markers, so a replay gives both kinds of result in - the order of the first run. As for a local activity, the replay uses the same activation as the - first run only if workflow task chunking is off. With chunking, it can give the jobs of several - activations in one, in their order. + """Core delivers the result in the next activation, or in the next task when the Store answers + during completion. Stream and Local Activity markers share an activation index. Replay + preserves result order. With task chunking, several activations can replay as one. """ DESCRIPTOR: google.protobuf.descriptor.Descriptor diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi index 2e8fd0661e..f3cbe7caaf 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi @@ -1953,23 +1953,16 @@ global___RequestCancelNexusOperation = RequestCancelNexusOperation @typing.final class AppendToStream(google.protobuf.message.Message): - """Appends Records to a Stream as the Workflow's Producer. Core calls the Store while the Workflow - Task is open, keeps the task open as it does for a Local Activity, and sends the result in a - `ResolveStreamAppend` job. - - * An append is at-least-once. If History has no result for it, a later attempt of the Workflow - Task writes the batch again. - * No command cancels an append. Lang must accept the result of an append that nothing awaits, - and Core drops an append that has no result at the Workflow's last command. - * The appends of one Stream go to the Store one at a time, in the order of their commands. - * A `stream` with no Store name is on the Store of the Worker's Stream runtime under the empty - name, else of its only Stream runtime, also in a replay. If the Worker has neither, the - Workflow Task fails. - * A bad `seq` or `stream`, or a Store that the Worker has no runtime for, fails the Workflow - Task. So does a Store that is still unavailable at the task's heartbeat, with a failure - message that starts with `StreamStoreUnavailable:`. - * An empty batch, or one over the limits of its Store, gives lang a `failed` job. - * A replay compares the `seq` and the `stream` of the command with History, not the `bodies`. + """Appends Records as the Workflow Producer and returns ResolveStreamAppend. A retry of a task + whose append has no result in History can write the batch again. Core sends appends to each + Stream in command order. + + An empty Store name selects the runtime under the empty name, or the only runtime if there + is no such entry. Invalid seq or Stream references, missing runtimes and a Store outage at + the task heartbeat fail the Workflow Task. Invalid batches return a failed job. + + Lang must accept results for appends it no longer awaits. The terminal Workflow command drops + unresolved appends. Replay matches seq and Stream and uses the result in History. """ DESCRIPTOR: google.protobuf.descriptor.Descriptor @@ -2009,68 +2002,34 @@ global___AppendToStream = AppendToStream @typing.final class ReadStream(google.protobuf.message.Message): - """Reads one page of a Stream, with the Records after `from_offset`. The result comes in one - `ResolveStreamRead` job, by the activation rules of `ResolveStreamAppend`. To read on, lang sends - a new `ReadStream` from the `last_offset` of the page. A Stream has no end that a read reports, - so the application's own last Record tells a reader to stop. - - A page is one answer of the Store. It has the Records that the Store has at once, up to - `max_records` and `max_bytes`, and Core never waits to fill it. A read with no Record after - `from_offset` waits up to `wait`, but at most the read time that its Workflow Task has left - (`StreamSettings::read_time`, half the task timeout by default, from the end of a replay). If - the Store answers with no Record before the wait is up, Core asks again from that answer's - `last_offset`, at most once per 100 ms. A page with no Record has the `last_offset` of the - Store's answer, which is `from_offset` if the Store moved past nothing. Its `wait_cut` is true if - the read time ended the wait before `wait`. - - At the read limit a read with a `wait` gives a page with no Record and `wait_cut`. A read with no - `wait` goes on, since only the Store can say that the Stream has no Record after its offset. - Before the limit Core keeps the task open while a read runs, unless the task has a command or a - message for the server. - - Before the task completes, each read that had no answer in it gets a check, which is one Store - call with no wait and a short deadline of 1 s. A command waits for the check and no longer. If - the check gets Records, the task gives them, or holds them for the first activation of the next - task if it has a command. If it gets no Record, a read with a `wait` stops and starts again when - the next task opens, and a read with no `wait` gives the page with no Record. After the read - limit each new read of the task is a check. So a read on an idle Stream never makes a new task, - and a drain with no `wait` ends in its task. - - Core asks for a new task when it knows that the Stream has Records for an open read. It knows - that when the Store gave Records after the page that the read continues from, or when the task - holds back the read's page. It also asks for a new task when the read result budget of the task - holds back a read. A query answer and the heartbeat of a Local Activity or an append ask for a - new task whatever the reads say. - - A Store outage fails the Workflow Task, as for an append, and never reaches lang as a read - result. That's the case if a check fails or gets no answer by its deadline, or if a read has had - no answer since a failed try at the read limit, at the completion or at the heartbeat. The - failure message then starts with `StreamStoreUnavailable:`. - - One Workflow Task gives at most 16 MiB of Records. A page that doesn't fit comes in the first - activation of the next task. Once a task gave 256 read results, its new reads get no check and - start when the next task opens, which Core asks for at once. - - No command cancels a read, so lang must accept the job of a read that nothing awaits. Core drops - a read that has no result when lang sends the Workflow's last command. - - The `core_stream_read` marker of the activation that gets the page keeps its offsets, the count - and a digest of its Records, and never the Records. A replay, also the replay for a query of a - closed Workflow, reads the page from the Store again, and fails if the Records are gone or - differ. So the Retention of the Stream must cover the life of the Workflow and the time in which - it gets queries. A replay reads the Records of all the read markers of History again, so a - reader should continue as new before those pass the 16 MiB that a Worker reads in one task. A - Worker with no runtime for the Store of a marker can't replay, and fails the task, or gives the - error as the answer of a legacy query. - - A `stream` with no Store name is on the Store of the Worker's Stream runtime under the empty - name, else of its only Stream runtime, as for an append. - - A replay compares the `seq`, the `stream` and the `from_offset` of the command with History, and - not the `max_records`, the `max_bytes` or the `wait`. It accepts a marker with no entry after any - task. After a replay Core doesn't know which Streams have Records after the pages of History, so - it learns that from the next answer of the Store. A negative `wait`, `max_records` or - `max_bytes`, a `from_offset` over 1024 bytes, or a bad `seq` or `stream` fails the Workflow Task. + """Reads one page after from_offset. A reader continues from the page's last_offset until an + application Record tells it to stop. ResolveStreamRead follows the ordering of ResolveStreamAppend. + + A page returns as soon as Records are available. For an empty page Core polls from the Store's + returned offset at most once per 100 ms until wait expires or the task reaches its read time. + StreamSettings.read_time defaults to half the task timeout and starts when replay ends. + An empty page reports wait_cut when the task read time shortens the wait. + + Before completing a task, Core checks unanswered reads with a nonblocking Store call and a + one-second deadline. If the task has a command or a server message, it waits only for this check. + Core carries available Records into the next task when a command must go first. An empty + blocking read resumes on a later task. An idle Stream alone does not request another task. + A nonblocking read can return an empty page in the current task, even after the read deadline. + + Each task delivers at most 16 MiB of encoded Records. After 256 read results, new reads wait + for the next task. Reads already running can finish. A single Record over 16 MiB gives a failed + job with stream_unsupported. A Store outage or an unanswered check fails the Workflow Task with + StreamStoreUnavailable. Lang must accept results it no longer awaits. The terminal Workflow + command drops unresolved reads. + + Replay matches seq, Stream and from_offset. It rereads the recorded range and verifies the + Record count and digest. Retention must cover Workflow replay and later queries. Missing or + changed Records give a StreamReplay error. A missing runtime or unavailable Store fails the + Workflow Task, or the legacy query. Replay loads History in parts. The Store selection rules + are the same as for AppendToStream. + + Negative limits or wait, an offset over 1024 bytes, or an invalid seq or Stream reference + fail the Workflow Task. """ DESCRIPTOR: google.protobuf.descriptor.Descriptor @@ -2090,8 +2049,8 @@ class ReadStream(google.protobuf.message.Message): max_records: builtins.int """The maximum number of Records in the page, which is 256 if this is zero.""" max_bytes: builtins.int - """The maximum size of the Records in the page, which is 4 MiB if this is zero. Core asks the - Store for at most 16 MiB. One larger Record still comes as a page. + """Page size in encoded Record bytes. Zero selects 4 MiB. A single Record may exceed this + request limit up to the Workflow Task limit of 16 MiB. """ @property def stream(self) -> temporalio.api.sdk.v1.stream_pb2.StreamRef: ... diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index 816a90e0df..70325823a6 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit 816a90e0df94154fa0683b52587ccb72e86bec26 +Subproject commit 70325823a6c4a3a290cde8b3bf752975d72fbd39 diff --git a/temporalio/bridge/src/lib.rs b/temporalio/bridge/src/lib.rs index 246a6059a9..71a4d66d55 100644 --- a/temporalio/bridge/src/lib.rs +++ b/temporalio/bridge/src/lib.rs @@ -54,7 +54,6 @@ fn temporal_sdk_bridge(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { (wrap_pyfunction!(runtime::shutdown_runtimes, m)?,), )?; - // Stream stuff m.add_function(wrap_pyfunction!(streams::call_stream_store, m)?)?; m.add_function(wrap_pyfunction!(streams::check_stream_append, m)?)?; diff --git a/temporalio/bridge/src/streams.rs b/temporalio/bridge/src/streams.rs index e5c9b8edc7..c4244b991c 100644 --- a/temporalio/bridge/src/streams.rs +++ b/temporalio/bridge/src/streams.rs @@ -21,8 +21,6 @@ use temporalio_streams::{ use crate::runtime; -/// A Stream Store that is a Python object. `caller` is a `_StoreCaller` of -/// `temporalio.client._stream_store`, and its `call` runs on the event loop of the task locals. struct PythonStore { caller: Py, event_loop_task_locals: Arc>, @@ -60,8 +58,7 @@ impl OnTask { } } -/// The guard that cancels the Python task of a call that its caller drops before the answer. Core -/// drops a call when it stops a read, evicts a run, gives up a try or shuts down. +// Dropping a Core future must also stop its Python Store task. struct CallGuard<'a> { state: Arc>, task_locals: &'a pyo3_async_runtimes::TaskLocals, @@ -71,8 +68,7 @@ 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 { - // The loop may be closed and the interpreter may be finalizing, and then there's no - // task left to cancel. asyncio lets another thread only schedule the cancel. + // 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); @@ -138,7 +134,6 @@ impl PythonStore { } } -/// Returns the error of a call that can't reach Python, since the interpreter is shutting down. 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" @@ -199,12 +194,8 @@ impl StreamStore for PythonStore { } } -/// Calls the Python Store of `caller` for one Stream operation through a `StreamRuntime`, which -/// checks the request and the response. The request and the response are those of a Store, with -/// the Stream id, so a Store can run the checks of the runtime around itself. A create and an -/// append need their `request_id`, which the other operations don't take. The awaitable raises -/// `StreamError` for a failed call. The runtime has no limit of a batch, since the SDK that calls -/// the Store has those in its Stream config. +// Stores use Core's request and response checks without duplicating its validation rules. +// The calling SDK checks batch limits from its Stream config. #[pyfunction] #[pyo3(signature = (runtime_ref, caller, operation, request, request_id=None))] pub fn call_stream_store<'p>( @@ -285,8 +276,6 @@ pub fn call_stream_store<'p>( } } -/// Returns the ref that the runtime takes for a Store request's Stream id. The runtime gives the -/// Store only the id, so the ref needs no Store name. fn stream_ref(id: String) -> sdk::StreamRef { sdk::StreamRef { id, diff --git a/temporalio/client/_client.py b/temporalio/client/_client.py index e6bdaebcd7..f98b21607e 100644 --- a/temporalio/client/_client.py +++ b/temporalio/client/_client.py @@ -307,7 +307,6 @@ def __init__( stream_config=stream_config, ) self._initial_config = config.copy() - # The id of this client as a Producer of Streams self._stream_producer_id = str(uuid.uuid4()) for plugin in plugins: diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index c188f8a7bc..0cdb4e273d 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -356,9 +356,9 @@ class StreamConfig: """ max_record_bytes: int = 1536 * 1024 - """Maximum size in bytes of one Record of an append or a live Workflow read. Defaults to 1.5 MiB. Must be greater than or - equal to one. The size is that of the stored Record, which counts its - Producer. + """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 @@ -414,7 +414,6 @@ def __post_init__(self) -> None: object.__setattr__(self, "_by_name", by_name) def _store(self, name: str) -> StreamStore: - """Return the Store with a name, raising :class:`ValueError` if none has it.""" store = self._by_name.get(name) if store is None: raise ValueError(f"No Stream Store found with name '{name}'") @@ -426,9 +425,6 @@ def _store_for( target: StorageDriverActivityInfo | StorageDriverWorkflowInfo | None, namespace: str, ) -> StreamStore: - """Return the Store of a call on ``ref``, the ref of the call's request, - raising :class:`ValueError` if there is none. - """ if ref.store: return self._store(ref.store) if self.store_selector is None: @@ -443,12 +439,10 @@ def _store_for( return selected def _limits(self) -> tuple[int, int, int]: - """Return the three limits, in the order in which the bridge takes them.""" return self.max_record_bytes, self.max_batch_bytes, self.max_batch_records def _request_ref(request: google.protobuf.message.Message) -> sdk.StreamRef: - """Return the ref of an SDK Stream request, which is ``stream_ref`` in a create.""" if isinstance(request, sdk.CreateStreamRequest): return request.stream_ref assert isinstance( @@ -473,18 +467,12 @@ def _request_ref(request: google.protobuf.message.Message) -> sdk.StreamRef: def _store_operation(name: str) -> tuple[str, _Message, _Message]: - """Return the :py:class:`StreamStore` method of a Stream operation, with the - classes of its Store request and of its Store response. - """ return _STORE_OPERATIONS[name] def _sdk_request_type( # pyright: ignore[reportUnusedFunction] name: str, ) -> _Message: - """Return the class of the SDK request of a Stream operation, which has the - ref of its Stream. - """ operation = _STREAM_SERVICE.operation_definitions[name] converter = _get_transfer_type_converter(operation.input_type) assert converter and converter.transfer_type @@ -494,9 +482,6 @@ def _sdk_request_type( # pyright: ignore[reportUnusedFunction] def _store_request( request: google.protobuf.message.Message, ) -> google.protobuf.message.Message: - """Return the Store request of an SDK request, which has the id of the Stream - of the request's ref. - """ stream_id = _request_ref(request).id if isinstance(request, sdk.CreateStreamRequest): return CreateStreamRequest( @@ -634,7 +619,6 @@ async def _call_store( # pyright: ignore[reportUnusedFunction] def _activity_target() -> StorageDriverActivityInfo | None: - """Return the running Activity as the target of a Stream call, if there is one.""" if not temporalio.activity.in_activity(): return None info = temporalio.activity.info() @@ -650,9 +634,6 @@ async def _call_stream_store( # pyright: ignore[reportUnusedFunction] client: temporalio.client.Client, input: temporalio.client.StartNexusOperationInput, ) -> temporalio.client.NexusOperationHandle[Any]: - """Call the Stream Store of a Stream operation of a client, and return a handle - that has its result. - """ stream_config = client._config["stream_config"] if stream_config is None: raise ValueError( @@ -679,7 +660,6 @@ async def _call_stream_store( # pyright: ignore[reportUnusedFunction] request_id, input.rpc_timeout, ) - # Each generated Stream call gives its result type. result_type: Any = input.result_type handle: temporalio.client.NexusOperationHandle[Any] = ( temporalio.client.NexusOperationHandle( diff --git a/temporalio/nexus/system/stream_service/client/_resources/stream.py b/temporalio/nexus/system/stream_service/client/_resources/stream.py index afa0d63b5d..04f5b6ca44 100644 --- a/temporalio/nexus/system/stream_service/client/_resources/stream.py +++ b/temporalio/nexus/system/stream_service/client/_resources/stream.py @@ -129,11 +129,10 @@ async def read_pages( Args: from_offset: Read after this offset. Empty means from the beginning. - max_records: The maximum number of Records in one page. Zero uses the Store - default. + max_records: The maximum Records per page. Zero uses the configured default. wait: How long to wait for a new Record. Unset returns immediately. - max_bytes: The maximum bytes of Records in a page. A larger Record is - returned alone. + max_bytes: The page byte target. One larger Record can be returned unless an + SDK hard limit rejects it. """ request = ReadRecordsRequest( ref=self.ref, @@ -181,11 +180,10 @@ def read( Args: from_offset: Read after this offset. Empty means from the beginning. - max_records: The maximum number of Records in one page. Zero uses the Store - default. + max_records: The maximum Records per page. Zero uses the configured default. wait: How long to wait for a new Record. Unset returns immediately. - max_bytes: The maximum bytes of Records in a page. A larger Record is - returned alone. + max_bytes: The page byte target. One larger Record can be returned unless an + SDK hard limit rejects it. """ request = ReadRecordsRequest( ref=self.ref, diff --git a/temporalio/nexus/system/stream_service/workflow/_resources/stream.py b/temporalio/nexus/system/stream_service/workflow/_resources/stream.py index 2e2ea161d4..c85d0dc354 100644 --- a/temporalio/nexus/system/stream_service/workflow/_resources/stream.py +++ b/temporalio/nexus/system/stream_service/workflow/_resources/stream.py @@ -94,11 +94,10 @@ async def read_pages( Args: from_offset: Read after this offset. Empty means from the beginning. - max_records: The maximum number of Records in one page. Zero uses the Store - default. + max_records: The maximum Records per page. Zero uses the configured default. wait: How long to wait for a new Record. Unset returns immediately. - max_bytes: The maximum bytes of Records in a page. A larger Record is - returned alone. + max_bytes: The page byte target. One larger Record can be returned unless an + SDK hard limit rejects it. """ request = ReadRecordsRequest( ref=self.ref, @@ -133,11 +132,10 @@ def read( Args: from_offset: Read after this offset. Empty means from the beginning. - max_records: The maximum number of Records in one page. Zero uses the Store - default. + max_records: The maximum Records per page. Zero uses the configured default. wait: How long to wait for a new Record. Unset returns immediately. - max_bytes: The maximum bytes of Records in a page. A larger Record is - returned alone. + max_bytes: The page byte target. One larger Record can be returned unless an + SDK hard limit rejects it. """ request = ReadRecordsRequest( ref=self.ref, diff --git a/temporalio/worker/_workflow_streams.py b/temporalio/worker/_workflow_streams.py index 4f1b196b55..53cd68bfbb 100644 --- a/temporalio/worker/_workflow_streams.py +++ b/temporalio/worker/_workflow_streams.py @@ -124,9 +124,6 @@ def stop(_: asyncio.Task[OutputT]) -> None: return _StreamCall(task) def _store(self, ref: sdk.StreamRef) -> StreamStore: - """Return the Store of a call on ``ref``, from the Stream config of the - Worker's client. A call with no Store fails the Workflow Task. - """ config = self._stream_config() if config is None: raise self._fail_task( @@ -201,9 +198,6 @@ def _schedule_store_call( request: google.protobuf.message.Message, request_id: str | None, ) -> asyncio.Future[Any]: - """Schedule the SDK's Local Activity for a create or a describe on the - Store named ``store``. - """ instance = self._instance activity = instance._outbound.start_local_activity( StartLocalActivityInput( @@ -234,7 +228,6 @@ def _response( request: google.protobuf.message.Message, result: asyncio.Future[Any], ) -> google.protobuf.message.Message: - """Return the response message of a call whose ``result`` is done.""" if isinstance(request, sdk.AppendRecordsRequest): appended = result.result() return proto.AppendRecordsResponse( @@ -414,9 +407,6 @@ def _stream_error_from_failure( def _for_core( stream_config: StreamConfig | None, ) -> tuple[set[str], tuple[int, int, int] | None]: - """Return the Store names and the limits of a Stream config, which Core has - from the start of a worker. - """ if stream_config is None: return set(), None return set(stream_config._by_name), stream_config._limits() @@ -455,9 +445,6 @@ def store(name: str) -> StreamStore: def _check_stream_swap( # pyright: ignore[reportUnusedFunction] existing: StreamConfig | None, new: StreamConfig | None ) -> None: - """Raise if the new client of a worker has other Stream Stores or other - limits than the existing one. - """ names, limits = _for_core(existing) new_names, new_limits = _for_core(new) if new_names != names: From b26dbb099c1ba0385628d24c5242c6c81fe2702c Mon Sep 17 00:00:00 2001 From: Mohammad Dashti Date: Fri, 27 Nov 2026 02:29:51 -0700 Subject: [PATCH 41/50] Correct the Store cancellation comments --- temporalio/bridge/src/streams.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/temporalio/bridge/src/streams.rs b/temporalio/bridge/src/streams.rs index c4244b991c..dadd366141 100644 --- a/temporalio/bridge/src/streams.rs +++ b/temporalio/bridge/src/streams.rs @@ -68,7 +68,7 @@ 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. + // `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); @@ -80,7 +80,6 @@ impl Drop for CallGuard<'_> { } impl PythonStore { - // Core doesn't catch Store panics, so failures must return errors. async fn call( &self, operation: &'static str, From a98a63ddfef41f85a8e424c31e8ccb27687928a7 Mon Sep 17 00:00:00 2001 From: Mohammad Dashti Date: Fri, 27 Nov 2026 10:45:43 -0700 Subject: [PATCH 42/50] Simplify Stream routing and replay tests Fixed scenarios make routing, cancellation and replay failures easier to diagnose. --- tests/nexus/test_streams.py | 439 +++++++++++--------------- tests/test_converter.py | 77 ++--- tests/worker/test_workflow_streams.py | 432 ++++++++++++------------- 3 files changed, 401 insertions(+), 547 deletions(-) diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index cd9ce0f815..a0131ac07c 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -59,6 +59,7 @@ from tests.helpers.streams import ( FaultStore, Hold, + answers, core_failure, failure_note, run_with_virtual_clock, @@ -120,181 +121,156 @@ def _producer_proto(producer: Any) -> Producer: return message -async def test_a_client_call_reaches_the_right_store_as_written() -> None: - request_ids: set[str] = set() - for seed in range(300): - with failure_note(f"seed {seed}"): - await _routing_script(seed, random.Random(seed), request_ids) - - -async def _routing_script(seed: int, rng: random.Random, request_ids: set[str]) -> None: - to_payload = temporalio.converter.PayloadConverter.default.to_payload +@pytest.mark.parametrize("operation", ["create", "append", "read", "describe"]) +@pytest.mark.parametrize( + "routing", ["only", "selector", "explicit", "unknown", "unregistered"] +) +@pytest.mark.parametrize("in_activity", [False, True]) +async def test_a_client_call_reaches_the_selected_store( + operation: str, routing: str, in_activity: bool +) -> None: service_client = Mock(spec=ServiceClient) - names = rng.sample("abcd", rng.randrange(1, 5)) - has_selector = len(names) > 1 or rng.random() < 0.5 - stores = [FaultStore(name) for name in names] + a, b = FaultStore("a"), FaultStore("b") + stores = [a] if routing == "only" else [a, b] + selected = FaultStore("other") if routing == "unregistered" else b selects: list[StreamSelectContext] = [] - # The Store that the selector returns at its next call, which may be unregistered. - selected = [FaultStore("other")] def selector(context: StreamSelectContext) -> FaultStore: selects.append(context) - return selected[0] + return selected - # A client with no Stream config refuses a call, and the server gets nothing. - with pytest.raises(ValueError): - await Client(service_client).create_stream(id="s") - assert not service_client.mock_calls - ref_stores: list[tuple[str | None, str | None]] = [] + ref_store = {"explicit": "a", "unknown": "unknown"}.get(routing) + intercepted: list[tuple[str | None, str | None]] = [] client = Client( service_client, - interceptors=[_Interceptor(lambda next: _RecordingOutbound(next, ref_stores))], + interceptors=[_Interceptor(lambda next: _RecordingOutbound(next, intercepted))], stream_config=StreamConfig( - stores=stores, store_selector=selector if has_selector else None + stores, store_selector=None if routing == "only" else selector ), ) activity = ActivityEnvironment() activity.info = dataclasses.replace( - activity.info, activity_id=f"activity-{seed}", activity_run_id="run" + activity.info, activity_id="activity", activity_run_id="run" ) - # A write has the Producer of its caller, which is the client or the Activity. - producers = [ - Producer( + producer = ( + _producer_proto(activity.run(current_producer)) + if in_activity + else Producer( client=ClientProducer(namespace="default", id=client._stream_producer_id) - ), - _producer_proto(activity.run(current_producer)), - ] - created: list[tuple[Any, FaultStore]] = [] - for step in range(12): - with failure_note(f"step {step}"): - selected[0] = rng.choice([*stores, *stores, FaultStore("other")]) - stream_id = f"stream-{seed}-{step}" - ref_store = rng.choice([None, None, "unknown", *names]) - store: FaultStore | None - in_activity = rng.random() < 0.3 - expected: Message - operation = rng.choice(["create", "read", "describe", "created"]) - if operation == "created" and not created: - operation = "create" - if operation == "created": - # A created Stream stays on its Store, whatever the selector picks at this call. - stream, store = rng.choice(created) - ref_store = stream.ref.store - if rng.random() < 0.5: - bodies = [rng.randrange(100) for _ in range(rng.randrange(3))] - call = stream.append(*bodies) - expected = proto.AppendRecordsRequest( - stream_id=stream.ref.id, - producer=producers[in_activity], - records=[ - AppendRecord(body=to_payload(body)) for body in bodies - ], - ) - else: - call = stream.describe() - expected = proto.DescribeStreamRequest(stream_id=stream.ref.id) - else: - store = next((s for s in stores if s.name() == ref_store), None) - if ref_store is None and has_selector: - store = selected[0] if selected[0] in stores else None - elif ref_store is None: - store = stores[0] - ref = StreamRef[int](id=stream_id, store=ref_store) - match operation: - case "create": - policy = rng.choice(list(StreamIdConflictPolicy.values())) - call = client.create_stream( - id=stream_id, - store=ref_store, - id_conflict_policy=ConflictPolicy(policy) - if policy - else None, - body_type=int, - ) - expected = proto.CreateStreamRequest( - stream_id=stream_id, id_conflict_policy=policy - ) - case "read": - expected = proto.ReadRecordsRequest( - stream_id=stream_id, - from_offset=rng.randbytes(rng.randrange(3)), - max_records=rng.choice([0, 1, 2**31 - 1]), - max_bytes=rng.choice([0, 1, 2**62]), - ) - wait = rng.choice([None, 0, 1, 30 * 24 * 3600]) - # A Store gets no wait for a wait of zero. - if wait: - expected.wait.FromSeconds(wait) - call = client.get_stream(ref).read_page( - from_offset=expected.from_offset or None, - max_records=expected.max_records or None, - wait=None if wait is None else timedelta(seconds=wait), - max_bytes=expected.max_bytes or None, - ) - case _: - call = client.get_stream(ref).describe() - expected = proto.DescribeStreamRequest(stream_id=stream_id) - logs = [list(s.requests) for s in stores] - del selects[:], ref_stores[:] - - async def run_call() -> Any: - # A read or a describe of a Stream that nobody created fails in the Store. - try: - return await call - except StreamError as err: - return err - - if store is None: - with pytest.raises(ValueError): - await (activity.run(run_call) if in_activity else run_call()) - assert [s.requests for s in stores] == logs - continue - result = await (activity.run(run_call) if in_activity else run_call()) - if ( - isinstance(expected, proto.AppendRecordsRequest) - and not expected.records - ): - # The SDK refuses a batch with no Record before the Store gets it. - assert isinstance(result, StreamError) - assert result.reason == _INVALID_ARGUMENT - assert [s.requests for s in stores] == logs - continue - for other, log in zip(stores, logs): - if other is not store: - assert other.requests == log - [(request, request_id)] = store.calls[len(logs[stores.index(store)]) :] - if isinstance( - request, (proto.CreateStreamRequest, proto.AppendRecordsRequest) - ): - assert request_id and request_id not in request_ids - request_ids.add(request_id) - else: - assert request_id is None - assert request == expected - assert not service_client.mock_calls - # An interceptor sees the ref as the caller wrote it, also after the call. - assert ref_stores == [(ref_store, ref_store)] - target = None - if in_activity: - target = StorageDriverActivityInfo( - namespace="default", - id=f"activity-{seed}", - run_id="run", - type="unknown", - ) - used_selector = has_selector and ref_store is None - assert selects == ( - [ - StreamSelectContext( - id=stream_id, target=target, namespace=client.namespace - ) - ] - if used_selector - else [] + ) + ) + for store in stores: + await store.memory.create_stream( + proto.CreateStreamRequest(stream_id="s"), request_id="setup" + ) + store.faults["read_records"].extend([answers(proto.ReadRecordsResponse())] * 2) + stream = client.get_stream(StreamRef[int](id="s", store=ref_store)) + payload = temporalio.converter.PayloadConverter.default.to_payload + expected: Message + if operation == "create": + expected = proto.CreateStreamRequest( + stream_id="s", + id_conflict_policy=StreamIdConflictPolicy.STREAM_ID_CONFLICT_POLICY_USE_EXISTING, + ) + elif operation == "append": + expected = proto.AppendRecordsRequest( + stream_id="s", + producer=producer, + records=[AppendRecord(body=payload(i)) for i in (3, 5)], + ) + elif operation == "read": + expected = proto.ReadRecordsRequest( + stream_id="s", max_records=2, max_bytes=4096 + ) + expected.wait.FromSeconds(5) + else: + expected = proto.DescribeStreamRequest(stream_id="s") + + async def call() -> Any: + if operation == "create": + return await client.create_stream( + id="s", + store=ref_store, + body_type=int, + id_conflict_policy=ConflictPolicy.StreamIdConflictPolicyUseExisting, + ) + if operation == "append": + return await stream.append(3, 5) + if operation == "read": + return await stream.read_page( + max_records=2, max_bytes=4096, wait=timedelta(seconds=5) + ) + return await stream.describe() + + if routing in ("unknown", "unregistered"): + with pytest.raises(ValueError): + await (activity.run(call) if in_activity else call()) + assert not a.calls and not b.calls and not service_client.mock_calls + return + + for _ in range(2): + result = await (activity.run(call) if in_activity else call()) + if operation == "create": + assert result.ref == StreamRef( + id="s", store="b" if routing == "selector" else "a" ) - if operation == "create": - assert result.ref == StreamRef(id=stream_id, store=store.name()) - created.append((result, store)) + chosen, other = (b, a) if routing == "selector" else (a, b) + assert chosen.requests == [expected, expected] + assert not other.calls and not service_client.mock_calls + ids = [request_id for _, request_id in chosen.calls] + if operation in ("create", "append"): + assert all(ids) and ids[0] != ids[1] + else: + assert ids == [None, None] + assert intercepted == [(ref_store, ref_store)] * 2 + target = ( + StorageDriverActivityInfo( + namespace="default", id="activity", run_id="run", type="unknown" + ) + if in_activity + else None + ) + assert selects == ( + [StreamSelectContext(id="s", target=target, namespace="default")] * 2 + if routing == "selector" + else [] + ) + + +async def test_a_client_without_stream_config_does_not_call_the_server() -> None: + service_client = Mock(spec=ServiceClient) + with pytest.raises(ValueError): + await Client(service_client).create_stream(id="s") + assert not service_client.mock_calls + + +async def test_a_created_stream_keeps_its_selected_store() -> None: + a, b = FaultStore("a"), FaultStore("b") + selected = a + client = Client( + Mock(spec=ServiceClient), + stream_config=StreamConfig([a, b], store_selector=lambda _: selected), + ) + stream = await client.create_stream(id="s", body_type=int) + selected = b + await stream.append(1) + await stream.describe() + assert stream.ref.store == "a" + assert [type(request) for request in a.requests] == [ + proto.CreateStreamRequest, + proto.AppendRecordsRequest, + proto.DescribeStreamRequest, + ] + assert not b.calls + + +async def test_an_empty_client_append_does_not_reach_the_store() -> None: + store = FaultStore() + client = Client(Mock(spec=ServiceClient), stream_config=StreamConfig([store])) + with pytest.raises(StreamError) as raised: + await client.get_stream(StreamRef[int](id="s")).append() + assert raised.value.reason == _INVALID_ARGUMENT + assert not store.calls async def test_a_stream_error_keeps_its_reason_on_every_path() -> None: @@ -345,124 +321,67 @@ async def test_a_stream_error_keeps_its_reason_on_every_path() -> None: class _FakeReads(temporalio.client.OutboundInterceptor): - """Answers each read with the next page of a generated Stream.""" - - def __init__( - self, next: temporalio.client.OutboundInterceptor, rng: random.Random - ) -> None: + def __init__(self, next: temporalio.client.OutboundInterceptor) -> None: super().__init__(next) - self._rng = rng - self.records = 0 - """The number of Records of the Stream, which a test can raise.""" + self.pages = iter([(1, 2), (), (3, 4), (), (4, 5)]) self.starts: list[int] = [] - """The Record after which each read started, in the order of the reads.""" self.waits: list[timedelta | None] = [] - """The wait of each read, in the order of the reads.""" async def start_nexus_operation( self, input: temporalio.client.StartNexusOperationInput ) -> NexusOperationHandle[Any]: request: ReadRecordsRequest[int] = input.arg - start = int.from_bytes(request.from_offset or b"", "big") - self.starts.append(start) + self.starts.append(int.from_bytes(request.from_offset or b"", "big")) self.waits.append(request.wait) - size = self._rng.randrange(1, 4) - # A read with a wait can see no Record come within its wait, also when more - # come later. With no wait, a Store answers with no Record only at the end. - if request.wait and self._rng.random() < 0.2: - size = 0 - end = min(self.records, start + size) + records = [ + StreamRecord(body=at, offset=at.to_bytes(8, "big")) + for at in next(self.pages) + ] page = ReadRecordsResponse( - records=[ - StreamRecord(body=at, offset=at.to_bytes(8, "big")) - for at in range(start + 1, end + 1) - ], - last_offset=request.from_offset or None, + records=records, + last_offset=records[-1].offset if records else request.from_offset, ) - if page.records: - page.last_offset = page.records[-1].offset handle: NexusOperationHandle[Any] = NexusOperationHandle(Mock(), input.id) handle._known_outcome = page return handle -async def test_a_read_gives_each_record_once_past_pages_with_no_record() -> None: - for seed in range(300): - with failure_note(f"seed {seed}"): - await _read_script(random.Random(seed)) - - -async def _read_script(rng: random.Random) -> None: +@pytest.mark.parametrize("wait", [None, timedelta(0), timedelta(seconds=5)]) +async def test_a_read_resumes_after_a_partial_page_and_skips_empty_pages( + wait: timedelta | None, +) -> None: fake: list[_FakeReads] = [] def outbound(next: temporalio.client.OutboundInterceptor) -> _FakeReads: - fake.append(_FakeReads(next, rng)) + fake.append(_FakeReads(next)) return fake[0] client = Client(Mock(spec=ServiceClient), interceptors=[_Interceptor(outbound)]) stream = client.get_stream(StreamRef[int](id="s")) [reads] = fake - wait = rng.choice([None, timedelta(0), timedelta(seconds=5)]) got: list[int] = [] later = _support.DEFAULT_READ_WAIT if wait is None else wait - for _ in range(rng.randrange(1, 4)): - # More Records come after each read, and a reader picks up where it stopped. - reads.records += rng.randrange(1, 6) + for stop_at in (3, 5): offset = got[-1].to_bytes(8, "big") if got else None - # A Stream has no end, so the reader stops at a Record that it knows of. - stop_at = rng.randrange(len(got) + 1, reads.records + 1) - first_read = len(reads.starts) async for record in stream.read(from_offset=offset, wait=wait): got.append(record.body) - if len(got) == stop_at: + if record.body == stop_at: break - # A page with no Record before the caller's last Record doesn't end the read. - assert got == list(range(1, stop_at + 1)) - # The read stops at the caller's last Record, so no read starts after it. - assert all(start < stop_at for start in reads.starts[first_read:]) - # The first read has the caller's wait. A later one has it too, or the - # default wait when the caller gave none. - assert reads.waits[first_read:] == [wait] + [later] * ( - len(reads.waits) - first_read - 1 - ) + assert got == [1, 2, 3, 4, 5] + assert reads.starts == [0, 2, 2, 3, 3] + assert reads.waits == [wait, later, later, wait, later] @dataclasses.dataclass(frozen=True) class _WriterInfo: - """A generated writer of a Stream, with the fields that its Producer takes.""" - kind: str - """The field of the kind in the proto ``Producer``.""" namespace: str workflow_id: str run_id: str activity_id: str attempt: int time: datetime - """The scheduled time of an Activity attempt, or the started time of a task.""" event_id: int - """The started event id of the task of a Local Activity, or the scheduled event id - of an Activity of a Workflow, which is zero when SDK Core couldn't read it.""" - - -def _writer_info(rng: random.Random) -> _WriterInfo: - def text() -> str: - return "".join(rng.choice("ab:/ '\"é") for _ in range(rng.randrange(1, 5))) - - kinds = ["workflow", "local_activity", "workflow_activity", "standalone_activity"] - kind = rng.choice(kinds) - return _WriterInfo( - kind=kind, - namespace=text(), - workflow_id=text(), - run_id=text(), - activity_id=text(), - attempt=rng.randrange(1, 9), - time=datetime.fromtimestamp(rng.randrange(10**9), timezone.utc), - event_id=rng.choice([0, rng.randrange(3, 99)]) - if kind == "workflow_activity" - else rng.randrange(3, 99), - ) def _default_producer(writer: _WriterInfo) -> Any: @@ -526,15 +445,37 @@ def _expected_producer(writer: _WriterInfo) -> Producer: return producer -def test_a_writer_is_one_producer_on_each_attempt() -> None: - for seed in range(300): - with failure_note(f"seed {seed}"): - rng = random.Random(seed) - writer = _writer_info(rng) - producer = _producer_proto(_default_producer(writer)) - assert producer == _expected_producer(writer) +@pytest.mark.parametrize( + ("kind", "event_id"), + [ + ("workflow", 7), + ("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 + - # Two Streams of one client have one Producer, and two clients have two. +def test_a_client_uses_one_producer_for_all_its_streams() -> None: service_client = Mock(spec=ServiceClient) config = StreamConfig(stores=[FaultStore()]) clients = [Client(service_client, stream_config=config) for _ in range(2)] @@ -548,17 +489,6 @@ def test_a_writer_is_one_producer_on_each_attempt() -> None: assert first.client.namespace == "default" and first.client.id -def test_a_stored_producer_comes_back_as_a_producer() -> None: - converter = temporalio.converter.PayloadConverter.default - for seed in range(50): - with failure_note(f"seed {seed}"): - producer = _default_producer(_writer_info(random.Random(seed))) - # A value such as a heartbeat detail comes back with no type hint. - [stored] = converter.from_payloads(converter.to_payloads([producer])) - assert as_producer(stored) == producer - assert as_producer(producer) is producer - - @dataclasses.dataclass class _Turn: text: str @@ -650,7 +580,6 @@ def test_each_stream_module_can_be_the_first_import() -> None: for module in pkgutil.walk_packages(system.__path__, system.__name__ + ".") ), ] - assert len(modules) > 15 def first_import(module: str) -> str: imported = subprocess.run( diff --git a/tests/test_converter.py b/tests/test_converter.py index 1e34c7de1d..5c48a36215 100644 --- a/tests/test_converter.py +++ b/tests/test_converter.py @@ -4,12 +4,11 @@ import inspect import ipaddress import logging -import random import sys import traceback import typing from collections import deque -from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence +from collections.abc import Iterable, Mapping, MutableMapping, Sequence from dataclasses import dataclass from datetime import datetime, timedelta, timezone from enum import Enum, IntEnum, StrEnum @@ -716,64 +715,28 @@ def test_json_generic_dataclass_round_trip(monkeypatch: pytest.MonkeyPatch): _decode_typed(monkeypatch, GenericDataClass, GenericPairDataClass) - # Each type argument, with a function that makes a value of it - arguments: list[tuple[Any, Callable[[random.Random], Any]]] = [ - (int, lambda rng: rng.randrange(100)), - (str, lambda rng: f"text {rng.randrange(100)}"), - (list[int], lambda rng: [rng.randrange(100) for _ in range(rng.randrange(3))]), - ( - MyDataClass, - lambda rng: MyDataClass("foo", rng.randrange(100), SerializableEnum.FOO), - ), - ( - GenericDataClass[str], - lambda rng: GenericDataClass(f"text {rng.randrange(100)}"), - ), - ] - - def generic( - rng: random.Random, make: Callable[[random.Random], Any], depth: int - ) -> GenericDataClass[Any]: - return GenericDataClass( - value=make(rng), - items=[make(rng) for _ in range(rng.randrange(3))], - nested=generic(rng, make, depth - 1) - if depth and rng.random() < 0.7 - else None, - maybe=make(rng) if rng.random() < 0.5 else None, - ) - - for seed in range(200): - rng = random.Random(seed) - argument, make = rng.choice(arguments) - value = generic(rng, make, 2) + for argument, value in [ + (int, GenericDataClass(1, items=[2], nested=GenericDataClass(3), maybe=4)), + (str, GenericDataClass("text")), + (list[int], GenericDataClass([1], items=[[2], []], maybe=[3])), + (MyDataClass, GenericDataClass(MyDataClass("foo", 1, SerializableEnum.FOO))), + (GenericDataClass[str], GenericDataClass(GenericDataClass("nested"))), + ]: payload = converter.to_payload(value) assert payload decoded = converter.from_payload(payload, generic_type[argument]) - assert decoded == value, f"seed {seed}" - assert decoded.__orig_class__ == generic_type[argument], f"seed {seed}" - - # A value of another type argument fails or converts as it does for a field - # of that type in a plain dataclass. - other, _ = rng.choice(arguments) - plain = dataclasses.make_dataclass("Plain", [("value", other)]) - payload = converter.to_payload({"value": make(rng)}) - assert payload - outcomes: list[Any] = [] - for hint in (generic_type[other], plain): - try: - outcomes.append(converter.from_payload(payload, hint).value) - except Exception as err: - outcomes.append(type(err)) - assert outcomes[0] == outcomes[1], f"seed {seed}" - - # Each of two type arguments goes to its own parameter. - second, make_second = rng.choice(arguments) - pair = GenericPairDataClass(key=make(rng), value=make_second(rng)) - payload = converter.to_payload(pair) - assert payload - decoded = converter.from_payload(payload, pair_type[argument, second]) - assert decoded == pair, f"seed {seed}" + assert decoded == value + assert decoded.__orig_class__ == generic_type[argument] + + payload = converter.to_payload({"value": "not an integer"}) + assert payload + with pytest.raises(TypeError): + converter.from_payload(payload, generic_type[int]) + + pair = GenericPairDataClass(key=1, value="text") + payload = converter.to_payload(pair) + assert payload + assert converter.from_payload(payload, pair_type[int, str]) == pair def test_json_type_hints(): diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py index a8bde15eb8..f457452397 100644 --- a/tests/worker/test_workflow_streams.py +++ b/tests/worker/test_workflow_streams.py @@ -54,7 +54,6 @@ WorkflowActivationJob, ) from temporalio.bridge.proto.workflow_commands import ( - ActivityCancellationType, AppendToStream, CompleteWorkflowExecution, ReadStream, @@ -280,37 +279,22 @@ async def test_stream_payloads_take_the_codec_with_no_context_and_no_storage() - @dataclass class _Call: - """One generated Stream call, and what Workflow code got for it.""" - operation: str - """One of ``create``, ``append`` and ``describe``.""" stream: str - """The id of the Stream. A call on a Stream that an earlier phase created uses the - Stream of that create.""" store: str | None = None - """The Store name that Workflow code gives, to a create or in a ref that it builds.""" bodies: Sequence[int] = () cancel: bool = False refusal: StreamErrorReason.ValueType | None = None - """The reason of the failure that the test answers the call with, if any.""" timeout: bool = False - """Whether the Local Activity of the call ends in a timeout.""" unserved: bool = False - """Whether the Local Activity of the call fails since the Worker lacks the Store.""" outcome: Any = None class _Script: - """The calls of :py:class:`_ScriptWorkflow`, which makes the calls of one phase - together and then waits for all of them, and what its interceptor saw. - """ - phases: list[list[_Call]] = [] late_cancels = False - """Whether a cancel comes after the task of its call ran, and not before.""" intercepted: list[tuple[str, Any]] = [] local_activities: list[str] = [] - """The Activity of each Local Activity that the interceptor saw.""" @workflow.defn @@ -361,10 +345,6 @@ def init(self, outbound: temporalio.worker.WorkflowOutboundInterceptor) -> None: class _RecordingOutbound(temporalio.worker.WorkflowOutboundInterceptor): - """Logs the operation of the interceptor method of each Stream call, with its - request, and each Local Activity. - """ - def start_local_activity( self, input: temporalio.worker.StartLocalActivityInput ) -> workflow.ActivityHandle[Any]: @@ -384,248 +364,230 @@ async def start_describe_stream(self, request: Any) -> Any: return await super().start_describe_stream(request) -def _plan( - call: _Call, seq: int, ref_store: str, store: str, history_store: str -) -> tuple[WorkflowCommand, WorkflowActivationJob, Any]: - """Return the command that a call must send, the job that the test answers it - with, and what Workflow code must get for it. - - ``ref_store`` is the Store name of the ref that Workflow code passes, ``store`` - the name of the Store that the SDK chose for the call, and ``history_store`` the - one that the result of a create has. - """ +def _resolve_call(call: _Call, seq: int) -> WorkflowActivationJob: converter = temporalio.converter.DefaultPayloadConverter() - refused = None if call.refusal is None else core_failure(call.refusal) - command, job = WorkflowCommand(), WorkflowActivationJob() - outcome: Any + job = WorkflowActivationJob() if call.operation == "append": - bodies = converter.to_payloads(call.bodies) - stream = StreamRef(id=call.stream, store=store) - command.append_to_stream.CopyFrom( - AppendToStream(seq=seq, stream=stream, bodies=bodies) - ) - outcome = (b"first%d" % seq, b"last%d" % seq) job.resolve_stream_append.seq = seq - if refused: - job.resolve_stream_append.failed.CopyFrom(refused) + 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=outcome[0], last_offset=outcome[1]) + StreamAppended( + first_offset=b"first%d" % seq, last_offset=b"last%d" % seq + ) ) - else: - # The request of the Local Activity has the ref of Workflow code, and the - # Activity gets the name of the chosen Store next to it. - ref = StreamRef(id=call.stream, store=ref_store) - request: Message = DescribeStreamRequest(ref=ref) - request_id = None - described = DescribeStreamResponse(last_offset=b"last%d" % seq) - answer: Message = described - outcome = described.last_offset - if call.operation == "create": - # Each create of a run chain has the first run id as its request id. - request, request_id = CreateStreamRequest(stream_ref=ref), "first-run" - answer = CreateStreamResponse( - ref=StreamRef(id=call.stream, store=history_store), - created=seq % 2 == 0, + 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"), ) - outcome = (history_store, seq % 2 == 0 or None) - activity = command.schedule_local_activity - activity.seq = seq - activity.activity_id = str(seq) - activity.activity_type = _STORE_CALL - operation = request.DESCRIPTOR.name.removesuffix("Request") - activity.arguments.extend( - converter.to_payloads( - [operation, store, request.SerializeToString(), request_id] + ) + 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, + ), ) ) - activity.schedule_to_close_timeout.FromSeconds(5) - temporalio.common.RetryPolicy(maximum_attempts=1).apply_to_proto( - activity.retry_policy + else: + answer: Message = ( + CreateStreamResponse(ref=StreamRef(id=call.stream, store="b"), created=True) + if call.operation == "create" + else DescribeStreamResponse(last_offset=b"last%d" % seq) ) - activity.cancellation_type = ActivityCancellationType.TRY_CANCEL - 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 refused: - # Core gives the failure of an attempt of a Local Activity as it is. - result.failed.failure.CopyFrom(refused) - elif call.unserved: - error = ApplicationFailureInfo(type="ValueError") - result.failed.failure.CopyFrom( - Failure(message="No Stream Store", application_failure_info=error) - ) - elif call.timeout: - timeout = TimeoutFailureInfo( - timeout_type=TimeoutType.TIMEOUT_TYPE_SCHEDULE_TO_CLOSE - ) - result.failed.failure.CopyFrom( - Failure( - message="Local Activity timed out", - cause=Failure(timeout_failure_info=timeout), - activity_failure_info=ActivityFailureInfo( - activity_type=ActivityType(name=_STORE_CALL), - retry_state=RetryState.RETRY_STATE_CANCEL_REQUESTED, - ), - ) - ) - else: - result.completed.result.CopyFrom( - converter.to_payload(answer.SerializeToString()) - ) - if call.cancel: - outcome = "cancelled" - elif call.refusal is not None: - outcome = call.refusal - return command, job, outcome - - -async def test_stream_calls_get_the_results_of_their_own_seq() -> None: - for seed in range(200): - with failure_note(f"seed {seed}"): - await _calls_script(random.Random(seed)) + result.completed.result.CopyFrom( + converter.to_payload(answer.SerializeToString()) + ) + return job -async def _calls_script(rng: random.Random) -> None: - stores: list[StreamStore] = [MemoryStreamStore(name=name) for name in "ab"] +@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) - if context.id == "fatal": - raise ApplicationError("The selector has no Store for this Stream") - return stores[int(context.id[1:]) % 2] - - config = rng.choice( - [StreamConfig(stores[:1]), StreamConfig(stores, store_selector=selector)] - ) - names = "a" if len(config.stores) == 1 else "ab" - # A replay chooses the Store of each call again, as the first run did. - replaying = rng.random() < 0.3 - - # The Store name that History has for each Stream that a create of the script makes. - # It need not be the one that the config picks for the create. - created: dict[str, str] = {} - phases: list[list[_Call]] = [] - streams = 0 - for _ in range(rng.randrange(1, 5)): - phase: list[_Call] = [] - for _ in range(rng.randrange(1, 5)): - operation = rng.choice(["create", "append", "append", "describe"]) - if operation != "create" and created and rng.random() < 0.5: - call = _Call(operation, rng.choice(sorted(created))) - else: - call = _Call(operation, f"s{streams}", rng.choice([None, *names])) - streams += 1 - if operation == "append": - call.bodies = [rng.randrange(100) for _ in range(rng.randrange(3))] - # The first call of a phase isn't cancelled, so each phase waits for a job. - call.cancel = bool(phase) and rng.random() < 0.3 - call.refusal = rng.choice([None, None, None, None, *_REFUSALS]) - phase.append(call) - phases.append(phase) - for call in phase: - if call.operation == "create" and not call.cancel and call.refusal is None: - created[call.stream] = rng.choice(names) - # The last phase can be one call that fails the Workflow Task. Its Local Activity - # ends in an outage or finds no Store, or the selector raises for the call. - fatal = rng.choice([None, None, "outage", "unserved", "selector"]) - if fatal == "selector" and not config.store_selector: - fatal = None - if fatal == "selector": - phases.append([_Call(rng.choice(["create", "append", "describe"]), "fatal")]) - elif fatal: - last = _Call(rng.choice(["create", "describe"]), f"s{streams}") - last.unserved = fatal == "unserved" - last.timeout = fatal == "outage" and rng.random() < 0.5 - if fatal == "outage" and not last.timeout: - last.refusal = _UNAVAILABLE - phases.append([last]) - + 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 = rng.random() < 0.5 - # The task also fails on a Worker that fails a Workflow for any exception. - failure_types = rng.choice([[], [Exception]]) + _Script.late_cancels = late_cancels instance = _new_instance( - _ScriptWorkflow, config, [_RecordingInbound], failure_types - ) - target = StorageDriverWorkflowInfo( - namespace="ns", id="wf", run_id="run", type="_ScriptWorkflow" + _ScriptWorkflow, + StreamConfig([a, b], store_selector=selector), + [_RecordingInbound], ) - seqs = {"append": 0, "activity": 0} + converter = temporalio.converter.DefaultPayloadConverter() jobs = [WorkflowActivationJob(initialize_workflow=InitializeWorkflow())] - outcomes: list[Any] = [] - expected_selects: list[StreamSelectContext] = [] - # The created Streams that Workflow code has, which have their Store name of History - usable: set[str] = set() + seqs = {"append": 0, "activity": 0} for phase in phases: completion = await _activate(instance, *jobs, replaying=replaying) - if fatal == "selector" and phase is phases[-1]: - break - commands: list[WorkflowCommand] = [] - cancels: list[WorkflowCommand] = [] + commands = completion.successful.commands jobs = [] - for call in phase: - # Each call gets its Store in Workflow code, and only a ref with no Store - # name asks the selector. - if call.stream in usable: - ref_store = store = created[call.stream] - elif call.store: - ref_store = store = call.store - elif config.store_selector is None: - ref_store, store = "", "a" + 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: - ref_store, store = "", stores[int(call.stream[1:]) % 2].name() - expected_selects.append( - StreamSelectContext(id=call.stream, target=target, namespace="ns") + 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 ) - kind = call.operation if call.operation in seqs else "activity" - seqs[kind] += 1 - command, job, outcome = _plan( - call, seqs[kind], ref_store, store, created.get(call.stream, "a") + 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) ) - commands.append(command) - jobs.append(job) - outcomes.append(outcome) - if call.cancel and kind == "activity": - cancel = RequestCancelLocalActivity(seq=seqs[kind]) - cancels.append(WorkflowCommand(request_cancel_local_activity=cancel)) - # The commands are in the order of the calls, and a cancel sends a command only - # for a Local Activity. - assert list(completion.successful.commands) == commands + cancels - usable.update(call.stream for call in phase if call.operation == "create") - usable &= created.keys() - # Core gives the results in any order, also those of calls that were cancelled. - rng.shuffle(jobs) - else: - completion = await _activate(instance, *jobs, replaying=replaying) - if fatal: - assert completion.HasField("failed") - else: - [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] == outcomes - assert not instance._streams._appends - assert selects == expected_selects - # An interceptor sees each call in the method of its operation, and the ref of - # a create as Workflow code wrote it, also after its result. - assert [operation for operation, _ in _Script.intercepted] == [ - call.operation for call in calls + for seq in cancelled ] - # The Local Activity of a create or a describe goes through the interceptors too. - store_calls = [ - call for call in calls if call.operation in ("create", "describe") - ] - assert _Script.local_activities == [_STORE_CALL] * len(store_calls) - for call, (_, request) in zip(calls, _Script.intercepted): - if call.operation == "create": - assert request.stream_ref.store == call.store - # An eviction ends each task of the instance, also the task of a call that waits. - evict = WorkflowActivationJob(remove_from_cache=RemoveFromCache()) - assert (await _activate(instance, evict)).HasField("successful") + 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 + target = StorageDriverWorkflowInfo( + namespace="ns", id="wf", run_id="run", type="_ScriptWorkflow" + ) + assert selects == [ + StreamSelectContext(id=id, target=target, 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") class _EachCall: From 06528ce2bd3eeef4ea8f862d1dbc5a8607cacf06 Mon Sep 17 00:00:00 2001 From: Mohammad Dashti Date: Fri, 27 Nov 2026 10:48:16 -0700 Subject: [PATCH 43/50] Replace generated StreamRef shapes with fixed cases --- tests/nexus/test_streams.py | 120 +++++++++++++++--------------------- 1 file changed, 51 insertions(+), 69 deletions(-) diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index a0131ac07c..6caa5aa63b 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -6,7 +6,6 @@ import dataclasses import pickle import pkgutil -import random import subprocess import sys from collections.abc import Awaitable, Callable @@ -494,77 +493,60 @@ class _Turn: text: str -def _refs(value: Any) -> list[Any]: - """Return each ``StreamRef`` of a value, in the order of its lists and fields.""" - if isinstance(value, StreamRef): - return [value] - if isinstance(value, list): - return [ref for item in value for ref in _refs(item)] - if dataclasses.is_dataclass(value): - fields = dataclasses.fields(value) - return _refs([getattr(value, field.name) for field in fields]) - return [] +@pytest.mark.parametrize( + ("hint", "ref", "body_type"), + [ + (StreamRef[int], StreamRef[int](id="count", store="a"), int), + (StreamRef[str], StreamRef[str](id="text"), str), + (StreamRef[_Turn], StreamRef[_Turn](id="turn", store="b"), _Turn), + (StreamRef, StreamRef(id="untyped"), object), + (StreamRef[int] | None, None, None), + (StreamRef[str] | None, StreamRef[str](id="optional"), str), + ], +) +def test_a_stream_ref_keeps_its_body_type( + hint: Any, ref: StreamRef[Any] | None, body_type: type | None +) -> None: + converter = temporalio.converter.DataConverter.default.payload_converter + client = Client( + Mock(spec=ServiceClient), stream_config=StreamConfig([FaultStore()]) + ) + [decoded] = converter.from_payloads(converter.to_payloads([ref]), [hint]) + assert decoded == ref + if decoded is not None: + for get_stream in (client.get_stream, temporalio.workflow.get_stream): + assert get_stream(decoded).body_type is body_type -def test_a_stream_ref_keeps_its_type_inside_a_value() -> None: +@dataclasses.dataclass +class _RefFields: + typed: StreamRef[_Turn] + untyped: StreamRef + nested: list[StreamRef[int] | None] + + +def test_stream_ref_fields_keep_their_body_types_inside_lists() -> None: + value = [ + _RefFields( + typed=StreamRef[_Turn](id="turn", store="a"), + untyped=StreamRef(id="untyped"), + nested=[StreamRef[int](id="count"), None], + ) + ] converter = temporalio.converter.DataConverter.default.payload_converter - config = StreamConfig([FaultStore()]) - client = Client(Mock(spec=ServiceClient), stream_config=config) - # mypy takes a type argument from a variable only on a value of type Any. - ref_type: Any = StreamRef - list_type: Any = list - for seed in range(60): - rng = random.Random(seed) - - def ref(typed: Any) -> Any: - store = rng.choice([None, "a", "b"]) - return typed(id=f"stream-{rng.randrange(1000)}", store=store) - - def shape( - kind: str, depth: int - ) -> tuple[Any, Callable[[], tuple[Any, list[Any]]]]: - """Return a hint with a ref in it, and a function that makes a value of - the hint with the body type of each of its refs, in their order. - """ - if kind == "argument" or depth == 0: - body = rng.choice([_Turn, str, int]) - return ref_type[body], lambda: (ref(ref_type[body]), [body]) - if kind == "untyped field": - # A ref with no type argument reads bodies of any type. - untyped = dataclasses.make_dataclass("Untyped", [("ref", StreamRef)]) - return untyped, lambda: (untyped(ref(StreamRef)), [object]) - kinds = ["argument", "untyped field", "field", "list", "optional"] - hint, make = shape(rng.choice(kinds), depth - 1) - if kind == "optional": - return hint | None, lambda: make() if rng.random() < 0.7 else (None, []) - if kind == "list": - - def make_list() -> tuple[Any, list[Any]]: - made = [make() for _ in range(rng.randrange(3))] - bodies = [body for _, bodies in made for body in bodies] - return [value for value, _ in made], bodies - - return list_type[hint], make_list - holder = dataclasses.make_dataclass("Holder", [("ref", hint)]) - - def make_field() -> tuple[Any, list[Any]]: - value, bodies = make() - return holder(value), bodies - - return holder, make_field - - # With a depth of 1, these are an argument or a result, a field with no type - # argument, a field, a list, and an argument or a result that can be None. - for top in ("argument", "untyped field", "field", "list", "optional"): - with failure_note(f"seed {seed}, {top}"): - hint, make = shape(top, rng.randrange(1, 4)) - value, bodies = make() - payloads = converter.to_payloads([value]) - [decoded] = converter.from_payloads(payloads, [hint]) - assert decoded == value - refs = _refs(decoded) - for get_stream in (client.get_stream, temporalio.workflow.get_stream): - assert [get_stream(ref).body_type for ref in refs] == bodies + client = Client( + Mock(spec=ServiceClient), stream_config=StreamConfig([FaultStore()]) + ) + [decoded] = converter.from_payloads( + converter.to_payloads([value]), [list[_RefFields]] + ) + assert decoded == value + [fields] = decoded + assert fields.nested[1] is None + for get_stream in (client.get_stream, temporalio.workflow.get_stream): + assert get_stream(fields.typed).body_type is _Turn + assert get_stream(fields.untyped).body_type is object + assert get_stream(fields.nested[0]).body_type is int def test_each_stream_module_can_be_the_first_import() -> None: From 7f2d20b4cf2abccaf03b04ff9c2f2763c8f63f0e Mon Sep 17 00:00:00 2001 From: Mohammad Dashti Date: Sat, 28 Nov 2026 03:14:05 -0700 Subject: [PATCH 44/50] Preserve replay when filling a missing Stream cursor --- changelog/fixed/patient-poll.md | 1 + temporalio/_workflow_context.py | 5 ++++- temporalio/nexus/system/_support.py | 11 ++++++++++- tests/nexus/test_streams.py | 22 ++++++++++++++++++++++ tests/worker/test_workflow_streams.py | 10 ++++++++++ 5 files changed, 47 insertions(+), 2 deletions(-) diff --git a/changelog/fixed/patient-poll.md b/changelog/fixed/patient-poll.md index 9eb729fb75..1de5adcc2f 100644 --- a/changelog/fixed/patient-poll.md +++ b/changelog/fixed/patient-poll.md @@ -1 +1,2 @@ Client and Activity Stream polling yields to asyncio between empty pages, including when the caller sets a zero wait. +Stream iterators resume from the last Record when a page omits its cursor. diff --git a/temporalio/_workflow_context.py b/temporalio/_workflow_context.py index 2a9041dcec..d56a734099 100644 --- a/temporalio/_workflow_context.py +++ b/temporalio/_workflow_context.py @@ -31,9 +31,12 @@ class _WorkflowLogicFlag(IntEnum): # Remove the explicit overrides for this flag from tests/worker/test_workflow_flags.py # when enabling it. Then remove this reminder. DECODE_DATETIME_PROXIES = 3 + USE_LAST_STREAM_RECORD_OFFSET = 4 -_DEFAULT_ENABLED_WORKFLOW_LOGIC_FLAGS: frozenset[_WorkflowLogicFlag] = frozenset() +_DEFAULT_ENABLED_WORKFLOW_LOGIC_FLAGS: frozenset[_WorkflowLogicFlag] = frozenset( + {_WorkflowLogicFlag.USE_LAST_STREAM_RECORD_OFFSET} +) @dataclass(frozen=True) diff --git a/temporalio/nexus/system/_support.py b/temporalio/nexus/system/_support.py index 009c562bc1..2951b2f872 100644 --- a/temporalio/nexus/system/_support.py +++ b/temporalio/nexus/system/_support.py @@ -15,6 +15,7 @@ import temporalio.common import temporalio.converter import temporalio.nexus.system +from temporalio._workflow_context import _current_workflow_flags, _WorkflowLogicFlag from temporalio.converter._payload_converter import _get_transfer_type_converter if typing.TYPE_CHECKING: @@ -189,10 +190,18 @@ def _timestamp(time: datetime) -> "Timestamp": def next_read_request( request: "ReadRecordsRequest[_BodyT]", response: "ReadRecordsResponse[_BodyT]" ) -> "ReadRecordsRequest[_BodyT] | None": + cursor = response.last_offset or request.from_offset + if not response.last_offset and response.records: + # An unflagged replay must issue its next read at the recorded request cursor. + flags = _current_workflow_flags.get() + if flags is None or flags.is_flag_enabled( + _WorkflowLogicFlag.USE_LAST_STREAM_RECORD_OFFSET + ): + cursor = response.records[-1].offset # Empty pages don't end a Stream. The default wait avoids busy polling. return dataclasses.replace( request, - from_offset=response.last_offset or request.from_offset, + from_offset=cursor, wait=DEFAULT_READ_WAIT if request.wait is None else request.wait, ) diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index 6caa5aa63b..e9cf6688af 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -668,6 +668,28 @@ async def append_later() -> None: run_with_virtual_clock(script()) +@pytest.mark.parametrize( + "offsets, last_offset, expected", + [ + ([b"b", b"c"], b"d", b"d"), + ([b"b", b"c"], None, b"c"), + ([], None, b"a"), + ], +) +def test_the_next_read_uses_the_position_covered_by_the_page( + offsets: list[bytes], last_offset: bytes | None, expected: bytes +) -> None: + request = ReadRecordsRequest(ref=StreamRef[int](id="s"), from_offset=b"a") + page = ReadRecordsResponse( + records=[ + StreamRecord(body=i, offset=offset) for i, offset in enumerate(offsets) + ], + last_offset=last_offset, + ) + next_request = _support.next_read_request(request, page) + assert next_request is not None and next_request.from_offset == expected + + def test_a_page_with_no_last_offset_ends_at_its_last_record() -> None: async def unset(call: Callable[[], Awaitable[Any]]) -> Any: page = await call() diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py index f457452397..dd67d5508e 100644 --- a/tests/worker/test_workflow_streams.py +++ b/tests/worker/test_workflow_streams.py @@ -1081,6 +1081,16 @@ def result(completion: WorkflowActivationCompletion) -> Any: expected = [1, 2] if how == "read" else [[1], [], [], [2]] assert result(completion) == expected + flag = _WorkflowLogicFlag.USE_LAST_STREAM_RECORD_OFFSET + for replaying, flags, after in [(False, (), 1), (True, (), 0), (True, (flag,), 1)]: + instance = _new_instance(_ReadToTwoWorkflow, config) + await _activate(instance, start("read_pages"), replaying=replaying, flags=flags) + completion = await _activate( + instance, page(1, [1], 0), replaying=replaying, flags=flags + ) + assert list(completion.successful.commands) == [read(2, after)] + assert (flag in completion.successful.used_internal_flags) == (not replaying) + # The first read of an iterator has the caller's wait. A later read has it too, # or the default of 1 minute when the caller gave none. A wait of zero stays. default = int(_support.DEFAULT_READ_WAIT.total_seconds()) From fbe7fa565be336b66cfbf72ef03f7948873f0b69 Mon Sep 17 00:00:00 2001 From: Mohammad Dashti Date: Sat, 28 Nov 2026 03:47:09 -0700 Subject: [PATCH 45/50] Update Core to the reviewed Stream runtime --- changelog/added/nonstretchable-jamie.md | 1 + changelog/fixed/nonstretchable-jamie.md | 1 + temporalio/bridge/Cargo.lock | 6 ++++-- .../bridge/proto/external_data/external_data_pb2.pyi | 3 ++- .../proto/workflow_activation/workflow_activation_pb2.pyi | 7 +++---- .../proto/workflow_commands/workflow_commands_pb2.pyi | 3 ++- temporalio/bridge/sdk-core | 2 +- 7 files changed, 14 insertions(+), 9 deletions(-) create mode 100644 changelog/added/nonstretchable-jamie.md create mode 100644 changelog/fixed/nonstretchable-jamie.md diff --git a/changelog/added/nonstretchable-jamie.md b/changelog/added/nonstretchable-jamie.md new file mode 100644 index 0000000000..036a7c38e7 --- /dev/null +++ b/changelog/added/nonstretchable-jamie.md @@ -0,0 +1 @@ +Core: Stream metrics record Store calls by `stream_store` and failures by `failure_reason`. Live append and read counters exclude replay. Replay Store reads have separate `stream_replay_read_total`, `stream_replay_read_execution_failed`, `stream_replay_read_records` and `stream_replay_read_execution_latency` instruments. diff --git a/changelog/fixed/nonstretchable-jamie.md b/changelog/fixed/nonstretchable-jamie.md new file mode 100644 index 0000000000..7b531db416 --- /dev/null +++ b/changelog/fixed/nonstretchable-jamie.md @@ -0,0 +1 @@ +Core: Workflow queries retain task results when replay needs another History page. diff --git a/temporalio/bridge/Cargo.lock b/temporalio/bridge/Cargo.lock index a1f7e784df..0b34830004 100644 --- a/temporalio/bridge/Cargo.lock +++ b/temporalio/bridge/Cargo.lock @@ -2468,9 +2468,9 @@ dependencies = [ [[package]] name = "sha2" -version = "0.11.1" +version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27" dependencies = [ "cfg-if", "cpufeatures", @@ -2875,6 +2875,7 @@ dependencies = [ "futures-util", "prost", "temporalio-common", + "thiserror", ] [[package]] @@ -2986,6 +2987,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "futures-util", "libc", "pin-project-lite", "tokio", diff --git a/temporalio/bridge/proto/external_data/external_data_pb2.pyi b/temporalio/bridge/proto/external_data/external_data_pb2.pyi index 9925078f9c..d153ec2389 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.pyi +++ b/temporalio/bridge/proto/external_data/external_data_pb2.pyi @@ -388,7 +388,8 @@ class StreamReadPage(google.protobuf.message.Message): record_count: builtins.int digest: builtins.bytes """The first 16 bytes of SHA-256 over the Records in a Core-owned encoding. New markers prefix - these bytes with version 1. Original markers contain just the legacy hash. Empty for no Records. + these bytes with version 1. Original markers contain just the legacy hash. + Empty for no Records. """ record_bytes: builtins.int """The size of the Records, as the `max_bytes` of a read measures it. A replay asks the Store for diff --git a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi index 27ca55f056..0fbd803777 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi @@ -72,9 +72,8 @@ class WorkflowActivation(google.protobuf.message.Message): that event, so it scans ahead in History for the marker, as for a local activity marker. Each result in the marker has the index of the activation that got it, so the replay gives it in that same activation. In one activation, the Stream results go first, appends before reads, - each in `seq` order, and then the local activity resolutions. A replay with workflow task - chunking on can give several activations of the first run as one. Then the results go in the - order of those activations. + each in `seq` order, and then the local activity resolutions. A task with a Stream marker + retains its recorded activation groups. * Queries always go last (and, in fact, always come in their own activation) * Evictions also always come in their own activation @@ -1682,7 +1681,7 @@ global___RemoveFromCache = RemoveFromCache class ResolveStreamAppend(google.protobuf.message.Message): """Core delivers the result in the next activation, or in the next task when the Store answers during completion. Stream and Local Activity markers share an activation index. Replay - preserves result order. With task chunking, several activations can replay as one. + preserves the recorded activation groups for tasks that contain a Stream marker. """ DESCRIPTOR: google.protobuf.descriptor.Descriptor diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi index f3cbe7caaf..aa64aa718b 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi @@ -2003,7 +2003,8 @@ global___AppendToStream = AppendToStream @typing.final class ReadStream(google.protobuf.message.Message): """Reads one page after from_offset. A reader continues from the page's last_offset until an - application Record tells it to stop. ResolveStreamRead follows the ordering of ResolveStreamAppend. + application Record tells it to stop. + ResolveStreamRead follows the ordering of ResolveStreamAppend. A page returns as soon as Records are available. For an empty page Core polls from the Store's returned offset at most once per 100 ms until wait expires or the task reaches its read time. diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index 70325823a6..506dba286e 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit 70325823a6c4a3a290cde8b3bf752975d72fbd39 +Subproject commit 506dba286e14da52ec221ae93c1cc1932c5d53df From 649b351a43751a6376d347357401f0852e2d2871 Mon Sep 17 00:00:00 2001 From: Mohammad Dashti Date: Sat, 28 Nov 2026 03:47:09 -0700 Subject: [PATCH 46/50] Preserve historical Stream creation results --- changelog/added/steady-stream-heron.md | 1 + temporalio/_workflow_context.py | 6 ++- temporalio/nexus/system/_support.py | 56 +++++++++++++++++++ tests/nexus/test_streams.py | 1 + tests/worker/test_workflow_streams.py | 74 +++++++++++++++++++++++++- 5 files changed, 135 insertions(+), 3 deletions(-) diff --git a/changelog/added/steady-stream-heron.md b/changelog/added/steady-stream-heron.md index ffe007056e..c7aeb522e6 100644 --- a/changelog/added/steady-stream-heron.md +++ b/changelog/added/steady-stream-heron.md @@ -3,3 +3,4 @@ Add experimental Streams for client and Activity code. `stream_config=StreamConf Add experimental Streams for Workflow code. `workflow.create_stream` and `workflow.get_stream` return a `Stream` to append to, read and describe on the Stream Stores of the Worker's client, and `Replayer(stream_config=...)` gives a replay its Stores. The SDK chooses the Store of each call before the call starts, also in a replay. It calls the `store_selector` only for a ref with no Store name, in Workflow code for each such call, also for a create and a describe, and again in a replay. So the selector must return the same Store for the same call, must not block or do I/O, and must be safe to call from more than one thread. SDK Core fails a replay with a nondeterminism error when a replayed append or read goes to another Store than the one in History. Add experimental Stream reads for Workflow code. `Stream.read`, `read_pages` and `read_page` of a Workflow `Stream` give the Records as they come, a replay reads them again from the Store, and `temporalio.workflow.StreamReplayError` in the failure exception types of a Worker or a Workflow fails the Workflow when the Store no longer has them. The Worker option `stream_read_time` sets how long the reads of a Workflow Task can wait, and a read with a wait gives a page with no Record at that limit. In Workflow code, `read` and `read_pages` never end at a page with no Record and read again, also in later Workflow Tasks, so Workflow code decides when to stop. Each page is a read result in History. With the default wait of 1 minute, an iterator on an idle Stream gets few pages with no Record and makes no new Workflow Task, and with a `wait` of zero it reads again at once. A read with no wait gives the answer of the Store, which can be a page with no Record, and an outage of the Store at a read fails the Workflow Task. Add experimental `temporalio.contrib.streams.BufferedAppender`, which batches the appends of one Stream in client and Activity code. `append` returns immediately, a batch waits at most `max_delay`, one write runs at a time, and `async with` or `flush()` writes what is left. +A Stream returned by `create_stream` with `USE_EXISTING` has `created=False` if it already existed. diff --git a/temporalio/_workflow_context.py b/temporalio/_workflow_context.py index d56a734099..7b35f4568b 100644 --- a/temporalio/_workflow_context.py +++ b/temporalio/_workflow_context.py @@ -32,10 +32,14 @@ class _WorkflowLogicFlag(IntEnum): # when enabling it. Then remove this reminder. DECODE_DATETIME_PROXIES = 3 USE_LAST_STREAM_RECORD_OFFSET = 4 + REPORT_EXISTING_STREAM_AS_FALSE = 5 _DEFAULT_ENABLED_WORKFLOW_LOGIC_FLAGS: frozenset[_WorkflowLogicFlag] = frozenset( - {_WorkflowLogicFlag.USE_LAST_STREAM_RECORD_OFFSET} + { + _WorkflowLogicFlag.USE_LAST_STREAM_RECORD_OFFSET, + _WorkflowLogicFlag.REPORT_EXISTING_STREAM_AS_FALSE, + } ) diff --git a/temporalio/nexus/system/_support.py b/temporalio/nexus/system/_support.py index 2951b2f872..9f4cd52d5b 100644 --- a/temporalio/nexus/system/_support.py +++ b/temporalio/nexus/system/_support.py @@ -21,13 +21,20 @@ if typing.TYPE_CHECKING: import temporalio.activity import temporalio.client + from temporalio.client import NexusClient as ClientNexusClient + from temporalio.nexus.system.stream_service.client import Stream as ClientStream from temporalio.nexus.system.stream_service.models import ( + CreateStreamResult, Producer, ReadRecordsRequest, ReadRecordsResponse, StreamRecord, Timestamp, ) + from temporalio.nexus.system.stream_service.workflow._resources import ( + Stream as WorkflowStream, + ) + from temporalio.workflow import NexusClient as WorkflowNexusClient _BodyT = typing.TypeVar("_BodyT") _ModelT = typing.TypeVar("_ModelT") @@ -73,6 +80,55 @@ def model_from_proto( return converter.from_transfer_type(proto, model_type) +@typing.overload +def stream_from_create( + result: "CreateStreamResult[_BodyT]", + nexus_client: "ClientNexusClient[typing.Any]", + body_type: type[_BodyT], +) -> "ClientStream[_BodyT]": ... + + +@typing.overload +def stream_from_create( + result: "CreateStreamResult[_BodyT]", + nexus_client: "WorkflowNexusClient[typing.Any]", + body_type: type[_BodyT], +) -> "WorkflowStream[_BodyT]": ... + + +def stream_from_create( + result: "CreateStreamResult[_BodyT]", + nexus_client: "ClientNexusClient[typing.Any] | WorkflowNexusClient[typing.Any]", + body_type: type[_BodyT], +) -> "ClientStream[_BodyT] | WorkflowStream[_BodyT]": + import temporalio.workflow + + if result.ref is None: + raise RuntimeError("CreateStream answered without `ref`") + created: bool | None = bool(result.created) + if isinstance(nexus_client, temporalio.workflow.NexusClient): + from temporalio.nexus.system.stream_service.workflow._resources import ( + Stream as WorkflowStream, + ) + + if not created: + flags = _current_workflow_flags.get() + # Unflagged replay must retain None, including responses from interceptors. + if flags is not None and not flags.is_flag_enabled( + _WorkflowLogicFlag.REPORT_EXISTING_STREAM_AS_FALSE + ): + created = None + return WorkflowStream[body_type]( # type: ignore[valid-type, reportInvalidTypeForm] + ref=result.ref, created=created + ) + + from temporalio.nexus.system.stream_service.client import Stream as ClientStream + + return ClientStream[body_type]( # type: ignore[valid-type, reportInvalidTypeForm] + nexus_client, ref=result.ref, created=created + ) + + def default_producer( nexus_client: "temporalio.client.NexusClient[typing.Any]", ) -> "Producer": diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index e9cf6688af..a93dca05d3 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -210,6 +210,7 @@ async def call() -> Any: for _ in range(2): result = await (activity.run(call) if in_activity else call()) if operation == "create": + assert result.created is False assert result.ref == StreamRef( id="s", store="b" if routing == "selector" else "a" ) diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py index dd67d5508e..96b749873c 100644 --- a/tests/worker/test_workflow_streams.py +++ b/tests/worker/test_workflow_streams.py @@ -73,6 +73,10 @@ from temporalio.exceptions import ApplicationError, StreamError from temporalio.nexus.system import _support 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 ( @@ -364,7 +368,9 @@ async def start_describe_stream(self, request: Any) -> Any: return await super().start_describe_stream(request) -def _resolve_call(call: _Call, seq: int) -> WorkflowActivationJob: +def _resolve_call( + call: _Call, seq: int, *, created: bool = True +) -> WorkflowActivationJob: converter = temporalio.converter.DefaultPayloadConverter() job = WorkflowActivationJob() if call.operation == "append": @@ -410,7 +416,9 @@ def _resolve_call(call: _Call, seq: int) -> WorkflowActivationJob: ) else: answer: Message = ( - CreateStreamResponse(ref=StreamRef(id=call.stream, store="b"), created=True) + CreateStreamResponse( + ref=StreamRef(id=call.stream, store="b"), created=created + ) if call.operation == "create" else DescribeStreamResponse(last_offset=b"last%d" % seq) ) @@ -420,6 +428,68 @@ def _resolve_call(call: _Call, seq: int) -> WorkflowActivationJob: 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_preserves_the_recorded_existing_stream_result( + 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) + flag = _WorkflowLogicFlag.REPORT_EXISTING_STREAM_AS_FALSE + for replaying, flags, expected in [ + (False, (), False), + (True, (), None), + (True, (flag,), False), + ]: + instance = _new_instance( + _ReuseStreamWorkflow, + StreamConfig([MemoryStreamStore(name="b")]), + [_RecordingInbound], + ) + completion = await _activate( + instance, + WorkflowActivationJob(initialize_workflow=InitializeWorkflow()), + replaying=replaying, + flags=flags, + ) + 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, + flags=flags, + ) + [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 expected + ) + assert (flag in completion.successful.used_internal_flags) == (not replaying) + + @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( From b16c10d094038bed8049f1d299b0f2f2f1c6a360 Mon Sep 17 00:00:00 2001 From: Mohammad Dashti Date: Sat, 28 Nov 2026 03:47:09 -0700 Subject: [PATCH 47/50] Use UTC for Activity test timestamps --- changelog/fixed/punctual-puffin.md | 1 + temporalio/testing/_activity.py | 2 +- tests/testing/test_activity.py | 5 +++++ 3 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 changelog/fixed/punctual-puffin.md diff --git a/changelog/fixed/punctual-puffin.md b/changelog/fixed/punctual-puffin.md new file mode 100644 index 0000000000..bd18de3a1f --- /dev/null +++ b/changelog/fixed/punctual-puffin.md @@ -0,0 +1 @@ +`ActivityEnvironment` defaults to the Unix epoch for Activity timestamps in every time zone. 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 fe2e7e8aaa3745eebd4ee78764b488683a6fbb9e Mon Sep 17 00:00:00 2001 From: Mohammad Dashti Date: Sat, 28 Nov 2026 04:03:26 -0700 Subject: [PATCH 48/50] Preserve Stream retries and async cleanup --- changelog/added/steady-stream-heron.md | 9 +- changelog/fixed/sleepy-signal-finch.md | 1 + temporalio/bridge/Cargo.toml | 2 +- temporalio/bridge/src/streams.rs | 16 +- temporalio/client/_client.py | 4 +- temporalio/client/_interceptor.py | 7 +- temporalio/client/_stream_store.py | 405 ++++++++------------- temporalio/contrib/streams/_appender.py | 5 + temporalio/converter/_payload_converter.py | 2 +- temporalio/testing/_stream_store.py | 6 +- temporalio/worker/_replayer.py | 15 +- temporalio/worker/_worker.py | 20 +- temporalio/worker/_workflow_instance.py | 17 +- temporalio/worker/_workflow_streams.py | 72 +--- tests/contrib/streams/test_appender.py | 194 +++++----- tests/nexus/test_streams.py | 32 ++ tests/testing/test_stream_store.py | 65 ++-- tests/worker/test_workflow_streams.py | 343 ++++++++--------- 18 files changed, 538 insertions(+), 677 deletions(-) create mode 100644 changelog/fixed/sleepy-signal-finch.md diff --git a/changelog/added/steady-stream-heron.md b/changelog/added/steady-stream-heron.md index c7aeb522e6..3cd4bb8330 100644 --- a/changelog/added/steady-stream-heron.md +++ b/changelog/added/steady-stream-heron.md @@ -1,6 +1,3 @@ -Add experimental `temporalio.client.StreamStore`, the base class of a Stream Store, and `temporalio.testing.MemoryStreamStore`, a Store that keeps its Streams in memory for tests and local runs. A Store gets the requests of `temporalio.api.streamservice.v1`, which have the Stream id, and the request id of each create and each append as `request_id`. A create returns only `created`, and the SDK gives the caller the ref with the name of the Store. A Stream has no close, and it expires when the Retention of its Store has passed since its create or its last append that wrote a batch. -Add experimental Streams for client and Activity code. `stream_config=StreamConfig(stores=[...])` of `Client.connect` gives a client its Stream Stores, and `Client.create_stream` and `Client.get_stream` return a `Stream` to append to, read and describe. A failed call raises `temporalio.exceptions.StreamError` with a `reason`. `max_record_bytes`, `max_batch_bytes` and `max_batch_records` of `StreamConfig` bound an append, and one over a limit fails before its Store gets it. A read of a Stream from `get_stream` needs `body_type=` or a `StreamRef` with a type argument, and raises `TypeError` with neither. `Stream.read` and `read_pages` never end at a page with no Record and read again, so the caller decides when to stop, for example with a `break`. With no `wait`, the first read of an iterator gives the answer of the Store at once, and each later read waits up to 1 minute, so an iterator on an idle Stream doesn't call its Store in a loop. A `wait` that the caller gives holds for each read, and a `wait` of zero is no wait at all. `read_page` has no default wait. The wait of a read ends shortly before its `rpc_timeout`, so that the Store can answer in time. `temporalio.contrib.streams.current_producer` gives the Producer of an Activity attempt, and `as_producer` gives back one that code stored. -Add experimental Streams for Workflow code. `workflow.create_stream` and `workflow.get_stream` return a `Stream` to append to, read and describe on the Stream Stores of the Worker's client, and `Replayer(stream_config=...)` gives a replay its Stores. The SDK chooses the Store of each call before the call starts, also in a replay. It calls the `store_selector` only for a ref with no Store name, in Workflow code for each such call, also for a create and a describe, and again in a replay. So the selector must return the same Store for the same call, must not block or do I/O, and must be safe to call from more than one thread. SDK Core fails a replay with a nondeterminism error when a replayed append or read goes to another Store than the one in History. -Add experimental Stream reads for Workflow code. `Stream.read`, `read_pages` and `read_page` of a Workflow `Stream` give the Records as they come, a replay reads them again from the Store, and `temporalio.workflow.StreamReplayError` in the failure exception types of a Worker or a Workflow fails the Workflow when the Store no longer has them. The Worker option `stream_read_time` sets how long the reads of a Workflow Task can wait, and a read with a wait gives a page with no Record at that limit. In Workflow code, `read` and `read_pages` never end at a page with no Record and read again, also in later Workflow Tasks, so Workflow code decides when to stop. Each page is a read result in History. With the default wait of 1 minute, an iterator on an idle Stream gets few pages with no Record and makes no new Workflow Task, and with a `wait` of zero it reads again at once. A read with no wait gives the answer of the Store, which can be a page with no Record, and an outage of the Store at a read fails the Workflow Task. -Add experimental `temporalio.contrib.streams.BufferedAppender`, which batches the appends of one Stream in client and Activity code. `append` returns immediately, a batch waits at most `max_delay`, one write runs at a time, and `async with` or `flush()` writes what is left. -A Stream returned by `create_stream` with `USE_EXISTING` has `created=False` if it already existed. +Add experimental Streams for client, Activity and Workflow code, with configurable Stores and append limits. `MemoryStreamStore` supports tests and local runs. +Add Workflow Stream reads and replay through `Replayer(stream_config=...)`. Replay reads Records from the Store again, so retention must cover later replays and queries. +Add `BufferedAppender` for client and Activity batching, plus `current_producer` and `as_producer` for Activity attempts. diff --git a/changelog/fixed/sleepy-signal-finch.md b/changelog/fixed/sleepy-signal-finch.md new file mode 100644 index 0000000000..58d1ecdce2 --- /dev/null +++ b/changelog/fixed/sleepy-signal-finch.md @@ -0,0 +1 @@ +Prevent unawaited Workflow and Signal coroutines when an activation fails before their tasks start. diff --git a/temporalio/bridge/Cargo.toml b/temporalio/bridge/Cargo.toml index 19cb233335..1d6bad33c7 100644 --- a/temporalio/bridge/Cargo.toml +++ b/temporalio/bridge/Cargo.toml @@ -72,7 +72,7 @@ temporalio-sdk-core = { version = "0.12.0", path = "./sdk-core/crates/sdk-core", "ephemeral-server", "envconfig", "prometheus", - # With chunking, a replay can run Workflow code in another order than the first run. + # 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" } diff --git a/temporalio/bridge/src/streams.rs b/temporalio/bridge/src/streams.rs index dadd366141..224ca23bcd 100644 --- a/temporalio/bridge/src/streams.rs +++ b/temporalio/bridge/src/streams.rs @@ -38,8 +38,6 @@ fn lock(state: &Mutex) -> MutexGuard<'_, CallState> { state.lock().unwrap_or_else(PoisonError::into_inner) } -/// The callback that takes the Python task of a call from `_StoreCaller.call`, which then calls -/// the Store. #[pyclass] struct OnTask { state: Arc>, @@ -139,8 +137,7 @@ fn interpreter_gone(operation: &str) -> StreamError { )) } -/// Returns the error of an operation for the exception of a Store. A `StreamError` is a refusal -/// with its reason, and any other exception is an outage, which the caller can try again. +// 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); @@ -282,8 +279,6 @@ fn stream_ref(id: String) -> sdk::StreamRef { } } -/// Returns the limits of a Stream config, which Python gives as its `max_record_bytes`, -/// `max_batch_bytes` and `max_batch_records`. fn store_limits( (max_record_bytes, max_batch_bytes, max_batch_records): (usize, usize, usize), ) -> PyResult { @@ -294,8 +289,6 @@ fn store_limits( .map_err(|err| PyValueError::new_err(err.message)) } -/// The Stream Stores of a Worker, which Python gives as a `WorkerStreams` of -/// `temporalio.bridge.streams`. #[derive(FromPyObject)] pub(crate) struct WorkerStreams { limits: Option<(usize, usize, usize)>, @@ -304,8 +297,6 @@ pub(crate) struct WorkerStreams { } impl WorkerStreams { - /// Returns the runtime of each Store by its name. Each Store runs its calls on the event - /// loop of `task_locals`. pub(crate) fn into_runtimes( self, task_locals: &Arc>, @@ -327,9 +318,7 @@ impl WorkerStreams { } } -/// Checks an encoded append of client code as the runtime of a Worker checks one of Workflow -/// code, with the limits of the Stream config. Client code reaches its Store through no such -/// runtime. Raises `StreamError` for an append that the check refuses. +// Client and Workflow appends must enforce the same limits. #[pyfunction] pub fn check_stream_append( limits: (usize, usize, usize), @@ -342,7 +331,6 @@ pub fn check_stream_append( .map_err(|err| stream_error(err.reason.into(), err.message)) } -/// Returns a `temporalio.exceptions.StreamError`, or the error that building it raised. fn stream_error(reason: StreamErrorReason, message: String) -> PyErr { Python::attach(|py| { let error = || { diff --git a/temporalio/client/_client.py b/temporalio/client/_client.py index f98b21607e..f4cd1b9161 100644 --- a/temporalio/client/_client.py +++ b/temporalio/client/_client.py @@ -232,9 +232,7 @@ async def connect( stream_config: Stream Stores of this client and of each worker that uses it. The client sends each Stream call to one of these Stores, so a Stream call of a client with none raises - :exc:`ValueError`. A client interceptor that changes the Stream - of a call must change the ``ref`` of the request in place, since - a created Stream takes the ref of its create request. + :exc:`ValueError`. .. warning:: This API is experimental and subject to change. diff --git a/temporalio/client/_interceptor.py b/temporalio/client/_interceptor.py index 75463b4971..c6cc6bd3ab 100644 --- a/temporalio/client/_interceptor.py +++ b/temporalio/client/_interceptor.py @@ -2,13 +2,14 @@ from __future__ import annotations +import uuid from collections.abc import ( Awaitable, Callable, Mapping, Sequence, ) -from dataclasses import dataclass +from dataclasses import dataclass, field from datetime import timedelta from typing import ( TYPE_CHECKING, @@ -609,6 +610,10 @@ class StartNexusOperationInput: rpc_metadata: Mapping[str, str | bytes] rpc_timeout: timedelta | None completion_callbacks: Sequence[temporalio.nexus.CompletionCallback[Any]] = () + # Interceptors can retry a Store write with a copy of this input after losing its answer. + _stream_request_id: uuid.UUID = field( + default_factory=uuid.uuid4, repr=False, compare=False, kw_only=True + ) @dataclass diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 0cdb4e273d..c34fb2519a 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -4,7 +4,6 @@ import asyncio import logging -import uuid from abc import ABC, abstractmethod from collections.abc import Callable, Sequence from dataclasses import dataclass, field @@ -54,78 +53,56 @@ class StreamStore(ABC): - """Base class of a Stream Store, which keeps the Records of Streams. + """Base class for a Store that keeps Stream Records. - A Store serves the operations of the Nexus service - ``temporal.api.streamservice.v1.StreamService``. Each method takes the request - message of its operation and returns its response message, both from - :py:mod:`temporalio.api.streamservice.v1`. A request has the id of its Stream - and no ``StreamRef``. A :py:class:`StreamConfig` registers a Store under its - :py:meth:`name`, and the SDK sends each Stream call to the Store of the call's - ``StreamRef``. The SDK gives the ref of a created Stream the name of its Store, - so only the SDK reads and sets the ``store`` of a ref. + 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``. - Callers rely on a Store to follow the rules below and those of each method. - SDK Core reads a Stream for Workflow code and reads it again in a replay, and - both depend on them. + Workflow execution and replay depend on these contracts. Retention: - * A Stream expires when its Retention has passed since its create or since - the last append that wrote a batch. Retention is a setting of the Store. - * A Store answers a call for an expired Stream with ``EXPIRED``, and no longer - keeps its Records. - * A Stream has no end that a Store records. A reader learns the end from the - application's own last Record. - - The log: - - * A Store keeps the body of a Record as the append gave it. The payload codec - has already encoded it. - * A Store writes a batch, which is the Records of one append, whole or not at - all. Its Records are next to each other, in the order of the request. - * The offsets of a Stream sort bytewise in the order of its Records, and the - offset of a Record is never empty. - * Once a response returned an offset, no Record ever appears at or below it - later, even from an append that ran at the same time as that call. - * A Store doesn't change or remove a Record before its Stream expires. + * 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 is one writer of a Stream, which is a Workflow run, an Activity, - a Local Activity or a client. Two Producers are the same when they have the - same kind and the same ids of that kind. - * An attempt is the try of a Producer that made a write, such as one Workflow - Task or one attempt of an Activity. - * Fencing is optional. A Store that fences keeps the newest attempt of each - Producer that appended to a Stream, and refuses an append of an earlier - attempt of that Producer. Every Record has its Producer and attempt either - way, so a reader can tell the attempts apart. - - A method refuses a call by raising a - :py:class:`temporalio.exceptions.StreamError` with the reason, such as - ``STREAM_ERROR_REASON_EXPIRED`` for ``EXPIRED`` in these docs. Any other - exception is an outage of the Store, and the caller gets a ``StreamError`` - with ``STREAM_ERROR_REASON_STORE_UNAVAILABLE``. A refusal of an append or a - read of Workflow code puts its message, cut to 4 KiB, in a Stream marker - whose data has at most 1 MiB. So a Store keeps its messages short, since - many long ones in one activation fail the Workflow Task with - ``StreamMarkerTooLarge``. - - How the SDK calls a Store: - - * Calls run at the same time on the event loop, and a read can wait while - appends run. - * The SDK can cancel the task of a call, for example at a timeout, at an - eviction or at a Worker shutdown. The call may still have taken effect, and - the Store must stay usable after it. - * A resend can come while its first try still runs, and the Store still writes - the batch once. - * SDK Core checks each append and read of Workflow code, and its response, - and tries the call again during an outage. For every other call - the SDK checks only an append, against the limits of the - :py:class:`StreamConfig`, and sends one request. A Store that needs more - checks runs them itself. + * 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 only append + limits from :py:class:`StreamConfig`. Stores must perform any other checks + they require. .. warning:: This API is experimental and subject to change. @@ -133,10 +110,10 @@ class StreamStore(ABC): @abstractmethod def name(self) -> str: - """Return the name that a :py:class:`StreamConfig` registers this Store - under. It must return the same name every time. A Store may take its name - as an argument, so that two instances of one Store class can be in one - config. + """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 @@ -144,23 +121,19 @@ def name(self) -> str: async def create_stream( self, request: CreateStreamRequest, *, request_id: str ) -> CreateStreamResponse: - """Create a Stream, or find the one that has the id if the conflict policy - allows it. + """Create a Stream, or reuse it if the conflict policy permits. - Each try of one create has the same ``request_id``. A create with the - ``request_id`` of the create that made the Stream is a retry of it, and a - create with an empty ``request_id`` never is. The response has only - ``created``. + Retries use the same ``request_id``. An empty id never identifies a retry. + The response contains only ``created``. - A Store checks a create for an id that has a Stream in this order: + For an existing Stream, check these conditions in order. - 1. The Stream expired, so the create fails with ``EXPIRED``. - 2. The create is a retry, so it returns ``created`` true. - 3. The policy is ``USE_EXISTING``, so it returns ``created`` false. With - ``FAIL``, or with no policy, it fails with ``ALREADY_EXISTS``. + 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``. - A create that makes the Stream starts its Retention. A create of a Stream - that exists doesn't start it again. + Only a new Stream starts retention. Reusing a Stream doesn't extend it. """ raise NotImplementedError @@ -170,45 +143,38 @@ async def append_records( ) -> AppendRecordsResponse: """Append one batch from one Producer. - Each try of one append has the same ``request_id``. A Store remembers the - request ids of the recent batches of each Producer of a Stream, at least - the last one. An append with the Producer, the attempt and the - ``request_id`` of a remembered batch is a resend. An append with an empty - ``request_id`` never is. + 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. - A Store checks an append in this order: + Check these conditions in order. - 1. The Stream doesn't exist or it expired, so the append fails with - ``NOT_FOUND`` or ``EXPIRED``. - 2. The append is a resend, so the Store writes nothing and returns the - offsets of the first write. It doesn't compare the Records. - 3. The Store fences, and a later attempt of the Producer already wrote, so - the append fails with ``FENCED``. + 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``. - The response has the offsets of the first and the last Record. An append - that writes its batch starts the Retention of the Stream again, and a - resend doesn't. + 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 of Records after ``from_offset``, in the order of the Stream. - - * A page has at most ``max_records`` Records, and Records of at most - ``max_bytes`` in total. Zero uses the Store's default. A page has its first - Record, even when that Record alone is over ``max_bytes``. - * ``last_offset`` is where the next read continues. A Store doesn't have to - set it. If it's empty, the caller gets the offset of the last Record of - the page, or ``from_offset`` for a page with no Record. - * A read with nothing after ``from_offset`` answers once a Record comes or - once its ``wait`` is up. With no ``wait``, it answers at once. The SDK - never sends a ``wait`` of zero, and sends no ``wait`` instead. A Store - that answers at once with no Record despite a ``wait`` makes an iterator - of the caller read again and again. - * Every offset that a response returned is a valid ``from_offset``. A read - fails with ``OFFSET_TOO_HIGH`` only when ``from_offset`` is past the end - of the Stream. + """Read one page after ``from_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``. + * ``last_offset`` is the cursor for the next read. If omitted, the SDK + uses the last Record's offset, or ``from_offset`` for an empty page. + * 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 ``from_offset`` with + ``OFFSET_TOO_HIGH`` only if it exceeds the end of the Stream. """ raise NotImplementedError @@ -216,9 +182,7 @@ async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse async def describe_stream( self, request: DescribeStreamRequest ) -> DescribeStreamResponse: - """Return a ``last_offset`` that is never below the offset of the newest - Record of a Stream. - """ + """Return a ``last_offset`` at or beyond the newest Record's offset.""" raise NotImplementedError @@ -246,84 +210,57 @@ class StreamSelectContext: @dataclass(frozen=True) class StreamConfig: - """The Stream Stores of a client and of each Worker that uses the client. - - The SDK checks each append against :py:attr:`max_record_bytes`, - :py:attr:`max_batch_bytes` and :py:attr:`max_batch_records` before its Store - gets it, and refuses one over a limit with - ``STREAM_ERROR_REASON_TOO_LARGE``. The ``rpc_metadata`` of a Stream call has - no effect, since a call to a Store is not an RPC of the Temporal server. - - A Stream has no close. It expires when the Retention of its Store has passed - since its create or since the last append that wrote a batch. A reader learns - the end of a Stream from the application's own last Record. - - ``read`` and ``read_pages`` never end at a page with no Record, in client, - Activity and Workflow code. ``read_pages`` yields that page, and both read - again from its offset. The caller decides when to stop, for example with a - ``break`` or its own timeout. With no ``wait``, the first read of an iterator - gives the answer of the Store at once, and each later read waits up to 1 - minute for a new Record. So an iterator on an idle Stream doesn't call its - Store in a loop. After the first page, the ``next_request`` of ``read`` has - that wait. A ``wait`` of zero is no wait at all, also for the later - reads, so such an iterator on an idle Stream reads again at once, page after - page. ``read_page`` has no default wait. - - In client and Activity code, a positive ``rpc_timeout`` caps the read's wait - below that timeout, so the Store has time to answer. A read holds an - Activity up to its wait, so an Activity that heartbeats between Records needs - a ``wait`` shorter than its heartbeat timeout, or a heartbeat from another - task. - - For the Stream calls of Workflow code: - - - The SDK chooses the Store of each call before the call starts, also in a - replay. SDK Core makes each append and read. A create and a describe run - in a Local Activity of the SDK, which the interceptors of the Worker see as - any other Local Activity. - - An append is at-least-once. If a Workflow Task fails after its append, the - next attempt of the task writes the batch again. - - An outage of the Store gives Workflow code no error, also at a read. The - Workflow Task fails, and the server tries it again. - - A call that Workflow code doesn't await before the Workflow ends may not - happen. - - A call with no Store fails the Workflow Task, also when Workflow code - catches the error. - - A Worker reads the three limits when it starts. It refuses a new client - with other limits, as it refuses one with other Store names. - - A page of a read has at most 256 Records and 4 MiB of Records by default, - and never more than 16 MiB. - - A live read fails with ``STREAM_ERROR_REASON_UNSUPPORTED`` for a Record - over :py:attr:`max_record_bytes`. A reader needs a limit at least as large - as each writer's limit. Replay accepts recorded successes under smaller - limits, so a configuration change cannot alter a recorded result. - - A read with no wait gives the answer of the Store, which can be a page with - no Record. - - A read with a ``wait`` and no Record to give waits up to its ``wait``, but - at most to the read limit of its Workflow Task, which the Worker option - ``stream_read_time`` sets. At that limit ``read_page`` gives a page with no - Record. - - ``read`` and ``read_pages`` go on until a Record comes, also over more - than one Workflow Task. Workflow code decides when to stop, for example - with a ``break``, its own timer, a Signal or an Activity. Each page is a - read result in History. With a ``wait`` of zero or a short one, an - iterator on a Stream with no new Record gets page after page with no - Record, and History grows fast. With the default wait, an idle Stream - gives an iterator few such pages and no new Workflow Task. - - A read holds its Workflow Task up to the read limit. A Signal that comes - meanwhile waits until the read has its page, or until that limit. A - command for the server waits only for one Store call with no wait for each - read, of at most 1 s. - - A read with a ``wait`` that has no Record when its Workflow Task completes - starts again in the next task. It asks for that task only when SDK Core - knows that the Stream has more Records for it, so a read of an idle Stream - makes no task. A Workflow Task gives at most 256 read results, and later - reads start in the next task. - - A replay reads the Records of each read from the Store again. So the - Retention of a Stream must cover the life of each Workflow that reads it, - and the time in which that Workflow gets queries. - - A body that isn't of the Stream's type fails the Workflow Task, as an - Activity result that can't be converted does. + """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. + + 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. + * Pages default to 256 Records and 4 MiB, with a 16 MiB byte cap. A live read + rejects a Record over :py:attr:`max_record_bytes` with + ``STREAM_ERROR_REASON_UNSUPPORTED``. Reader limits must cover writer limits. + Replay accepts recorded successes even if the limits decrease. + * An immediate read can return an empty page. A waiting read stops at its + wait or the Worker's ``stream_read_time`` limit, whichever comes first. + At the task limit, ``read_page`` returns an empty page. + * Iterators can continue across Workflow Tasks. Each page adds a result to + History, so zero or short waits can cause rapid History growth. The default + wait limits empty pages, and an idle Stream doesn't create new tasks. + * A waiting read holds its task and delays Signals until its page or the read + limit. A server command waits for at most one immediate Store call per read, + bounded by one second. + * An unfinished waiting read restarts in the next task. It requests that task + only when Core knows more Records are available. A task returns at most + 256 read results. Later reads start in the next task. + * Replay reads the Records from the Store again. Retention must cover the + Workflow's life and any later replay or query. + * A body that can't convert to the Stream's type fails the Workflow Task. .. warning:: This API is experimental and subject to change. @@ -336,23 +273,19 @@ class StreamConfig: """ store_selector: Callable[[StreamSelectContext], StreamStore] | None = None - """Picks the Store of a call whose ``StreamRef`` has no Store name. It must - return one of :py:attr:`stores`. - - Required when more than one Store is registered. When ``None``, the one - Store takes each such call. In Workflow code, the SDK gives SDK Core the - name of the Store that it picks, so Core never gets a ref with no Store - name. - - The SDK calls the selector only for a ref with no Store name. In Workflow - code it calls it for each such Stream call, also for a create and a - describe, and again in a replay. So the selector must return the same Store - for the same call, must not block or do I/O, and must be safe to call from - more than one thread. SDK Core fails a replay with a nondeterminism error - when a replayed append or read goes to another Store than the one in - History. A replayed create or describe gives the result that History has. A - created Stream has the name of its Store in its ref, so its calls don't - depend on the selector. + """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. + + 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 @@ -374,9 +307,7 @@ class StreamConfig: _by_name: dict[str, StreamStore] = field( init=False, repr=False, compare=False, default_factory=dict ) - """Each Store of :py:attr:`stores` by its name. :py:meth:`__post_init__` - fills it once, so a Store that changes its name later can't change a lookup. - """ + """Snapshot Store names so later name changes can't change routing.""" def __post_init__(self) -> None: """Validate the Stores and the limits. @@ -512,15 +443,7 @@ async def _call_method( request: google.protobuf.message.Message, request_id: str | None, ) -> google.protobuf.message.Message: - """Call the method of ``store`` for a Stream operation. ``request_id`` is that - of a create or an append, and ``None`` for the other operations. - - Raises: - StreamError: The Store refused the call. The reason is - ``STREAM_ERROR_REASON_STORE_UNAVAILABLE`` if the method raised any - other exception, and ``STREAM_ERROR_REASON_STORE_CORRUPT`` if it - returned something else than the response message of the operation. - """ + """Translate Store exceptions before Core decides whether to retry.""" method, _, response_type = _store_operation(operation) call = getattr(store, method) try: @@ -554,18 +477,10 @@ async def _call_store( # pyright: ignore[reportUnusedFunction] request_id: str | None, timeout: timedelta | None = None, ) -> google.protobuf.message.Message: - """Call a Store for client code, which is :py:func:`_call_method` with the - Store request of an SDK request, the payload codec, the check of an append, - the ref of a created Stream and a timeout. - - ``request`` is the SDK request, with its ref, and the response of a create is - the SDK response, with the ref. The other responses are those of the Store. The - codec gets each body of an append and each Record of a read alone, with no - serialization context, since the reader of a Record can be any code. ``limits`` - are those of the Stream config, from :py:meth:`StreamConfig._limits`. - - Raises: - StreamError: The call failed. + """Keep client codec and append checks consistent with Workflow calls. + + Records have no serialization context because any client or Workflow can + read them. Each codec call receives one Record body. """ store_request = _store_request(request) if ( @@ -601,7 +516,7 @@ async def _call_store( # pyright: ignore[reportUnusedFunction] ) from err if isinstance(response, ReadRecordsResponse) and not response.last_offset: assert isinstance(store_request, ReadRecordsRequest) - # The page shows where it ended, so a Store doesn't have to say it. + # Stores may omit the cursor when the page already identifies it. records = response.records response.last_offset = ( records[-1].offset if records else store_request.from_offset @@ -650,7 +565,7 @@ async def _call_stream_store( # pyright: ignore[reportUnusedFunction] ) request_id = None if isinstance(request, (sdk.CreateStreamRequest, sdk.AppendRecordsRequest)): - request_id = str(uuid.uuid4()) + request_id = str(input._stream_request_id) response = await _call_store( store, stream_config._limits(), @@ -678,14 +593,10 @@ async def _call_stream_store( # pyright: ignore[reportUnusedFunction] class _StoreCaller: # pyright: ignore[reportUnusedClass] - """The caller of a Stream Store for the bridge, which gives and takes the - encoded Store messages. - - SDK Core calls :py:meth:`call` for each append and read of Workflow code. - """ + """Keep Store calls on the Python event loop so Core can cancel them.""" def __init__(self, store: Callable[[], StreamStore]) -> None: - """Create a caller of the Store that ``store`` returns at each call.""" + """Resolve the Store at each call so client replacement takes effect.""" self._store = store async def call( @@ -695,12 +606,10 @@ async def call( request_id: str | None, on_task: Callable[[asyncio.Task[Any]], None], ) -> bytes: - """Call the Store for a Stream operation and return its encoded response. + """Register the Python task before any Store work can start. - ``request_id`` is that of a create or an append, and ``None`` for the other - operations. ``on_task`` gets the task of this call, so that the bridge can - cancel it. It raises :py:class:`asyncio.CancelledError` if the bridge has - already dropped the call. + ``on_task`` raises :py:class:`asyncio.CancelledError` if Core already + dropped the call. """ task = asyncio.current_task() assert task diff --git a/temporalio/contrib/streams/_appender.py b/temporalio/contrib/streams/_appender.py index b476266fc1..197c1a65bc 100644 --- a/temporalio/contrib/streams/_appender.py +++ b/temporalio/contrib/streams/_appender.py @@ -154,6 +154,9 @@ async def __aexit__( """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 @@ -178,6 +181,8 @@ def _start(self) -> None: 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: diff --git a/temporalio/converter/_payload_converter.py b/temporalio/converter/_payload_converter.py index b3d898a16e..424e0ee8ec 100644 --- a/temporalio/converter/_payload_converter.py +++ b/temporalio/converter/_payload_converter.py @@ -1083,7 +1083,7 @@ def value_to_type( # Simply instantiate the dataclass. This will fail as expected when # missing required fields. # TODO(cretz): Want way to convert snake case to camel case? - # Calling the hint lets an instance of ``Box[int]`` keep its type argument. + # The alias retains type arguments that its dataclass origin would lose. obj = hint(**field_values) # init=False fields cannot be passed to __init__ but are serialized, so # restore them afterwards. object.__setattr__ also works on frozen diff --git a/temporalio/testing/_stream_store.py b/temporalio/testing/_stream_store.py index c4f9156bb7..6a42282d92 100644 --- a/temporalio/testing/_stream_store.py +++ b/temporalio/testing/_stream_store.py @@ -259,12 +259,14 @@ async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse stream.records, request.from_offset, key=lambda record: record.offset ) wait = request.wait.ToTimedelta().total_seconds() - if start == len(stream.records) and wait > 0: + until = self._now() + wait + while start == len(stream.records) and self._now() < until: try: - async with asyncio.timeout(wait): + async with asyncio.timeout_at(min(until, stream.expires_at)): await stream.changed.wait() except TimeoutError: pass + self._stream(request.stream_id) end = len(stream.records) if request.max_records > 0: end = min(end, start + request.max_records) diff --git a/temporalio/worker/_replayer.py b/temporalio/worker/_replayer.py index edb89d59c0..8189cef00a 100644 --- a/temporalio/worker/_replayer.py +++ b/temporalio/worker/_replayer.py @@ -73,15 +73,12 @@ def __init__( 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`` is the Stream config of the client that the worker - used. A replay chooses the Store of each Stream call again, so a - Workflow with Stream calls needs a config with the same Store names and - the same selector. A replay takes the result of each append, create and - describe of a Stream from history, so it calls no Store for them, and a - Store of the same name, for example a - :py:class:`temporalio.testing.MemoryStreamStore`, can stand in. It reads - the Records of each Stream read again from the Store, and fails if the - Store no longer has them. + ``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), diff --git a/temporalio/worker/_worker.py b/temporalio/worker/_worker.py index a16b08e4ef..7c09f31ebc 100644 --- a/temporalio/worker/_worker.py +++ b/temporalio/worker/_worker.py @@ -348,17 +348,14 @@ def __init__( Please report any issues you encounter with this setting or if you feel the default should be changed. WARNING: This setting is experimental. - stream_read_time: How long the Stream reads of a Workflow Task can - wait, from the start of the task or the end of its replay. At that - limit, a read with a wait gives a page with no Record. ``read`` and - ``read_pages`` never end at a page with no Record, and read again - with the whole wait, also in a later task. With no wait given, - their reads after the first page wait up to 1 minute, cut at this - limit. A read with no wait, such as ``read_page`` with none, goes - on without holding the task until the Store answers. Defaults to - half the Workflow Task timeout. The limit is always before the - heartbeat of the task, so a read alone never makes the Worker send - a heartbeat. Appends have no such limit. + stream_read_time: Maximum time that Stream reads can keep a Workflow + Task open, measured from its start or the end of replay. Defaults + to half the task timeout and always ends before its heartbeat. + Reads alone don't cause task heartbeats. Appends have no such limit. + At the limit, waiting reads return empty pages. Iterators continue + with a new wait, possibly in another task. Unset iterator waits + default to one minute after the first page. Immediate reads can + continue without holding the task open until the Store answers. WARNING: This setting is experimental. """ @@ -515,7 +512,6 @@ def _init_from_config(self, client: temporalio.client.Client, config: WorkerConf ) activities = list(config.get("activities") or []) if client_config["stream_config"] and config.get("workflows"): - # Workflow code creates and describes a Stream in this Local Activity. activities.append(_stream_store_call) if activities: _warn_if_activity_executor_max_workers_is_inconsistent(config) diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index dc890d4215..ceeccaf6d1 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -585,8 +585,7 @@ def _activate( check_conditions=index == 1 or index == 2, jobs=act.jobs ) except Exception as err: - # A Stream call that the Worker can't serve fails the task, and so does a create - # or a describe in an outage, whatever the failure exception types are + # 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 @@ -1270,12 +1269,13 @@ async def run_workflow(input: ExecuteWorkflowInput) -> None: return raise - if not self._workflow_input: + workflow_input = self._workflow_input + if not workflow_input: raise RuntimeError( "Expected workflow input to be set. This is an SDK Python bug." ) self._primary_task = self.create_task( - self._run_top_level_workflow_function(run_workflow(self._workflow_input)), + self._run_top_level_workflow_function(lambda: run_workflow(workflow_input)), name="run", ) if self._cancel_primary_task_pending: @@ -2865,7 +2865,7 @@ async def run_signal() -> None: await self._inbound.handle_signal(input) task = self.create_task( - self._run_top_level_workflow_function(run_signal()), + self._run_top_level_workflow_function(run_signal), name=f"signal: {job.signal_name}", ) task.add_done_callback(done_callback) @@ -2946,9 +2946,12 @@ def _run_once( # This is used for the primary workflow function and signal handlers in # order to apply common exception handling to each - async def _run_top_level_workflow_function(self, coro: Awaitable[None]) -> None: + async def _run_top_level_workflow_function( + self, create_coro: Callable[[], Awaitable[None]] + ) -> None: try: - await coro + # Eviction can cancel this task before it starts, so defer the inner coroutine. + await create_coro() except _ContinueAsNewError as err: logger.debug("Workflow requested continue as new") err._apply_command() diff --git a/temporalio/worker/_workflow_streams.py b/temporalio/worker/_workflow_streams.py index 53cd68bfbb..2d701b8b38 100644 --- a/temporalio/worker/_workflow_streams.py +++ b/temporalio/worker/_workflow_streams.py @@ -53,31 +53,24 @@ class _Read: class _WorkflowStreams: # pyright: ignore[reportUnusedClass] - """The Stream calls of one Workflow instance. - - Each call first gets its Store, and :py:func:`_start_call` then starts it on - that Store. An append and a read are commands of SDK Core, which makes the - Store calls and gives each result in a job. Core has no command for a create or - a describe, so those run in a Local Activity of the SDK. + """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 - """The error of a call that must fail the Workflow Task, if one came.""" # Cancelled reads still receive one result from Core. self._reads: dict[int, _Read] = {} def start( self, input: StartNexusOperationInput[Any, OutputT] ) -> temporalio.workflow.NexusOperationHandle[OutputT]: - """Start a Stream operation and return its handle. + """Schedule before returning so command order matches call order. - The command of the call is added before this returns, so commands are in - the order of the calls. Cancelling the handle ends its wait immediately. - Core can't stop an append or a read, so those still run, and the job that - still comes for the call is dropped. + 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") @@ -89,8 +82,7 @@ def start( model = input.input result_type: Any = input.output_type request = temporalio.nexus.system._support.model_to_proto(model, *converters) - # The converter refuses a body of no type, and the job of the page would then - # fail the Workflow Task. + # Reject missing type information before a result could fail the task. if isinstance(request, sdk.ReadRecordsRequest) and typing.get_args( result_type ) == (object,): @@ -150,7 +142,7 @@ def resolve_append( future = self._appends.pop(job.seq, None) if future is None: raise RuntimeError(f"Failed finding Stream append for sequence {job.seq}") - # A cancelled call waits no more, and Core still gives the result of its write. + # Core completes writes even after their caller is cancelled. if future.done(): return if job.HasField("failed"): @@ -172,8 +164,7 @@ def resolve_read( page = proto.ReadRecordsResponse( records=job.page.records, last_offset=job.page.last_offset ) - # A body that the converter refuses fails the Workflow Task, as a result of a - # Local Activity does. + # Conversion failures must fail the task before Workflow code resumes. read.waiter.set_result( temporalio.nexus.system._support.model_from_proto( page, @@ -250,19 +241,13 @@ def _response( outage.__cause__ = err raise self._fail_task(outage) raise error from err - # The ref of a create has the Store name of History, so a replay gives the same - # ref under any Stream config. + # 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: - """Make ``error`` the failure of the Workflow Task and return it. - - Workflow code that catches the error of a call that the Worker can't serve - would go on with no Stream call in History. So the task fails, whatever the - failure exception types of the Worker and of the Workflow are. - """ + """Prevent caught errors from recording an unserved call as successful.""" self.task_error = self._instance._current_activation_error = error return error @@ -280,13 +265,7 @@ def _start_call( request: google.protobuf.message.Message, result_type: Any, ) -> asyncio.Future[Any]: - """Start a Stream call of Workflow code on the Store named ``store``, and return - the future of its result. - - An append or a read is a command of SDK Core. A create or a describe runs in - the SDK's Local Activity. ``request`` is the SDK request of the call, with its - ref, and ``result_type`` is the type of the call's result. - """ + """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): @@ -312,8 +291,7 @@ def _start_call( result = instance.create_future() streams._reads[seq] = _Read(result, result_type) return result - # Each run of a chain sends the same id, so a Store answers the create of a - # later run as the create that made the Stream. + # 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 @@ -321,7 +299,7 @@ def _start_call( class _StreamCall(temporalio.workflow.NexusOperationHandle[OutputT]): - """Handle of a Stream call, which a task of the Workflow instance runs.""" + """Cancel the caller's wait without waiting for the Store call to finish.""" def __init__(self, task: asyncio.Task[OutputT]) -> None: self._task = task @@ -341,14 +319,7 @@ def cancel(self) -> bool: async def _stream_store_call( # pyright: ignore[reportUnusedFunction] operation: str, store: str, request: bytes, request_id: str | None ) -> bytes: - """Call the Stream Store named ``store`` of the Worker's client for a create - or a describe of Workflow code, which chose that Store. ``request`` is the - encoded SDK request. ``request_id`` is that of a create, and ``None`` for a - describe. - - Returns the encoded response. The ref of a create's response has the name of - the Store that it called, so History has the Store of the created Stream. - """ + """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( @@ -375,13 +346,7 @@ async def _stream_store_call( # pyright: ignore[reportUnusedFunction] def _stream_error_from_failure( failure: temporalio.api.failure.v1.Failure, ) -> StreamError | None: - """Return the Stream error of a failure, or ``None`` if it isn't one. - - The failure of a Stream call has a - ``temporal.api.stream.v1.StreamErrorDetails`` message in its details. A - reason that this SDK doesn't know becomes - ``STREAM_ERROR_REASON_UNSPECIFIED``. - """ + """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(): @@ -416,12 +381,7 @@ def _bridge_streams( # pyright: ignore[reportUnusedFunction] stream_config: Callable[[], StreamConfig | None], read_time: timedelta | None, ) -> temporalio.bridge.streams.WorkerStreams: - """Return what the bridge needs for the Stream Stores of a worker. - - ``stream_config`` gives the Stream config that the worker has at a call, - which is the one of another client after a client swap. ``read_time`` is how - long the reads of a Workflow Task can wait, or ``None`` for Core's default. - """ + """Resolve Store instances at call time so client replacement takes effect.""" def store(name: str) -> StreamStore: current = stream_config() diff --git a/tests/contrib/streams/test_appender.py b/tests/contrib/streams/test_appender.py index ab8b6b00bd..51597af82e 100644 --- a/tests/contrib/streams/test_appender.py +++ b/tests/contrib/streams/test_appender.py @@ -1,9 +1,9 @@ """Tests of the buffered appender, with no server.""" import asyncio -import random from datetime import timedelta from typing import Any +from unittest.mock import AsyncMock, Mock, call import pytest @@ -11,7 +11,7 @@ from temporalio.contrib.streams import BufferedAppender from temporalio.exceptions import StreamError from temporalio.nexus.system.stream_service import AppendRecordsResponse -from tests.helpers.streams import failure_note, run_with_virtual_clock +from tests.helpers.streams import run_with_virtual_clock class _FakeStream: @@ -28,14 +28,10 @@ def __init__( self.written: list[int] = [] self.batches: list[tuple[float, float, tuple[int, ...]]] = [] """The start time, the end time and the Records of each batch.""" - self.writes = 0 - self.overlaps = 0 async def append(self, *records: int) -> AppendRecordsResponse: loop = asyncio.get_running_loop() started = loop.time() - self.overlaps += self.writes - self.writes += 1 try: await asyncio.sleep(self._write_time) if len(self.batches) == self._fails_at: @@ -49,112 +45,102 @@ async def append(self, *records: int) -> AppendRecordsResponse: offset = len(self.written).to_bytes(8, "big") return AppendRecordsResponse(first_offset=offset, last_offset=offset) finally: - self.writes -= 1 self.batches.append((started, loop.time(), records)) -def test_buffered_appender_writes_in_order_one_batch_at_a_time() -> None: - for seed in range(500): - with failure_note(f"seed {seed}"): - run_with_virtual_clock(_appends_script(random.Random(seed))) +@pytest.mark.parametrize("delay,seconds", [(None, 0.1), (timedelta(0), 0.0)]) +def test_the_batch_delay_starts_with_the_first_record( + delay: timedelta | None, seconds: float +) -> None: + async def script() -> None: + stream: Any = _FakeStream(0) + appender = BufferedAppender[int](stream, max_delay=delay) + appender.append(1) + if seconds: + await asyncio.sleep(seconds / 2) + appender.append(2) + await asyncio.sleep(1) + assert stream.batches == [(seconds, seconds, (1, 2))] + run_with_virtual_clock(script()) -async def _appends_script(rng: random.Random) -> None: + +def test_full_batches_wait_for_the_previous_write() -> None: + async def script() -> None: + stream: Any = _FakeStream(2) + appender = BufferedAppender[int]( + stream, max_delay=timedelta(seconds=3), 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, max_delay=timedelta(seconds=90) + ) 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() - max_delay = rng.choice([None, 0.0, 0.02, 0.5]) - max_batch_records = rng.choice([None, None, 1, 2, 5]) - fails_at = rng.choice([None, None, rng.randrange(6)]) - write_time = rng.choice([0.0, 0.03, 0.3]) - cancelled = rng.random() < 0.3 - stream: Any = _FakeStream(write_time, fails_at, cancelled=cancelled) - appender = BufferedAppender[int]( - stream, - max_delay=None if max_delay is None else timedelta(seconds=max_delay), - max_batch_records=max_batch_records, - ) - delay = 0.1 if max_delay is None else max_delay - # Sleeps that end inside a delay, inside a write, and after both - sleeps = [0, delay / 3, delay, write_time / 3, write_time, delay + write_time + 1] - # The time that each appended Record came at, by the Record - arrived: list[float] = [] - # The time from the start of each flush to its end - flushes: list[tuple[float, float]] = [] - # The count of ended batches at the start of the flush that the block waits in - flushing: int | None = None - error: BaseException | None = None + previous = loop.get_task_factory() + stream = Mock() + stream.append = AsyncMock(return_value=AppendRecordsResponse(last_offset=b"last")) try: - async with appender: - for _ in range(rng.randrange(1, 15)): - action = rng.choice(["append", "sleep"] * 3 + ["flush", "cancel"]) - called_at, appended = loop.time(), len(arrived) - if action == "append": - count = rng.randrange(1, 4) - appender.append(*range(appended, appended + count)) - arrived += [called_at] * count - elif action == "sleep": - await asyncio.sleep(rng.choice(sleeps)) - elif action == "flush": - flushes.append((called_at, float("inf"))) - flushing = len(stream.batches) - offset = await appender.flush() - flushing = None - flushes[-1] = (called_at, loop.time()) - # A flush writes each Record that came before it. - assert stream.written[:appended] == list(range(appended)) - assert int.from_bytes(offset or b"", "big") == len(stream.written) - else: - # A cancelled flush doesn't stop the write that it waits for. - flush = asyncio.ensure_future(appender.flush()) - await asyncio.sleep(rng.choice(sleeps[:4])) - flush.cancel() - flushes.append((called_at, loop.time())) - if rng.random() < 0.5: - # The timer alone writes what is left, with no flush. - await asyncio.sleep(1000) - assert stream.written == list(range(len(arrived))) or appender.unwritten - flushes.append((loop.time(), float("inf"))) - flushing = len(stream.batches) - except (StreamError, RuntimeError, asyncio.CancelledError) as err: - error = err - - # The written Records are the first of the appended ones, in their order. - assert stream.written == list(range(len(stream.written))) - assert stream.overlaps == 0 - assert len(stream.written) + appender.unwritten == len(arrived) - failed = fails_at is not None and len(stream.batches) > fails_at - assert (error is not None) == failed == bool(appender.unwritten) - if error: - # Nothing is written after the batch that failed, and each later call raises its - # error. After a cancelled write that is a `RuntimeError`, as nobody cancelled it. - assert len(stream.batches) == (fails_at or 0) + 1 - later = RuntimeError if cancelled else StreamError - with pytest.raises(later) as raised: - appender.append(0) - with pytest.raises(later) as again: - await appender.flush() - assert raised.value is again.value - # Only a flush that waited for the cancelled write got its cancel. - waited = flushing is not None and flushing <= (fails_at or 0) - if cancelled and waited: - assert isinstance(error, asyncio.CancelledError) - else: - assert error is raised.value - previous_end = float("-inf") - for started, ended, records in stream.batches: - assert 0 < len(records) <= (max_batch_records or len(records)) - due = arrived[records[0]] + delay - # A batch starts once the delay of its first Record ends, or when the write - # before it ends, if that is later. - assert started <= max(due, previous_end) + 1e-9 - # Only a flush starts a batch with no maximum earlier. - flushed = any(start <= started <= end for start, end in flushes) - assert max_batch_records or flushed or started >= due - 1e-9 - previous_end = ended - - -def test_async_with_keeps_the_error_of_its_block() -> None: + 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) + 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") diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index a93dca05d3..b032755a3a 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -61,6 +61,7 @@ answers, core_failure, failure_note, + loses_answer, run_with_virtual_clock, ) @@ -264,6 +265,37 @@ async def test_a_created_stream_keeps_its_selected_store() -> None: assert not b.calls +async def test_a_client_retry_recovers_a_lost_store_answer() -> None: + class Retry(temporalio.client.OutboundInterceptor): + async def start_nexus_operation( + self, input: temporalio.client.StartNexusOperationInput + ) -> NexusOperationHandle[Any]: + try: + return await self.next.start_nexus_operation(dataclasses.replace(input)) + except StreamError as err: + if err.reason != _UNAVAILABLE: + raise + return await self.next.start_nexus_operation(dataclasses.replace(input)) + + store = FaultStore() + store.faults["create_stream"].append(loses_answer()) + store.faults["append_records"].append(loses_answer()) + client = Client( + Mock(spec=ServiceClient), + stream_config=StreamConfig([store]), + interceptors=[_Interceptor(Retry)], + ) + stream = await client.create_stream(id="s", body_type=int) + assert stream.created is True + await stream.append(1) + await stream.append(2) + create, create_retry, append, append_retry, second = (key for _, key in store.calls) + assert create == create_retry + assert append == append_retry + assert len({create, append, second}) == 3 + assert [record.body for record in (await stream.read_page()).records] == [1, 2] + + async def test_an_empty_client_append_does_not_reach_the_store() -> None: store = FaultStore() client = Client(Mock(spec=ServiceClient), stream_config=StreamConfig([store])) diff --git a/tests/testing/test_stream_store.py b/tests/testing/test_stream_store.py index 059deac265..9a6e54b98d 100644 --- a/tests/testing/test_stream_store.py +++ b/tests/testing/test_stream_store.py @@ -357,40 +357,47 @@ async def script(rng: random.Random) -> None: run_with_virtual_clock(script(random.Random(seed))) -def test_a_read_waits_for_the_next_write_or_for_its_wait() -> None: - async def script(rng: random.Random) -> None: +@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=100) + streams = _streams(retention=10) await streams.create_stream(CreateStreamRequest(stream_id=_S), request_id="") first = await streams.append_records(_client_append(), request_id="") - wait, write_in = rng.sample(range(1, 60), 2) - write = rng.random() < 0.5 - read = asyncio.ensure_future( - streams.read_records( - ReadRecordsRequest( - stream_id=_S, - from_offset=first.last_offset, - wait=Duration(seconds=wait), - ) - ) + request = ReadRecordsRequest( + stream_id=_S, from_offset=first.last_offset, wait=Duration(seconds=wait) ) - answered_at: list[float] = [] - read.add_done_callback(lambda _: answered_at.append(loop.time())) - await asyncio.sleep(write_in) - if write: - await streams.append_records(_client_append(), request_id="") - page = await read - in_time = write and write_in < wait - assert ( - answered_at == [float(write_in if in_time else wait)] - and len(page.records) == in_time - and page.last_offset - == (page.records[-1].offset if in_time else first.last_offset) - ), f"{page} at {answered_at}" - for seed in range(200): - with failure_note(f"seed {seed}"): - run_with_virtual_clock(script(random.Random(seed))) + 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(last_offset=first.last_offset) + else: + [record] = page.records + assert page.last_offset == record.offset > first.last_offset + + run_with_virtual_clock(script()) async def test_a_store_call_of_the_bridge_gives_the_store_the_caps_of_the_read() -> ( diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py index 96b749873c..86113207bc 100644 --- a/tests/worker/test_workflow_streams.py +++ b/tests/worker/test_workflow_streams.py @@ -2,7 +2,6 @@ import asyncio import dataclasses -import random from collections.abc import Sequence from dataclasses import dataclass from datetime import datetime, timedelta, timezone @@ -712,9 +711,7 @@ def _store_of(command: WorkflowCommand) -> str: async def test_the_store_of_a_call_is_chosen_before_its_command() -> None: operations = ["create", "append", "read", "describe"] a, b = MemoryStreamStore(name="a"), MemoryStreamStore(name="b") - for mask in range(2 ** len(operations)): - # Bit `at` of `mask` gives call `at` to Store b. - on_b = [bool(mask >> at & 1) for at in range(len(operations))] + for on_b in ([False, True, False, True], [True, False, True, False]): def selector(context: StreamSelectContext) -> StreamStore: assert _EachCall.instance @@ -805,10 +802,6 @@ async def test_a_stream_call_with_no_stream_config_fails_the_task() -> None: @dataclass class _ReadCall: - """One generated reader, which reads pages of a Stream one after the other, and - what Workflow code got for each page. - """ - stream: str start: int """The offset that the first page comes after. Zero is the start of the Stream.""" @@ -823,10 +816,6 @@ class _ReadCall: class _ReadScript: - """The readers of :py:class:`_ReadsWorkflow`, and for each ``step`` Signal the - readers that its handler cancels and the ones that it starts. - """ - calls: list[_ReadCall] = [] steps: list[tuple[list[int], list[int]]] = [] @@ -880,188 +869,174 @@ def _offset(number: int) -> bytes: return number.to_bytes(8, "big") if number else b"" -def _body(stream: str, number: int) -> Any: - """Return the body of a Record, which for some isn't the ``int`` of a reader.""" - return "text" if stream == "s1" and number % 3 == 0 else number - +_READ_FLAGS = [ + (), + (_WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH,), +] -@dataclass -class _OpenRead: - """A read whose job hasn't come, and the reader that started it.""" - stream: str - after: int - call: int - cancelled: bool = False - """Whether its reader was cancelled. SDK Core still gives the read its one job.""" - - -async def test_a_read_page_call_is_one_command_and_one_job() -> None: - single_batch = _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH - for seed in range(300): - # Signals run before the Stream jobs of their activation, or after all of them - # with the single-batch flag of the History. - for flags in ((), (single_batch,)): - # A replay sends the same commands as the first run. - replaying = seed % 2 == 1 - with failure_note(f"seed {seed}, flags {flags}, replaying {replaying}"): - await _reads_script(random.Random(seed), flags, replaying) - - -async def _reads_script( - rng: random.Random, flags: Sequence[int], replaying: bool -) -> None: - converter = temporalio.converter.DefaultPayloadConverter() - calls: list[_ReadCall] = [] - _ReadScript.calls, _ReadScript.steps = calls, [] +async def _start_readers( + calls: list[_ReadCall], flags: Sequence[int], replaying: bool +) -> tuple[_WorkflowInstanceImpl, WorkflowActivationCompletion]: + _ReadScript.calls = calls + _ReadScript.steps = [([], list(range(len(calls))))] instance = _new_instance( _ReadsWorkflow, StreamConfig([MemoryStreamStore(name="a")]) ) - initialize = WorkflowActivationJob(initialize_workflow=InitializeWorkflow()) - completion = await _activate(instance, initialize, flags=flags, replaying=replaying) - assert not completion.successful.commands + completion = await _activate( + instance, + WorkflowActivationJob(initialize_workflow=InitializeWorkflow()), + WorkflowActivationJob(signal_workflow=SignalWorkflow(signal_name="step")), + flags=flags, + replaying=replaying, + ) + return instance, completion - reads: dict[int, _OpenRead] = {} - # The offset that each reader is at - positions: list[int] = [] - outcomes: list[list[Any]] = [] - seqs = 0 - - def call_read(call: int, commands: list[WorkflowCommand]) -> None: - """Start the read of a reader's next page.""" - nonlocal seqs - reader, after = calls[call], positions[call] - if reader.body_type is None: - # A read with no body type raises in the call, before any command. - outcomes[call].append("TypeError") - return - seqs += 1 - reads[seqs] = _OpenRead(reader.stream, after, call) - # The command has the wait and the limits of the call, and none that the call lacks. - wait = None - if reader.wait is not None: - wait = Duration() - wait.FromTimedelta(reader.wait) - read = ReadStream( - seq=seqs, - stream=StreamRef(id=reader.stream, store="a"), - from_offset=_offset(after), - wait=wait, - max_records=reader.max_records or 0, - max_bytes=reader.max_bytes or 0, - ) - commands.append(WorkflowCommand(read_stream=read)) - - for step in range(rng.randrange(2, 7)): - # Each read gets one job, also one whose reader was cancelled. - jobs: list[ResolveStreamRead] = [] - for seq, read in reads.items(): - if rng.random() >= 0.6: - continue - records = [read.after + 1 + at for at in range(rng.randrange(4))] - # The last_offset of a page can be past its last Record, also in a page with - # no Record. - last = (records[-1] if records else read.after) + rng.choice([0, 0, 1]) - page = StreamPage( + +def _read_result(seq: int, bodies: Sequence[Any], last: int) -> WorkflowActivationJob: + converter = temporalio.converter.DefaultPayloadConverter() + return WorkflowActivationJob( + resolve_stream_read=ResolveStreamRead( + seq=seq, + page=StreamPage( records=[ - StreamRecord( - offset=_offset(number), - body=converter.to_payload(_body(read.stream, number)), - ) - for number in records + StreamRecord(offset=_offset(at), body=converter.to_payload(body)) + for at, body in enumerate(bodies, 1) ], last_offset=_offset(last), - ) - job = ResolveStreamRead(seq=seq, page=page) - if rng.random() < 0.15: - not_found = StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND - job = ResolveStreamRead(seq=seq, failed=core_failure(not_found)) - jobs.append(job) - rng.shuffle(jobs) - waiting = sorted(read.call for read in reads.values() if not read.cancelled) - cancels = [call for call in waiting if rng.random() < 0.25] - starts: list[int] = [] - for _ in range(rng.randrange(3)): - reader = _ReadCall( - stream=rng.choice(["s0", "s1"]), - start=rng.choice([0, 1, 2]), - wait=rng.choice([None, timedelta(0), timedelta(seconds=5)]), - max_records=rng.choice([None, 2]), - max_bytes=rng.choice([None, 100]), - pages=rng.randrange(1, 4), - body_type=rng.choice([int, int, int, Any, Any, None]), - ) - starts.append(len(calls)) - calls.append(reader) - outcomes.append([]) - positions.append(reader.start) - _ReadScript.steps.append((cancels, starts)) - - commands: list[WorkflowCommand] = [] - # The readers that got a job in this activation, in the order of the jobs - got: list[tuple[int, ResolveStreamRead]] = [] - # Whether a reader that waits gets a body that isn't of its type. The job converts - # the page, so this fails the Workflow Task, also if the reader is cancelled later. - refused = False - - def apply_jobs() -> None: - nonlocal refused - for job in jobs: - read = reads.pop(job.seq) - # A cancelled reader no longer waits, so its job is dropped, whatever it is. - if read.cancelled: - continue - got.append((read.call, job)) - bodies = [converter.from_payload(r.body) for r in job.page.records] - typed = calls[read.call].body_type is int - refused = refused or (typed and "text" in bodies) - - def run_handler() -> None: - for call in starts: - call_read(call, commands) - for call in cancels: - outcomes[call].append("cancelled") - # A cancel wins over a job that came for the reader in this activation. - got[:] = [(of, job) for of, job in got if of != call] - # No command cancels a read. - for read in reads.values(): - if read.call == call: - read.cancelled = True - - for part in (apply_jobs, run_handler) if flags else (run_handler, apply_jobs): - part() - for call, job in got: - reader = calls[call] - if job.HasField("failed"): - outcomes[call].append(StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND) - continue - bodies = [converter.from_payload(r.body) for r in job.page.records] - # The next page comes after the last_offset of this one. - positions[call] = int.from_bytes(job.page.last_offset, "big") - outcomes[call].append((bodies, job.page.last_offset)) - if len(outcomes[call]) < reader.pages: - call_read(call, commands) - - signal = SignalWorkflow(signal_name="step", originating_event_id=step + 1) - activation = [WorkflowActivationJob(signal_workflow=signal)] - if refused and flags: - # The jobs come first here, so the handler of the Signal would never start. - activation = [] - activation += [WorkflowActivationJob(resolve_stream_read=job) for job in jobs] - completion = await _activate( - instance, *activation, flags=flags, replaying=replaying + ), + ) + ) + + +@pytest.mark.parametrize("flags", _READ_FLAGS) +@pytest.mark.parametrize("replaying", [False, True]) +async def test_read_pages_keep_their_sequence_and_cursor( + flags: Sequence[int], replaying: bool +) -> None: + calls = [ + _ReadCall("first", 1, timedelta(seconds=5), 2, 100, 2, int), + _ReadCall("second", 0, timedelta(0), None, None, 1, Any), + _ReadCall("untyped", 0, None, None, None, 1, None), + ] + instance, completion = await _start_readers(calls, flags, replaying) + expected = [ + ReadStream( + seq=1, + stream=StreamRef(id="first", store="a"), + from_offset=_offset(1), + wait=Duration(seconds=5), + max_records=2, + max_bytes=100, + ), + ReadStream(seq=2, stream=StreamRef(id="second", store="a"), wait=Duration()), + ] + assert list(completion.successful.commands) == [ + WorkflowCommand(read_stream=read) for read in expected + ] + assert calls[2].outcome == ["TypeError"] + + completion = await _activate( + instance, + _read_result(2, ["text"], 3), + _read_result(1, [], 4), + flags=flags, + replaying=replaying, + ) + assert [call.outcome for call in calls] == [ + [([], _offset(4))], + [(["text"], _offset(3))], + ["TypeError"], + ] + next_read = expected[0] + next_read.seq, next_read.from_offset = 3, _offset(4) + assert list(completion.successful.commands) == [ + WorkflowCommand(read_stream=next_read) + ] + + reason = StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND + completion = await _activate( + instance, + WorkflowActivationJob( + resolve_stream_read=ResolveStreamRead(seq=3, failed=core_failure(reason)) + ), + flags=flags, + replaying=replaying, + ) + assert not completion.successful.commands + assert calls[0].outcome == [([], _offset(4)), reason] + assert not instance._streams._reads + assert not ( + await _activate( + instance, WorkflowActivationJob(remove_from_cache=RemoveFromCache()) + ) + ).successful.commands + + +@pytest.mark.parametrize("flags", _READ_FLAGS) +@pytest.mark.parametrize("replaying", [False, True]) +@pytest.mark.parametrize("when", ["before result", "with result", "after a page"]) +async def test_cancelled_reads_discard_later_results( + flags: Sequence[int], replaying: bool, when: str +) -> None: + call = _ReadCall("s", 0, None, None, None, 2, int) + instance, _ = await _start_readers([call], flags, replaying) + seq = 1 + expected: list[Any] = [] + if when == "after a page": + await _activate( + instance, _read_result(1, [1], 1), flags=flags, replaying=replaying + ) + expected.append(([1], _offset(1))) + seq = 2 + _ReadScript.steps = [([0], [])] + cancel = WorkflowActivationJob(signal_workflow=SignalWorkflow(signal_name="step")) + if when != "with result": + completion = await _activate(instance, cancel, flags=flags, replaying=replaying) + assert not completion.successful.commands + completion = await _activate( + instance, + *([cancel] if when == "with result" else []), + _read_result(seq, [2] if when == "with result" else ["not an integer"], 2), + flags=flags, + replaying=replaying, + ) + assert not completion.successful.commands + assert call.outcome == [*expected, "cancelled"] + assert not instance._streams._reads + assert not ( + await _activate( + instance, WorkflowActivationJob(remove_from_cache=RemoveFromCache()) + ) + ).successful.commands + + +@pytest.mark.parametrize("flags", _READ_FLAGS) +@pytest.mark.parametrize("replaying", [False, True]) +@pytest.mark.parametrize("cancelled", [False, True]) +async def test_invalid_read_bodies_follow_recorded_activation_order( + flags: Sequence[int], replaying: bool, cancelled: bool +) -> None: + call = _ReadCall("s", 0, None, None, None, 1, int) + instance, _ = await _start_readers([call], flags, replaying) + jobs = [] + if cancelled: + _ReadScript.steps = [([0], [])] + jobs.append( + WorkflowActivationJob(signal_workflow=SignalWorkflow(signal_name="step")) + ) + jobs.append(_read_result(1, ["not an integer"], 1)) + completion = await _activate(instance, *jobs, flags=flags, replaying=replaying) + # Single-batch Histories convert the body before the Signal can cancel its reader. + failed = not cancelled or bool(flags) + assert completion.HasField("failed") == failed + assert call.outcome == ([] if failed else ["cancelled"]) + assert not instance._streams._reads + assert not ( + await _activate( + instance, WorkflowActivationJob(remove_from_cache=RemoveFromCache()) ) - if refused: - assert completion.HasField("failed") - break - assert list(completion.successful.commands) == commands - assert [call.outcome for call in calls] == outcomes - # Each read leaves with its job, also a cancelled one. - assert set(instance._streams._reads) == set(reads) - - # An eviction sends no command, also for the reads whose readers it cancels. - evict = WorkflowActivationJob(remove_from_cache=RemoveFromCache()) - assert not (await _activate(instance, evict)).successful.commands + ).successful.commands @workflow.defn From 8cce7b309070d0de6b344f1d84f04ab9be5629dc Mon Sep 17 00:00:00 2001 From: Mohammad Dashti Date: Sat, 28 Nov 2026 04:25:44 -0700 Subject: [PATCH 49/50] Close owned replay iterators before shutdown --- changelog/fixed/sleepy-signal-finch.md | 1 + temporalio/worker/_replayer.py | 14 +++++++++----- tests/worker/test_replayer.py | 17 +++++++++++++++++ 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/changelog/fixed/sleepy-signal-finch.md b/changelog/fixed/sleepy-signal-finch.md index 58d1ecdce2..a0d3f0d669 100644 --- a/changelog/fixed/sleepy-signal-finch.md +++ b/changelog/fixed/sleepy-signal-finch.md @@ -1 +1,2 @@ Prevent unawaited Workflow and Signal coroutines when an activation fails before their tasks start. +Close replay iterators when replay returns early so cleanup finishes before the event loop stops. diff --git a/temporalio/worker/_replayer.py b/temporalio/worker/_replayer.py index 8189cef00a..8f122f0e1b 100644 --- a/temporalio/worker/_replayer.py +++ b/temporalio/worker/_replayer.py @@ -5,8 +5,8 @@ import asyncio import concurrent.futures import logging -from collections.abc import AsyncIterator, Mapping, Sequence -from contextlib import AbstractAsyncContextManager, asynccontextmanager +from collections.abc import AsyncGenerator, AsyncIterator, Mapping, Sequence +from contextlib import AbstractAsyncContextManager, aclosing, asynccontextmanager from dataclasses import dataclass from typing_extensions import TypedDict @@ -153,7 +153,10 @@ async def replay_workflow( async def history_iterator(): yield history - async with self.workflow_replay_iterator(history_iterator()) as replay_iterator: + async with ( + aclosing(history_iterator()) as histories, + self.workflow_replay_iterator(histories) as replay_iterator, + ): async for result in replay_iterator: if raise_on_replay_failure and result.replay_failure: raise result.replay_failure @@ -383,7 +386,7 @@ def on_eviction_hook( workflow_worker_task = asyncio.create_task(workflow_worker.run()) # Yield iterator - async def replay_iterator() -> AsyncIterator[WorkflowReplayResult]: + async def replay_iterator() -> AsyncGenerator[WorkflowReplayResult, None]: async for history in histories: # Clear last complete and push history last_replay_complete.clear() @@ -416,7 +419,8 @@ async def replay_iterator() -> AsyncIterator[WorkflowReplayResult]: replay_failure=last_replay_failure, ) - yield replay_iterator() + async with aclosing(replay_iterator()) as results: + yield results finally: # Close the pusher if pusher is not None: diff --git a/tests/worker/test_replayer.py b/tests/worker/test_replayer.py index 8f4b1fd507..e1bbc4dee9 100644 --- a/tests/worker/test_replayer.py +++ b/tests/worker/test_replayer.py @@ -3,6 +3,7 @@ import re import sys import uuid +from contextlib import aclosing from dataclasses import dataclass from datetime import timedelta from pathlib import Path @@ -131,6 +132,22 @@ async def test_replayer_workflow_complete_json() -> None: ) +async def test_replay_iterator_closes_after_an_early_exit() -> None: + path = Path(__file__).with_name("test_replayer_complete_history.json") + history = WorkflowHistory.from_json("fake", path.read_text()) + + async def histories(): + yield history + yield history + + replayer = Replayer(workflows=[SayHelloWorkflow]) + async with aclosing(histories()) as source: + async with replayer.workflow_replay_iterator(source) as results: + assert (await anext(results)).replay_failure is None + assert await anext(results, None) is None + assert await anext(source) is history + + async def test_replayer_workflow_incomplete(client: Client) -> None: # Run workflow to wait point async with new_say_hello_worker(client) as worker: From c450d7ea997f40b1b9f2b8073444fe1690b3f56c Mon Sep 17 00:00:00 2001 From: Mohammad Dashti Date: Sat, 28 Nov 2026 06:03:33 -0700 Subject: [PATCH 50/50] Update Core for replay failure delivery --- temporalio/bridge/sdk-core | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index 506dba286e..5c01cbf94a 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit 506dba286e14da52ec221ae93c1cc1932c5d53df +Subproject commit 5c01cbf94a5d136cc5173c96e1dfae9e792d04c8