diff --git a/changelog/added/steady-stream-heron.md b/changelog/added/steady-stream-heron.md new file mode 100644 index 0000000000..8a9a6cb1b4 --- /dev/null +++ b/changelog/added/steady-stream-heron.md @@ -0,0 +1 @@ +Add experimental Streams for clients, Activities, and Workflows, with configurable Stores, buffered appends, client interceptor hooks, and replay support. diff --git a/changelog/changed/juggling-jellyfish.md b/changelog/changed/juggling-jellyfish.md new file mode 100644 index 0000000000..c2f441cd97 --- /dev/null +++ b/changelog/changed/juggling-jellyfish.md @@ -0,0 +1 @@ +Route client and Activity Stream calls through operation-specific outbound interceptor hooks using typed Nexus input envelopes and operation handles, without invoking generic Nexus start or result hooks. Preserve request IDs and call options across interceptor retries. diff --git a/scripts/gen_nexus_system_api.py b/scripts/gen_nexus_system_api.py index 8c8dcf6b67..b89ac8de5d 100644 --- a/scripts/gen_nexus_system_api.py +++ b/scripts/gen_nexus_system_api.py @@ -26,7 +26,7 @@ notification_output_dir = base_dir / "temporalio" / "nexus" / "notifications" stream_output_dir = base_dir / "temporalio" / "nexus" / "system" / "stream_service" workflow_init_path = base_dir / "temporalio" / "workflow" / "__init__.py" -NEX_GEN_REVISION = "38c39883e78980a864b1b838aa8f6ff91561bb9f" +NEX_GEN_REVISION = "db48bf91ace1f2669022c26ca3d00f1ae6889056" proto_files = [ gen_protos.api_proto_dir / "temporal" 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 d0304f3887..0b34830004 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.2" @@ -376,6 +391,15 @@ version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "darling" version = "0.24.1" @@ -433,6 +457,17 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + [[package]] name = "dirs" version = "7.0.0" @@ -871,6 +906,15 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.13.0" @@ -2422,6 +2466,17 @@ dependencies = [ "serde", ] +[[package]] +name = "sha2" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "sharded-slab" version = "0.1.7" @@ -2626,6 +2681,7 @@ dependencies = [ "temporalio-client", "temporalio-common", "temporalio-sdk-core", + "temporalio-streams", "tokio", "tokio-rustls", "tokio-stream", @@ -2791,6 +2847,7 @@ dependencies = [ "reqwest", "serde", "serde_json", + "sha2", "siphasher", "slotmap", "sysinfo", @@ -2798,6 +2855,7 @@ dependencies = [ "temporalio-client", "temporalio-common", "temporalio-macros", + "temporalio-streams", "thiserror", "tokio", "tokio-stream", @@ -2809,6 +2867,17 @@ dependencies = [ "zip", ] +[[package]] +name = "temporalio-streams" +version = "0.1.0" +dependencies = [ + "enum-iterator", + "futures-util", + "prost", + "temporalio-common", + "thiserror", +] + [[package]] name = "termtree" version = "0.5.1" @@ -2918,6 +2987,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "futures-util", "libc", "pin-project-lite", "tokio", @@ -3186,6 +3256,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/Cargo.toml b/temporalio/bridge/Cargo.toml index 3d63f69cdf..1d6bad33c7 100644 --- a/temporalio/bridge/Cargo.toml +++ b/temporalio/bridge/Cargo.toml @@ -72,7 +72,10 @@ temporalio-sdk-core = { version = "0.12.0", path = "./sdk-core/crates/sdk-core", "ephemeral-server", "envconfig", "prometheus", + # Replay must retain the result groups of Stream create and describe Local Activities. + "disable_workflow_task_chunking", ] } +temporalio-streams = { version = "0.1.0", path = "./sdk-core/crates/streams" } tokio = "1.26" # Matches the sdk-core client crate's rustls stack; used to build the custom # server certificate verifier for TLSConfig.verification_server_name. diff --git a/temporalio/bridge/_visitor.py b/temporalio/bridge/_visitor.py index ead09a986f..ab059e9642 100644 --- a/temporalio/bridge/_visitor.py +++ b/temporalio/bridge/_visitor.py @@ -308,6 +308,32 @@ async def _visit_coresdk_workflow_activation_ResolveNexusOperation( if o.HasField("result"): await self._visit_coresdk_nexus_NexusOperationResult(fs, o.result) + async def _visit_coresdk_workflow_activation_ResolveStreamAppend( + self, fs: VisitorFunctions, o: Any + ): + if o.HasField("failed"): + await self._visit_temporal_api_failure_v1_Failure(fs, o.failed) + + async def _visit_temporal_api_stream_v1_StreamRecord( + self, fs: VisitorFunctions, o: Any + ): + 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_WorkflowActivationJob( self, fs: VisitorFunctions, o: Any ): @@ -353,6 +379,14 @@ async def _visit_coresdk_workflow_activation_WorkflowActivationJob( await self._visit_coresdk_workflow_activation_ResolveNexusOperation( fs, o.resolve_nexus_operation ) + elif o.HasField("resolve_stream_append"): + await self._visit_coresdk_workflow_activation_ResolveStreamAppend( + fs, o.resolve_stream_append + ) + elif o.HasField("resolve_stream_read"): + await self._visit_coresdk_workflow_activation_ResolveStreamRead( + fs, o.resolve_stream_read + ) async def _visit_coresdk_workflow_activation_WorkflowActivation( self, fs: VisitorFunctions, o: Any @@ -492,6 +526,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 +590,10 @@ async def _visit_coresdk_workflow_commands_WorkflowCommand( await self._visit_coresdk_workflow_commands_ScheduleNexusOperation( fs, o.schedule_nexus_operation ) + elif o.HasField("append_to_stream"): + await self._visit_coresdk_workflow_commands_AppendToStream( + fs, o.append_to_stream + ) async def _visit_coresdk_workflow_completion_Success( self, fs: VisitorFunctions, o: Any @@ -639,6 +682,54 @@ async def _visit_temporal_api_notificationservice_v1_OnCompleteResponse( ) -> None: pass + async def _visit_temporal_api_sdk_v1_CreateStreamRequest( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_sdk_v1_CreateStreamResponse( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_stream_v1_AppendRecord( + self, fs: VisitorFunctions, o: Any + ): + if o.HasField("body"): + await self._visit_temporal_api_common_v1_Payload(fs, o.body) + + async def _visit_temporal_api_sdk_v1_AppendRecordsRequest( + self, fs: VisitorFunctions, o: Any + ): + for v in o.records: + await self._visit_temporal_api_stream_v1_AppendRecord(fs, v) + + async def _visit_temporal_api_streamservice_v1_AppendRecordsResponse( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_sdk_v1_ReadRecordsRequest( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_streamservice_v1_ReadRecordsResponse( + self, fs: VisitorFunctions, o: Any + ): + for v in o.records: + await self._visit_temporal_api_stream_v1_StreamRecord(fs, v) + + async def _visit_temporal_api_sdk_v1_DescribeStreamRequest( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_streamservice_v1_DescribeStreamResponse( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + async def _visit_temporal_api_common_v1_Header(self, fs: VisitorFunctions, o: Any): for v in o.fields.values(): await self._visit_temporal_api_common_v1_Payload(fs, v) diff --git a/temporalio/bridge/proto/activity_result/activity_result_pb2.py b/temporalio/bridge/proto/activity_result/activity_result_pb2.py index c7ecc2a0ed..80eeadca2a 100644 --- a/temporalio/bridge/proto/activity_result/activity_result_pb2.py +++ b/temporalio/bridge/proto/activity_result/activity_result_pb2.py @@ -25,9 +25,12 @@ from temporalio.api.failure.v1 import ( message_pb2 as temporal_dot_api_dot_failure_dot_v1_dot_message__pb2, ) +from temporalio.bridge.proto.common import ( + common_pb2 as temporal_dot_sdk_dot_core_dot_common_dot_common__pb2, +) DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n7temporal/sdk/core/activity_result/activity_result.proto\x12\x17\x63oresdk.activity_result\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a$temporal/api/common/v1/message.proto\x1a(temporal/api/enums/v1/failed_cause.proto\x1a%temporal/api/failure/v1/message.proto"\x95\x02\n\x17\x41\x63tivityExecutionResult\x12\x35\n\tcompleted\x18\x01 \x01(\x0b\x32 .coresdk.activity_result.SuccessH\x00\x12\x32\n\x06\x66\x61iled\x18\x02 \x01(\x0b\x32 .coresdk.activity_result.FailureH\x00\x12:\n\tcancelled\x18\x03 \x01(\x0b\x32%.coresdk.activity_result.CancellationH\x00\x12I\n\x13will_complete_async\x18\x04 \x01(\x0b\x32*.coresdk.activity_result.WillCompleteAsyncH\x00\x42\x08\n\x06status"\xfc\x01\n\x12\x41\x63tivityResolution\x12\x35\n\tcompleted\x18\x01 \x01(\x0b\x32 .coresdk.activity_result.SuccessH\x00\x12\x32\n\x06\x66\x61iled\x18\x02 \x01(\x0b\x32 .coresdk.activity_result.FailureH\x00\x12:\n\tcancelled\x18\x03 \x01(\x0b\x32%.coresdk.activity_result.CancellationH\x00\x12\x35\n\x07\x62\x61\x63koff\x18\x04 \x01(\x0b\x32".coresdk.activity_result.DoBackoffH\x00\x42\x08\n\x06status":\n\x07Success\x12/\n\x06result\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"{\n\x07\x46\x61ilure\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12=\n\x05\x63\x61use\x18\x02 \x01(\x0e\x32..temporal.api.enums.v1.ActivityTaskFailedCause"A\n\x0c\x43\x61ncellation\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"\x13\n\x11WillCompleteAsync"\x8d\x01\n\tDoBackoff\x12\x0f\n\x07\x61ttempt\x18\x01 \x01(\r\x12\x33\n\x10\x62\x61\x63koff_duration\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration\x12:\n\x16original_schedule_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.TimestampB4\xea\x02\x31Temporalio::Internal::Bridge::Api::ActivityResultb\x06proto3' + b'\n7temporal/sdk/core/activity_result/activity_result.proto\x12\x17\x63oresdk.activity_result\x1a\x1egoogle/protobuf/duration.proto\x1a%temporal/sdk/core/common/common.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a$temporal/api/common/v1/message.proto\x1a(temporal/api/enums/v1/failed_cause.proto\x1a%temporal/api/failure/v1/message.proto"\x95\x02\n\x17\x41\x63tivityExecutionResult\x12\x35\n\tcompleted\x18\x01 \x01(\x0b\x32 .coresdk.activity_result.SuccessH\x00\x12\x32\n\x06\x66\x61iled\x18\x02 \x01(\x0b\x32 .coresdk.activity_result.FailureH\x00\x12:\n\tcancelled\x18\x03 \x01(\x0b\x32%.coresdk.activity_result.CancellationH\x00\x12I\n\x13will_complete_async\x18\x04 \x01(\x0b\x32*.coresdk.activity_result.WillCompleteAsyncH\x00\x42\x08\n\x06status"\xfc\x01\n\x12\x41\x63tivityResolution\x12\x35\n\tcompleted\x18\x01 \x01(\x0b\x32 .coresdk.activity_result.SuccessH\x00\x12\x32\n\x06\x66\x61iled\x18\x02 \x01(\x0b\x32 .coresdk.activity_result.FailureH\x00\x12:\n\tcancelled\x18\x03 \x01(\x0b\x32%.coresdk.activity_result.CancellationH\x00\x12\x35\n\x07\x62\x61\x63koff\x18\x04 \x01(\x0b\x32".coresdk.activity_result.DoBackoffH\x00\x42\x08\n\x06status":\n\x07Success\x12/\n\x06result\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"{\n\x07\x46\x61ilure\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12=\n\x05\x63\x61use\x18\x02 \x01(\x0e\x32..temporal.api.enums.v1.ActivityTaskFailedCause"A\n\x0c\x43\x61ncellation\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"\x13\n\x11WillCompleteAsync"\xd1\x01\n\tDoBackoff\x12\x0f\n\x07\x61ttempt\x18\x01 \x01(\r\x12\x33\n\x10\x62\x61\x63koff_duration\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration\x12:\n\x16original_schedule_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x42\n\x15local_activity_origin\x18\x04 \x01(\x0b\x32#.coresdk.common.LocalActivityOriginB4\xea\x02\x31Temporalio::Internal::Bridge::Api::ActivityResultb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -37,18 +40,18 @@ DESCRIPTOR._serialized_options = ( b"\352\0021Temporalio::Internal::Bridge::Api::ActivityResult" ) - _ACTIVITYEXECUTIONRESULT._serialized_start = 269 - _ACTIVITYEXECUTIONRESULT._serialized_end = 546 - _ACTIVITYRESOLUTION._serialized_start = 549 - _ACTIVITYRESOLUTION._serialized_end = 801 - _SUCCESS._serialized_start = 803 - _SUCCESS._serialized_end = 861 - _FAILURE._serialized_start = 863 - _FAILURE._serialized_end = 986 - _CANCELLATION._serialized_start = 988 - _CANCELLATION._serialized_end = 1053 - _WILLCOMPLETEASYNC._serialized_start = 1055 - _WILLCOMPLETEASYNC._serialized_end = 1074 - _DOBACKOFF._serialized_start = 1077 - _DOBACKOFF._serialized_end = 1218 + _ACTIVITYEXECUTIONRESULT._serialized_start = 308 + _ACTIVITYEXECUTIONRESULT._serialized_end = 585 + _ACTIVITYRESOLUTION._serialized_start = 588 + _ACTIVITYRESOLUTION._serialized_end = 840 + _SUCCESS._serialized_start = 842 + _SUCCESS._serialized_end = 900 + _FAILURE._serialized_start = 902 + _FAILURE._serialized_end = 1025 + _CANCELLATION._serialized_start = 1027 + _CANCELLATION._serialized_end = 1092 + _WILLCOMPLETEASYNC._serialized_start = 1094 + _WILLCOMPLETEASYNC._serialized_end = 1113 + _DOBACKOFF._serialized_start = 1116 + _DOBACKOFF._serialized_end = 1325 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/activity_result/activity_result_pb2.pyi b/temporalio/bridge/proto/activity_result/activity_result_pb2.pyi index 35647cbd3f..ea5b7e539d 100644 --- a/temporalio/bridge/proto/activity_result/activity_result_pb2.pyi +++ b/temporalio/bridge/proto/activity_result/activity_result_pb2.pyi @@ -14,6 +14,7 @@ import google.protobuf.timestamp_pb2 import temporalio.api.common.v1.message_pb2 import temporalio.api.enums.v1.failed_cause_pb2 import temporalio.api.failure.v1.message_pb2 +import temporalio.bridge.proto.common.common_pb2 DESCRIPTOR: google.protobuf.descriptor.FileDescriptor @@ -253,6 +254,7 @@ class DoBackoff(google.protobuf.message.Message): ATTEMPT_FIELD_NUMBER: builtins.int BACKOFF_DURATION_FIELD_NUMBER: builtins.int ORIGINAL_SCHEDULE_TIME_FIELD_NUMBER: builtins.int + LOCAL_ACTIVITY_ORIGIN_FIELD_NUMBER: builtins.int attempt: builtins.int """The attempt number that lang should provide when scheduling the retry. If the LA failed on attempt 4 and we told lang to back off with a timer, this number will be 5. @@ -265,18 +267,28 @@ class DoBackoff(google.protobuf.message.Message): to the retry LA. """ + @property + def local_activity_origin( + self, + ) -> temporalio.bridge.proto.common.common_pb2.LocalActivityOrigin: + """Pass this origin to the retry so the timer cannot change its Producer identity.""" + def __init__( self, *, attempt: builtins.int = ..., backoff_duration: google.protobuf.duration_pb2.Duration | None = ..., original_schedule_time: google.protobuf.timestamp_pb2.Timestamp | None = ..., + local_activity_origin: temporalio.bridge.proto.common.common_pb2.LocalActivityOrigin + | None = ..., ) -> None: ... def HasField( self, field_name: typing.Literal[ "backoff_duration", b"backoff_duration", + "local_activity_origin", + b"local_activity_origin", "original_schedule_time", b"original_schedule_time", ], @@ -288,6 +300,8 @@ class DoBackoff(google.protobuf.message.Message): b"attempt", "backoff_duration", b"backoff_duration", + "local_activity_origin", + b"local_activity_origin", "original_schedule_time", b"original_schedule_time", ], diff --git a/temporalio/bridge/proto/activity_task/activity_task_pb2.py b/temporalio/bridge/proto/activity_task/activity_task_pb2.py index 25233f5241..a00de328e0 100644 --- a/temporalio/bridge/proto/activity_task/activity_task_pb2.py +++ b/temporalio/bridge/proto/activity_task/activity_task_pb2.py @@ -27,7 +27,7 @@ ) DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n3temporal/sdk/core/activity_task/activity_task.proto\x12\x15\x63oresdk.activity_task\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a$temporal/api/common/v1/message.proto\x1a#temporal/api/nexus/v1/message.proto\x1a%temporal/sdk/core/common/common.proto"\x8d\x01\n\x0c\x41\x63tivityTask\x12\x12\n\ntask_token\x18\x01 \x01(\x0c\x12-\n\x05start\x18\x03 \x01(\x0b\x32\x1c.coresdk.activity_task.StartH\x00\x12/\n\x06\x63\x61ncel\x18\x04 \x01(\x0b\x32\x1d.coresdk.activity_task.CancelH\x00\x42\t\n\x07variant"\xdb\x08\n\x05Start\x12\x1a\n\x12workflow_namespace\x18\x01 \x01(\t\x12\x15\n\rworkflow_type\x18\x02 \x01(\t\x12\x45\n\x12workflow_execution\x18\x03 \x01(\x0b\x32).temporal.api.common.v1.WorkflowExecution\x12\x13\n\x0b\x61\x63tivity_id\x18\x04 \x01(\t\x12\x15\n\ractivity_type\x18\x05 \x01(\t\x12\x45\n\rheader_fields\x18\x06 \x03(\x0b\x32..coresdk.activity_task.Start.HeaderFieldsEntry\x12.\n\x05input\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12:\n\x11heartbeat_details\x18\x08 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x32\n\x0escheduled_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x42\n\x1e\x63urrent_attempt_scheduled_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x30\n\x0cstarted_time\x18\x0b \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07\x61ttempt\x18\x0c \x01(\r\x12<\n\x19schedule_to_close_timeout\x18\r \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\x0e \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x34\n\x11heartbeat_timeout\x18\x0f \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x10 \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x32\n\x08priority\x18\x12 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12\x10\n\x08is_local\x18\x11 \x01(\x08\x12\x0e\n\x06run_id\x18\x13 \x01(\t\x12\x65\n&propagated_nexus_serialization_context\x18\x14 \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x12\x41\n\rworkflow_task\x18\x15 \x01(\x0b\x32*.coresdk.activity_task.WorkflowTaskAttempt\x1aT\n\x11HeaderFieldsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x80\x02\n\x13WorkflowTaskAttempt\x12\x18\n\x10started_event_id\x18\x01 \x01(\x03\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\r\x12\x30\n\x0cstarted_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12!\n\x19previous_started_event_id\x18\x04 \x01(\x03\x12\x14\n\x0c\x66\x61iled_tasks\x18\x05 \x03(\x03\x12\x18\n\x10previous_attempt\x18\x06 \x01(\r\x12\x39\n\x15previous_started_time\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"\x8a\x01\n\x06\x43\x61ncel\x12;\n\x06reason\x18\x01 \x01(\x0e\x32+.coresdk.activity_task.ActivityCancelReason\x12\x43\n\x07\x64\x65tails\x18\x02 \x01(\x0b\x32\x32.coresdk.activity_task.ActivityCancellationDetails"\xa0\x01\n\x1b\x41\x63tivityCancellationDetails\x12\x14\n\x0cis_not_found\x18\x01 \x01(\x08\x12\x14\n\x0cis_cancelled\x18\x02 \x01(\x08\x12\x11\n\tis_paused\x18\x03 \x01(\x08\x12\x14\n\x0cis_timed_out\x18\x04 \x01(\x08\x12\x1a\n\x12is_worker_shutdown\x18\x05 \x01(\x08\x12\x10\n\x08is_reset\x18\x06 \x01(\x08*o\n\x14\x41\x63tivityCancelReason\x12\r\n\tNOT_FOUND\x10\x00\x12\r\n\tCANCELLED\x10\x01\x12\r\n\tTIMED_OUT\x10\x02\x12\x13\n\x0fWORKER_SHUTDOWN\x10\x03\x12\n\n\x06PAUSED\x10\x04\x12\t\n\x05RESET\x10\x05\x42\x32\xea\x02/Temporalio::Internal::Bridge::Api::ActivityTaskb\x06proto3' + b'\n3temporal/sdk/core/activity_task/activity_task.proto\x12\x15\x63oresdk.activity_task\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a$temporal/api/common/v1/message.proto\x1a#temporal/api/nexus/v1/message.proto\x1a%temporal/sdk/core/common/common.proto"\x8d\x01\n\x0c\x41\x63tivityTask\x12\x12\n\ntask_token\x18\x01 \x01(\x0c\x12-\n\x05start\x18\x03 \x01(\x0b\x32\x1c.coresdk.activity_task.StartH\x00\x12/\n\x06\x63\x61ncel\x18\x04 \x01(\x0b\x32\x1d.coresdk.activity_task.CancelH\x00\x42\t\n\x07variant"\xbb\t\n\x05Start\x12\x1a\n\x12workflow_namespace\x18\x01 \x01(\t\x12\x15\n\rworkflow_type\x18\x02 \x01(\t\x12\x45\n\x12workflow_execution\x18\x03 \x01(\x0b\x32).temporal.api.common.v1.WorkflowExecution\x12\x13\n\x0b\x61\x63tivity_id\x18\x04 \x01(\t\x12\x15\n\ractivity_type\x18\x05 \x01(\t\x12\x45\n\rheader_fields\x18\x06 \x03(\x0b\x32..coresdk.activity_task.Start.HeaderFieldsEntry\x12.\n\x05input\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12:\n\x11heartbeat_details\x18\x08 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x32\n\x0escheduled_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x42\n\x1e\x63urrent_attempt_scheduled_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x30\n\x0cstarted_time\x18\x0b \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07\x61ttempt\x18\x0c \x01(\r\x12<\n\x19schedule_to_close_timeout\x18\r \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\x0e \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x34\n\x11heartbeat_timeout\x18\x0f \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x10 \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x32\n\x08priority\x18\x12 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12\x10\n\x08is_local\x18\x11 \x01(\x08\x12\x0e\n\x06run_id\x18\x13 \x01(\t\x12\x65\n&propagated_nexus_serialization_context\x18\x14 \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x12\x41\n\rworkflow_task\x18\x15 \x01(\x0b\x32*.coresdk.activity_task.WorkflowTaskAttempt\x12\x1a\n\x12scheduled_event_id\x18\x16 \x01(\x03\x12\x42\n\x15local_activity_origin\x18\x17 \x01(\x0b\x32#.coresdk.common.LocalActivityOrigin\x1aT\n\x11HeaderFieldsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x80\x02\n\x13WorkflowTaskAttempt\x12\x18\n\x10started_event_id\x18\x01 \x01(\x03\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\r\x12\x30\n\x0cstarted_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12!\n\x19previous_started_event_id\x18\x04 \x01(\x03\x12\x14\n\x0c\x66\x61iled_tasks\x18\x05 \x03(\x03\x12\x18\n\x10previous_attempt\x18\x06 \x01(\r\x12\x39\n\x15previous_started_time\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"\x8a\x01\n\x06\x43\x61ncel\x12;\n\x06reason\x18\x01 \x01(\x0e\x32+.coresdk.activity_task.ActivityCancelReason\x12\x43\n\x07\x64\x65tails\x18\x02 \x01(\x0b\x32\x32.coresdk.activity_task.ActivityCancellationDetails"\xa0\x01\n\x1b\x41\x63tivityCancellationDetails\x12\x14\n\x0cis_not_found\x18\x01 \x01(\x08\x12\x14\n\x0cis_cancelled\x18\x02 \x01(\x08\x12\x11\n\tis_paused\x18\x03 \x01(\x08\x12\x14\n\x0cis_timed_out\x18\x04 \x01(\x08\x12\x1a\n\x12is_worker_shutdown\x18\x05 \x01(\x08\x12\x10\n\x08is_reset\x18\x06 \x01(\x08*o\n\x14\x41\x63tivityCancelReason\x12\r\n\tNOT_FOUND\x10\x00\x12\r\n\tCANCELLED\x10\x01\x12\r\n\tTIMED_OUT\x10\x02\x12\x13\n\x0fWORKER_SHUTDOWN\x10\x03\x12\n\n\x06PAUSED\x10\x04\x12\t\n\x05RESET\x10\x05\x42\x32\xea\x02/Temporalio::Internal::Bridge::Api::ActivityTaskb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -39,18 +39,18 @@ ) _START_HEADERFIELDSENTRY._options = None _START_HEADERFIELDSENTRY._serialized_options = b"8\001" - _ACTIVITYCANCELREASON._serialized_start = 2082 - _ACTIVITYCANCELREASON._serialized_end = 2193 + _ACTIVITYCANCELREASON._serialized_start = 2178 + _ACTIVITYCANCELREASON._serialized_end = 2289 _ACTIVITYTASK._serialized_start = 258 _ACTIVITYTASK._serialized_end = 399 _START._serialized_start = 402 - _START._serialized_end = 1517 - _START_HEADERFIELDSENTRY._serialized_start = 1433 - _START_HEADERFIELDSENTRY._serialized_end = 1517 - _WORKFLOWTASKATTEMPT._serialized_start = 1520 - _WORKFLOWTASKATTEMPT._serialized_end = 1776 - _CANCEL._serialized_start = 1779 - _CANCEL._serialized_end = 1917 - _ACTIVITYCANCELLATIONDETAILS._serialized_start = 1920 - _ACTIVITYCANCELLATIONDETAILS._serialized_end = 2080 + _START._serialized_end = 1613 + _START_HEADERFIELDSENTRY._serialized_start = 1529 + _START_HEADERFIELDSENTRY._serialized_end = 1613 + _WORKFLOWTASKATTEMPT._serialized_start = 1616 + _WORKFLOWTASKATTEMPT._serialized_end = 1872 + _CANCEL._serialized_start = 1875 + _CANCEL._serialized_end = 2013 + _ACTIVITYCANCELLATIONDETAILS._serialized_start = 2016 + _ACTIVITYCANCELLATIONDETAILS._serialized_end = 2176 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/activity_task/activity_task_pb2.pyi b/temporalio/bridge/proto/activity_task/activity_task_pb2.pyi index 345b0a6b1e..5820ec579b 100644 --- a/temporalio/bridge/proto/activity_task/activity_task_pb2.pyi +++ b/temporalio/bridge/proto/activity_task/activity_task_pb2.pyi @@ -19,6 +19,7 @@ import google.protobuf.timestamp_pb2 import temporalio.api.common.v1.message_pb2 import temporalio.api.nexus.v1.message_pb2 +import temporalio.bridge.proto.common.common_pb2 if sys.version_info >= (3, 10): import typing as typing_extensions @@ -167,6 +168,8 @@ class Start(google.protobuf.message.Message): RUN_ID_FIELD_NUMBER: builtins.int PROPAGATED_NEXUS_SERIALIZATION_CONTEXT_FIELD_NUMBER: builtins.int WORKFLOW_TASK_FIELD_NUMBER: builtins.int + SCHEDULED_EVENT_ID_FIELD_NUMBER: builtins.int + LOCAL_ACTIVITY_ORIGIN_FIELD_NUMBER: builtins.int workflow_namespace: builtins.str """The namespace the workflow lives in""" workflow_type: builtins.str @@ -182,6 +185,10 @@ class Start(google.protobuf.message.Message): """ run_id: builtins.str """Run ID of this activity execution. Only set for standalone activities.""" + scheduled_event_id: builtins.int + """For an activity that a workflow scheduled, the event id of its ActivityTaskScheduled event. + 0 for a local activity, for a standalone activity, and when Core can't read it. + """ @property def workflow_execution( self, @@ -260,6 +267,12 @@ class Start(google.protobuf.message.Message): Core runs locally keep the value. Unset for other activities. """ + @property + def local_activity_origin( + self, + ) -> temporalio.bridge.proto.common.common_pb2.LocalActivityOrigin: + """Local Activity Stream writes keep their scheduling identity across retries.""" + def __init__( self, *, @@ -294,6 +307,9 @@ class Start(google.protobuf.message.Message): propagated_nexus_serialization_context: temporalio.api.nexus.v1.message_pb2.PropagatedSerializationContext | None = ..., workflow_task: global___WorkflowTaskAttempt | None = ..., + scheduled_event_id: builtins.int = ..., + local_activity_origin: temporalio.bridge.proto.common.common_pb2.LocalActivityOrigin + | None = ..., ) -> None: ... def HasField( self, @@ -302,6 +318,8 @@ class Start(google.protobuf.message.Message): b"current_attempt_scheduled_time", "heartbeat_timeout", b"heartbeat_timeout", + "local_activity_origin", + b"local_activity_origin", "priority", b"priority", "propagated_nexus_serialization_context", @@ -343,6 +361,8 @@ class Start(google.protobuf.message.Message): b"input", "is_local", b"is_local", + "local_activity_origin", + b"local_activity_origin", "priority", b"priority", "propagated_nexus_serialization_context", @@ -353,6 +373,8 @@ class Start(google.protobuf.message.Message): b"run_id", "schedule_to_close_timeout", b"schedule_to_close_timeout", + "scheduled_event_id", + b"scheduled_event_id", "scheduled_time", b"scheduled_time", "start_to_close_timeout", diff --git a/temporalio/bridge/proto/common/__init__.py b/temporalio/bridge/proto/common/__init__.py index a8506090de..c7fdd2e4b8 100644 --- a/temporalio/bridge/proto/common/__init__.py +++ b/temporalio/bridge/proto/common/__init__.py @@ -1,5 +1,6 @@ from .common_pb2 import ( ExternalStorageMetrics, + LocalActivityOrigin, NamespacedWorkflowExecution, VersioningIntent, WorkerDeploymentVersion, @@ -7,6 +8,7 @@ __all__ = [ "ExternalStorageMetrics", + "LocalActivityOrigin", "NamespacedWorkflowExecution", "VersioningIntent", "WorkerDeploymentVersion", diff --git a/temporalio/bridge/proto/common/common_pb2.py b/temporalio/bridge/proto/common/common_pb2.py index 0b9a5c8169..98d53ad2e9 100644 --- a/temporalio/bridge/proto/common/common_pb2.py +++ b/temporalio/bridge/proto/common/common_pb2.py @@ -16,7 +16,7 @@ from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n%temporal/sdk/core/common/common.proto\x12\x0e\x63oresdk.common\x1a\x1egoogle/protobuf/duration.proto"U\n\x1bNamespacedWorkflowExecution\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x02 \x01(\t\x12\x0e\n\x06run_id\x18\x03 \x01(\t"D\n\x17WorkerDeploymentVersion\x12\x17\n\x0f\x64\x65ployment_name\x18\x01 \x01(\t\x12\x10\n\x08\x62uild_id\x18\x02 \x01(\t"\x92\x01\n\x16\x45xternalStorageMetrics\x12\x15\n\rpayload_count\x18\x01 \x01(\x04\x12\x18\n\x10total_size_bytes\x18\x02 \x01(\x04\x12\x31\n\x0etotal_duration\x18\x03 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x14\n\x0c\x64river_names\x18\x04 \x03(\t*@\n\x10VersioningIntent\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nCOMPATIBLE\x10\x01\x12\x0b\n\x07\x44\x45\x46\x41ULT\x10\x02\x42,\xea\x02)Temporalio::Internal::Bridge::Api::Commonb\x06proto3' + b'\n%temporal/sdk/core/common/common.proto\x12\x0e\x63oresdk.common\x1a\x1egoogle/protobuf/duration.proto"D\n\x13LocalActivityOrigin\x12\x18\n\x10workflow_task_id\x18\x01 \x01(\x03\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t"U\n\x1bNamespacedWorkflowExecution\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x02 \x01(\t\x12\x0e\n\x06run_id\x18\x03 \x01(\t"D\n\x17WorkerDeploymentVersion\x12\x17\n\x0f\x64\x65ployment_name\x18\x01 \x01(\t\x12\x10\n\x08\x62uild_id\x18\x02 \x01(\t"\x92\x01\n\x16\x45xternalStorageMetrics\x12\x15\n\rpayload_count\x18\x01 \x01(\x04\x12\x18\n\x10total_size_bytes\x18\x02 \x01(\x04\x12\x31\n\x0etotal_duration\x18\x03 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x14\n\x0c\x64river_names\x18\x04 \x03(\t*@\n\x10VersioningIntent\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nCOMPATIBLE\x10\x01\x12\x0b\n\x07\x44\x45\x46\x41ULT\x10\x02\x42,\xea\x02)Temporalio::Internal::Bridge::Api::Commonb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -26,12 +26,14 @@ DESCRIPTOR._serialized_options = ( b"\352\002)Temporalio::Internal::Bridge::Api::Common" ) - _VERSIONINGINTENT._serialized_start = 395 - _VERSIONINGINTENT._serialized_end = 459 - _NAMESPACEDWORKFLOWEXECUTION._serialized_start = 89 - _NAMESPACEDWORKFLOWEXECUTION._serialized_end = 174 - _WORKERDEPLOYMENTVERSION._serialized_start = 176 - _WORKERDEPLOYMENTVERSION._serialized_end = 244 - _EXTERNALSTORAGEMETRICS._serialized_start = 247 - _EXTERNALSTORAGEMETRICS._serialized_end = 393 + _VERSIONINGINTENT._serialized_start = 465 + _VERSIONINGINTENT._serialized_end = 529 + _LOCALACTIVITYORIGIN._serialized_start = 89 + _LOCALACTIVITYORIGIN._serialized_end = 157 + _NAMESPACEDWORKFLOWEXECUTION._serialized_start = 159 + _NAMESPACEDWORKFLOWEXECUTION._serialized_end = 244 + _WORKERDEPLOYMENTVERSION._serialized_start = 246 + _WORKERDEPLOYMENTVERSION._serialized_end = 314 + _EXTERNALSTORAGEMETRICS._serialized_start = 317 + _EXTERNALSTORAGEMETRICS._serialized_end = 463 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/common/common_pb2.pyi b/temporalio/bridge/proto/common/common_pb2.pyi index 7c2b057024..25ae4de103 100644 --- a/temporalio/bridge/proto/common/common_pb2.pyi +++ b/temporalio/bridge/proto/common/common_pb2.pyi @@ -68,6 +68,31 @@ build ID. """ global___VersioningIntent = VersioningIntent +@typing.final +class LocalActivityOrigin(google.protobuf.message.Message): + """Timer-backed retries keep the original Producer identity even when the execution id changes.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + WORKFLOW_TASK_ID_FIELD_NUMBER: builtins.int + ACTIVITY_ID_FIELD_NUMBER: builtins.int + workflow_task_id: builtins.int + activity_id: builtins.str + def __init__( + self, + *, + workflow_task_id: builtins.int = ..., + activity_id: builtins.str = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "activity_id", b"activity_id", "workflow_task_id", b"workflow_task_id" + ], + ) -> None: ... + +global___LocalActivityOrigin = LocalActivityOrigin + @typing.final class NamespacedWorkflowExecution(google.protobuf.message.Message): """Identifying information about a particular workflow execution, including namespace""" diff --git a/temporalio/bridge/proto/external_data/__init__.py b/temporalio/bridge/proto/external_data/__init__.py index 836e97ef43..c6b5cff265 100644 --- a/temporalio/bridge/proto/external_data/__init__.py +++ b/temporalio/bridge/proto/external_data/__init__.py @@ -1,6 +1,27 @@ -from .external_data_pb2 import LocalActivityMarkerData, PatchedMarkerData +from .external_data_pb2 import ( + LocalActivityMarkerData, + PatchedMarkerData, + PendingLocalActivityOrigins, + StreamAppendMarkerData, + StreamAppendOffsets, + StreamAppendOrigin, + StreamAppendResult, + StreamFailure, + StreamReadMarkerData, + StreamReadPage, + StreamReadResult, +) __all__ = [ "LocalActivityMarkerData", "PatchedMarkerData", + "PendingLocalActivityOrigins", + "StreamAppendMarkerData", + "StreamAppendOffsets", + "StreamAppendOrigin", + "StreamAppendResult", + "StreamFailure", + "StreamReadMarkerData", + "StreamReadPage", + "StreamReadResult", ] diff --git a/temporalio/bridge/proto/external_data/external_data_pb2.py b/temporalio/bridge/proto/external_data/external_data_pb2.py index 4bda6f5144..708921dd8d 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.py +++ b/temporalio/bridge/proto/external_data/external_data_pb2.py @@ -16,8 +16,12 @@ from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 +from temporalio.bridge.proto.common import ( + common_pb2 as temporal_dot_sdk_dot_core_dot_common_dot_common__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%temporal/sdk/core/common/common.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xf6\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\x12\x42\n\x15local_activity_origin\x18\t \x01(\x0b\x32#.coresdk.common.LocalActivityOriginB\x13\n\x11_activation_index"E\n\x1bPendingLocalActivityOrigins\x12\x18\n\x10workflow_task_id\x18\x01 \x01(\x03\x12\x0c\n\x04seqs\x18\x02 \x03(\r"3\n\x11PatchedMarkerData\x12\n\n\x02id\x18\x01 \x01(\t\x12\x12\n\ndeprecated\x18\x02 \x01(\x08"\x97\x01\n\x16StreamAppendMarkerData\x12:\n\x07\x61ppends\x18\x01 \x03(\x0b\x32).coresdk.external_data.StreamAppendResult\x12\x41\n\x0epending_origin\x18\x02 \x01(\x0b\x32).coresdk.external_data.StreamAppendOrigin"\xb0\x01\n\x12StreamAppendOrigin\x12\x11\n\tfirst_seq\x18\x01 \x01(\r\x12\x10\n\x08last_seq\x18\x02 \x01(\r\x12\x18\n\x10workflow_task_id\x18\x03 \x01(\x03\x12\x18\n\x10started_event_id\x18\x04 \x01(\x03\x12\x0f\n\x07\x61ttempt\x18\x05 \x01(\x05\x12\x30\n\x0cstarted_time\x18\x06 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"\xe0\x01\n\x12StreamAppendResult\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x11\n\tstream_id\x18\x02 \x01(\t\x12\r\n\x05store\x18\x03 \x01(\t\x12\x18\n\x10\x61\x63tivation_index\x18\x04 \x01(\x04\x12>\n\x08\x61ppended\x18\x05 \x01(\x0b\x32*.coresdk.external_data.StreamAppendOffsetsH\x00\x12\x37\n\x07\x66\x61ilure\x18\x06 \x01(\x0b\x32$.coresdk.external_data.StreamFailureH\x00\x42\x08\n\x06result"@\n\x13StreamAppendOffsets\x12\x14\n\x0c\x66irst_offset\x18\x01 \x01(\x0c\x12\x13\n\x0blast_offset\x18\x02 \x01(\x0c"0\n\rStreamFailure\x12\x0e\n\x06reason\x18\x01 \x01(\t\x12\x0f\n\x07message\x18\x02 \x01(\t"N\n\x14StreamReadMarkerData\x12\x36\n\x05reads\x18\x01 \x03(\x0b\x32\'.coresdk.external_data.StreamReadResult"\xeb\x01\n\x10StreamReadResult\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x11\n\tstream_id\x18\x02 \x01(\t\x12\r\n\x05store\x18\x03 \x01(\t\x12\x18\n\x10\x61\x63tivation_index\x18\x04 \x01(\x04\x12\x14\n\x0c\x61\x66ter_offset\x18\x05 \x01(\x0c\x12\x35\n\x04page\x18\x06 \x01(\x0b\x32%.coresdk.external_data.StreamReadPageH\x00\x12\x37\n\x07\x66\x61ilure\x18\x07 \x01(\x0b\x32$.coresdk.external_data.StreamFailureH\x00\x42\x08\n\x06result"^\n\x0eStreamReadPage\x12\x14\n\x0crecord_count\x18\x01 \x01(\r\x12\x0e\n\x06\x64igest\x18\x02 \x01(\x0c\x12\x14\n\x0crecord_bytes\x18\x03 \x01(\x04\x12\x10\n\x08wait_cut\x18\x05 \x01(\x08\x42\x32\xea\x02/Temporalio::Internal::Bridge::Api::ExternalDatab\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -27,8 +31,26 @@ 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 = 183 + _LOCALACTIVITYMARKERDATA._serialized_end = 557 + _PENDINGLOCALACTIVITYORIGINS._serialized_start = 559 + _PENDINGLOCALACTIVITYORIGINS._serialized_end = 628 + _PATCHEDMARKERDATA._serialized_start = 630 + _PATCHEDMARKERDATA._serialized_end = 681 + _STREAMAPPENDMARKERDATA._serialized_start = 684 + _STREAMAPPENDMARKERDATA._serialized_end = 835 + _STREAMAPPENDORIGIN._serialized_start = 838 + _STREAMAPPENDORIGIN._serialized_end = 1014 + _STREAMAPPENDRESULT._serialized_start = 1017 + _STREAMAPPENDRESULT._serialized_end = 1241 + _STREAMAPPENDOFFSETS._serialized_start = 1243 + _STREAMAPPENDOFFSETS._serialized_end = 1307 + _STREAMFAILURE._serialized_start = 1309 + _STREAMFAILURE._serialized_end = 1357 + _STREAMREADMARKERDATA._serialized_start = 1359 + _STREAMREADMARKERDATA._serialized_end = 1437 + _STREAMREADRESULT._serialized_start = 1440 + _STREAMREADRESULT._serialized_end = 1675 + _STREAMREADPAGE._serialized_start = 1677 + _STREAMREADPAGE._serialized_end = 1771 # @@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..379f83f126 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.pyi +++ b/temporalio/bridge/proto/external_data/external_data_pb2.pyi @@ -4,13 +4,17 @@ isort:skip_file """ import builtins +import collections.abc import typing import google.protobuf.descriptor import google.protobuf.duration_pb2 +import google.protobuf.internal.containers import google.protobuf.message import google.protobuf.timestamp_pb2 +import temporalio.bridge.proto.common.common_pb2 + DESCRIPTOR: google.protobuf.descriptor.FileDescriptor @typing.final @@ -30,6 +34,7 @@ class LocalActivityMarkerData(google.protobuf.message.Message): BACKOFF_FIELD_NUMBER: builtins.int ORIGINAL_SCHEDULE_TIME_FIELD_NUMBER: builtins.int ACTIVATION_INDEX_FIELD_NUMBER: builtins.int + LOCAL_ACTIVITY_ORIGIN_FIELD_NUMBER: builtins.int seq: builtins.int attempt: builtins.int """The number of attempts at execution before we recorded this result. Typically starts at 1, @@ -62,6 +67,12 @@ class LocalActivityMarkerData(google.protobuf.message.Message): schedule-to-close timeouts when timer-based backoffs are used """ + @property + def local_activity_origin( + self, + ) -> temporalio.bridge.proto.common.common_pb2.LocalActivityOrigin: + """Replay of a backoff must give the retry its original scheduling identity.""" + def __init__( self, *, @@ -73,6 +84,8 @@ class LocalActivityMarkerData(google.protobuf.message.Message): backoff: google.protobuf.duration_pb2.Duration | None = ..., original_schedule_time: google.protobuf.timestamp_pb2.Timestamp | None = ..., activation_index: builtins.int | None = ..., + local_activity_origin: temporalio.bridge.proto.common.common_pb2.LocalActivityOrigin + | None = ..., ) -> None: ... def HasField( self, @@ -85,6 +98,8 @@ class LocalActivityMarkerData(google.protobuf.message.Message): b"backoff", "complete_time", b"complete_time", + "local_activity_origin", + b"local_activity_origin", "original_schedule_time", b"original_schedule_time", ], @@ -106,6 +121,8 @@ class LocalActivityMarkerData(google.protobuf.message.Message): b"backoff", "complete_time", b"complete_time", + "local_activity_origin", + b"local_activity_origin", "original_schedule_time", b"original_schedule_time", "seq", @@ -118,6 +135,36 @@ class LocalActivityMarkerData(google.protobuf.message.Message): global___LocalActivityMarkerData = LocalActivityMarkerData +@typing.final +class PendingLocalActivityOrigins(google.protobuf.message.Message): + """A worker can lose outstanding Local Activities after the scheduling Workflow Task completes.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + WORKFLOW_TASK_ID_FIELD_NUMBER: builtins.int + SEQS_FIELD_NUMBER: builtins.int + workflow_task_id: builtins.int + @property + def seqs( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[ + builtins.int + ]: ... + def __init__( + self, + *, + workflow_task_id: builtins.int = ..., + seqs: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "seqs", b"seqs", "workflow_task_id", b"workflow_task_id" + ], + ) -> None: ... + +global___PendingLocalActivityOrigins = PendingLocalActivityOrigins + @typing.final class PatchedMarkerData(google.protobuf.message.Message): DESCRIPTOR: google.protobuf.descriptor.Descriptor @@ -139,3 +186,345 @@ class PatchedMarkerData(google.protobuf.message.Message): ) -> None: ... global___PatchedMarkerData = PatchedMarkerData + +@typing.final +class StreamAppendMarkerData(google.protobuf.message.Message): + """The data of a `core_stream_append` marker, as JSON with `bytes` fields in lower-case hex. An + empty marker keeps a task with an open append apart from the next task when chunking is on. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + APPENDS_FIELD_NUMBER: builtins.int + PENDING_ORIGIN_FIELD_NUMBER: builtins.int + @property + def appends( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___StreamAppendResult + ]: ... + @property + def pending_origin(self) -> global___StreamAppendOrigin: + """Replay must resend outstanding writes with the original Producer, attempt and request id.""" + + def __init__( + self, + *, + appends: collections.abc.Iterable[global___StreamAppendResult] | None = ..., + pending_origin: global___StreamAppendOrigin | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["pending_origin", b"pending_origin"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "appends", b"appends", "pending_origin", b"pending_origin" + ], + ) -> None: ... + +global___StreamAppendMarkerData = StreamAppendMarkerData + +@typing.final +class StreamAppendOrigin(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FIRST_SEQ_FIELD_NUMBER: builtins.int + LAST_SEQ_FIELD_NUMBER: builtins.int + WORKFLOW_TASK_ID_FIELD_NUMBER: builtins.int + STARTED_EVENT_ID_FIELD_NUMBER: builtins.int + ATTEMPT_FIELD_NUMBER: builtins.int + STARTED_TIME_FIELD_NUMBER: builtins.int + first_seq: builtins.int + last_seq: builtins.int + workflow_task_id: builtins.int + started_event_id: builtins.int + attempt: builtins.int + @property + def started_time(self) -> google.protobuf.timestamp_pb2.Timestamp: ... + def __init__( + self, + *, + first_seq: builtins.int = ..., + last_seq: builtins.int = ..., + workflow_task_id: builtins.int = ..., + started_event_id: builtins.int = ..., + attempt: builtins.int = ..., + started_time: google.protobuf.timestamp_pb2.Timestamp | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["started_time", b"started_time"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "attempt", + b"attempt", + "first_seq", + b"first_seq", + "last_seq", + b"last_seq", + "started_event_id", + b"started_event_id", + "started_time", + b"started_time", + "workflow_task_id", + b"workflow_task_id", + ], + ) -> None: ... + +global___StreamAppendOrigin = StreamAppendOrigin + +@typing.final +class StreamAppendResult(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + STREAM_ID_FIELD_NUMBER: builtins.int + STORE_FIELD_NUMBER: builtins.int + ACTIVATION_INDEX_FIELD_NUMBER: builtins.int + APPENDED_FIELD_NUMBER: builtins.int + FAILURE_FIELD_NUMBER: builtins.int + seq: builtins.int + stream_id: builtins.str + store: builtins.str + """The name of the Store that the append used. For a ref with no Store name, it is the empty + name if the Worker has a Stream runtime under it, else the name of its only runtime. + """ + activation_index: builtins.int + """The index of the activation, within its Workflow Task, in which Workflow code got the result.""" + @property + def appended(self) -> global___StreamAppendOffsets: ... + @property + def failure(self) -> global___StreamFailure: ... + def __init__( + self, + *, + seq: builtins.int = ..., + stream_id: builtins.str = ..., + store: builtins.str = ..., + activation_index: builtins.int = ..., + appended: global___StreamAppendOffsets | None = ..., + failure: global___StreamFailure | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "appended", b"appended", "failure", b"failure", "result", b"result" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "activation_index", + b"activation_index", + "appended", + b"appended", + "failure", + b"failure", + "result", + b"result", + "seq", + b"seq", + "store", + b"store", + "stream_id", + b"stream_id", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["result", b"result"] + ) -> typing.Literal["appended", "failure"] | None: ... + +global___StreamAppendResult = StreamAppendResult + +@typing.final +class StreamAppendOffsets(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FIRST_OFFSET_FIELD_NUMBER: builtins.int + LAST_OFFSET_FIELD_NUMBER: builtins.int + first_offset: builtins.bytes + last_offset: builtins.bytes + def __init__( + self, + *, + first_offset: builtins.bytes = ..., + last_offset: builtins.bytes = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "first_offset", b"first_offset", "last_offset", b"last_offset" + ], + ) -> None: ... + +global___StreamAppendOffsets = StreamAppendOffsets + +@typing.final +class StreamFailure(google.protobuf.message.Message): + """Why a Stream call failed. Core builds the failure that Workflow code gets from these two.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REASON_FIELD_NUMBER: builtins.int + MESSAGE_FIELD_NUMBER: builtins.int + reason: builtins.str + """The name of the `temporalio.api.enums.v1.StreamErrorReason`, such as + `STREAM_ERROR_REASON_FENCED`. History stores the name, so a reason must never change its name. + """ + message: builtins.str + """The message of the failure, of at most 4096 bytes.""" + def __init__( + self, + *, + reason: builtins.str = ..., + message: builtins.str = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["message", b"message", "reason", b"reason"] + ) -> None: ... + +global___StreamFailure = StreamFailure + +@typing.final +class StreamReadMarkerData(google.protobuf.message.Message): + """The data of a `core_stream_read` marker. Core records one in each activation in which Workflow + code got the page of a read. An empty marker keeps a task with an open read and no open append + apart from the next task when chunking is on. The marker keeps the starting offset, Record count + and digest of each page so replay can verify the Records it reads from the Store. + Its JSON has `bytes` fields in lower-case hex, as for appends. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + READS_FIELD_NUMBER: builtins.int + @property + def reads( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___StreamReadResult + ]: ... + def __init__( + self, + *, + reads: collections.abc.Iterable[global___StreamReadResult] | None = ..., + ) -> None: ... + def ClearField(self, field_name: typing.Literal["reads", b"reads"]) -> None: ... + +global___StreamReadMarkerData = StreamReadMarkerData + +@typing.final +class StreamReadResult(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + STREAM_ID_FIELD_NUMBER: builtins.int + STORE_FIELD_NUMBER: builtins.int + ACTIVATION_INDEX_FIELD_NUMBER: builtins.int + AFTER_OFFSET_FIELD_NUMBER: builtins.int + PAGE_FIELD_NUMBER: builtins.int + FAILURE_FIELD_NUMBER: builtins.int + seq: builtins.int + stream_id: builtins.str + store: builtins.str + """The name of the Store that the read used. For a ref with no Store name, it is the empty name + if the Worker has a Stream runtime under it, else the name of its only runtime. + """ + activation_index: builtins.int + """The index of the activation, within its Workflow Task, in which Workflow code got the result.""" + after_offset: builtins.bytes + """The `after_offset` of the read. A replay reads the Records of the page after it.""" + @property + def page(self) -> global___StreamReadPage: ... + @property + def failure(self) -> global___StreamFailure: ... + def __init__( + self, + *, + seq: builtins.int = ..., + stream_id: builtins.str = ..., + store: builtins.str = ..., + activation_index: builtins.int = ..., + after_offset: builtins.bytes = ..., + page: global___StreamReadPage | None = ..., + failure: global___StreamFailure | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "failure", b"failure", "page", b"page", "result", b"result" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "activation_index", + b"activation_index", + "after_offset", + b"after_offset", + "failure", + b"failure", + "page", + b"page", + "result", + b"result", + "seq", + b"seq", + "store", + b"store", + "stream_id", + b"stream_id", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["result", b"result"] + ) -> typing.Literal["page", "failure"] | None: ... + +global___StreamReadResult = StreamReadResult + +@typing.final +class StreamReadPage(google.protobuf.message.Message): + """A page that a read gave Workflow code, without its Records.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RECORD_COUNT_FIELD_NUMBER: builtins.int + DIGEST_FIELD_NUMBER: builtins.int + RECORD_BYTES_FIELD_NUMBER: builtins.int + WAIT_CUT_FIELD_NUMBER: builtins.int + record_count: builtins.int + digest: builtins.bytes + """The first 16 bytes of SHA-256 over the Records in a Core-owned encoding. New markers prefix + these bytes with version 1. Original markers contain just the legacy hash. + Empty for no Records. + """ + record_bytes: builtins.int + """The size of the Records, as the `max_bytes` of a read measures it. A replay asks the Store for + this much. + """ + wait_cut: builtins.bool + """The `wait_cut` that Workflow code got with the page.""" + def __init__( + self, + *, + record_count: builtins.int = ..., + digest: builtins.bytes = ..., + record_bytes: builtins.int = ..., + wait_cut: builtins.bool = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "digest", + b"digest", + "record_bytes", + b"record_bytes", + "record_count", + b"record_count", + "wait_cut", + b"wait_cut", + ], + ) -> None: ... + +global___StreamReadPage = StreamReadPage diff --git a/temporalio/bridge/proto/workflow_activation/__init__.py b/temporalio/bridge/proto/workflow_activation/__init__.py index 5c178e2185..decfcf1474 100644 --- a/temporalio/bridge/proto/workflow_activation/__init__.py +++ b/temporalio/bridge/proto/workflow_activation/__init__.py @@ -16,7 +16,11 @@ ResolveNexusOperationStart, ResolveRequestCancelExternalWorkflow, ResolveSignalExternalWorkflow, + ResolveStreamAppend, + ResolveStreamRead, SignalWorkflow, + StreamAppended, + StreamPage, UpdateRandomSeed, WorkflowActivation, WorkflowActivationJob, @@ -40,7 +44,11 @@ "ResolveNexusOperationStart", "ResolveRequestCancelExternalWorkflow", "ResolveSignalExternalWorkflow", + "ResolveStreamAppend", + "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..c37c592d94 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/enums/v1/failed_cause.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a$temporal/api/stream/v1/message.proto\x1a\x37temporal/sdk/core/activity_result/activity_result.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a%temporal/sdk/core/common/common.proto\x1a#temporal/sdk/core/nexus/nexus.proto"\xa2\x04\n\x12WorkflowActivation\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x14\n\x0cis_replaying\x18\x03 \x01(\x08\x12\x16\n\x0ehistory_length\x18\x04 \x01(\r\x12@\n\x04jobs\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.WorkflowActivationJob\x12 \n\x18\x61vailable_internal_flags\x18\x06 \x03(\r\x12\x1a\n\x12history_size_bytes\x18\x07 \x01(\x04\x12!\n\x19\x63ontinue_as_new_suggested\x18\x08 \x01(\x08\x12T\n#deployment_version_for_current_task\x18\t \x01(\x0b\x32\'.coresdk.common.WorkerDeploymentVersion\x12\x18\n\x10last_sdk_version\x18\n \x01(\t\x12Z\n\x1fsuggest_continue_as_new_reasons\x18\x0b \x03(\x0e\x32\x31.temporal.api.enums.v1.SuggestContinueAsNewReason\x12\x30\n(target_worker_deployment_version_changed\x18\x0c \x01(\x08"\x82\x0c\n\x15WorkflowActivationJob\x12N\n\x13initialize_workflow\x18\x01 \x01(\x0b\x32/.coresdk.workflow_activation.InitializeWorkflowH\x00\x12<\n\nfire_timer\x18\x02 \x01(\x0b\x32&.coresdk.workflow_activation.FireTimerH\x00\x12K\n\x12update_random_seed\x18\x04 \x01(\x0b\x32-.coresdk.workflow_activation.UpdateRandomSeedH\x00\x12\x44\n\x0equery_workflow\x18\x05 \x01(\x0b\x32*.coresdk.workflow_activation.QueryWorkflowH\x00\x12\x46\n\x0f\x63\x61ncel_workflow\x18\x06 \x01(\x0b\x32+.coresdk.workflow_activation.CancelWorkflowH\x00\x12\x46\n\x0fsignal_workflow\x18\x07 \x01(\x0b\x32+.coresdk.workflow_activation.SignalWorkflowH\x00\x12H\n\x10resolve_activity\x18\x08 \x01(\x0b\x32,.coresdk.workflow_activation.ResolveActivityH\x00\x12G\n\x10notify_has_patch\x18\t \x01(\x0b\x32+.coresdk.workflow_activation.NotifyHasPatchH\x00\x12q\n&resolve_child_workflow_execution_start\x18\n \x01(\x0b\x32?.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartH\x00\x12\x66\n resolve_child_workflow_execution\x18\x0b \x01(\x0b\x32:.coresdk.workflow_activation.ResolveChildWorkflowExecutionH\x00\x12\x66\n resolve_signal_external_workflow\x18\x0c \x01(\x0b\x32:.coresdk.workflow_activation.ResolveSignalExternalWorkflowH\x00\x12u\n(resolve_request_cancel_external_workflow\x18\r \x01(\x0b\x32\x41.coresdk.workflow_activation.ResolveRequestCancelExternalWorkflowH\x00\x12:\n\tdo_update\x18\x0e \x01(\x0b\x32%.coresdk.workflow_activation.DoUpdateH\x00\x12`\n\x1dresolve_nexus_operation_start\x18\x0f \x01(\x0b\x32\x37.coresdk.workflow_activation.ResolveNexusOperationStartH\x00\x12U\n\x17resolve_nexus_operation\x18\x10 \x01(\x0b\x32\x32.coresdk.workflow_activation.ResolveNexusOperationH\x00\x12Q\n\x15resolve_stream_append\x18\x11 \x01(\x0b\x32\x30.coresdk.workflow_activation.ResolveStreamAppendH\x00\x12M\n\x13resolve_stream_read\x18\x12 \x01(\x0b\x32..coresdk.workflow_activation.ResolveStreamReadH\x00\x12I\n\x11remove_from_cache\x18\x32 \x01(\x0b\x32,.coresdk.workflow_activation.RemoveFromCacheH\x00\x42\t\n\x07variant"\xe3\x0b\n\x12InitializeWorkflow\x12\x15\n\rworkflow_type\x18\x01 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x17\n\x0frandomness_seed\x18\x04 \x01(\x04\x12M\n\x07headers\x18\x05 \x03(\x0b\x32<.coresdk.workflow_activation.InitializeWorkflow.HeadersEntry\x12\x10\n\x08identity\x18\x06 \x01(\t\x12I\n\x14parent_workflow_info\x18\x07 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecution\x12=\n\x1aworkflow_execution_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14workflow_run_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\'\n\x1f\x63ontinued_from_execution_run_id\x18\x0b \x01(\t\x12J\n\x13\x63ontinued_initiator\x18\x0c \x01(\x0e\x32-.temporal.api.enums.v1.ContinueAsNewInitiator\x12;\n\x11\x63ontinued_failure\x18\r \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12@\n\x16last_completion_result\x18\x0e \x01(\x0b\x32 .temporal.api.common.v1.Payloads\x12\x1e\n\x16\x66irst_execution_run_id\x18\x0f \x01(\t\x12\x39\n\x0cretry_policy\x18\x10 \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x0f\n\x07\x61ttempt\x18\x11 \x01(\x05\x12\x15\n\rcron_schedule\x18\x12 \x01(\t\x12\x46\n"workflow_execution_expiration_time\x18\x13 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x45\n"cron_schedule_to_schedule_interval\x18\x14 \x01(\x0b\x32\x19.google.protobuf.Duration\x12*\n\x04memo\x18\x15 \x01(\x0b\x32\x1c.temporal.api.common.v1.Memo\x12\x43\n\x11search_attributes\x18\x16 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12.\n\nstart_time\x18\x17 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12@\n\rroot_workflow\x18\x18 \x01(\x0b\x32).temporal.api.common.v1.WorkflowExecution\x12\x32\n\x08priority\x18\x19 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12!\n\x19original_execution_run_id\x18\x1a \x01(\t\x12\x65\n&propagated_nexus_serialization_context\x18\x1b \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x18\n\tFireTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r"m\n\x0fResolveActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12;\n\x06result\x18\x02 \x01(\x0b\x32+.coresdk.activity_result.ActivityResolution\x12\x10\n\x08is_local\x18\x03 \x01(\x08"\xd1\x02\n"ResolveChildWorkflowExecutionStart\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12[\n\tsucceeded\x18\x02 \x01(\x0b\x32\x46.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartSuccessH\x00\x12X\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32\x46.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartFailureH\x00\x12]\n\tcancelled\x18\x04 \x01(\x0b\x32H.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartCancelledH\x00\x42\x08\n\x06status";\n)ResolveChildWorkflowExecutionStartSuccess\x12\x0e\n\x06run_id\x18\x01 \x01(\t"\xa6\x01\n)ResolveChildWorkflowExecutionStartFailure\x12\x13\n\x0bworkflow_id\x18\x01 \x01(\t\x12\x15\n\rworkflow_type\x18\x02 \x01(\t\x12M\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32>.coresdk.child_workflow.StartChildWorkflowExecutionFailedCause"`\n+ResolveChildWorkflowExecutionStartCancelled\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"i\n\x1dResolveChildWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12;\n\x06result\x18\x02 \x01(\x0b\x32+.coresdk.child_workflow.ChildWorkflowResult"+\n\x10UpdateRandomSeed\x12\x17\n\x0frandomness_seed\x18\x01 \x01(\x04"\x84\x02\n\rQueryWorkflow\x12\x10\n\x08query_id\x18\x01 \x01(\t\x12\x12\n\nquery_type\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12H\n\x07headers\x18\x05 \x03(\x0b\x32\x37.coresdk.workflow_activation.QueryWorkflow.HeadersEntry\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01" \n\x0e\x43\x61ncelWorkflow\x12\x0e\n\x06reason\x18\x01 \x01(\t"\xa1\x02\n\x0eSignalWorkflow\x12\x13\n\x0bsignal_name\x18\x01 \x01(\t\x12.\n\x05input\x18\x02 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x10\n\x08identity\x18\x03 \x01(\t\x12I\n\x07headers\x18\x05 \x03(\x0b\x32\x38.coresdk.workflow_activation.SignalWorkflow.HeadersEntry\x12\x1c\n\x14originating_event_id\x18\x06 \x01(\x03\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01""\n\x0eNotifyHasPatch\x12\x10\n\x08patch_id\x18\x01 \x01(\t"\xb1\x01\n\x1dResolveSignalExternalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x07\x66\x61ilure\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12P\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32\x41.temporal.api.enums.v1.SignalExternalWorkflowExecutionFailedCause"\xb8\x01\n$ResolveRequestCancelExternalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x07\x66\x61ilure\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12P\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32\x41.temporal.api.enums.v1.CancelExternalWorkflowExecutionFailedCause"\xb2\x03\n\x08\x44oUpdate\x12\n\n\x02id\x18\x01 \x01(\t\x12\x1c\n\x14protocol_instance_id\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12.\n\x05input\x18\x04 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x43\n\x07headers\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.DoUpdate.HeadersEntry\x12*\n\x04meta\x18\x06 \x01(\x0b\x32\x1c.temporal.api.update.v1.Meta\x12\x15\n\rrun_validator\x18\x07 \x01(\x08\x12\x65\n&propagated_nexus_serialization_context\x18\x08 \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x9a\x01\n\x1aResolveNexusOperationStart\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x19\n\x0foperation_token\x18\x02 \x01(\tH\x00\x12\x16\n\x0cstarted_sync\x18\x03 \x01(\x08H\x00\x12\x32\n\x06\x66\x61iled\x18\x04 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status"Y\n\x15ResolveNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x33\n\x06result\x18\x02 \x01(\x0b\x32#.coresdk.nexus.NexusOperationResult"\xe0\x02\n\x0fRemoveFromCache\x12\x0f\n\x07message\x18\x01 \x01(\t\x12K\n\x06reason\x18\x02 \x01(\x0e\x32;.coresdk.workflow_activation.RemoveFromCache.EvictionReason"\xee\x01\n\x0e\x45victionReason\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nCACHE_FULL\x10\x01\x12\x0e\n\nCACHE_MISS\x10\x02\x12\x12\n\x0eNONDETERMINISM\x10\x03\x12\r\n\tLANG_FAIL\x10\x04\x12\x12\n\x0eLANG_REQUESTED\x10\x05\x12\x12\n\x0eTASK_NOT_FOUND\x10\x06\x12\x15\n\x11UNHANDLED_COMMAND\x10\x07\x12\t\n\x05\x46\x41TAL\x10\x08\x12\x1f\n\x1bPAGINATION_OR_HISTORY_FETCH\x10\t\x12\x1d\n\x19WORKFLOW_EXECUTION_ENDING\x10\n"\xa1\x01\n\x13ResolveStreamAppend\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12?\n\x08\x61ppended\x18\x02 \x01(\x0b\x32+.coresdk.workflow_activation.StreamAppendedH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status";\n\x0eStreamAppended\x12\x14\n\x0c\x66irst_offset\x18\x01 \x01(\x0c\x12\x13\n\x0blast_offset\x18\x02 \x01(\x0c"\x97\x01\n\x11ResolveStreamRead\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x37\n\x04page\x18\x02 \x01(\x0b\x32\'.coresdk.workflow_activation.StreamPageH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status"U\n\nStreamPage\x12\x35\n\x07records\x18\x01 \x03(\x0b\x32$.temporal.api.stream.v1.StreamRecord\x12\x10\n\x08wait_cut\x18\x03 \x01(\x08\x42\x38\xea\x02\x35Temporalio::Internal::Bridge::Api::WorkflowActivationb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -67,56 +70,64 @@ _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 = 2736 + _INITIALIZEWORKFLOW._serialized_start = 2739 + _INITIALIZEWORKFLOW._serialized_end = 4246 + _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_start = 4167 + _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_end = 4246 + _FIRETIMER._serialized_start = 4248 + _FIRETIMER._serialized_end = 4272 + _RESOLVEACTIVITY._serialized_start = 4274 + _RESOLVEACTIVITY._serialized_end = 4383 + _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_start = 4386 + _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_end = 4723 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_start = 4725 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_end = 4784 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_start = 4787 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_end = 4953 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_start = 4955 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_end = 5051 + _RESOLVECHILDWORKFLOWEXECUTION._serialized_start = 5053 + _RESOLVECHILDWORKFLOWEXECUTION._serialized_end = 5158 + _UPDATERANDOMSEED._serialized_start = 5160 + _UPDATERANDOMSEED._serialized_end = 5203 + _QUERYWORKFLOW._serialized_start = 5206 + _QUERYWORKFLOW._serialized_end = 5466 + _QUERYWORKFLOW_HEADERSENTRY._serialized_start = 4167 + _QUERYWORKFLOW_HEADERSENTRY._serialized_end = 4246 + _CANCELWORKFLOW._serialized_start = 5468 + _CANCELWORKFLOW._serialized_end = 5500 + _SIGNALWORKFLOW._serialized_start = 5503 + _SIGNALWORKFLOW._serialized_end = 5792 + _SIGNALWORKFLOW_HEADERSENTRY._serialized_start = 4167 + _SIGNALWORKFLOW_HEADERSENTRY._serialized_end = 4246 + _NOTIFYHASPATCH._serialized_start = 5794 + _NOTIFYHASPATCH._serialized_end = 5828 + _RESOLVESIGNALEXTERNALWORKFLOW._serialized_start = 5831 + _RESOLVESIGNALEXTERNALWORKFLOW._serialized_end = 6008 + _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_start = 6011 + _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_end = 6195 + _DOUPDATE._serialized_start = 6198 + _DOUPDATE._serialized_end = 6632 + _DOUPDATE_HEADERSENTRY._serialized_start = 4167 + _DOUPDATE_HEADERSENTRY._serialized_end = 4246 + _RESOLVENEXUSOPERATIONSTART._serialized_start = 6635 + _RESOLVENEXUSOPERATIONSTART._serialized_end = 6789 + _RESOLVENEXUSOPERATION._serialized_start = 6791 + _RESOLVENEXUSOPERATION._serialized_end = 6880 + _REMOVEFROMCACHE._serialized_start = 6883 + _REMOVEFROMCACHE._serialized_end = 7235 + _REMOVEFROMCACHE_EVICTIONREASON._serialized_start = 6997 + _REMOVEFROMCACHE_EVICTIONREASON._serialized_end = 7235 + _RESOLVESTREAMAPPEND._serialized_start = 7238 + _RESOLVESTREAMAPPEND._serialized_end = 7399 + _STREAMAPPENDED._serialized_start = 7401 + _STREAMAPPENDED._serialized_end = 7460 + _RESOLVESTREAMREAD._serialized_start = 7463 + _RESOLVESTREAMREAD._serialized_end = 7614 + _STREAMPAGE._serialized_start = 7616 + _STREAMPAGE._serialized_end = 7701 # @@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 e55917d810..f600f19d4a 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi @@ -23,6 +23,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 +50,7 @@ class WorkflowActivation(google.protobuf.message.Message): 3. random-seed-updates 4. signals/updates 5. all others - 6. local activity resolutions + 6. Stream results and local activity resolutions 7. queries 8. evictions @@ -65,6 +66,14 @@ class WorkflowActivation(google.protobuf.message.Message): in that same activation (prime example: cancelling not-wait-for-cancel activities). So, we do this to ensure the LA resolution happens after that cancel (or whatever else it may be) as it normally would have when executing. + * Stream results go with the local activity resolutions, for the same reason. Core records a + Stream result in a `core_stream_append` or `core_stream_read` marker, which History has after + the `WorkflowTaskCompleted` event of its task. A replay must give the result before it reaches + that event, so it scans ahead in History for the marker, as for a local activity marker. Each + result in the marker has the index of the activation that got it, so the replay gives it in + that same activation. In one activation, the Stream results go first, appends before reads, + each in `seq` order, and then the local activity resolutions. A task with a Stream marker + retains its recorded activation groups. * Queries always go last (and, in fact, always come in their own activation) * Evictions also always come in their own activation @@ -250,6 +259,8 @@ class WorkflowActivationJob(google.protobuf.message.Message): DO_UPDATE_FIELD_NUMBER: builtins.int RESOLVE_NEXUS_OPERATION_START_FIELD_NUMBER: builtins.int RESOLVE_NEXUS_OPERATION_FIELD_NUMBER: builtins.int + RESOLVE_STREAM_APPEND_FIELD_NUMBER: builtins.int + RESOLVE_STREAM_READ_FIELD_NUMBER: builtins.int REMOVE_FROM_CACHE_FIELD_NUMBER: builtins.int @property def initialize_workflow(self) -> global___InitializeWorkflow: @@ -324,6 +335,14 @@ class WorkflowActivationJob(google.protobuf.message.Message): def resolve_nexus_operation(self) -> global___ResolveNexusOperation: """A nexus operation resolved.""" + @property + def resolve_stream_append(self) -> global___ResolveStreamAppend: + """An append to a Stream finished.""" + + @property + def resolve_stream_read(self) -> global___ResolveStreamRead: + """A read of a Stream finished.""" + @property def remove_from_cache(self) -> global___RemoveFromCache: """Remove the workflow identified by the [WorkflowActivation] containing this job from the @@ -353,6 +372,8 @@ class WorkflowActivationJob(google.protobuf.message.Message): do_update: global___DoUpdate | None = ..., resolve_nexus_operation_start: global___ResolveNexusOperationStart | None = ..., resolve_nexus_operation: global___ResolveNexusOperation | None = ..., + resolve_stream_append: global___ResolveStreamAppend | None = ..., + resolve_stream_read: global___ResolveStreamRead | None = ..., remove_from_cache: global___RemoveFromCache | None = ..., ) -> None: ... def HasField( @@ -386,6 +407,10 @@ 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_read", + b"resolve_stream_read", "signal_workflow", b"signal_workflow", "update_random_seed", @@ -425,6 +450,10 @@ 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_read", + b"resolve_stream_read", "signal_workflow", b"signal_workflow", "update_random_seed", @@ -452,6 +481,8 @@ class WorkflowActivationJob(google.protobuf.message.Message): "do_update", "resolve_nexus_operation_start", "resolve_nexus_operation", + "resolve_stream_append", + "resolve_stream_read", "remove_from_cache", ] | None @@ -1645,3 +1676,162 @@ class RemoveFromCache(google.protobuf.message.Message): ) -> None: ... global___RemoveFromCache = RemoveFromCache + +@typing.final +class ResolveStreamAppend(google.protobuf.message.Message): + """Core delivers the result in the next activation, or in the next task when the Store answers + during completion. Stream and Local Activity markers share an activation index. Replay + preserves the recorded activation groups for tasks that contain a Stream marker. + """ + + 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: + """An `ApplicationFailureInfo` of the type `stream_`, such as `stream_fenced`, with + `non_retryable` set. Its details have one `binary/protobuf` payload of a + `temporalio.api.stream.v1.StreamErrorDetails`. + """ + + 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 ResolveStreamRead(google.protobuf.message.Message): + """The result of a `ReadStream`. Each read gets exactly one, unless Core drops the read (see + `ReadStream`). The activation rules of `ResolveStreamAppend` apply to it too, with the + `core_stream_read` marker in place of the `core_stream_append` one. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + PAGE_FIELD_NUMBER: builtins.int + FAILED_FIELD_NUMBER: builtins.int + seq: builtins.int + """The `seq` of the `ReadStream`.""" + @property + def page(self) -> global___StreamPage: ... + @property + def failed(self) -> temporalio.api.failure.v1.message_pb2.Failure: + """The failure of the read. It has the parts of the `failed` of a `ResolveStreamAppend`.""" + + def __init__( + self, + *, + seq: builtins.int = ..., + page: global___StreamPage | None = ..., + failed: temporalio.api.failure.v1.message_pb2.Failure | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "failed", b"failed", "page", b"page", "status", b"status" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "failed", b"failed", "page", b"page", "seq", b"seq", "status", b"status" + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["status", b"status"] + ) -> typing.Literal["page", "failed"] | None: ... + +global___ResolveStreamRead = ResolveStreamRead + +@typing.final +class StreamPage(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RECORDS_FIELD_NUMBER: builtins.int + WAIT_CUT_FIELD_NUMBER: builtins.int + wait_cut: builtins.bool + """True if the page has no Record because the read time of the Workflow Task ended the wait + before the `wait` of the read. A reader that waits for a Record can read again from + the same `after_offset`. It's false for a page that ends a whole wait. + """ + @property + def records( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + temporalio.api.stream.v1.message_pb2.StreamRecord + ]: + """The Records of the page, in the order of the Stream. It's empty if no Record came while the + read waited. + """ + + def __init__( + self, + *, + records: collections.abc.Iterable[ + temporalio.api.stream.v1.message_pb2.StreamRecord + ] + | None = ..., + wait_cut: builtins.bool = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["records", b"records", "wait_cut", b"wait_cut"] + ) -> None: ... + +global___StreamPage = StreamPage diff --git a/temporalio/bridge/proto/workflow_commands/__init__.py b/temporalio/bridge/proto/workflow_commands/__init__.py index f599917afa..280eb77ab2 100644 --- a/temporalio/bridge/proto/workflow_commands/__init__.py +++ b/temporalio/bridge/proto/workflow_commands/__init__.py @@ -1,5 +1,6 @@ from .workflow_commands_pb2 import ( ActivityCancellationType, + AppendToStream, CancelChildWorkflowExecution, CancelSignalWorkflow, CancelTimer, @@ -10,6 +11,7 @@ ModifyWorkflowProperties, QueryResult, QuerySuccess, + ReadStream, RequestCancelActivity, RequestCancelExternalWorkflowExecution, RequestCancelLocalActivity, @@ -28,6 +30,7 @@ __all__ = [ "ActivityCancellationType", + "AppendToStream", "CancelChildWorkflowExecution", "CancelSignalWorkflow", "CancelTimer", @@ -38,6 +41,7 @@ "ModifyWorkflowProperties", "QueryResult", "QuerySuccess", + "ReadStream", "RequestCancelActivity", "RequestCancelExternalWorkflowExecution", "RequestCancelLocalActivity", diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py index 3573f36b11..6c0bf51ccd 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py @@ -29,6 +29,9 @@ from temporalio.api.sdk.v1 import ( event_group_marker_pb2 as temporal_dot_api_dot_sdk_dot_v1_dot_event__group__marker__pb2, ) +from temporalio.api.sdk.v1 import ( + stream_pb2 as temporal_dot_api_dot_sdk_dot_v1_dot_stream__pb2, +) from temporalio.api.sdk.v1 import ( user_metadata_pb2 as temporal_dot_api_dot_sdk_dot_v1_dot_user__metadata__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/sdk/v1/stream.proto\x1a&temporal/api/workflow/v1/message.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a#temporal/sdk/core/nexus/nexus.proto\x1a%temporal/sdk/core/common/common.proto"\xae\x11\n\x0fWorkflowCommand\x12\x38\n\ruser_metadata\x18\x64 \x01(\x0b\x32!.temporal.api.sdk.v1.UserMetadata\x12\x42\n\x13\x65vent_group_markers\x18\x65 \x03(\x0b\x32%.temporal.api.sdk.v1.EventGroupMarker\x12<\n\x0bstart_timer\x18\x01 \x01(\x0b\x32%.coresdk.workflow_commands.StartTimerH\x00\x12H\n\x11schedule_activity\x18\x02 \x01(\x0b\x32+.coresdk.workflow_commands.ScheduleActivityH\x00\x12\x42\n\x10respond_to_query\x18\x03 \x01(\x0b\x32&.coresdk.workflow_commands.QueryResultH\x00\x12S\n\x17request_cancel_activity\x18\x04 \x01(\x0b\x32\x30.coresdk.workflow_commands.RequestCancelActivityH\x00\x12>\n\x0c\x63\x61ncel_timer\x18\x05 \x01(\x0b\x32&.coresdk.workflow_commands.CancelTimerH\x00\x12[\n\x1b\x63omplete_workflow_execution\x18\x06 \x01(\x0b\x32\x34.coresdk.workflow_commands.CompleteWorkflowExecutionH\x00\x12S\n\x17\x66\x61il_workflow_execution\x18\x07 \x01(\x0b\x32\x30.coresdk.workflow_commands.FailWorkflowExecutionH\x00\x12g\n"continue_as_new_workflow_execution\x18\x08 \x01(\x0b\x32\x39.coresdk.workflow_commands.ContinueAsNewWorkflowExecutionH\x00\x12W\n\x19\x63\x61ncel_workflow_execution\x18\t \x01(\x0b\x32\x32.coresdk.workflow_commands.CancelWorkflowExecutionH\x00\x12\x45\n\x10set_patch_marker\x18\n \x01(\x0b\x32).coresdk.workflow_commands.SetPatchMarkerH\x00\x12`\n\x1estart_child_workflow_execution\x18\x0b \x01(\x0b\x32\x36.coresdk.workflow_commands.StartChildWorkflowExecutionH\x00\x12\x62\n\x1f\x63\x61ncel_child_workflow_execution\x18\x0c \x01(\x0b\x32\x37.coresdk.workflow_commands.CancelChildWorkflowExecutionH\x00\x12w\n*request_cancel_external_workflow_execution\x18\r \x01(\x0b\x32\x41.coresdk.workflow_commands.RequestCancelExternalWorkflowExecutionH\x00\x12h\n"signal_external_workflow_execution\x18\x0e \x01(\x0b\x32:.coresdk.workflow_commands.SignalExternalWorkflowExecutionH\x00\x12Q\n\x16\x63\x61ncel_signal_workflow\x18\x0f \x01(\x0b\x32/.coresdk.workflow_commands.CancelSignalWorkflowH\x00\x12S\n\x17schedule_local_activity\x18\x10 \x01(\x0b\x32\x30.coresdk.workflow_commands.ScheduleLocalActivityH\x00\x12^\n\x1drequest_cancel_local_activity\x18\x11 \x01(\x0b\x32\x35.coresdk.workflow_commands.RequestCancelLocalActivityH\x00\x12\x66\n!upsert_workflow_search_attributes\x18\x12 \x01(\x0b\x32\x39.coresdk.workflow_commands.UpsertWorkflowSearchAttributesH\x00\x12Y\n\x1amodify_workflow_properties\x18\x13 \x01(\x0b\x32\x33.coresdk.workflow_commands.ModifyWorkflowPropertiesH\x00\x12\x44\n\x0fupdate_response\x18\x14 \x01(\x0b\x32).coresdk.workflow_commands.UpdateResponseH\x00\x12U\n\x18schedule_nexus_operation\x18\x15 \x01(\x0b\x32\x31.coresdk.workflow_commands.ScheduleNexusOperationH\x00\x12`\n\x1erequest_cancel_nexus_operation\x18\x16 \x01(\x0b\x32\x36.coresdk.workflow_commands.RequestCancelNexusOperationH\x00\x12\x45\n\x10\x61ppend_to_stream\x18\x17 \x01(\x0b\x32).coresdk.workflow_commands.AppendToStreamH\x00\x12<\n\x0bread_stream\x18\x18 \x01(\x0b\x32%.coresdk.workflow_commands.ReadStreamH\x00\x42\t\n\x07variant"S\n\nStartTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x38\n\x15start_to_fire_timeout\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration"\x1a\n\x0b\x43\x61ncelTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r"\xb8\x06\n\x10ScheduleActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x15\n\ractivity_type\x18\x03 \x01(\t\x12\x12\n\ntask_queue\x18\x05 \x01(\t\x12I\n\x07headers\x18\x06 \x03(\x0b\x32\x38.coresdk.workflow_commands.ScheduleActivity.HeadersEntry\x12\x32\n\targuments\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x34\n\x11heartbeat_timeout\x18\x0b \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x0c \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12N\n\x11\x63\x61ncellation_type\x18\r \x01(\x0e\x32\x33.coresdk.workflow_commands.ActivityCancellationType\x12\x1e\n\x16\x64o_not_eagerly_execute\x18\x0e \x01(\x08\x12;\n\x11versioning_intent\x18\x0f \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12\x32\n\x08priority\x18\x10 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\xd7\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\x12\x42\n\x15local_activity_origin\x18\x0f \x01(\x0b\x32#.coresdk.common.LocalActivityOrigin\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"$\n\x15RequestCancelActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r")\n\x1aRequestCancelLocalActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r"\x9c\x01\n\x0bQueryResult\x12\x10\n\x08query_id\x18\x01 \x01(\t\x12<\n\tsucceeded\x18\x02 \x01(\x0b\x32\'.coresdk.workflow_commands.QuerySuccessH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\t\n\x07variant"A\n\x0cQuerySuccess\x12\x31\n\x08response\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"L\n\x19\x43ompleteWorkflowExecution\x12/\n\x06result\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"J\n\x15\x46\x61ilWorkflowExecution\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"\x92\x07\n\x1e\x43ontinueAsNewWorkflowExecution\x12\x15\n\rworkflow_type\x18\x01 \x01(\t\x12\x12\n\ntask_queue\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x37\n\x14workflow_run_timeout\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12Q\n\x04memo\x18\x06 \x03(\x0b\x32\x43.coresdk.workflow_commands.ContinueAsNewWorkflowExecution.MemoEntry\x12W\n\x07headers\x18\x07 \x03(\x0b\x32\x46.coresdk.workflow_commands.ContinueAsNewWorkflowExecution.HeadersEntry\x12\x43\n\x11search_attributes\x18\x08 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12\x39\n\x0cretry_policy\x18\t \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12;\n\x11versioning_intent\x18\n \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12[\n\x1binitial_versioning_behavior\x18\x0b \x01(\x0e\x32\x36.temporal.api.enums.v1.ContinueAsNewVersioningBehavior\x12\x39\n\x16\x62\x61\x63koff_start_interval\x18\x0c \x01(\x0b\x32\x19.google.protobuf.Duration\x1aL\n\tMemoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"L\n\x17\x43\x61ncelWorkflowExecution\x12\x31\n\x07\x64\x65tails\x18\x01 \x01(\x0b\x32 .temporal.api.common.v1.Payloads"6\n\x0eSetPatchMarker\x12\x10\n\x08patch_id\x18\x01 \x01(\t\x12\x12\n\ndeprecated\x18\x02 \x01(\x08"\xe1\t\n\x1bStartChildWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x11\n\tnamespace\x18\x02 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x03 \x01(\t\x12\x15\n\rworkflow_type\x18\x04 \x01(\t\x12\x12\n\ntask_queue\x18\x05 \x01(\t\x12.\n\x05input\x18\x06 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12=\n\x1aworkflow_execution_timeout\x18\x07 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14workflow_run_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x46\n\x13parent_close_policy\x18\n \x01(\x0e\x32).coresdk.child_workflow.ParentClosePolicy\x12N\n\x18workflow_id_reuse_policy\x18\x0c \x01(\x0e\x32,.temporal.api.enums.v1.WorkflowIdReusePolicy\x12\x39\n\x0cretry_policy\x18\r \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x15\n\rcron_schedule\x18\x0e \x01(\t\x12T\n\x07headers\x18\x0f \x03(\x0b\x32\x43.coresdk.workflow_commands.StartChildWorkflowExecution.HeadersEntry\x12N\n\x04memo\x18\x10 \x03(\x0b\x32@.coresdk.workflow_commands.StartChildWorkflowExecution.MemoEntry\x12\x43\n\x11search_attributes\x18\x11 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12P\n\x11\x63\x61ncellation_type\x18\x12 \x01(\x0e\x32\x35.coresdk.child_workflow.ChildWorkflowCancellationType\x12;\n\x11versioning_intent\x18\x13 \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12\x32\n\x08priority\x18\x14 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12I\n\x13versioning_override\x18\x15 \x01(\x0b\x32,.temporal.api.workflow.v1.VersioningOverride\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x1aL\n\tMemoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"J\n\x1c\x43\x61ncelChildWorkflowExecution\x12\x1a\n\x12\x63hild_workflow_seq\x18\x01 \x01(\r\x12\x0e\n\x06reason\x18\x02 \x01(\t"\x8e\x01\n&RequestCancelExternalWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12G\n\x12workflow_execution\x18\x02 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecution\x12\x0e\n\x06reason\x18\x03 \x01(\t"\x8f\x03\n\x1fSignalExternalWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12I\n\x12workflow_execution\x18\x02 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecutionH\x00\x12\x1b\n\x11\x63hild_workflow_id\x18\x03 \x01(\tH\x00\x12\x13\n\x0bsignal_name\x18\x04 \x01(\t\x12-\n\x04\x61rgs\x18\x05 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12X\n\x07headers\x18\x06 \x03(\x0b\x32G.coresdk.workflow_commands.SignalExternalWorkflowExecution.HeadersEntry\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x42\x08\n\x06target"#\n\x14\x43\x61ncelSignalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r"e\n\x1eUpsertWorkflowSearchAttributes\x12\x43\n\x11search_attributes\x18\x01 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes"O\n\x18ModifyWorkflowProperties\x12\x33\n\rupserted_memo\x18\x01 \x01(\x0b\x32\x1c.temporal.api.common.v1.Memo"\xd2\x01\n\x0eUpdateResponse\x12\x1c\n\x14protocol_instance_id\x18\x01 \x01(\t\x12*\n\x08\x61\x63\x63\x65pted\x18\x02 \x01(\x0b\x32\x16.google.protobuf.EmptyH\x00\x12\x34\n\x08rejected\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x12\x34\n\tcompleted\x18\x04 \x01(\x0b\x32\x1f.temporal.api.common.v1.PayloadH\x00\x42\n\n\x08response"\x9a\x04\n\x16ScheduleNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x10\n\x08\x65ndpoint\x18\x02 \x01(\t\x12\x0f\n\x07service\x18\x03 \x01(\t\x12\x11\n\toperation\x18\x04 \x01(\t\x12.\n\x05input\x18\x05 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x06 \x01(\x0b\x32\x19.google.protobuf.Duration\x12X\n\x0cnexus_header\x18\x07 \x03(\x0b\x32\x42.coresdk.workflow_commands.ScheduleNexusOperation.NexusHeaderEntry\x12H\n\x11\x63\x61ncellation_type\x18\x08 \x01(\x0e\x32-.coresdk.nexus.NexusOperationCancellationType\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x1a\x32\n\x10NexusHeaderEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"*\n\x1bRequestCancelNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r"~\n\x0e\x41ppendToStream\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12.\n\x06stream\x18\x02 \x01(\x0b\x32\x1e.temporal.api.sdk.v1.StreamRef\x12/\n\x06\x62odies\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload"\xb0\x01\n\nReadStream\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12.\n\x06stream\x18\x02 \x01(\x0b\x32\x1e.temporal.api.sdk.v1.StreamRef\x12\x14\n\x0c\x61\x66ter_offset\x18\x03 \x01(\x0c\x12\'\n\x04wait\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x13\n\x0bmax_records\x18\x05 \x01(\x05\x12\x11\n\tmax_bytes\x18\x06 \x01(\x03*X\n\x18\x41\x63tivityCancellationType\x12\x0e\n\nTRY_CANCEL\x10\x00\x12\x1f\n\x1bWAIT_CANCELLATION_COMPLETED\x10\x01\x12\x0b\n\x07\x41\x42\x41NDON\x10\x02\x42\x36\xea\x02\x33Temporalio::Internal::Bridge::Api::WorkflowCommandsb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -72,70 +75,74 @@ _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 = 9327 + _ACTIVITYCANCELLATIONTYPE._serialized_end = 9415 + _WORKFLOWCOMMAND._serialized_start = 592 + _WORKFLOWCOMMAND._serialized_end = 2814 + _STARTTIMER._serialized_start = 2816 + _STARTTIMER._serialized_end = 2899 + _CANCELTIMER._serialized_start = 2901 + _CANCELTIMER._serialized_end = 2927 + _SCHEDULEACTIVITY._serialized_start = 2930 + _SCHEDULEACTIVITY._serialized_end = 3754 + _SCHEDULEACTIVITY_HEADERSENTRY._serialized_start = 3675 + _SCHEDULEACTIVITY_HEADERSENTRY._serialized_end = 3754 + _SCHEDULELOCALACTIVITY._serialized_start = 3757 + _SCHEDULELOCALACTIVITY._serialized_end = 4612 + _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_start = 3675 + _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_end = 3754 + _REQUESTCANCELACTIVITY._serialized_start = 4614 + _REQUESTCANCELACTIVITY._serialized_end = 4650 + _REQUESTCANCELLOCALACTIVITY._serialized_start = 4652 + _REQUESTCANCELLOCALACTIVITY._serialized_end = 4693 + _QUERYRESULT._serialized_start = 4696 + _QUERYRESULT._serialized_end = 4852 + _QUERYSUCCESS._serialized_start = 4854 + _QUERYSUCCESS._serialized_end = 4919 + _COMPLETEWORKFLOWEXECUTION._serialized_start = 4921 + _COMPLETEWORKFLOWEXECUTION._serialized_end = 4997 + _FAILWORKFLOWEXECUTION._serialized_start = 4999 + _FAILWORKFLOWEXECUTION._serialized_end = 5073 + _CONTINUEASNEWWORKFLOWEXECUTION._serialized_start = 5076 + _CONTINUEASNEWWORKFLOWEXECUTION._serialized_end = 5990 + _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5833 + _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5909 + _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3675 + _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3754 + _CANCELWORKFLOWEXECUTION._serialized_start = 5992 + _CANCELWORKFLOWEXECUTION._serialized_end = 6068 + _SETPATCHMARKER._serialized_start = 6070 + _SETPATCHMARKER._serialized_end = 6124 + _STARTCHILDWORKFLOWEXECUTION._serialized_start = 6127 + _STARTCHILDWORKFLOWEXECUTION._serialized_end = 7376 + _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3675 + _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3754 + _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5833 + _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5909 + _CANCELCHILDWORKFLOWEXECUTION._serialized_start = 7378 + _CANCELCHILDWORKFLOWEXECUTION._serialized_end = 7452 + _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_start = 7455 + _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_end = 7597 + _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_start = 7600 + _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_end = 7999 + _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3675 + _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3754 + _CANCELSIGNALWORKFLOW._serialized_start = 8001 + _CANCELSIGNALWORKFLOW._serialized_end = 8036 + _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_start = 8038 + _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_end = 8139 + _MODIFYWORKFLOWPROPERTIES._serialized_start = 8141 + _MODIFYWORKFLOWPROPERTIES._serialized_end = 8220 + _UPDATERESPONSE._serialized_start = 8223 + _UPDATERESPONSE._serialized_end = 8433 + _SCHEDULENEXUSOPERATION._serialized_start = 8436 + _SCHEDULENEXUSOPERATION._serialized_end = 8974 + _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_start = 8924 + _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_end = 8974 + _REQUESTCANCELNEXUSOPERATION._serialized_start = 8976 + _REQUESTCANCELNEXUSOPERATION._serialized_end = 9018 + _APPENDTOSTREAM._serialized_start = 9020 + _APPENDTOSTREAM._serialized_end = 9146 + _READSTREAM._serialized_start = 9149 + _READSTREAM._serialized_end = 9325 # @@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..ed3b946823 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi @@ -24,6 +24,7 @@ import temporalio.api.common.v1.message_pb2 import temporalio.api.enums.v1.workflow_pb2 import temporalio.api.failure.v1.message_pb2 import temporalio.api.sdk.v1.event_group_marker_pb2 +import temporalio.api.sdk.v1.stream_pb2 import temporalio.api.sdk.v1.user_metadata_pb2 import temporalio.api.workflow.v1.message_pb2 import temporalio.bridge.proto.child_workflow.child_workflow_pb2 @@ -105,6 +106,8 @@ class WorkflowCommand(google.protobuf.message.Message): UPDATE_RESPONSE_FIELD_NUMBER: builtins.int SCHEDULE_NEXUS_OPERATION_FIELD_NUMBER: builtins.int REQUEST_CANCEL_NEXUS_OPERATION_FIELD_NUMBER: builtins.int + APPEND_TO_STREAM_FIELD_NUMBER: builtins.int + READ_STREAM_FIELD_NUMBER: builtins.int @property def user_metadata(self) -> temporalio.api.sdk.v1.user_metadata_pb2.UserMetadata: """User metadata that may or may not be persisted into history depending on the command type. @@ -181,6 +184,10 @@ class WorkflowCommand(google.protobuf.message.Message): def request_cancel_nexus_operation( self, ) -> global___RequestCancelNexusOperation: ... + @property + def append_to_stream(self) -> global___AppendToStream: ... + @property + def read_stream(self) -> global___ReadStream: ... def __init__( self, *, @@ -219,10 +226,14 @@ class WorkflowCommand(google.protobuf.message.Message): schedule_nexus_operation: global___ScheduleNexusOperation | None = ..., request_cancel_nexus_operation: global___RequestCancelNexusOperation | None = ..., + append_to_stream: global___AppendToStream | None = ..., + read_stream: global___ReadStream | 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", @@ -239,6 +250,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", @@ -276,6 +289,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", @@ -294,6 +309,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", @@ -354,6 +371,8 @@ class WorkflowCommand(google.protobuf.message.Message): "update_response", "schedule_nexus_operation", "request_cancel_nexus_operation", + "append_to_stream", + "read_stream", ] | None ): ... @@ -632,6 +651,7 @@ class ScheduleLocalActivity(google.protobuf.message.Message): LOCAL_RETRY_THRESHOLD_FIELD_NUMBER: builtins.int CANCELLATION_TYPE_FIELD_NUMBER: builtins.int INCLUDE_ARGUMENTS_IN_MARKER_FIELD_NUMBER: builtins.int + LOCAL_ACTIVITY_ORIGIN_FIELD_NUMBER: builtins.int seq: builtins.int """Lang's incremental sequence number, used as the operation identifier""" activity_id: builtins.str @@ -708,6 +728,12 @@ class ScheduleLocalActivity(google.protobuf.message.Message): core. Defaults to 1 minute. """ + @property + def local_activity_origin( + self, + ) -> temporalio.bridge.proto.common.common_pb2.LocalActivityOrigin: + """A timer-backed retry echoes the origin from DoBackoff. Leave unset on the first schedule.""" + def __init__( self, *, @@ -731,10 +757,14 @@ class ScheduleLocalActivity(google.protobuf.message.Message): local_retry_threshold: google.protobuf.duration_pb2.Duration | None = ..., cancellation_type: global___ActivityCancellationType.ValueType = ..., include_arguments_in_marker: builtins.bool = ..., + local_activity_origin: temporalio.bridge.proto.common.common_pb2.LocalActivityOrigin + | None = ..., ) -> None: ... def HasField( self, field_name: typing.Literal[ + "local_activity_origin", + b"local_activity_origin", "local_retry_threshold", b"local_retry_threshold", "original_schedule_time", @@ -766,6 +796,8 @@ class ScheduleLocalActivity(google.protobuf.message.Message): b"headers", "include_arguments_in_marker", b"include_arguments_in_marker", + "local_activity_origin", + b"local_activity_origin", "local_retry_threshold", b"local_retry_threshold", "original_schedule_time", @@ -1931,3 +1963,146 @@ 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 as the Workflow Producer and returns ResolveStreamAppend. A retry of a task + whose append has no result in History can write the batch again. Core sends appends to each + Stream in command order. + + An empty Store name selects the runtime under the empty name, or the only runtime if there + is no such entry. Invalid seq or Stream references, missing runtimes and a Store outage at + the task heartbeat fail the Workflow Task. Invalid batches return a failed job. + + Lang must accept results for appends it no longer awaits. The terminal Workflow command drops + unresolved appends. Replay matches seq and Stream and uses the result in History. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + 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.sdk.v1.stream_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.sdk.v1.stream_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 ReadStream(google.protobuf.message.Message): + """Reads one page after after_offset. A reader continues after the last Record it received until + an application Record tells it to stop. + ResolveStreamRead follows the ordering of ResolveStreamAppend. + + A page returns as soon as Records are available. After an empty page Core polls from the same + offset at most once per 100 ms until wait expires or the task reaches its read time. + StreamSettings.read_time defaults to half the task timeout and starts when replay ends. + An empty page reports wait_cut when the task read time shortens the wait. + + Before completing a task, Core checks unanswered reads with a nonblocking Store call and a + one-second deadline. If the task has a command or a server message, it waits only for this check. + Core carries available Records into the next task when a command must go first. An empty + blocking read resumes on a later task. An idle Stream alone does not request another task. + A nonblocking read can return an empty page in the current task, even after the read deadline. + + Each task delivers at most 16 MiB of encoded Records. After 256 read results, new reads wait + for the next task. Reads already running can finish. A single Record over 16 MiB gives a failed + job with stream_unsupported. A Store outage or an unanswered check fails the Workflow Task with + StreamStoreUnavailable. Lang must accept results it no longer awaits. The terminal Workflow + command drops unresolved reads. + + Replay matches seq, Stream and after_offset. It rereads the recorded range and verifies the + Record count and digest. Retention must cover Workflow replay and later queries. Missing or + changed Records give a StreamReplay error. A missing runtime or unavailable Store fails the + Workflow Task, or the legacy query. Replay loads History in parts. The Store selection rules + are the same as for AppendToStream. + + Negative limits or wait, an offset over 1024 bytes, or an invalid seq or Stream reference + fail the Workflow Task. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + STREAM_FIELD_NUMBER: builtins.int + AFTER_OFFSET_FIELD_NUMBER: builtins.int + WAIT_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.""" + after_offset: builtins.bytes + """The page has the Records after this offset. If it's empty, the page starts at the beginning + of the Stream. + """ + max_records: builtins.int + """The maximum number of Records in the page, which is 256 if this is zero.""" + max_bytes: builtins.int + """Page size in encoded Record bytes. Zero selects 4 MiB. A single Record may exceed this + request limit up to the Workflow Task limit of 16 MiB. + """ + @property + def stream(self) -> temporalio.api.sdk.v1.stream_pb2.StreamRef: ... + @property + def wait(self) -> google.protobuf.duration_pb2.Duration: + """How long the read waits for a Record if the Stream has none after `after_offset`. If it's + unset, the read doesn't wait. + """ + + def __init__( + self, + *, + seq: builtins.int = ..., + stream: temporalio.api.sdk.v1.stream_pb2.StreamRef | None = ..., + after_offset: builtins.bytes = ..., + wait: google.protobuf.duration_pb2.Duration | None = ..., + 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[ + "after_offset", + b"after_offset", + "max_bytes", + b"max_bytes", + "max_records", + b"max_records", + "seq", + b"seq", + "stream", + b"stream", + "wait", + b"wait", + ], + ) -> None: ... + +global___ReadStream = ReadStream diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index a5ca9a551e..25a88045ec 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit a5ca9a551e3ca10acb6b2d3194eb65bdc3aa6a3a +Subproject commit 25a88045ecf67787c7f0f0e8b336b2f32c45636b diff --git a/temporalio/bridge/src/lib.rs b/temporalio/bridge/src/lib.rs index 867da998ec..63fae3d88e 100644 --- a/temporalio/bridge/src/lib.rs +++ b/temporalio/bridge/src/lib.rs @@ -6,6 +6,7 @@ mod client_rpc_generated; mod envconfig; mod metric; mod runtime; +mod streams; mod testing; mod worker; diff --git a/temporalio/bridge/src/streams.rs b/temporalio/bridge/src/streams.rs new file mode 100644 index 0000000000..db53e68629 --- /dev/null +++ b/temporalio/bridge/src/streams.rs @@ -0,0 +1,227 @@ +use futures::future::BoxFuture; +use prost::Message; +use pyo3::exceptions::asyncio::CancelledError; +use pyo3::exceptions::PyValueError; +use pyo3::prelude::*; +use pyo3::sync::PyOnceLock; +use pyo3::types::{PyBytes, PyType}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError}; +use std::time::Duration; +use temporalio_sdk_core::StreamRuntimes; +use temporalio_streams::proto::{ + AppendRecordsRequest, AppendRecordsResponse, CreateStreamRequest, CreateStreamResponse, + DescribeStreamRequest, DescribeStreamResponse, ReadRecordsRequest, ReadRecordsResponse, +}; +use temporalio_streams::record::StoreLimits; +use temporalio_streams::{ + AppendError, CreateError, DescribeError, ReadError, StreamError, StreamRuntime, StreamStore, + WireReason, +}; + +struct PythonStore { + caller: Py, + event_loop_task_locals: Arc>, +} + +enum CallState { + Pending, + Running(Py), + Dropped, + Done, +} + +// Release this lock before acquiring the GIL to avoid a deadlock with `OnTask`. +fn lock(state: &Mutex) -> MutexGuard<'_, CallState> { + state.lock().unwrap_or_else(PoisonError::into_inner) +} + +#[pyclass] +struct OnTask { + state: Arc>, +} + +#[pymethods] +impl OnTask { + fn __call__(&self, task: Py) -> PyResult<()> { + let mut state = lock(&self.state); + if matches!(*state, CallState::Dropped) { + drop(state); + return Err(CancelledError::new_err(())); + } + *state = CallState::Running(task); + Ok(()) + } +} + +// Dropping a Core future must also stop its Python Store task. +struct CallGuard<'a> { + state: Arc>, + task_locals: &'a pyo3_async_runtimes::TaskLocals, +} + +impl Drop for CallGuard<'_> { + fn drop(&mut self) { + let state = std::mem::replace(&mut *lock(&self.state), CallState::Dropped); + if let CallState::Running(task) = state { + // `asyncio` requires cross-thread cancellation to run through its event loop. + let _ = Python::try_attach(|py| { + let cancel = task.getattr(py, "cancel")?; + let event_loop = self.task_locals.event_loop(py); + event_loop.call_method1("call_soon_threadsafe", (cancel,))?; + PyResult::Ok(()) + }); + } + } +} + +impl PythonStore { + async fn call( + &self, + operation: &'static str, + request: Request, + request_id: Option, + ) -> Result> + where + Request: Message, + Response: Message + Default, + R: WireReason, + { + let Some(task_locals) = self.event_loop_task_locals.get() else { + return Err(StreamError::store_unavailable( + "The Worker hasn't set the event loop of its Stream Stores yet", + )); + }; + let state = Arc::new(Mutex::new(CallState::Pending)); + let _guard = CallGuard { + state: state.clone(), + task_locals, + }; + let called = Python::try_attach(|py| { + let on_task = OnTask { + state: state.clone(), + }; + let request = PyBytes::new(py, &request.encode_to_vec()); + let arguments = (operation, request, request_id, on_task); + let coroutine = (self.caller.bind(py)).call_method1("call", arguments)?; + pyo3_async_runtimes::into_future_with_locals(task_locals, coroutine) + }); + let answer = match called { + Some(Ok(answer)) => answer.await, + Some(Err(err)) => Err(err), + None => return Err(interpreter_gone(operation)), + }; + let done = Python::try_attach(|py| { + let _task = std::mem::replace(&mut *lock(&state), CallState::Done); + match answer { + Ok(response) => (response.bind(py).cast::().ok()) + .and_then(|bytes| Response::decode(bytes.as_bytes()).ok()) + .ok_or_else(|| { + StreamError::store_corrupt(format!( + "The Store didn't answer the {operation} call with its encoded \ + response message" + )) + }), + Err(err) => Err(store_error(py, err)), + } + }); + done.unwrap_or_else(|| Err(interpreter_gone(operation))) + } +} + +fn interpreter_gone(operation: &str) -> StreamError { + StreamError::store_unavailable(format!( + "The Python interpreter is shutting down, so the Store can't take the {operation} call" + )) +} + +// Only Store refusals retain their reason. Other exceptions can be retried. +fn store_error(py: Python<'_>, err: PyErr) -> StreamError { + let refusal = || -> PyResult> { + let value = err.value(py); + if !value.is_instance(stream_error_type(py)?)? { + return Ok(None); + } + let reason = value.getattr("reason")?.extract()?; + Ok(Some((reason, value.getattr("message")?.extract()?))) + }; + match refusal() { + Ok(Some((reason, message))) => StreamError::from_wire(reason, message), + _ => StreamError::store_unavailable(err.to_string()), + } +} + +fn stream_error_type(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> { + static STREAM_ERROR: PyOnceLock> = PyOnceLock::new(); + STREAM_ERROR.import(py, "temporalio.exceptions", "StreamError") +} + +impl StreamStore for PythonStore { + fn create_stream( + &self, + request: CreateStreamRequest, + request_id: String, + ) -> BoxFuture<'_, Result> { + Box::pin(self.call("CreateStream", request, Some(request_id))) + } + + fn append_records( + &self, + request: AppendRecordsRequest, + request_id: String, + ) -> BoxFuture<'_, Result> { + Box::pin(self.call("AppendRecords", request, Some(request_id))) + } + + fn read_records( + &self, + request: ReadRecordsRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(self.call("ReadRecords", request, None)) + } + + fn describe_stream( + &self, + request: DescribeStreamRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(self.call("DescribeStream", request, None)) + } +} + +fn store_limits( + (max_record_bytes, max_batch_bytes, max_batch_records): (usize, usize, usize), +) -> PyResult { + StoreLimits::default() + .with_max_record_bytes(max_record_bytes) + .and_then(|limits| limits.with_max_batch_bytes(max_batch_bytes)) + .and_then(|limits| limits.with_max_batch_records(max_batch_records)) + .map_err(|err| PyValueError::new_err(err.message)) +} + +#[derive(FromPyObject)] +pub(crate) struct WorkerStreams { + limits: Option<(usize, usize, usize)>, + stores: Vec<(String, Py)>, + read_time_millis: Option, +} + +impl WorkerStreams { + pub(crate) fn into_runtimes( + self, + task_locals: &Arc>, + ) -> PyResult { + let limits = (self.limits.map(store_limits).transpose()?).unwrap_or_default(); + let runtimes = self.stores.into_iter().map(|(name, caller)| { + let store = PythonStore { + caller, + event_loop_task_locals: task_locals.clone(), + }; + let runtime = StreamRuntime::new(Arc::new(store), limits); + (name, Arc::new(runtime)) + }); + let mut runtimes = StreamRuntimes::new(runtimes); + if let Some(millis) = self.read_time_millis { + runtimes.settings.read_time = Some(Duration::from_millis(millis)); + } + Ok(runtimes) + } +} diff --git a/temporalio/bridge/src/worker.rs b/temporalio/bridge/src/worker.rs index 46b6c00de9..335fa0e8a1 100644 --- a/temporalio/bridge/src/worker.rs +++ b/temporalio/bridge/src/worker.rs @@ -5,7 +5,7 @@ use prost::Message; use pyo3::exceptions::{PyException, PyRuntimeError, PyValueError}; use pyo3::prelude::*; use pyo3::types::{PyBytes, PyTuple}; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::marker::PhantomData; use std::sync::{Arc, OnceLock}; use std::time::Duration; @@ -27,6 +27,7 @@ use tracing::error; use crate::client; use crate::runtime; +use crate::streams::WorkerStreams; pyo3::create_exception!(temporal_sdk_bridge, PollShutdownError, PyException); @@ -65,6 +66,9 @@ pub struct WorkerConfig { plugins: Vec<(String, String)>, storage_drivers: HashSet, disable_payload_error_limit: bool, + streams: WorkerStreams, + stream_replay_as_workflow_fail: bool, + stream_replay_as_workflow_fail_for_types: HashSet, } #[derive(FromPyObject)] @@ -522,7 +526,11 @@ pub fn new_replay_worker<'a>( runtime_ref .runtime .assert_same_process("create replay worker")?; - let event_loop_task_locals = Arc::new(OnceLock::new()); + // A replay Worker gets no `validate` call, and a replay reads its Python Stores on the + // loop that created it. + let event_loop_task_locals = Arc::new(OnceLock::from( + pyo3_async_runtimes::TaskLocals::with_running_loop(py)?.copy_context(py)?, + )); let config = convert_worker_config(config, event_loop_task_locals.clone())?; let (history_pusher, stream) = HistoryPusher::new(runtime_ref.runtime.clone()); let worker = WorkerRef { @@ -532,7 +540,7 @@ pub fn new_replay_worker<'a>( PyValueError::new_err(format!("Failed creating replay worker: {err}")) })?, )), - event_loop_task_locals: Default::default(), + event_loop_task_locals, runtime: runtime_ref.runtime.clone(), }; PyTuple::new( @@ -720,6 +728,23 @@ fn convert_worker_config( conf: WorkerConfig, task_locals: Arc>, ) -> PyResult { + let stream_runtimes = conf.streams.into_runtimes(&task_locals)?; + let mut failure_errors = HashSet::new(); + if conf.nondeterminism_as_workflow_fail { + failure_errors.insert(WorkflowErrorType::Nondeterminism); + } + if conf.stream_replay_as_workflow_fail { + failure_errors.insert(WorkflowErrorType::StreamReplay); + } + let mut type_failure_errors = HashMap::>::new(); + for workflow_type in conf.nondeterminism_as_workflow_fail_for_types { + let errors = type_failure_errors.entry(workflow_type).or_default(); + errors.insert(WorkflowErrorType::Nondeterminism); + } + for workflow_type in conf.stream_replay_as_workflow_fail_for_types { + let errors = type_failure_errors.entry(workflow_type).or_default(); + errors.insert(WorkflowErrorType::StreamReplay); + } let converted_tuner = convert_tuner_holder(conf.tuner, task_locals)?; let converted_versioning_strategy = convert_versioning_strategy(conf.versioning_strategy); temporalio_sdk_core::WorkerConfig::builder() @@ -751,22 +776,8 @@ fn convert_worker_config( // auto-cancel-activity behavior of shutdown will not occur, so we // always set it even if 0. .graceful_shutdown_period(Duration::from_millis(conf.graceful_shutdown_period_millis)) - .workflow_failure_errors(if conf.nondeterminism_as_workflow_fail { - HashSet::from([WorkflowErrorType::Nondeterminism]) - } else { - HashSet::new() - }) - .workflow_types_to_failure_errors( - conf.nondeterminism_as_workflow_fail_for_types - .iter() - .map(|s| { - ( - s.to_owned(), - HashSet::from([WorkflowErrorType::Nondeterminism]), - ) - }) - .collect(), - ) + .workflow_failure_errors(failure_errors) + .workflow_types_to_failure_errors(type_failure_errors) .maybe_nexus_task_poller_behavior(conf.nexus_task_poller_behavior.map(Into::into)) .plugins( conf.plugins @@ -781,6 +792,7 @@ fn convert_worker_config( .collect::>(), ) .disable_payload_error_limit(conf.disable_payload_error_limit) + .stream_runtimes(stream_runtimes) .build() .map_err(|err| PyValueError::new_err(format!("Invalid worker config: {err}"))) } diff --git a/temporalio/bridge/streams.py b/temporalio/bridge/streams.py new file mode 100644 index 0000000000..daf43c3cb6 --- /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, Sequence +from dataclasses import dataclass +from typing import Any, Protocol + + +class StoreCaller(Protocol): + """What SDK Core calls to reach a Stream Store that is a Python object.""" + + async def call( + self, + operation: str, + request: bytes, + request_id: str | None, + on_task: Callable[[asyncio.Task[Any]], None], + ) -> bytes: + """Call the Store for a Stream operation with its encoded request, and + return its encoded response. + + ``request_id`` is that of a create or an append, and ``None`` for the + other operations. + """ + ... + + +@dataclass +class WorkerStreams: + """Python representation of the Rust struct for the Stream Stores of a worker.""" + + limits: tuple[int, int, int] | None + """The ``max_record_bytes``, the ``max_batch_bytes`` and the ``max_batch_records`` + of the Stream config, or ``None`` with no Stream config.""" + stores: Sequence[tuple[str, StoreCaller]] + """The caller of each Stream Store that Workflow code can use, by Store name.""" + read_time_millis: int | None diff --git a/temporalio/bridge/worker.py b/temporalio/bridge/worker.py index fa5f337ca7..c5f6eb8a6c 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 @@ -29,7 +30,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 @@ -60,6 +64,9 @@ class WorkerConfig: plugins: Sequence[tuple[str, str]] storage_drivers: set[str] disable_payload_error_limit: bool + streams: temporalio.bridge.streams.WorkerStreams + stream_replay_as_workflow_fail: bool + stream_replay_as_workflow_fail_for_types: set[str] @dataclass @@ -315,14 +322,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 +371,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 +380,7 @@ async def encode_completion( completion, ) - await CommandAwarePayloadVisitor( + await StoragePayloadVisitor( skip_search_attributes=True, skip_headers=not encode_headers, ).visit( 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/_client.py b/temporalio/client/_client.py index 18c9d27a58..c1db740e79 100644 --- a/temporalio/client/_client.py +++ b/temporalio/client/_client.py @@ -14,6 +14,7 @@ TYPE_CHECKING, Any, Concatenate, + TypeVar, cast, overload, ) @@ -29,6 +30,11 @@ import temporalio.runtime import temporalio.service import temporalio.workflow +from temporalio.nexus.system.stream_service import StreamIdConflictPolicy, StreamRef +from temporalio.nexus.system.stream_service.client import ( + Stream, + StreamServiceClientExtension, +) from temporalio.service import ( ConnectConfig, DnsLoadBalancingConfig, @@ -95,6 +101,7 @@ ScheduleBackfill, ScheduleHandle, ) +from ._stream_store import StreamConfig from ._worker_versioning import ( BuildIdOp, TaskReachabilityType, @@ -114,6 +121,25 @@ from ._interceptor import Interceptor from ._plugin import Plugin +_BodyT = TypeVar("_BodyT") + + +class _StreamCalls(StreamServiceClientExtension): + """Starts the Stream operations of a client, so that the generated extension + stays out of the bases of :py:class:`Client`. + """ + + def __init__(self, client: Client) -> None: + self._client = client + + def create_nexus_client( + self, + service: type[NexusServiceType] | str, + endpoint: str, + ) -> NexusClient[NexusServiceType]: + """Return the Nexus client of the client.""" + return self._client.create_nexus_client(service, endpoint) + class Client: """Client for accessing Temporal. @@ -157,6 +183,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. @@ -226,6 +253,13 @@ 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`. + + .. warning:: + This API is experimental and subject to change. """ connect_config = temporalio.service.ConnectConfig( target_host=target_host, @@ -263,6 +297,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__( @@ -276,6 +311,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. @@ -290,6 +326,7 @@ 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() self._stream_producer_id = str(uuid.uuid4()) @@ -2874,6 +2911,114 @@ def create_nexus_client( """ return _NexusClient(client=self, service=service, endpoint=endpoint) + @overload + async def create_stream( + self, + *, + id: str, + store: str | None = None, + id_conflict_policy: StreamIdConflictPolicy | None = None, + body_type: type[_BodyT], + rpc_metadata: Mapping[str, str | bytes] | None = None, + rpc_timeout: timedelta | None = None, + ) -> Stream[_BodyT]: ... + + @overload + async def create_stream( + self, + *, + id: str, + store: str | None = None, + id_conflict_policy: StreamIdConflictPolicy | None = None, + body_type: None = None, + rpc_metadata: Mapping[str, str | bytes] | None = None, + rpc_timeout: timedelta | None = None, + ) -> Stream[object]: ... + + async def create_stream( + self, + *, + id: str, + store: str | None = None, + id_conflict_policy: StreamIdConflictPolicy | None = None, + body_type: Any = None, + rpc_metadata: Mapping[str, str | bytes] | None = None, + rpc_timeout: timedelta | None = None, + ) -> Stream[Any]: + """Create a Stream on a Store of the client's ``stream_config``. + + .. warning:: + This API is experimental and unstable. + + Args: + id: The Stream id. It must not be empty. + store: The name of the Store. If empty, the client uses its Store + selector or its only Store. + id_conflict_policy: What the create does if the Stream already exists. + Unspecified means fail. + body_type: The type of the Record bodies. ``None`` means any type. + rpc_metadata: Passed to the interceptor hooks. A Store call doesn't use + it. + rpc_timeout: How long the Store has to answer. + + Returns: + The handle of the Stream. + """ + return await _StreamCalls(self).create_stream( + id=id, + store=store, + id_conflict_policy=id_conflict_policy, + body_type=body_type, + rpc_metadata=rpc_metadata, + rpc_timeout=rpc_timeout, + ) + + @overload + def get_stream( + self, + ref: StreamRef[_BodyT], + *, + created: bool | None = None, + body_type: None = None, + ) -> Stream[_BodyT]: ... + + @overload + def get_stream( + self, + ref: StreamRef[_BodyT] | StreamRef[object], + *, + created: bool | None = None, + body_type: type[_BodyT], + ) -> Stream[_BodyT]: ... + + def get_stream( + self, + ref: StreamRef[Any], + *, + created: bool | None = None, + body_type: Any = None, + ) -> Stream[Any]: + """Return the handle of the Stream of ``ref``, with no call. + + .. warning:: + This API is experimental and unstable. + + Args: + ref: The ref of the Stream. A typed ref, such as ``StreamRef[str]``, + gives the type of the Record bodies. + created: The ``created`` value of the handle. ``None`` means unknown. + body_type: The type of the Record bodies. ``None`` means the type of a + typed ref, else ``object``. With a typed ref other than + ``StreamRef[object]``, it must be the type of the ref. + + Returns: + The handle of the Stream. + + Raises: + TypeError: ``body_type`` differs from the type of a typed ref. + """ + return _StreamCalls(self).get_stream(ref, created=created, body_type=body_type) + def list_nexus_operations( self, query: str, @@ -3031,6 +3176,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): @@ -3045,3 +3191,4 @@ class ClientConfig(TypedDict, total=False): temporalio.common.QueryRejectCondition | None ] header_codec_behavior: Required[HeaderCodecBehavior] + stream_config: Required[StreamConfig | None] diff --git a/temporalio/client/_impl.py b/temporalio/client/_impl.py index e6424c15eb..8d681198d5 100644 --- a/temporalio/client/_impl.py +++ b/temporalio/client/_impl.py @@ -42,10 +42,14 @@ StorageDriverWorkflowInfo, WorkflowSerializationContext, ) +from temporalio.nexus.system.stream_service.client._system_nexus_interceptor import ( + _SystemNexusClientOutboundInterceptorTerminal, +) from temporalio.service import ( RPCError, RPCStatusCode, ) +from temporalio.types import ReturnType from ..common import HeaderCodecBehavior from ._activity import ( @@ -126,6 +130,7 @@ ScheduleUpdate, ScheduleUpdateInput, ) +from ._stream_store import _STREAM_SERVICE, _call_stream_store from ._worker_versioning import WorkerBuildIdVersionSets, WorkerTaskReachability from ._workflow import ( WorkflowExecutionAsyncIterator, @@ -142,7 +147,9 @@ from ._client import Client -class _ClientImpl(OutboundInterceptor): # pyright: ignore[reportUnusedClass] +class _ClientImpl( # pyright: ignore[reportUnusedClass] + _SystemNexusClientOutboundInterceptorTerminal, OutboundInterceptor +): def __init__(self, client: Client) -> None: # type: ignore # We are intentionally not calling the base class's __init__ here self._client = client @@ -1577,6 +1584,14 @@ async def get_worker_task_reachability( ### Nexus operation calls + async def _start_system_nexus_operation( + self, + input: StartNexusOperationInput[Any, ReturnType], + ) -> NexusOperationHandle[ReturnType]: + if input.service != _STREAM_SERVICE.name: + raise ValueError(f"unsupported System Nexus service: {input.service}") + return await _call_stream_store(self._client, input) + async def start_nexus_operation( self, input: StartNexusOperationInput ) -> NexusOperationHandle[Any]: diff --git a/temporalio/client/_interceptor.py b/temporalio/client/_interceptor.py index 75463b4971..26bb8a1659 100644 --- a/temporalio/client/_interceptor.py +++ b/temporalio/client/_interceptor.py @@ -2,24 +2,31 @@ from __future__ import annotations +import uuid from collections.abc import ( Awaitable, Callable, Mapping, Sequence, ) -from dataclasses import dataclass +from dataclasses import dataclass, field from datetime import timedelta from typing import ( TYPE_CHECKING, Any, + Generic, ) +from typing_extensions import TypeVar + import temporalio.api.common.v1 import temporalio.api.workflowservice.v1 import temporalio.common import temporalio.nexus from temporalio.converter import DataConverter +from temporalio.nexus.system.stream_service.client._system_nexus_interceptor import ( + _SystemNexusClientOutboundInterceptorBase, +) if TYPE_CHECKING: from ._activity import ( @@ -584,20 +591,27 @@ class GetWorkerTaskReachabilityInput: rpc_timeout: timedelta | None +_NexusInputT = TypeVar("_NexusInputT", default=Any) +_NexusOutputT = TypeVar("_NexusOutputT", default=Any) + + @dataclass -class StartNexusOperationInput: +class StartNexusOperationInput(Generic[_NexusInputT, _NexusOutputT]): """Input for :py:meth:`OutboundInterceptor.start_nexus_operation`. + Type parameters describe the operation argument and result. Operation-specific + Stream hooks use them to type the envelope without unpacking its call options. + .. warning:: This API is experimental and unstable. """ operation: str - arg: Any + arg: _NexusInputT id: str endpoint: str service: str - result_type: type | None + result_type: type[_NexusOutputT] | None schedule_to_close_timeout: timedelta | None schedule_to_start_timeout: timedelta | None start_to_close_timeout: timedelta | None @@ -609,6 +623,10 @@ class StartNexusOperationInput: rpc_metadata: Mapping[str, str | bytes] rpc_timeout: timedelta | None completion_callbacks: Sequence[temporalio.nexus.CompletionCallback[Any]] = () + # Interceptors can retry a Store write with a copy of this input after losing its answer. + _stream_request_id: uuid.UUID = field( + default_factory=uuid.uuid4, repr=False, compare=False, kw_only=True + ) @dataclass @@ -722,10 +740,17 @@ def intercept_client(self, next: OutboundInterceptor) -> OutboundInterceptor: return next -class OutboundInterceptor: +class OutboundInterceptor(_SystemNexusClientOutboundInterceptorBase): """OutboundInterceptor for intercepting client calls. This should be extended by any client outbound interceptors. + + Stream calls use the ``start_create_stream``, ``start_append_records``, + ``start_read_records``, and ``start_describe_stream`` hooks, taking a typed + :py:class:`StartNexusOperationInput` and returning a + :py:class:`NexusOperationHandle`. They do not call the generic Nexus start or + result hooks. Reuse the input, or a dataclass copy of it, when retrying so the + Store can deduplicate a write whose response was lost. """ def __init__(self, next: OutboundInterceptor) -> None: @@ -737,6 +762,11 @@ def __init__(self, next: OutboundInterceptor) -> None: """ self.next = next + def _next_system_nexus_interceptor( + self, + ) -> _SystemNexusClientOutboundInterceptorBase: + return self.next + ### Workflow calls async def start_workflow( diff --git a/temporalio/client/_nexus.py b/temporalio/client/_nexus.py index fa22c11c24..1b55c92264 100644 --- a/temporalio/client/_nexus.py +++ b/temporalio/client/_nexus.py @@ -17,6 +17,10 @@ import temporalio.converter._search_attributes import temporalio.exceptions import temporalio.nexus._util +import temporalio.nexus.system +from temporalio.nexus.system.stream_service.client._system_nexus_interceptor import ( + _start_system_nexus_operation, +) from temporalio.types import NexusServiceType, ReturnType from ._helpers import _decode_user_metadata @@ -28,6 +32,7 @@ StartNexusOperationInput, TerminateNexusOperationInput, ) +from ._stream_store import _STREAM_SERVICE if TYPE_CHECKING: from ._client import Client @@ -1098,27 +1103,32 @@ async def start_operation( result_type if isinstance(operation, str) else output_type ) - return await self._client._impl.start_nexus_operation( - StartNexusOperationInput( - operation=op_name, - arg=arg, - id=id, - endpoint=self._endpoint, - service=self._service_name, - result_type=final_result_type, - schedule_to_close_timeout=schedule_to_close_timeout, - schedule_to_start_timeout=schedule_to_start_timeout, - start_to_close_timeout=start_to_close_timeout, - id_reuse_policy=id_reuse_policy, - id_conflict_policy=id_conflict_policy, - search_attributes=search_attributes, - summary=summary, - headers=dict(headers) if headers else {}, - rpc_metadata=rpc_metadata, - rpc_timeout=rpc_timeout, - completion_callbacks=completion_callbacks, - ) + input = StartNexusOperationInput( + operation=op_name, + arg=arg, + id=id, + endpoint=self._endpoint, + service=self._service_name, + result_type=final_result_type, + schedule_to_close_timeout=schedule_to_close_timeout, + schedule_to_start_timeout=schedule_to_start_timeout, + start_to_close_timeout=start_to_close_timeout, + id_reuse_policy=id_reuse_policy, + id_conflict_policy=id_conflict_policy, + search_attributes=search_attributes, + summary=summary, + headers=dict(headers) if headers else {}, + rpc_metadata=rpc_metadata, + rpc_timeout=rpc_timeout, + completion_callbacks=completion_callbacks, ) + # Stream operations use their typed hooks, not the generic Nexus chain. + if ( + temporalio.nexus.system.is_system_endpoint(input.endpoint) + and input.service == _STREAM_SERVICE.name + ): + return await _start_system_nexus_operation(self._client._impl, input) + return await self._client._impl.start_nexus_operation(input) async def execute_operation( self, diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py new file mode 100644 index 0000000000..fbbb587b75 --- /dev/null +++ b/temporalio/client/_stream_store.py @@ -0,0 +1,819 @@ +"""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, field +from datetime import timedelta +from typing import Any + +import google.protobuf.message +import nexusrpc + +import temporalio.api.sdk.v1 as sdk + +# pydoctor reads this module before the client package, for the worker modules that +# import it. A `from` import of a sibling here would lose the package's re-exports. +import temporalio.client +import temporalio.nexus.system._support +from temporalio.api.enums.v1 import StreamErrorReason, StreamIdConflictPolicy +from temporalio.api.stream.v1 import ( + LocalActivityProducer, + StandaloneActivityProducer, + WorkflowActivityProducer, + WorkflowProducer, + WorkflowTaskAttempt, +) +from temporalio.api.streamservice.v1 import ( + AppendRecordsRequest, + AppendRecordsResponse, + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, +) +from temporalio.converter import PayloadCodec +from temporalio.converter._payload_converter import _get_transfer_type_converter +from temporalio.exceptions import StreamError +from temporalio.nexus.system.stream_service import StreamService +from temporalio.types import ReturnType + +logger = logging.getLogger(__name__) + +_definition = nexusrpc.get_service_definition(StreamService) +assert _definition +_STREAM_SERVICE: nexusrpc.ServiceDefinition = _definition + +_READ_ANSWER_TIME = timedelta(seconds=1) +"""The time that a client read leaves its Store to answer before the +``rpc_timeout``. A tenth of a shorter timeout is used instead.""" + + +class StreamStore(ABC): + """Base class for a Store that keeps Stream Records. + + Methods use request and response messages from + :py:mod:`temporalio.api.streamservice.v1`. Requests contain a Stream id. + The SDK routes each ``StreamRef`` to its registered Store and sets the Store + name on refs returned by create. Stores don't read or set ``StreamRef.store``. + + Workflow execution and replay depend on these contracts. + + Retention: + + * Retention starts at create and restarts after an append that writes a batch. + Retries and reads don't extend it. The Store sets the retention period. + * An expired Stream has no Records and rejects calls with ``EXPIRED``. + * Streams have no stored end. Applications use their own terminal Record. + + Records and offsets: + + * Keep each body as received. The payload codec has already encoded it. + * Write each append batch atomically, with contiguous Records in request order. + * Record offsets are nonempty and sort bytewise in Record order. + * After a response returns an offset, no later write can insert a Record at + or below it. This also applies to concurrent writes. + * Keep Records unchanged until the Stream expires. + + Producers and attempts: + + * A Producer identifies a Workflow run, Activity, Local Activity or client. + Its kind and ids determine its identity. + * An attempt identifies a Producer's execution attempt, such as a Workflow + Task or Activity attempt. Every Record retains its Producer and attempt. + * Fencing is optional. A Store that fences rejects an earlier attempt once + a later attempt of that Producer has written to the Stream. + + Reject calls with :py:class:`temporalio.exceptions.StreamError` and its reason. + These docs omit the ``STREAM_ERROR_REASON_`` prefix from reason names. + Other exceptions become ``STORE_UNAVAILABLE`` errors. Workflow append and + read refusals record messages of at most 4 KiB in History. All Stream marker + data in an activation must fit within 1 MiB. Keep messages short to avoid + failing the Workflow Task with ``StreamMarkerTooLarge``. + + Calls can run concurrently on the event loop. Cancellation can follow a + timeout, eviction or Worker shutdown. A cancelled call may have taken effect. + The Store must remain usable, and overlapping retries must not duplicate a + batch. + + SDK Core validates and retries Workflow appends and reads during outages. + Other calls make one attempt. For those calls, the SDK checks each request + with the rules of SDK Core and the append limits from :py:class:`StreamConfig`, + but it doesn't check the answer. Stores must perform any other checks they + require. + + .. warning:: + This API is experimental and subject to change. + """ + + @abstractmethod + def name(self) -> str: + """Return the Store name registered in :py:class:`StreamConfig`. + + The name must remain stable. Separate instances of one Store class can + use different names. + """ + raise NotImplementedError + + @abstractmethod + async def create_stream( + self, request: CreateStreamRequest, *, request_id: str + ) -> CreateStreamResponse: + """Create a Stream, or reuse it if the conflict policy permits. + + Retries use the same ``request_id``. An empty id never identifies a retry. + The response contains only ``created``. + + For an existing Stream, check these conditions in order. + + 1. An expired Stream fails with ``EXPIRED``. + 2. A matching create ``request_id`` returns ``created=True``. + 3. ``USE_EXISTING`` returns ``created=False``. ``FAIL`` or an unset policy + fails with ``ALREADY_EXISTS``. + + Only a new Stream starts retention. Reusing a Stream doesn't extend it. + """ + raise NotImplementedError + + @abstractmethod + async def append_records( + self, request: AppendRecordsRequest, *, request_id: str + ) -> AppendRecordsResponse: + """Append one batch from one Producer. + + Retries of one append use the same ``request_id``. + Retain recent request ids for each Producer, including at least its last + batch. Matching Producer, attempt and ``request_id`` identify a resend. + An empty request id never identifies a resend. + + Check these conditions in order. + + 1. Missing or expired Streams fail with ``NOT_FOUND`` or ``EXPIRED``. + 2. A resend returns the original offsets without comparing or writing + Records. + 3. If fencing is enabled, an attempt older than the latest writer attempt + fails with ``FENCED``. + + Return the first and last Record offsets. Only a new batch extends + retention. A resend doesn't extend it. + """ + raise NotImplementedError + + @abstractmethod + async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: + """Read one page after ``after_offset``, in Stream order. + + * Apply ``max_records`` and ``max_bytes``. Zero uses the Store's default. + Include the first Record even if it exceeds ``max_bytes``. + * The next read starts after the last returned Record. An empty page + leaves ``after_offset`` unchanged. + * If no Records are available, wait until one arrives or ``wait`` expires. + An unset wait returns immediately. The SDK converts zero to an unset + wait. Returning empty pages before a requested wait expires can cause + callers to poll repeatedly. + * Accept any offset returned by a response. Reject ``after_offset`` with + ``OFFSET_TOO_HIGH`` only if it exceeds the end of the Stream. + """ + raise NotImplementedError + + @abstractmethod + async def describe_stream( + self, request: DescribeStreamRequest + ) -> DescribeStreamResponse: + """Return the newest Record's offset, or empty bytes for an empty Stream.""" + raise NotImplementedError + + +@dataclass(frozen=True) +class StreamSelectContext: + """Context passed to :py:attr:`StreamConfig.store_selector` calls. + + .. warning:: + This API is experimental and subject to change. + """ + + id: str + """The id of the Stream of the call.""" + + namespace: str | None = None + """The namespace of the client or Worker that makes the call.""" + + +@dataclass(frozen=True) +class StreamConfig: + """Stream Stores shared by a client and its Workers. + + Appends that exceed :py:attr:`max_record_bytes`, :py:attr:`max_batch_bytes` + or :py:attr:`max_batch_records` fail with ``STREAM_ERROR_REASON_TOO_LARGE`` + before reaching the Store. ``rpc_metadata`` has no effect on Store calls. + + Streams have no close. Retention starts at create and restarts after each + append that writes a batch. Applications use their own terminal Record. + + In client, Activity and Workflow code, ``read`` and ``read_pages`` continue + after empty pages. ``read_pages`` yields those pages. Callers must stop the + iterator, for example with ``break`` or a timeout. An unset ``wait`` makes the + first request immediate. Later requests wait up to one minute. An explicit + wait applies to every request. Zero disables waiting, so an idle Stream can + cause repeated empty reads. ``read_page`` has no default wait. After a page, + the ``read`` iterator's ``next_request`` includes the next request's wait. + + A positive ``rpc_timeout`` caps client and Activity waits below the timeout, + leaving time for the Store to answer. An Activity that heartbeats between + Records needs a wait below its heartbeat timeout, or a separate heartbeat task. + + Workflow calls: + + * The SDK selects a Store before each call, including replay. SDK Core handles + append and read. Create and describe use SDK Local Activities, which pass + through Worker interceptors. + * Appends are at-least-once. A Workflow Task retry can write its batch again. + * Store outages fail the Workflow Task. Workflow code gets no outage error. + * A missing Store fails the Workflow Task even if Workflow code catches the + error. A call not awaited before Workflow completion may not run. + * Workers read the limits at startup. A replacement client must have the same + limits and Store names. + * Pages default to 256 Records and 4 MiB, with a 16 MiB byte cap. A live read + rejects a Record over :py:attr:`max_record_bytes` with + ``STREAM_ERROR_REASON_UNSUPPORTED``. Reader limits must cover writer limits. + Replay accepts recorded successes even if the limits decrease. + * An immediate read can return an empty page. A waiting read stops at its + wait or the Worker's ``stream_read_time`` limit, whichever comes first. + At the task limit, ``read_page`` returns an empty page. + * Iterators can continue across Workflow Tasks. Each page adds a result to + History, so zero or short waits can cause rapid History growth. The default + wait limits empty pages, and an idle Stream doesn't create new tasks. + * A waiting read holds its task and delays Signals until its page or the read + limit. A server command waits for at most one immediate Store call per read, + bounded by one second. + * An unfinished waiting read restarts in the next task. It requests that task + only when Core knows more Records are available. A task returns at most + 256 read results. Later reads start in the next task. + * Replay reads the Records from the Store again. Retention must cover the + Workflow's life and any later replay or query. + * A body that can't convert to the Stream's type fails the Workflow Task. + + .. warning:: + This API is experimental and subject to change. + """ + + stores: Sequence[StreamStore] + """Stores available for Stream calls. At least one Store must be provided, + and each Store must have a unique :py:meth:`StreamStore.name` that isn't + empty. + """ + + store_selector: Callable[[StreamSelectContext], StreamStore] | None = None + """Select the Store for a call whose ``StreamRef`` has no Store name. + + Return an instance from :py:attr:`stores`. A selector is required with + multiple Stores. Without one, the sole Store handles these calls. + + Workflow calls invoke the selector before each command, including creates, + describes and replay. The selector must return the same Store for the same + call, must not block or perform I/O, and must be safe across threads. Core + receives the selected Store name with each command. + + Replayed appends and reads fail with nondeterminism if their selected Store + differs from History. Create and describe use their recorded results. A + created Stream's ref includes its Store name, so later calls skip selection. + """ + + max_record_bytes: int = 1536 * 1024 + """Maximum stored Record size for an append or a live Workflow read. + + Includes its Producer. Defaults to 1.5 MiB and must be at least one. + """ + + max_batch_bytes: int = 4 * 1024 * 1024 + """Maximum size in bytes of the Records of one append, each in its stored + size. Defaults to 4 MiB. Must be greater than or equal to one. + """ + + max_batch_records: int = 1000 + """Maximum number of Records of one append. Defaults to 1000. Must be + greater than or equal to one. + """ + + _by_name: dict[str, StreamStore] = field( + init=False, repr=False, compare=False, default_factory=dict + ) + """Snapshot Store names so later name changes can't change routing.""" + + def __post_init__(self) -> None: + """Validate the Stores and the limits. + + Raises :exc:`ValueError` if no Store is provided, if a limit is less + than one, if more than one Store is registered without a + :py:attr:`store_selector`, if a Store has an empty name, or if any two + Stores have the same name. + """ + if not self.stores: + raise ValueError("StreamConfig.stores must contain at least one Store.") + for limit in ("max_record_bytes", "max_batch_bytes", "max_batch_records"): + if getattr(self, limit) < 1: + raise ValueError( + f"StreamConfig.{limit} must be greater than or equal to one." + ) + if len(self.stores) > 1 and self.store_selector is None: + raise ValueError( + "StreamConfig.store_selector must be specified if multiple Stores " + "are registered." + ) + by_name: dict[str, StreamStore] = {} + for store in self.stores: + name = store.name() + if not name: + raise ValueError( + "StreamConfig.stores contains a Store with an empty name." + ) + if name in by_name: + raise ValueError( + f"StreamConfig.stores contains multiple Stores with name '{name}'. " + "Each Store must have a unique name." + ) + by_name[name] = store + object.__setattr__(self, "_by_name", by_name) + + def _store(self, name: str) -> StreamStore: + store = self._by_name.get(name) + if store is None: + raise ValueError(f"No Stream Store found with name '{name}'") + return store + + def _store_for(self, ref: sdk.StreamRef, namespace: str) -> StreamStore: + if 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, namespace=namespace) + ) + if not any(selected is store for store in self.stores): + raise ValueError( + "Store returned by store_selector is not registered in StreamConfig.stores" + ) + return selected + + def _limits(self) -> tuple[int, int, int]: + return self.max_record_bytes, self.max_batch_bytes, self.max_batch_records + + +def _request_ref(request: google.protobuf.message.Message) -> sdk.StreamRef: + if isinstance(request, sdk.CreateStreamRequest): + return request.stream_ref + assert isinstance( + request, + (sdk.AppendRecordsRequest, sdk.ReadRecordsRequest, sdk.DescribeStreamRequest), + ) + return request.ref + + +_Message = type[google.protobuf.message.Message] + +_STORE_OPERATIONS: dict[str, tuple[str, _Message, _Message]] = { + "CreateStream": ("create_stream", CreateStreamRequest, CreateStreamResponse), + "AppendRecords": ("append_records", AppendRecordsRequest, AppendRecordsResponse), + "ReadRecords": ("read_records", ReadRecordsRequest, ReadRecordsResponse), + "DescribeStream": ( + "describe_stream", + DescribeStreamRequest, + DescribeStreamResponse, + ), +} + + +def _store_operation(name: str) -> tuple[str, _Message, _Message]: + return _STORE_OPERATIONS[name] + + +def _sdk_request_type( # pyright: ignore[reportUnusedFunction] + name: str, +) -> _Message: + operation = _STREAM_SERVICE.operation_definitions[name] + converter = _get_transfer_type_converter(operation.input_type) + assert converter and converter.transfer_type + return converter.transfer_type + + +def _store_request( + request: google.protobuf.message.Message, +) -> google.protobuf.message.Message: + stream_id = _request_ref(request).id + if isinstance(request, sdk.CreateStreamRequest): + return CreateStreamRequest( + stream_id=stream_id, id_conflict_policy=request.id_conflict_policy + ) + if isinstance(request, sdk.AppendRecordsRequest): + append = AppendRecordsRequest(stream_id=stream_id, records=request.records) + if request.HasField("producer"): + append.producer.CopyFrom(request.producer) + return append + if isinstance(request, sdk.ReadRecordsRequest): + read = ReadRecordsRequest( + stream_id=stream_id, + after_offset=request.after_offset, + max_records=request.max_records, + max_bytes=request.max_bytes, + ) + # A Store may take a zero wait as one with no end, such as Redis BLOCK 0. + if request.HasField("wait") and (request.wait.seconds or request.wait.nanos): + read.wait.CopyFrom(request.wait) + return read + return DescribeStreamRequest(stream_id=stream_id) + + +_MAX_STREAM_ID_BYTES = 4096 +"""The maximum length of a Stream id in bytes, as the API of the Stream service +sets it.""" + +_MAX_OFFSET_BYTES = 1024 +"""The maximum length of an offset in bytes. Offsets go into Workflow History.""" + +_MAX_NANOS = 999_999_999 +"""The maximum nanos of a ``Timestamp`` or a ``Duration``, whose whole seconds are +in a separate field.""" + +_MAX_DURATION_SECONDS = 315_576_000_000 +"""The maximum seconds of a protobuf ``Duration``.""" + +_PRODUCER_IDS: dict[str, tuple[tuple[str, str], ...]] = { + "workflow": ( + ("namespace", "namespace"), + ("workflow_id", "Workflow id"), + ("run_id", "run id"), + ("workflow_task_id", "Workflow Task id"), + ), + "local_activity": ( + ("namespace", "namespace"), + ("workflow_id", "Workflow id"), + ("run_id", "run id"), + ("workflow_task_id", "Workflow Task id"), + ("activity_id", "Activity id"), + ), + "workflow_activity": ( + ("namespace", "namespace"), + ("workflow_id", "Workflow id"), + ("run_id", "run id"), + ("activity_id", "Activity id"), + ("scheduled_event_id", "scheduled event id"), + ), + "standalone_activity": ( + ("namespace", "namespace"), + ("activity_id", "Activity id"), + ("run_id", "run id"), + ), + "client": (("namespace", "namespace"), ("id", "client id")), +} +"""The ids of each kind of Producer, with the words of their errors.""" + + +def _check_request( + request: google.protobuf.message.Message, limits: tuple[int, int, int] +) -> None: + """Check a Store request as the Stream runtime of SDK Core checks one. + + ``limits`` are the ``max_record_bytes``, the ``max_batch_bytes`` and the + ``max_batch_records`` of a Stream config. + + Raises: + temporalio.exceptions.StreamError: The check refuses the request. + """ + if isinstance(request, CreateStreamRequest): + _check_stream_id(request.stream_id) + policy = request.id_conflict_policy + if policy not in StreamIdConflictPolicy.values(): + raise _invalid(f"The conflict policy {policy} is unknown") + elif isinstance(request, AppendRecordsRequest): + _check_append(request, *limits) + elif isinstance(request, ReadRecordsRequest): + _check_read(request) + else: + assert isinstance(request, DescribeStreamRequest) + _check_stream_id(request.stream_id) + + +def _check_append( + request: AppendRecordsRequest, + max_record_bytes: int, + max_batch_bytes: int, + max_batch_records: int, +) -> None: + _check_stream_id(request.stream_id) + _check_producer(request) + records = request.records + if not records: + raise _invalid("The batch has no Record") + for at, record in enumerate(records): + if not record.HasField("body"): + raise _invalid(f"Record {at} of the batch has no body") + if len(records) > max_batch_records: + raise _too_large( + f"The batch has {len(records)} Records, more than {max_batch_records}" + ) + # A Record is measured in its stored form, a `StreamRecord` with no offset. + producer_bytes = _field_bytes(request.producer.ByteSize()) + total = 0 + for at, record in enumerate(records): + size = producer_bytes + _field_bytes(record.body.ByteSize()) + if size > max_record_bytes: + raise _too_large( + f"Record {at} of the batch has {size} bytes, more than " + f"{max_record_bytes}" + ) + total += size + if total > max_batch_bytes: + raise _too_large(f"The batch has {total} bytes, more than {max_batch_bytes}") + + +def _check_read(request: ReadRecordsRequest) -> None: + _check_stream_id(request.stream_id) + if len(request.after_offset) > _MAX_OFFSET_BYTES: + raise _invalid( + f"The after_offset of the read has {len(request.after_offset)} bytes, " + f"more than {_MAX_OFFSET_BYTES}" + ) + if request.max_records < 0: + raise _invalid("max_records must be 0 or more") + if request.max_bytes < 0: + raise _invalid("max_bytes must be 0 or more") + if request.HasField("wait"): + wait = request.wait + if wait.seconds < 0 or wait.nanos < 0: + raise _invalid("wait must be 0 or more") + if wait.seconds > _MAX_DURATION_SECONDS or wait.nanos > _MAX_NANOS: + raise _invalid("wait exceeds the protobuf Duration range") + + +def _check_stream_id(stream_id: str) -> None: + if not stream_id: + raise _invalid("The Stream id is empty") + size = len(stream_id.encode()) + if size > _MAX_STREAM_ID_BYTES: + raise _invalid( + f"The Stream id has {size} bytes, more than {_MAX_STREAM_ID_BYTES}" + ) + + +def _check_producer(request: AppendRecordsRequest) -> None: + """Refuse a Producer whose identity or attempt is incomplete, since a Store + keeps the retry state of each Producer and orders its attempts. + """ + if not request.HasField("producer"): + raise _invalid("The request has no Producer") + name = request.producer.WhichOneof("kind") + if name is None: + raise _missing("kind") + kind = getattr(request.producer, name) + for field_name, words in _PRODUCER_IDS[name]: + value = getattr(kind, field_name) + if value == "": + raise _missing(words) + if isinstance(value, int) and value < 0: + raise _invalid(f"The {words} is {value}, and it must be 0 or more") + if isinstance(kind, WorkflowProducer): + if not kind.HasField("attempt"): + raise _missing("Workflow Task attempt") + _check_task(kind.attempt) + elif isinstance(kind, LocalActivityProducer): + if not kind.HasField("attempt"): + raise _missing("attempt") + if not kind.attempt.HasField("task"): + raise _missing("Workflow Task that dispatched it") + _check_task(kind.attempt.task) + _check_attempt_number(kind.attempt.attempt, "Local Activity") + elif isinstance(kind, (WorkflowActivityProducer, StandaloneActivityProducer)): + if not kind.HasField("attempt"): + raise _missing("attempt") + if not kind.attempt.HasField("attempt_scheduled_time"): + raise _missing("attempt scheduled time") + scheduled = kind.attempt.attempt_scheduled_time + _check_time(scheduled.seconds, scheduled.nanos, "attempt scheduled time") + _check_attempt_number(kind.attempt.attempt, "Activity") + + +def _check_task(task: WorkflowTaskAttempt) -> None: + # Tasks are ordered by their started event id first, so an attempt without one + # would sort below every real task. + if task.started_event_id <= 0: + raise _invalid("The Workflow Task attempt has no started event id") + if task.HasField("started_time"): + started = task.started_time + _check_time(started.seconds, started.nanos, "started time of the Workflow Task") + _check_attempt_number(task.attempt, "Workflow Task") + + +def _check_time(seconds: int, nanos: int, time: str) -> None: + # Stores order the attempts of a Producer by these times, and a time before 1970 + # or with a second or more of nanos would sort in the wrong place. + if seconds < 0: + raise _invalid(f"The {time} is before the Unix epoch") + if nanos < 0 or nanos > _MAX_NANOS: + raise _invalid( + f"The {time} has {nanos} nanos, and it must have 0 to {_MAX_NANOS}" + ) + + +def _check_attempt_number(number: int, of: str) -> None: + if number < 1: + raise _invalid(f"The {of} attempt number is {number}, and it must be 1 or more") + + +def _field_bytes(size: int) -> int: + """Return the encoded size of a length-delimited field whose content has + ``size`` bytes. The field number must be below 16, so that its tag is one byte. + """ + return 1 + max(1, (size.bit_length() + 6) // 7) + size + + +def _missing(field_name: str) -> StreamError: + return _invalid(f"The Producer has no {field_name}") + + +def _invalid(message: str) -> StreamError: + return StreamError( + message, reason=StreamErrorReason.STREAM_ERROR_REASON_INVALID_ARGUMENT + ) + + +def _too_large(message: str) -> StreamError: + return StreamError(message, reason=StreamErrorReason.STREAM_ERROR_REASON_TOO_LARGE) + + +async def _call_method( + store: StreamStore, + operation: str, + request: google.protobuf.message.Message, + request_id: str | None, +) -> google.protobuf.message.Message: + """Translate Store exceptions before Core decides whether to retry.""" + method, _, response_type = _store_operation(operation) + call = getattr(store, method) + try: + if request_id is None: + response = await call(request) + else: + response = await call(request, request_id=request_id) + except StreamError: + raise + except Exception as err: + 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 + + +async def _call_store( # pyright: ignore[reportUnusedFunction] + store: StreamStore, + limits: tuple[int, int, int], + codec: PayloadCodec | None, + operation: str, + request: google.protobuf.message.Message, + request_id: str | None, + timeout: timedelta | None = None, +) -> google.protobuf.message.Message: + """Keep client codec and request checks consistent with Workflow calls. + + Records have no serialization context because any client or Workflow can + read them. Each codec call receives one Record body. + """ + store_request = _store_request(request) + if codec and isinstance(store_request, AppendRecordsRequest): + for appended in store_request.records: + # An encoded empty body would hide a Record with no body from the check. + if appended.HasField("body"): + [body] = await codec.encode([appended.body]) + appended.body.CopyFrom(body) + # SDK Core checks the appends and reads of Workflow code the same way, so each + # path refuses the same requests before its Store gets them. + _check_request(store_request, limits) + if ( + isinstance(store_request, ReadRecordsRequest) + and store_request.HasField("wait") + and timeout is not None + and timeout > timedelta(0) + ): + # A wait is only a bound, and a Store that waits all of it must still answer + # before the timeout fails the read. + longest = timeout - min(_READ_ANSWER_TIME, timeout / 10) + if store_request.wait.ToTimedelta() > longest: + store_request.wait.FromTimedelta(longest) + 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, store_request, request_id) + 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) + if isinstance(response, CreateStreamResponse): + # Each later call of the created Stream goes to this Store, whatever the + # selector picks then. + ref = sdk.StreamRef(id=_request_ref(request).id, store=store.name()) + return sdk.CreateStreamResponse(ref=ref, created=response.created) + return response + + +async def _call_stream_store( # pyright: ignore[reportUnusedFunction] + client: temporalio.client.Client, + input: temporalio.client.StartNexusOperationInput[Any, ReturnType], +) -> temporalio.client.NexusOperationHandle[ReturnType]: + stream_config = client._config["stream_config"] + if stream_config is None: + raise ValueError( + "Client has no stream_config, which every Stream call requires." + ) + data_converter = client.data_converter + converters = ( + data_converter.payload_converter, + data_converter.failure_converter, + ) + request = temporalio.nexus.system._support.model_to_proto(input.arg, *converters) + store = stream_config._store_for(_request_ref(request), client.namespace) + request_id = None + if isinstance(request, (sdk.CreateStreamRequest, sdk.AppendRecordsRequest)): + request_id = str(input._stream_request_id) + response = await _call_store( + store, + stream_config._limits(), + data_converter.payload_codec, + input.operation, + request, + request_id, + input.rpc_timeout, + ) + result_type = ( + input.result_type + or _STREAM_SERVICE.operation_definitions[input.operation].output_type + ) + handle: temporalio.client.NexusOperationHandle[ReturnType] = ( + temporalio.client.NexusOperationHandle( + client, + input.id, + result_type=result_type, + endpoint=input.endpoint, + service=input.service, + operation=input.operation, + ) + ) + handle._known_outcome = temporalio.nexus.system._support.model_from_proto( + response, result_type, *converters + ) + return handle + + +class _StoreCaller: # pyright: ignore[reportUnusedClass] + """Keep Store calls on the Python event loop so Core can cancel them.""" + + def __init__(self, store: Callable[[], StreamStore]) -> None: + """Resolve the Store at each call so client replacement takes effect.""" + self._store = store + + async def call( + self, + operation: str, + request: bytes, + request_id: str | None, + on_task: Callable[[asyncio.Task[Any]], None], + ) -> bytes: + """Register the Python task before any Store work can start. + + ``on_task`` raises :py:class:`asyncio.CancelledError` if Core already + dropped the call. + """ + task = asyncio.current_task() + assert task + on_task(task) + _, request_type, _ = _store_operation(operation) + try: + response = await _call_method( + self._store(), operation, request_type.FromString(request), request_id + ) + except StreamError as err: + unavailable = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE + if err.reason == unavailable and err.__cause__: + # Core keeps only the text of the error, so the traceback is logged here. + logger.warning( + "Stream Store failed the %s call", operation, exc_info=err.__cause__ + ) + raise + return response.SerializeToString() diff --git a/temporalio/contrib/streams/README.md b/temporalio/contrib/streams/README.md new file mode 100644 index 0000000000..38134086f6 --- /dev/null +++ b/temporalio/contrib/streams/README.md @@ -0,0 +1,83 @@ +# Stream helpers + +> This package is experimental. Its API can change. + +`temporalio.contrib.streams` supports the SDK's Stream API. Configure Stores with +`stream_config=StreamConfig(stores=[...])`. Use `create_stream` or `get_stream` +on the client or `temporalio.workflow` to get a `Stream`. + +`temporalio.contrib.workflow_streams` is a separate API that stores events in +Workflow state. + +## `BufferedAppender` + +Use `BufferedAppender` in client or Activity code to combine frequent appends. + +```python +from temporalio.contrib.streams import BufferedAppender + +async with BufferedAppender(stream) as tokens: + async for token in model_tokens(): + tokens.append(token) +``` + +`append` returns immediately. When no write is active, the appender starts one on +the next turn of the event loop with the buffered Records. Records that arrive +during a write form the next batch. Writes are sequential. + +`async with` flushes before exit. Without it, call `await tokens.flush()` before +the Activity ends. Otherwise the last write can run after the Activity ends, even +after a write of a later attempt, and nobody gets its error. + +The buffer has no size limit. Await `flush()` periodically if the producer is +faster than the Store. Set the appender's `max_batch_records` to stay within the +client's batch count limit. The client's byte limits still apply. + +A failed batch stops later writes. Later `append` and `flush` calls raise that +error, or `RuntimeError` if the write was cancelled. `unwritten` counts Records +in the failed batch and the remaining buffer. The Store may have accepted the +failed batch if only its response was lost. + +Workflow code batches values in one Stream `append` call. + +## Store a Producer + +`current_producer()` returns the running Activity attempt's Producer. Use +`as_producer` to restore it from heartbeat details. Pass the restored value as +`append(..., producer=...)` when resumed work must retain that Producer. + +A `WorkflowProducer` includes `workflow_task_id` so readers can distinguish +retries from separate Workflow Tasks. Core sets it to the started event ID of the +last completed Workflow Task, or zero for the first task. Each retry has its own +`attempt`. + +## Read a Stream + +Pass `body_type=` or a typed ref such as `StreamRef[str](id=...)` to `get_stream`. +A ref without a body type raises `TypeError` when read. A Stream from +`create_stream` without a body type accepts any body. + +A Stream has no close. Stop at the application's terminal Record or cancel the +iterator. `read` and `read_pages` continue after empty pages. `read_pages` yields +those pages. `read_page` returns one page and has no default wait. + +With no `wait`, an iterator requests its first page immediately. Later requests +wait up to one minute. An explicit `wait` applies to every page. Zero disables +waiting, so an idle Stream produces repeated empty pages. Client iterators yield +to the event loop between them so cancellation can run. + +A positive `rpc_timeout` caps client and Activity waits below the timeout. An +Activity that heartbeats between Records needs a shorter `wait` than its +heartbeat timeout, or a separate heartbeat task. + +Workflow reads can span Workflow Tasks. `stream_read_time` bounds how long a +read keeps its task open. Each page adds a result to History. Short waits on an +idle Stream can make History grow quickly. Store outages fail the Workflow Task +without returning an error to Workflow code. + +Live Workflow pages default to 256 Records and 4 MiB, with a 16 MiB cap. A live +read fails if a Record exceeds the Worker's `max_record_bytes`. Replay preserves +recorded successes under smaller limits. + +Replay reads Records from the Store again. Retention must cover every replay +and query. Values in Workflow state do not remove this Store dependency. diff --git a/temporalio/contrib/streams/__init__.py b/temporalio/contrib/streams/__init__.py new file mode 100644 index 0000000000..fd05faea41 --- /dev/null +++ b/temporalio/contrib/streams/__init__.py @@ -0,0 +1,15 @@ +"""Helpers on top of the Streams API. + +:py:class:`BufferedAppender` batches the appends of one Stream, in client and +Activity code. :py:func:`current_producer` gives the Producer that a write of +the running Activity sends by default, and :py:func:`as_producer` gives back a +Producer that code stored. + +.. warning:: + This package is experimental and may change in future versions. +""" + +from temporalio.contrib.streams._appender import BufferedAppender +from temporalio.contrib.streams._producer import as_producer, current_producer + +__all__ = ["BufferedAppender", "as_producer", "current_producer"] diff --git a/temporalio/contrib/streams/_appender.py b/temporalio/contrib/streams/_appender.py new file mode 100644 index 0000000000..6141216a29 --- /dev/null +++ b/temporalio/contrib/streams/_appender.py @@ -0,0 +1,194 @@ +"""A helper that batches the appends of one Stream. + +.. warning:: + This module is experimental and subject to change. +""" + +from __future__ import annotations + +import asyncio +from types import TracebackType +from typing import Generic, TypeVar + +from typing_extensions import Self + +import temporalio.nexus.system.stream_service.client +import temporalio.workflow + +BodyT = TypeVar("BodyT") + + +class BufferedAppender(Generic[BodyT]): + """A buffer that writes the appends of one Stream in batches. + + Use it in code that appends often, such as an Activity that streams model + tokens. :py:meth:`append` returns immediately and does no I/O. While no write + runs, the appender starts one on the next turn of the event loop, with the + Records that are buffered by then. Records that arrive during a write go into + the next batch. One write runs at a time, and the Records keep their order. + + Use it in ``async with``, or await :py:meth:`flush` before the code that + appends ends. Otherwise the last Records are written after that code ends, + and nobody gets the error of that write. For an Activity that has ended, + that write can come after a write of the next attempt. + + ``await flush()`` is the backpressure point. The buffer has no bound, so code + that appends faster than the Store takes Records must await it from time to + time. + + After a batch fails, the appender writes nothing more, so a reader sees no + gap. Each later :py:meth:`append` and :py:meth:`flush` raises the error of + that batch, or :exc:`RuntimeError` if the write was cancelled. + + The appender is for client and Activity code. Workflow code passes its + Records to one ``append`` call of its Stream. + + .. warning:: + This API is experimental and subject to change. + """ + + def __init__( + self, + stream: temporalio.nexus.system.stream_service.client.Stream[BodyT], + *, + max_batch_records: int | None = None, + ) -> None: + """Create an appender. It starts no write before the first append. + + Args: + stream: The Stream to append to, from a client or from the client of + an Activity. + max_batch_records: The maximum number of Records of one batch. A + buffer with this many Records is written immediately. ``None`` + means no maximum of the appender, and a batch over a limit of + the client's ``StreamConfig`` then fails. + + Raises: + RuntimeError: The appender is created in Workflow code. + ValueError: ``max_batch_records`` is below 1. + """ + if temporalio.workflow.in_workflow(): + raise RuntimeError( + "BufferedAppender is for client and Activity code. In Workflow code, " + "pass the Records to one append call." + ) + if max_batch_records is not None and max_batch_records < 1: + raise ValueError("max_batch_records must be 1 or more") + self._stream = stream + self._max_batch_records = max_batch_records + self._buffer: list[BodyT] = [] + self._scheduled: asyncio.Handle | None = None + self._writing: asyncio.Task[None] | None = None + self._appended = 0 + # Failed batches also settle buffered Records, so flush cannot wait forever. + self._settled = 0 + self._error: Exception | None = None + self._last_offset: bytes | None = None + self._unwritten = 0 + + def append(self, *records: BodyT) -> None: + """Add one Record for each value to the buffer, and return immediately. + + Raises: + temporalio.exceptions.StreamError: A batch failed, so the appender + takes no more Records. + RuntimeError: The write of a batch was cancelled. + """ + if self._error: + raise self._error + self._buffer.extend(records) + self._appended += len(records) + self._schedule() + + async def flush(self) -> bytes | None: + """Write every Record that was appended before the call. + + Returns: + The offset of the last written Record, or ``None`` if the appender + has written nothing. + + Raises: + temporalio.exceptions.StreamError: A batch failed. + RuntimeError: The write of a batch was cancelled before the call. + """ + target = self._appended + while self._settled < target: + if not self._writing: + self._start() + assert self._writing + # A write is one batch at the Store, so a cancel of the caller doesn't stop it. + await asyncio.shield(self._writing) + if self._error: + raise self._error + return self._last_offset + + @property + def unwritten(self) -> int: + """Number of Records of the failed batch and of the buffer behind it. + + The appender wrote none of the buffer. The Store may still have taken the + failed batch, if only its answer was lost. + """ + return self._unwritten + + async def __aenter__(self) -> Self: + """Use the appender in ``async with``.""" + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + """Write the buffered Records. An error of the block wins over a write error.""" + try: + await self.flush() + except asyncio.CancelledError: + if exc is None or self._error is None: + raise + except Exception: + if exc is None: + raise + + def _schedule(self) -> None: + if self._writing or not self._buffer: + return + if self._max_batch_records and len(self._buffer) >= self._max_batch_records: + self._start() + elif not self._scheduled: + # The Records that the caller appends before it yields join this batch. + self._scheduled = asyncio.get_running_loop().call_soon(self._start) + + def _start(self) -> None: + if self._scheduled: + self._scheduled.cancel() + self._scheduled = None + batch = self._buffer[: self._max_batch_records] + del self._buffer[: self._max_batch_records] + self._writing = asyncio.get_running_loop().create_task(self._write(batch)) + + async def _write(self, batch: list[BodyT]) -> None: + try: + # An eager task factory must let append return before the Store call starts. + await asyncio.sleep(0) + response = await self._stream.append(*batch) + self._last_offset = response.last_offset + except BaseException as err: + # Later batches must not create a gap after this failed batch. + self._unwritten = len(batch) + len(self._buffer) + self._settled += len(self._buffer) + self._buffer.clear() + if isinstance(err, Exception): + self._error = err + else: + # Nobody cancelled a later caller, so it gets no `CancelledError`. + self._error = RuntimeError( + "The write of a batch was cancelled, so the appender takes no " + "more Records." + ) + raise + finally: + self._settled += len(batch) + self._writing = None + self._schedule() diff --git a/temporalio/contrib/streams/_producer.py b/temporalio/contrib/streams/_producer.py new file mode 100644 index 0000000000..70ef0d242b --- /dev/null +++ b/temporalio/contrib/streams/_producer.py @@ -0,0 +1,57 @@ +"""The Producer of a Stream write. + +.. warning:: + This module is experimental and subject to change. +""" + +from __future__ import annotations + +import temporalio.activity +import temporalio.api.stream.v1 +import temporalio.converter +from temporalio.nexus.system import _support +from temporalio.nexus.system.stream_service import Producer + + +def current_producer() -> Producer: + """Return the Producer of the running attempt of an Activity. + + An append of that attempt sends it by default. Code that stores + it, such as in heartbeat details, gets it back from :py:func:`as_producer`. + + The Producer of an Activity of a Workflow has the Activity id and the id of + its ``ActivityTaskScheduled`` event. So a later Activity of the run that uses + the same Activity id is a separate Producer. A Local Activity's Producer + uses the Workflow Task id and Activity id from its original schedule. + Its retries keep both ids, including when a timer delays the retry. + + Raises: + RuntimeError: The caller is outside an Activity or its Local Activity + scheduling metadata is unavailable. + + .. warning:: + This API is experimental and subject to change. + """ + return _support.activity_producer(temporalio.activity.info()) + + +def as_producer(value: object) -> Producer: + """Return the Producer that code stored, such as in heartbeat details. + + The default data converter gives a stored Producer back as its proto + message, since such a value has no type hint. + + Raises: + TypeError: ``value`` is neither a Producer nor its proto message. + + .. warning:: + This API is experimental and subject to change. + """ + if isinstance(value, Producer): + return value + if not isinstance(value, temporalio.api.stream.v1.Producer): + raise TypeError(f"Expected a Producer, got {type(value).__name__}") + converter = temporalio.converter.DataConverter.default + return _support.model_from_proto( + value, Producer, converter.payload_converter, converter.failure_converter + ) diff --git a/temporalio/converter/_payload_converter.py b/temporalio/converter/_payload_converter.py index ff7d477cc2..424e0ee8ec 100644 --- a/temporalio/converter/_payload_converter.py +++ b/temporalio/converter/_payload_converter.py @@ -584,6 +584,26 @@ def from_payload( raise RuntimeError("Failed parsing") from err +# Restrict new decoding rules to new types to preserve existing Workflow histories. +_typed_decode_types: set[type] = set() + + +def _is_typed_decode_type(hint: Any) -> bool: + origin = typing.get_origin(hint) or hint + return any(origin is typed for typed in _typed_decode_types) + + +def _non_none_arg(hint: Any) -> Any: + origin = typing.get_origin(hint) + if origin is typing.Union or origin is UnionType: # type:ignore[reportDeprecated] + args = typing.get_args(hint) + if len(args) == 2 and type(None) in args: + arg = args[0] if args[1] is type(None) else args[1] + if _is_typed_decode_type(arg): + return arg + return hint + + class _TemporalTransferTypePayloadConverter(PayloadConverter, WithSerializationContext): """Payload converter wrapper for registered Temporal transfer type converters. @@ -591,7 +611,9 @@ class _TemporalTransferTypePayloadConverter(PayloadConverter, WithSerializationC transfer type value, then encoded by the wrapped payload converter. When decoding to a type with a registered transfer type converter, the wrapped converter first decodes the payload to the transfer type value and this wrapper - constructs the requested user-facing type from it. + constructs the requested user-facing type from it. For a type of + ``_typed_decode_types``, a hint of the type or ``None`` decodes the same way, and a + null payload gives ``None``. """ _inner_payload_converter: PayloadConverter @@ -627,21 +649,33 @@ def from_payloads( """See base class.""" if type_hints is None: return self._inner_payload_converter.from_payloads(payloads, None) + value_hints = [_non_none_arg(type_hint) for type_hint in type_hints] converters = [ - _get_transfer_type_converter(type_hint) for type_hint in type_hints - ] - inner_type_hints = [ - converter.transfer_type if converter is not None else type_hint - for converter, type_hint in zip(converters, type_hints) + _get_transfer_type_converter(value_hint) for value_hint in value_hints ] + inner_type_hints: list[Any] = [] + for converter, value_hint, type_hint in zip( + converters, value_hints, type_hints + ): + if converter is None: + inner_type_hints.append(type_hint) + elif value_hint is type_hint or converter.transfer_type is None: + inner_type_hints.append(converter.transfer_type) + else: + # A transfer type can be a value with no `|`, such as a string. + inner_type_hints.append( + typing.Optional[converter.transfer_type] # type:ignore[reportDeprecated] + ) values = self._inner_payload_converter.from_payloads( payloads, typing.cast("list[type]", inner_type_hints) ) return [ - converter.from_transfer_type(value, type_hint) - if converter is not None - else value - for value, converter, type_hint in zip(values, converters, type_hints) + value + if converter is None or (value is None and value_hint is not type_hint) + else converter.from_transfer_type(value, value_hint) + for value, converter, value_hint, type_hint in zip( + values, converters, value_hints, type_hints + ) ] def with_context(self, context: SerializationContext) -> Self: @@ -822,6 +856,18 @@ def _get_iso_datetime_parser() -> Callable[[str], datetime]: return datetime.fromisoformat +def _with_type_args(hint: Any, type_var_args: Mapping[Any, Any]) -> Any: + if not type_var_args: + return hint + if isinstance(hint, TypeVar): + return type_var_args.get(hint, hint) + # Only an alias takes arguments. A bare generic class keeps its own variables. + parameters = getattr(hint, "__parameters__", ()) + if parameters and typing.get_origin(hint) is not None: + return hint[tuple(type_var_args.get(param, param) for param in parameters)] + return hint + + def value_to_type( hint: type, value: Any, @@ -993,8 +1039,14 @@ def value_to_type( ret_dict = hint(**ret_dict) return ret_dict - # Dataclass - if dataclasses.is_dataclass(hint): + dataclass_type: Any = hint + type_var_args: dict[Any, Any] = {} + alias_origin = typing.get_origin(hint) + if _is_typed_decode_type(alias_origin) and dataclasses.is_dataclass(alias_origin): + dataclass_type = alias_origin + parameters = getattr(alias_origin, "__parameters__", ()) + type_var_args = dict(zip(parameters, type_args)) + if dataclasses.is_dataclass(dataclass_type): if not isinstance(value, dict): raise TypeError( f"Cannot convert to dataclass {hint}, value is {type(value)} not dict" @@ -1002,8 +1054,8 @@ def value_to_type( # Obtain dataclass fields and check that all dict fields are there and # that no required fields are missing. Unknown fields are silently # ignored. - fields = dataclasses.fields(hint) - field_hints = get_type_hints(hint) + fields = dataclasses.fields(dataclass_type) + field_hints = get_type_hints(dataclass_type) field_values = {} non_init_field_values = {} for field in fields: @@ -1016,7 +1068,9 @@ def value_to_type( # rejects this dataclass when trying union members try: converted = value_to_type( - field_hints[field.name], field_value, custom_converters + _with_type_args(field_hints[field.name], type_var_args), + field_value, + custom_converters, ) except Exception as err: raise TypeError( @@ -1029,6 +1083,7 @@ def value_to_type( # Simply instantiate the dataclass. This will fail as expected when # missing required fields. # TODO(cretz): Want way to convert snake case to camel case? + # The alias retains type arguments that its dataclass origin would lose. obj = hint(**field_values) # init=False fields cannot be passed to __init__ but are serialized, so # restore them afterwards. object.__setattr__ also works on frozen diff --git a/temporalio/exceptions.py b/temporalio/exceptions.py index 03a623c21e..5bec57528c 100644 --- a/temporalio/exceptions.py +++ b/temporalio/exceptions.py @@ -1,6 +1,7 @@ """Common Temporal exceptions.""" import asyncio +import functools from collections.abc import Sequence from datetime import timedelta from enum import IntEnum @@ -8,6 +9,7 @@ import temporalio.api.enums.v1 import temporalio.api.failure.v1 +import temporalio.api.stream.v1 class TemporalError(Exception): @@ -474,6 +476,48 @@ def operation_token(self) -> str: return self._operation_token +class StreamError(ApplicationError): + """Error raised when a Stream call fails. + + Client, Activity and Workflow code all get this class for a failed Stream + call, with no other error around it, and :py:attr:`reason` says why the call + failed. A call that fails with ``STREAM_ERROR_REASON_STORE_UNAVAILABLE`` may + succeed on another try, so it's the only reason that isn't ``non_retryable``. + + .. warning:: + This API is experimental and subject to change. + """ + + def __init__( + self, + message: str, + *, + reason: temporalio.api.enums.v1.StreamErrorReason.ValueType, + ) -> None: + """Initialize a Stream error.""" + reasons = temporalio.api.enums.v1.StreamErrorReason + super().__init__( + message, + temporalio.api.stream.v1.StreamErrorDetails(reason=reason), + # The form of the type in a failure that Core builds + type="stream_" + + reasons.Name(reason).removeprefix("STREAM_ERROR_REASON_").lower(), + non_retryable=reason != reasons.STREAM_ERROR_REASON_STORE_UNAVAILABLE, + ) + self._reason = reason + + @property + def reason(self) -> temporalio.api.enums.v1.StreamErrorReason.ValueType: + """Why the Stream call failed.""" + return self._reason + + def __reduce__(self) -> Any: + """Return the parts that ``copy`` and ``pickle`` build the error from.""" + # The default calls the class with `args` alone, which has no reason. + _, *rest = tuple(super().__reduce__()) + return functools.partial(type(self), reason=self._reason), *rest + + def is_cancelled_exception(exception: BaseException) -> bool: """Check whether the given exception is considered a cancellation exception according to Temporal. diff --git a/temporalio/nexus/system/__init__.py b/temporalio/nexus/system/__init__.py index da102bd304..e2e2086a56 100644 --- a/temporalio/nexus/system/__init__.py +++ b/temporalio/nexus/system/__init__.py @@ -20,6 +20,7 @@ from temporalio.converter import BinaryProtoPayloadConverter, CompositePayloadConverter from temporalio.converter._payload_converter import ( _TemporalTransferTypePayloadConverter, + _typed_decode_types, ) TEMPORAL_SYSTEM_ENDPOINT = "__temporal_system" @@ -198,3 +199,8 @@ def _get_serialization_context( # pyright: ignore[reportUnusedFunction] # `temporalio.workflow` and the generated Workflow modules of a system service import each # other. It's loaded here last, so that any of those modules can be the first import. import temporalio.workflow # noqa: E402 # pyright: ignore[reportUnusedImport] +from temporalio.nexus.system.stream_service.models import StreamRef # noqa: E402 + +# Workflow code can decode a `StreamRef` only on an SDK with this rule, so the rule can't +# change a replay. Any import of the generated class runs this module first. +_typed_decode_types.add(StreamRef) diff --git a/temporalio/nexus/system/_support.py b/temporalio/nexus/system/_support.py index 5fda5a01f1..09b93b0a93 100644 --- a/temporalio/nexus/system/_support.py +++ b/temporalio/nexus/system/_support.py @@ -42,6 +42,7 @@ class SignalWithStartWorkflowModelRequest(typing.Protocol): namespace: str id: str + workflow: str | collections.abc.Callable[..., collections.abc.Awaitable[object]] def model_to_proto( @@ -341,6 +342,16 @@ def signal_with_start_workflow_serialization_context( ) +def signal_with_start_workflow_storage_target( + request: SignalWithStartWorkflowModelRequest, +) -> temporalio.converter.StorageDriverWorkflowInfo: + return temporalio.converter.StorageDriverWorkflowInfo( + namespace=request.namespace, + id=request.id, + type=workflow_function_name(request.workflow), + ) + + def payloads_to_proto( values: collections.abc.Sequence[typing.Any], ) -> common_pb2.Payloads: diff --git a/temporalio/nexus/system/stream_service/client/_resources/stream.py b/temporalio/nexus/system/stream_service/client/_resources/stream.py index 813416fb20..1d12942cb8 100644 --- a/temporalio/nexus/system/stream_service/client/_resources/stream.py +++ b/temporalio/nexus/system/stream_service/client/_resources/stream.py @@ -121,7 +121,7 @@ async def read_pages( rpc_metadata: collections.abc.Mapping[str, str | bytes] | None = None, rpc_timeout: datetime.timedelta | None = None, ) -> collections.abc.AsyncGenerator[ReadRecordsResponse[BodyT], None]: - """Yield each response of ``read_page`` until the poll helper returns ``None``. + """Yield each response of ``read_page`` until the poll helper stops. Read one page of Records. The poll iterator keeps reading after a page with no Record. diff --git a/temporalio/nexus/system/stream_service/client/_system_nexus_interceptor.py b/temporalio/nexus/system/stream_service/client/_system_nexus_interceptor.py new file mode 100644 index 0000000000..fb53dd04df --- /dev/null +++ b/temporalio/nexus/system/stream_service/client/_system_nexus_interceptor.py @@ -0,0 +1,172 @@ +# Generated by nexgen v0.2.14. DO NOT EDIT! + +from __future__ import annotations + +import abc +import typing + +from .. import models + +if typing.TYPE_CHECKING: + from temporalio.client import NexusOperationHandle, StartNexusOperationInput + + +__all__ = [ + "_start_system_nexus_operation", + "_SystemNexusClientOutboundInterceptorBase", + "_SystemNexusClientOutboundInterceptorTerminal", +] + + +_InputT = typing.TypeVar("_InputT") +_OutputT = typing.TypeVar("_OutputT") + + +async def _start_system_nexus_operation( + interceptor: _SystemNexusClientOutboundInterceptorBase, + input: StartNexusOperationInput[_InputT, _OutputT], +) -> NexusOperationHandle[_OutputT]: + if ( + input.service == "temporal.api.streamservice.v1.StreamService" + and input.operation == "CreateStream" + ): + return typing.cast( + "NexusOperationHandle[_OutputT]", + await interceptor.start_create_stream( + typing.cast( + "StartNexusOperationInput[models.CreateStreamRequest[typing.Any], models.CreateStreamResult[typing.Any]]", + input, + ), + ), + ) + if ( + input.service == "temporal.api.streamservice.v1.StreamService" + and input.operation == "AppendRecords" + ): + return typing.cast( + "NexusOperationHandle[_OutputT]", + await interceptor.start_append_records( + typing.cast( + "StartNexusOperationInput[models.AppendRecordsRequest[typing.Any], models.AppendRecordsResponse]", + input, + ), + ), + ) + if ( + input.service == "temporal.api.streamservice.v1.StreamService" + and input.operation == "ReadRecords" + ): + return typing.cast( + "NexusOperationHandle[_OutputT]", + await interceptor.start_read_records( + typing.cast( + "StartNexusOperationInput[models.ReadRecordsRequest[typing.Any], models.ReadRecordsResponse[typing.Any]]", + input, + ), + ), + ) + if ( + input.service == "temporal.api.streamservice.v1.StreamService" + and input.operation == "DescribeStream" + ): + return typing.cast( + "NexusOperationHandle[_OutputT]", + await interceptor.start_describe_stream( + typing.cast( + "StartNexusOperationInput[models.DescribeStreamRequest[typing.Any], models.DescribeStreamResponse]", + input, + ), + ), + ) + raise ValueError( + f"unsupported System Nexus operation: {input.service}/{input.operation}" + ) + + +class _SystemNexusClientOutboundInterceptorBase(abc.ABC): + @abc.abstractmethod + def _next_system_nexus_interceptor( + self, + ) -> _SystemNexusClientOutboundInterceptorBase: ... + + async def start_create_stream( + self, + input: StartNexusOperationInput[ + models.CreateStreamRequest[typing.Any], + models.CreateStreamResult[typing.Any], + ], + ) -> NexusOperationHandle[models.CreateStreamResult[typing.Any]]: + """Intercept the CreateStream operation.""" + return await self._next_system_nexus_interceptor().start_create_stream(input) + + async def start_append_records( + self, + input: StartNexusOperationInput[ + models.AppendRecordsRequest[typing.Any], models.AppendRecordsResponse + ], + ) -> NexusOperationHandle[models.AppendRecordsResponse]: + """Intercept the AppendRecords operation.""" + return await self._next_system_nexus_interceptor().start_append_records(input) + + async def start_read_records( + self, + input: StartNexusOperationInput[ + models.ReadRecordsRequest[typing.Any], + models.ReadRecordsResponse[typing.Any], + ], + ) -> NexusOperationHandle[models.ReadRecordsResponse[typing.Any]]: + """Intercept the ReadRecords operation.""" + return await self._next_system_nexus_interceptor().start_read_records(input) + + async def start_describe_stream( + self, + input: StartNexusOperationInput[ + models.DescribeStreamRequest[typing.Any], models.DescribeStreamResponse + ], + ) -> NexusOperationHandle[models.DescribeStreamResponse]: + """Intercept the DescribeStream operation.""" + return await self._next_system_nexus_interceptor().start_describe_stream(input) + + +class _SystemNexusClientOutboundInterceptorTerminal(abc.ABC): + @abc.abstractmethod + async def _start_system_nexus_operation( + self, + input: StartNexusOperationInput[_InputT, _OutputT], + ) -> NexusOperationHandle[_OutputT]: + """Start directly, without entering generic Nexus interception.""" + ... + + async def start_create_stream( + self, + input: StartNexusOperationInput[ + models.CreateStreamRequest[typing.Any], + models.CreateStreamResult[typing.Any], + ], + ) -> NexusOperationHandle[models.CreateStreamResult[typing.Any]]: + return await self._start_system_nexus_operation(input) + + async def start_append_records( + self, + input: StartNexusOperationInput[ + models.AppendRecordsRequest[typing.Any], models.AppendRecordsResponse + ], + ) -> NexusOperationHandle[models.AppendRecordsResponse]: + return await self._start_system_nexus_operation(input) + + async def start_read_records( + self, + input: StartNexusOperationInput[ + models.ReadRecordsRequest[typing.Any], + models.ReadRecordsResponse[typing.Any], + ], + ) -> NexusOperationHandle[models.ReadRecordsResponse[typing.Any]]: + return await self._start_system_nexus_operation(input) + + async def start_describe_stream( + self, + input: StartNexusOperationInput[ + models.DescribeStreamRequest[typing.Any], models.DescribeStreamResponse + ], + ) -> NexusOperationHandle[models.DescribeStreamResponse]: + return await self._start_system_nexus_operation(input) diff --git a/temporalio/nexus/system/stream_service/workflow/_resources/stream.py b/temporalio/nexus/system/stream_service/workflow/_resources/stream.py index 477499e728..16f1bfb81f 100644 --- a/temporalio/nexus/system/stream_service/workflow/_resources/stream.py +++ b/temporalio/nexus/system/stream_service/workflow/_resources/stream.py @@ -87,7 +87,7 @@ async def read_pages( wait: datetime.timedelta | None = None, max_bytes: int | None = None, ) -> collections.abc.AsyncGenerator[ReadRecordsResponse[BodyT], None]: - """Yield each response of ``read_page`` until the poll helper returns ``None``. + """Yield each response of ``read_page`` until the poll helper stops. Read one page of Records. The poll iterator keeps reading after a page with no Record. 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/_activity.py b/temporalio/testing/_activity.py index 6f0a9ab5d5..63fb08c588 100644 --- a/temporalio/testing/_activity.py +++ b/temporalio/testing/_activity.py @@ -67,7 +67,7 @@ def default_info() -> temporalio.activity.Info: Returns a new default Info instance that can be modified using :py:func:`dataclasses.replace` before assigning to the info attribute. """ - utc_zero = datetime.fromtimestamp(0).replace(tzinfo=timezone.utc) + utc_zero = datetime.fromtimestamp(0, tz=timezone.utc) return temporalio.activity.Info( activity_id="test", activity_type="unknown", diff --git a/temporalio/testing/_stream_store.py b/temporalio/testing/_stream_store.py new file mode 100644 index 0000000000..d82619e013 --- /dev/null +++ b/temporalio/testing/_stream_store.py @@ -0,0 +1,294 @@ +"""Stream Store that keeps its Streams in memory.""" + +from __future__ import annotations + +import asyncio +import bisect +import collections +from dataclasses import dataclass, field +from datetime import timedelta + +import google.protobuf.message + +from temporalio.api.enums.v1 import StreamErrorReason, StreamIdConflictPolicy +from temporalio.api.stream.v1 import ( + ActivityAttempt, + LocalActivityAttempt, + Producer, + StreamRecord, + WorkflowTaskAttempt, +) +from temporalio.api.streamservice.v1 import ( + AppendRecordsRequest, + AppendRecordsResponse, + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, +) +from temporalio.client._stream_store import StreamStore +from temporalio.exceptions import StreamError + +_Attempt = tuple[int, ...] + + +@dataclass +class _Batch: + attempt: _Attempt + request_id: str + response: AppendRecordsResponse + + +@dataclass +class _Writer: + """What a Stream keeps of one of its Producers.""" + + window: collections.deque[_Batch] + """The last batches that the Producer wrote, oldest first.""" + + newest: _Attempt = () + """The latest attempt of the Producer that wrote.""" + + +@dataclass +class _Stream: + request_id: str + """The request id of the create that made the Stream.""" + + expires_at: float + """The time of the event loop at which the Stream expires.""" + + records: list[StreamRecord] = field(default_factory=list) + writers: dict[bytes, _Writer] = field(default_factory=dict) + changed: asyncio.Event = field(default_factory=asyncio.Event) + """Set at the next append that writes, which then puts a new event here.""" + + @property + def last_offset(self) -> bytes: + return self.records[-1].offset if self.records else b"" + + +class MemoryStreamStore(StreamStore): + """Stream Store that keeps its Streams in the memory of this process. + + It's for tests and local runs, and it shows what a Store does. A client and a + Worker see the same Streams only through the same instance, in one event loop. + + The Store has no limit of a batch, since the limits are those of the + :py:class:`temporalio.client.StreamConfig` of the caller. A read with no + ``max_records`` or no ``max_bytes`` has no limit of that kind. + + .. warning:: + This API is experimental and subject to change. + """ + + def __init__( + self, + *, + name: str = "memory", + retention: timedelta | None = None, + resend_window: int | None = None, + fence: bool = False, + ) -> None: + """Create a memory Store. + + Args: + name: The name of the Store in a + :py:class:`temporalio.client.StreamConfig`. + retention: How long after its create, or after its last append that + wrote a batch, a Stream expires. Defaults to 7 days. A resend and + a create of a Stream that exists don't start it again. + resend_window: The number of recent batches of each Producer of a + Stream whose request ids the Store remembers, so that it writes + a resend of one of them only once. Defaults to 16, and must be + at least 1, since a Store remembers the last batch of a Producer. + fence: Whether the Store fences. If true, an append of an attempt + fails with ``STREAM_ERROR_REASON_FENCED`` once a later attempt of + its Producer has written to the Stream. + """ + if resend_window is not None and resend_window < 1: + raise ValueError("resend_window must be greater than zero.") + self._name = name + self._retention = timedelta(days=7) if retention is None else retention + self._resend_window = 16 if resend_window is None else resend_window + self._fence = fence + self._streams: dict[str, _Stream] = {} + + def name(self) -> str: + """See base class.""" + return self._name + + async def create_stream( + self, request: CreateStreamRequest, *, request_id: str + ) -> CreateStreamResponse: + """See base class.""" + stream_id = request.stream_id + if stream_id not in self._streams: + self._streams[stream_id] = _Stream(request_id, self._expiry()) + return CreateStreamResponse(created=True) + stream = self._stream(stream_id) + # An empty request id identifies no create, so it never matches. + if request_id and request_id == stream.request_id: + return CreateStreamResponse(created=True) + use_existing = StreamIdConflictPolicy.STREAM_ID_CONFLICT_POLICY_USE_EXISTING + if request.id_conflict_policy == use_existing: + return CreateStreamResponse(created=False) + raise StreamError( + f"The Stream '{stream_id}' already exists", + reason=StreamErrorReason.STREAM_ERROR_REASON_ALREADY_EXISTS, + ) + + async def append_records( + self, request: AppendRecordsRequest, *, request_id: str + ) -> AppendRecordsResponse: + """See base class.""" + stream = self._stream(request.stream_id) + key, attempt = _producer_key(request.producer), _attempt(request.producer) + writer = stream.writers.get(key) + if writer is None: + writer = _Writer(collections.deque(maxlen=self._resend_window)) + if request_id: + for batch in writer.window: + if (batch.attempt, batch.request_id) == (attempt, request_id): + return batch.response + if self._fence and attempt < writer.newest: + raise _fenced(request.stream_id) + first = len(stream.records) + 1 + stream.records.extend( + StreamRecord( + producer=request.producer, + body=record.body, + offset=(first + at).to_bytes(8, "big"), + ) + for at, record in enumerate(request.records) + ) + response = AppendRecordsResponse( + first_offset=first.to_bytes(8, "big"), last_offset=stream.last_offset + ) + writer.newest = attempt + writer.window.append(_Batch(attempt, request_id, response)) + stream.writers[key] = writer + stream.expires_at = self._expiry() + self._notify(stream) + return response + + async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: + """See base class.""" + stream = self._stream(request.stream_id) + if request.after_offset > stream.last_offset: + raise StreamError( + f"The after_offset of the read is past the newest offset of the " + f"Stream '{request.stream_id}'", + reason=StreamErrorReason.STREAM_ERROR_REASON_OFFSET_TOO_HIGH, + ) + start = bisect.bisect_right( + stream.records, request.after_offset, key=lambda record: record.offset + ) + wait = request.wait.ToTimedelta().total_seconds() + until = self._now() + wait + while start == len(stream.records) and self._now() < until: + try: + async with asyncio.timeout_at(min(until, stream.expires_at)): + await stream.changed.wait() + except TimeoutError: + pass + self._stream(request.stream_id) + page: list[StreamRecord] = [] + page_bytes = 0 + for record in stream.records[start:]: + if request.max_records and len(page) == request.max_records: + break + page_bytes += record.ByteSize() + # The first Record is always in the page, so a read makes progress. + if request.max_bytes and page and page_bytes > request.max_bytes: + break + page.append(record) + return ReadRecordsResponse(records=page) + + async def describe_stream( + self, request: DescribeStreamRequest + ) -> DescribeStreamResponse: + """See base class.""" + stream = self._stream(request.stream_id) + return DescribeStreamResponse(last_offset=stream.last_offset) + + def _stream(self, stream_id: str) -> _Stream: + stream = self._streams.get(stream_id) + if stream is None: + raise StreamError( + f"The Stream '{stream_id}' doesn't exist", + reason=StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND, + ) + if self._now() >= stream.expires_at: + raise StreamError( + f"The Stream '{stream_id}' expired", + reason=StreamErrorReason.STREAM_ERROR_REASON_EXPIRED, + ) + return stream + + def _now(self) -> float: + return asyncio.get_running_loop().time() + + def _expiry(self) -> float: + return self._now() + self._retention.total_seconds() + + def _notify(self, stream: _Stream) -> None: + stream.changed.set() + stream.changed = asyncio.Event() + + +def _fenced(stream_id: str) -> StreamError: + return StreamError( + f"A later attempt of the Producer has written to the Stream '{stream_id}'", + reason=StreamErrorReason.STREAM_ERROR_REASON_FENCED, + ) + + +def _kind(producer: Producer) -> google.protobuf.message.Message: + name = producer.WhichOneof("kind") + assert name, "The SDK refuses a Producer with no kind before a Store gets it" + return getattr(producer, name) + + +def _producer_key(producer: Producer) -> bytes: + """Return what identifies a Producer, which is its kind with the ids of that + kind and without its attempt. + """ + key = Producer() + key.CopyFrom(producer) + kind = _kind(key) + if "attempt" in kind.DESCRIPTOR.fields_by_name: + kind.ClearField("attempt") + return key.SerializeToString(deterministic=True) + + +def _attempt(producer: Producer) -> _Attempt: + """Return a value that orders the attempts of one Producer, as the attempt key + of SDK Core does. + + Two attempts compare by the Workflow Task first (its started event id, its + attempt number, its started time), and then by the Activity attempt (its + scheduled time, its attempt number). A field that the kind of the Producer + doesn't have, or that is negative, is zero. So every write of a client has + the same attempt. + """ + attempt = getattr(_kind(producer), "attempt", None) + task, scheduled, number = WorkflowTaskAttempt(), ActivityAttempt(), 0 + if isinstance(attempt, WorkflowTaskAttempt): + task = attempt + elif isinstance(attempt, LocalActivityAttempt): + task, number = attempt.task, attempt.attempt + elif isinstance(attempt, ActivityAttempt): + scheduled, number = attempt, attempt.attempt + fields = ( + task.started_event_id, + task.attempt, + task.started_time.seconds, + task.started_time.nanos, + scheduled.attempt_scheduled_time.seconds, + scheduled.attempt_scheduled_time.nanos, + number, + ) + return tuple(max(0, value) for value in fields) diff --git a/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/temporalio/worker/_activity.py b/temporalio/worker/_activity.py index 7c95449df8..e0b1c609fe 100644 --- a/temporalio/worker/_activity.py +++ b/temporalio/worker/_activity.py @@ -709,6 +709,13 @@ async def _execute_activity( ) if start.HasField("workflow_task") else None, + _local_activity_origin=( + start.local_activity_origin.workflow_task_id, + start.local_activity_origin.activity_id, + ) + if start.HasField("local_activity_origin") + else None, + _scheduled_event_id=start.scheduled_event_id, ) if self._encode_headers: diff --git a/temporalio/worker/_command_aware_visitor.py b/temporalio/worker/_command_aware_visitor.py index 888c06f298..68f4459011 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,11 @@ ResolveNexusOperationStart, ResolveRequestCancelExternalWorkflow, ResolveSignalExternalWorkflow, + ResolveStreamAppend, + ResolveStreamRead, ) from temporalio.bridge.proto.workflow_commands.workflow_commands_pb2 import ( + AppendToStream, CompleteWorkflowExecution, FailWorkflowExecution, ScheduleActivity, @@ -211,6 +215,47 @@ 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_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 +265,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/_interceptor.py b/temporalio/worker/_interceptor.py index 09d49884db..f164103a09 100644 --- a/temporalio/worker/_interceptor.py +++ b/temporalio/worker/_interceptor.py @@ -21,6 +21,9 @@ import temporalio.nexus import temporalio.nexus._util import temporalio.workflow +from temporalio.nexus.system.stream_service.workflow._system_nexus_interceptor import ( + _SystemNexusWorkflowOutboundInterceptorBase as _StreamOutboundInterceptorBase, +) from temporalio.nexus.system.workflow_service._system_nexus_interceptor import ( _SystemNexusWorkflowOutboundInterceptorBase, ) @@ -455,7 +458,9 @@ async def handle_update_handler(self, input: HandleUpdateInput) -> Any: return await self.next.handle_update_handler(input) -class WorkflowOutboundInterceptor(_SystemNexusWorkflowOutboundInterceptorBase): +class WorkflowOutboundInterceptor( + _SystemNexusWorkflowOutboundInterceptorBase, _StreamOutboundInterceptorBase +): """Outbound interceptor to wrap calls made from within workflows. This should be extended by any workflow outbound interceptors. @@ -472,9 +477,7 @@ def __init__(self, next: WorkflowOutboundInterceptor) -> None: """ self.next = next - def _next_system_nexus_interceptor( - self, - ) -> _SystemNexusWorkflowOutboundInterceptorBase: + def _next_system_nexus_interceptor(self) -> WorkflowOutboundInterceptor: return self.next def continue_as_new(self, input: ContinueAsNewInput) -> NoReturn: diff --git a/temporalio/worker/_replayer.py b/temporalio/worker/_replayer.py index 1542b3e0f2..8189cef00a 100644 --- a/temporalio/worker/_replayer.py +++ b/temporalio/worker/_replayer.py @@ -32,6 +32,7 @@ UnsandboxedWorkflowRunner, WorkflowRunner, ) +from ._workflow_streams import _bridge_streams from .workflow_sandbox import SandboxedWorkflowRunner logger = logging.getLogger(__name__) @@ -58,6 +59,7 @@ def __init__( runtime: temporalio.runtime.Runtime | None = None, disable_safe_workflow_eviction: bool = False, header_codec_behavior: HeaderCodecBehavior = HeaderCodecBehavior.NO_CODEC, + stream_config: temporalio.client.StreamConfig | None = None, ) -> None: """Create a replayer to replay workflows from history. @@ -70,6 +72,13 @@ def __init__( will default to a new thread pool executor with no max_workers set that will be shared across all replay calls and never explicitly shut down. Users are encouraged to provide their own if needing more control. + + ``stream_config`` must preserve the Worker's Store names and selector + choices because replay selects the Store of each call again. Append, + create and describe use recorded results without calling the Store. + A :py:class:`temporalio.testing.MemoryStreamStore` with the same name can + serve those operations during replay. Reads fetch Records from the Store + again and fail if the recorded Records are unavailable or changed. """ self._config = ReplayerConfig( workflows=list(workflows), @@ -88,6 +97,7 @@ def __init__( runtime=runtime, disable_safe_workflow_eviction=disable_safe_workflow_eviction, header_codec_behavior=header_codec_behavior, + stream_config=stream_config, ) self._initial_config = self._config.copy() self._default_workflow_logic_flags = set(_DEFAULT_ENABLED_WORKFLOW_LOGIC_FLAGS) @@ -253,6 +263,7 @@ def on_eviction_hook( self._config.get("data_converter") or temporalio.converter.DataConverter.default ) + stream_config = self._config.get("stream_config") workflow_worker = _WorkflowWorker( bridge_worker=lambda: bridge_worker, namespace=self._config.get("namespace", "ReplayNamespace"), @@ -281,6 +292,7 @@ def on_eviction_hook( ), should_enforce_versioning_behavior=False, assert_local_activity_valid=lambda a: None, + stream_config=lambda: stream_config, encode_headers=self._config.get( "header_codec_behavior", HeaderCodecBehavior.NO_CODEC ) @@ -309,6 +321,10 @@ def on_eviction_hook( # per workflow type nondeterminism_as_workflow_fail=workflow_worker.nondeterminism_as_workflow_fail(), nondeterminism_as_workflow_fail_for_types=workflow_worker.nondeterminism_as_workflow_fail_for_types(), + stream_replay_as_workflow_fail=workflow_worker.stream_replay_as_workflow_fail(), + stream_replay_as_workflow_fail_for_types=( + workflow_worker.stream_replay_as_workflow_fail_for_types() + ), # All values below are ignored but required by Core max_cached_workflows=2, tuner=temporalio.bridge.worker.TunerHolder( @@ -358,6 +374,7 @@ def on_eviction_hook( (plugin.name(), plugin.version()) for plugin in self.plugins ], storage_drivers=storage_driver_types, + streams=_bridge_streams(lambda: stream_config, None), ), ) bridge_worker_scope = bridge_worker @@ -437,6 +454,7 @@ class ReplayerConfig(TypedDict, total=False): runtime: temporalio.runtime.Runtime | None disable_safe_workflow_eviction: bool header_codec_behavior: HeaderCodecBehavior + stream_config: temporalio.client.StreamConfig | None @dataclass(frozen=True) diff --git a/temporalio/worker/_worker.py b/temporalio/worker/_worker.py index cf8125d819..7c09f31ebc 100644 --- a/temporalio/worker/_worker.py +++ b/temporalio/worker/_worker.py @@ -45,6 +45,7 @@ UnsandboxedWorkflowRunner, WorkflowRunner, ) +from ._workflow_streams import _bridge_streams, _check_stream_swap, _stream_store_call from .workflow_sandbox import SandboxedWorkflowRunner logger = logging.getLogger(__name__) @@ -147,6 +148,7 @@ def __init__( nexus_task_poller_behavior: PollerBehavior | None = None, disable_payload_error_limit: bool = False, max_workflow_task_external_storage_concurrency: int = _DEFAULT_WORKFLOW_TASK_EXTERNAL_STORAGE_CONCURRENCY, + stream_read_time: timedelta | None = None, ) -> None: """Create a worker to process workflows and/or activities. @@ -346,6 +348,15 @@ def __init__( Please report any issues you encounter with this setting or if you feel the default should be changed. WARNING: This setting is experimental. + stream_read_time: Maximum time that Stream reads can keep a Workflow + Task open, measured from its start or the end of replay. Defaults + to half the task timeout and always ends before its heartbeat. + Reads alone don't cause task heartbeats. Appends have no such limit. + At the limit, waiting reads return empty pages. Iterators continue + with a new wait, possibly in another task. Unset iterator waits + default to one minute after the first page. Immediate reads can + continue without holding the task open until the Store answers. + WARNING: This setting is experimental. """ config = WorkerConfig( @@ -395,6 +406,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_time=stream_read_time, ) plugins_from_client = cast( @@ -498,7 +510,9 @@ def _init_from_config(self, client: temporalio.client.Client, config: WorkerConf or bridge_client.config.runtime or temporalio.runtime.Runtime.default() ) - activities = config.get("activities") + activities = list(config.get("activities") or []) + if client_config["stream_config"] and config.get("workflows"): + activities.append(_stream_store_call) if activities: _warn_if_activity_executor_max_workers_is_inconsistent(config) self._activity_worker = _ActivityWorker( @@ -575,6 +589,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 +682,7 @@ def check_activity(activity: str): enable_workflows=self._workflow_worker is not None, enable_local_activities=self._activity_worker is not None and self._workflow_worker is not None, - enable_remote_activities=self._activity_worker is not None + enable_remote_activities=bool(config.get("activities")) and not config.get("no_remote_activities"), enable_nexus=self._nexus_worker is not None, ), @@ -716,6 +731,17 @@ def check_activity(activity: str): disable_payload_error_limit=config.get( "disable_payload_error_limit", False ), + streams=_bridge_streams( + lambda: self.client._config["stream_config"], + config.get("stream_read_time"), + ), + stream_replay_as_workflow_fail=self._workflow_worker is not None + and self._workflow_worker.stream_replay_as_workflow_fail(), + stream_replay_as_workflow_fail_for_types=( + self._workflow_worker.stream_replay_as_workflow_fail_for_types() + if self._workflow_worker + else set() + ), ), ) @@ -758,6 +784,9 @@ def client(self, value: temporalio.client.Client) -> None: raise ValueError( "New client is not on the same runtime as the existing client" ) + _check_stream_swap( + self.client._config["stream_config"], value._config["stream_config"] + ) assert bridge_client._bridge_client self._bridge_worker.replace_client(bridge_client._bridge_client) self._config["client"] = value @@ -1062,6 +1091,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_time: timedelta | None def _poller_behavior_to_bridge( diff --git a/temporalio/worker/_workflow.py b/temporalio/worker/_workflow.py index b0f18b7b8c..58fd845371 100644 --- a/temporalio/worker/_workflow.py +++ b/temporalio/worker/_workflow.py @@ -27,6 +27,7 @@ import temporalio.exceptions import temporalio.workflow from temporalio.bridge.worker import PollShutdownError +from temporalio.client._stream_store import StreamConfig from temporalio.converter import StorageDriverStoreContext, StorageDriverWorkflowInfo from temporalio.worker.workflow_sandbox._runner import SandboxedWorkflowRunner @@ -136,6 +137,7 @@ def __init__( encode_headers: bool, max_workflow_task_external_storage_concurrency: int, default_workflow_logic_flags: frozenset[_WorkflowLogicFlag] | None = None, + stream_config: Callable[[], StreamConfig | None] = lambda: None, ) -> None: # Debug mode is enabled if specified or if the TEMPORAL_DEBUG env var is truthy debug_mode = debug_mode or bool(os.environ.get("TEMPORAL_DEBUG")) @@ -192,6 +194,7 @@ def __init__( **_WorkflowExternFunctions( # type: ignore __temporal_get_metric_meter=lambda: metric_meter, __temporal_assert_local_activity_valid=assert_local_activity_valid, + __temporal_stream_config=stream_config, ) ) @@ -865,6 +868,22 @@ def nondeterminism_as_workflow_fail_for_types(self) -> set[str]: ) } + def stream_replay_as_workflow_fail(self) -> bool: + return any( + issubclass(temporalio.workflow.StreamReplayError, typ) + for typ in self._workflow_failure_exception_types + ) + + def stream_replay_as_workflow_fail_for_types(self) -> set[str]: + return { + k + for k, v in self._workflows.items() + if any( + issubclass(temporalio.workflow.StreamReplayError, typ) + for typ in v.failure_exception_types + ) + } + class _DeadlockError(Exception): """Exception class for deadlocks. Contains functionality to swap the default traceback for another.""" diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index bcca2648a8..ab70a870f1 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -58,7 +58,14 @@ import temporalio.exceptions import temporalio.nexus.system import temporalio.workflow +from temporalio.client._stream_store import _STREAM_SERVICE, StreamConfig from temporalio.converter import StorageDriverStoreContext, StorageDriverWorkflowInfo +from temporalio.nexus.system.stream_service.workflow._system_nexus_interceptor import ( + _start_system_nexus_operation as _start_stream_nexus_operation, +) +from temporalio.nexus.system.stream_service.workflow._system_nexus_interceptor import ( + _SystemNexusWorkflowOutboundInterceptorTerminal as _StreamOutboundInterceptorTerminal, +) from temporalio.nexus.system.workflow_service._system_nexus_interceptor import ( _start_system_nexus_operation, _SystemNexusWorkflowOutboundInterceptorTerminal, @@ -92,6 +99,7 @@ WorkflowInboundInterceptor, WorkflowOutboundInterceptor, ) +from ._workflow_streams import _WorkflowStreams logger = logging.getLogger(__name__) @@ -352,6 +360,7 @@ def __init__(self, det: WorkflowInstanceDetails) -> None: self._pending_nexus_operations: dict[int, _NexusOperationHandle] = {} self._pending_external_signals: dict[int, tuple[asyncio.Future, str]] = {} self._pending_external_cancels: dict[int, tuple[asyncio.Future, str]] = {} + self._streams = _WorkflowStreams(self) # Keyed by type self._curr_seqs: dict[str, int] = {} # TODO(cretz): Any concerns about not sharing this? Maybe the types I @@ -497,6 +506,7 @@ def _activate( self._finished_nexus_update_ids.clear() self._current_activation_error: Exception | None = None + self._streams.task_error = None self._deployment_version_for_current_task = ( act.deployment_version_for_current_task ) @@ -575,10 +585,13 @@ def _activate( check_conditions=index == 1 or index == 2, jobs=act.jobs ) except Exception as err: + # Store outages must remain retryable even when Workflow failure types include them. + if self._streams.task_error: + activation_err = self._streams.task_error # We want some errors during activation, like those that can happen # during payload conversion, to be able to fail the workflow not the # task - if self.workflow_is_failure_exception(err): + elif self.workflow_is_failure_exception(err): try: self._set_workflow_failure(err) except Exception as inner_err: @@ -695,6 +708,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_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"): @@ -1848,7 +1865,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, @@ -2547,6 +2569,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 @@ -3381,7 +3410,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 @@ -3423,7 +3454,9 @@ async def start_nexus_operation( async def _schedule_system_nexus_operation( self, input: StartNexusOperationInput[Any, OutputT] - ) -> _NexusOperationHandle[OutputT]: + ) -> temporalio.workflow.NexusOperationHandle[OutputT]: + if input.service == _STREAM_SERVICE.name: + return self._instance._streams.start(input) return await self._instance._outbound_start_nexus_operation(input) def start_local_activity( @@ -3637,6 +3670,10 @@ def _apply_schedule_command( self._input.local_retry_threshold ) if local_backoff: + if local_backoff.HasField("local_activity_origin"): + command.schedule_local_activity.local_activity_origin.CopyFrom( + local_backoff.local_activity_origin + ) command.schedule_local_activity.attempt = local_backoff.attempt command.schedule_local_activity.original_schedule_time.CopyFrom( local_backoff.original_schedule_time @@ -4052,6 +4089,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..a967f1937b --- /dev/null +++ b/temporalio/worker/_workflow_streams.py @@ -0,0 +1,407 @@ +"""Stream calls of Workflow code.""" + +from __future__ import annotations + +import asyncio +import functools +import typing +from collections.abc import Callable, Generator +from dataclasses import dataclass +from datetime import timedelta +from typing import TYPE_CHECKING, Any, cast + +import google.protobuf.json_format +import google.protobuf.message +from nexusrpc import OutputT + +import temporalio.activity +import temporalio.api.failure.v1 +import temporalio.api.sdk.v1 as sdk +import temporalio.api.stream.v1 +import temporalio.api.streamservice.v1 as proto +import temporalio.bridge.proto.workflow_activation +import temporalio.bridge.proto.workflow_commands +import temporalio.bridge.streams +import temporalio.common +import temporalio.exceptions +import temporalio.nexus.system._support +import temporalio.workflow +from temporalio.api.enums.v1 import StreamErrorReason +from temporalio.client._stream_store import ( + StreamConfig, + StreamStore, + _call_store, + _request_ref, + _sdk_request_type, + _StoreCaller, +) +from temporalio.exceptions import StreamError + +from ._interceptor import StartLocalActivityInput, StartNexusOperationInput + +if TYPE_CHECKING: + from ._workflow_instance import _WorkflowInstanceImpl + +_STORE_CALL_ACTIVITY = "__temporal_stream_store_call" + + +@dataclass +class _Read: + waiter: asyncio.Future[Any] + page_type: Any + + +class _WorkflowStreams: # pyright: ignore[reportUnusedClass] + """Use Local Activities for create and describe because Core has no commands + for those operations. + """ + + def __init__(self, instance: _WorkflowInstanceImpl) -> None: + self._instance = instance + self._appends: dict[int, asyncio.Future[Any]] = {} + self.task_error: Exception | None = None + # Cancelled reads still receive one result from Core. + self._reads: dict[int, _Read] = {} + + def start( + self, input: StartNexusOperationInput[Any, OutputT] + ) -> temporalio.workflow.NexusOperationHandle[OutputT]: + """Schedule before returning so command order matches call order. + + Cancellation stops the caller's wait. Core still completes appends and + reads, so their later results must be discarded. + """ + instance = self._instance + instance._assert_not_read_only("start a Stream call") + operation = input.operation_name + converters = ( + instance._context_free_payload_converter, + instance._context_free_failure_converter, + ) + model = input.input + result_type: Any = input.output_type + request = temporalio.nexus.system._support.model_to_proto(model, *converters) + # Reject missing type information before a result could fail the task. + if isinstance(request, sdk.ReadRecordsRequest) and typing.get_args( + result_type + ) == (object,): + raise TypeError( + "Cannot read a Stream with no body type. Give get_stream a " + "body_type, or a StreamRef with a type argument." + ) + store = self._store(_request_ref(request)).name() + result = _start_call(self, store, operation, request, result_type) + + async def call() -> OutputT: + # `asyncio.wait` ends at a cancel of this task. `await result` would pass the + # cancel on and wait for the cancelled Local Activity. + await asyncio.wait([result]) + if isinstance(request, sdk.ReadRecordsRequest): + return result.result() + return temporalio.nexus.system._support.model_from_proto( + self._response(operation, request, result), + result_type, + *converters, + ) + + def stop(_: asyncio.Task[OutputT]) -> None: + if result.done(): + return + result.cancel() + + task = instance.create_task(call(), name=f"stream: {operation}") + # A callback also runs for a task that is cancelled before its first step. + task.add_done_callback(stop) + return _StreamCall(task) + + def _store(self, ref: sdk.StreamRef) -> StreamStore: + config = self._stream_config() + if config is None: + raise self._fail_task( + ValueError( + "Worker or Replayer has no stream_config, which every " + "Stream call requires, also in a replay." + ) + ) + try: + return config._store_for(ref, self._instance._info.namespace) + except Exception as err: + raise self._fail_task(err) + + def resolve_append( + self, job: temporalio.bridge.proto.workflow_activation.ResolveStreamAppend + ) -> None: + future = self._appends.pop(job.seq, None) + if future is None: + raise RuntimeError(f"Failed finding Stream append for sequence {job.seq}") + # Core completes writes even after their caller is cancelled. + if future.done(): + return + if job.HasField("failed"): + future.set_exception(self._error(job.failed)) + else: + future.set_result(job.appended) + + def 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}") + if read.waiter.done(): + return + if job.HasField("failed"): + read.waiter.set_exception(self._error(job.failed)) + return + page = proto.ReadRecordsResponse(records=job.page.records) + # Conversion failures must fail the task before Workflow code resumes. + 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 _error(self, failure: temporalio.api.failure.v1.Failure) -> BaseException: + instance = self._instance + return _stream_error_from_failure(failure) or ( + instance._context_free_failure_converter.from_failure( + failure, instance._context_free_payload_converter + ) + ) + + def _schedule_store_call( + self, + store: str, + operation: str, + request: google.protobuf.message.Message, + request_id: str | None, + ) -> asyncio.Future[Any]: + instance = self._instance + activity = instance._outbound.start_local_activity( + StartLocalActivityInput( + activity=_STORE_CALL_ACTIVITY, + args=(operation, store, request.SerializeToString(), request_id), + activity_id=None, + # A call that hangs ends before the heartbeat of the Workflow Task, and an + # outage fails the task immediately, so neither writes into History. + schedule_to_close_timeout=instance._info.task_timeout / 2, + schedule_to_start_timeout=None, + start_to_close_timeout=None, + retry_policy=temporalio.common.RetryPolicy(maximum_attempts=1), + local_retry_threshold=None, + cancellation_type=temporalio.workflow.ActivityCancellationType.TRY_CANCEL, + headers={}, + summary=None, + arg_types=None, + ret_type=None, + ) + ) + # Nothing awaits the Activity once its call is cancelled. + activity.add_done_callback(lambda done: done.cancelled() or done.exception()) + return activity + + def _response( + self, + operation: str, + request: google.protobuf.message.Message, + result: asyncio.Future[Any], + ) -> google.protobuf.message.Message: + if isinstance(request, sdk.AppendRecordsRequest): + appended = result.result() + return proto.AppendRecordsResponse( + first_offset=appended.first_offset, last_offset=appended.last_offset + ) + try: + answer = result.result() + except temporalio.exceptions.FailureError as err: + # A refusal of the Store comes as the failure of the attempt. A timeout comes + # inside an Activity failure, which has no Stream details. + error = _stream_error_from_failure(err.failure) if err.failure else None + if ( + error is None + or error.reason + == StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE + ): + # Workflow code could catch an error of this call, so the task fails and + # nothing goes into History, as for an outage during an append. + outage = RuntimeError(f"Stream Store call {operation} failed") + outage.__cause__ = err + raise self._fail_task(outage) + raise error from err + # Replay must retain the Store recorded by create. + if isinstance(request, sdk.CreateStreamRequest): + return sdk.CreateStreamResponse.FromString(answer) + return proto.DescribeStreamResponse.FromString(answer) + + def _fail_task(self, error: Exception) -> Exception: + """Prevent caught errors from recording an unserved call as successful.""" + self.task_error = self._instance._current_activation_error = error + return error + + def _stream_config(self) -> StreamConfig | None: + functions = self._instance._extern_functions + return cast( + Callable[[], StreamConfig | None], functions["__temporal_stream_config"] + )() + + +def _start_call( + streams: _WorkflowStreams, + store: str, + operation: str, + request: google.protobuf.message.Message, + result_type: Any, +) -> asyncio.Future[Any]: + """Use the selected Store in commands so replay can detect routing changes.""" + instance = streams._instance + stream = sdk.StreamRef(id=_request_ref(request).id, store=store) + if isinstance(request, sdk.AppendRecordsRequest): + seq = instance._next_seq("stream_append") + append = instance._add_command().append_to_stream + append.seq = seq + append.stream.CopyFrom(stream) + append.bodies.extend(record.body for record in request.records) + result = streams._appends[seq] = instance.create_future() + return result + if isinstance(request, sdk.ReadRecordsRequest): + seq = instance._next_seq("stream_read") + instance._add_command().read_stream.CopyFrom( + temporalio.bridge.proto.workflow_commands.ReadStream( + seq=seq, + stream=stream, + after_offset=request.after_offset, + wait=request.wait if request.HasField("wait") else None, + max_records=request.max_records, + max_bytes=request.max_bytes, + ) + ) + result = instance.create_future() + streams._reads[seq] = _Read(result, result_type) + return result + # Runs in a chain must retry the same create. + request_id = None + if isinstance(request, sdk.CreateStreamRequest): + request_id = instance._info.first_execution_run_id + return streams._schedule_store_call(store, operation, request, request_id) + + +class _StreamCall(temporalio.workflow.NexusOperationHandle[OutputT]): + """Cancel the caller's wait without waiting for the Store call to finish.""" + + def __init__(self, task: asyncio.Task[OutputT]) -> None: + self._task = task + + @property + def operation_token(self) -> str | None: + return None + + def __await__(self) -> Generator[Any, Any, OutputT]: + return self._task.__await__() + + def cancel(self) -> bool: + return self._task.cancel() + + +@temporalio.activity.defn(name=_STORE_CALL_ACTIVITY) +async def _stream_store_call( # pyright: ignore[reportUnusedFunction] + operation: str, store: str, request: bytes, request_id: str | None +) -> bytes: + """Record the selected Store in create results so replay keeps the same ref.""" + info = temporalio.activity.info() + if not info.is_local or operation not in ("CreateStream", "DescribeStream"): + raise temporalio.exceptions.ApplicationError( + f"{_STORE_CALL_ACTIVITY} is an Activity of the SDK, which only runs " + "a create or a describe of a Stream as a Local Activity", + non_retryable=True, + ) + client = temporalio.activity.client() + stream_config = client._config["stream_config"] + if stream_config is None: + raise ValueError("Client of this Worker has no stream_config.") + stream_request = _sdk_request_type(operation).FromString(request) + response = await _call_store( + stream_config._store(store), + stream_config._limits(), + client.data_converter.payload_codec, + operation, + stream_request, + request_id, + ) + return response.SerializeToString() + + +def _stream_error_from_failure( + failure: temporalio.api.failure.v1.Failure, +) -> StreamError | None: + """Accept Core's binary details and the default converter's JSON details.""" + details = temporalio.api.stream.v1.StreamErrorDetails() + for payload in failure.application_failure_info.details.payloads: + if payload.metadata.get("messageType") != details.DESCRIPTOR.full_name.encode(): + continue + # Core writes the details as binary, and the default converter as JSON. + if payload.metadata.get("encoding") == b"json/protobuf": + try: + google.protobuf.json_format.Parse(payload.data, details) + except google.protobuf.json_format.ParseError: + # The JSON has a reason by a name that this SDK doesn't know. + pass + else: + details.ParseFromString(payload.data) + reason = details.reason + if reason not in StreamErrorReason.values(): + reason = StreamErrorReason.STREAM_ERROR_REASON_UNSPECIFIED + error = StreamError(failure.message, reason=reason) + error._failure = failure + return error + return None + + +def _for_core( + stream_config: StreamConfig | None, +) -> tuple[set[str], tuple[int, int, int] | None]: + if stream_config is None: + return set(), None + return set(stream_config._by_name), stream_config._limits() + + +def _bridge_streams( # pyright: ignore[reportUnusedFunction] + stream_config: Callable[[], StreamConfig | None], + read_time: timedelta | None, +) -> temporalio.bridge.streams.WorkerStreams: + """Resolve Store instances at call time so client replacement takes effect.""" + + def store(name: str) -> StreamStore: + current = stream_config() + assert current + return current._store(name) + + names, limits = _for_core(stream_config()) + return temporalio.bridge.streams.WorkerStreams( + limits=limits, + # Client swaps must affect later Store calls. + stores=[ + (name, _StoreCaller(functools.partial(store, name))) + for name in sorted(names) + ], + read_time_millis=int(1000 * read_time.total_seconds()) + if read_time is not None + else None, + ) + + +def _check_stream_swap( # pyright: ignore[reportUnusedFunction] + existing: StreamConfig | None, new: StreamConfig | None +) -> None: + names, limits = _for_core(existing) + new_names, new_limits = _for_core(new) + if new_names != names: + raise ValueError( + "New client does not have the Stream Stores of the existing client" + ) + if new_limits != limits: + raise ValueError( + "New client does not have the Stream limits of the existing client" + ) diff --git a/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/contrib/streams/__init__.py b/tests/contrib/streams/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/contrib/streams/test_appender.py b/tests/contrib/streams/test_appender.py new file mode 100644 index 0000000000..1b0d5052bb --- /dev/null +++ b/tests/contrib/streams/test_appender.py @@ -0,0 +1,154 @@ +"""Tests of the buffered appender, with no server.""" + +import asyncio +from typing import Any +from unittest.mock import AsyncMock, Mock, call + +import pytest + +from temporalio.api.enums.v1 import StreamErrorReason +from temporalio.contrib.streams import BufferedAppender +from temporalio.exceptions import StreamError +from temporalio.nexus.system.stream_service import AppendRecordsResponse +from tests.helpers.streams import run_with_virtual_clock + + +class _FakeStream: + """Stream whose append takes time on the clock of the loop, and whose batch + number ``fails_at`` fails, or has its write cancelled. + """ + + def __init__( + self, write_time: float, fails_at: int | None = None, cancelled: bool = False + ) -> None: + self._write_time = write_time + self._fails_at = fails_at + self._cancelled = cancelled + self.written: list[int] = [] + self.batches: list[tuple[float, float, tuple[int, ...]]] = [] + """The start time, the end time and the Records of each batch.""" + + async def append(self, *records: int) -> AppendRecordsResponse: + loop = asyncio.get_running_loop() + started = loop.time() + try: + await asyncio.sleep(self._write_time) + if len(self.batches) == self._fails_at: + if self._cancelled: + raise asyncio.CancelledError() + raise StreamError( + "The Store is down", + reason=StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE, + ) + self.written.extend(records) + offset = len(self.written).to_bytes(8, "big") + return AppendRecordsResponse(first_offset=offset, last_offset=offset) + finally: + self.batches.append((started, loop.time(), records)) + + +def test_records_that_arrive_during_a_write_form_the_next_batch() -> None: + async def script() -> None: + stream: Any = _FakeStream(2) + appender = BufferedAppender[int](stream) + appender.append(1) + appender.append(2) + await asyncio.sleep(1) + appender.append(3) + appender.append(4) + await asyncio.sleep(5) + assert stream.batches == [(0, 2, (1, 2)), (2, 4, (3, 4))] + + run_with_virtual_clock(script()) + + +def test_a_flush_takes_over_the_scheduled_write() -> None: + async def script() -> None: + stream: Any = _FakeStream(2) + appender = BufferedAppender[int](stream) + appender.append(1) + assert await appender.flush() == (1).to_bytes(8, "big") + await asyncio.sleep(5) + assert stream.batches == [(0, 2, (1,))] + + run_with_virtual_clock(script()) + + +def test_full_batches_wait_for_the_previous_write() -> None: + async def script() -> None: + stream: Any = _FakeStream(2) + appender = BufferedAppender[int](stream, max_batch_records=2) + assert await appender.flush() is None + appender.append(1, 2) + await asyncio.sleep(1) + appender.append(3, 4, 5) + await asyncio.sleep(6) + assert stream.batches == [(0, 2, (1, 2)), (2, 4, (3, 4)), (4, 6, (5,))] + assert await appender.flush() == (5).to_bytes(8, "big") + + run_with_virtual_clock(script()) + + +def test_cancelling_a_flush_preserves_the_write_and_buffer() -> None: + async def script() -> None: + stream: Any = _FakeStream(2) + async with BufferedAppender[int](stream) as appender: + appender.append(1) + flushing = asyncio.create_task(appender.flush()) + await asyncio.sleep(1) + appender.append(2) + flushing.cancel() + with pytest.raises(asyncio.CancelledError): + await flushing + assert stream.batches == [(0, 2, (1,)), (2, 4, (2,))] + + run_with_virtual_clock(script()) + + +@pytest.mark.parametrize("cancelled", [False, True]) +async def test_a_failed_batch_stops_later_writes(cancelled: bool) -> None: + stream: Any = _FakeStream(0, fails_at=1, cancelled=cancelled) + appender = BufferedAppender[int](stream, max_batch_records=2) + appender.append(1, 2, 3, 4, 5) + with pytest.raises(asyncio.CancelledError if cancelled else StreamError): + await appender.flush() + assert stream.written == [1, 2] + assert appender.unwritten == 3 + later = RuntimeError if cancelled else StreamError + with pytest.raises(later) as raised: + appender.append(6) + with pytest.raises(later) as again: + await appender.flush() + assert raised.value is again.value + + +async def test_append_defers_immediate_writes_with_an_eager_task_factory() -> None: + eager = getattr(asyncio, "eager_task_factory", None) + if eager is None: + pytest.skip("Eager task factories require Python 3.12") + loop = asyncio.get_running_loop() + previous = loop.get_task_factory() + stream = Mock() + stream.append = AsyncMock(return_value=AppendRecordsResponse(last_offset=b"last")) + try: + loop.set_task_factory(eager) + appender = BufferedAppender[int](stream, max_batch_records=1) + appender.append(1) + appender.append(2) + stream.append.assert_not_awaited() + assert await appender.flush() == b"last" + assert stream.append.await_args_list == [call(1), call(2)] + finally: + loop.set_task_factory(previous) + + +@pytest.mark.parametrize("cancelled", [False, True]) +def test_async_with_keeps_the_error_of_its_block(cancelled: bool) -> None: + async def block() -> None: + stream: Any = _FakeStream(0.0, fails_at=0, cancelled=cancelled) + async with BufferedAppender[int](stream) as appender: + appender.append(1) + raise KeyError("The block failed") + + with pytest.raises(KeyError): + run_with_virtual_clock(block()) diff --git a/tests/helpers/streams.py b/tests/helpers/streams.py new file mode 100644 index 0000000000..674ee63c3b --- /dev/null +++ b/tests/helpers/streams.py @@ -0,0 +1,368 @@ +"""Helpers for the tests of Streams.""" + +import asyncio +import collections +import selectors +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, 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, + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, +) +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") + +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(), + ) + + +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.""" + try: + yield + except BaseException as err: + err.add_note(note) + 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.calls: list[tuple[Any, str | None]] = [] + """Each request, with its request id, which is ``None`` for a read and a + describe.""" + self.faults: dict[str, collections.deque[Fault]] = collections.defaultdict( + collections.deque + ) + + @property + def requests(self) -> list[Any]: + """Each request of :py:attr:`calls`.""" + return [request for request, _ in self.calls] + + def name(self) -> str: + return self.memory.name() + + async def create_stream( + self, request: CreateStreamRequest, *, request_id: str + ) -> CreateStreamResponse: + return await self._call("create_stream", request, request_id) + + async def append_records( + self, request: AppendRecordsRequest, *, request_id: str + ) -> AppendRecordsResponse: + return await self._call("append_records", request, request_id) + + async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: + return await self._call("read_records", request) + + async def describe_stream( + self, request: DescribeStreamRequest + ) -> DescribeStreamResponse: + return await self._call("describe_stream", request) + + async def _call( + self, method: str, request: Message, request_id: str | None = None + ) -> Any: + self.calls.append((request, request_id)) + + async def call() -> Any: + if request_id is None: + return await getattr(self.memory, method)(request) + return await getattr(self.memory, method)(request, request_id=request_id) + + if self.faults[method]: + return await self.faults[method].popleft()(call) + return await call() + + +def core_failure(reason: int, message: str = "The Store refused the call") -> Failure: + """Return the failure of a Stream job as SDK Core builds it, also for a reason + number that this SDK doesn't know. + """ + unavailable = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE + details = StreamErrorDetails(reason=reason) # type: ignore[arg-type] + return Failure( + message=message, + application_failure_info=ApplicationFailureInfo( + type="stream_token", + non_retryable=reason != unavailable, + details=Payloads( + payloads=[ + Payload( + metadata={ + "encoding": b"binary/protobuf", + "messageType": details.DESCRIPTOR.full_name.encode(), + }, + data=details.SerializeToString(), + ) + ] + ), + ), + ) + + +def stream_client( + client: Client, + *stores: StreamStore, + store_selector: Callable[[StreamSelectContext], StreamStore] | None = None, + data_converter: DataConverter | None = None, + **limits: int, +) -> Client: + """Return a client on the connection of ``client`` with the given Stream Stores + and limits. + """ + config = client.config() + config["stream_config"] = StreamConfig( + stores, store_selector=store_selector, **limits + ) + if data_converter: + config["data_converter"] = data_converter + return Client(**config) + + +@dataclass +class RunOptions: + """What :py:func:`run` runs, and on which Worker.""" + + workflow: Any + """The Workflow class.""" + + args: Sequence[Any] = () + activities: Sequence[Callable[..., Any]] = () + cached: bool = True + """If false, the Worker caches no run, so each Workflow Task replays its run.""" + + replay: bool = False + """Whether a ``Replayer`` with the Stream config of the client replays the History.""" + + task_timeout: timedelta | None = None + worker: Mapping[str, Any] = field(default_factory=dict) + """More options of the Worker.""" + + during: Callable[[WorkflowHandle[Any, Any], Worker], Awaitable[None]] | None = None + """Called once the Workflow has started, while its Worker runs.""" + + +@dataclass +class Run: + """What a Workflow of :py:func:`run` did.""" + + result: Any + """The result of the Workflow, or the error that it failed with.""" + + history: WorkflowHistory + + +async def run(client: Client, options: RunOptions) -> Run: + """Run a Workflow to its end on a new Worker.""" + async with new_worker( + client, + options.workflow, + activities=options.activities, + max_cached_workflows=1000 if options.cached else 0, + **options.worker, + ) as worker: + handle = await client.start_workflow( + options.workflow.run, + args=options.args, + id=f"wf-{uuid.uuid4()}", + task_queue=worker.task_queue, + task_timeout=options.task_timeout, + ) + if options.during: + await options.during(handle, worker) + result: Any + try: + result = await handle.result() + except WorkflowFailureError as err: + result = err + history = await handle.fetch_history() + if options.replay: + await Replayer( + workflows=[options.workflow], + data_converter=client.data_converter, + stream_config=client._config["stream_config"], + ).replay_workflow(history) + return Run(result, history) + + +class _JumpingSelector(selectors.DefaultSelector): + """Selector that moves the clock of its loop past a wait and doesn't wait.""" + + def __init__(self, loop: "VirtualClockLoop") -> None: + super().__init__() + self._loop = loop + + def select( + self, timeout: float | None = None + ) -> list[tuple[selectors.SelectorKey, int]]: + # With no timer, only another thread can wake the loop, so this waits for it. + if timeout is None: + return super().select(None) + events = super().select(0) + if not events: + self._loop.now += max(timeout, 0) + return events + + +class VirtualClockLoop(asyncio.SelectorEventLoop): + """Event loop whose clock jumps to its next timer when no task can run. + + A test on it must not wait for another thread while a timer is pending, since + the clock then jumps past the wait. + """ + + def __init__(self) -> None: + self.now = 0.0 + super().__init__(_JumpingSelector(self)) + # asyncio runs a timer that is due within the resolution of the real clock, which is + # about 16 ms on Windows. This clock is exact, so its timers run when they are due. + self._clock_resolution = 1e-9 + + def time(self) -> float: + return self.now + + +def run_with_virtual_clock(main: Coroutine[Any, Any, _T]) -> _T: + """Run ``main`` on a new :py:class:`VirtualClockLoop` and return its result.""" + with asyncio.Runner(loop_factory=VirtualClockLoop) as runner: + return runner.run(main) diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py new file mode 100644 index 0000000000..352a874d0b --- /dev/null +++ b/tests/nexus/test_streams.py @@ -0,0 +1,1392 @@ +"""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 Awaitable, Callable +from datetime import datetime, timedelta, timezone +from types import SimpleNamespace +from typing import Any, assert_type, cast, get_args +from unittest.mock import Mock, patch + +import pytest +from google.protobuf.message import Message +from google.protobuf.timestamp_pb2 import Timestamp + +import temporalio.api.sdk.v1 as sdk +import temporalio.api.stream.v1 as stream_api +import temporalio.api.streamservice.v1 as proto +import temporalio.client +import temporalio.converter +import temporalio.nexus.system +import temporalio.workflow +from temporalio.activity import WorkflowTaskAttempt +from temporalio.api.common.v1 import Payload +from temporalio.api.enums.v1 import StreamErrorReason, StreamIdConflictPolicy +from temporalio.api.failure.v1 import Failure +from temporalio.api.stream.v1 import ( + AppendRecord, + ClientProducer, + Producer, + StreamErrorDetails, +) +from temporalio.client import ( + Client, + NexusOperationHandle, + StreamConfig, + StreamSelectContext, +) +from temporalio.client._stream_store import ( + _PRODUCER_IDS, # pyright: ignore[reportPrivateUsage] + _call_store, # pyright: ignore[reportPrivateUsage] + _check_request, # pyright: ignore[reportPrivateUsage] + _store_request, # pyright: ignore[reportPrivateUsage] +) +from temporalio.contrib.streams import as_producer, current_producer +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.nexus.system.stream_service import models as stream_models +from temporalio.nexus.system.stream_service.client import Stream as ClientStream +from temporalio.service import ServiceClient +from temporalio.testing import ActivityEnvironment, MemoryStreamStore +from temporalio.types import ReturnType +from temporalio.worker._workflow_streams import _stream_error_from_failure +from tests.helpers.streams import ( + ContextCodec, + FaultStore, + Hold, + answers, + core_failure, + failure_note, + loses_answer, + run_with_virtual_clock, +) + +_UNAVAILABLE = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE +_INVALID_ARGUMENT = StreamErrorReason.STREAM_ERROR_REASON_INVALID_ARGUMENT + + +class _Interceptor(temporalio.client.Interceptor): + """Gives a client the outbound interceptor that ``outbound`` makes.""" + + def __init__( + self, + outbound: Callable[ + [temporalio.client.OutboundInterceptor], + temporalio.client.OutboundInterceptor, + ], + ) -> None: + super().__init__() + self._outbound = outbound + + def intercept_client( + self, next: temporalio.client.OutboundInterceptor + ) -> temporalio.client.OutboundInterceptor: + return self._outbound(next) + + +class _RecordingOutbound(temporalio.client.OutboundInterceptor): + """Logs the Store name of the ref 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 _record( + self, + input: temporalio.client.StartNexusOperationInput[Any, ReturnType], + call: Awaitable[NexusOperationHandle[ReturnType]], + ) -> NexusOperationHandle[ReturnType]: + ref = getattr(input.arg, "stream_ref", None) or input.arg.ref + before = ref.store + try: + return await call + finally: + self._stores.append((before, ref.store)) + + async def start_create_stream( + self, + input: temporalio.client.StartNexusOperationInput[ + stream_models.CreateStreamRequest[Any], + stream_models.CreateStreamResult[Any], + ], + ) -> NexusOperationHandle[stream_models.CreateStreamResult[Any]]: + return await self._record(input, self.next.start_create_stream(input)) + + async def start_append_records( + self, + input: temporalio.client.StartNexusOperationInput[ + stream_models.AppendRecordsRequest[Any], stream_models.AppendRecordsResponse + ], + ) -> NexusOperationHandle[stream_models.AppendRecordsResponse]: + return await self._record(input, self.next.start_append_records(input)) + + async def start_read_records( + self, + input: temporalio.client.StartNexusOperationInput[ + stream_models.ReadRecordsRequest[Any], + stream_models.ReadRecordsResponse[Any], + ], + ) -> NexusOperationHandle[stream_models.ReadRecordsResponse[Any]]: + return await self._record(input, self.next.start_read_records(input)) + + async def start_describe_stream( + self, + input: temporalio.client.StartNexusOperationInput[ + stream_models.DescribeStreamRequest[Any], + stream_models.DescribeStreamResponse, + ], + ) -> NexusOperationHandle[stream_models.DescribeStreamResponse]: + return await self._record(input, self.next.start_describe_stream(input)) + + async def start_nexus_operation( + self, input: temporalio.client.StartNexusOperationInput + ) -> NexusOperationHandle[Any]: + raise AssertionError( + "Stream calls must bypass generic Nexus start interception" + ) + + async def get_nexus_operation_result( + self, input: temporalio.client.GetNexusOperationResultInput + ) -> Any: + raise AssertionError( + "Stream calls must bypass generic Nexus result interception" + ) + + +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 + + +@pytest.mark.parametrize("operation", ["create", "append", "read", "describe"]) +@pytest.mark.parametrize( + "routing", ["only", "selector", "explicit", "unknown", "unregistered"] +) +@pytest.mark.parametrize("in_activity", [False, True]) +async def test_a_client_call_reaches_the_selected_store( + operation: str, routing: str, in_activity: bool +) -> None: + service_client = Mock(spec=ServiceClient) + a, b = FaultStore("a"), FaultStore("b") + stores = [a] if routing == "only" else [a, b] + selected = FaultStore("other") if routing == "unregistered" else b + selects: list[StreamSelectContext] = [] + + def selector(context: StreamSelectContext) -> FaultStore: + selects.append(context) + return selected + + ref_store = {"explicit": "a", "unknown": "unknown"}.get(routing) + intercepted: list[tuple[str | None, str | None]] = [] + client = Client( + service_client, + interceptors=[_Interceptor(lambda next: _RecordingOutbound(next, intercepted))], + stream_config=StreamConfig( + stores, store_selector=None if routing == "only" else selector + ), + ) + activity = ActivityEnvironment() + activity.info = dataclasses.replace( + activity.info, activity_id="activity", activity_run_id="run" + ) + producer = ( + _producer_proto(activity.run(current_producer)) + if in_activity + else Producer( + client=ClientProducer(namespace="default", id=client._stream_producer_id) + ) + ) + for store in stores: + await store.memory.create_stream( + proto.CreateStreamRequest(stream_id="s"), request_id="setup" + ) + store.faults["read_records"].extend([answers(proto.ReadRecordsResponse())] * 2) + stream = client.get_stream(StreamRef[int](id="s", store=ref_store)) + payload = temporalio.converter.PayloadConverter.default.to_payload + expected: Message + if operation == "create": + expected = proto.CreateStreamRequest( + stream_id="s", + id_conflict_policy=StreamIdConflictPolicy.STREAM_ID_CONFLICT_POLICY_USE_EXISTING, + ) + elif operation == "append": + expected = proto.AppendRecordsRequest( + stream_id="s", + producer=producer, + records=[AppendRecord(body=payload(i)) for i in (3, 5)], + ) + elif operation == "read": + expected = proto.ReadRecordsRequest( + stream_id="s", max_records=2, max_bytes=4096 + ) + expected.wait.FromSeconds(5) + else: + expected = proto.DescribeStreamRequest(stream_id="s") + + async def call() -> Any: + if operation == "create": + return await client.create_stream( + id="s", + store=ref_store, + body_type=int, + id_conflict_policy=ConflictPolicy.StreamIdConflictPolicyUseExisting, + ) + if operation == "append": + return await stream.append(3, 5) + if operation == "read": + return await stream.read_page( + max_records=2, max_bytes=4096, wait=timedelta(seconds=5) + ) + return await stream.describe() + + if routing in ("unknown", "unregistered"): + with pytest.raises(ValueError): + await (activity.run(call) if in_activity else call()) + assert not a.calls and not b.calls and not service_client.mock_calls + return + + for _ in range(2): + result = await (activity.run(call) if in_activity else call()) + if operation == "create": + assert result.created is False + assert result.ref == StreamRef( + id="s", store="b" if routing == "selector" else "a" + ) + chosen, other = (b, a) if routing == "selector" else (a, b) + assert chosen.requests == [expected, expected] + assert not other.calls and not service_client.mock_calls + ids = [request_id for _, request_id in chosen.calls] + if operation in ("create", "append"): + assert all(ids) and ids[0] != ids[1] + else: + assert ids == [None, None] + assert intercepted == [(ref_store, ref_store)] * 2 + assert selects == ( + [StreamSelectContext(id="s", namespace="default")] * 2 + if routing == "selector" + else [] + ) + + +async def test_a_client_without_stream_config_does_not_call_the_server() -> None: + service_client = Mock(spec=ServiceClient) + with pytest.raises(ValueError): + await Client(service_client).create_stream(id="s") + assert not service_client.mock_calls + + +async def test_a_stream_hook_can_change_the_request_and_response() -> None: + metadata: dict[str, str | bytes] = {"key": "value", "binary": b"value"} + timeout = timedelta(seconds=3) + received: list[tuple[str, object, object, object]] = [] + + class Edit(temporalio.client.OutboundInterceptor): + async def start_create_stream( + self, + input: temporalio.client.StartNexusOperationInput[ + stream_models.CreateStreamRequest[Any], + stream_models.CreateStreamResult[Any], + ], + ) -> NexusOperationHandle[stream_models.CreateStreamResult[Any]]: + received.append( + ( + str(input._stream_request_id), + input.result_type, + input.rpc_metadata, + input.rpc_timeout, + ) + ) + handle = await super().start_create_stream( + dataclasses.replace( + input, + arg=dataclasses.replace( + input.arg, + stream_ref=dataclasses.replace( + input.arg.stream_ref, id="changed" + ), + ), + ), + ) + response = await handle.result() + handle._known_outcome = dataclasses.replace(response, created=False) + return handle + + store = FaultStore() + client = Client( + Mock(spec=ServiceClient), + stream_config=StreamConfig([store]), + interceptors=[_Interceptor(Edit)], + ) + stream = await client.create_stream( + id="original", + body_type=int, + rpc_metadata=metadata, + rpc_timeout=timeout, + ) + assert stream.ref.id == "changed" + assert stream.created is False + assert store.requests == [proto.CreateStreamRequest(stream_id="changed")] + assert received == [ + ( + store.calls[0][1], + stream_models.CreateStreamResult[int], + metadata, + timeout, + ) + ] + + +async def test_a_stream_hook_can_return_without_calling_the_store() -> None: + class Cached(temporalio.client.OutboundInterceptor): + async def start_describe_stream( + self, + input: temporalio.client.StartNexusOperationInput[ + stream_models.DescribeStreamRequest[Any], + stream_models.DescribeStreamResponse, + ], + ) -> NexusOperationHandle[stream_models.DescribeStreamResponse]: + handle: NexusOperationHandle[stream_models.DescribeStreamResponse] = ( + NexusOperationHandle(Mock(), input.id) + ) + handle._known_outcome = stream_models.DescribeStreamResponse( + last_offset=b"cached" + ) + return handle + + service_client = Mock(spec=ServiceClient) + client = Client(service_client, interceptors=[_Interceptor(Cached)]) + response = await client.get_stream(StreamRef[int](id="s")).describe() + assert response.last_offset == b"cached" + assert not service_client.mock_calls + + +async def test_stream_hooks_preserve_the_nexus_input_envelope() -> None: + seen: list[ + temporalio.client.StartNexusOperationInput[ + stream_models.CreateStreamRequest[Any], + stream_models.CreateStreamResult[Any], + ] + ] = [] + + class Inspect(temporalio.client.OutboundInterceptor): + async def start_create_stream( + self, + input: temporalio.client.StartNexusOperationInput[ + stream_models.CreateStreamRequest[Any], + stream_models.CreateStreamResult[Any], + ], + ) -> NexusOperationHandle[stream_models.CreateStreamResult[Any]]: + seen.append(input) + return await super().start_create_stream(input) + + store = FaultStore() + service_client = Mock(spec=ServiceClient) + client = Client( + service_client, + stream_config=StreamConfig([store]), + interceptors=[_Interceptor(Inspect), _Interceptor(Inspect)], + ) + request = stream_models.CreateStreamRequest( + stream_ref=StreamRef[int](id="envelope") + ) + nexus: temporalio.client.NexusClient[Any] = client.create_nexus_client( + "temporal.api.streamservice.v1.StreamService", + endpoint=temporalio.nexus.system.TEMPORAL_SYSTEM_ENDPOINT, + ) + metadata = {"key": "value"} + handle = await nexus.start_operation( + "CreateStream", + request, + id="operation-id", + result_type=stream_models.CreateStreamResult[int], + schedule_to_close_timeout=timedelta(seconds=10), + schedule_to_start_timeout=timedelta(seconds=8), + start_to_close_timeout=timedelta(seconds=6), + headers={"header": "value"}, + summary="create a stream", + rpc_metadata=metadata, + rpc_timeout=timedelta(seconds=3), + ) + assert (await handle.result()).created is True + first, second = seen + assert first is second + assert first.arg is request + assert first.id == "operation-id" + assert first.result_type == stream_models.CreateStreamResult[int] + assert first.schedule_to_close_timeout == timedelta(seconds=10) + assert first.schedule_to_start_timeout == timedelta(seconds=8) + assert first.start_to_close_timeout == timedelta(seconds=6) + assert first.headers == {"header": "value"} + assert first.summary == "create a stream" + assert first.rpc_metadata == metadata + assert first.rpc_timeout == timedelta(seconds=3) + assert store.calls == [ + (proto.CreateStreamRequest(stream_id="envelope"), str(first._stream_request_id)) + ] + assert not service_client.mock_calls + + +async def test_unknown_stream_operation_bypasses_generic_nexus() -> None: + service_client = Mock(spec=ServiceClient) + client = Client(service_client) + nexus: temporalio.client.NexusClient[Any] = client.create_nexus_client( + "temporal.api.streamservice.v1.StreamService", + endpoint=temporalio.nexus.system.TEMPORAL_SYSTEM_ENDPOINT, + ) + with pytest.raises(ValueError, match="Unknown"): + _ = await nexus.start_operation("Unknown", None, id="unknown") + assert not service_client.mock_calls + + +def test_the_client_gives_the_handle_of_a_ref_with_its_body_type() -> None: + client = Client( + Mock(spec=ServiceClient), stream_config=StreamConfig([FaultStore()]) + ) + typed = client.get_stream(StreamRef[int](id="s", store="a"), created=True) + by_type = client.get_stream(StreamRef(id="s"), body_type=str) + any_body = client.get_stream(StreamRef[object](id="s"), body_type=bytes) + assert_type(typed, ClientStream[int]) + assert_type(by_type, ClientStream[str]) + assert_type(any_body, ClientStream[bytes]) + assert typed.ref == StreamRef(id="s", store="a") + for stream, body_type, created in ( + (typed, int, True), + (by_type, str, None), + (any_body, bytes, None), + ): + assert get_args(getattr(stream, "__orig_class__")) == (body_type,) + assert get_args(getattr(stream.ref, "__orig_class__")) == (body_type,) + assert stream.created is created + # The overloads refuse this call statically, so the ref is typed `Any` here. + mismatched: Any = StreamRef[int](id="s") + with pytest.raises(TypeError, match="must match the typed ref"): + client.get_stream(mismatched, body_type=str) + + +async def test_a_created_stream_keeps_its_selected_store() -> None: + a, b = FaultStore("a"), FaultStore("b") + selected = a + client = Client( + Mock(spec=ServiceClient), + stream_config=StreamConfig([a, b], store_selector=lambda _: selected), + ) + stream = await client.create_stream(id="s", body_type=int) + selected = b + await stream.append(1) + await stream.describe() + assert stream.ref.store == "a" + assert [type(request) for request in a.requests] == [ + proto.CreateStreamRequest, + proto.AppendRecordsRequest, + proto.DescribeStreamRequest, + ] + assert not b.calls + + +async def test_a_client_retry_recovers_a_lost_store_answer() -> None: + class Retry(temporalio.client.OutboundInterceptor): + async def _retry(self, call: Callable[[], Awaitable[ReturnType]]) -> ReturnType: + try: + return await call() + except StreamError as err: + if err.reason != _UNAVAILABLE: + raise + return await call() + + async def start_create_stream( + self, + input: temporalio.client.StartNexusOperationInput[ + stream_models.CreateStreamRequest[Any], + stream_models.CreateStreamResult[Any], + ], + ) -> NexusOperationHandle[stream_models.CreateStreamResult[Any]]: + return await self._retry( + lambda: self.next.start_create_stream(dataclasses.replace(input)) + ) + + async def start_append_records( + self, + input: temporalio.client.StartNexusOperationInput[ + stream_models.AppendRecordsRequest[Any], + stream_models.AppendRecordsResponse, + ], + ) -> NexusOperationHandle[stream_models.AppendRecordsResponse]: + return await self._retry( + lambda: self.next.start_append_records(dataclasses.replace(input)) + ) + + store = FaultStore() + store.faults["create_stream"].append(loses_answer()) + store.faults["append_records"].append(loses_answer()) + client = Client( + Mock(spec=ServiceClient), + stream_config=StreamConfig([store]), + interceptors=[_Interceptor(Retry)], + ) + stream = await client.create_stream(id="s", body_type=int) + assert stream.created is True + await stream.append(1) + await stream.append(2) + create, create_retry, append, append_retry, second = (key for _, key in store.calls) + assert create == create_retry + assert append == append_retry + assert len({create, append, second}) == 3 + assert [record.body for record in (await stream.read_page()).records] == [1, 2] + + +async def test_an_empty_client_append_does_not_reach_the_store() -> None: + store = FaultStore() + client = Client(Mock(spec=ServiceClient), stream_config=StreamConfig([store])) + with pytest.raises(StreamError) as raised: + await client.get_stream(StreamRef[int](id="s")).append() + assert raised.value.reason == _INVALID_ARGUMENT + assert not store.calls + + +_PRODUCER_KINDS: dict[str, dict[str, Any]] = { + "workflow": { + "namespace": "n", + "workflow_id": "w", + "run_id": "r", + "attempt": {"started_event_id": 3, "attempt": 1}, + }, + "local_activity": { + "namespace": "n", + "workflow_id": "w", + "run_id": "r", + "activity_id": "a", + "attempt": {"task": {"started_event_id": 3, "attempt": 1}, "attempt": 1}, + }, + "workflow_activity": { + "namespace": "n", + "workflow_id": "w", + "run_id": "r", + "activity_id": "a", + "attempt": {"attempt_scheduled_time": {"seconds": 1}, "attempt": 1}, + }, + "standalone_activity": { + "namespace": "n", + "activity_id": "a", + "run_id": "r", + "attempt": {"attempt_scheduled_time": {"seconds": 1}, "attempt": 1}, + }, + "client": {"namespace": "n", "id": "c"}, +} +"""The fields of a Producer of each kind that a Store takes.""" + + +def _producer_of(kind: str, **fields: Any) -> Producer: + arguments: dict[str, Any] = {kind: {**_PRODUCER_KINDS[kind], **fields}} + return Producer(**arguments) + + +async def test_a_bad_request_fails_before_the_store() -> None: + store = FaultStore() + limits = (1536 * 1024, 4 * 1024 * 1024, 2) + invalid, too_large = ( + _INVALID_ARGUMENT, + StreamErrorReason.STREAM_ERROR_REASON_TOO_LARGE, + ) + ref = sdk.StreamRef(id="s") + body = Payload(data=b"x") + client = _producer_of("client") + + def create(**fields: Any) -> tuple[str, Message]: + fields = {"stream_ref": ref, **fields} + return "CreateStream", sdk.CreateStreamRequest(**fields) + + def append( + producer: Producer | None = client, **fields: Any + ) -> tuple[str, Message]: + fields = {"ref": ref, "records": [AppendRecord(body=body)] * 2, **fields} + return "AppendRecords", sdk.AppendRecordsRequest(producer=producer, **fields) + + def read(**fields: Any) -> tuple[str, Message]: + fields = {"ref": ref, **fields} + return "ReadRecords", sdk.ReadRecordsRequest(**fields) + + def describe(**fields: Any) -> tuple[str, Message]: + fields = {"ref": ref, **fields} + return "DescribeStream", sdk.DescribeStreamRequest(**fields) + + activity = {"attempt_scheduled_time": {"seconds": 1}, "attempt": 1} + task = {"started_event_id": 3, "attempt": 1} + no_id = "The Stream id is empty" + # Each of the 2049 characters has two bytes in UTF-8. + long_id = sdk.StreamRef(id="é" * 2049) + long_id_message = "The Stream id has 4098 bytes, more than 4096" + cases: list[tuple[tuple[str, Message], StreamErrorReason.ValueType, str]] = [ + (create(stream_ref=sdk.StreamRef()), invalid, no_id), + (create(stream_ref=long_id), invalid, long_id_message), + (create(id_conflict_policy=99), invalid, "The conflict policy 99 is unknown"), + (append(ref=sdk.StreamRef()), invalid, no_id), + (append(None), invalid, "The request has no Producer"), + (append(Producer()), invalid, "The Producer has no kind"), + ( + append(_producer_of("workflow", attempt=None)), + invalid, + "The Producer has no Workflow Task attempt", + ), + ( + append(_producer_of("workflow", workflow_task_id=-1)), + invalid, + "The Workflow Task id is -1, and it must be 0 or more", + ), + ( + append(_producer_of("workflow", attempt={"attempt": 1})), + invalid, + "The Workflow Task attempt has no started event id", + ), + ( + append(_producer_of("workflow", attempt={**task, "attempt": 0})), + invalid, + "The Workflow Task attempt number is 0, and it must be 1 or more", + ), + ( + append( + _producer_of( + "workflow", attempt={**task, "started_time": {"seconds": -1}} + ) + ), + invalid, + "The started time of the Workflow Task is before the Unix epoch", + ), + ( + append( + _producer_of( + "workflow", + attempt={**task, "started_time": {"nanos": 1_000_000_000}}, + ) + ), + invalid, + "The started time of the Workflow Task has 1000000000 nanos, and it must " + "have 0 to 999999999", + ), + ( + append(_producer_of("local_activity", attempt=None)), + invalid, + "The Producer has no attempt", + ), + ( + append(_producer_of("local_activity", attempt={"attempt": 1})), + invalid, + "The Producer has no Workflow Task that dispatched it", + ), + ( + append(_producer_of("local_activity", attempt={"task": task})), + invalid, + "The Local Activity attempt number is 0, and it must be 1 or more", + ), + ( + append(_producer_of("workflow_activity", scheduled_event_id=-1)), + invalid, + "The scheduled event id is -1, and it must be 0 or more", + ), + ( + append(_producer_of("standalone_activity", attempt=None)), + invalid, + "The Producer has no attempt", + ), + ( + append(_producer_of("standalone_activity", attempt={"attempt": 1})), + invalid, + "The Producer has no attempt scheduled time", + ), + ( + append( + _producer_of( + "workflow_activity", + attempt={**activity, "attempt_scheduled_time": {"seconds": -1}}, + ) + ), + invalid, + "The attempt scheduled time is before the Unix epoch", + ), + ( + append( + _producer_of( + "standalone_activity", + attempt={**activity, "attempt_scheduled_time": {"nanos": -1}}, + ) + ), + invalid, + "The attempt scheduled time has -1 nanos, and it must have 0 to 999999999", + ), + ( + append( + _producer_of("workflow_activity", attempt={**activity, "attempt": 0}) + ), + invalid, + "The Activity attempt number is 0, and it must be 1 or more", + ), + (append(records=[]), invalid, "The batch has no Record"), + ( + append(records=[AppendRecord(body=body), AppendRecord()]), + invalid, + "Record 1 of the batch has no body", + ), + ( + append(records=[AppendRecord(body=body)] * 3), + too_large, + "The batch has 3 Records, more than 2", + ), + (read(ref=sdk.StreamRef()), invalid, no_id), + (read(ref=long_id), invalid, long_id_message), + ( + read(after_offset=b"o" * 1025), + invalid, + "The after_offset of the read has 1025 bytes, more than 1024", + ), + (read(max_records=-1), invalid, "max_records must be 0 or more"), + (read(max_bytes=-1), invalid, "max_bytes must be 0 or more"), + (read(wait={"seconds": -1}), invalid, "wait must be 0 or more"), + (read(wait={"nanos": -1}), invalid, "wait must be 0 or more"), + ( + read(wait={"nanos": 1_000_000_000}), + invalid, + "wait exceeds the protobuf Duration range", + ), + ( + read(wait={"seconds": 315_576_000_001}), + invalid, + "wait exceeds the protobuf Duration range", + ), + (describe(ref=sdk.StreamRef()), invalid, no_id), + (describe(ref=long_id), invalid, long_id_message), + # A request that breaks two rules fails with the rule that Core checks first. + (create(stream_ref=sdk.StreamRef(), id_conflict_policy=99), invalid, no_id), + (append(Producer(), ref=sdk.StreamRef()), invalid, no_id), + (append(None, records=[]), invalid, "The request has no Producer"), + ( + append(_producer_of("workflow", workflow_id="", run_id="")), + invalid, + "The Producer has no Workflow id", + ), + ( + append(_producer_of("local_activity", workflow_task_id=-1, attempt=None)), + invalid, + "The Workflow Task id is -1, and it must be 0 or more", + ), + ( + append(_producer_of("workflow", attempt={"attempt": 0})), + invalid, + "The Workflow Task attempt has no started event id", + ), + ( + append( + _producer_of( + "workflow", + attempt={**task, "started_time": {"seconds": -1, "nanos": -1}}, + ) + ), + invalid, + "The started time of the Workflow Task is before the Unix epoch", + ), + ( + append( + _producer_of( + "workflow_activity", + attempt={"attempt_scheduled_time": {"seconds": -1}, "attempt": 0}, + ) + ), + invalid, + "The attempt scheduled time is before the Unix epoch", + ), + ( + append(records=[AppendRecord()] * 3), + invalid, + "Record 0 of the batch has no body", + ), + ( + append(records=[AppendRecord(body=Payload(data=b"x" * limits[0]))] * 3), + too_large, + "The batch has 3 Records, more than 2", + ), + ( + read(after_offset=b"o" * 1025, max_records=-1), + invalid, + "The after_offset of the read has 1025 bytes, more than 1024", + ), + ( + read(max_records=-1, max_bytes=-1), + invalid, + "max_records must be 0 or more", + ), + ( + read(max_bytes=-1, wait={"seconds": -1}), + invalid, + "max_bytes must be 0 or more", + ), + ( + read(wait={"seconds": -1, "nanos": 1_000_000_000}), + invalid, + "wait must be 0 or more", + ), + ] + # Each text id of each kind of Producer, with the words of its error. + words = { + "namespace": "namespace", + "workflow_id": "Workflow id", + "run_id": "run id", + "activity_id": "Activity id", + "id": "client id", + } + for kind, fields in _PRODUCER_KINDS.items(): + for name in fields.keys() & words.keys(): + missing = append(_producer_of(kind, **{name: ""})) + cases.append((missing, invalid, f"The Producer has no {words[name]}")) + for codec in (None, ContextCodec()): + for (operation, request), reason, message in cases: + with failure_note(f"{message}, with a codec: {codec is not None}"): + with pytest.raises(StreamError) as raised: + await _call_store(store, limits, codec, operation, request, None) + assert (raised.value.reason, raised.value.message) == (reason, message) + assert not store.calls + + # The largest values that the checks take. + longest_id = sdk.StreamRef(id="é" * 2048) + largest_time = {"seconds": 0, "nanos": 999_999_999} + taken = [ + create(stream_ref=longest_id), + *(append(_producer_of(kind)) for kind in _PRODUCER_KINDS), + append( + _producer_of( + "workflow", + workflow_task_id=0, + attempt={**task, "started_time": largest_time}, + ) + ), + append( + _producer_of( + "workflow_activity", + scheduled_event_id=0, + attempt={**activity, "attempt_scheduled_time": largest_time}, + ) + ), + read( + ref=longest_id, + after_offset=b"o" * 1024, + wait={"seconds": 315_576_000_000, "nanos": 999_999_999}, + ), + describe(ref=longest_id), + ] + for _, request in taken: + _check_request(_store_request(request), limits) + + +def test_the_producer_check_has_each_id_of_each_kind_in_proto_order() -> None: + kinds = Producer.DESCRIPTOR.oneofs_by_name["kind"].fields + assert set(_PRODUCER_IDS) == {kind.name for kind in kinds} + for kind in kinds: + assert kind.message_type + fields = sorted(kind.message_type.fields, key=lambda field: field.number) + ids = [field.name for field in fields if field.name != "attempt"] + assert [name for name, _ in _PRODUCER_IDS[kind.name]] == ids, kind.name + + +def test_the_append_check_measures_each_record_in_its_stored_size() -> None: + too_large = StreamErrorReason.STREAM_ERROR_REASON_TOO_LARGE + rng = random.Random(0) + for case in range(200): + kind = rng.choice(list(_PRODUCER_KINDS)) + # Ids of 200 bytes or more give the Producer a longer length prefix. + ids = { + name: "i" * rng.choice([1, 2, 200, 20_000]) + for name, value in _PRODUCER_KINDS[kind].items() + if isinstance(value, str) + } + producer = _producer_of(kind, **ids) + bodies = [ + Payload( + metadata=rng.choice([{}, {"encoding": b"json/plain"}]), + data=b"x" * rng.choice([0, 1, 127, 128, 300, 20_000]), + ) + for _ in range(rng.randint(1, 3)) + ] + request = proto.AppendRecordsRequest( + stream_id="s", + producer=producer, + records=[AppendRecord(body=body) for body in bodies], + ) + sizes = [ + stream_api.StreamRecord(producer=producer, body=body).ByteSize() + for body in bodies + ] + largest, total, count = max(sizes), sum(sizes), len(sizes) + with failure_note(f"case {case}"): + _check_request(request, (largest, total, count)) + over_record = ( + (largest - 1, total, count), + f"Record {sizes.index(largest)} of the batch has {largest} bytes, " + f"more than {largest - 1}", + ) + over_batch = ( + (largest, total - 1, count), + f"The batch has {total} bytes, more than {total - 1}", + ) + # The size of each Record comes before the size of the batch. + over_both = ((largest - 1, total - 1, count), over_record[1]) + for limits, message in (over_record, over_batch, over_both): + with pytest.raises(StreamError) as raised: + _check_request(request, limits) + assert (raised.value.reason, raised.value.message) == ( + too_large, + message, + ) + + +async def test_a_stream_error_keeps_its_reason_on_every_path() -> None: + converter = temporalio.converter.DataConverter.default + for number in [*StreamErrorReason.values(), 99]: + known = number in StreamErrorReason.values() + reason = StreamErrorReason.ValueType(number if known else 0) + token = ( + "stream_" + + StreamErrorReason.Name(reason) + .removeprefix("STREAM_ERROR_REASON_") + .lower() + ) + message = f"The call failed with {number}" + expected = (reason, token, message, reason != _UNAVAILABLE) + details = StreamErrorDetails(reason=number) # type: ignore[arg-type] + + # Through an Activity, which gives its error to the default failure converter. + raised: ApplicationError = ( + StreamError(message, reason=reason) + if known + else ApplicationError(message, details, type=token, non_retryable=True) + ) + failure = Failure() + converter.failure_converter.to_failure( + raised, converter.payload_converter, failure + ) + # From Core, which builds the failure of a Stream job itself. + from_core = core_failure(number, message) + for form in (failure, from_core): + error = _stream_error_from_failure(form) + assert error is not None, number + # A copy of the error, also one from another process, is the same error. + for same in (error, copy.copy(error), pickle.loads(pickle.dumps(error))): + assert ( + same.reason, + same.type, + same.message, + same.non_retryable, + ) == expected, number + if not known: + # A newer Worker can record a reason by a name that this SDK doesn't have. + named = failure.application_failure_info.details.payloads[0] + named.data = b'{"reason": "STREAM_ERROR_REASON_ADDED_LATER"}' + later = _stream_error_from_failure(failure) + assert later and (later.reason, later.message) == (reason, message) + assert _stream_error_from_failure(Failure(message="other")) is None + + +class _FakeReads(temporalio.client.OutboundInterceptor): + def __init__(self, next: temporalio.client.OutboundInterceptor) -> None: + super().__init__(next) + self.pages = iter([(1, 2), (), (3, 4), (), (4, 5)]) + self.starts: list[int] = [] + self.waits: list[timedelta | None] = [] + + async def start_read_records( + self, + input: temporalio.client.StartNexusOperationInput[ + ReadRecordsRequest[Any], ReadRecordsResponse[Any] + ], + ) -> NexusOperationHandle[ReadRecordsResponse[Any]]: + request = input.arg + self.starts.append(int.from_bytes(request.after_offset or b"", "big")) + self.waits.append(request.wait) + records = [ + StreamRecord(body=at, offset=at.to_bytes(8, "big")) + for at in next(self.pages) + ] + page = ReadRecordsResponse(records=records) + handle: NexusOperationHandle[ReadRecordsResponse[Any]] = NexusOperationHandle( + Mock(), input.id + ) + handle._known_outcome = page + return handle + + +@pytest.mark.parametrize("wait", [None, timedelta(0), timedelta(seconds=5)]) +async def test_a_read_resumes_after_a_partial_page_and_skips_empty_pages( + wait: timedelta | None, +) -> None: + fake: list[_FakeReads] = [] + + def outbound(next: temporalio.client.OutboundInterceptor) -> _FakeReads: + fake.append(_FakeReads(next)) + return fake[0] + + client = Client(Mock(spec=ServiceClient), interceptors=[_Interceptor(outbound)]) + stream = client.get_stream(StreamRef[int](id="s")) + [reads] = fake + got: list[int] = [] + later = _support.DEFAULT_READ_WAIT if wait is None else wait + for stop_at in (3, 5): + offset = got[-1].to_bytes(8, "big") if got else None + async for record in stream.read(after_offset=offset, wait=wait): + got.append(record.body) + if record.body == stop_at: + break + assert got == [1, 2, 3, 4, 5] + assert reads.starts == [0, 2, 2, 3, 3] + assert reads.waits == [wait, later, later, wait, later] + + +@dataclasses.dataclass(frozen=True) +class _WriterInfo: + kind: str + namespace: str + workflow_id: str + run_id: str + activity_id: str + attempt: int + time: datetime + event_id: int + + +def _default_producer(writer: _WriterInfo) -> Any: + """Return the default Producer of a write of ``writer``.""" + if writer.kind == "workflow": + info = SimpleNamespace( + namespace=writer.namespace, + workflow_id=writer.workflow_id, + run_id=writer.run_id, + ) + with patch("temporalio.workflow.info", lambda: info): + return _support.workflow_producer() + in_workflow = writer.kind != "standalone_activity" + activity = ActivityEnvironment() + activity.info = dataclasses.replace( + activity.info, + namespace=writer.namespace, + activity_id=writer.activity_id, + attempt=writer.attempt, + current_attempt_scheduled_time=writer.time, + is_local=writer.kind == "local_activity", + workflow_id=writer.workflow_id if in_workflow else None, + workflow_run_id=writer.run_id if in_workflow else None, + activity_run_id=None if in_workflow else writer.run_id, + workflow_task=WorkflowTaskAttempt( + writer.event_id + 3, writer.attempt + 1, writer.time + ) + if writer.kind == "local_activity" + else None, + _local_activity_origin=(writer.event_id, "original") + if writer.kind == "local_activity" + else None, + _scheduled_event_id=writer.event_id + if writer.kind == "workflow_activity" + else 0, + ) + producer = activity.run(current_producer) + # The default of a write in an Activity is that Producer, and it reads no client. + assert activity.run(_support.default_producer, cast(Any, None)) == producer + return producer + + +def _expected_producer(writer: _WriterInfo) -> Producer: + """Return the whole Producer of ``writer``, built field by field.""" + time = Timestamp() + time.FromDatetime(writer.time) + producer = Producer() + kind = getattr(producer, writer.kind) + kind.namespace, kind.run_id = writer.namespace, writer.run_id + if writer.kind != "standalone_activity": + kind.workflow_id = writer.workflow_id + if writer.kind == "workflow": + return producer + kind.activity_id = writer.activity_id + kind.attempt.attempt = writer.attempt + if writer.kind == "local_activity": + kind.workflow_task_id, kind.activity_id = writer.event_id, "original" + task = kind.attempt.task + task.started_event_id, task.attempt = writer.event_id + 3, writer.attempt + 1 + task.started_time.CopyFrom(time) + else: + kind.attempt.attempt_scheduled_time.CopyFrom(time) + if writer.kind == "workflow_activity": + kind.scheduled_event_id = writer.event_id + return producer + + +@pytest.mark.parametrize( + ("kind", "event_id"), + [ + ("workflow", 7), + ("local_activity", 0), + ("local_activity", 9), + ("workflow_activity", 0), + ("workflow_activity", 17), + ("standalone_activity", 0), + ], +) +def test_a_writer_keeps_its_identity_and_attempt(kind: str, event_id: int) -> None: + writer = _WriterInfo( + kind=kind, + namespace="ns:/é", + workflow_id="workflow", + run_id="run", + activity_id="activity", + attempt=3, + time=datetime(2026, 1, 1, tzinfo=timezone.utc), + event_id=event_id, + ) + producer = _default_producer(writer) + assert _producer_proto(producer) == _expected_producer(writer) + converter = temporalio.converter.PayloadConverter.default + # Heartbeat details can be decoded without a type hint. + [stored] = converter.from_payloads(converter.to_payloads([producer])) + assert as_producer(stored) == producer + assert as_producer(producer) is producer + + +def test_a_local_activity_requires_its_origin_to_identify_a_stream_producer() -> None: + activity = ActivityEnvironment() + activity.info = dataclasses.replace( + activity.info, is_local=True, workflow_task=WorkflowTaskAttempt(17, 2, None) + ) + with pytest.raises(RuntimeError, match="no scheduling origin"): + activity.run(current_producer) + + +def test_a_workflow_producer_preserves_the_task_id_and_attempt() -> None: + proto = Producer() + task = proto.workflow + task.namespace, task.workflow_id, task.run_id = "ns", "workflow", "run" + task.workflow_task_id = 11 + task.attempt.started_event_id, task.attempt.attempt = 37, 2 + assert _producer_proto(as_producer(proto)) == proto + + +def test_a_client_uses_one_producer_for_all_its_streams() -> None: + service_client = Mock(spec=ServiceClient) + config = StreamConfig(stores=[FaultStore()]) + clients = [Client(service_client, stream_config=config) for _ in range(2)] + [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 + + +@dataclasses.dataclass +class _Turn: + text: str + + +@pytest.mark.parametrize( + ("hint", "ref", "body_type"), + [ + (StreamRef[int], StreamRef[int](id="count", store="a"), int), + (StreamRef[str], StreamRef[str](id="text"), str), + (StreamRef[_Turn], StreamRef[_Turn](id="turn", store="b"), _Turn), + (StreamRef, StreamRef(id="untyped"), object), + (StreamRef[int] | None, None, None), + (StreamRef[str] | None, StreamRef[str](id="optional"), str), + ], +) +def test_a_stream_ref_keeps_its_body_type( + hint: Any, ref: StreamRef[Any] | None, body_type: type | None +) -> None: + converter = temporalio.converter.DataConverter.default.payload_converter + client = Client( + Mock(spec=ServiceClient), stream_config=StreamConfig([FaultStore()]) + ) + [decoded] = converter.from_payloads(converter.to_payloads([ref]), [hint]) + assert decoded == ref + if decoded is not None: + for get_stream in (client.get_stream, temporalio.workflow.get_stream): + assert get_stream(decoded).body_type is body_type + + +@dataclasses.dataclass +class _RefFields: + typed: StreamRef[_Turn] + untyped: StreamRef + nested: list[StreamRef[int] | None] + + +def test_stream_ref_fields_keep_their_body_types_inside_lists() -> None: + value = [ + _RefFields( + typed=StreamRef[_Turn](id="turn", store="a"), + untyped=StreamRef(id="untyped"), + nested=[StreamRef[int](id="count"), None], + ) + ] + converter = temporalio.converter.DataConverter.default.payload_converter + client = Client( + Mock(spec=ServiceClient), stream_config=StreamConfig([FaultStore()]) + ) + [decoded] = converter.from_payloads( + converter.to_payloads([value]), [list[_RefFields]] + ) + assert decoded == value + [fields] = decoded + assert fields.nested[1] is None + for get_stream in (client.get_stream, temporalio.workflow.get_stream): + assert get_stream(fields.typed).body_type is _Turn + assert get_stream(fields.untyped).body_type is object + assert get_stream(fields.nested[0]).body_type is int + + +def test_each_stream_module_can_be_the_first_import() -> None: + 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__ + ".") + ), + ] + + 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()) + + +def test_a_client_iterator_on_an_idle_stream_waits_between_reads() -> None: + class ReadLog(MemoryStreamStore): + def __init__(self) -> None: + super().__init__() + self.reads: list[proto.ReadRecordsRequest] = [] + + async def read_records( + self, request: proto.ReadRecordsRequest + ) -> proto.ReadRecordsResponse: + self.reads.append(request) + return await super().read_records(request) + + def waits(store: ReadLog) -> list[timedelta | None]: + return [ + request.wait.ToTimedelta() if request.HasField("wait") else None + for request in store.reads + ] + + async def script() -> None: + loop = asyncio.get_running_loop() + store = ReadLog() + client = Client(Mock(spec=ServiceClient), stream_config=StreamConfig([store])) + stream = await client.create_stream(id="s", body_type=int) + minute = _support.DEFAULT_READ_WAIT + ten, nine = timedelta(seconds=10), timedelta(seconds=9) + # With no wait, the first read answers at once and each later one waits the + # default wait. A wait of zero is the caller's choice to read in a loop, and + # the Store gets no wait for it. A wait ends before the rpc_timeout, so the + # Store answers in time. + cases: list[tuple[timedelta | None, timedelta | None, list[Any]]] = [ + (None, None, [None, minute, minute, minute, minute]), + (ten, None, [ten] * 5), + (timedelta(0), None, [None] * 5), + (None, ten, [None, nine, nine, nine, nine]), + (minute, ten, [nine] * 5), + (timedelta(seconds=5), ten, [timedelta(seconds=5)] * 5), + # A Store has a tenth of a short timeout to answer, and a timeout of + # zero is no timeout. + (ten, timedelta(seconds=2), [timedelta(seconds=1.8)] * 5), + (ten, timedelta(0), [ten] * 5), + ] + for wait, rpc_timeout, expected in cases: + with failure_note(f"wait {wait}, rpc_timeout {rpc_timeout}"): + store.reads.clear() + start = loop.time() + pages = stream.read_pages(wait=wait, rpc_timeout=rpc_timeout) + for _ in expected: + assert not (await anext(pages)).records + await pages.aclose() + assert waits(store) == expected + assert loop.time() - start == pytest.approx( + sum(w.total_seconds() for w in expected if w) + ) + + # A Record that comes during a wait ends it at once, and the caller stops. + async def append_later() -> None: + await asyncio.sleep(90) + await stream.append(1) + + store.reads.clear() + start = loop.time() + appending = asyncio.create_task(append_later()) + async with asyncio.timeout(600): + async for record in stream.read(): + assert record.body == 1 + break + await appending + assert loop.time() - start == pytest.approx(90) + assert waits(store) == [None, minute, minute] + + run_with_virtual_clock(script()) + + +@pytest.mark.parametrize("offsets, expected", [([b"b", b"c"], b"c"), ([], b"a")]) +def test_next_read_resumes_after_the_last_returned_record( + offsets: list[bytes], expected: bytes +) -> None: + request = ReadRecordsRequest(ref=StreamRef[int](id="s"), after_offset=b"a") + page = ReadRecordsResponse( + records=[ + StreamRecord(body=i, offset=offset) for i, offset in enumerate(offsets) + ], + ) + next_request = _support.next_read_request(request, page) + assert next_request is not None and next_request.after_offset == expected diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py new file mode 100644 index 0000000000..37f495304d --- /dev/null +++ b/tests/nexus/test_streams_with_worker.py @@ -0,0 +1,1656 @@ +"""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 +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, + CreateStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, +) +from temporalio.api.taskqueue.v1 import TaskQueue +from temporalio.api.workflowservice.v1 import DescribeTaskQueueRequest +from temporalio.client import Client, StreamConfig, WorkflowFailureError +from temporalio.common import RetryPolicy +from temporalio.contrib.streams import current_producer +from temporalio.converter import ( + DataConverter, + ExternalStorage, +) +from temporalio.exceptions import ApplicationError, StreamError +from temporalio.nexus.system.stream_service import ( + ProducerKindLocalActivity, + ProducerKindWorkflow, + StreamIdConflictPolicy, + StreamRef, +) +from temporalio.testing import MemoryStreamStore +from temporalio.worker import ( + ActivityInboundInterceptor, + Interceptor, + Replayer, + Worker, +) +from tests.helpers import assert_eventually, assert_task_fail_eventually, new_worker +from tests.helpers.streams import ( + ContextCodec, + FaultStore, + Hold, + 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 == "read": + page = await stream.read_page() + bodies = [record.body for record in page.records] + last = page.records[-1].offset if page.records else b"" + answers.append([bodies, last.hex()]) + else: + described = await stream.describe() + answers.append([(described.last_offset or b"").hex()]) + except StreamError as err: + answers.append(["error", err.reason, err.message]) + return answers + + +@activity.defn +async def _calls_activity(calls: list[list[Any]]) -> list[Any]: + return await _answers(activity.client(), calls) + + +@workflow.defn +class _CallsWorkflow: + @workflow.run + async def run(self, calls: list[list[Any]], in_activity: bool = False) -> list[Any]: + if in_activity: + return await workflow.execute_activity( + _calls_activity, calls, start_to_close_timeout=timedelta(seconds=10) + ) + return await _answers(workflow, calls) + + +def _writes(store: FaultStore) -> list[Message]: + """Return each request of a Store but its reads, which Core pages in its own way, + without the Producer, which 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) + if "producer" in copy.DESCRIPTOR.fields_by_name: + copy.ClearField("producer") + 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) + # 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", "describe"] + reads = seed % 2 == 1 + if reads: + operations += ["read", "read"] + for _ in range(rng.randrange(4, 12)): + # 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: + calls += [["read", f"s-{seed}-0"], ["read", f"s-{seed}-1"]] + # The two Stores have one name and the same Stream ids, so a call is the same + # request in both. + for_client, for_workflow = FaultStore(), FaultStore() + 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 _writes(for_workflow) == _writes(for_client) + appends = [ + request_id + for request, request_id in for_workflow.calls + if isinstance(request, AppendRecordsRequest) + ] + assert all(appends) and len(set(appends)) == len(appends) + # A replay with the Stores of the run writes nothing. A replay chooses the + # Store of each call again, so one with no Stream config fails. + written = _writes(for_workflow) + await Replayer( + workflows=[_CallsWorkflow], + stream_config=workflow_client._config["stream_config"], + ).replay_workflow(ran.history) + assert _writes(for_workflow) == written + with pytest.raises(Exception, match="no stream_config"): + await Replayer(workflows=[_CallsWorkflow]).replay_workflow(ran.history) + + +def _bodies(writer: str) -> list[Any]: + """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] + + +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)) + await stream.append(*_bodies("activity")) + + +@workflow.defn +class _BodiesWorkflow: + @workflow.run + 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[Any](id=stream_id)) + await stream.append(*_bodies("workflow")) + bodies: list[Any] = [] + async for record in stream.read(): + bodies.append(record.body) + # A Stream has no end, so the reader stops at the Records of the 3 writers. + if len(bodies) == 3 * len(_bodies("workflow")): + break + return _digest(bodies) + + +async def test_a_body_reads_the_same_on_every_path(client: Client) -> None: + 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]) + ran = await run(client, options) + + expected = [*_bodies("client"), *_bodies("activity"), *_bodies("workflow")] + # A Stream has no end, so the reader takes the Records that it knows of. + records = stream.read() + async with asyncio.timeout(10): + assert [(await anext(records)).body for _ in expected] == expected + assert ran.result == _digest(expected) + # The Store has each body as the codec gave it with no context, and the storage of + # the Worker has none of them. + 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() + ) + + +@activity.defn +async def _append_one(stream_id: str) -> None: + await activity.client().get_stream(StreamRef[int](id=stream_id)).append(1) + + +@workflow.defn +class _OneActivityIdWorkflow: + @workflow.run + async def run(self, stream_id: str) -> None: + for _ in range(2): + await workflow.execute_activity( + _append_one, + stream_id, + activity_id="one id", + start_to_close_timeout=timedelta(seconds=10), + ) + + +async def test_two_activities_with_one_id_write_as_two_producers( + client: Client, +) -> None: + store = FaultStore() + client = stream_client(client, store) + await client.create_stream(id="one id", body_type=int) + options = RunOptions(_OneActivityIdWorkflow, ["one id"], activities=[_append_one]) + ran = await run(client, options) + # The Producer of each Activity has the id of the Activity's scheduled event. + scheduled = _events(ran.history, EventType.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED) + page = await store.memory.read_records(ReadRecordsRequest(stream_id="one id")) + producers = [record.producer.workflow_activity for record in page.records] + assert [(p.activity_id, p.scheduled_event_id) for p in producers] == [ + ("one id", event.event_id) for event in scheduled + ] + + +@activity.defn +async def _write_local_attempt(stream_id: str, retry: bool) -> str: + info = activity.info() + stream = activity.client().get_stream(StreamRef[str](id=stream_id)) + await stream.append(info.activity_id) + if retry and info.attempt == 1: + await activity.wait_for_worker_shutdown() + raise ApplicationError("retry after a timer") + kind = current_producer().kind + assert isinstance(kind, ProducerKindLocalActivity) + return kind.value.activity_id + + +@workflow.defn +class _LocalProducerWorkflow: + @workflow.run + async def run(self, stream_id: str, schedule_after_timer: bool) -> None: + if schedule_after_timer: + await asyncio.sleep(0.01) + original_id = await workflow.execute_local_activity( + _write_local_attempt, + args=[stream_id, True], + start_to_close_timeout=timedelta(seconds=10), + local_retry_threshold=timedelta(milliseconds=50), + retry_policy=RetryPolicy( + initial_interval=timedelta(milliseconds=250), maximum_attempts=2 + ), + ) + await workflow.execute_local_activity( + _write_local_attempt, + args=[stream_id, False], + activity_id=original_id, + start_to_close_timeout=timedelta(seconds=10), + ) + + +@pytest.mark.parametrize("schedule_after_timer", [False, True]) +async def test_local_activity_producers_survive_timer_retries_and_worker_restart( + client: Client, + schedule_after_timer: bool, +) -> None: + store, writing = FaultStore(), Hold() + client = stream_client(client, store) + stream = await client.create_stream(id="local producers", body_type=str) + store.faults["append_records"].append(writing) + async with new_worker( + client, + _LocalProducerWorkflow, + activities=[_write_local_attempt], + identity="before restart", + graceful_shutdown_timeout=timedelta(seconds=10), + ) as first: + queue = first.task_queue + handle = await client.start_workflow( + _LocalProducerWorkflow.run, + args=[stream.ref.id, schedule_after_timer], + id=queue, + task_queue=queue, + ) + await writing.started.wait() + writing.release() + async with new_worker( + client, + _LocalProducerWorkflow, + activities=[_write_local_attempt], + task_queue=queue, + identity="after restart", + ): + await handle.result() + history = await handle.fetch_history() + await Replayer(workflows=[_LocalProducerWorkflow]).replay_workflow(history) + timer_count = 2 if schedule_after_timer else 1 + assert len(_events(history, EventType.EVENT_TYPE_TIMER_STARTED)) == timer_count + starts = _events(history, EventType.EVENT_TYPE_WORKFLOW_TASK_STARTED) + workers = [ + event.workflow_task_started_event_attributes.identity for event in starts + ] + assert workers == ["before restart"] * timer_count + ["after restart"] + origin = starts[0].event_id if schedule_after_timer else 0 + before, after = starts[-2].event_id, starts[-1].event_id + records = (await stream.read_page()).records + first_id, retry_id, reused_id = [record.body for record in records] + assert first_id == reused_id and first_id != retry_id + producers = [] + for record in records: + assert record.producer and isinstance( + record.producer.kind, ProducerKindLocalActivity + ) + producer = record.producer.kind.value + assert producer.attempt and producer.attempt.task + producers.append( + ( + producer.workflow_task_id, + producer.activity_id, + producer.attempt.task.started_event_id, + producer.attempt.attempt, + ) + ) + assert producers == [ + (origin, first_id, before, 1), + (origin, first_id, after, 2), + (before, first_id, after, 1), + ] + + +@workflow.defn +class _WorkflowTaskProducerWorkflow: + @workflow.run + async def run(self, stream_id: str) -> None: + stream = workflow.get_stream(StreamRef[int](id=stream_id)) + await stream.append(1) + await asyncio.sleep(0.1) + await stream.append(2) + await workflow.create_stream(id="after append", body_type=int) + + +async def test_workflow_task_retries_write_as_one_producer(client: Client) -> None: + store = FaultStore() + client = stream_client(client, store) + stream = await client.create_stream(id="task producers", body_type=int) + # Fail the second task after it writes, so its retry writes to the same Stream. + store.faults["create_stream"].append(raises(ConnectionError("down"))) + ran = await run( + client, RunOptions(_WorkflowTaskProducerWorkflow, [stream.ref.id], replay=True) + ) + assert ran.result is None + [first, second] = _events(ran.history, EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED) + [failed] = _events(ran.history, EventType.EVENT_TYPE_WORKFLOW_TASK_FAILED) + first_start = first.workflow_task_completed_event_attributes.started_event_id + page = await stream.read_page() + assert [record.body for record in page.records] == [1, 2, 2] + ids = [] + for record in page.records: + assert record.producer and isinstance( + record.producer.kind, ProducerKindWorkflow + ) + producer = record.producer.kind.value + assert producer.attempt + ids.append((producer.workflow_task_id, producer.attempt.started_event_id)) + assert ids == [ + (0, first_start), + (first_start, failed.workflow_task_failed_event_attributes.started_event_id), + (first_start, second.workflow_task_completed_event_attributes.started_event_id), + ] + + +def _events(history: Any, event_type: EventType.ValueType) -> list[Any]: + return [event for event in history.events if event.event_type == event_type] + + +def _stream_markers(history: Any, kind: str) -> list[Any]: + """Return the markers in which Core records the Stream calls of ``kind``, which + is ``append`` or ``read``. + """ + return [ + event + for event in _events(history, EventType.EVENT_TYPE_MARKER_RECORDED) + if event.marker_recorded_event_attributes.marker_name == f"core_stream_{kind}" + ] + + +async def test_a_store_error_is_the_same_error_on_every_path(client: Client) -> None: + store = FaultStore() + client = stream_client(client, store) + 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]], on: Client = client, **options: Any + ) -> Any: + if path == "client": + return await _answers(on, calls) + args = [calls, path == "activity"] + run_options = RunOptions( + _CallsWorkflow, args, activities=[_calls_activity], **options + ) + return (await run(on, run_options)).result + + def append_request_ids() -> list[str | None]: + calls, store.calls = store.calls, [] + return [i for r, i in calls if isinstance(r, AppendRecordsRequest)] + + # Core tries an append again in an outage of the Store, with one request id, so the + # Store writes it once. Workflow code gets no error, and History has no failure. + 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]] + request_ids = append_request_ids() + assert len(request_ids) == len(faults) + 1 + assert len(set(request_ids)) == 1 + assert not _events(ran.history, EventType.EVENT_TYPE_WORKFLOW_TASK_FAILED) + # A client and an Activity get the outage as the error of their call. + for path in ("client", "activity"): + appends.append(raises(ConnectionError("The connection is gone"))) + [[error, reason, _]] = await answers_on(path, [append]) + assert (error, reason, len(append_request_ids())) == ("error", unavailable, 1) + + # An answer of the wrong message fails the call, and nothing tries it again. + corrupt = StreamErrorReason.STREAM_ERROR_REASON_STORE_CORRUPT + for path in ("client", "activity", "workflow"): + with failure_note(path): + appends.append(answers(DescribeStreamResponse())) + [[error, reason, _]] = await answers_on(path, [append]) + assert (error, reason, len(append_request_ids())) == ("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. + not_found = StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND + calls: list[list[Any]] = [ + ["append", "missing", [1]], + ["describe", "errors"], + ["describe", "missing"], + ["read", "missing"], + ] + refused = await answers_on("client", calls) + assert [answer[:2] for answer in refused] == [ + ["error", not_found], + [(3).to_bytes(8, "big").hex()], + ["error", not_found], + ["error", not_found], + ] + for path in ("activity", "workflow"): + with failure_note(path): + assert await answers_on(path, calls, cached=False, replay=True) == refused + + # When its Retention has passed since its last append, a Stream refuses each call + # as expired, on each path. + expiring = stream_client(client, FaultStore(retention=timedelta(seconds=2))) + stream = await expiring.create_stream(id="expires", body_type=int) + await stream.append(1) + await asyncio.sleep(2.5) + expired = StreamErrorReason.STREAM_ERROR_REASON_EXPIRED + calls = [["append", "expires", [2]], ["describe", "expires"], ["read", "expires"]] + for path in ("client", "activity", "workflow"): + with failure_note(f"expired, {path}"): + answered = await answers_on(path, calls, on=expiring, replay=True) + assert [answer[:2] for answer in answered] == [["error", expired]] * 3 + + # An outage during a create fails the Workflow Task, also on a Worker that fails a + # Workflow for any exception. The create runs in the next task, with the Store back. + for failure_types in ([], [Exception]): + 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, + ] + + +class _DownReadsStore(FaultStore): + """A Store whose reads fail as an outage until :py:attr:`up` is true.""" + + def __init__(self) -> None: + super().__init__() + self.up = False + + async def read_records(self, request: ReadRecordsRequest) -> Any: + if not self.up: + self.calls.append((request, None)) + raise ConnectionError("The connection is gone") + return await super().read_records(request) + + +async def test_a_store_outage_at_a_workflow_read_fails_the_workflow_task( + client: Client, +) -> None: + store = _DownReadsStore() + client = stream_client(client, store) + await (await client.create_stream(id="down", body_type=int)).append(1) + + async def back_after_a_task_failure(handle: Any, _worker: Any) -> None: + await assert_task_fail_eventually(handle) + store.up = True + + # SDK Core tries the read again up to the read limit, and then fails the task, as + # for an append. Workflow code gets no error, also on a Worker that fails a + # Workflow for any exception, and the read runs in the next task. + for failure_types in ([], [Exception]): + with failure_note(f"failure types {failure_types}"): + store.up = False + options = RunOptions( + _CallsWorkflow, + [[["read", "down"]]], + task_timeout=timedelta(seconds=2), + worker={"workflow_failure_exception_types": failure_types}, + during=back_after_a_task_failure, + ) + ran = await run(client, options) + assert ran.result == [[[1], (1).to_bytes(8, "big").hex()]] + failed = _events(ran.history, EventType.EVENT_TYPE_WORKFLOW_TASK_FAILED) + assert failed + for event in failed: + message = event.workflow_task_failed_event_attributes.failure.message + assert message.startswith("StreamStoreUnavailable:"), message + + +@workflow.defn +class _CatchingWorkflow: + @workflow.run + 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]], + ["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( + 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) + + +class _ActivityTypes(Interceptor): + """Logs the type of each Activity that its Worker runs.""" + + def __init__(self) -> None: + super().__init__() + self.types: list[str] = [] + + def intercept_activity( + self, next: ActivityInboundInterceptor + ) -> ActivityInboundInterceptor: + self.types.append(activity.info().activity_type) + return next + + +async def test_a_worker_with_only_workflows_creates_a_stream(client: Client) -> None: + client = stream_client(client, FaultStore()) + interceptor = _ActivityTypes() + pollers: list[Any] = [] + + async def activity_pollers(handle: Any, worker: Worker) -> None: + await handle.result() + described = await client.workflow_service.describe_task_queue( + DescribeTaskQueueRequest( + namespace=client.namespace, + task_queue=TaskQueue(name=worker.task_queue), + task_queue_type=TaskQueueType.TASK_QUEUE_TYPE_ACTIVITY, + ) + ) + pollers.extend(described.pollers) + + options = RunOptions( + _CallsWorkflow, + [[["create", "alone"], ["describe", "alone"]]], + worker={"interceptors": [interceptor]}, + during=activity_pollers, + ) + ran = await run(client, options) + assert ran.result == [["memory", True], [""]] + assert interceptor.types == ["__temporal_stream_store_call"] * 2 + assert not pollers + + +@activity.defn +async def _append_to(stream_id: str) -> None: + stream = activity.client().get_stream(StreamRef[int](id=stream_id)) + await stream.append(3) + + +@workflow.defn +class _SwapWorkflow: + def __init__(self) -> None: + self._swapped = False + + @workflow.signal + def swapped(self) -> None: + self._swapped = True + + @workflow.run + async def run(self, own: str, shared: str) -> str | None: + created = await workflow.create_stream(id=own, body_type=int) + await workflow.wait_condition(lambda: self._swapped) + await created.append(1) + stream = workflow.get_stream(StreamRef[int](id=shared)) + await stream.append(2) + await workflow.execute_activity( + _append_to, shared, start_to_close_timeout=timedelta(seconds=10) + ) + return created.ref.store + + +def _calls(store: FaultStore) -> list[tuple[str, str]]: + """Return the request type and the Stream id of each call of a Store.""" + return [(type(r).__name__, r.stream_id) for r in store.requests] + + +# On a server with worker commands, a lone Worker polls in a loop after a new client. Marked as +# `test_workflow_replace_worker_client` and `test_nexus_client_updates_when_worker_client_changes`. +@pytest.mark.requires_local_server +async def test_a_worker_uses_the_stream_config_of_its_new_client( + client: Client, +) -> None: + for cached in (True, False): + with failure_note(f"cached {cached}"): + first, second = FaultStore("first"), FaultStore("second") + # The new client has other Store objects, with the Streams of the first ones. + new_first, new_second = FaultStore("first"), FaultStore("second") + new_first.memory = first.memory + selects: list[tuple[str, str | None]] = [] + + def pick_first(context: Any) -> FaultStore: + selects.append((context.id, context.namespace)) + return first + + before = stream_client(client, first, second, store_selector=pick_first) + after = stream_client( + client, new_first, new_second, store_selector=lambda _: new_second + ) + await after.create_stream(id="shared", body_type=int) + + async def swap(handle: Any, worker: Worker) -> None: + async def created() -> None: + assert first.requests + + await assert_eventually(created) + # A client with other Store names or other limits is refused. + for other in ( + stream_client(client, FaultStore("third")), + stream_client( + client, + first, + second, + store_selector=pick_first, + max_batch_records=1, + ), + ): + with pytest.raises(ValueError): + worker.client = other + worker.client = after + await handle.signal(_SwapWorkflow.swapped) + + options = RunOptions( + _SwapWorkflow, + ["own", "shared"], + activities=[_append_to], + cached=cached, + during=swap, + ) + # The created Stream stays on its Store. A ref with no Store name goes to the + # Store that the new selector picks, in Workflow code as in an Activity. + assert (await run(before, options)).result == "first" + assert _calls(first) == [("CreateStreamRequest", "own")] + # After the swap, Core calls the Store objects of the new client. + assert _calls(new_first) == [("AppendRecordsRequest", "own")] + assert _calls(new_second) == [ + ("CreateStreamRequest", "shared"), + ("AppendRecordsRequest", "shared"), + ("AppendRecordsRequest", "shared"), + ] + assert not second.requests + # The selector of the Workflow's create got the Stream id and the namespace of + # the Worker. + assert selects == [("own", client.namespace)] + + +@workflow.defn +class _AppendOnceWorkflow: + @workflow.run + async def run(self, stream_id: str) -> None: + await workflow.get_stream(StreamRef[int](id=stream_id)).append(1) + + +async def test_a_replay_fails_when_the_selector_picks_another_store( + client: Client, +) -> None: + first, second = FaultStore("first"), FaultStore("second") + for store in (first, second): + await stream_client(client, store).create_stream(id="picked", body_type=int) + options = RunOptions(_AppendOnceWorkflow, ["picked"]) + ran = await run( + stream_client(client, first, second, store_selector=lambda _: first), options + ) + assert ran.result is None + for picked in (first, second): + with failure_note(f"replay picks {picked.name()}"): + + def select(_: Any) -> FaultStore: + return picked + + config = StreamConfig([first, second], store_selector=select) + replay = Replayer(workflows=[_AppendOnceWorkflow], stream_config=config) + if picked is first: + await replay.replay_workflow(ran.history) + continue + # SDK Core compares the Store of a replayed append with History. + with pytest.raises(workflow.NondeterminismError, match="Store `first`"): + await replay.replay_workflow(ran.history) + + +async def test_an_append_over_a_limit_of_the_config_never_reaches_the_store( + client: Client, +) -> None: + too_large = StreamErrorReason.STREAM_ERROR_REASON_TOO_LARGE + unsupported = StreamErrorReason.STREAM_ERROR_REASON_UNSUPPORTED + default_bytes = 4 * 1024 * 1024 + for seed in range(12): + with failure_note(f"seed {seed}"): + rng = random.Random(seed) + # One seed in four has limits over the defaults, which only the config bounds. + larger = seed % 4 == 0 + record = rng.choice([1000, 3000, 1536 * 1024]) + batch = ( + default_bytes if larger else rng.choice([4000, 20_000, default_bytes]) + ) + count = 1200 if larger else rng.choice([1, 3, 1000]) + # The body sizes of each batch, and whether the batch is within every limit. + # A stored Record counts its Producer, so no size is within 500 bytes of a + # limit, and the test needs no size logic. + batches: list[tuple[list[int], bool]] = [] + if larger: + batches.append(([0] * 1100, True)) + for _ in range(6): + match rng.choice(["fits", "fits", "records", "record", "batch"]): + case "records": + batches.append(([0] * (count + 1), False)) + case "record" if record <= 3000: + batches.append(([2 * record], False)) + case "batch" if batch <= 20_000: + size = min(record, batch) - 500 + batches.append(([size] * (batch // size + 1), False)) + case _: + fits = [rng.randrange(40)] * rng.randrange(1, min(count, 3) + 1) + batches.append((fits, True)) + store = FaultStore() + streams = stream_client( + client, + store, + max_record_bytes=record, + max_batch_bytes=batch, + max_batch_records=count, + ) + + def calls(stream_id: str) -> list[list[Any]]: + appends = [["x" * size for size in sizes] for sizes, _ in batches] + return [["create", stream_id]] + [ + ["append", stream_id, bodies] for bodies in appends + ] + + from_client = await _answers(streams, calls(f"client {seed}")) + workflow_calls = calls(f"workflow {seed}") + if record <= 3000: + # A client with a larger limit writes a Record over the limit of the + # Worker, and a read of Workflow code refuses that Record. + writer = stream_client(client, store) + large = await writer.create_stream(id=f"large {seed}", body_type=str) + await large.append("x" * 2 * record) + workflow_calls.append(["read", f"large {seed}"]) + options = RunOptions(_CallsWorkflow, [workflow_calls], replay=True) + from_workflow = (await run(streams, options)).result + if record <= 3000: + assert from_workflow.pop()[:2] == ["error", unsupported] + for answers in (from_client, from_workflow): + assert [ + "written" if answer[0] != "error" else answer[1] + for answer in answers[1:] + ] == ["written" if fits else too_large for _, fits in batches] + # The Store got the batches within the limits from each path, and no other. + assert [ + len(request.records) + for request in store.requests + if isinstance(request, AppendRecordsRequest) + and request.stream_id != f"large {seed}" + ] == [len(sizes) for sizes, fits in batches if fits] * 2 + + +@workflow.defn +class _ChainWorkflow: + @workflow.run + async def run(self, stream_id: str, runs: int) -> bool | None: + stream = await workflow.create_stream(id=stream_id) + if runs > 1: + workflow.continue_as_new(args=[stream_id, runs - 1]) + return stream.created + + +async def test_a_create_in_a_later_run_of_the_chain_is_the_same_create( + client: Client, +) -> None: + store = FaultStore() + # The Store loses the answer of the first create of each run, so the Workflow Task + # fails after its create ran, and its next attempt makes the create again. + faults = [loses_answer(), lambda call: call(), loses_answer()] + store.faults["create_stream"].extend(faults) + ran = await run( + stream_client(client, store), RunOptions(_ChainWorkflow, ["chain", 2]) + ) + # Each run makes its create twice, and the Store takes all four for one create. + assert ran.result is True + creates = [i for r, i in store.calls if isinstance(r, CreateStreamRequest)] + assert len(creates) == 4 and len(set(creates)) == 1 + + +_handled: dict[int, asyncio.Event] = {} +"""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: + client = activity.client() + stream = client.get_stream(StreamRef[str](id=stream_id)) + workflow_id = activity.info().workflow_id or "" + for number in range(count): + await stream.append(f"a body, number {number}") + # A read makes no Workflow Task for a Record that SDK Core doesn't know of, so + # the writer signals the Workflow. + await client.get_workflow_handle(workflow_id).signal(_ReadingWorkflow.wake) + # The next Record comes only once the Workflow has handled this one. + await _handled[number].wait() + + +@activity.defn +async def _handle(number: int) -> None: + _handled[number].set() + + +@workflow.defn +class _ReadingWorkflow: + @workflow.signal + def wake(self) -> None: + pass + + @workflow.run + async def run(self, stream_id: str, count: int) -> list[int]: + stream = await workflow.create_stream(id=stream_id, body_type=str) + 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) + # A Stream has no end, so the reader stops at the writer's last Record. + if number == count - 1: + break + 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: + stream = await workflow.create_stream(id=stream_id, body_type=int) + if how == "append": + asyncio.ensure_future(stream.append(1)) + elif how == "page": + await stream.append(1) + await stream.read_page(wait=timedelta(minutes=5)) + return + else: + 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) + + +async def test_a_read_that_core_stops_leaves_no_store_task(client: Client) -> None: + # The read limit of the task stops a held Store call, also while the Worker shuts + # down, since the shutdown waits for the task. + for how in ("read limit", "shutdown"): + with failure_note(how): + store, hold = FaultStore(), Hold() + store.faults["read_records"].append(hold) + + async def end(handle: Any, worker: Worker) -> None: + await hold.started.wait() + if how == "shutdown": + await worker.shutdown() + else: + await handle.signal(_EndingWorkflow.go_on) + await asyncio.wait_for(hold.cancelled.wait(), 10) + if how == "shutdown": + await handle.terminate() + + # A task timeout of 2 seconds gives a read limit of 1 second. + options = RunOptions( + _EndingWorkflow, + [f"ends by {how}", how], + task_timeout=timedelta(seconds=2), + during=end, + replay=True, + ) + ran = await run(stream_client(client, store), options) + assert (ran.result is None) == (how == "read limit") + reads = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] + assert len(reads) == 1 + + +@pytest.mark.parametrize("how", ["page", "append"]) +async def test_a_stream_call_does_not_hold_the_last_command( + client: Client, how: str +) -> None: + # A read that gave a page, and an append 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.signal + def wake(self) -> None: + pass + + @workflow.run + async def run(self, how: str) -> list[list[str]]: + s = workflow.get_stream(StreamRef[str](id=f"s of {how}")) + t = workflow.get_stream(StreamRef[str](id=f"t of {how}")) + 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(self._page(s)) + await self._page(t) + offset = (await first).records[-1].offset + second = await self._page(s, offset) + return [[r.body for r in page.records] for page in (await first, second)] + pages: list[list[str]] = [] + offset = None + while True: + page = await s.read_page(after_offset=offset, wait=timedelta(seconds=30)) + pages.append([record.body for record in page.records]) + if page.records: + offset = page.records[-1].offset + # A Stream has no end, so the loop stops at the writer's last Record. + if "b" in pages[-1]: + return pages + + async def _page(self, stream: Any, offset: bytes | None = None) -> Any: + """Return the first page of ``stream`` after ``offset`` that has a Record.""" + while True: + # At the read limit of its task, a read gives a page with no Record. + page = await stream.read_page( + after_offset=offset, wait=timedelta(seconds=30) + ) + if page.records: + return page + + +@pytest.mark.parametrize("how", ["a loop", "two readers"]) +async def test_a_replay_gives_a_read_the_pages_of_the_first_run( + client: Client, how: str +) -> None: + 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) + writes, expected = { + "a loop": ([(s, "a"), (s, "b")], ["a", "b"]), + "two readers": ([(s, "a"), (t, "x"), (s, "b")], ["a", "b"]), + }[how] + + async def write(handle: Any, _worker: Any) -> None: + async def first_task() -> None: + history = await handle.fetch_history() + completed = EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED + assert _events(history, completed) + + # The reads of the first task end with no Record, and a read of an idle Stream + # makes no task. A Signal opens the next task, whose reads start again. The + # pages then come in several activations of that task, and a replay gives each + # page in its activation. + await assert_eventually(first_task) + await handle.signal(_LatePagesWorkflow.wake) + for stream, body in writes: + await stream.append(body) + # The page of this Record gets an activation before the next Record comes. + await asyncio.sleep(0.3) + + # The default read limit is half the task timeout, so a read with no Record + # is cut at 3 s, and a slow host still doesn't time out the task. + options = RunOptions( + _LatePagesWorkflow, + [how], + task_timeout=timedelta(seconds=6), + 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) + marker = EventType.EVENT_TYPE_MARKER_RECORDED + later = [event for event in events[completed + 1 :] if event != marker] + assert later[0] == EventType.EVENT_TYPE_WORKFLOW_EXECUTION_SIGNALED + + +@workflow.defn +class _TwoReadsWorkflow: + @workflow.run + async def run(self, first: str, second: str) -> list[list[str]]: + wait = timedelta(seconds=30) + streams = [workflow.get_stream(StreamRef[str](id=id)) for id in (first, second)] + pages = await asyncio.gather( + *(stream.read_page(wait=wait) for stream in streams) + ) + return [[record.body for record in page.records] for page in pages] + + +async def test_a_replay_gives_each_result_in_the_activation_of_the_first_run( + client: Client, +) -> None: + # A local import, so that the sandbox of each Workflow here doesn't import that module. + from tests.worker.test_workflow import CustomWorkflowRunner + + store, holds = FaultStore(), [Hold(), Hold()] + store.faults["read_records"].extend(holds) + client = stream_client(client, store) + for stream_id in ("first", "second"): + stream = await client.create_stream(id=stream_id, body_type=str) + await stream.append(stream_id) + live, replayed = CustomWorkflowRunner(), CustomWorkflowRunner() + + def read_results(runner: CustomWorkflowRunner) -> list[list[int]]: + """Return the seqs of the read results of each activation that has one.""" + activations = [ + [ + job.resolve_stream_read.seq + for job in activation.jobs + if job.HasField("resolve_stream_read") + ] + for activation, _ in runner._pairs + ] + return [seqs for seqs in activations if seqs] + + async def release(_handle: Any, _worker: Any) -> None: + # Both reads wait in the first task, and each page comes before its read limit. + for hold in holds: + await hold.started.wait() + for count, hold in enumerate(holds, 1): + hold.release() + + async def given() -> None: + assert len(read_results(live)) == count + + # This page gets its activation before the Store answers the other read. + await assert_eventually(given) + + options = RunOptions( + _TwoReadsWorkflow, + ["first", "second"], + worker={"workflow_runner": live}, + during=release, + ) + ran = await run(client, options) + assert ran.result == [["first"], ["second"]] + await Replayer( + workflows=[_TwoReadsWorkflow], + workflow_runner=replayed, + stream_config=client._config["stream_config"], + ).replay_workflow(ran.history) + assert len(read_results(live)) == 2 + assert read_results(replayed) == read_results(live) + + +@workflow.defn +class _ReadOnceWorkflow: + def __init__(self) -> None: + 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: list[int] = [] + async for record in stream.read(): + bodies.append(record.body) + # A Stream has no end, so the reader stops at the writer's last Record. + if record.body == 3: + break + await workflow.wait_condition(lambda: self._go_on) + return bodies + + +@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 _stream_markers(history, "read") + + 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"), + ) + bodies: list[int] = [] + async for record in records: + bodies.append(record.body) + # A Stream has no end, so the reader stops at the writer's last Record. + if record.body == 3: + break + return bodies + + +async def test_a_workflow_read_asks_the_store_with_its_limits(client: Client) -> None: + store = FaultStore() + client = stream_client(client, store) + stream = await client.create_stream(id="paged", body_type=int) + await stream.append(1, 2, 3) + + # A read with no limit asks for 256 Records and 4 MiB. SDK Core asks the Store for + # room for one Record more, since it acts on whether the Stream has more. That + # Record has at most the Record size of the config and an offset of 1024 bytes, + # each in its field. A Store call waits no longer than the read time of the + # Worker, which is shorter than the wait of the read. + def field(size: int) -> int: + return 1 + (size.bit_length() + 6) // 7 + size + + one_more = field(StreamConfig([store]).max_record_bytes + field(1024)) + cases: list[tuple[dict[str, int], tuple[int, int]]] = [ + ({"max_records": 1, "max_bytes": 100}, (2, 100 + one_more)), + ({}, (257, 4 * 1024 * 1024 + one_more)), + ] + read_time = timedelta(seconds=2) + for limits, expected in cases: + with failure_note(f"limits {limits}"): + store.calls.clear() + options = RunOptions( + _ReadAllWorkflow, + ["paged", limits], + worker={"stream_read_time": read_time}, + ) + ran = await run(client, options) + assert ran.result == [1, 2, 3] + reads = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] + asked = [(r.max_records, r.max_bytes) for r in reads] + # With one Record in a page, the read of each Record is one Store call. + assert asked == [expected] * (3 if limits else 1) + waits = [r.wait.ToTimedelta() for r in reads] + assert timedelta(0) < waits[0] and max(waits) <= read_time + # A replay asks for the Records that History recorded, and no more. + store.calls.clear() + await Replayer( + workflows=[_ReadAllWorkflow], + stream_config=client._config["stream_config"], + ).replay_workflow(ran.history) + replayed = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] + assert [r.max_records for r in replayed] == ([1] * 3 if limits else [3]) + + +@workflow.defn +class _QuietReadWorkflow: + @workflow.signal + def wake(self) -> None: + pass + + @workflow.run + async def run(self, stream_id: str) -> list[int]: + stream = workflow.get_stream(StreamRef[int](id=stream_id)) + bodies: list[int] = [] + offset = None + # The writer's last Record is 2, since a Stream has no end. + while 2 not in bodies: + page = await stream.read_page( + after_offset=offset, wait=timedelta(minutes=5) + ) + bodies.extend(record.body for record in page.records) + if page.records: + offset = page.records[-1].offset + return bodies + + +async def test_a_workflow_read_of_a_quiet_stream_makes_no_workflow_task( + client: Client, +) -> None: + store = FaultStore() + client = stream_client(client, store) + stream = await client.create_stream(id="quiet", body_type=int) + completed = EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED + + async def write(handle: Any, _worker: Any) -> None: + async def first_task() -> None: + assert _events(await handle.fetch_history(), completed) + + # On a quiet Stream, the reads get pages with no Record until the read limit, + # and the task then completes with no new task, over several read limits. + await assert_eventually(first_task) + await asyncio.sleep(1) + history = await handle.fetch_history() + assert len(_events(history, EventType.EVENT_TYPE_WORKFLOW_TASK_STARTED)) == 1 + quiet = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] + assert quiet and not any(r.after_offset for r in quiet) + # The read starts again from the same offset in the task of a Signal. + await stream.append(1, 2) + await handle.signal(_QuietReadWorkflow.wake) + + options = RunOptions( + _QuietReadWorkflow, + ["quiet"], + worker={"stream_read_time": timedelta(milliseconds=300)}, + during=write, + replay=True, + ) + assert (await run(client, options)).result == [1, 2] + + +@workflow.defn +class _FirstRecordWorkflow: + @workflow.signal + def wake(self) -> None: + pass + + @workflow.run + async def run(self, stream_id: str, seconds: float | None = 5) -> list[int]: + stream = workflow.get_stream(StreamRef[int](id=stream_id)) + wait = None if seconds is None else timedelta(seconds=seconds) + async for record in stream.read(wait=wait): + return [record.body] + raise AssertionError("A Workflow reader never ends by itself") + + +async def test_a_workflow_read_goes_on_after_the_read_limit_cut_its_wait( + client: Client, +) -> None: + store = FaultStore() + client = stream_client(client, store) + stream = await client.create_stream(id="cut", body_type=int) + + async def write(handle: Any, _worker: Any) -> None: + async def cut_page() -> None: + history = await handle.fetch_history() + markers = _stream_markers(history, "read") + assert any(b'"wait_cut":true' in m.SerializeToString() for m in markers) + assert _events(history, EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED) + + # The read limit cuts the wait of 5 s at 1 s. The iterator reads again, and + # that read waits for the next task, which a Signal opens. + await assert_eventually(cut_page) + await stream.append(1) + await handle.signal(_FirstRecordWorkflow.wake) + + options = RunOptions( + _FirstRecordWorkflow, + ["cut"], + worker={"stream_read_time": timedelta(seconds=1)}, + during=write, + replay=True, + ) + assert (await run(client, options)).result == [1] + + +async def test_a_workflow_iterator_with_no_wait_parks_on_an_idle_stream( + client: Client, +) -> None: + store = FaultStore() + client = stream_client(client, store) + stream = await client.create_stream(id="idle", body_type=int) + + async def write(handle: Any, _worker: Any) -> None: + async def first_task() -> None: + completed = EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED + assert _events(await handle.fetch_history(), completed) + + # The first read gives the empty answer of the Store at once. The later ones + # have the default wait. The read limit cuts a few of them, then one parks, + # so the idle Stream makes no new task over several read limits. + await assert_eventually(first_task) + await asyncio.sleep(4) + history = await handle.fetch_history() + tasks = _events(history, EventType.EVENT_TYPE_WORKFLOW_TASK_STARTED) + markers = _stream_markers(history, "read") + assert len(tasks) == 1, len(tasks) + assert 2 <= len(markers) <= 6, len(markers) + await stream.append(1) + await handle.signal(_FirstRecordWorkflow.wake) + + options = RunOptions( + _FirstRecordWorkflow, + ["idle", None], + task_timeout=timedelta(seconds=10), + worker={"stream_read_time": timedelta(seconds=1)}, + during=write, + replay=True, + ) + ran = await asyncio.wait_for(run(client, options), 30) + assert ran.result == [1] + + +async def test_a_workflow_read_with_no_wait_reads_again_in_the_next_task( + client: Client, +) -> None: + store, hold = FaultStore(), Hold() + stream = await stream_client(client, store).create_stream(id="slow", body_type=int) + await stream.append(1, 2, 3) + store.faults["read_records"].append(hold) + + async def release(handle: Any, _worker: Any) -> None: + async def task_completed() -> None: + history = await handle.fetch_history() + completed = EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED + assert _events(history, completed) + + # The read goes on at the read limit, since only the Store can say that the + # Stream has no Record. The task then completes, which stops the held read, + # and the read starts again in the task of the Signal. + await assert_eventually(task_completed) + await asyncio.wait_for(hold.cancelled.wait(), 10) + await handle.signal(_ReadOnceWorkflow.go_on) + + options = RunOptions( + _ReadOnceWorkflow, + ["slow"], + task_timeout=timedelta(seconds=2), + during=release, + replay=True, + ) + assert (await run(stream_client(client, store), options)).result == [1, 2, 3] + reads = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] + assert len([r for r in reads if not r.after_offset]) >= 2 + + +@dataclasses.dataclass +class _Turn: + text: str + + +@dataclasses.dataclass +class _AgentInput: + turns: StreamRef[_Turn] | None = None + + +@dataclasses.dataclass +class _TurnsInput: + turns: StreamRef[_Turn] + texts: list[str] + + +@activity.defn +async def _append_turns(input: _TurnsInput) -> None: + stream = activity.client().get_stream(input.turns) + await stream.append(*(_Turn(text) for text in input.texts)) + + +@workflow.defn +class _AgentWorkflow: + def __init__(self) -> None: + self._turns: StreamRef[_Turn] | None = None + self._go_on = False + + @workflow.query + def turns(self) -> StreamRef[_Turn] | None: + return self._turns + + @workflow.signal + def go_on(self) -> None: + self._go_on = True + + @workflow.run + async def run(self, input: _AgentInput) -> list[str]: + self._turns = input.turns + await workflow.wait_condition(lambda: self._go_on) + if self._turns is None: + created = await workflow.create_stream(id="turns", body_type=_Turn) + self._turns = created.ref + await workflow.execute_activity( + _append_turns, + _TurnsInput(self._turns, ["a", "b"]), + start_to_close_timeout=timedelta(seconds=10), + ) + page = await workflow.get_stream(self._turns).read_page() + # Only a body that the read converted to its type has the attribute. + return [record.body.text for record in page.records] + + +async def test_a_stream_ref_keeps_its_type_through_a_workflow(client: Client) -> None: + streams = stream_client(client, MemoryStreamStore()) + ref: Any = None + # The first run gets no ref and creates the Stream. The second one gets that ref. + for texts in (["a", "b"], ["a", "b", "a", "b"]): + with failure_note(f"texts {texts}"): + + async def answer(handle: Any, _worker: Any) -> None: + nonlocal ref + assert await handle.query(_AgentWorkflow.turns) == ref + await handle.signal(_AgentWorkflow.go_on) + await handle.result() + ref = await handle.query(_AgentWorkflow.turns) + + options = RunOptions( + _AgentWorkflow, + [_AgentInput(ref)], + activities=[_append_turns], + during=answer, + replay=True, + ) + assert (await run(streams, options)).result == texts + assert ref == StreamRef(id="turns", store="memory") + # The ref of the query has the body type, so the read needs no `body_type=`. + page = await streams.get_stream(ref).read_page() + assert [record.body for record in page.records] == [ + _Turn(text) for text in texts + ] diff --git a/tests/test_converter.py b/tests/test_converter.py index b47cadbdd0..5c48a36215 100644 --- a/tests/test_converter.py +++ b/tests/test_converter.py @@ -59,6 +59,7 @@ ) from temporalio.converter._payload_converter import ( _TemporalTransferTypePayloadConverter, + _typed_decode_types, ) from temporalio.exceptions import ( ApplicationError, @@ -388,6 +389,28 @@ def from_transfer_type( ) +class TemporalTransferTypeJSONValueConverter( + TransferTypeConverter["TemporalTransferTypeJSONValue", dict[str, str]] +): + transfer_type = dict[str, str] + + def to_transfer_type(self, value: TemporalTransferTypeJSONValue) -> dict[str, str]: + return {"id": value.value} + + def from_transfer_type( + self, + value: dict[str, str], + type_hint: type[TemporalTransferTypeJSONValue], + ) -> TemporalTransferTypeJSONValue: + return TemporalTransferTypeJSONValue(value=value["id"]) + + +@transfer_type_convertible(TemporalTransferTypeJSONValueConverter) +@dataclass +class TemporalTransferTypeJSONValue: + value: str + + class CustomDefaultPayloadConverter(DefaultPayloadConverter): pass @@ -455,6 +478,54 @@ def test_temporal_transfer_type_payload_converter_with_generic_value( assert converter.from_payload(payload, type_hint) == value +def _decode_typed(monkeypatch: pytest.MonkeyPatch, *types: type) -> None: + """Let ``types`` decode by their type arguments and under ``T | None`` in one test.""" + monkeypatch.setattr( + "temporalio.converter._payload_converter._typed_decode_types", + _typed_decode_types | set(types), + ) + + +@pytest.mark.parametrize( + ("value", "type_hint"), + [ + (TemporalTransferTypeValue("workflow-id"), TemporalTransferTypeValue | None), + (None, TemporalTransferTypeValue | None), + ( + TemporalTransferTypeValueWithoutHint("workflow-id"), + TemporalTransferTypeValueWithoutHint | None, + ), + ( + TemporalTransferTypeGenericValue(123), + TemporalTransferTypeGenericValue[int] | None, + ), + (None, TemporalTransferTypeGenericValue[int] | None), + (TemporalTransferTypeValue("workflow-id"), None | TemporalTransferTypeValue), + (TemporalTransferTypeJSONValue("id"), TemporalTransferTypeJSONValue | None), + (None, TemporalTransferTypeJSONValue | None), + ], +) +def test_temporal_transfer_type_payload_converter_with_optional_hint( + value: Any, type_hint: Any, monkeypatch: pytest.MonkeyPatch +): + _decode_typed( + monkeypatch, + TemporalTransferTypeValue, + TemporalTransferTypeValueWithoutHint, + TemporalTransferTypeGenericValue, + TemporalTransferTypeJSONValue, + ) + converter = DataConverter.default.payload_converter + + payloads = [converter.to_payload(value)] + if value is None: + # A converter of another SDK can write None as a JSON null. + payloads.append(Payload(metadata={"encoding": b"json/plain"}, data=b"null")) + + for payload in payloads: + assert converter.from_payload(payload, type_hint) == value + + def test_transfer_type_convertible_rejects_existing_converter(): with pytest.raises(TypeError, match="already has a transfer type converter"): transfer_type_convertible(TemporalTransferTypeValueConverter)( @@ -564,6 +635,14 @@ class InitFalseIntDataClass: bar: int = dataclasses.field(default=0, init=False) +@dataclass +class GenericDataClass(Generic[T]): + value: T + items: list[T] = dataclasses.field(default_factory=list) + nested: GenericDataClass[T] | None = None + maybe: T | None = None + + class MyTypedDict(TypedDict): foo: str bar: MyDataClass @@ -605,6 +684,61 @@ def test_json_nested_frozenset_round_trip(): assert converter.from_payload(payload, set[frozenset[int]]) == value +K = TypeVar("K") + + +@dataclass +class GenericPairDataClass(Generic[K, T]): + key: K + value: T + + +def test_json_generic_dataclass_round_trip(monkeypatch: pytest.MonkeyPatch): + converter = JSONPlainPayloadConverter() + # mypy takes a type argument from a variable only on a value of type Any + generic_type: Any = GenericDataClass + pair_type: Any = GenericPairDataClass + + # A generic dataclass that isn't registered keeps its decoding, which the replay of + # an existing History needs. + payload = converter.to_payload(GenericDataClass(1)) + assert payload + with pytest.raises(TypeError): + converter.from_payload(payload, generic_type[int]) + generic_or_dict: Any = generic_type[int] | dict + assert converter.from_payload(payload, generic_or_dict) == { + "value": 1, + "items": [], + "nested": None, + "maybe": None, + } + + _decode_typed(monkeypatch, GenericDataClass, GenericPairDataClass) + + for argument, value in [ + (int, GenericDataClass(1, items=[2], nested=GenericDataClass(3), maybe=4)), + (str, GenericDataClass("text")), + (list[int], GenericDataClass([1], items=[[2], []], maybe=[3])), + (MyDataClass, GenericDataClass(MyDataClass("foo", 1, SerializableEnum.FOO))), + (GenericDataClass[str], GenericDataClass(GenericDataClass("nested"))), + ]: + payload = converter.to_payload(value) + assert payload + decoded = converter.from_payload(payload, generic_type[argument]) + assert decoded == value + assert decoded.__orig_class__ == generic_type[argument] + + payload = converter.to_payload({"value": "not an integer"}) + assert payload + with pytest.raises(TypeError): + converter.from_payload(payload, generic_type[int]) + + pair = GenericPairDataClass(key=1, value="text") + payload = converter.to_payload(pair) + assert payload + assert converter.from_payload(payload, pair_type[int, str]) == pair + + def test_json_type_hints(): converter = JSONPlainPayloadConverter() diff --git a/tests/testing/test_activity.py b/tests/testing/test_activity.py index 71ba7f5907..d7941d05a0 100644 --- a/tests/testing/test_activity.py +++ b/tests/testing/test_activity.py @@ -2,6 +2,7 @@ import threading import time from contextvars import copy_context +from datetime import datetime, timezone from unittest.mock import Mock import pytest @@ -38,6 +39,10 @@ async def via_create_task(): return "done" env = ActivityEnvironment() + epoch = datetime(1970, 1, 1, tzinfo=timezone.utc) + assert env.info.scheduled_time == epoch + assert env.info.current_attempt_scheduled_time == epoch + assert env.info.started_time == epoch # Set heartbeat handler to add to list heartbeats = [] env.on_heartbeat = lambda *args: heartbeats.append(args[0]) diff --git a/tests/testing/test_stream_store.py b/tests/testing/test_stream_store.py new file mode 100644 index 0000000000..c32ece184c --- /dev/null +++ b/tests/testing/test_stream_store.py @@ -0,0 +1,420 @@ +"""Tests of the memory Stream Store.""" + +import asyncio +import random +from collections.abc import Awaitable +from dataclasses import dataclass, field +from datetime import timedelta +from typing import Any + +import pytest +from google.protobuf.duration_pb2 import Duration +from google.protobuf.message import Message +from google.protobuf.timestamp_pb2 import Timestamp + +from temporalio.api.common.v1 import Payload +from temporalio.api.enums.v1 import ( + StreamErrorReason, + StreamIdConflictPolicy, +) +from temporalio.api.stream.v1 import ( + ActivityAttempt, + AppendRecord, + LocalActivityAttempt, + Producer, + StreamRecord, + WorkflowTaskAttempt, +) +from temporalio.api.streamservice.v1 import ( + AppendRecordsRequest, + AppendRecordsResponse, + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, +) +from temporalio.client._stream_store import _StoreCaller +from temporalio.exceptions import StreamError +from temporalio.testing import MemoryStreamStore +from tests.helpers.streams import failure_note, run_with_virtual_clock + +_NOT_FOUND = StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND +_EXPIRED = StreamErrorReason.STREAM_ERROR_REASON_EXPIRED +_FENCED = StreamErrorReason.STREAM_ERROR_REASON_FENCED + +# Attempts of each attempt message, earliest first. Where a later attempt wins by one field, +# its fields after that one are lower, so a comparison in another order of the fields differs. +_TASKS = [ + WorkflowTaskAttempt(started_event_id=3, attempt=2), + WorkflowTaskAttempt( + started_event_id=3, attempt=2, started_time=Timestamp(seconds=9) + ), + WorkflowTaskAttempt( + started_event_id=3, attempt=3, started_time=Timestamp(seconds=1) + ), + WorkflowTaskAttempt(started_event_id=5, attempt=1), +] +_ATTEMPTS: dict[type[Message], list[Any]] = { + WorkflowTaskAttempt: _TASKS, + LocalActivityAttempt: [ + LocalActivityAttempt(task=_TASKS[0], attempt=2), + LocalActivityAttempt(task=_TASKS[0], attempt=3), + LocalActivityAttempt(task=_TASKS[1], attempt=1), + LocalActivityAttempt(task=_TASKS[3], attempt=1), + ], + ActivityAttempt: [ + ActivityAttempt( + attempt_scheduled_time=Timestamp(seconds=4, nanos=7), attempt=2 + ), + ActivityAttempt( + attempt_scheduled_time=Timestamp(seconds=4, nanos=7), attempt=3 + ), + ActivityAttempt( + attempt_scheduled_time=Timestamp(seconds=4, nanos=8), attempt=1 + ), + ActivityAttempt(attempt_scheduled_time=Timestamp(seconds=5), attempt=1), + ], +} + + +@dataclass(frozen=True) +class _Writer: + """A generated Producer, with what a Store tells Producers and attempts apart by.""" + + producer: Producer + ids: tuple[str | int, ...] + """The kind and each id of the Producer.""" + rank: int + """The place of the attempt among the attempts of the Producer.""" + + +def _writer(rng: random.Random, same: _Writer | None = None) -> _Writer: + """Return a new Producer, or the Producer of ``same``, with an attempt.""" + producer = Producer() + if same: + producer.CopyFrom(same.producer) + name = ( + str(same.ids[0]) + if same + else rng.choice(list(Producer.DESCRIPTOR.fields_by_name)) + ) + kind = getattr(producer, name) + kind.SetInParent() + ids: list[str | int] = [name] + for id_field in kind.DESCRIPTOR.fields: + # A number id, such as the scheduled event id of an Activity, can be zero. + values = {id_field.TYPE_STRING: "aab", id_field.TYPE_INT64: [0, 0, 5]} + if id_field.type in values: + if not same: + setattr(kind, id_field.name, rng.choice(values[id_field.type])) + ids.append(getattr(kind, id_field.name)) + rank = 0 + if attempt := kind.DESCRIPTOR.fields_by_name.get("attempt"): + attempts = _ATTEMPTS[type(getattr(kind, attempt.name))] + rank = rng.randrange(len(attempts)) + getattr(kind, attempt.name).CopyFrom(attempts[rank]) + return _Writer(producer, tuple(ids), rank) + + +@dataclass +class _ModelBatch: + writer: _Writer + request_id: str + response: AppendRecordsResponse + + +@dataclass +class _ModelStream: + request_id: str + records: list[StreamRecord] = field(default_factory=list) + batches: list[_ModelBatch] = field(default_factory=list) + + def fenced(self, writer: _Writer) -> bool: + return any( + batch.writer.ids == writer.ids and batch.writer.rank > writer.rank + for batch in self.batches + ) + + +@dataclass +class _Model: + """What a Store with the rules of ``StreamStore`` answers, from all that it wrote.""" + + resend_window: int + fence: bool + streams: dict[str, _ModelStream] = field(default_factory=dict) + + def create(self, request: CreateStreamRequest, request_id: str) -> Any: + stream = self.streams.get(request.stream_id) + if stream is None: + self.streams[request.stream_id] = _ModelStream(request_id) + return CreateStreamResponse(created=True) + if request_id and request_id == stream.request_id: + return CreateStreamResponse(created=True) + use_existing = StreamIdConflictPolicy.STREAM_ID_CONFLICT_POLICY_USE_EXISTING + if request.id_conflict_policy == use_existing: + return CreateStreamResponse() + return StreamErrorReason.STREAM_ERROR_REASON_ALREADY_EXISTS + + def append( + self, request: AppendRecordsRequest, writer: _Writer, request_id: str + ) -> Any: + stream = self.streams.get(request.stream_id) + if stream is None: + return _NOT_FOUND + own = [batch for batch in stream.batches if batch.writer.ids == writer.ids] + for batch in own[len(own) - min(len(own), self.resend_window) :]: + if request_id and (batch.writer.rank, batch.request_id) == ( + writer.rank, + request_id, + ): + return batch.response + if self.fence and stream.fenced(writer): + return _FENCED + response = AppendRecordsResponse() + for record in request.records: + offset = (len(stream.records) + 1).to_bytes(8, "big") + response.first_offset = response.first_offset or offset + response.last_offset = offset + stream.records.append( + StreamRecord(producer=request.producer, body=record.body, offset=offset) + ) + stream.batches.append(_ModelBatch(writer, request_id, response)) + return response + + def read(self, request: ReadRecordsRequest) -> Any: + stream = self.streams.get(request.stream_id) + if stream is None: + return _NOT_FOUND + start = int.from_bytes(request.after_offset, "big") + if start > len(stream.records): + return StreamErrorReason.STREAM_ERROR_REASON_OFFSET_TOO_HIGH + records = stream.records[start:][: request.max_records or None] + return ReadRecordsResponse(records=records) + + +_OPERATIONS = ["create", "append", "again", "read"] +_WEIGHTS = [3, 10, 6, 4] + + +async def _answer(call: Awaitable[Message]) -> Any: + """Return the response of a Store call, or the reason of its refusal.""" + try: + return await call + except StreamError as err: + return err.reason + + +async def test_workflow_attempt_fencing_is_scoped_to_each_task() -> None: + store = MemoryStreamStore(fence=True) + await store.create_stream(CreateStreamRequest(stream_id="s"), request_id="") + + async def append(task_id: int, started: int, attempt: int) -> AppendRecordsResponse: + request = AppendRecordsRequest( + stream_id="s", records=[AppendRecord(body=Payload())] + ) + producer = request.producer.workflow + producer.namespace, producer.workflow_id, producer.run_id = "ns", "wf", "run" + producer.workflow_task_id = task_id + producer.attempt.started_event_id = started + producer.attempt.attempt = attempt + return await store.append_records(request, request_id="") + + await append(0, 11, 2) + await append(11, 19, 1) + # A delayed write from the first task still competes only with its own attempts. + await append(0, 11, 2) + assert await _answer(append(0, 3, 1)) == _FENCED + + +async def test_the_memory_store_keeps_the_rules_of_the_redis_store() -> None: + for seed in range(150): + with failure_note(f"seed {seed}"): + await _store_script(random.Random(seed)) + + +async def _store_script(rng: random.Random) -> None: + model = _Model(resend_window=rng.randrange(1, 4), fence=rng.random() < 0.5) + store = MemoryStreamStore(resend_window=model.resend_window, fence=model.fence) + appends: list[tuple[AppendRecordsRequest, _Writer, str]] = [] + writers: list[_Writer] = [] + for step in range(50): + stream_id = rng.choice("xy") + # Most writes come from another attempt of a Producer that the script already has. + writer = _writer( + rng, rng.choice(writers) if rng.random() < 0.7 * bool(writers) else None + ) + writers.append(writer) + request: Message + match rng.choices(_OPERATIONS, _WEIGHTS)[0]: + case "create": + request = CreateStreamRequest( + stream_id=stream_id, + id_conflict_policy=rng.choice( + list(StreamIdConflictPolicy.values()) + ), + ) + request_id = rng.choice(["", "r1", "r2"]) + expected = model.create(request, request_id) + answer = await _answer( + store.create_stream(request, request_id=request_id) + ) + case "append" | "again" as op: + request = AppendRecordsRequest( + stream_id=stream_id, producer=writer.producer + ) + request_id = rng.choice(["", "r1", "r2", "r3"]) + if op == "again" and appends: + # A late or a repeated try has the Producer, the attempt and the + # request id of an earlier append, and it may have other Records. + earlier, writer, request_id = rng.choice(appends) + request.CopyFrom(earlier) + del request.records[:] + # The SDK refuses a batch with no Record before a Store gets it. + for _ in range(rng.randrange(1, 3)): + body = Payload(data=bytes([rng.randrange(256)])) + request.records.append(AppendRecord(body=body)) + appends.append((request, writer, request_id)) + expected = model.append(request, writer, request_id) + answer = await _answer( + store.append_records(request, request_id=request_id) + ) + case _: + request = ReadRecordsRequest( + stream_id=stream_id, + after_offset=rng.choice( + [b"", *(i.to_bytes(8, "big") for i in range(1, 9))] + ), + max_records=rng.randrange(4), + ) + expected = model.read(request) + answer = await _answer(store.read_records(request)) + assert answer == expected, f"step {step}: {request}" + + +def _streams(retention: int = 1) -> MemoryStreamStore: + return MemoryStreamStore(retention=timedelta(seconds=retention), resend_window=1) + + +_S = "s" + + +def _client_append() -> AppendRecordsRequest: + request = AppendRecordsRequest(stream_id=_S, records=[AppendRecord()]) + request.producer.client.SetInParent() + return request + + +def test_a_stream_expires_after_its_retention_from_its_create_or_last_write() -> None: + async def script(rng: random.Random) -> None: + loop = asyncio.get_running_loop() + retention = rng.randrange(1, 50) + streams = _streams(retention) + await streams.create_stream(CreateStreamRequest(stream_id=_S), request_id="c") + expires_at = loop.time() + retention + # The window of the client Producer has its last batch, so an append with the + # request id of that batch is a resend, which writes nothing. + last_batch: str | None = None + for step in range(12): + await asyncio.sleep(rng.randrange(40)) + expired = loop.time() >= expires_at + match rng.choice(["append", "append", "read", "describe", "create"]): + case "append": + request_id = rng.choice(["", "r"]) + append = streams.append_records( + _client_append(), request_id=request_id + ) + answer = await _answer(append) + expected: Any = AppendRecordsResponse + resend = bool(request_id) and request_id == last_batch + if not expired and not resend: + expires_at, last_batch = loop.time() + retention, request_id + case "read": + read = ReadRecordsRequest(stream_id=_S) + answer = await _answer(streams.read_records(read)) + expected = ReadRecordsResponse + case "describe": + describe = DescribeStreamRequest(stream_id=_S) + answer = await _answer(streams.describe_stream(describe)) + expected = DescribeStreamResponse + case _: + use_existing = ( + StreamIdConflictPolicy.STREAM_ID_CONFLICT_POLICY_USE_EXISTING + ) + create = CreateStreamRequest( + stream_id=_S, id_conflict_policy=use_existing + ) + answer = await _answer( + streams.create_stream(create, request_id=rng.choice("cd")) + ) + expected = CreateStreamResponse + if expired: + expected = _EXPIRED + assert answer == expected or type(answer) is expected, ( + f"step {step}: {answer} at {loop.time()}" + ) + + for seed in range(200): + with failure_note(f"seed {seed}"): + run_with_virtual_clock(script(random.Random(seed))) + + +@pytest.mark.parametrize( + "wait,write_in,answered_at,outcome", + [ + (5, 3, 3, "record"), + (5, 7, 5, "empty"), + (5, None, 5, "empty"), + (20, None, 10, "expired"), + (10, None, 10, "expired"), + ], +) +def test_a_read_waits_for_a_write_its_timeout_or_expiry( + wait: int, write_in: int | None, answered_at: int, outcome: str +) -> None: + async def script() -> None: + loop = asyncio.get_running_loop() + streams = _streams(retention=10) + await streams.create_stream(CreateStreamRequest(stream_id=_S), request_id="") + first = await streams.append_records(_client_append(), request_id="") + request = ReadRecordsRequest( + stream_id=_S, after_offset=first.last_offset, wait=Duration(seconds=wait) + ) + + async def read() -> tuple[float, Any]: + response = await _answer(streams.read_records(request)) + return loop.time(), response + + reader = asyncio.create_task(read()) + if write_in is not None: + await asyncio.sleep(write_in) + await streams.append_records(_client_append(), request_id="") + ended, page = await reader + assert ended == answered_at + if outcome == "expired": + assert page == _EXPIRED + elif outcome == "empty": + assert page == ReadRecordsResponse() + else: + [record] = page.records + assert record.offset > first.last_offset + + run_with_virtual_clock(script()) + + +async def test_a_dropped_store_call_never_reaches_the_store() -> None: + asked: list[str] = [] + + def store() -> MemoryStreamStore: + asked.append("store") + return MemoryStreamStore() + + def on_task(_task: asyncio.Task[Any]) -> None: + raise asyncio.CancelledError + + request = DescribeStreamRequest(stream_id=_S).SerializeToString() + with pytest.raises(asyncio.CancelledError): + await _StoreCaller(store).call("DescribeStream", request, None, on_task) + assert not asked diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py new file mode 100644 index 0000000000..fa5cdb61e7 --- /dev/null +++ b/tests/worker/test_workflow_streams.py @@ -0,0 +1,1138 @@ +"""Tests of the Stream calls of one Workflow instance, with no server.""" + +import asyncio +import dataclasses +from collections.abc import Sequence +from dataclasses import dataclass +from datetime import datetime, timedelta, timezone +from typing import Any + +import pytest +from google.protobuf.duration_pb2 import Duration +from google.protobuf.message import Message + +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 ActivityType, Payload +from temporalio.api.enums.v1 import RetryState, StreamErrorReason, TimeoutType +from temporalio.api.failure.v1 import ( + ActivityFailureInfo, + ApplicationFailureInfo, + Failure, + TimeoutFailureInfo, +) +from temporalio.api.sdk.v1 import ( + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + StreamRef, +) +from temporalio.api.sdk.v1.external_storage_pb2 import ExternalStorageReference +from temporalio.api.stream.v1 import StreamRecord +from temporalio.api.streamservice.v1 import DescribeStreamResponse +from temporalio.bridge.proto.activity_result import ( + ActivityResolution, +) +from temporalio.bridge.proto.activity_result import Success as ActivitySuccess +from temporalio.bridge.proto.workflow_activation import ( + InitializeWorkflow, + RemoveFromCache, + ResolveActivity, + ResolveStreamAppend, + ResolveStreamRead, + SignalWorkflow, + StreamAppended, + StreamPage, + WorkflowActivation, + WorkflowActivationJob, +) +from temporalio.bridge.proto.workflow_commands import ( + AppendToStream, + CompleteWorkflowExecution, + ReadStream, + RequestCancelLocalActivity, + WorkflowCommand, +) +from temporalio.bridge.proto.workflow_completion import ( + Success, + WorkflowActivationCompletion, +) +from temporalio.client import StreamConfig, StreamSelectContext, StreamStore +from temporalio.converter import ( + ExternalStorage, + WorkflowSerializationContext, +) +from temporalio.exceptions import ApplicationError, StreamError +from temporalio.nexus.system import _support +from temporalio.nexus.system.stream_service import StreamRef as ModelRef +from temporalio.nexus.system.stream_service.models import ( + CreateStreamResult, + StreamIdConflictPolicy, +) +from temporalio.testing import MemoryStreamStore +from temporalio.worker._workflow import _CommandAwareDataConverter +from temporalio.worker._workflow_instance import ( + _WorkflowInstanceImpl, + _WorkflowLogicFlag, # type: ignore[reportPrivateLocalImportUsage] +) +from tests.helpers.streams import ( + CodecCall, + ContextCodec, + core_failure, + failure_note, + wrapped, +) +from tests.test_extstore import InMemoryTestDriver + + +@workflow.defn +class _StreamWorkflow: + @workflow.run + async def run(self) -> None: + pass + + +def _new_instance( + workflow_class: type, + stream_config: StreamConfig | None = None, + interceptor_classes: Sequence[ + type[temporalio.worker.WorkflowInboundInterceptor] + ] = (), + failure_exception_types: Sequence[type[BaseException]] = (), +) -> _WorkflowInstanceImpl: + defn = workflow._Definition.must_from_class(workflow_class) + start_time = datetime(2026, 1, 1, tzinfo=timezone.utc) + instance = temporalio.worker.UnsandboxedWorkflowRunner().create_instance( + temporalio.worker.WorkflowInstanceDetails( + payload_converter_factory=temporalio.converter.DefaultPayloadConverter, + failure_converter_class=temporalio.converter.DefaultFailureConverter, + interceptor_classes=interceptor_classes, + defn=defn, + info=workflow.Info( + attempt=1, + continued_run_id=None, + cron_schedule=None, + execution_timeout=None, + first_execution_run_id="first-run", + headers={}, + namespace="ns", + original_execution_run_id="run", + parent=None, + root=None, + priority=temporalio.common.Priority(), + raw_memo={}, + retry_policy=None, + run_id="run", + run_timeout=None, + search_attributes={}, + start_time=start_time, + task_queue="tq", + task_timeout=timedelta(seconds=10), + typed_search_attributes=temporalio.common.TypedSearchAttributes.empty, + workflow_id="wf", + workflow_start_time=start_time, + workflow_type=defn.name or "", + ), + randomness_seed=1, + extern_functions={"__temporal_stream_config": lambda: stream_config}, + disable_eager_activity_execution=False, + worker_level_failure_exception_types=failure_exception_types, + patch_activation_callback=None, + last_completion_result=temporalio.api.common.v1.Payloads(), + last_failure=None, + ) + ) + assert isinstance(instance, _WorkflowInstanceImpl) + return instance + + +async def _activate( + instance: _WorkflowInstanceImpl, + *jobs: WorkflowActivationJob, + replaying: bool = False, + flags: Sequence[int] = (), +) -> WorkflowActivationCompletion: + # A Worker runs an activation in another thread too, so that the tasks of the + # Workflow don't run inside the task of the caller. + activation = WorkflowActivation( + run_id="run", jobs=jobs, is_replaying=replaying, available_internal_flags=flags + ) + return await asyncio.to_thread(instance.activate, activation) + + +async def test_stream_payloads_take_the_codec_with_no_context_and_no_storage() -> None: + calls: list[CodecCall] = [] + driver = InMemoryTestDriver() + converter = dataclasses.replace( + temporalio.converter.DataConverter.default, + payload_codec=ContextCodec(calls), + external_storage=ExternalStorage(drivers=[driver], payload_size_threshold=0), + ) + context = WorkflowSerializationContext(namespace="ns", workflow_id="wf") + command_aware = _CommandAwareDataConverter.create( + instance=_new_instance(_StreamWorkflow), + context_free_dc=converter, + workflow_context_dc=converter.with_context(context), + workflow_context=context, + ) + to_payload = temporalio.converter.PayloadConverter.default.to_payload + reference = to_payload(ExternalStorageReference(driver_name=driver.name())) + bodies = [to_payload("plain"), reference] + result = to_payload("result") + + completion = WorkflowActivationCompletion( + successful=Success( + commands=[ + WorkflowCommand( + append_to_stream=AppendToStream( + seq=1, stream=StreamRef(id="s", store="memory"), bodies=bodies + ) + ), + WorkflowCommand( + complete_workflow_execution=CompleteWorkflowExecution(result=result) + ), + ] + ) + ) + await temporalio.bridge.worker.encode_completion( + completion, command_aware, encode_headers=True, storage_concurrency_limit=1 + ) + append, complete = completion.successful.commands + assert list(append.append_to_stream.bodies) == [wrapped(body) for body in bodies] + stored = complete.complete_workflow_execution.result + assert stored.metadata["messageType"] == reference.metadata["messageType"] + assert driver._store_calls == 1 + assert calls == [("encode", None, 1)] * 2 + [("encode", context, 1)] + + # 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="A later attempt has written to the Stream", + application_failure_info=ApplicationFailureInfo( + type="stream_fenced", + 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_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, 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 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_EXPIRED, + StreamErrorReason.STREAM_ERROR_REASON_FENCED, +] +_UNAVAILABLE = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE +_STORE_CALL = "__temporal_stream_store_call" + + +@dataclass +class _Call: + operation: str + stream: str + store: str | None = None + bodies: Sequence[int] = () + cancel: bool = False + refusal: StreamErrorReason.ValueType | None = None + timeout: bool = False + unserved: bool = False + outcome: Any = None + + +class _Script: + phases: list[list[_Call]] = [] + late_cancels = False + intercepted: list[tuple[str, Any]] = [] + local_activities: list[str] = [] + + +@workflow.defn +class _ScriptWorkflow: + @workflow.run + async def run(self) -> None: + streams: dict[str, Any] = {} + for phase in _Script.phases: + tasks = [asyncio.ensure_future(self._call(streams, call)) for call in phase] + # Each task makes its call in its first step, and the task of the call runs + # one step later. + await asyncio.sleep(0) + if _Script.late_cancels: + await asyncio.sleep(0) + for call, task in zip(phase, tasks): + if call.cancel: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + + async def _call(self, streams: dict[str, Any], call: _Call) -> None: + try: + if call.operation == "create": + stream = await workflow.create_stream( + id=call.stream, store=call.store, body_type=int + ) + streams[call.stream] = stream + call.outcome = (stream.ref.store, stream.created) + return + stream = streams.get(call.stream) or workflow.get_stream( + ModelRef[int](id=call.stream, store=call.store) + ) + if call.operation == "append": + appended = await stream.append(*call.bodies) + call.outcome = (appended.first_offset, appended.last_offset) + else: + described = await stream.describe() + call.outcome = described.last_offset + except StreamError as err: + call.outcome = err.reason + except asyncio.CancelledError: + call.outcome = "cancelled" + raise + + +class _RecordingInbound(temporalio.worker.WorkflowInboundInterceptor): + def init(self, outbound: temporalio.worker.WorkflowOutboundInterceptor) -> None: + super().init(_RecordingOutbound(outbound)) + + +class _RecordingOutbound(temporalio.worker.WorkflowOutboundInterceptor): + def start_local_activity( + self, input: temporalio.worker.StartLocalActivityInput + ) -> workflow.ActivityHandle[Any]: + _Script.local_activities.append(input.activity) + return super().start_local_activity(input) + + async def start_create_stream(self, request: Any, output_type: Any = None) -> Any: + _Script.intercepted.append(("create", request)) + return await super().start_create_stream(request, output_type) + + async def start_append_records(self, request: Any) -> Any: + _Script.intercepted.append(("append", request)) + return await super().start_append_records(request) + + async def start_describe_stream(self, request: Any) -> Any: + _Script.intercepted.append(("describe", request)) + return await super().start_describe_stream(request) + + +def _resolve_call( + call: _Call, seq: int, *, created: bool = True +) -> WorkflowActivationJob: + converter = temporalio.converter.DefaultPayloadConverter() + job = WorkflowActivationJob() + if call.operation == "append": + job.resolve_stream_append.seq = seq + if call.refusal is not None: + job.resolve_stream_append.failed.CopyFrom(core_failure(call.refusal)) + else: + job.resolve_stream_append.appended.CopyFrom( + StreamAppended( + first_offset=b"first%d" % seq, last_offset=b"last%d" % seq + ) + ) + return job + + job.resolve_activity.seq = seq + job.resolve_activity.is_local = True + result = job.resolve_activity.result + if call.cancel: + result.cancelled.failure.canceled_failure_info.SetInParent() + elif call.refusal is not None: + result.failed.failure.CopyFrom(core_failure(call.refusal)) + elif call.unserved: + result.failed.failure.CopyFrom( + Failure( + message="No Stream Store", + application_failure_info=ApplicationFailureInfo(type="ValueError"), + ) + ) + elif call.timeout: + result.failed.failure.CopyFrom( + Failure( + message="Local Activity timed out", + cause=Failure( + timeout_failure_info=TimeoutFailureInfo( + timeout_type=TimeoutType.TIMEOUT_TYPE_SCHEDULE_TO_CLOSE + ) + ), + activity_failure_info=ActivityFailureInfo( + activity_type=ActivityType(name=_STORE_CALL), + retry_state=RetryState.RETRY_STATE_CANCEL_REQUESTED, + ), + ) + ) + else: + answer: Message = ( + CreateStreamResponse( + ref=StreamRef(id=call.stream, store="b"), created=created + ) + if call.operation == "create" + else DescribeStreamResponse(last_offset=b"last%d" % seq) + ) + result.completed.result.CopyFrom( + converter.to_payload(answer.SerializeToString()) + ) + return job + + +@workflow.defn +class _ReuseStreamWorkflow: + @workflow.run + async def run(self) -> bool | None: + stream = await workflow.create_stream( + id="s", + store="b", + id_conflict_policy=StreamIdConflictPolicy.StreamIdConflictPolicyUseExisting, + ) + return stream.created + + +@pytest.mark.parametrize("intercepted", [False, True]) +async def test_create_reports_an_existing_stream_as_not_created( + intercepted: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + async def existing(_self: Any, request: Any, _output_type: Any = None) -> Any: + answer = asyncio.get_running_loop().create_future() + answer.set_result(CreateStreamResult(ref=request.stream_ref, created=False)) + return answer + + if intercepted: + monkeypatch.setattr(_RecordingOutbound, "start_create_stream", existing) + for replaying in (False, True): + instance = _new_instance( + _ReuseStreamWorkflow, + StreamConfig([MemoryStreamStore(name="b")]), + [_RecordingInbound], + ) + completion = await _activate( + instance, + WorkflowActivationJob(initialize_workflow=InitializeWorkflow()), + replaying=replaying, + ) + if not intercepted: + [schedule] = completion.successful.commands + completion = await _activate( + instance, + _resolve_call( + _Call("create", "s"), + schedule.schedule_local_activity.seq, + created=False, + ), + replaying=replaying, + ) + [command] = completion.successful.commands + assert command.HasField("complete_workflow_execution") + payload = command.complete_workflow_execution.result + assert ( + temporalio.converter.PayloadConverter.default.from_payload(payload) is False + ) + + +@pytest.mark.parametrize("replaying", [False, True]) +@pytest.mark.parametrize("late_cancels", [False, True]) +async def test_stream_calls_keep_their_results_when_jobs_arrive_in_reverse_order( + replaying: bool, late_cancels: bool +) -> None: + a, b = MemoryStreamStore(name="a"), MemoryStreamStore(name="b") + selects: list[StreamSelectContext] = [] + + def selector(context: StreamSelectContext) -> StreamStore: + selects.append(context) + return a + + phases = [ + [ + _Call("create", "created"), + _Call("append", "appended", "a", [1, 2]), + _Call("describe", "described", "a"), + ], + [ + _Call("append", "created", bodies=[3]), + _Call("create", "cancelled", cancel=True), + _Call("append", "cancelled-append", "a", [4], cancel=True), + _Call("describe", "refused", "a", refusal=_REFUSALS[0]), + ], + ] + _Script.phases, _Script.intercepted, _Script.local_activities = phases, [], [] + _Script.late_cancels = late_cancels + instance = _new_instance( + _ScriptWorkflow, + StreamConfig([a, b], store_selector=selector), + [_RecordingInbound], + ) + converter = temporalio.converter.DefaultPayloadConverter() + jobs = [WorkflowActivationJob(initialize_workflow=InitializeWorkflow())] + seqs = {"append": 0, "activity": 0} + for phase in phases: + completion = await _activate(instance, *jobs, replaying=replaying) + commands = completion.successful.commands + jobs = [] + cancelled: list[int] = [] + for call, command in zip(phase, commands[: len(phase)], strict=True): + kind = "append" if call.operation == "append" else "activity" + seqs[kind] += 1 + seq = seqs[kind] + if kind == "append": + assert command.append_to_stream.seq == seq + assert command.append_to_stream.stream == StreamRef( + id=call.stream, store="b" if call.stream == "created" else "a" + ) + assert converter.from_payloads(command.append_to_stream.bodies) == list( + call.bodies + ) + else: + activity = command.schedule_local_activity + assert activity.seq == seq and activity.activity_type == _STORE_CALL + operation, store, raw, request_id = converter.from_payloads( + activity.arguments + ) + assert operation == ( + "CreateStream" if call.operation == "create" else "DescribeStream" + ) + assert store == "a" + assert request_id == ( + "first-run" if call.operation == "create" else None + ) + if call.operation == "create": + assert CreateStreamRequest.FromString(raw).stream_ref == StreamRef( + id=call.stream + ) + else: + assert DescribeStreamRequest.FromString(raw).ref == StreamRef( + id=call.stream, store="a" + ) + if call.cancel: + cancelled.append(seq) + jobs.append(_resolve_call(call, seq)) + assert list(commands[len(phase) :]) == [ + WorkflowCommand( + request_cancel_local_activity=RequestCancelLocalActivity(seq=seq) + ) + for seq in cancelled + ] + jobs.reverse() + completion = await _activate(instance, *jobs, replaying=replaying) + [command] = completion.successful.commands + assert command.HasField("complete_workflow_execution") + calls = [call for phase in phases for call in phase] + assert [call.outcome for call in calls] == [ + ("b", True), + (b"first1", b"last1"), + b"last2", + (b"first2", b"last2"), + "cancelled", + "cancelled", + _REFUSALS[0], + ] + assert not instance._streams._appends + assert selects == [ + StreamSelectContext(id=id, namespace="ns") for id in ("created", "cancelled") + ] + assert [operation for operation, _ in _Script.intercepted] == [ + call.operation for call in calls + ] + assert _Script.local_activities == [_STORE_CALL] * 4 + for operation, request in _Script.intercepted: + if operation == "create": + assert request.stream_ref.store is None + assert ( + await _activate( + instance, WorkflowActivationJob(remove_from_cache=RemoveFromCache()) + ) + ).HasField("successful") + + +@pytest.mark.parametrize("replaying", [False, True]) +@pytest.mark.parametrize( + ("operation", "failure"), + [ + (op, failure) + for op in ("create", "describe") + for failure in ("outage", "timeout", "unserved") + ] + + [(op, "selector") for op in ("create", "append", "describe")], +) +async def test_store_failures_fail_the_task_even_when_workflow_errors_are_enabled( + operation: str, failure: str, replaying: bool +) -> None: + store = MemoryStreamStore(name="a") + + def selector(_context: StreamSelectContext) -> StreamStore: + if failure == "selector": + raise ApplicationError("The selector has no Store for this Stream") + return store + + call = _Call( + operation, + "s", + bodies=[1], + refusal=_UNAVAILABLE if failure == "outage" else None, + timeout=failure == "timeout", + unserved=failure == "unserved", + ) + _Script.phases, _Script.late_cancels = [[call]], False + instance = _new_instance( + _ScriptWorkflow, + StreamConfig([store], store_selector=selector), + failure_exception_types=[Exception], + ) + completion = await _activate( + instance, + WorkflowActivationJob(initialize_workflow=InitializeWorkflow()), + replaying=replaying, + ) + if failure != "selector": + assert len(completion.successful.commands) == 1 + completion = await _activate( + instance, _resolve_call(call, 1), replaying=replaying + ) + assert completion.HasField("failed") + assert ( + await _activate( + instance, WorkflowActivationJob(remove_from_cache=RemoveFromCache()) + ) + ).HasField("successful") + + +class _EachCall: + """The calls of :py:class:`_EachCallWorkflow`, and what its selector saw.""" + + operations: list[str] = [] + instance: _WorkflowInstanceImpl | None = None + selects: list[tuple[str, int]] = [] + """The Stream id of each selector call, with the number of commands before it.""" + + +@workflow.defn +class _EachCallWorkflow: + @workflow.run + async def run(self) -> None: + calls: list[Any] = [] + for at, operation in enumerate(_EachCall.operations): + stream = workflow.get_stream(ModelRef[int](id=f"s{at}")) + if operation == "create": + calls.append(workflow.create_stream(id=f"s{at}", body_type=int)) + elif operation == "append": + calls.append(stream.append(at)) + elif operation == "read": + calls.append(stream.read_page()) + else: + calls.append(stream.describe()) + if len(calls) == 1: + # The run gets the error of its one call, so no task holds an error that + # no one reads. + await calls[0] + return + tasks = [asyncio.ensure_future(call) for call in calls] + # Each task makes its call in its first step. + await asyncio.sleep(0) + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + + +def _store_of(command: WorkflowCommand) -> str: + """Return the Store name that the command of a Stream call has.""" + variant = command.WhichOneof("variant") + if variant == "append_to_stream": + return command.append_to_stream.stream.store + if variant == "read_stream": + return command.read_stream.stream.store + # The Local Activity of a create or a describe has the Store name second. + [_, store, *_] = command.schedule_local_activity.arguments + return temporalio.converter.DefaultPayloadConverter().from_payload(store, str) + + +async def test_the_store_of_a_call_is_chosen_before_its_command() -> None: + operations = ["create", "append", "read", "describe"] + a, b = MemoryStreamStore(name="a"), MemoryStreamStore(name="b") + for on_b in ([False, True, False, True], [True, False, True, False]): + + def selector(context: StreamSelectContext) -> StreamStore: + assert _EachCall.instance + sent = _EachCall.instance._current_completion.successful.commands + _EachCall.selects.append((context.id, len(sent))) + return b if on_b[int(context.id[1:])] else a + + config = StreamConfig([a, b], store_selector=selector) + _EachCall.operations = operations + for replaying in (False, True): + with failure_note(f"on b {on_b}, replaying {replaying}"): + _EachCall.selects = [] + instance = _EachCall.instance = _new_instance(_EachCallWorkflow, config) + initialize = WorkflowActivationJob( + initialize_workflow=InitializeWorkflow() + ) + completion = await _activate(instance, initialize, replaying=replaying) + # The selector runs once for each call, before the command of the call. + assert _EachCall.selects == [ + (f"s{at}", at) for at in range(len(operations)) + ] + commands = completion.successful.commands + assert [command.WhichOneof("variant") for command in commands] == [ + "schedule_local_activity", + "append_to_stream", + "read_stream", + "schedule_local_activity", + # A cancel sends a command only for a Local Activity. + "request_cancel_local_activity", + "request_cancel_local_activity", + "complete_workflow_execution", + ] + assert [_store_of(command) for command in commands[:4]] == [ + "b" if mine else "a" for mine in on_b + ] + + +# SDK Core uses the only Store of a Worker for a ref with no Store name. The SDK +# picks that Store itself, so each command has its name. +async def test_a_ref_with_no_store_name_goes_to_the_only_store() -> None: + operations = ["create", "append", "read", "describe"] + config = StreamConfig([MemoryStreamStore(name="only")]) + _EachCall.operations = operations + for replaying in (False, True): + with failure_note(f"replaying {replaying}"): + instance = _new_instance(_EachCallWorkflow, config) + initialize = WorkflowActivationJob(initialize_workflow=InitializeWorkflow()) + completion = await _activate(instance, initialize, replaying=replaying) + commands = completion.successful.commands[: len(operations)] + assert [command.WhichOneof("variant") for command in commands] == [ + "schedule_local_activity", + "append_to_stream", + "read_stream", + "schedule_local_activity", + ] + stores = [_store_of(command) for command in commands] + assert stores == ["only"] * len(operations) + + +async def test_a_ref_with_no_store_name_needs_a_selector_for_two_stores() -> None: + a, b = MemoryStreamStore(name="a"), MemoryStreamStore(name="b") + with pytest.raises(ValueError, match="store_selector must be specified"): + StreamConfig([a, b]) + unregistered = MemoryStreamStore(name="c") + config = StreamConfig([a, b], store_selector=lambda _: unregistered) + for operation in ["create", "append", "read", "describe"]: + _EachCall.operations = [operation] + for replaying in (False, True): + with failure_note(f"{operation}, replaying {replaying}"): + instance = _new_instance(_EachCallWorkflow, config) + initialize = WorkflowActivationJob( + initialize_workflow=InitializeWorkflow() + ) + completion = await _activate(instance, initialize, replaying=replaying) + message = completion.failed.failure.message + assert "not registered in StreamConfig.stores" in message + + +async def test_a_stream_call_with_no_stream_config_fails_the_task() -> None: + for operation in ["create", "append", "read", "describe"]: + _EachCall.operations = [operation] + for replaying in (False, True): + instance = _new_instance(_EachCallWorkflow) + initialize = WorkflowActivationJob(initialize_workflow=InitializeWorkflow()) + completion = await _activate(instance, initialize, replaying=replaying) + assert "no stream_config" in completion.failed.failure.message, operation + + +@dataclass +class _ReadCall: + 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: + 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( + after_offset=offset, + wait=call.wait, + max_records=call.max_records, + max_bytes=call.max_bytes, + ) + bodies = [record.body for record in page.records] + if page.records: + offset = page.records[-1].offset + call.outcome.append((bodies, offset or b"")) + 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"" + + +_READ_FLAGS = [ + (), + (_WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH,), +] + + +async def _start_readers( + calls: list[_ReadCall], flags: Sequence[int], replaying: bool +) -> tuple[_WorkflowInstanceImpl, WorkflowActivationCompletion]: + _ReadScript.calls = calls + _ReadScript.steps = [([], list(range(len(calls))))] + instance = _new_instance( + _ReadsWorkflow, StreamConfig([MemoryStreamStore(name="a")]) + ) + completion = await _activate( + instance, + WorkflowActivationJob(initialize_workflow=InitializeWorkflow()), + WorkflowActivationJob(signal_workflow=SignalWorkflow(signal_name="step")), + flags=flags, + replaying=replaying, + ) + return instance, completion + + +def _read_result(seq: int, *records: tuple[int, Any]) -> WorkflowActivationJob: + converter = temporalio.converter.DefaultPayloadConverter() + return WorkflowActivationJob( + resolve_stream_read=ResolveStreamRead( + seq=seq, + page=StreamPage( + records=[ + StreamRecord(offset=_offset(at), body=converter.to_payload(body)) + for at, body in records + ], + ), + ) + ) + + +@pytest.mark.parametrize("flags", _READ_FLAGS) +@pytest.mark.parametrize("replaying", [False, True]) +async def test_read_pages_keep_their_sequence_and_cursor( + flags: Sequence[int], replaying: bool +) -> None: + calls = [ + _ReadCall("first", 1, timedelta(seconds=5), 2, 100, 2, int), + _ReadCall("second", 0, timedelta(0), None, None, 1, Any), + _ReadCall("untyped", 0, None, None, None, 1, None), + ] + instance, completion = await _start_readers(calls, flags, replaying) + expected = [ + ReadStream( + seq=1, + stream=StreamRef(id="first", store="a"), + after_offset=_offset(1), + wait=Duration(seconds=5), + max_records=2, + max_bytes=100, + ), + ReadStream(seq=2, stream=StreamRef(id="second", store="a"), wait=Duration()), + ] + assert list(completion.successful.commands) == [ + WorkflowCommand(read_stream=read) for read in expected + ] + assert calls[2].outcome == ["TypeError"] + + completion = await _activate( + instance, + _read_result(2, (3, "text")), + _read_result(1), + flags=flags, + replaying=replaying, + ) + assert [call.outcome for call in calls] == [ + [([], _offset(1))], + [(["text"], _offset(3))], + ["TypeError"], + ] + next_read = expected[0] + next_read.seq = 3 + assert list(completion.successful.commands) == [ + WorkflowCommand(read_stream=next_read) + ] + + reason = StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND + completion = await _activate( + instance, + WorkflowActivationJob( + resolve_stream_read=ResolveStreamRead(seq=3, failed=core_failure(reason)) + ), + flags=flags, + replaying=replaying, + ) + assert not completion.successful.commands + assert calls[0].outcome == [([], _offset(1)), reason] + assert not instance._streams._reads + assert not ( + await _activate( + instance, WorkflowActivationJob(remove_from_cache=RemoveFromCache()) + ) + ).successful.commands + + +@pytest.mark.parametrize("flags", _READ_FLAGS) +@pytest.mark.parametrize("replaying", [False, True]) +@pytest.mark.parametrize("when", ["before result", "with result", "after a page"]) +async def test_cancelled_reads_discard_later_results( + flags: Sequence[int], replaying: bool, when: str +) -> None: + call = _ReadCall("s", 0, None, None, None, 2, int) + instance, _ = await _start_readers([call], flags, replaying) + seq = 1 + expected: list[Any] = [] + if when == "after a page": + await _activate( + instance, _read_result(1, (1, 1)), flags=flags, replaying=replaying + ) + expected.append(([1], _offset(1))) + seq = 2 + _ReadScript.steps = [([0], [])] + cancel = WorkflowActivationJob(signal_workflow=SignalWorkflow(signal_name="step")) + if when != "with result": + completion = await _activate(instance, cancel, flags=flags, replaying=replaying) + assert not completion.successful.commands + completion = await _activate( + instance, + *([cancel] if when == "with result" else []), + _read_result(seq, (2, 2 if when == "with result" else "not an integer")), + flags=flags, + replaying=replaying, + ) + assert not completion.successful.commands + assert call.outcome == [*expected, "cancelled"] + assert not instance._streams._reads + assert not ( + await _activate( + instance, WorkflowActivationJob(remove_from_cache=RemoveFromCache()) + ) + ).successful.commands + + +@pytest.mark.parametrize("flags", _READ_FLAGS) +@pytest.mark.parametrize("replaying", [False, True]) +@pytest.mark.parametrize("cancelled", [False, True]) +async def test_invalid_read_bodies_follow_recorded_activation_order( + flags: Sequence[int], replaying: bool, cancelled: bool +) -> None: + call = _ReadCall("s", 0, None, None, None, 1, int) + instance, _ = await _start_readers([call], flags, replaying) + jobs = [] + if cancelled: + _ReadScript.steps = [([0], [])] + jobs.append( + WorkflowActivationJob(signal_workflow=SignalWorkflow(signal_name="step")) + ) + jobs.append(_read_result(1, (1, "not an integer"))) + completion = await _activate(instance, *jobs, flags=flags, replaying=replaying) + # Single-batch Histories convert the body before the Signal can cancel its reader. + failed = not cancelled or bool(flags) + assert completion.HasField("failed") == failed + assert call.outcome == ([] if failed else ["cancelled"]) + assert not instance._streams._reads + assert not ( + await _activate( + instance, WorkflowActivationJob(remove_from_cache=RemoveFromCache()) + ) + ).successful.commands + + +@workflow.defn +class _ReadToTwoWorkflow: + @workflow.run + async def run(self, how: str, seconds: float | None = 5) -> list[Any]: + stream = workflow.get_stream(ModelRef[int](id="s", store="a")) + wait = None if seconds is None else timedelta(seconds=seconds) + if how == "read_page": + page = await stream.read_page(wait=wait) + return list(page.records) + # A Stream has no end, so the reader stops at the writer's last Record, 2. + found: list[Any] = [] + if how == "read": + async for record in stream.read(wait=wait): + found.append(record.body) + if record.body == 2: + break + return found + async for page in stream.read_pages(wait=wait): + found.append([record.body for record in page.records]) + if 2 in found[-1]: + break + return found + + +async def test_a_read_goes_on_after_a_page_with_no_record() -> None: + converter = temporalio.converter.DefaultPayloadConverter() + + def read(seq: int, after: int, seconds: int | None = 5) -> WorkflowCommand: + command = ReadStream( + seq=seq, + stream=StreamRef(id="s", store="a"), + after_offset=_offset(after), + wait=None if seconds is None else Duration(seconds=seconds), + ) + return WorkflowCommand(read_stream=command) + + def page( + seq: int, records: Sequence[int], wait_cut: bool = False + ) -> WorkflowActivationJob: + stream_page = StreamPage( + records=[ + StreamRecord(offset=_offset(number), body=converter.to_payload(number)) + for number in records + ], + wait_cut=wait_cut, + ) + job = ResolveStreamRead(seq=seq, page=stream_page) + return WorkflowActivationJob(resolve_stream_read=job) + + def start(how: str, seconds: int | None = 5) -> WorkflowActivationJob: + arguments = [converter.to_payload(how), converter.to_payload(seconds)] + return WorkflowActivationJob( + initialize_workflow=InitializeWorkflow(arguments=arguments) + ) + + def result(completion: WorkflowActivationCompletion) -> Any: + [complete] = completion.successful.commands + return converter.from_payload(complete.complete_workflow_execution.result) + + config = StreamConfig([MemoryStreamStore(name="a")]) + # A single read gives a page with no Record as it is, also a cut one. + for wait_cut in (True, False): + with failure_note(f"wait_cut {wait_cut}"): + instance = _new_instance(_ReadToTwoWorkflow, config) + completion = await _activate(instance, start("read_page")) + assert list(completion.successful.commands) == [read(1, 0)] + completion = await _activate(instance, page(1, [], wait_cut=wait_cut)) + assert result(completion) == [] + + for how in ("read", "read_pages"): + with failure_note(how): + instance = _new_instance(_ReadToTwoWorkflow, config) + completion = await _activate(instance, start(how)) + assert list(completion.successful.commands) == [read(1, 0)] + completion = await _activate(instance, page(1, [1])) + assert list(completion.successful.commands) == [read(2, 1)] + # A page with no Record doesn't end the reader, whether the read limit of + # the task cut its wait or the whole wait passed. + completion = await _activate(instance, page(2, [], wait_cut=True)) + assert list(completion.successful.commands) == [read(3, 1)] + completion = await _activate(instance, page(3, [])) + assert list(completion.successful.commands) == [read(4, 1)] + completion = await _activate(instance, page(4, [2])) + expected = [1, 2] if how == "read" else [[1], [], [], [2]] + assert result(completion) == expected + + instance = _new_instance(_ReadToTwoWorkflow, config) + await _activate(instance, start("read_pages"), replaying=True) + completion = await _activate(instance, page(1, [1]), replaying=True) + assert list(completion.successful.commands) == [read(2, 1)] + completion = await _activate(instance, page(2, []), replaying=True) + assert list(completion.successful.commands) == [read(3, 1)] + + # The first read of an iterator has the caller's wait. A later read has it too, + # or the default of 1 minute when the caller gave none. A wait of zero stays. + default = int(_support.DEFAULT_READ_WAIT.total_seconds()) + cases: list[tuple[int | None, int | None]] = [(None, default), (0, 0), (5, 5)] + for how in ("read", "read_pages"): + for given, later in cases: + with failure_note(f"{how} with wait {given}"): + instance = _new_instance(_ReadToTwoWorkflow, config) + completion = await _activate(instance, start(how, given)) + assert list(completion.successful.commands) == [read(1, 0, given)] + completion = await _activate(instance, page(1, [1])) + assert list(completion.successful.commands) == [read(2, 1, later)] + completion = await _activate(instance, page(2, [])) + assert list(completion.successful.commands) == [read(3, 1, later)] + # A single read has no default wait. + instance = _new_instance(_ReadToTwoWorkflow, config) + completion = await _activate(instance, start("read_page", None)) + assert list(completion.successful.commands) == [read(1, 0, None)]