From c346cb81b7114e64d31f31730fdbbdcdbcb0cf44 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Fri, 20 Nov 2026 20:16:36 -0700 Subject: [PATCH 1/6] Pin Core with the Stream runtime and regenerate the bridge protos The Workflow path of Streams needs the Stream commands and jobs of this Core. The regenerated payload visitor reaches their payloads, so the rule for a Stream body is in this commit. --- scripts/gen_payload_visitor.py | 43 ++- temporalio/bridge/Cargo.lock | 78 +++- temporalio/bridge/_visitor.py | 59 ++- .../bridge/proto/external_data/__init__.py | 19 +- .../proto/external_data/external_data_pb2.py | 32 +- .../proto/external_data/external_data_pb2.pyi | 350 ++++++++++++++++++ .../proto/workflow_activation/__init__.py | 10 + .../workflow_activation_pb2.py | 119 +++--- .../workflow_activation_pb2.pyi | 259 ++++++++++++- .../proto/workflow_commands/__init__.py | 8 + .../workflow_commands_pb2.py | 145 ++++---- .../workflow_commands_pb2.pyi | 287 ++++++++++++++ temporalio/bridge/sdk-core | 2 +- temporalio/bridge/src/metric.rs | 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 ++++++++++ 19 files changed, 1589 insertions(+), 157 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 3285c012ca..76ce97bfea 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.12.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" @@ -2671,7 +2726,6 @@ dependencies = [ "tracing-core", "tracing-subscriber", "url", - "uuid", ] [[package]] @@ -2695,8 +2749,6 @@ dependencies = [ "thiserror", "tracing", "tracing-core", - "tracing-subscriber", - "url", ] [[package]] @@ -2745,6 +2797,7 @@ dependencies = [ "futures", "futures-util", "gethostname", + "hyper", "itertools 0.14.0", "lru", "mockall", @@ -2758,6 +2811,7 @@ dependencies = [ "reqwest", "serde", "serde_json", + "sha2", "siphasher", "slotmap", "sysinfo", @@ -2765,6 +2819,7 @@ dependencies = [ "temporalio-client", "temporalio-common", "temporalio-macros", + "temporalio-streams", "thiserror", "tokio", "tokio-stream", @@ -2776,6 +2831,17 @@ dependencies = [ "zip", ] +[[package]] +name = "temporalio-streams" +version = "0.1.0" +dependencies = [ + "enum-iterator", + "futures-util", + "prost", + "prost-wkt-types", + "temporalio-common", +] + [[package]] name = "termtree" version = "0.5.1" @@ -3141,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/_visitor.py b/temporalio/bridge/_visitor.py index 8832b56bc4..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 @@ -681,12 +734,6 @@ async def _visit_temporal_api_streamservice_v1_ReadRecordsRequest( ) -> None: pass - 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_temporal_api_streamservice_v1_ReadRecordsResponse( self, fs: VisitorFunctions, o: Any ): diff --git a/temporalio/bridge/proto/external_data/__init__.py b/temporalio/bridge/proto/external_data/__init__.py index 836e97ef43..75c7d2547d 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, + StreamAppendOffsets, + StreamAppendResult, + StreamCloseIntent, + StreamCloseResult, + StreamMarkerData, + StreamReadPage, + StreamReadResult, +) __all__ = [ "LocalActivityMarkerData", "PatchedMarkerData", + "StreamAppendOffsets", + "StreamAppendResult", + "StreamCloseIntent", + "StreamCloseResult", + "StreamMarkerData", + "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..bf18205207 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.py +++ b/temporalio/bridge/proto/external_data/external_data_pb2.py @@ -14,10 +14,18 @@ from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 +from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 +from temporalio.api.failure.v1 import ( + message_pb2 as temporal_dot_api_dot_failure_dot_v1_dot_message__pb2, +) +from temporalio.api.stream.v1 import ( + message_pb2 as temporal_dot_api_dot_stream_dot_v1_dot_message__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\x1bgoogle/protobuf/empty.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a%temporal/api/failure/v1/message.proto\x1a$temporal/api/stream/v1/message.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"\xb5\x02\n\x10StreamMarkerData\x12\x32\n\x07streams\x18\x01 \x03(\x0b\x32!.temporal.api.stream.v1.StreamRef\x12?\n\rclose_intents\x18\x02 \x03(\x0b\x32(.coresdk.external_data.StreamCloseIntent\x12:\n\x07\x61ppends\x18\x03 \x03(\x0b\x32).coresdk.external_data.StreamAppendResult\x12\x38\n\x06\x63loses\x18\x04 \x03(\x0b\x32(.coresdk.external_data.StreamCloseResult\x12\x36\n\x05reads\x18\x05 \x03(\x0b\x32\'.coresdk.external_data.StreamReadResult"0\n\x11StreamCloseIntent\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x0e\n\x06stream\x18\x02 \x01(\r"\xc4\x01\n\x12StreamAppendResult\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x0e\n\x06stream\x18\x02 \x01(\r\x12\x12\n\nactivation\x18\x03 \x01(\x04\x12>\n\x08\x61ppended\x18\x04 \x01(\x0b\x32*.coresdk.external_data.StreamAppendOffsetsH\x00\x12\x33\n\x07\x66\x61ilure\x18\x05 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\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"g\n\x11StreamCloseResult\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x12\n\nactivation\x18\x02 \x01(\x04\x12\x31\n\x07\x66\x61ilure\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"\xfb\x01\n\x10StreamReadResult\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x0e\n\x06stream\x18\x02 \x01(\r\x12\x12\n\nactivation\x18\x03 \x01(\x04\x12\x13\n\x0b\x66rom_offset\x18\x04 \x01(\x0c\x12\x35\n\x04page\x18\x05 \x01(\x0b\x32%.coresdk.external_data.StreamReadPageH\x00\x12\x33\n\x07\x66\x61ilure\x18\x06 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x12+\n\tcancelled\x18\x07 \x01(\x0b\x32\x16.google.protobuf.EmptyH\x00\x42\x08\n\x06result"\x91\x01\n\x0eStreamReadPage\x12\x14\n\x0crecord_count\x18\x01 \x01(\r\x12\x0c\n\x04\x64one\x18\x02 \x01(\x08\x12\x35\n\x07records\x18\x03 \x03(\x0b\x32$.temporal.api.stream.v1.StreamRecord\x12\x0e\n\x06\x64igest\x18\x04 \x01(\x0c\x12\x14\n\x0crecord_bytes\x18\x05 \x01(\x04\x42\x32\xea\x02/Temporalio::Internal::Bridge::Api::ExternalDatab\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -27,8 +35,22 @@ DESCRIPTOR._serialized_options = ( b"\352\002/Temporalio::Internal::Bridge::Api::ExternalData" ) - _LOCALACTIVITYMARKERDATA._serialized_start = 144 - _LOCALACTIVITYMARKERDATA._serialized_end = 450 - _PATCHEDMARKERDATA._serialized_start = 452 - _PATCHEDMARKERDATA._serialized_end = 503 + _LOCALACTIVITYMARKERDATA._serialized_start = 250 + _LOCALACTIVITYMARKERDATA._serialized_end = 556 + _PATCHEDMARKERDATA._serialized_start = 558 + _PATCHEDMARKERDATA._serialized_end = 609 + _STREAMMARKERDATA._serialized_start = 612 + _STREAMMARKERDATA._serialized_end = 921 + _STREAMCLOSEINTENT._serialized_start = 923 + _STREAMCLOSEINTENT._serialized_end = 971 + _STREAMAPPENDRESULT._serialized_start = 974 + _STREAMAPPENDRESULT._serialized_end = 1170 + _STREAMAPPENDOFFSETS._serialized_start = 1172 + _STREAMAPPENDOFFSETS._serialized_end = 1236 + _STREAMCLOSERESULT._serialized_start = 1238 + _STREAMCLOSERESULT._serialized_end = 1341 + _STREAMREADRESULT._serialized_start = 1344 + _STREAMREADRESULT._serialized_end = 1595 + _STREAMREADPAGE._serialized_start = 1598 + _STREAMREADPAGE._serialized_end = 1743 # @@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 edcd4581a1..17365e71a2 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.pyi +++ b/temporalio/bridge/proto/external_data/external_data_pb2.pyi @@ -4,13 +4,19 @@ 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 +import temporalio.api.failure.v1.message_pb2 +import temporalio.api.stream.v1.message_pb2 + DESCRIPTOR: google.protobuf.descriptor.FileDescriptor @typing.final @@ -139,3 +145,347 @@ 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, in its `data` detail as `binary/protobuf`. Core records one + in each Workflow Task in which Workflow code got a Stream result or asked for a close. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + STREAMS_FIELD_NUMBER: builtins.int + CLOSE_INTENTS_FIELD_NUMBER: builtins.int + APPENDS_FIELD_NUMBER: builtins.int + CLOSES_FIELD_NUMBER: builtins.int + READS_FIELD_NUMBER: builtins.int + @property + def streams( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + temporalio.api.stream.v1.message_pb2.StreamRef + ]: + """Each Stream that the entries refer to, once. An entry refers to a Stream by its index here.""" + + @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, + *, + streams: collections.abc.Iterable[ + temporalio.api.stream.v1.message_pb2.StreamRef + ] + | None = ..., + 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", + "streams", + b"streams", + ], + ) -> None: ... + +global___StreamMarkerData = StreamMarkerData + +@typing.final +class StreamCloseIntent(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + STREAM_FIELD_NUMBER: builtins.int + seq: builtins.int + stream: builtins.int + def __init__( + self, + *, + seq: builtins.int = ..., + stream: builtins.int = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["seq", b"seq", "stream", b"stream"] + ) -> None: ... + +global___StreamCloseIntent = StreamCloseIntent + +@typing.final +class StreamAppendResult(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + STREAM_FIELD_NUMBER: builtins.int + ACTIVATION_FIELD_NUMBER: builtins.int + APPENDED_FIELD_NUMBER: builtins.int + FAILURE_FIELD_NUMBER: builtins.int + seq: builtins.int + stream: builtins.int + activation: 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) -> temporalio.api.failure.v1.message_pb2.Failure: ... + def __init__( + self, + *, + seq: builtins.int = ..., + stream: builtins.int = ..., + activation: builtins.int = ..., + appended: global___StreamAppendOffsets | None = ..., + failure: temporalio.api.failure.v1.message_pb2.Failure | 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", + b"activation", + "appended", + b"appended", + "failure", + b"failure", + "result", + b"result", + "seq", + b"seq", + "stream", + b"stream", + ], + ) -> 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 StreamCloseResult(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + ACTIVATION_FIELD_NUMBER: builtins.int + FAILURE_FIELD_NUMBER: builtins.int + seq: builtins.int + activation: builtins.int + @property + def failure(self) -> temporalio.api.failure.v1.message_pb2.Failure: + """Unset if the Stream is closed.""" + + def __init__( + self, + *, + seq: builtins.int = ..., + activation: builtins.int = ..., + failure: temporalio.api.failure.v1.message_pb2.Failure | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["failure", b"failure"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "activation", b"activation", "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_FIELD_NUMBER: builtins.int + ACTIVATION_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: builtins.int + activation: 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) -> temporalio.api.failure.v1.message_pb2.Failure: ... + @property + def cancelled(self) -> google.protobuf.empty_pb2.Empty: + """Workflow code cancelled the read before it had a result.""" + + def __init__( + self, + *, + seq: builtins.int = ..., + stream: builtins.int = ..., + activation: builtins.int = ..., + from_offset: builtins.bytes = ..., + page: global___StreamReadPage | None = ..., + failure: 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", + "failure", + b"failure", + "page", + b"page", + "result", + b"result", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "activation", + b"activation", + "cancelled", + b"cancelled", + "failure", + b"failure", + "from_offset", + b"from_offset", + "page", + b"page", + "result", + b"result", + "seq", + b"seq", + "stream", + b"stream", + ], + ) -> 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 + RECORDS_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 the page had its last Record, or no Record.""" + digest: builtins.bytes + """The first 16 bytes of the SHA-256 of the Records. It's empty if `records` is set, 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. + """ + @property + def records( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + temporalio.api.stream.v1.message_pb2.StreamRecord + ]: + """The Records of the page, for a read with `records_in_history`.""" + + def __init__( + self, + *, + record_count: builtins.int = ..., + done: builtins.bool = ..., + records: collections.abc.Iterable[ + temporalio.api.stream.v1.message_pb2.StreamRecord + ] + | None = ..., + 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", + "records", + b"records", + ], + ) -> None: ... + +global___StreamReadPage = StreamReadPage 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..68fe115f44 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"\xc4\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\x12+\n\tcancelled\x18\x04 \x01(\x0b\x32\x16.google.protobuf.EmptyH\x00\x42\x08\n\x06status"Q\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"\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.FailureB8\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 + _RESOLVESTREAMREAD._serialized_start = 7319 + _RESOLVESTREAMREAD._serialized_end = 7515 + _STREAMPAGE._serialized_start = 7517 + _STREAMPAGE._serialized_end = 7598 + _RESOLVESTREAMAPPEND._serialized_start = 7601 + _RESOLVESTREAMAPPEND._serialized_end = 7762 + _STREAMAPPENDED._serialized_start = 7764 + _STREAMAPPENDED._serialized_end = 7823 + _RESOLVESTREAMCLOSE._serialized_start = 7825 + _RESOLVESTREAMCLOSE._serialized_end = 7908 # @@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 af1a2e38ad..8eb3556b6f 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,11 @@ 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, since a replay scans + ahead for their marker too, the appends by `seq`, then the closes by `seq`, and then the reads + by `seq`. A replay that gives the results of several activations in one keeps the order of + those activations among the results of Stream calls, and gives them after each local activity + resolution. * Queries always go last (and, in fact, always come in their own activation) * Evictions also always come in their own activation @@ -77,6 +84,8 @@ class WorkflowActivation(google.protobuf.message.Message): (which must be stable based on lang implementation or convention), rather than the order jobs are processed. + Workflow tasks with no activation jobs are handled internally by Core, without activating lang. + ## Evictions Evictions appear as an activations that contains only a `remove_from_cache` job. Such activations @@ -244,6 +253,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: @@ -318,6 +330,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 @@ -347,6 +371,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( @@ -380,6 +407,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", @@ -419,6 +452,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", @@ -446,6 +485,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 @@ -1639,3 +1681,218 @@ class RemoveFromCache(google.protobuf.message.Message): ) -> None: ... global___RemoveFromCache = RemoveFromCache + +@typing.final +class ResolveStreamRead(google.protobuf.message.Message): + """The result of a `ReadStream`. Each read gets exactly one, also a read that lang cancelled. What + `ResolveStreamAppend` says of its activation holds for it. + """ + + 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: + """Lang cancelled the read with a `RequestCancelStreamRead` before it had a result.""" + + 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 the page has its last Record, or no Record.""" + @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 it comes, + so each result can cost an activation. A replay gives a result in the activation in which the + first run gave it only if History has the flag that turns workflow task chunking off. Without + that flag a replay gives the results of Stream calls as it gives the results of Local + Activities. It can give the results of several activations in one, and a result can come one + activation before or after a Local Activity result that the first run gave with it. + """ + + 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, with these parts: + * an `ApplicationFailureInfo` whose type is `stream_` and the reason of the Stream error + in snake case, such as `stream_closed`, and whose `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`. What `ResolveStreamAppend` says of its activation holds for it.""" + + 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, even if it was already closed before. If set, it has the parts + of 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/__init__.py b/temporalio/bridge/proto/workflow_commands/__init__.py index f599917afa..e2cc730d8d 100644 --- a/temporalio/bridge/proto/workflow_commands/__init__.py +++ b/temporalio/bridge/proto/workflow_commands/__init__.py @@ -1,19 +1,23 @@ from .workflow_commands_pb2 import ( ActivityCancellationType, + AppendToStream, CancelChildWorkflowExecution, CancelSignalWorkflow, CancelTimer, CancelWorkflowExecution, + CloseStream, CompleteWorkflowExecution, ContinueAsNewWorkflowExecution, FailWorkflowExecution, ModifyWorkflowProperties, QueryResult, QuerySuccess, + ReadStream, RequestCancelActivity, RequestCancelExternalWorkflowExecution, RequestCancelLocalActivity, RequestCancelNexusOperation, + RequestCancelStreamRead, ScheduleActivity, ScheduleLocalActivity, ScheduleNexusOperation, @@ -28,20 +32,24 @@ __all__ = [ "ActivityCancellationType", + "AppendToStream", "CancelChildWorkflowExecution", "CancelSignalWorkflow", "CancelTimer", "CancelWorkflowExecution", + "CloseStream", "CompleteWorkflowExecution", "ContinueAsNewWorkflowExecution", "FailWorkflowExecution", "ModifyWorkflowProperties", "QueryResult", "QuerySuccess", + "ReadStream", "RequestCancelActivity", "RequestCancelExternalWorkflowExecution", "RequestCancelLocalActivity", "RequestCancelNexusOperation", + "RequestCancelStreamRead", "ScheduleActivity", "ScheduleLocalActivity", "ScheduleNexusOperation", diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py index 3573f36b11..7c8d6682de 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"\xc8\x12\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\x12X\n\x1arequest_cancel_stream_read\x18\x18 \x01(\x0b\x32\x32.coresdk.workflow_commands.RequestCancelStreamReadH\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"\xce\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\x1a\n\x12records_in_history\x18\x05 \x01(\x08\x12\x13\n\x0bmax_records\x18\x06 \x01(\x05\x12\x11\n\tmax_bytes\x18\x07 \x01(\x03"&\n\x17RequestCancelStreamRead\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' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -72,70 +75,78 @@ _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 = 9570 + _ACTIVITYCANCELLATIONTYPE._serialized_end = 9658 + _WORKFLOWCOMMAND._serialized_start = 596 + _WORKFLOWCOMMAND._serialized_end = 2972 + _STARTTIMER._serialized_start = 2974 + _STARTTIMER._serialized_end = 3057 + _CANCELTIMER._serialized_start = 3059 + _CANCELTIMER._serialized_end = 3085 + _SCHEDULEACTIVITY._serialized_start = 3088 + _SCHEDULEACTIVITY._serialized_end = 3912 + _SCHEDULEACTIVITY_HEADERSENTRY._serialized_start = 3833 + _SCHEDULEACTIVITY_HEADERSENTRY._serialized_end = 3912 + _SCHEDULELOCALACTIVITY._serialized_start = 3915 + _SCHEDULELOCALACTIVITY._serialized_end = 4702 + _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_start = 3833 + _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_end = 3912 + _REQUESTCANCELACTIVITY._serialized_start = 4704 + _REQUESTCANCELACTIVITY._serialized_end = 4740 + _REQUESTCANCELLOCALACTIVITY._serialized_start = 4742 + _REQUESTCANCELLOCALACTIVITY._serialized_end = 4783 + _QUERYRESULT._serialized_start = 4786 + _QUERYRESULT._serialized_end = 4942 + _QUERYSUCCESS._serialized_start = 4944 + _QUERYSUCCESS._serialized_end = 5009 + _COMPLETEWORKFLOWEXECUTION._serialized_start = 5011 + _COMPLETEWORKFLOWEXECUTION._serialized_end = 5087 + _FAILWORKFLOWEXECUTION._serialized_start = 5089 + _FAILWORKFLOWEXECUTION._serialized_end = 5163 + _CONTINUEASNEWWORKFLOWEXECUTION._serialized_start = 5166 + _CONTINUEASNEWWORKFLOWEXECUTION._serialized_end = 6080 + _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5923 + _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5999 + _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3833 + _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3912 + _CANCELWORKFLOWEXECUTION._serialized_start = 6082 + _CANCELWORKFLOWEXECUTION._serialized_end = 6158 + _SETPATCHMARKER._serialized_start = 6160 + _SETPATCHMARKER._serialized_end = 6214 + _STARTCHILDWORKFLOWEXECUTION._serialized_start = 6217 + _STARTCHILDWORKFLOWEXECUTION._serialized_end = 7466 + _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3833 + _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3912 + _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5923 + _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5999 + _CANCELCHILDWORKFLOWEXECUTION._serialized_start = 7468 + _CANCELCHILDWORKFLOWEXECUTION._serialized_end = 7542 + _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_start = 7545 + _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_end = 7687 + _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_start = 7690 + _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_end = 8089 + _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3833 + _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3912 + _CANCELSIGNALWORKFLOW._serialized_start = 8091 + _CANCELSIGNALWORKFLOW._serialized_end = 8126 + _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_start = 8128 + _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_end = 8229 + _MODIFYWORKFLOWPROPERTIES._serialized_start = 8231 + _MODIFYWORKFLOWPROPERTIES._serialized_end = 8310 + _UPDATERESPONSE._serialized_start = 8313 + _UPDATERESPONSE._serialized_end = 8523 + _SCHEDULENEXUSOPERATION._serialized_start = 8526 + _SCHEDULENEXUSOPERATION._serialized_end = 9064 + _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_start = 9014 + _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_end = 9064 + _REQUESTCANCELNEXUSOPERATION._serialized_start = 9066 + _REQUESTCANCELNEXUSOPERATION._serialized_end = 9108 + _APPENDTOSTREAM._serialized_start = 9111 + _APPENDTOSTREAM._serialized_end = 9240 + _CLOSESTREAM._serialized_start = 9242 + _CLOSESTREAM._serialized_end = 9319 + _READSTREAM._serialized_start = 9322 + _READSTREAM._serialized_end = 9528 + _REQUESTCANCELSTREAMREAD._serialized_start = 9530 + _REQUESTCANCELSTREAMREAD._serialized_end = 9568 # @@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 81c47c0b03..7da3288c4b 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,253 @@ 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. The result comes in a + `ResolveStreamAppend` job. Core makes the request id of the append. + + An append is at-least-once. A later attempt of the Workflow Task writes it again, on this Worker + or another. A try that reaches the Store after more batches than the Store remembers is written + again too, after them. + + No command stops an append, so lang takes the job of an append whose awaiter is gone. Core drops + an append that has no result when the Workflow's last command comes, as it drops a Local + Activity. That append may have reached the Store or not, and lang gets no job for it. + + The appends and the closes of one Stream reach the Store one at a time, in the order of their + commands. A close takes its place only once History has its intent. So an append that comes + after a `CloseStream`, before History has the task of that close, is written before the close. + + Core fails the Workflow Task, and gives lang no failure of the append, in these cases: + * `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 waits to try again when the heartbeat of the Workflow Task comes, because the Store + answered `StoreUnavailable` or gave no answer. The message of that failure 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, and not its + `bodies`. A `stream` with no Store name matches any Store of History. An append with no result + in History runs again once the replay is over, as a later attempt, so a reader of the Stream can + see its batch twice. + + A completion of the Workflow Task while an append has no result in a marker forces a new task, + unless it 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, and + Core closes the Stream once History has that task. The result comes in a `ResolveStreamClose` + job of a later task, so a close needs at least one more Workflow Task. + + These rules of `AppendToStream` hold for a close too: + * No command stops it. + * Core drops it when the Workflow's last command comes and it has no result. + * The same cases fail the Workflow Task. + * A replay compares the command with History in the same way. + * A completion of the Workflow Task while it has no result in a marker forces a new task. + + Workflow code that needs its close awaits the result before its last command. A close whose + intent is in History with no result runs again once a replay is over. + """ + + 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. Core asks the Store when the command comes, and the result + comes in exactly one `ResolveStreamRead` job, which has a page, a failure or a cancel. + + 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. + + 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. + + Core fails the Workflow Task in the cases that `AppendToStream` lists, and when `from_offset` + is longer than 1024 bytes or `wait` is negative or has its nanoseconds out of range. A + `max_records` or a `max_bytes` below zero doesn't fail the task. Lang gets a `failed` job for + it. 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. + """ + 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. + """ + @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. The read still gets its + one `ResolveStreamRead` job. The job has `cancelled`, or the result of the read if that came + before the cancel. + + In a replay, the job is the one that History has. 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. The cancel of a read that Workflow code + never sent 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 c675c32469..3bd2ce9938 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit c675c32469af707e1c979a7b808c70b4a0608b82 +Subproject commit 3bd2ce993859d51abba59303459b6bcf3dc877cd diff --git a/temporalio/bridge/src/metric.rs b/temporalio/bridge/src/metric.rs index 276933f6db..ee45990eb8 100644 --- a/temporalio/bridge/src/metric.rs +++ b/temporalio/bridge/src/metric.rs @@ -355,7 +355,7 @@ fn convert_metric_event( ) .expect("Unable to create buffered metric"), )); - populate_into.set(Arc::new(buffered_ref)).unwrap(); + populate_into.set(buffered_ref).unwrap(); None } // Create the attributes and put it on the lazy ref 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 03463e2c03..8b6bdc5593 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -2539,6 +2539,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 eba9c122b9ef989ede73b2c90077a29038f094c7 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Fri, 20 Nov 2026 20:35:52 -0700 Subject: [PATCH 2/6] 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 | 248 +++++++++++++ temporalio/bridge/streams.py | 42 +++ temporalio/client/__init__.py | 8 + temporalio/client/_stream_store.py | 408 +++++++++++++++++++++ temporalio/exceptions.py | 78 +++++ temporalio/testing/__init__.py | 2 + temporalio/testing/_stream_store.py | 404 +++++++++++++++++++++ tests/helpers/streams.py | 61 +++- tests/testing/test_stream_store.py | 467 +++++++++++++++++++++++++ 13 files changed, 1724 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 76ce97bfea..4bcb90c875 100644 --- a/temporalio/bridge/Cargo.lock +++ b/temporalio/bridge/Cargo.lock @@ -2648,6 +2648,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 4b23ae6ce9..6bb89e5b79 100644 --- a/temporalio/bridge/Cargo.toml +++ b/temporalio/bridge/Cargo.toml @@ -72,6 +72,7 @@ temporalio-sdk-core = { version = "0.11.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 ClientTlsConfig.verification_server_name. diff --git a/temporalio/bridge/src/lib.rs b/temporalio/bridge/src/lib.rs index a4fda26db6..6693a8c4a9 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; @@ -48,6 +49,9 @@ fn temporal_sdk_bridge(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(init_runtime, m)?)?; m.add_function(wrap_pyfunction!(raise_in_thread, 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..f5c1312506 --- /dev/null +++ b/temporalio/bridge/src/streams.rs @@ -0,0 +1,248 @@ +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. +pub(crate) struct PythonStore { + pub(crate) caller: Py, + pub(crate) 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) +} + +/// 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(()) + } +} + +/// 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. +#[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::default()); + 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..9ee3ba4440 --- /dev/null +++ b/temporalio/client/_stream_store.py @@ -0,0 +1,408 @@ +"""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 only checks that the 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 ``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. + + .. 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. + """ + + def __post_init__(self) -> None: + """Validate the Stores. + + Raises :exc:`ValueError` if no Store is provided, 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.") + 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] + """Calls 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..9f55ba9d13 100644 --- a/temporalio/exceptions.py +++ b/temporalio/exceptions.py @@ -1,13 +1,17 @@ """Common Temporal exceptions.""" import asyncio +import functools from collections.abc import Sequence from datetime import timedelta from enum import IntEnum from typing import Any +import google.protobuf.json_format + import temporalio.api.enums.v1 import temporalio.api.failure.v1 +import temporalio.api.stream.v1 class TemporalError(Exception): @@ -474,6 +478,80 @@ 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 what ``copy`` and ``pickle`` build the error again 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 + + @classmethod + def _from_failure( + cls, 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``. + """ + reasons = temporalio.api.enums.v1.StreamErrorReason + 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": + google.protobuf.json_format.Parse(payload.data, details) + else: + details.ParseFromString(payload.data) + reason = details.reason + if reason not in reasons.values(): + reason = reasons.STREAM_ERROR_REASON_UNSPECIFIED + error = cls(failure.message, reason=reason) + error._failure = failure + return error + return None + + 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..b0fff5bbac --- /dev/null +++ b/temporalio/testing/_stream_store.py @@ -0,0 +1,404 @@ +"""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. + + .. 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..eee3d0815c 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,56 @@ 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)) + + 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..1256c8e43f --- /dev/null +++ b/tests/testing/test_stream_store.py @@ -0,0 +1,467 @@ +"""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) + # A Store remembers at least the last batch of each Producer. + with pytest.raises(ValueError): + MemoryStreamStore(resend_window=0) + + +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}" + + # A Producer with no kind is refused before the Store gets it. + for stream_id in model.streams: + no_kind = AppendRecordsRequest(stream_id=stream_id, producer=Producer()) + no_kind.records.add().body.data = b"body" + assert ( + await _answer(store.append_records(no_kind)) + == StreamErrorReason.STREAM_ERROR_REASON_INVALID_ARGUMENT + ) + + +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 21d7e94aec7c3ceea8b6c85531bdbab97298b288 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Fri, 20 Nov 2026 20:47:04 -0700 Subject: [PATCH 3/6] 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, apart from the two that build a Producer. --- changelog/added/steady-stream-heron.md | 1 + temporalio/client/_client.py | 22 +- temporalio/client/_impl.py | 54 +++ temporalio/client/_stream_store.py | 63 ++- temporalio/contrib/streams/__init__.py | 13 + temporalio/contrib/streams/_producer.py | 56 +++ 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 | 604 ++++++++++++++++++++++++ 11 files changed, 1146 insertions(+), 7 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..98c83a9f85 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`. 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/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 72986ffa70..41ffe93a6e 100644 --- a/temporalio/client/_impl.py +++ b/temporalio/client/_impl.py @@ -33,6 +33,8 @@ import temporalio.exceptions import temporalio.nexus import temporalio.nexus._operation_context +import temporalio.nexus.system +import temporalio.nexus.system._support from temporalio.activity import ActivityCancellationDetails from temporalio.converter import ( ActivitySerializationContext, @@ -41,6 +43,7 @@ StorageDriverWorkflowInfo, WorkflowSerializationContext, ) +from temporalio.nexus.system.stream_service import CreateStreamRequest from temporalio.service import ( RPCError, RPCStatusCode, @@ -125,6 +128,7 @@ ScheduleUpdate, ScheduleUpdateInput, ) +from ._stream_store import _STREAM_SERVICE, _activity_target, _call_store from ._worker_versioning import WorkerBuildIdVersionSets, WorkerTaskReachability from ._workflow import ( WorkflowExecutionAsyncIterator, @@ -1565,6 +1569,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 self._call_stream_store(input) nexus_context = temporalio.converter.NexusSerializationContext( endpoint=input.endpoint, service=input.service, @@ -1648,6 +1657,51 @@ async def start_nexus_operation( operation=input.operation, ) + async def _call_stream_store( + self, input: StartNexusOperationInput + ) -> NexusOperationHandle[Any]: + """Call the Stream Store of a Stream operation, and return a handle that + has its result. + """ + stream_config = self._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, CreateStreamRequest): + # The created Stream takes the ref of its request. + request.ref.store = store.name() + data_converter = self._client.data_converter + converters = ( + data_converter.payload_converter, + data_converter.failure_converter, + ) + response = await _call_store( + store, + data_converter.payload_codec, + input.operation, + temporalio.nexus.system._support.model_to_proto(request, *converters), + input.rpc_timeout, + ) + result_type = ( + input.result_type + or _STREAM_SERVICE.operation_definitions[input.operation].output_type + ) + handle: NexusOperationHandle[Any] = NexusOperationHandle( + self._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 + async def describe_nexus_operation( self, input: DescribeNexusOperationInput ) -> NexusOperationExecutionDescription: diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 9ee3ba4440..1a3e136927 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -7,11 +7,13 @@ 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 from temporalio.api.enums.v1 import StreamErrorReason from temporalio.api.streamservice.v1 import ( AppendRecordsRequest, @@ -25,13 +27,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 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. @@ -324,9 +334,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) @@ -366,6 +374,53 @@ async def _call_method( return response +async def _call_store( # pyright: ignore[reportUnusedFunction] + store: StreamStore, + 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 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. + """ + if codec and isinstance(request, AppendRecordsRequest): + for appended in request.records: + [body] = await codec.encode([appended.body]) + appended.body.CopyFrom(body) + 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: # pyright: ignore[reportUnusedFunction] + """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, + ) + + class _StoreCaller: # pyright: ignore[reportUnusedClass] """Calls 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..a6b0feb672 --- /dev/null +++ b/temporalio/contrib/streams/_producer.py @@ -0,0 +1,56 @@ +"""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. + + 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 15a8e80102..d15bddbf38 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 eee3d0815c..15a7070236 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..677e8b096c --- /dev/null +++ b/tests/nexus/test_streams.py @@ -0,0 +1,604 @@ +"""Tests of the client path of Streams, with no server.""" + +import asyncio +import concurrent.futures +import copy +import dataclasses +import pickle +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.common.v1 import Payload, Payloads +from temporalio.api.enums.v1 import StreamErrorReason, StreamIdConflictPolicy +from temporalio.api.failure.v1 import ApplicationFailureInfo, Failure +from temporalio.api.stream.v1 import ( + AppendRecord, + ClientProducer, + Producer, + StreamErrorDetails, +) +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 ApplicationError, 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 + + +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 + # One seed in eight has a config that `StreamConfig` refuses. + wrong = rng.random() < 0.125 + if wrong: + names, has_selector = rng.choice( + [ + ([], True), + ([*names, ""], True), + ([*names, names[0]], True), + (["a", "b"], False), + ] + ) + 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] + + if wrong: + with pytest.raises(ValueError): + StreamConfig(stores, store_selector=selector if has_selector else None) + with pytest.raises(ValueError): + await Client(service_client).create_stream(id="s") + assert not service_client.mock_calls + return + 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()) + 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)) + + +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 = Failure( + message=message, + application_failure_info=ApplicationFailureInfo( + type=token, + non_retryable=reason != _UNAVAILABLE, + details=Payloads( + payloads=[ + Payload( + metadata={ + "encoding": b"binary/protobuf", + "messageType": details.DESCRIPTOR.full_name.encode(), + }, + data=details.SerializeToString(), + ) + ] + ), + ), + ) + for form in (failure, from_core): + error = StreamError._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 + assert StreamError._from_failure(Failure(message="other")) is 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, + 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 0fc40c3b787279e5a6157c1853313caaa2a642a7 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Fri, 20 Nov 2026 21:37:09 -0700 Subject: [PATCH 4/6] 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/worker.rs | 16 +- temporalio/bridge/worker.py | 3 + temporalio/client/_stream_store.py | 32 +- temporalio/worker/_interceptor.py | 11 +- temporalio/worker/_replayer.py | 22 + temporalio/worker/_worker.py | 30 +- temporalio/worker/_workflow.py | 3 + temporalio/worker/_workflow_instance.py | 42 +- temporalio/worker/_workflow_streams.py | 314 ++++++++++++++ tests/helpers/streams.py | 136 +++++- tests/nexus/test_streams.py | 23 +- tests/nexus/test_streams_with_worker.py | 552 ++++++++++++++++++++++++ tests/worker/test_workflow_streams.py | 451 ++++++++++++++++++- 14 files changed, 1583 insertions(+), 53 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 98c83a9f85..04dd7ebf97 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`. 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/worker.rs b/temporalio/bridge/src/worker.rs index 39cdc5e773..5b03c767a2 100644 --- a/temporalio/bridge/src/worker.rs +++ b/temporalio/bridge/src/worker.rs @@ -19,14 +19,17 @@ use temporalio_sdk_core::replay::{HistoryForReplay, ReplayWorkerInput}; use temporalio_sdk_core::{ PollError, SlotInfo, SlotInfoTrait, SlotKind, SlotKindType, SlotMarkUsedContext, SlotReleaseContext, SlotReservationContext, SlotSupplier as SlotSupplierTrait, - SlotSupplierPermit, WorkflowErrorType, + SlotSupplierPermit, StreamRuntimes, WorkflowErrorType, }; +use temporalio_streams::record::StoreLimits; +use temporalio_streams::StreamRuntime; use tokio::sync::mpsc::{channel, Sender}; use tokio_stream::wrappers::ReceiverStream; use tracing::error; use crate::client; use crate::runtime; +use crate::streams::PythonStore; pyo3::create_exception!(temporal_sdk_bridge, PollShutdownError, PyException); @@ -65,6 +68,7 @@ pub struct WorkerConfig { plugins: Vec<(String, String)>, storage_drivers: HashSet, disable_payload_error_limit: bool, + stream_stores: Vec<(String, Py)>, } #[derive(FromPyObject)] @@ -716,6 +720,15 @@ fn convert_worker_config( conf: WorkerConfig, task_locals: Arc>, ) -> PyResult { + let stream_runtimes = + StreamRuntimes::new(conf.stream_stores.into_iter().map(|(name, caller)| { + let store = PythonStore { + caller, + event_loop_task_locals: task_locals.clone(), + }; + let runtime = StreamRuntime::new(Arc::new(store), StoreLimits::default()); + (name, Arc::new(runtime)) + })); 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() @@ -777,6 +790,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/worker.py b/temporalio/bridge/worker.py index fd4d2aae3c..d82ee56d56 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,8 @@ class WorkerConfig: plugins: Sequence[tuple[str, str]] storage_drivers: set[str] disable_payload_error_limit: bool + stream_stores: Sequence[tuple[str, temporalio.bridge.streams.StoreCaller]] + """The caller of each Stream Store that Workflow code can use, by Store name.""" @dataclass diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 1a3e136927..1ce477df85 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -255,6 +255,21 @@ class StreamSelectContext: class StreamConfig: """The Stream Stores of a client and of each Worker that uses the client. + 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. + - 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. + .. warning:: This API is experimental and subject to change. """ @@ -272,7 +287,8 @@ 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. + 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. """ def __post_init__(self) -> None: @@ -303,6 +319,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], @@ -312,10 +335,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)) @@ -457,7 +477,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 6196f5efe1..cbfca40e61 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 62a27b29cf..cae5b514b2 100644 --- a/temporalio/worker/_replayer.py +++ b/temporalio/worker/_replayer.py @@ -4,6 +4,7 @@ import asyncio import concurrent.futures +import functools import logging from collections.abc import AsyncIterator, Mapping, Sequence from contextlib import AbstractAsyncContextManager, asynccontextmanager @@ -19,6 +20,7 @@ import temporalio.runtime import temporalio.worker import temporalio.workflow +from temporalio.client._stream_store import _StoreCaller from ..common import HeaderCodecBehavior from ._interceptor import Interceptor @@ -56,6 +58,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. @@ -68,6 +71,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), @@ -86,6 +93,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) @@ -251,6 +259,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"), @@ -279,6 +288,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 ) @@ -356,6 +366,17 @@ def on_eviction_hook( (plugin.name(), plugin.version()) for plugin in self.plugins ], storage_drivers=storage_driver_types, + stream_stores=[ + ( + store.name(), + _StoreCaller( + functools.partial(stream_config._store, store.name()) + ), + ) + for store in stream_config.stores + ] + if stream_config + else [], ), ) bridge_worker_scope = bridge_worker @@ -435,6 +456,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 e06bb99a4b..9fa680c478 100644 --- a/temporalio/worker/_worker.py +++ b/temporalio/worker/_worker.py @@ -4,6 +4,7 @@ import asyncio import concurrent.futures +import functools import hashlib import logging import sys @@ -24,6 +25,7 @@ import temporalio.common import temporalio.runtime import temporalio.service +from temporalio.client._stream_store import _StoreCaller from temporalio.common import ( HeaderCodecBehavior, VersioningBehavior, @@ -45,6 +47,7 @@ WorkflowRunner, _WorkflowLogicFlag, ) +from ._workflow_streams import _stream_store_call from .workflow_sandbox import SandboxedWorkflowRunner logger = logging.getLogger(__name__) @@ -498,7 +501,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 +581,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 +674,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,9 +723,19 @@ def check_activity(activity: str): disable_payload_error_limit=config.get( "disable_payload_error_limit", False ), + # Each caller finds its Store in the client that the worker has at the call. + stream_stores=[ + (name, _StoreCaller(functools.partial(self._stream_store, name))) + for name in sorted(_stream_store_names(client)) + ], ), ) + def _stream_store(self, name: str) -> temporalio.client.StreamStore: + stream_config = self.client._config["stream_config"] + assert stream_config + return stream_config._store(name) + def config(self, *, active_config: bool = False) -> WorkerConfig: """Config, as a dictionary, used to create this worker. @@ -758,6 +775,10 @@ def client(self, value: temporalio.client.Client) -> None: raise ValueError( "New client is not on the same runtime as the existing client" ) + if _stream_store_names(value) != _stream_store_names(self.client): + raise ValueError( + "New client does not have the Stream Stores of the existing client" + ) assert bridge_client._bridge_client self._bridge_worker.replace_client(bridge_client._bridge_client) self._config["client"] = value @@ -1070,6 +1091,11 @@ def _poller_behavior_to_bridge( return None if behavior is None else behavior._to_bridge() +def _stream_store_names(client: temporalio.client.Client) -> set[str]: + stream_config = client._config["stream_config"] + return {store.name() for store in stream_config.stores} if stream_config else set() + + def _warn_if_activity_executor_max_workers_is_inconsistent( config: WorkerConfig, ) -> None: diff --git a/temporalio/worker/_workflow.py b/temporalio/worker/_workflow.py index d8380a6b90..c33ceb0ccb 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 @@ -125,6 +126,7 @@ def __init__( disable_safe_eviction: bool, should_enforce_versioning_behavior: bool, assert_local_activity_valid: Callable[[str], None], + stream_config: Callable[[], StreamConfig | None], encode_headers: bool, max_workflow_task_external_storage_concurrency: int, default_workflow_logic_flags: frozenset[_WorkflowLogicFlag] | None = None, @@ -184,6 +186,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 8b6bdc5593..83dbd44682 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -59,7 +59,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, @@ -88,6 +95,7 @@ WorkflowInboundInterceptor, WorkflowOutboundInterceptor, ) +from ._workflow_streams import _WorkflowStreams logger = logging.getLogger(__name__) @@ -348,6 +356,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 @@ -562,10 +571,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, 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: @@ -677,6 +690,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"): @@ -1830,7 +1847,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, @@ -2355,7 +2377,9 @@ async def _intercept_system_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._streams.start(input) return await self._outbound_start_nexus_operation(input) #### Miscellaneous helpers #### @@ -3367,7 +3391,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 @@ -3414,7 +3440,12 @@ async def _intercept_system_nexus_operation( async def start_system_nexus_operation( self, input: StartNexusOperationInput[Any, OutputT] - ) -> _NexusOperationHandle[OutputT]: + ) -> temporalio.workflow.NexusOperationHandle[OutputT]: + return await self._instance._schedule_system_nexus_operation(input) + + async def _schedule_system_nexus_operation( + self, input: StartNexusOperationInput[InputT, OutputT] + ) -> temporalio.workflow.NexusOperationHandle[OutputT]: return await self._instance._schedule_system_nexus_operation(input) def start_local_activity( @@ -4043,6 +4074,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..4299db6bb7 --- /dev/null +++ b/temporalio/worker/_workflow_streams.py @@ -0,0 +1,314 @@ +"""Stream calls of Workflow code.""" + +from __future__ import annotations + +import asyncio +from collections.abc import Callable, Generator +from typing import TYPE_CHECKING, Any, cast + +import google.protobuf.message +from nexusrpc import OutputT + +import temporalio.activity +import temporalio.api.stream.v1 +import temporalio.api.streamservice.v1 as proto +import temporalio.bridge.proto.workflow_activation +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, _call_store, _operation +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( + StreamError._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: + # Core gives the failure of an attempt as it is, and a timeout inside an + # Activity failure, which has no Stream error. + error = StreamError._from_failure(err.failure) if err.failure else None + if ( + error is None + or error.reason + == StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE + ): + # The task fails and nothing goes into History, as for an outage during + # an append. Workflow code could catch an error of this call. + 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, client.data_converter.payload_codec, operation, stream_request + ) + 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 15a7070236..dc5ca8e218 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,121 @@ 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, +) -> Client: + """Return a client on the connection of ``client`` with the given Stream Stores.""" + config = client.config() + config["stream_config"] = StreamConfig(stores, store_selector=store_selector) + 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 677e8b096c..16e1517441 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -24,9 +24,8 @@ import temporalio.converter import temporalio.nexus.system from temporalio.activity import WorkflowTaskAttempt -from temporalio.api.common.v1 import Payload, Payloads from temporalio.api.enums.v1 import StreamErrorReason, StreamIdConflictPolicy -from temporalio.api.failure.v1 import ApplicationFailureInfo, Failure +from temporalio.api.failure.v1 import Failure from temporalio.api.stream.v1 import ( AppendRecord, ClientProducer, @@ -57,6 +56,7 @@ from tests.helpers.streams import ( FaultStore, Hold, + core_failure, failure_note, run_with_virtual_clock, ) @@ -323,24 +323,7 @@ async def test_a_stream_error_keeps_its_reason_on_every_path() -> None: raised, converter.payload_converter, failure ) # From Core, which builds the failure of a Stream job itself. - from_core = Failure( - message=message, - application_failure_info=ApplicationFailureInfo( - type=token, - non_retryable=reason != _UNAVAILABLE, - details=Payloads( - payloads=[ - Payload( - metadata={ - "encoding": b"binary/protobuf", - "messageType": details.DESCRIPTOR.full_name.encode(), - }, - data=details.SerializeToString(), - ) - ] - ), - ), - ) + from_core = core_failure(number, message) for form in (failure, from_core): error = StreamError._from_failure(form) assert error is not None, number diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py new file mode 100644 index 0000000000..5f78e007cb --- /dev/null +++ b/tests/nexus/test_streams_with_worker.py @@ -0,0 +1,552 @@ +"""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 + + +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") + before = stream_client( + client, first, second, store_selector=lambda _: first + ) + after = stream_client( + client, first, second, store_selector=lambda _: 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) + with pytest.raises(ValueError): + worker.client = stream_client(client, FaultStore("third")) + 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"), + ("AppendRecordsRequest", "own"), + ] + assert [(type(r).__name__, r.stream_id) for r in second.requests] == [ + ("CreateStreamRequest", "shared"), + ("AppendRecordsRequest", "shared"), + ("AppendRecordsRequest", "shared"), + ] + + +@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 workflow.info().get_current_history_length() < 4: + raise RuntimeError( + "The first Workflow Task of each run fails after its create" + ) + 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() + 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 282846b96fd9485553a630eda6e3eb52ca3a7758 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Fri, 20 Nov 2026 21:58:19 -0700 Subject: [PATCH 5/6] 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/worker.rs | 52 ++- temporalio/bridge/worker.py | 3 + temporalio/client/_stream_store.py | 6 + temporalio/worker/_replayer.py | 9 +- temporalio/worker/_worker.py | 20 + temporalio/worker/_workflow.py | 16 + temporalio/worker/_workflow_instance.py | 2 + temporalio/worker/_workflow_streams.py | 111 +++++- temporalio/workflow/__init__.py | 2 + temporalio/workflow/_exceptions.py | 13 + tests/nexus/test_streams_with_worker.py | 489 ++++++++++++++++++++++-- tests/worker/test_workflow_streams.py | 296 +++++++++++++- 13 files changed, 948 insertions(+), 72 deletions(-) diff --git a/changelog/added/steady-stream-heron.md b/changelog/added/steady-stream-heron.md index 04dd7ebf97..bed229f6eb 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`. 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/worker.rs b/temporalio/bridge/src/worker.rs index 5b03c767a2..4b824954b3 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; @@ -69,6 +69,9 @@ pub struct WorkerConfig { storage_drivers: HashSet, disable_payload_error_limit: bool, stream_stores: Vec<(String, Py)>, + stream_read_max_wait_millis: Option, + stream_replay_as_workflow_fail: bool, + stream_replay_as_workflow_fail_for_types: HashSet, } #[derive(FromPyObject)] @@ -522,7 +525,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 { @@ -532,7 +539,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( @@ -720,7 +727,7 @@ fn convert_worker_config( conf: WorkerConfig, task_locals: Arc>, ) -> PyResult { - let stream_runtimes = + let mut stream_runtimes = StreamRuntimes::new(conf.stream_stores.into_iter().map(|(name, caller)| { let store = PythonStore { caller, @@ -729,6 +736,25 @@ fn convert_worker_config( let runtime = StreamRuntime::new(Arc::new(store), StoreLimits::default()); (name, Arc::new(runtime)) })); + if let Some(millis) = conf.stream_read_max_wait_millis { + stream_runtimes.settings.read_max_wait = Duration::from_millis(millis); + } + 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() @@ -760,22 +786,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/worker.py b/temporalio/bridge/worker.py index d82ee56d56..b891936196 100644 --- a/temporalio/bridge/worker.py +++ b/temporalio/bridge/worker.py @@ -66,6 +66,9 @@ class WorkerConfig: disable_payload_error_limit: bool stream_stores: Sequence[tuple[str, temporalio.bridge.streams.StoreCaller]] """The caller of each Stream Store that Workflow code can use, by Store name.""" + stream_read_max_wait_millis: int | None + 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 1ce477df85..faa9199174 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -269,6 +269,12 @@ class StreamConfig: 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 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 of a Stream with no body type raises :exc:`TypeError` in the call, as + in client code, and a body that isn't of the Stream's type fails the + Workflow Task. .. warning:: This API is experimental and subject to change. diff --git a/temporalio/worker/_replayer.py b/temporalio/worker/_replayer.py index cae5b514b2..87e2a69766 100644 --- a/temporalio/worker/_replayer.py +++ b/temporalio/worker/_replayer.py @@ -74,7 +74,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), @@ -317,6 +319,11 @@ 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() + ), + stream_read_max_wait_millis=None, # All values below are ignored but required by Core max_cached_workflows=2, tuner=temporalio.bridge.worker.TunerHolder( diff --git a/temporalio/worker/_worker.py b/temporalio/worker/_worker.py index 9fa680c478..38c15ffcb3 100644 --- a/temporalio/worker/_worker.py +++ b/temporalio/worker/_worker.py @@ -150,6 +150,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. @@ -349,6 +350,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 time that one Stream read of Workflow + code asks its Store to wait for a Record before it asks again. + Defaults to 60 seconds. + WARNING: This setting is experimental. """ config = WorkerConfig( @@ -398,6 +403,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( @@ -648,6 +654,7 @@ def check_activity(activity: str): deduped_storage_driver_types = { driver.type() for driver in self._storage_drivers } + stream_read_max_wait = config.get("stream_read_max_wait") # Create bridge worker last. We have empirically observed that if it is # created before an error is raised from the activity worker @@ -728,6 +735,18 @@ def check_activity(activity: str): (name, _StoreCaller(functools.partial(self._stream_store, name))) for name in sorted(_stream_store_names(client)) ], + stream_read_max_wait_millis=int( + 1000 * stream_read_max_wait.total_seconds() + ) + if stream_read_max_wait is not None + else None, + 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() + ), ), ) @@ -1083,6 +1102,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 c33ceb0ccb..0966684cae 100644 --- a/temporalio/worker/_workflow.py +++ b/temporalio/worker/_workflow.py @@ -852,6 +852,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 83dbd44682..58b2b74d8b 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -694,6 +694,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 4299db6bb7..7b66f0816f 100644 --- a/temporalio/worker/_workflow_streams.py +++ b/temporalio/worker/_workflow_streams.py @@ -3,16 +3,20 @@ from __future__ import annotations import asyncio +import typing from collections.abc import Callable, Generator +from dataclasses import dataclass from typing import TYPE_CHECKING, Any, cast 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.proto.workflow_commands import temporalio.common import temporalio.exceptions import temporalio.nexus.system._support @@ -31,12 +35,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: @@ -46,6 +64,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] @@ -54,7 +74,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") @@ -69,6 +91,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") @@ -84,6 +108,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. @@ -95,15 +141,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( @@ -116,6 +172,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]], @@ -130,15 +216,18 @@ def _resolve( if future.done(): return if job.HasField("failed"): - future.set_exception( - StreamError._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 StreamError._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]: 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 5f78e007cb..47ee83b10c 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( @@ -550,3 +581,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..a29bb62865 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, +) 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 fab988c0279e711b415b25132abaaca992363ec8 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Fri, 20 Nov 2026 22:07:50 -0700 Subject: [PATCH 6/6] 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 | 56 +++++++ temporalio/contrib/streams/__init__.py | 10 +- temporalio/contrib/streams/_appender.py | 198 ++++++++++++++++++++++++ tests/contrib/streams/__init__.py | 0 tests/contrib/streams/test_appender.py | 150 ++++++++++++++++++ 6 files changed, 411 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 bed229f6eb..726fd16d3d 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`. 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..89d1b939e3 --- /dev/null +++ b/temporalio/contrib/streams/README.md @@ -0,0 +1,56 @@ +# 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. + +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. `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`. 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..f9f074fb3d --- /dev/null +++ b/temporalio/contrib/streams/_appender.py @@ -0,0 +1,198 @@ +"""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]): + """Batches the appends of one Stream. + + 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. + + 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, and a Store that limits its batches then + refuses a larger one. + + 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: BaseException | 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. + """ + 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. + """ + target = self._appended + while self._settled < target: + if not self._writing: + self._start() + assert self._writing + # A cancel of the caller doesn't stop the write, which is one batch of the Store. + 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._error = err + self._unwritten = len(batch) + len(self._buffer) + self._settled += len(self._buffer) + self._buffer.clear() + if not isinstance(err, Exception): + 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..af09a5d644 --- /dev/null +++ b/tests/contrib/streams/test_appender.py @@ -0,0 +1,150 @@ +"""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]) + stream: Any = _FakeStream(write_time, fails_at, cancelled=rng.random() < 0.3) + 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]] = [] + 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"))) + offset = await appender.flush() + 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"))) + except (StreamError, 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. + assert len(stream.batches) == (fails_at or 0) + 1 + with pytest.raises(type(error)) as raised: + appender.append(0) + assert raised.value is error or isinstance(error, asyncio.CancelledError) + with pytest.raises(type(error)): + await appender.flush() + 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())