From ffc969e31e2d33ee33327991b986c25f0245c8f9 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Tue, 1 Dec 2026 10:13:05 -0700 Subject: [PATCH 1/3] Pin Core with the Stream runtime This Core has the Workflow commands and activation jobs of Stream appends and reads. A codec gets each Stream body alone and with no serialization context, and the passes of external storage skip Stream bodies, since any writer can make a body. --- scripts/gen_payload_visitor.py | 43 ++- temporalio/bridge/Cargo.lock | 13 + temporalio/bridge/Cargo.toml | 1 + temporalio/bridge/_visitor.py | 73 ++++++ .../activity_result/activity_result_pb2.py | 33 +-- .../activity_result/activity_result_pb2.pyi | 14 + .../proto/activity_task/activity_task_pb2.py | 24 +- .../proto/activity_task/activity_task_pb2.pyi | 22 ++ temporalio/bridge/proto/common/__init__.py | 2 + temporalio/bridge/proto/common/common_pb2.py | 20 +- temporalio/bridge/proto/common/common_pb2.pyi | 25 ++ .../bridge/proto/external_data/__init__.py | 17 +- .../proto/external_data/external_data_pb2.py | 26 +- .../proto/external_data/external_data_pb2.pyi | 247 ++++++++++++++++++ .../proto/workflow_activation/__init__.py | 4 + .../workflow_activation_pb2.py | 104 ++++---- .../workflow_activation_pb2.pyi | 98 ++++++- .../proto/workflow_commands/__init__.py | 2 + .../workflow_commands_pb2.py | 139 +++++----- .../workflow_commands_pb2.pyi | 72 +++++ temporalio/bridge/sdk-core | 2 +- temporalio/bridge/worker.py | 13 +- temporalio/worker/_command_aware_visitor.py | 41 ++- temporalio/worker/_workflow_instance.py | 7 + 24 files changed, 862 insertions(+), 180 deletions(-) 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..5e1b6f9574 100644 --- a/temporalio/bridge/Cargo.lock +++ b/temporalio/bridge/Cargo.lock @@ -2626,6 +2626,7 @@ dependencies = [ "temporalio-client", "temporalio-common", "temporalio-sdk-core", + "temporalio-streams", "tokio", "tokio-rustls", "tokio-stream", @@ -2798,6 +2799,7 @@ dependencies = [ "temporalio-client", "temporalio-common", "temporalio-macros", + "temporalio-streams", "thiserror", "tokio", "tokio-stream", @@ -2809,6 +2811,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" diff --git a/temporalio/bridge/Cargo.toml b/temporalio/bridge/Cargo.toml index 3d63f69cdf..10ffc2208c 100644 --- a/temporalio/bridge/Cargo.toml +++ b/temporalio/bridge/Cargo.toml @@ -73,6 +73,7 @@ temporalio-sdk-core = { version = "0.12.0", path = "./sdk-core/crates/sdk-core", "envconfig", "prometheus", ] } +temporalio-streams = { version = "0.1.0", path = "./sdk-core/crates/streams" } tokio = "1.26" # Matches the sdk-core client crate's rustls stack; used to build the custom # server certificate verifier for TLSConfig.verification_server_name. diff --git a/temporalio/bridge/_visitor.py b/temporalio/bridge/_visitor.py index ead09a986f..06f5b43463 100644 --- a/temporalio/bridge/_visitor.py +++ b/temporalio/bridge/_visitor.py @@ -308,6 +308,12 @@ async def _visit_coresdk_workflow_activation_ResolveNexusOperation( if o.HasField("result"): await self._visit_coresdk_nexus_NexusOperationResult(fs, o.result) + async def _visit_coresdk_workflow_activation_ResolveStreamAppend( + self, fs: VisitorFunctions, o: Any + ): + if o.HasField("failed"): + await self._visit_temporal_api_failure_v1_Failure(fs, o.failed) + async def _visit_coresdk_workflow_activation_WorkflowActivationJob( self, fs: VisitorFunctions, o: Any ): @@ -353,6 +359,10 @@ 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 + ) async def _visit_coresdk_workflow_activation_WorkflowActivation( self, fs: VisitorFunctions, o: Any @@ -492,6 +502,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 +566,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 +658,60 @@ 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_stream_v1_StreamRecord( + self, fs: VisitorFunctions, o: Any + ): + if o.HasField("body"): + await self._visit_temporal_api_common_v1_Payload(fs, o.body) + + async def _visit_temporal_api_streamservice_v1_ReadRecordsResponse( + self, fs: VisitorFunctions, o: Any + ): + 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..9140144f96 100644 --- a/temporalio/bridge/proto/external_data/__init__.py +++ b/temporalio/bridge/proto/external_data/__init__.py @@ -1,6 +1,21 @@ -from .external_data_pb2 import LocalActivityMarkerData, PatchedMarkerData +from .external_data_pb2 import ( + LocalActivityMarkerData, + PatchedMarkerData, + PendingLocalActivityOrigins, + StreamAppendMarkerData, + StreamAppendOffsets, + StreamAppendOrigin, + StreamAppendResult, + StreamFailure, +) __all__ = [ "LocalActivityMarkerData", "PatchedMarkerData", + "PendingLocalActivityOrigins", + "StreamAppendMarkerData", + "StreamAppendOffsets", + "StreamAppendOrigin", + "StreamAppendResult", + "StreamFailure", ] diff --git a/temporalio/bridge/proto/external_data/external_data_pb2.py b/temporalio/bridge/proto/external_data/external_data_pb2.py index 4bda6f5144..72227786bf 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(\tB2\xea\x02/Temporalio::Internal::Bridge::Api::ExternalDatab\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -27,8 +31,20 @@ 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 # @@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..e7ee58369a 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,203 @@ 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 diff --git a/temporalio/bridge/proto/workflow_activation/__init__.py b/temporalio/bridge/proto/workflow_activation/__init__.py index 5c178e2185..453c0eefe8 100644 --- a/temporalio/bridge/proto/workflow_activation/__init__.py +++ b/temporalio/bridge/proto/workflow_activation/__init__.py @@ -16,7 +16,9 @@ ResolveNexusOperationStart, ResolveRequestCancelExternalWorkflow, ResolveSignalExternalWorkflow, + ResolveStreamAppend, SignalWorkflow, + StreamAppended, UpdateRandomSeed, WorkflowActivation, WorkflowActivationJob, @@ -40,7 +42,9 @@ "ResolveNexusOperationStart", "ResolveRequestCancelExternalWorkflow", "ResolveSignalExternalWorkflow", + "ResolveStreamAppend", "SignalWorkflow", + "StreamAppended", "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..bfae7abbde 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py @@ -49,7 +49,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\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"\xb3\x0b\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\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\x42\x38\xea\x02\x35Temporalio::Internal::Bridge::Api::WorkflowActivationb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -70,53 +70,57 @@ _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 + _WORKFLOWACTIVATIONJOB._serialized_end = 2619 + _INITIALIZEWORKFLOW._serialized_start = 2622 + _INITIALIZEWORKFLOW._serialized_end = 4129 + _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_start = 4050 + _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_end = 4129 + _FIRETIMER._serialized_start = 4131 + _FIRETIMER._serialized_end = 4155 + _RESOLVEACTIVITY._serialized_start = 4157 + _RESOLVEACTIVITY._serialized_end = 4266 + _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_start = 4269 + _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_end = 4606 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_start = 4608 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_end = 4667 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_start = 4670 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_end = 4836 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_start = 4838 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_end = 4934 + _RESOLVECHILDWORKFLOWEXECUTION._serialized_start = 4936 + _RESOLVECHILDWORKFLOWEXECUTION._serialized_end = 5041 + _UPDATERANDOMSEED._serialized_start = 5043 + _UPDATERANDOMSEED._serialized_end = 5086 + _QUERYWORKFLOW._serialized_start = 5089 + _QUERYWORKFLOW._serialized_end = 5349 + _QUERYWORKFLOW_HEADERSENTRY._serialized_start = 4050 + _QUERYWORKFLOW_HEADERSENTRY._serialized_end = 4129 + _CANCELWORKFLOW._serialized_start = 5351 + _CANCELWORKFLOW._serialized_end = 5383 + _SIGNALWORKFLOW._serialized_start = 5386 + _SIGNALWORKFLOW._serialized_end = 5675 + _SIGNALWORKFLOW_HEADERSENTRY._serialized_start = 4050 + _SIGNALWORKFLOW_HEADERSENTRY._serialized_end = 4129 + _NOTIFYHASPATCH._serialized_start = 5677 + _NOTIFYHASPATCH._serialized_end = 5711 + _RESOLVESIGNALEXTERNALWORKFLOW._serialized_start = 5714 + _RESOLVESIGNALEXTERNALWORKFLOW._serialized_end = 5891 + _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_start = 5894 + _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_end = 6078 + _DOUPDATE._serialized_start = 6081 + _DOUPDATE._serialized_end = 6515 + _DOUPDATE_HEADERSENTRY._serialized_start = 4050 + _DOUPDATE_HEADERSENTRY._serialized_end = 4129 + _RESOLVENEXUSOPERATIONSTART._serialized_start = 6518 + _RESOLVENEXUSOPERATIONSTART._serialized_end = 6672 + _RESOLVENEXUSOPERATION._serialized_start = 6674 + _RESOLVENEXUSOPERATION._serialized_end = 6763 + _REMOVEFROMCACHE._serialized_start = 6766 + _REMOVEFROMCACHE._serialized_end = 7118 + _REMOVEFROMCACHE_EVICTIONREASON._serialized_start = 6880 + _REMOVEFROMCACHE_EVICTIONREASON._serialized_end = 7118 + _RESOLVESTREAMAPPEND._serialized_start = 7121 + _RESOLVESTREAMAPPEND._serialized_end = 7282 + _STREAMAPPENDED._serialized_start = 7284 + _STREAMAPPENDED._serialized_end = 7343 # @@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..2c43796eef 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi @@ -49,7 +49,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 +65,13 @@ 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` 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, in `seq` order, and then + the local activity resolutions. A task with a Stream marker retains its recorded groups. * Queries always go last (and, in fact, always come in their own activation) * Evictions also always come in their own activation @@ -250,6 +257,7 @@ 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 REMOVE_FROM_CACHE_FIELD_NUMBER: builtins.int @property def initialize_workflow(self) -> global___InitializeWorkflow: @@ -324,6 +332,10 @@ 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 remove_from_cache(self) -> global___RemoveFromCache: """Remove the workflow identified by the [WorkflowActivation] containing this job from the @@ -353,6 +365,7 @@ 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 = ..., remove_from_cache: global___RemoveFromCache | None = ..., ) -> None: ... def HasField( @@ -386,6 +399,8 @@ 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", "signal_workflow", b"signal_workflow", "update_random_seed", @@ -425,6 +440,8 @@ 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", "signal_workflow", b"signal_workflow", "update_random_seed", @@ -452,6 +469,7 @@ class WorkflowActivationJob(google.protobuf.message.Message): "do_update", "resolve_nexus_operation_start", "resolve_nexus_operation", + "resolve_stream_append", "remove_from_cache", ] | None @@ -1645,3 +1663,81 @@ 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 diff --git a/temporalio/bridge/proto/workflow_commands/__init__.py b/temporalio/bridge/proto/workflow_commands/__init__.py index f599917afa..0b2f25566b 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, @@ -28,6 +29,7 @@ __all__ = [ "ActivityCancellationType", + "AppendToStream", "CancelChildWorkflowExecution", "CancelSignalWorkflow", "CancelTimer", diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py index 3573f36b11..64a58bbb36 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"\xf0\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\x12\x45\n\x10\x61ppend_to_stream\x18\x17 \x01(\x0b\x32).coresdk.workflow_commands.AppendToStreamH\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*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,72 @@ _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 = 9086 + _ACTIVITYCANCELLATIONTYPE._serialized_end = 9174 + _WORKFLOWCOMMAND._serialized_start = 592 + _WORKFLOWCOMMAND._serialized_end = 2752 + _STARTTIMER._serialized_start = 2754 + _STARTTIMER._serialized_end = 2837 + _CANCELTIMER._serialized_start = 2839 + _CANCELTIMER._serialized_end = 2865 + _SCHEDULEACTIVITY._serialized_start = 2868 + _SCHEDULEACTIVITY._serialized_end = 3692 + _SCHEDULEACTIVITY_HEADERSENTRY._serialized_start = 3613 + _SCHEDULEACTIVITY_HEADERSENTRY._serialized_end = 3692 + _SCHEDULELOCALACTIVITY._serialized_start = 3695 + _SCHEDULELOCALACTIVITY._serialized_end = 4550 + _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_start = 3613 + _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_end = 3692 + _REQUESTCANCELACTIVITY._serialized_start = 4552 + _REQUESTCANCELACTIVITY._serialized_end = 4588 + _REQUESTCANCELLOCALACTIVITY._serialized_start = 4590 + _REQUESTCANCELLOCALACTIVITY._serialized_end = 4631 + _QUERYRESULT._serialized_start = 4634 + _QUERYRESULT._serialized_end = 4790 + _QUERYSUCCESS._serialized_start = 4792 + _QUERYSUCCESS._serialized_end = 4857 + _COMPLETEWORKFLOWEXECUTION._serialized_start = 4859 + _COMPLETEWORKFLOWEXECUTION._serialized_end = 4935 + _FAILWORKFLOWEXECUTION._serialized_start = 4937 + _FAILWORKFLOWEXECUTION._serialized_end = 5011 + _CONTINUEASNEWWORKFLOWEXECUTION._serialized_start = 5014 + _CONTINUEASNEWWORKFLOWEXECUTION._serialized_end = 5928 + _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5771 + _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5847 + _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3613 + _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3692 + _CANCELWORKFLOWEXECUTION._serialized_start = 5930 + _CANCELWORKFLOWEXECUTION._serialized_end = 6006 + _SETPATCHMARKER._serialized_start = 6008 + _SETPATCHMARKER._serialized_end = 6062 + _STARTCHILDWORKFLOWEXECUTION._serialized_start = 6065 + _STARTCHILDWORKFLOWEXECUTION._serialized_end = 7314 + _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3613 + _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3692 + _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5771 + _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5847 + _CANCELCHILDWORKFLOWEXECUTION._serialized_start = 7316 + _CANCELCHILDWORKFLOWEXECUTION._serialized_end = 7390 + _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_start = 7393 + _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_end = 7535 + _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_start = 7538 + _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_end = 7937 + _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3613 + _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3692 + _CANCELSIGNALWORKFLOW._serialized_start = 7939 + _CANCELSIGNALWORKFLOW._serialized_end = 7974 + _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_start = 7976 + _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_end = 8077 + _MODIFYWORKFLOWPROPERTIES._serialized_start = 8079 + _MODIFYWORKFLOWPROPERTIES._serialized_end = 8158 + _UPDATERESPONSE._serialized_start = 8161 + _UPDATERESPONSE._serialized_end = 8371 + _SCHEDULENEXUSOPERATION._serialized_start = 8374 + _SCHEDULENEXUSOPERATION._serialized_end = 8912 + _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_start = 8862 + _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_end = 8912 + _REQUESTCANCELNEXUSOPERATION._serialized_start = 8914 + _REQUESTCANCELNEXUSOPERATION._serialized_end = 8956 + _APPENDTOSTREAM._serialized_start = 8958 + _APPENDTOSTREAM._serialized_end = 9084 # @@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..6b77439602 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,7 @@ 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 @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 +183,8 @@ class WorkflowCommand(google.protobuf.message.Message): def request_cancel_nexus_operation( self, ) -> global___RequestCancelNexusOperation: ... + @property + def append_to_stream(self) -> global___AppendToStream: ... def __init__( self, *, @@ -219,10 +223,13 @@ 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 = ..., ) -> 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", @@ -276,6 +283,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", @@ -354,6 +363,7 @@ class WorkflowCommand(google.protobuf.message.Message): "update_response", "schedule_nexus_operation", "request_cancel_nexus_operation", + "append_to_stream", ] | None ): ... @@ -632,6 +642,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 +719,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 +748,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 +787,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 +1954,52 @@ 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 diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index c350082361..80655abac3 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit c350082361cfa8e18c9da3efe59cb1e31fa560cf +Subproject commit 80655abac30adc11635f0e7fea6e452b5004e438 diff --git a/temporalio/bridge/worker.py b/temporalio/bridge/worker.py index fa5f337ca7..fd4d2aae3c 100644 --- a/temporalio/bridge/worker.py +++ b/temporalio/bridge/worker.py @@ -29,7 +29,10 @@ from temporalio.bridge.temporal_sdk_bridge import ( PollShutdownError, # type: ignore # noqa: F401 ) -from temporalio.worker._command_aware_visitor import CommandAwarePayloadVisitor +from temporalio.worker._command_aware_visitor import ( + CommandAwarePayloadVisitor, + StoragePayloadVisitor, +) @dataclass @@ -315,14 +318,14 @@ async def decode_activation( Returns: Metrics from any external storage retrieval operations that occurred. """ - await CommandAwarePayloadVisitor( + await StoragePayloadVisitor( skip_search_attributes=True, skip_headers=not decode_headers, ).visit(_Visitor(data_converter._decode_reference_payload_sequence), activation) metrics = temporalio.converter._extstore.StorageOperationMetrics() with metrics.track(): - await CommandAwarePayloadVisitor( + await StoragePayloadVisitor( skip_search_attributes=True, skip_headers=not decode_headers, concurrency_limit=storage_concurrency_limit, @@ -364,7 +367,7 @@ async def encode_completion( if data_converter.external_storage: with metrics.track(): - await CommandAwarePayloadVisitor( + await StoragePayloadVisitor( skip_search_attributes=True, skip_headers=not encode_headers, concurrency_limit=storage_concurrency_limit, @@ -373,7 +376,7 @@ async def encode_completion( completion, ) - await CommandAwarePayloadVisitor( + await StoragePayloadVisitor( skip_search_attributes=True, skip_headers=not encode_headers, ).visit( diff --git a/temporalio/worker/_command_aware_visitor.py b/temporalio/worker/_command_aware_visitor.py index 888c06f298..a75c42d754 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,10 @@ ResolveNexusOperationStart, ResolveRequestCancelExternalWorkflow, ResolveSignalExternalWorkflow, + ResolveStreamAppend, ) from temporalio.bridge.proto.workflow_commands.workflow_commands_pb2 import ( + AppendToStream, CompleteWorkflowExecution, FailWorkflowExecution, ScheduleActivity, @@ -211,6 +214,40 @@ 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_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 +257,8 @@ def current_command( update_protocol_instance_id: str | None = None, ) -> Iterator[None]: """Context manager for setting command info.""" + # `COMMAND_TYPE_UNSPECIFIED` marks the body of a Stream Record, which gets no + # serialization context. No other command may use that type. token = current_command_info.set( CommandInfo( command_type=command_type, diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index bcca2648a8..c710748779 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -2547,6 +2547,13 @@ def get_serialization_context( # The update's result and failure go back to the Nexus caller return self._nexus_update_contexts[command_info.update_protocol_instance_id] + if ( + command_info.command_type + == temporalio.api.enums.v1.command_type_pb2.CommandType.COMMAND_TYPE_UNSPECIFIED + ): + # The body of a Stream Record, which any code may read, so it has no context + return None + if ( command_info.command_type == temporalio.api.enums.v1.command_type_pb2.CommandType.COMMAND_TYPE_SCHEDULE_ACTIVITY_TASK From 7e6fdedc1445149ed4f40946beb6b646413c9465 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Tue, 1 Dec 2026 10:13:05 -0700 Subject: [PATCH 2/3] Send the Stream calls of client and Activity code to Stores The client sends each system Nexus call of the generated Stream API to the Store that its ref or the selector picks, with the codec and a request id that interceptor retries keep. It checks each request with the rules of SDK Core and the limits of the Stream config, so that client and Workflow calls refuse the same requests. An Activity writes as the Producer of its schedule, from the info that Core gives. --- temporalio/client/_client.py | 147 ++++ temporalio/client/_impl.py | 7 + temporalio/client/_interceptor.py | 7 +- temporalio/client/_stream_store.py | 461 ++++++++++++- temporalio/testing/_workflow.py | 12 + temporalio/worker/_activity.py | 7 + temporalio/worker/_workflow_instance.py | 4 + tests/helpers/streams.py | 196 +++++- tests/nexus/test_streams.py | 860 +++++++++++++++++++++++- tests/nexus/test_streams_with_worker.py | 136 ++++ 10 files changed, 1830 insertions(+), 7 deletions(-) create mode 100644 tests/nexus/test_streams_with_worker.py 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..d647abc5e9 100644 --- a/temporalio/client/_impl.py +++ b/temporalio/client/_impl.py @@ -34,6 +34,7 @@ import temporalio.exceptions import temporalio.nexus import temporalio.nexus._operation_context +import temporalio.nexus.system from temporalio.activity import ActivityCancellationDetails from temporalio.converter import ( ActivitySerializationContext, @@ -126,6 +127,7 @@ ScheduleUpdate, ScheduleUpdateInput, ) +from ._stream_store import _STREAM_SERVICE, _call_stream_store from ._worker_versioning import WorkerBuildIdVersionSets, WorkerTaskReachability from ._workflow import ( WorkflowExecutionAsyncIterator, @@ -1581,6 +1583,11 @@ async def start_nexus_operation( self, input: StartNexusOperationInput ) -> NexusOperationHandle[Any]: """Start a nexus operation and return a handle to it.""" + if ( + temporalio.nexus.system.is_system_endpoint(input.endpoint) + and input.service == _STREAM_SERVICE.name + ): + return await _call_stream_store(self._client, input) nexus_context = temporalio.converter.NexusSerializationContext( endpoint=input.endpoint, service=input.service, diff --git a/temporalio/client/_interceptor.py b/temporalio/client/_interceptor.py index 0561c4ab6c..0f016c4b88 100644 --- a/temporalio/client/_interceptor.py +++ b/temporalio/client/_interceptor.py @@ -2,13 +2,14 @@ from __future__ import annotations +import uuid from collections.abc import ( Awaitable, Callable, Mapping, Sequence, ) -from dataclasses import dataclass +from dataclasses import dataclass, field from datetime import timedelta from typing import ( TYPE_CHECKING, @@ -619,6 +620,10 @@ class StartNexusOperationInput(Generic[_NexusInputT, _NexusOutputT]): rpc_metadata: Mapping[str, str | bytes] rpc_timeout: timedelta | None completion_callbacks: Sequence[temporalio.nexus.CompletionCallback[Any]] = () + # Interceptors can retry a Store write with a copy of this input after losing its answer. + _stream_request_id: uuid.UUID = field( + default_factory=uuid.uuid4, repr=False, compare=False, kw_only=True + ) @dataclass diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index ddba2554f8..c070d33dff 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -2,10 +2,30 @@ from __future__ import annotations +import asyncio 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, @@ -16,6 +36,17 @@ ReadRecordsRequest, ReadRecordsResponse, ) +from temporalio.converter import PayloadCodec +from temporalio.exceptions import StreamError +from temporalio.nexus.system.stream_service import StreamService + +_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): @@ -263,3 +294,431 @@ def __post_init__(self) -> None: ) 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 _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, +) -> temporalio.client.NexusOperationHandle[Any]: + 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: Any = input.result_type + handle: temporalio.client.NexusOperationHandle[Any] = ( + temporalio.client.NexusOperationHandle( + client, + input.id, + result_type=result_type, + endpoint=input.endpoint, + service=input.service, + operation=input.operation, + ) + ) + handle._known_outcome = temporalio.nexus.system._support.model_from_proto( + response, result_type, *converters + ) + return handle 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/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index c710748779..06621aa219 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -3644,6 +3644,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 diff --git a/tests/helpers/streams.py b/tests/helpers/streams.py index 10e43a2b66..f8c78cdb18 100644 --- a/tests/helpers/streams.py +++ b/tests/helpers/streams.py @@ -1,13 +1,93 @@ """Helpers for the tests of Streams.""" import asyncio +import collections import selectors -from collections.abc import Coroutine, Iterator +from collections.abc import Awaitable, Callable, Coroutine, Iterator, Sequence from contextlib import contextmanager from typing import Any, TypeVar +from google.protobuf.message import Message + +from temporalio.api.common.v1 import Payload +from temporalio.api.streamservice.v1 import ( + AppendRecordsRequest, + AppendRecordsResponse, + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, +) +from temporalio.client import ( + Client, + StreamConfig, + StreamSelectContext, + StreamStore, +) +from temporalio.converter import ( + DataConverter, + PayloadCodec, + SerializationContext, + WithSerializationContext, +) +from temporalio.testing import MemoryStreamStore + _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]: @@ -19,6 +99,120 @@ def failure_note(note: str) -> Iterator[None]: raise +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 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) + + class _JumpingSelector(selectors.DefaultSelector): """Selector that moves the clock of its loop past a wait and doesn't wait.""" diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index 5ce7229e59..95a0c4ef61 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -1,22 +1,113 @@ """Tests of the client path of Streams, with no server.""" +import asyncio import dataclasses -from datetime import datetime, timezone +import random +from collections.abc import Callable +from datetime import datetime, timedelta, timezone from types import SimpleNamespace -from typing import Any, cast -from unittest.mock import patch +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 from temporalio.activity import WorkflowTaskAttempt +from temporalio.api.common.v1 import Payload +from temporalio.api.enums.v1 import StreamErrorReason, StreamIdConflictPolicy from temporalio.api.stream.v1 import ( + AppendRecord, + ClientProducer, Producer, ) +from temporalio.client import ( + Client, + NexusOperationHandle, + StreamConfig, + StreamSelectContext, +) +from temporalio.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 StreamError from temporalio.nexus.system import _support -from temporalio.testing import ActivityEnvironment +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.client import Stream as ClientStream +from temporalio.service import ServiceClient +from temporalio.testing import ActivityEnvironment, MemoryStreamStore +from tests.helpers.streams import ( + ContextCodec, + FaultStore, + Hold, + answers, + 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 start_nexus_operation( + self, input: temporalio.client.StartNexusOperationInput + ) -> NexusOperationHandle[Any]: + ref = getattr(input.arg, "stream_ref", None) or input.arg.ref + before = ref.store + try: + return await self.next.start_nexus_operation(input) + finally: + self._stores.append((before, ref.store)) def _producer_proto(producer: Any) -> Producer: @@ -28,6 +119,649 @@ def _producer_proto(producer: Any) -> 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 + + +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 start_nexus_operation( + self, input: temporalio.client.StartNexusOperationInput + ) -> NexusOperationHandle[Any]: + try: + return await self.next.start_nexus_operation(dataclasses.replace(input)) + except StreamError as err: + if err.reason != _UNAVAILABLE: + raise + return await self.next.start_nexus_operation(dataclasses.replace(input)) + + store = FaultStore() + store.faults["create_stream"].append(loses_answer()) + store.faults["append_records"].append(loses_answer()) + client = Client( + Mock(spec=ServiceClient), + stream_config=StreamConfig([store]), + interceptors=[_Interceptor(Retry)], + ) + stream = await client.create_stream(id="s", body_type=int) + assert stream.created is True + await stream.append(1) + await stream.append(2) + create, create_retry, append, append_retry, second = (key for _, key in store.calls) + assert create == create_retry + assert append == append_retry + assert len({create, append, second}) == 3 + assert [record.body for record in (await stream.read_page()).records] == [1, 2] + + +async def test_an_empty_client_append_does_not_reach_the_store() -> None: + store = FaultStore() + client = Client(Mock(spec=ServiceClient), stream_config=StreamConfig([store])) + 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, + ) + + +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_nexus_operation( + self, input: temporalio.client.StartNexusOperationInput + ) -> NexusOperationHandle[Any]: + request: ReadRecordsRequest[int] = 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[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 @@ -152,3 +886,121 @@ def test_a_workflow_producer_preserves_the_task_id_and_attempt() -> None: 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 + + +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..aef7d46611 --- /dev/null +++ b/tests/nexus/test_streams_with_worker.py @@ -0,0 +1,136 @@ +"""Tests of Streams with a Worker on the test server.""" + +import asyncio +from datetime import timedelta +from typing import Any + +import pytest + +from temporalio import activity, workflow +from temporalio.api.enums.v1 import EventType +from temporalio.client import Client +from temporalio.common import RetryPolicy +from temporalio.contrib.streams import current_producer +from temporalio.exceptions import ApplicationError +from temporalio.nexus.system.stream_service import ( + ProducerKindLocalActivity, + StreamRef, +) +from temporalio.worker import ( + Replayer, +) +from tests.helpers import new_worker +from tests.helpers.streams import ( + FaultStore, + Hold, + stream_client, +) + + +@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), + ] + + +def _events(history: Any, event_type: EventType.ValueType) -> list[Any]: + return [event for event in history.events if event.event_type == event_type] From c10fc045bea8893e71b9f774149e1323ff7d16f8 Mon Sep 17 00:00:00 2001 From: Tim Conley Date: Mon, 30 Nov 2026 16:11:27 -0800 Subject: [PATCH 3/3] Intercept Stream client calls by operation Each Stream operation of a client gets a typed hook on `OutboundInterceptor`, so interceptors see Stream calls without the generic Nexus chain. A hook that retries with the same input, or a copy, keeps its request id, and a call with no result type gets the type of its operation. --- temporalio/client/_impl.py | 22 ++- temporalio/client/_interceptor.py | 17 +- temporalio/client/_nexus.py | 50 +++--- temporalio/client/_stream_store.py | 12 +- tests/nexus/test_streams.py | 272 +++++++++++++++++++++++++++-- 5 files changed, 326 insertions(+), 47 deletions(-) diff --git a/temporalio/client/_impl.py b/temporalio/client/_impl.py index d647abc5e9..8d681198d5 100644 --- a/temporalio/client/_impl.py +++ b/temporalio/client/_impl.py @@ -34,7 +34,6 @@ import temporalio.exceptions import temporalio.nexus import temporalio.nexus._operation_context -import temporalio.nexus.system from temporalio.activity import ActivityCancellationDetails from temporalio.converter import ( ActivitySerializationContext, @@ -43,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 ( @@ -144,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 @@ -1579,15 +1584,18 @@ 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]: """Start a nexus operation and return a handle to it.""" - if ( - temporalio.nexus.system.is_system_endpoint(input.endpoint) - and input.service == _STREAM_SERVICE.name - ): - return await _call_stream_store(self._client, input) nexus_context = temporalio.converter.NexusSerializationContext( endpoint=input.endpoint, service=input.service, diff --git a/temporalio/client/_interceptor.py b/temporalio/client/_interceptor.py index 0f016c4b88..26bb8a1659 100644 --- a/temporalio/client/_interceptor.py +++ b/temporalio/client/_interceptor.py @@ -24,6 +24,9 @@ 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 ( @@ -737,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: @@ -752,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 index c070d33dff..12a40d1464 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -39,6 +39,7 @@ from temporalio.converter import PayloadCodec from temporalio.exceptions import StreamError from temporalio.nexus.system.stream_service import StreamService +from temporalio.types import ReturnType _definition = nexusrpc.get_service_definition(StreamService) assert _definition @@ -681,8 +682,8 @@ async def _call_store( # pyright: ignore[reportUnusedFunction] async def _call_stream_store( # pyright: ignore[reportUnusedFunction] client: temporalio.client.Client, - input: temporalio.client.StartNexusOperationInput, -) -> temporalio.client.NexusOperationHandle[Any]: + input: temporalio.client.StartNexusOperationInput[Any, ReturnType], +) -> temporalio.client.NexusOperationHandle[ReturnType]: stream_config = client._config["stream_config"] if stream_config is None: raise ValueError( @@ -707,8 +708,11 @@ async def _call_stream_store( # pyright: ignore[reportUnusedFunction] request_id, input.rpc_timeout, ) - result_type: Any = input.result_type - handle: temporalio.client.NexusOperationHandle[Any] = ( + 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, diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index 95a0c4ef61..210228ac53 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -3,7 +3,7 @@ import asyncio import dataclasses import random -from collections.abc import Callable +from collections.abc import Awaitable, Callable from datetime import datetime, timedelta, timezone from types import SimpleNamespace from typing import Any, assert_type, cast, get_args @@ -18,6 +18,7 @@ import temporalio.api.streamservice.v1 as proto import temporalio.client import temporalio.converter +import temporalio.nexus.system from temporalio.activity import WorkflowTaskAttempt from temporalio.api.common.v1 import Payload from temporalio.api.enums.v1 import StreamErrorReason, StreamIdConflictPolicy @@ -50,9 +51,11 @@ 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 tests.helpers.streams import ( ContextCodec, FaultStore, @@ -99,16 +102,67 @@ def __init__( super().__init__(next) self._stores = stores - async def start_nexus_operation( - self, input: temporalio.client.StartNexusOperationInput - ) -> NexusOperationHandle[Any]: + 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 self.next.start_nexus_operation(input) + 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 @@ -236,6 +290,169 @@ async def test_a_client_without_stream_config_does_not_call_the_server() -> None 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()]) @@ -283,15 +500,35 @@ async def test_a_created_stream_keeps_its_selected_store() -> None: async def test_a_client_retry_recovers_a_lost_store_answer() -> None: class Retry(temporalio.client.OutboundInterceptor): - async def start_nexus_operation( - self, input: temporalio.client.StartNexusOperationInput - ) -> NexusOperationHandle[Any]: + async def _retry(self, call: Callable[[], Awaitable[ReturnType]]) -> ReturnType: try: - return await self.next.start_nexus_operation(dataclasses.replace(input)) + return await call() except StreamError as err: if err.reason != _UNAVAILABLE: raise - return await self.next.start_nexus_operation(dataclasses.replace(input)) + 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()) @@ -720,10 +957,13 @@ def __init__(self, next: temporalio.client.OutboundInterceptor) -> None: self.starts: list[int] = [] self.waits: list[timedelta | None] = [] - async def start_nexus_operation( - self, input: temporalio.client.StartNexusOperationInput - ) -> NexusOperationHandle[Any]: - request: ReadRecordsRequest[int] = input.arg + 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 = [ @@ -731,7 +971,9 @@ async def start_nexus_operation( for at in next(self.pages) ] page = ReadRecordsResponse(records=records) - handle: NexusOperationHandle[Any] = NexusOperationHandle(Mock(), input.id) + handle: NexusOperationHandle[ReadRecordsResponse[Any]] = NexusOperationHandle( + Mock(), input.id + ) handle._known_outcome = page return handle