From 3fa94bb344b3aef206d077f3f8d29785ca91043f Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Tue, 1 Dec 2026 10:13:05 -0700 Subject: [PATCH 01/15] 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 a5548a91bc..23e9ffff37 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 c9a730c160..80655abac3 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit c9a730c160cfd92686fdd6e9f54127c5e4577253 +Subproject commit 80655abac30adc11635f0e7fea6e452b5004e438 diff --git a/temporalio/bridge/worker.py b/temporalio/bridge/worker.py index 187b867143..3b441887ac 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,13 +318,13 @@ async def decode_activation( Returns: Metrics from any external storage retrieval operations that occurred. """ - await CommandAwarePayloadVisitor( + await StoragePayloadVisitor( skip_search_attributes=True, ).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, concurrency_limit=storage_concurrency_limit, ).visit( @@ -362,7 +365,7 @@ async def encode_completion( if data_converter.external_storage: with metrics.track(): - await CommandAwarePayloadVisitor( + await StoragePayloadVisitor( skip_search_attributes=True, concurrency_limit=storage_concurrency_limit, ).visit( @@ -370,7 +373,7 @@ async def encode_completion( completion, ) - await CommandAwarePayloadVisitor( + await StoragePayloadVisitor( skip_search_attributes=True, ).visit( _Visitor(data_converter._encode_reference_payload_sequence), 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 42135e1f68f3289ef283c50986e5b7db685d5e58 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Tue, 1 Dec 2026 10:13:05 -0700 Subject: [PATCH 02/15] 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 | 716 +++++++++++++++++++ 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 | 872 +++++++++++++++++++++++- tests/nexus/test_streams_with_worker.py | 136 ++++ 10 files changed, 2093 insertions(+), 11 deletions(-) create mode 100644 temporalio/client/_stream_store.py create mode 100644 tests/nexus/test_streams_with_worker.py diff --git a/temporalio/client/_client.py b/temporalio/client/_client.py index 35b05e774c..8b338daeef 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()) @@ -2882,6 +2919,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, @@ -3039,6 +3184,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): @@ -3053,3 +3199,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 767dac3561..e32871c22f 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, @@ -1588,6 +1590,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 840218e4e6..0b71691016 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, @@ -621,6 +622,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 new file mode 100644 index 0000000000..443d916cc6 --- /dev/null +++ b/temporalio/client/_stream_store.py @@ -0,0 +1,716 @@ +"""Stream Stores and the Stream config of a client.""" + +from __future__ import annotations + +import asyncio +from abc import ABC, abstractmethod +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from datetime import timedelta +from typing import Any + +import google.protobuf.message +import nexusrpc + +import temporalio.api.sdk.v1 as sdk + +# pydoctor reads this module before the client package, for the worker modules that +# import it. A `from` import of a sibling here would lose the package's re-exports. +import temporalio.client +import temporalio.nexus.system._support +from temporalio.api.enums.v1 import StreamErrorReason, StreamIdConflictPolicy +from temporalio.api.stream.v1 import ( + LocalActivityProducer, + StandaloneActivityProducer, + WorkflowActivityProducer, + WorkflowProducer, + WorkflowTaskAttempt, +) +from temporalio.api.streamservice.v1 import ( + AppendRecordsRequest, + AppendRecordsResponse, + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, +) +from temporalio.converter import PayloadCodec +from temporalio.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): + """Base class for a Store that keeps Stream Records. + + Methods use request and response messages from + :py:mod:`temporalio.api.streamservice.v1`. Requests contain a Stream id. + The SDK routes each ``StreamRef`` to its registered Store and sets the Store + name on refs returned by create. Stores don't read or set ``StreamRef.store``. + + Workflow execution and replay depend on these contracts. + + Retention: + + * Retention starts at create and restarts after an append that writes a batch. + Retries and reads don't extend it. The Store sets the retention period. + * An expired Stream has no Records and rejects calls with ``EXPIRED``. + * Streams have no stored end. Applications use their own terminal Record. + + Records and offsets: + + * Keep each body as received. The payload codec has already encoded it. + * Write each append batch atomically, with contiguous Records in request order. + * Record offsets are nonempty and sort bytewise in Record order. + * After a response returns an offset, no later write can insert a Record at + or below it. This also applies to concurrent writes. + * Keep Records unchanged until the Stream expires. + + Producers and attempts: + + * A Producer identifies a Workflow run, Activity, Local Activity or client. + Its kind and ids determine its identity. + * An attempt identifies a Producer's execution attempt, such as a Workflow + Task or Activity attempt. Every Record retains its Producer and attempt. + * Fencing is optional. A Store that fences rejects an earlier attempt once + a later attempt of that Producer has written to the Stream. + + Reject calls with :py:class:`temporalio.exceptions.StreamError` and its reason. + These docs omit the ``STREAM_ERROR_REASON_`` prefix from reason names. + Other exceptions become ``STORE_UNAVAILABLE`` errors. Workflow append and + read refusals record messages of at most 4 KiB in History. All Stream marker + data in an activation must fit within 1 MiB. Keep messages short to avoid + failing the Workflow Task with ``StreamMarkerTooLarge``. + + Calls can run concurrently on the event loop. Cancellation can follow a + timeout, eviction or Worker shutdown. A cancelled call may have taken effect. + The Store must remain usable, and overlapping retries must not duplicate a + batch. + + SDK Core validates and retries Workflow appends and reads during outages. + Other calls make one attempt. For those calls, the SDK checks each request + with the rules of SDK Core and the append limits from :py:class:`StreamConfig`, + but it doesn't check the answer. Stores must perform any other checks they + require. + + .. warning:: + This API is experimental and subject to change. + """ + + @abstractmethod + def name(self) -> str: + """Return the Store name registered in :py:class:`StreamConfig`. + + The name must remain stable. Separate instances of one Store class can + use different names. + """ + raise NotImplementedError + + @abstractmethod + async def create_stream( + self, request: CreateStreamRequest, *, request_id: str + ) -> CreateStreamResponse: + """Create a Stream, or reuse it if the conflict policy permits. + + Retries use the same ``request_id``. An empty id never identifies a retry. + The response contains only ``created``. + + For an existing Stream, check these conditions in order. + + 1. An expired Stream fails with ``EXPIRED``. + 2. A matching create ``request_id`` returns ``created=True``. + 3. ``USE_EXISTING`` returns ``created=False``. ``FAIL`` or an unset policy + fails with ``ALREADY_EXISTS``. + + Only a new Stream starts retention. Reusing a Stream doesn't extend it. + """ + raise NotImplementedError + + @abstractmethod + async def append_records( + self, request: AppendRecordsRequest, *, request_id: str + ) -> AppendRecordsResponse: + """Append one batch from one Producer. + + Retries of one append use the same ``request_id``. + Retain recent request ids for each Producer, including at least its last + batch. Matching Producer, attempt and ``request_id`` identify a resend. + An empty request id never identifies a resend. + + Check these conditions in order. + + 1. Missing or expired Streams fail with ``NOT_FOUND`` or ``EXPIRED``. + 2. A resend returns the original offsets without comparing or writing + Records. + 3. If fencing is enabled, an attempt older than the latest writer attempt + fails with ``FENCED``. + + Return the first and last Record offsets. Only a new batch extends + retention. A resend doesn't extend it. + """ + raise NotImplementedError + + @abstractmethod + async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: + """Read one page after ``after_offset``, in Stream order. + + * Apply ``max_records`` and ``max_bytes``. Zero uses the Store's default. + Include the first Record even if it exceeds ``max_bytes``. + * The next read starts after the last returned Record. An empty page + leaves ``after_offset`` unchanged. + * If no Records are available, wait until one arrives or ``wait`` expires. + An unset wait returns immediately. The SDK converts zero to an unset + wait. Returning empty pages before a requested wait expires can cause + callers to poll repeatedly. + * Accept any offset returned by a response. Reject ``after_offset`` with + ``OFFSET_TOO_HIGH`` only if it exceeds the end of the Stream. + """ + raise NotImplementedError + + @abstractmethod + async def describe_stream( + self, request: DescribeStreamRequest + ) -> DescribeStreamResponse: + """Return the newest Record's offset, or empty bytes for an empty Stream.""" + raise NotImplementedError + + +@dataclass(frozen=True) +class StreamSelectContext: + """Context passed to :py:attr:`StreamConfig.store_selector` calls. + + .. warning:: + This API is experimental and subject to change. + """ + + id: str + """Id of the call's Stream.""" + + namespace: str | None = None + """Namespace of the calling client or Worker.""" + + +@dataclass(frozen=True) +class StreamConfig: + """Stream Stores shared by a client and its Workers. + + Appends that exceed :py:attr:`max_record_bytes`, :py:attr:`max_batch_bytes` + or :py:attr:`max_batch_records` fail with ``STREAM_ERROR_REASON_TOO_LARGE`` + before reaching the Store. ``rpc_metadata`` has no effect on Store calls. + + Streams have no close. Retention starts at create and restarts after each + append that writes a batch. Applications use their own terminal Record. + + In client, Activity and Workflow code, ``read`` and ``read_pages`` continue + after empty pages. ``read_pages`` yields those pages. Callers must stop the + iterator, for example with ``break`` or a timeout. An unset ``wait`` makes the + first request immediate. Later requests wait up to one minute. An explicit + wait applies to every request. Zero disables waiting, so an idle Stream can + cause repeated empty reads. ``read_page`` has no default wait. After a page, + the ``read`` iterator's ``next_request`` includes the next request's wait. + + A positive ``rpc_timeout`` caps client and Activity waits below the timeout, + leaving time for the Store to answer. An Activity that heartbeats between + Records needs a wait below its heartbeat timeout, or a separate heartbeat task. + + .. warning:: + This API is experimental and subject to change. + """ + + stores: Sequence[StreamStore] + """Stores available for Stream calls. At least one is required, and each + needs a unique, nonempty :py:meth:`StreamStore.name`. + """ + + store_selector: Callable[[StreamSelectContext], StreamStore] | None = None + """Select the Store for a call whose ``StreamRef`` has no Store name. + + Return an instance from :py:attr:`stores`. A selector is required with + multiple Stores. Without one, the sole Store handles these calls. + """ + + max_record_bytes: int = 1536 * 1024 + """Maximum stored Record size for an append or a live Workflow read. + + Includes its Producer. Defaults to 1.5 MiB and must be at least one. + """ + + max_batch_bytes: int = 4 * 1024 * 1024 + """Maximum total stored size of the Records in one append. Defaults to 4 MiB + and must be at least one. + """ + + max_batch_records: int = 1000 + """Maximum number of Records in one append. Defaults to 1000 and must be at + least one. + """ + + def __post_init__(self) -> None: + """Validate the Stores and the limits. + + Raises :exc:`ValueError` for no Store, a limit below one, several Stores + without a :py:attr:`store_selector`, an empty Store name, or a duplicate + name. + """ + if not self.stores: + raise ValueError("StreamConfig.stores must contain at least one Store.") + for limit in ("max_record_bytes", "max_batch_bytes", "max_batch_records"): + if getattr(self, limit) < 1: + raise ValueError( + f"StreamConfig.{limit} must be greater than or equal to one." + ) + if len(self.stores) > 1 and self.store_selector is None: + raise ValueError( + "StreamConfig.store_selector must be specified if multiple Stores " + "are registered." + ) + names: set[str] = set() + for store in self.stores: + name = store.name() + if not name: + raise ValueError( + "StreamConfig.stores contains a Store with an empty name." + ) + if name in names: + raise ValueError( + f"StreamConfig.stores contains multiple Stores with name '{name}'. " + "Each Store must have a unique name." + ) + names.add(name) + + def _store(self, name: str) -> StreamStore: + for store in self.stores: + if store.name() == name: + return store + raise ValueError(f"No Stream Store found with name '{name}'") + + def _store_for(self, ref: 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 e7bd820806..b8ae33cc25 100644 --- a/temporalio/testing/_workflow.py +++ b/temporalio/testing/_workflow.py @@ -104,6 +104,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. @@ -167,6 +168,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. @@ -196,6 +199,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 @@ -218,6 +222,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. @@ -278,6 +283,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. @@ -298,6 +305,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 @@ -741,6 +749,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, @@ -808,6 +817,7 @@ async def _bootstrap_dev_server( rpc_metadata=rpc_metadata, identity=identity, runtime=runtime, + stream_config=stream_config, ) except: try: @@ -878,6 +888,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 @@ -912,6 +923,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 cfd7fe0b08..9a4b693f74 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, ) for payload in start.header_fields.values(): 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 04516b7b9a..da6734bd74 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -1,20 +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.activity -import temporalio.api.stream.v1 -import temporalio.contrib.streams +import temporalio.api.sdk.v1 as sdk +import temporalio.api.stream.v1 as stream_api +import temporalio.api.streamservice.v1 as proto +import temporalio.client import temporalio.converter -import temporalio.nexus.system._support -import temporalio.testing +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.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) -> temporalio.api.stream.v1.Producer: @@ -26,6 +119,649 @@ def _producer_proto(producer: Any) -> temporalio.api.stream.v1.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 @@ -155,4 +891,122 @@ def test_a_workflow_producer_preserves_the_task_id_and_attempt() -> None: task.namespace, task.workflow_id, task.run_id = "ns", "workflow", "run" task.workflow_task_id = 11 task.attempt.started_event_id, task.attempt.attempt = 37, 2 - assert _producer_proto(temporalio.contrib.streams.as_producer(proto)) == proto + 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 db944aa5bbef59b556ffcfbb72d25cc2a8f8b052 Mon Sep 17 00:00:00 2001 From: Tim Conley Date: Mon, 30 Nov 2026 16:11:27 -0800 Subject: [PATCH 03/15] 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 e32871c22f..32da45ba4c 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 @@ -1586,15 +1591,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 0b71691016..86ec05197e 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 ( @@ -739,10 +742,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: @@ -754,6 +764,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 7e6526b95a..914856ff5e 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 @@ -1156,27 +1161,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 443d916cc6..1a80e9276c 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 @@ -673,8 +674,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( @@ -699,8 +700,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 da6734bd74..f8320a0dfe 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) -> temporalio.api.stream.v1.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 From 7c60ffd77ec9dc3a4bf5b01cccfa13e2bbcaa4c8 Mon Sep 17 00:00:00 2001 From: Tim Conley Date: Thu, 3 Dec 2026 00:34:09 -0700 Subject: [PATCH 04/15] Pin Core with Local Activity completion metadata Keep Python on the reviewed Core stack and use its task completion metadata for Local Activity identity during replay. --- .../api/sdk/v1/task_complete_metadata_pb2.py | 6 ++-- .../api/sdk/v1/task_complete_metadata_pb2.pyi | 21 +++++++++++++ .../activity_result/activity_result_pb2.pyi | 4 ++- .../proto/activity_task/activity_task_pb2.pyi | 4 ++- temporalio/bridge/proto/common/common_pb2.pyi | 6 +++- .../bridge/proto/external_data/__init__.py | 2 -- .../proto/external_data/external_data_pb2.py | 28 ++++++++--------- .../proto/external_data/external_data_pb2.pyi | 30 ------------------- .../workflow_commands_pb2.pyi | 4 ++- temporalio/bridge/sdk-core | 2 +- 10 files changed, 52 insertions(+), 55 deletions(-) diff --git a/temporalio/api/sdk/v1/task_complete_metadata_pb2.py b/temporalio/api/sdk/v1/task_complete_metadata_pb2.py index 411a4216bf..9c837d7c8a 100644 --- a/temporalio/api/sdk/v1/task_complete_metadata_pb2.py +++ b/temporalio/api/sdk/v1/task_complete_metadata_pb2.py @@ -14,7 +14,7 @@ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n0temporal/api/sdk/v1/task_complete_metadata.proto\x12\x13temporal.api.sdk.v1"x\n\x1dWorkflowTaskCompletedMetadata\x12\x17\n\x0f\x63ore_used_flags\x18\x01 \x03(\r\x12\x17\n\x0flang_used_flags\x18\x02 \x03(\r\x12\x10\n\x08sdk_name\x18\x03 \x01(\t\x12\x13\n\x0bsdk_version\x18\x04 \x01(\tB\x87\x01\n\x16io.temporal.api.sdk.v1B\x19TaskCompleteMetadataProtoP\x01Z\x1dgo.temporal.io/api/sdk/v1;sdk\xaa\x02\x15Temporalio.Api.Sdk.V1\xea\x02\x18Temporalio::Api::Sdk::V1b\x06proto3' + b'\n0temporal/api/sdk/v1/task_complete_metadata.proto\x12\x13temporal.api.sdk.v1"\x9d\x01\n\x1dWorkflowTaskCompletedMetadata\x12\x17\n\x0f\x63ore_used_flags\x18\x01 \x03(\r\x12\x17\n\x0flang_used_flags\x18\x02 \x03(\r\x12\x10\n\x08sdk_name\x18\x03 \x01(\t\x12\x13\n\x0bsdk_version\x18\x04 \x01(\t\x12#\n\x1bpending_local_activity_seqs\x18\x05 \x03(\rB\x87\x01\n\x16io.temporal.api.sdk.v1B\x19TaskCompleteMetadataProtoP\x01Z\x1dgo.temporal.io/api/sdk/v1;sdk\xaa\x02\x15Temporalio.Api.Sdk.V1\xea\x02\x18Temporalio::Api::Sdk::V1b\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -22,6 +22,6 @@ if _descriptor._USE_C_DESCRIPTORS == False: DESCRIPTOR._options = None DESCRIPTOR._serialized_options = b"\n\026io.temporal.api.sdk.v1B\031TaskCompleteMetadataProtoP\001Z\035go.temporal.io/api/sdk/v1;sdk\252\002\025Temporalio.Api.Sdk.V1\352\002\030Temporalio::Api::Sdk::V1" - _WORKFLOWTASKCOMPLETEDMETADATA._serialized_start = 73 - _WORKFLOWTASKCOMPLETEDMETADATA._serialized_end = 193 + _WORKFLOWTASKCOMPLETEDMETADATA._serialized_start = 74 + _WORKFLOWTASKCOMPLETEDMETADATA._serialized_end = 231 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/api/sdk/v1/task_complete_metadata_pb2.pyi b/temporalio/api/sdk/v1/task_complete_metadata_pb2.pyi index c4efd608b6..bff5c96395 100644 --- a/temporalio/api/sdk/v1/task_complete_metadata_pb2.pyi +++ b/temporalio/api/sdk/v1/task_complete_metadata_pb2.pyi @@ -21,6 +21,7 @@ class WorkflowTaskCompletedMetadata(google.protobuf.message.Message): LANG_USED_FLAGS_FIELD_NUMBER: builtins.int SDK_NAME_FIELD_NUMBER: builtins.int SDK_VERSION_FIELD_NUMBER: builtins.int + PENDING_LOCAL_ACTIVITY_SEQS_FIELD_NUMBER: builtins.int sdk_name: builtins.str """Name of the SDK that processed the task. This is usually something like "temporal-go" and is usually the same as client-name gRPC header. This should only be set if its value changed @@ -71,6 +72,22 @@ class WorkflowTaskCompletedMetadata(google.protobuf.message.Message): aip.dev/not-precedent: These really shouldn't have negative values. --) """ + @property + def pending_local_activity_seqs( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Sequence numbers of the local activities that this workflow task scheduled and that had no + result when the task completed. Set only in that case. On replay, the SDK gives each of these + local activities the origin that it had when this task scheduled it, so all its attempts keep + the same origin. The origin uses the `started_event_id` of the workflow task completion before + this one, so this field doesn't repeat it. + + Experimental. Might change in the future. + + (-- api-linter: core::0141::forbidden-types=disabled + aip.dev/not-precedent: Sequence numbers are never negative. --) + """ + def __init__( self, *, @@ -78,6 +95,8 @@ class WorkflowTaskCompletedMetadata(google.protobuf.message.Message): lang_used_flags: collections.abc.Iterable[builtins.int] | None = ..., sdk_name: builtins.str = ..., sdk_version: builtins.str = ..., + pending_local_activity_seqs: collections.abc.Iterable[builtins.int] + | None = ..., ) -> None: ... def ClearField( self, @@ -86,6 +105,8 @@ class WorkflowTaskCompletedMetadata(google.protobuf.message.Message): b"core_used_flags", "lang_used_flags", b"lang_used_flags", + "pending_local_activity_seqs", + b"pending_local_activity_seqs", "sdk_name", b"sdk_name", "sdk_version", diff --git a/temporalio/bridge/proto/activity_result/activity_result_pb2.pyi b/temporalio/bridge/proto/activity_result/activity_result_pb2.pyi index ea5b7e539d..f1cd152bf3 100644 --- a/temporalio/bridge/proto/activity_result/activity_result_pb2.pyi +++ b/temporalio/bridge/proto/activity_result/activity_result_pb2.pyi @@ -271,7 +271,9 @@ class DoBackoff(google.protobuf.message.Message): 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.""" + """The origin of this local activity. Lang must pass it to the retry that it schedules after + the backoff, so all attempts keep the same origin. + """ def __init__( self, diff --git a/temporalio/bridge/proto/activity_task/activity_task_pb2.pyi b/temporalio/bridge/proto/activity_task/activity_task_pb2.pyi index 5820ec579b..9efccb2059 100644 --- a/temporalio/bridge/proto/activity_task/activity_task_pb2.pyi +++ b/temporalio/bridge/proto/activity_task/activity_task_pb2.pyi @@ -271,7 +271,9 @@ class Start(google.protobuf.message.Message): def local_activity_origin( self, ) -> temporalio.bridge.proto.common.common_pb2.LocalActivityOrigin: - """Local Activity Stream writes keep their scheduling identity across retries.""" + """For a local activity, its origin. All its attempts have the same origin, also attempts that + Lang schedules again after a timer-backed backoff. Unset for other activities. + """ def __init__( self, diff --git a/temporalio/bridge/proto/common/common_pb2.pyi b/temporalio/bridge/proto/common/common_pb2.pyi index 25ae4de103..373bc6b45d 100644 --- a/temporalio/bridge/proto/common/common_pb2.pyi +++ b/temporalio/bridge/proto/common/common_pb2.pyi @@ -70,14 +70,18 @@ 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.""" + """Identifies one local activity in its workflow run, over all its attempts. A timer-backed backoff + schedules the next attempt as a new local activity, but that attempt keeps this origin. + """ DESCRIPTOR: google.protobuf.descriptor.Descriptor WORKFLOW_TASK_ID_FIELD_NUMBER: builtins.int ACTIVITY_ID_FIELD_NUMBER: builtins.int workflow_task_id: builtins.int + """The `previous_started_event_id` of the workflow task that scheduled the first attempt.""" activity_id: builtins.str + """The activity id of the first attempt.""" def __init__( self, *, diff --git a/temporalio/bridge/proto/external_data/__init__.py b/temporalio/bridge/proto/external_data/__init__.py index 9140144f96..1d221dc4b8 100644 --- a/temporalio/bridge/proto/external_data/__init__.py +++ b/temporalio/bridge/proto/external_data/__init__.py @@ -1,7 +1,6 @@ from .external_data_pb2 import ( LocalActivityMarkerData, PatchedMarkerData, - PendingLocalActivityOrigins, StreamAppendMarkerData, StreamAppendOffsets, StreamAppendOrigin, @@ -12,7 +11,6 @@ __all__ = [ "LocalActivityMarkerData", "PatchedMarkerData", - "PendingLocalActivityOrigins", "StreamAppendMarkerData", "StreamAppendOffsets", "StreamAppendOrigin", diff --git a/temporalio/bridge/proto/external_data/external_data_pb2.py b/temporalio/bridge/proto/external_data/external_data_pb2.py index 72227786bf..ffde6b9302 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.py +++ b/temporalio/bridge/proto/external_data/external_data_pb2.py @@ -21,7 +21,7 @@ ) 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%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' + 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"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()) @@ -33,18 +33,16 @@ ) _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 + _PATCHEDMARKERDATA._serialized_start = 559 + _PATCHEDMARKERDATA._serialized_end = 610 + _STREAMAPPENDMARKERDATA._serialized_start = 613 + _STREAMAPPENDMARKERDATA._serialized_end = 764 + _STREAMAPPENDORIGIN._serialized_start = 767 + _STREAMAPPENDORIGIN._serialized_end = 943 + _STREAMAPPENDRESULT._serialized_start = 946 + _STREAMAPPENDRESULT._serialized_end = 1170 + _STREAMAPPENDOFFSETS._serialized_start = 1172 + _STREAMAPPENDOFFSETS._serialized_end = 1236 + _STREAMFAILURE._serialized_start = 1238 + _STREAMFAILURE._serialized_end = 1286 # @@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 e7ee58369a..f5beeb8a36 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.pyi +++ b/temporalio/bridge/proto/external_data/external_data_pb2.pyi @@ -135,36 +135,6 @@ 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 diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi index 6b77439602..a1f058b00e 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi @@ -723,7 +723,9 @@ class ScheduleLocalActivity(google.protobuf.message.Message): 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.""" + """Pass the `local_activity_origin` from `DoBackoff` if this LA is scheduled because of a + timer-backed backoff attempt. + """ def __init__( self, diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index 80655abac3..605c64cdb0 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit 80655abac30adc11635f0e7fea6e452b5004e438 +Subproject commit 605c64cdb0ed67a272ddba4d8c7538cbe99009f9 From f51c197017a8cee23e992f5959c3925a8d48d757 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Thu, 3 Dec 2026 02:51:23 -0700 Subject: [PATCH 05/15] Use the combined Core append state machine Workflow appends and replay share one state machine. Regenerate the bridge bindings from the same Core revision used by the Worker. --- .../proto/external_data/external_data_pb2.pyi | 18 +++++++-------- .../workflow_activation_pb2.pyi | 22 ++++++++----------- .../workflow_commands_pb2.pyi | 16 +++++++------- temporalio/bridge/sdk-core | 2 +- 4 files changed, 27 insertions(+), 31 deletions(-) diff --git a/temporalio/bridge/proto/external_data/external_data_pb2.pyi b/temporalio/bridge/proto/external_data/external_data_pb2.pyi index f5beeb8a36..fb67a704bb 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.pyi +++ b/temporalio/bridge/proto/external_data/external_data_pb2.pyi @@ -159,8 +159,8 @@ 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. + """JSON data of a `core_stream_append` marker. Its `bytes` fields are Base64. An empty marker + separates a task that has an open append from the next task when chunking is on. """ DESCRIPTOR: google.protobuf.descriptor.Descriptor @@ -258,11 +258,11 @@ class StreamAppendResult(google.protobuf.message.Message): seq: builtins.int stream_id: builtins.str store: builtins.str - """The name of the Store that the append used. For a ref with no Store name, it is the empty - name if the Worker has a Stream runtime under it, else the name of its only runtime. + """The Store that the append used. A ref with no Store name uses the runtime under the empty name, + else the only runtime. """ activation_index: builtins.int - """The index of the activation, within its Workflow Task, in which Workflow code got the result.""" + """The activation, counted within its Workflow Task, that delivered the result.""" @property def appended(self) -> global___StreamAppendOffsets: ... @property @@ -333,18 +333,18 @@ 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.""" + """Why a Stream call failed. Core builds the failure for Workflow code from these two fields.""" 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. + """A `temporalio.api.enums.v1.StreamErrorReason` name, such as `STREAM_ERROR_REASON_FENCED`. History + stores it, so a reason can never be renamed. """ message: builtins.str - """The message of the failure, of at most 4096 bytes.""" + """The failure message, at most 4096 bytes.""" def __init__( self, *, diff --git a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi index 2c43796eef..91ead22b37 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi @@ -65,13 +65,12 @@ 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. + * Stream results share this slot with local activity resolutions, for the same reason. Both + are recorded in markers that replay scans ahead for. Each marker entry has the index of the + activation that delivered it. Both kinds share that index, so replay delivers every result + in its original activation. Within one activation, Stream results go first in `seq` order, + then local activity resolutions. A task with a Stream marker replays in its recorded + activations. * Queries always go last (and, in fact, always come in their own activation) * Evictions also always come in their own activation @@ -1666,10 +1665,7 @@ 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. - """ + """The result of an `AppendToStream` command.""" DESCRIPTOR: google.protobuf.descriptor.Descriptor @@ -1682,8 +1678,8 @@ class ResolveStreamAppend(google.protobuf.message.Message): def appended(self) -> global___StreamAppended: ... @property def failed(self) -> temporalio.api.failure.v1.message_pb2.Failure: - """An `ApplicationFailureInfo` of the type `stream_`, such as `stream_fenced`, with - `non_retryable` set. Its details have one `binary/protobuf` payload of a + """An `ApplicationFailureInfo` of type `stream_`, such as `stream_fenced`, with + `non_retryable` set. Its details are one `binary/protobuf` payload of a `temporalio.api.stream.v1.StreamErrorDetails`. """ diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi index a1f058b00e..e1436a6ff4 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi @@ -1959,16 +1959,16 @@ 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. + """Appends Records as the Workflow Producer and resolves with `ResolveStreamAppend`. Appends to one + Stream go out in command order. A task retry can write a batch again if History has no result for + it. - 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. + With no Store name, the append uses the runtime under the empty name, else the only runtime. A + bad seq or Stream ref, a missing runtime, or a Store outage at the task heartbeat fails the + Workflow Task. An invalid batch resolves with a failure. - 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. + Lang must accept results for appends that it no longer awaits. The terminal Workflow command + drops unresolved appends. Replay matches on seq and Stream and returns the result in History. """ DESCRIPTOR: google.protobuf.descriptor.Descriptor diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index 605c64cdb0..a3c2497be0 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit 605c64cdb0ed67a272ddba4d8c7538cbe99009f9 +Subproject commit a3c2497be0fcaa4af1e0e19edffa1a453c7ddf0b From 28d9c97d2d77a11942c6dc5ca1ff022231076716 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Thu, 3 Dec 2026 03:02:55 -0700 Subject: [PATCH 06/15] Document client and Activity Stream calls --- changelog/added/chatty-stream-otter.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog/added/chatty-stream-otter.md diff --git a/changelog/added/chatty-stream-otter.md b/changelog/added/chatty-stream-otter.md new file mode 100644 index 0000000000..6497333a14 --- /dev/null +++ b/changelog/added/chatty-stream-otter.md @@ -0,0 +1 @@ +Add experimental Stream calls for clients and Activities, with client interceptors for each operation. From 334cb6a6910fc894dbbd7da77d00c95f95c74ab0 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Thu, 3 Dec 2026 09:54:14 -0700 Subject: [PATCH 07/15] Simplify the client Stream docstrings The docstrings say the same in fewer words. No code changes. --- temporalio/client/_client.py | 7 +++---- temporalio/client/_stream_store.py | 11 +++++------ 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/temporalio/client/_client.py b/temporalio/client/_client.py index 8b338daeef..01e793b249 100644 --- a/temporalio/client/_client.py +++ b/temporalio/client/_client.py @@ -253,10 +253,9 @@ 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`. + stream_config: Stream Stores for this client and the workers that use + it. Each Stream call goes to one of these Stores. Without it, a + Stream call raises :exc:`ValueError`. .. warning:: This API is experimental and subject to change. diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 1a80e9276c..0957bc656e 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -46,8 +46,8 @@ _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.""" +"""Time reserved for the Store's answer before ``rpc_timeout`` ends a client read. +A shorter timeout reserves a tenth of itself.""" class StreamStore(ABC): @@ -368,8 +368,7 @@ def _store_request( _MAX_STREAM_ID_BYTES = 4096 -"""The maximum length of a Stream id in bytes, as the API of the Stream service -sets it.""" +"""Maximum length of a Stream id in bytes, as set by the Stream service API.""" _MAX_OFFSET_BYTES = 1024 """The maximum length of an offset in bytes. Offsets go into Workflow History.""" @@ -415,9 +414,9 @@ def _store_request( 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. + """Check a Store request the way SDK Core's Stream runtime does. - ``limits`` are the ``max_record_bytes``, the ``max_batch_bytes`` and the + ``limits`` are the ``max_record_bytes``, ``max_batch_bytes`` and ``max_batch_records`` of a Stream config. Raises: From c66f5a25a36f3769190a464eeba340bad8cd5701 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Thu, 3 Dec 2026 15:17:03 -0700 Subject: [PATCH 08/15] Use Core with the simpler Stream append rules Core dropped the append rules that no replay observes and corrected its marker docs, so the pin moves and the stubs take the new comments. --- .../proto/external_data/external_data_pb2.pyi | 13 ++++++++++--- .../workflow_activation/workflow_activation_pb2.pyi | 10 +++++----- temporalio/bridge/sdk-core | 2 +- 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/temporalio/bridge/proto/external_data/external_data_pb2.pyi b/temporalio/bridge/proto/external_data/external_data_pb2.pyi index fb67a704bb..0a517cc52b 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.pyi +++ b/temporalio/bridge/proto/external_data/external_data_pb2.pyi @@ -159,8 +159,9 @@ global___PatchedMarkerData = PatchedMarkerData @typing.final class StreamAppendMarkerData(google.protobuf.message.Message): - """JSON data of a `core_stream_append` marker. Its `bytes` fields are Base64. An empty marker - separates a task that has an open append from the next task when chunking is on. + """JSON data of a `core_stream_append` marker. Its `bytes` fields are Base64. A marker with no + result keeps a task that has an open append apart from the next task in a replay with chunking + on. """ DESCRIPTOR: google.protobuf.descriptor.Descriptor @@ -175,7 +176,9 @@ class StreamAppendMarkerData(google.protobuf.message.Message): ]: ... @property def pending_origin(self) -> global___StreamAppendOrigin: - """Replay must resend outstanding writes with the original Producer, attempt and request id.""" + """Set if the task completed with an open append that it issued. A new Worker resends each of + them with this Producer attempt and the same request id. + """ def __init__( self, @@ -197,6 +200,10 @@ global___StreamAppendMarkerData = StreamAppendMarkerData @typing.final class StreamAppendOrigin(google.protobuf.message.Message): + """The Workflow Task that issued the appends `first_seq` to `last_seq` that had no result when the + task completed. + """ + DESCRIPTOR: google.protobuf.descriptor.Descriptor FIRST_SEQ_FIELD_NUMBER: builtins.int diff --git a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi index 91ead22b37..f148a88948 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi @@ -66,11 +66,11 @@ class WorkflowActivation(google.protobuf.message.Message): this to ensure the LA resolution happens after that cancel (or whatever else it may be) as it normally would have when executing. * Stream results share this slot with local activity resolutions, for the same reason. Both - are recorded in markers that replay scans ahead for. Each marker entry has the index of the - activation that delivered it. Both kinds share that index, so replay delivers every result - in its original activation. Within one activation, Stream results go first in `seq` order, - then local activity resolutions. A task with a Stream marker replays in its recorded - activations. + are recorded in markers that replay scans ahead for, and each marker entry has the index of + the activation that delivered it. Both kinds share that index. A task with a Stream marker + replays in its recorded activations, and so does each task of a History with chunking off. + Within one activation, Stream results go first in `seq` order, then local activity + resolutions. * Queries always go last (and, in fact, always come in their own activation) * Evictions also always come in their own activation diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index a3c2497be0..fb24e79aa2 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit a3c2497be0fcaa4af1e0e19edffa1a453c7ddf0b +Subproject commit fb24e79aa2ed1cb485f9e847193e8db4f186eba5 From de1dcaed84317b23ebaf04b1e8b2e27fea94b81b Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Thu, 3 Dec 2026 16:34:10 -0700 Subject: [PATCH 09/15] Identify a Local Activity Producer by its first schedule Core gives a Local Activity the seq of the command that first scheduled it, and the Producer has it in place of the Workflow Task id. A retry keeps it, so the Workflow Task completion needs no list of pending Local Activities. --- temporalio/activity.py | 2 +- .../api/sdk/v1/task_complete_metadata_pb2.py | 6 ++-- .../api/sdk/v1/task_complete_metadata_pb2.pyi | 21 ------------ temporalio/api/stream/v1/message_pb2.py | 32 +++++++++---------- temporalio/api/stream/v1/message_pb2.pyi | 23 +++++++------ temporalio/bridge/proto/common/common_pb2.py | 20 ++++++------ temporalio/bridge/proto/common/common_pb2.pyi | 13 +++----- .../proto/external_data/external_data_pb2.py | 16 +++++----- .../proto/external_data/external_data_pb2.pyi | 14 ++------ temporalio/bridge/sdk-core | 2 +- temporalio/client/_stream_store.py | 2 +- temporalio/contrib/streams/_producer.py | 5 +-- temporalio/nexus/system/_support.py | 4 +-- .../nexus/system/stream_service/models.py | 8 ++--- temporalio/worker/_activity.py | 2 +- tests/nexus/test_streams.py | 5 ++- tests/nexus/test_streams_with_worker.py | 26 ++++++--------- 17 files changed, 81 insertions(+), 120 deletions(-) diff --git a/temporalio/activity.py b/temporalio/activity.py index 23f7155edc..23c9aab766 100644 --- a/temporalio/activity.py +++ b/temporalio/activity.py @@ -182,7 +182,7 @@ class Info: apart. Zero if Core couldn't read it.""" _local_activity_origin: tuple[int, str] | None = None - """Workflow Task id and Activity id of the first schedule of this Local Activity. + """Command seq and Activity id of the first schedule of this Local Activity. Retries keep them, so that every attempt writes to a Stream as the same Producer.""" @property diff --git a/temporalio/api/sdk/v1/task_complete_metadata_pb2.py b/temporalio/api/sdk/v1/task_complete_metadata_pb2.py index 9c837d7c8a..411a4216bf 100644 --- a/temporalio/api/sdk/v1/task_complete_metadata_pb2.py +++ b/temporalio/api/sdk/v1/task_complete_metadata_pb2.py @@ -14,7 +14,7 @@ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n0temporal/api/sdk/v1/task_complete_metadata.proto\x12\x13temporal.api.sdk.v1"\x9d\x01\n\x1dWorkflowTaskCompletedMetadata\x12\x17\n\x0f\x63ore_used_flags\x18\x01 \x03(\r\x12\x17\n\x0flang_used_flags\x18\x02 \x03(\r\x12\x10\n\x08sdk_name\x18\x03 \x01(\t\x12\x13\n\x0bsdk_version\x18\x04 \x01(\t\x12#\n\x1bpending_local_activity_seqs\x18\x05 \x03(\rB\x87\x01\n\x16io.temporal.api.sdk.v1B\x19TaskCompleteMetadataProtoP\x01Z\x1dgo.temporal.io/api/sdk/v1;sdk\xaa\x02\x15Temporalio.Api.Sdk.V1\xea\x02\x18Temporalio::Api::Sdk::V1b\x06proto3' + b'\n0temporal/api/sdk/v1/task_complete_metadata.proto\x12\x13temporal.api.sdk.v1"x\n\x1dWorkflowTaskCompletedMetadata\x12\x17\n\x0f\x63ore_used_flags\x18\x01 \x03(\r\x12\x17\n\x0flang_used_flags\x18\x02 \x03(\r\x12\x10\n\x08sdk_name\x18\x03 \x01(\t\x12\x13\n\x0bsdk_version\x18\x04 \x01(\tB\x87\x01\n\x16io.temporal.api.sdk.v1B\x19TaskCompleteMetadataProtoP\x01Z\x1dgo.temporal.io/api/sdk/v1;sdk\xaa\x02\x15Temporalio.Api.Sdk.V1\xea\x02\x18Temporalio::Api::Sdk::V1b\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -22,6 +22,6 @@ if _descriptor._USE_C_DESCRIPTORS == False: DESCRIPTOR._options = None DESCRIPTOR._serialized_options = b"\n\026io.temporal.api.sdk.v1B\031TaskCompleteMetadataProtoP\001Z\035go.temporal.io/api/sdk/v1;sdk\252\002\025Temporalio.Api.Sdk.V1\352\002\030Temporalio::Api::Sdk::V1" - _WORKFLOWTASKCOMPLETEDMETADATA._serialized_start = 74 - _WORKFLOWTASKCOMPLETEDMETADATA._serialized_end = 231 + _WORKFLOWTASKCOMPLETEDMETADATA._serialized_start = 73 + _WORKFLOWTASKCOMPLETEDMETADATA._serialized_end = 193 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/api/sdk/v1/task_complete_metadata_pb2.pyi b/temporalio/api/sdk/v1/task_complete_metadata_pb2.pyi index bff5c96395..c4efd608b6 100644 --- a/temporalio/api/sdk/v1/task_complete_metadata_pb2.pyi +++ b/temporalio/api/sdk/v1/task_complete_metadata_pb2.pyi @@ -21,7 +21,6 @@ class WorkflowTaskCompletedMetadata(google.protobuf.message.Message): LANG_USED_FLAGS_FIELD_NUMBER: builtins.int SDK_NAME_FIELD_NUMBER: builtins.int SDK_VERSION_FIELD_NUMBER: builtins.int - PENDING_LOCAL_ACTIVITY_SEQS_FIELD_NUMBER: builtins.int sdk_name: builtins.str """Name of the SDK that processed the task. This is usually something like "temporal-go" and is usually the same as client-name gRPC header. This should only be set if its value changed @@ -72,22 +71,6 @@ class WorkflowTaskCompletedMetadata(google.protobuf.message.Message): aip.dev/not-precedent: These really shouldn't have negative values. --) """ - @property - def pending_local_activity_seqs( - self, - ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: - """Sequence numbers of the local activities that this workflow task scheduled and that had no - result when the task completed. Set only in that case. On replay, the SDK gives each of these - local activities the origin that it had when this task scheduled it, so all its attempts keep - the same origin. The origin uses the `started_event_id` of the workflow task completion before - this one, so this field doesn't repeat it. - - Experimental. Might change in the future. - - (-- api-linter: core::0141::forbidden-types=disabled - aip.dev/not-precedent: Sequence numbers are never negative. --) - """ - def __init__( self, *, @@ -95,8 +78,6 @@ class WorkflowTaskCompletedMetadata(google.protobuf.message.Message): lang_used_flags: collections.abc.Iterable[builtins.int] | None = ..., sdk_name: builtins.str = ..., sdk_version: builtins.str = ..., - pending_local_activity_seqs: collections.abc.Iterable[builtins.int] - | None = ..., ) -> None: ... def ClearField( self, @@ -105,8 +86,6 @@ class WorkflowTaskCompletedMetadata(google.protobuf.message.Message): b"core_used_flags", "lang_used_flags", b"lang_used_flags", - "pending_local_activity_seqs", - b"pending_local_activity_seqs", "sdk_name", b"sdk_name", "sdk_version", diff --git a/temporalio/api/stream/v1/message_pb2.py b/temporalio/api/stream/v1/message_pb2.py index 9216b99620..2fe7bd7e9c 100644 --- a/temporalio/api/stream/v1/message_pb2.py +++ b/temporalio/api/stream/v1/message_pb2.py @@ -23,7 +23,7 @@ ) DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n$temporal/api/stream/v1/message.proto\x12\x16temporal.api.stream.v1\x1a\x1fgoogle/protobuf/timestamp.proto\x1a$temporal/api/common/v1/message.proto\x1a"temporal/api/enums/v1/stream.proto"r\n\x13WorkflowTaskAttempt\x12\x18\n\x10started_event_id\x18\x01 \x01(\x03\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\x05\x12\x30\n\x0cstarted_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"b\n\x14LocalActivityAttempt\x12\x39\n\x04task\x18\x01 \x01(\x0b\x32+.temporal.api.stream.v1.WorkflowTaskAttempt\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\x05"^\n\x0f\x41\x63tivityAttempt\x12:\n\x16\x61ttempt_scheduled_time\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\x05"\xa2\x01\n\x10WorkflowProducer\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\x12\x18\n\x10workflow_task_id\x18\x04 \x01(\x03\x12<\n\x07\x61ttempt\x18\x05 \x01(\x0b\x32+.temporal.api.stream.v1.WorkflowTaskAttempt"\xbd\x01\n\x15LocalActivityProducer\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\x12\x18\n\x10workflow_task_id\x18\x04 \x01(\x03\x12\x13\n\x0b\x61\x63tivity_id\x18\x05 \x01(\t\x12=\n\x07\x61ttempt\x18\x06 \x01(\x0b\x32,.temporal.api.stream.v1.LocalActivityAttempt"\xbd\x01\n\x18WorkflowActivityProducer\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\x12\x13\n\x0b\x61\x63tivity_id\x18\x04 \x01(\t\x12\x1a\n\x12scheduled_event_id\x18\x05 \x01(\x03\x12\x38\n\x07\x61ttempt\x18\x06 \x01(\x0b\x32\'.temporal.api.stream.v1.ActivityAttempt"\x8e\x01\n\x1aStandaloneActivityProducer\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x0e\n\x06run_id\x18\x03 \x01(\t\x12\x38\n\x07\x61ttempt\x18\x04 \x01(\x0b\x32\'.temporal.api.stream.v1.ActivityAttempt"/\n\x0e\x43lientProducer\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\n\n\x02id\x18\x02 \x01(\t"\xf5\x02\n\x08Producer\x12<\n\x08workflow\x18\x01 \x01(\x0b\x32(.temporal.api.stream.v1.WorkflowProducerH\x00\x12G\n\x0elocal_activity\x18\x02 \x01(\x0b\x32-.temporal.api.stream.v1.LocalActivityProducerH\x00\x12M\n\x11workflow_activity\x18\x03 \x01(\x0b\x32\x30.temporal.api.stream.v1.WorkflowActivityProducerH\x00\x12Q\n\x13standalone_activity\x18\x04 \x01(\x0b\x32\x32.temporal.api.stream.v1.StandaloneActivityProducerH\x00\x12\x38\n\x06\x63lient\x18\x05 \x01(\x0b\x32&.temporal.api.stream.v1.ClientProducerH\x00\x42\x06\n\x04kind"=\n\x0c\x41ppendRecord\x12-\n\x04\x62ody\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"\x81\x01\n\x0cStreamRecord\x12\x32\n\x08producer\x18\x01 \x01(\x0b\x32 .temporal.api.stream.v1.Producer\x12-\n\x04\x62ody\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x0e\n\x06offset\x18\x03 \x01(\x0c"N\n\x12StreamErrorDetails\x12\x38\n\x06reason\x18\x01 \x01(\x0e\x32(.temporal.api.enums.v1.StreamErrorReasonB\x89\x01\n\x19io.temporal.api.stream.v1B\x0cMessageProtoP\x01Z#go.temporal.io/api/stream/v1;stream\xaa\x02\x18Temporalio.Api.Stream.V1\xea\x02\x1bTemporalio::Api::Stream::V1b\x06proto3' + b'\n$temporal/api/stream/v1/message.proto\x12\x16temporal.api.stream.v1\x1a\x1fgoogle/protobuf/timestamp.proto\x1a$temporal/api/common/v1/message.proto\x1a"temporal/api/enums/v1/stream.proto"r\n\x13WorkflowTaskAttempt\x12\x18\n\x10started_event_id\x18\x01 \x01(\x03\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\x05\x12\x30\n\x0cstarted_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"b\n\x14LocalActivityAttempt\x12\x39\n\x04task\x18\x01 \x01(\x0b\x32+.temporal.api.stream.v1.WorkflowTaskAttempt\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\x05"^\n\x0f\x41\x63tivityAttempt\x12:\n\x16\x61ttempt_scheduled_time\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\x05"\xa2\x01\n\x10WorkflowProducer\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\x12\x18\n\x10workflow_task_id\x18\x04 \x01(\x03\x12<\n\x07\x61ttempt\x18\x05 \x01(\x0b\x32+.temporal.api.stream.v1.WorkflowTaskAttempt"\xc8\x01\n\x15LocalActivityProducer\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\x12\x13\n\x0b\x61\x63tivity_id\x18\x05 \x01(\t\x12=\n\x07\x61ttempt\x18\x06 \x01(\x0b\x32,.temporal.api.stream.v1.LocalActivityAttempt\x12\x0b\n\x03seq\x18\x07 \x01(\rJ\x04\x08\x04\x10\x05R\x10workflow_task_id"\xbd\x01\n\x18WorkflowActivityProducer\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\x12\x13\n\x0b\x61\x63tivity_id\x18\x04 \x01(\t\x12\x1a\n\x12scheduled_event_id\x18\x05 \x01(\x03\x12\x38\n\x07\x61ttempt\x18\x06 \x01(\x0b\x32\'.temporal.api.stream.v1.ActivityAttempt"\x8e\x01\n\x1aStandaloneActivityProducer\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x0e\n\x06run_id\x18\x03 \x01(\t\x12\x38\n\x07\x61ttempt\x18\x04 \x01(\x0b\x32\'.temporal.api.stream.v1.ActivityAttempt"/\n\x0e\x43lientProducer\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\n\n\x02id\x18\x02 \x01(\t"\xf5\x02\n\x08Producer\x12<\n\x08workflow\x18\x01 \x01(\x0b\x32(.temporal.api.stream.v1.WorkflowProducerH\x00\x12G\n\x0elocal_activity\x18\x02 \x01(\x0b\x32-.temporal.api.stream.v1.LocalActivityProducerH\x00\x12M\n\x11workflow_activity\x18\x03 \x01(\x0b\x32\x30.temporal.api.stream.v1.WorkflowActivityProducerH\x00\x12Q\n\x13standalone_activity\x18\x04 \x01(\x0b\x32\x32.temporal.api.stream.v1.StandaloneActivityProducerH\x00\x12\x38\n\x06\x63lient\x18\x05 \x01(\x0b\x32&.temporal.api.stream.v1.ClientProducerH\x00\x42\x06\n\x04kind"=\n\x0c\x41ppendRecord\x12-\n\x04\x62ody\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"\x81\x01\n\x0cStreamRecord\x12\x32\n\x08producer\x18\x01 \x01(\x0b\x32 .temporal.api.stream.v1.Producer\x12-\n\x04\x62ody\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x0e\n\x06offset\x18\x03 \x01(\x0c"N\n\x12StreamErrorDetails\x12\x38\n\x06reason\x18\x01 \x01(\x0e\x32(.temporal.api.enums.v1.StreamErrorReasonB\x89\x01\n\x19io.temporal.api.stream.v1B\x0cMessageProtoP\x01Z#go.temporal.io/api/stream/v1;stream\xaa\x02\x18Temporalio.Api.Stream.V1\xea\x02\x1bTemporalio::Api::Stream::V1b\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -40,19 +40,19 @@ _WORKFLOWPRODUCER._serialized_start = 484 _WORKFLOWPRODUCER._serialized_end = 646 _LOCALACTIVITYPRODUCER._serialized_start = 649 - _LOCALACTIVITYPRODUCER._serialized_end = 838 - _WORKFLOWACTIVITYPRODUCER._serialized_start = 841 - _WORKFLOWACTIVITYPRODUCER._serialized_end = 1030 - _STANDALONEACTIVITYPRODUCER._serialized_start = 1033 - _STANDALONEACTIVITYPRODUCER._serialized_end = 1175 - _CLIENTPRODUCER._serialized_start = 1177 - _CLIENTPRODUCER._serialized_end = 1224 - _PRODUCER._serialized_start = 1227 - _PRODUCER._serialized_end = 1600 - _APPENDRECORD._serialized_start = 1602 - _APPENDRECORD._serialized_end = 1663 - _STREAMRECORD._serialized_start = 1666 - _STREAMRECORD._serialized_end = 1795 - _STREAMERRORDETAILS._serialized_start = 1797 - _STREAMERRORDETAILS._serialized_end = 1875 + _LOCALACTIVITYPRODUCER._serialized_end = 849 + _WORKFLOWACTIVITYPRODUCER._serialized_start = 852 + _WORKFLOWACTIVITYPRODUCER._serialized_end = 1041 + _STANDALONEACTIVITYPRODUCER._serialized_start = 1044 + _STANDALONEACTIVITYPRODUCER._serialized_end = 1186 + _CLIENTPRODUCER._serialized_start = 1188 + _CLIENTPRODUCER._serialized_end = 1235 + _PRODUCER._serialized_start = 1238 + _PRODUCER._serialized_end = 1611 + _APPENDRECORD._serialized_start = 1613 + _APPENDRECORD._serialized_end = 1674 + _STREAMRECORD._serialized_start = 1677 + _STREAMRECORD._serialized_end = 1806 + _STREAMERRORDETAILS._serialized_start = 1808 + _STREAMERRORDETAILS._serialized_end = 1886 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/api/stream/v1/message_pb2.pyi b/temporalio/api/stream/v1/message_pb2.pyi index 1a925bf356..bd2f68cd4a 100644 --- a/temporalio/api/stream/v1/message_pb2.pyi +++ b/temporalio/api/stream/v1/message_pb2.pyi @@ -197,22 +197,25 @@ class LocalActivityProducer(google.protobuf.message.Message): NAMESPACE_FIELD_NUMBER: builtins.int WORKFLOW_ID_FIELD_NUMBER: builtins.int RUN_ID_FIELD_NUMBER: builtins.int - WORKFLOW_TASK_ID_FIELD_NUMBER: builtins.int ACTIVITY_ID_FIELD_NUMBER: builtins.int ATTEMPT_FIELD_NUMBER: builtins.int + SEQ_FIELD_NUMBER: builtins.int namespace: builtins.str """Required. The namespace of the Workflow that made the call.""" workflow_id: builtins.str """Required.""" run_id: builtins.str """Required.""" - workflow_task_id: builtins.int - """Retries retain the original scheduling task's id, including after a Workflow timer. - Zero identifies a Local Activity first scheduled in the run's first Workflow Task. - """ activity_id: builtins.str - """Required. The SDK keeps this id across retries so they share one Producer. - The id must distinguish Local Activities first scheduled in the same Workflow Task. + """Required. The Activity id of the first schedule, for display. The SDK keeps it across + retries. + """ + seq: builtins.int + """The sequence number of the command that first scheduled the Local Activity. It identifies + the Local Activity in its Workflow run. Retries retain it, including after a Workflow timer. + + (-- api-linter: core::0141::forbidden-types=disabled + aip.dev/not-precedent: Sequence numbers are never negative. --) """ @property def attempt(self) -> global___LocalActivityAttempt: @@ -224,9 +227,9 @@ class LocalActivityProducer(google.protobuf.message.Message): namespace: builtins.str = ..., workflow_id: builtins.str = ..., run_id: builtins.str = ..., - workflow_task_id: builtins.int = ..., activity_id: builtins.str = ..., attempt: global___LocalActivityAttempt | None = ..., + seq: builtins.int = ..., ) -> None: ... def HasField( self, field_name: typing.Literal["attempt", b"attempt"] @@ -242,10 +245,10 @@ class LocalActivityProducer(google.protobuf.message.Message): b"namespace", "run_id", b"run_id", + "seq", + b"seq", "workflow_id", b"workflow_id", - "workflow_task_id", - b"workflow_task_id", ], ) -> None: ... diff --git a/temporalio/bridge/proto/common/common_pb2.py b/temporalio/bridge/proto/common/common_pb2.py index 98d53ad2e9..abe2596725 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"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' + b'\n%temporal/sdk/core/common/common.proto\x12\x0e\x63oresdk.common\x1a\x1egoogle/protobuf/duration.proto"7\n\x13LocalActivityOrigin\x12\x0b\n\x03seq\x18\x01 \x01(\r\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,14 +26,14 @@ DESCRIPTOR._serialized_options = ( b"\352\002)Temporalio::Internal::Bridge::Api::Common" ) - _VERSIONINGINTENT._serialized_start = 465 - _VERSIONINGINTENT._serialized_end = 529 + _VERSIONINGINTENT._serialized_start = 452 + _VERSIONINGINTENT._serialized_end = 516 _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 + _LOCALACTIVITYORIGIN._serialized_end = 144 + _NAMESPACEDWORKFLOWEXECUTION._serialized_start = 146 + _NAMESPACEDWORKFLOWEXECUTION._serialized_end = 231 + _WORKERDEPLOYMENTVERSION._serialized_start = 233 + _WORKERDEPLOYMENTVERSION._serialized_end = 301 + _EXTERNALSTORAGEMETRICS._serialized_start = 304 + _EXTERNALSTORAGEMETRICS._serialized_end = 450 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/common/common_pb2.pyi b/temporalio/bridge/proto/common/common_pb2.pyi index 373bc6b45d..b438df0003 100644 --- a/temporalio/bridge/proto/common/common_pb2.pyi +++ b/temporalio/bridge/proto/common/common_pb2.pyi @@ -76,23 +76,20 @@ class LocalActivityOrigin(google.protobuf.message.Message): DESCRIPTOR: google.protobuf.descriptor.Descriptor - WORKFLOW_TASK_ID_FIELD_NUMBER: builtins.int + SEQ_FIELD_NUMBER: builtins.int ACTIVITY_ID_FIELD_NUMBER: builtins.int - workflow_task_id: builtins.int - """The `previous_started_event_id` of the workflow task that scheduled the first attempt.""" + seq: builtins.int + """The `seq` of the command that scheduled the first attempt.""" activity_id: builtins.str """The activity id of the first attempt.""" def __init__( self, *, - workflow_task_id: builtins.int = ..., + seq: 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" - ], + self, field_name: typing.Literal["activity_id", b"activity_id", "seq", b"seq"] ) -> None: ... global___LocalActivityOrigin = LocalActivityOrigin diff --git a/temporalio/bridge/proto/external_data/external_data_pb2.py b/temporalio/bridge/proto/external_data/external_data_pb2.py index ffde6b9302..a4b6cd4f3c 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.py +++ b/temporalio/bridge/proto/external_data/external_data_pb2.py @@ -21,7 +21,7 @@ ) 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%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"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' + 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"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"\x8b\x01\n\x12StreamAppendOrigin\x12\x18\n\x10workflow_task_id\x18\x01 \x01(\x03\x12\x18\n\x10started_event_id\x18\x02 \x01(\x03\x12\x0f\n\x07\x61ttempt\x18\x03 \x01(\x05\x12\x30\n\x0cstarted_time\x18\x04 \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()) @@ -38,11 +38,11 @@ _STREAMAPPENDMARKERDATA._serialized_start = 613 _STREAMAPPENDMARKERDATA._serialized_end = 764 _STREAMAPPENDORIGIN._serialized_start = 767 - _STREAMAPPENDORIGIN._serialized_end = 943 - _STREAMAPPENDRESULT._serialized_start = 946 - _STREAMAPPENDRESULT._serialized_end = 1170 - _STREAMAPPENDOFFSETS._serialized_start = 1172 - _STREAMAPPENDOFFSETS._serialized_end = 1236 - _STREAMFAILURE._serialized_start = 1238 - _STREAMFAILURE._serialized_end = 1286 + _STREAMAPPENDORIGIN._serialized_end = 906 + _STREAMAPPENDRESULT._serialized_start = 909 + _STREAMAPPENDRESULT._serialized_end = 1133 + _STREAMAPPENDOFFSETS._serialized_start = 1135 + _STREAMAPPENDOFFSETS._serialized_end = 1199 + _STREAMFAILURE._serialized_start = 1201 + _STREAMFAILURE._serialized_end = 1249 # @@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 0a517cc52b..452a492875 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.pyi +++ b/temporalio/bridge/proto/external_data/external_data_pb2.pyi @@ -200,20 +200,16 @@ global___StreamAppendMarkerData = StreamAppendMarkerData @typing.final class StreamAppendOrigin(google.protobuf.message.Message): - """The Workflow Task that issued the appends `first_seq` to `last_seq` that had no result when the - task completed. + """The Workflow Task that issued the appends that had no result when it completed. They are the + open appends that have no origin from an earlier task. """ 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 @@ -222,8 +218,6 @@ class StreamAppendOrigin(google.protobuf.message.Message): def __init__( self, *, - first_seq: builtins.int = ..., - last_seq: builtins.int = ..., workflow_task_id: builtins.int = ..., started_event_id: builtins.int = ..., attempt: builtins.int = ..., @@ -237,10 +231,6 @@ class StreamAppendOrigin(google.protobuf.message.Message): 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", diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index fb24e79aa2..79710137b6 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit fb24e79aa2ed1cb485f9e847193e8db4f186eba5 +Subproject commit 79710137b692866234b7523e8424de25bf4777b6 diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 0957bc656e..5fcfcd71f5 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -391,8 +391,8 @@ def _store_request( ("namespace", "namespace"), ("workflow_id", "Workflow id"), ("run_id", "run id"), - ("workflow_task_id", "Workflow Task id"), ("activity_id", "Activity id"), + ("seq", "Local Activity seq"), ), "workflow_activity": ( ("namespace", "namespace"), diff --git a/temporalio/contrib/streams/_producer.py b/temporalio/contrib/streams/_producer.py index 4fd3aa4c9e..6a13cd2429 100644 --- a/temporalio/contrib/streams/_producer.py +++ b/temporalio/contrib/streams/_producer.py @@ -22,8 +22,9 @@ def current_producer() -> temporalio.nexus.system.stream_service.Producer: For an Activity of a Workflow, the Producer has the Activity id and the id of its ``ActivityTaskScheduled`` event, so a later Activity that reuses the - Activity id is a separate Producer. A Local Activity keeps the identity of its - original schedule across retries, including retries after a Workflow timer. + Activity id is a separate Producer. For a Local Activity, it has the command + sequence number and the Activity id of the first schedule. Retries keep both, + also when a timer delays the retry. Raises: RuntimeError: The caller isn't in an Activity, or Core didn't give a diff --git a/temporalio/nexus/system/_support.py b/temporalio/nexus/system/_support.py index 654e5fc49e..025c854c23 100644 --- a/temporalio/nexus/system/_support.py +++ b/temporalio/nexus/system/_support.py @@ -143,7 +143,7 @@ def activity_producer(info: "temporalio.activity.Info") -> "Producer": raise RuntimeError( "Local Activity has no scheduling origin for its Producer" ) - workflow_task_id, activity_id = origin + seq, activity_id = origin local_attempt = models.LocalActivityAttempt( task=models.WorkflowTaskAttempt( started_event_id=task.started_event_id, @@ -160,7 +160,7 @@ def activity_producer(info: "temporalio.activity.Info") -> "Producer": namespace=info.namespace, workflow_id=workflow_id, run_id=run_id, - workflow_task_id=workflow_task_id, + seq=seq, activity_id=activity_id, attempt=local_attempt, ) diff --git a/temporalio/nexus/system/stream_service/models.py b/temporalio/nexus/system/stream_service/models.py index 989b1f6904..d99d809775 100644 --- a/temporalio/nexus/system/stream_service/models.py +++ b/temporalio/nexus/system/stream_service/models.py @@ -607,7 +607,7 @@ class LocalActivityProducer: namespace: str workflow_id: str run_id: str - workflow_task_id: int + seq: int activity_id: str attempt: LocalActivityAttempt @@ -637,7 +637,7 @@ def from_transfer_type( if not value.run_id: raise ValueError("missing required field LocalActivityProducer.run_id") run_id = value.run_id - workflow_task_id = value.workflow_task_id + seq = value.seq if not value.activity_id: raise ValueError("missing required field LocalActivityProducer.activity_id") activity_id = value.activity_id @@ -650,7 +650,7 @@ def from_transfer_type( namespace=namespace, workflow_id=workflow_id, run_id=run_id, - workflow_task_id=workflow_task_id, + seq=seq, activity_id=activity_id, attempt=attempt, ) @@ -664,7 +664,7 @@ def to_transfer_type( message.namespace = value.namespace message.workflow_id = value.workflow_id message.run_id = value.run_id - message.workflow_task_id = value.workflow_task_id + message.seq = value.seq message.activity_id = value.activity_id message.attempt.CopyFrom( _LocalActivityAttemptTransferTypeConverter().to_transfer_type(value.attempt) diff --git a/temporalio/worker/_activity.py b/temporalio/worker/_activity.py index 9a4b693f74..fadc1a42e9 100644 --- a/temporalio/worker/_activity.py +++ b/temporalio/worker/_activity.py @@ -710,7 +710,7 @@ 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.seq, start.local_activity_origin.activity_id, ) if start.HasField("local_activity_origin") diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index f8320a0dfe..7d662712f0 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -778,7 +778,7 @@ def describe(**fields: Any) -> tuple[str, Message]: "The Producer has no Workflow id", ), ( - append(_producer_of("local_activity", workflow_task_id=-1, attempt=None)), + append(_producer_of("workflow", workflow_task_id=-1, attempt=None)), invalid, "The Workflow Task id is -1, and it must be 0 or more", ), @@ -1074,7 +1074,7 @@ def _expected_producer(writer: _WriterInfo) -> temporalio.api.stream.v1.Producer kind.activity_id = writer.activity_id kind.attempt.attempt = writer.attempt if writer.kind == "local_activity": - kind.workflow_task_id, kind.activity_id = writer.event_id, "original" + kind.seq, kind.activity_id = writer.event_id, "original" task = kind.attempt.task task.started_event_id, task.attempt = writer.event_id + 3, writer.attempt + 1 task.started_time.CopyFrom(time) @@ -1089,7 +1089,6 @@ def _expected_producer(writer: _WriterInfo) -> temporalio.api.stream.v1.Producer ("kind", "event_id"), [ ("workflow", 7), - ("local_activity", 0), ("local_activity", 9), ("workflow_activity", 0), ("workflow_activity", 17), diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py index aef7d46611..406ecb1c86 100644 --- a/tests/nexus/test_streams_with_worker.py +++ b/tests/nexus/test_streams_with_worker.py @@ -1,11 +1,8 @@ """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 @@ -43,9 +40,7 @@ async def _write_local_attempt(stream_id: str, retry: bool) -> str: @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) + async def run(self, stream_id: str) -> None: original_id = await workflow.execute_local_activity( _write_local_attempt, args=[stream_id, True], @@ -63,10 +58,8 @@ async def run(self, stream_id: str, schedule_after_timer: bool) -> None: ) -@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) @@ -82,7 +75,7 @@ async def test_local_activity_producers_survive_timer_retries_and_worker_restart queue = first.task_queue handle = await client.start_workflow( _LocalProducerWorkflow.run, - args=[stream.ref.id, schedule_after_timer], + args=[stream.ref.id], id=queue, task_queue=queue, ) @@ -98,14 +91,12 @@ async def test_local_activity_producers_survive_timer_retries_and_worker_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 + assert len(_events(history, EventType.EVENT_TYPE_TIMER_STARTED)) == 1 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 + assert workers == ["before restart", "after restart"] 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] @@ -119,16 +110,17 @@ async def test_local_activity_producers_survive_timer_retries_and_worker_restart assert producer.attempt and producer.attempt.task producers.append( ( - producer.workflow_task_id, + producer.seq, producer.activity_id, producer.attempt.task.started_event_id, producer.attempt.attempt, ) ) + # The retry is a new schedule command, so the second Local Activity has seq 3. assert producers == [ - (origin, first_id, before, 1), - (origin, first_id, after, 2), - (before, first_id, after, 1), + (1, first_id, before, 1), + (1, first_id, after, 2), + (3, first_id, after, 1), ] From bf0b1944e7d4c9c498110d4cc0d13a60a1ee4238 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Thu, 3 Dec 2026 18:13:41 -0700 Subject: [PATCH 10/15] Pin the linear Core append history --- temporalio/bridge/sdk-core | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index 79710137b6..b003d54939 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit 79710137b692866234b7523e8424de25bf4777b6 +Subproject commit b003d54939f7b1971df9d65d346f3ba191659f72 From a060684c6eca9dad2cdd19841c2f58069ddc9e23 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Thu, 3 Dec 2026 18:26:29 -0700 Subject: [PATCH 11/15] Use the public Stream Store module in client calls --- temporalio/bridge/sdk-core | 2 +- temporalio/client/_client.py | 10 +- temporalio/client/_stream_store.py | 272 +------------- temporalio/contrib/streams/_producer.py | 5 +- temporalio/streams.py | 26 ++ temporalio/testing/_workflow.py | 9 +- tests/helpers/streams.py | 108 +++--- tests/nexus/test_streams.py | 462 +++++++++++++++--------- 8 files changed, 385 insertions(+), 509 deletions(-) diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index b003d54939..239b8b7d90 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit b003d54939f7b1971df9d65d346f3ba191659f72 +Subproject commit 239b8b7d90057d45b274fd9261c6d3b264cc3e61 diff --git a/temporalio/client/_client.py b/temporalio/client/_client.py index 01e793b249..05ccab86e3 100644 --- a/temporalio/client/_client.py +++ b/temporalio/client/_client.py @@ -29,6 +29,7 @@ import temporalio.converter import temporalio.runtime import temporalio.service +import temporalio.streams import temporalio.workflow from temporalio.nexus.system.stream_service import StreamIdConflictPolicy, StreamRef from temporalio.nexus.system.stream_service.client import ( @@ -101,7 +102,6 @@ ScheduleBackfill, ScheduleHandle, ) -from ._stream_store import StreamConfig from ._worker_versioning import ( BuildIdOp, TaskReachabilityType, @@ -183,7 +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, + stream_config: temporalio.streams.StreamConfig | None = None, ) -> Self: """Connect to a Temporal server. @@ -310,7 +310,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, + stream_config: temporalio.streams.StreamConfig | None = None, ): """Create a Temporal client from a service client. @@ -3183,7 +3183,7 @@ class ClientConnectConfig(TypedDict, total=False): grpc_compression: GrpcCompression payload_limits: PayloadLimitsConfig header_codec_behavior: HeaderCodecBehavior - stream_config: StreamConfig | None + stream_config: temporalio.streams.StreamConfig | None class ClientConfig(TypedDict, total=False): @@ -3198,4 +3198,4 @@ class ClientConfig(TypedDict, total=False): temporalio.common.QueryRejectCondition | None ] header_codec_behavior: Required[HeaderCodecBehavior] - stream_config: Required[StreamConfig | None] + stream_config: Required[temporalio.streams.StreamConfig | None] diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 5fcfcd71f5..1d9c8f808f 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -1,11 +1,8 @@ -"""Stream Stores and the Stream config of a client.""" +"""Client request validation and Store dispatch.""" from __future__ import annotations import asyncio -from abc import ABC, abstractmethod -from collections.abc import Callable, Sequence -from dataclasses import dataclass from datetime import timedelta from typing import Any @@ -18,6 +15,7 @@ # import it. A `from` import of a sibling here would lose the package's re-exports. import temporalio.client import temporalio.nexus.system._support +import temporalio.streams from temporalio.api.enums.v1 import StreamErrorReason, StreamIdConflictPolicy from temporalio.api.stream.v1 import ( LocalActivityProducer, @@ -50,268 +48,6 @@ A shorter timeout reserves a tenth of itself.""" -class StreamStore(ABC): - """Base class for a Store that keeps Stream Records. - - Methods use request and response messages from - :py:mod:`temporalio.api.streamservice.v1`. Requests contain a Stream id. - The SDK routes each ``StreamRef`` to its registered Store and sets the Store - name on refs returned by create. Stores don't read or set ``StreamRef.store``. - - Workflow execution and replay depend on these contracts. - - Retention: - - * Retention starts at create and restarts after an append that writes a batch. - Retries and reads don't extend it. The Store sets the retention period. - * An expired Stream has no Records and rejects calls with ``EXPIRED``. - * Streams have no stored end. Applications use their own terminal Record. - - Records and offsets: - - * Keep each body as received. The payload codec has already encoded it. - * Write each append batch atomically, with contiguous Records in request order. - * Record offsets are nonempty and sort bytewise in Record order. - * After a response returns an offset, no later write can insert a Record at - or below it. This also applies to concurrent writes. - * Keep Records unchanged until the Stream expires. - - Producers and attempts: - - * A Producer identifies a Workflow run, Activity, Local Activity or client. - Its kind and ids determine its identity. - * An attempt identifies a Producer's execution attempt, such as a Workflow - Task or Activity attempt. Every Record retains its Producer and attempt. - * Fencing is optional. A Store that fences rejects an earlier attempt once - a later attempt of that Producer has written to the Stream. - - Reject calls with :py:class:`temporalio.exceptions.StreamError` and its reason. - These docs omit the ``STREAM_ERROR_REASON_`` prefix from reason names. - Other exceptions become ``STORE_UNAVAILABLE`` errors. Workflow append and - read refusals record messages of at most 4 KiB in History. All Stream marker - data in an activation must fit within 1 MiB. Keep messages short to avoid - failing the Workflow Task with ``StreamMarkerTooLarge``. - - Calls can run concurrently on the event loop. Cancellation can follow a - timeout, eviction or Worker shutdown. A cancelled call may have taken effect. - The Store must remain usable, and overlapping retries must not duplicate a - batch. - - SDK Core validates and retries Workflow appends and reads during outages. - Other calls make one attempt. For those calls, the SDK checks each request - with the rules of SDK Core and the append limits from :py:class:`StreamConfig`, - but it doesn't check the answer. Stores must perform any other checks they - require. - - .. warning:: - This API is experimental and subject to change. - """ - - @abstractmethod - def name(self) -> str: - """Return the Store name registered in :py:class:`StreamConfig`. - - The name must remain stable. Separate instances of one Store class can - use different names. - """ - raise NotImplementedError - - @abstractmethod - async def create_stream( - self, request: CreateStreamRequest, *, request_id: str - ) -> CreateStreamResponse: - """Create a Stream, or reuse it if the conflict policy permits. - - Retries use the same ``request_id``. An empty id never identifies a retry. - The response contains only ``created``. - - For an existing Stream, check these conditions in order. - - 1. An expired Stream fails with ``EXPIRED``. - 2. A matching create ``request_id`` returns ``created=True``. - 3. ``USE_EXISTING`` returns ``created=False``. ``FAIL`` or an unset policy - fails with ``ALREADY_EXISTS``. - - Only a new Stream starts retention. Reusing a Stream doesn't extend it. - """ - raise NotImplementedError - - @abstractmethod - async def append_records( - self, request: AppendRecordsRequest, *, request_id: str - ) -> AppendRecordsResponse: - """Append one batch from one Producer. - - Retries of one append use the same ``request_id``. - Retain recent request ids for each Producer, including at least its last - batch. Matching Producer, attempt and ``request_id`` identify a resend. - An empty request id never identifies a resend. - - Check these conditions in order. - - 1. Missing or expired Streams fail with ``NOT_FOUND`` or ``EXPIRED``. - 2. A resend returns the original offsets without comparing or writing - Records. - 3. If fencing is enabled, an attempt older than the latest writer attempt - fails with ``FENCED``. - - Return the first and last Record offsets. Only a new batch extends - retention. A resend doesn't extend it. - """ - raise NotImplementedError - - @abstractmethod - async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: - """Read one page after ``after_offset``, in Stream order. - - * Apply ``max_records`` and ``max_bytes``. Zero uses the Store's default. - Include the first Record even if it exceeds ``max_bytes``. - * The next read starts after the last returned Record. An empty page - leaves ``after_offset`` unchanged. - * If no Records are available, wait until one arrives or ``wait`` expires. - An unset wait returns immediately. The SDK converts zero to an unset - wait. Returning empty pages before a requested wait expires can cause - callers to poll repeatedly. - * Accept any offset returned by a response. Reject ``after_offset`` with - ``OFFSET_TOO_HIGH`` only if it exceeds the end of the Stream. - """ - raise NotImplementedError - - @abstractmethod - async def describe_stream( - self, request: DescribeStreamRequest - ) -> DescribeStreamResponse: - """Return the newest Record's offset, or empty bytes for an empty Stream.""" - raise NotImplementedError - - -@dataclass(frozen=True) -class StreamSelectContext: - """Context passed to :py:attr:`StreamConfig.store_selector` calls. - - .. warning:: - This API is experimental and subject to change. - """ - - id: str - """Id of the call's Stream.""" - - namespace: str | None = None - """Namespace of the calling client or Worker.""" - - -@dataclass(frozen=True) -class StreamConfig: - """Stream Stores shared by a client and its Workers. - - Appends that exceed :py:attr:`max_record_bytes`, :py:attr:`max_batch_bytes` - or :py:attr:`max_batch_records` fail with ``STREAM_ERROR_REASON_TOO_LARGE`` - before reaching the Store. ``rpc_metadata`` has no effect on Store calls. - - Streams have no close. Retention starts at create and restarts after each - append that writes a batch. Applications use their own terminal Record. - - In client, Activity and Workflow code, ``read`` and ``read_pages`` continue - after empty pages. ``read_pages`` yields those pages. Callers must stop the - iterator, for example with ``break`` or a timeout. An unset ``wait`` makes the - first request immediate. Later requests wait up to one minute. An explicit - wait applies to every request. Zero disables waiting, so an idle Stream can - cause repeated empty reads. ``read_page`` has no default wait. After a page, - the ``read`` iterator's ``next_request`` includes the next request's wait. - - A positive ``rpc_timeout`` caps client and Activity waits below the timeout, - leaving time for the Store to answer. An Activity that heartbeats between - Records needs a wait below its heartbeat timeout, or a separate heartbeat task. - - .. warning:: - This API is experimental and subject to change. - """ - - stores: Sequence[StreamStore] - """Stores available for Stream calls. At least one is required, and each - needs a unique, nonempty :py:meth:`StreamStore.name`. - """ - - store_selector: Callable[[StreamSelectContext], StreamStore] | None = None - """Select the Store for a call whose ``StreamRef`` has no Store name. - - Return an instance from :py:attr:`stores`. A selector is required with - multiple Stores. Without one, the sole Store handles these calls. - """ - - max_record_bytes: int = 1536 * 1024 - """Maximum stored Record size for an append or a live Workflow read. - - Includes its Producer. Defaults to 1.5 MiB and must be at least one. - """ - - max_batch_bytes: int = 4 * 1024 * 1024 - """Maximum total stored size of the Records in one append. Defaults to 4 MiB - and must be at least one. - """ - - max_batch_records: int = 1000 - """Maximum number of Records in one append. Defaults to 1000 and must be at - least one. - """ - - def __post_init__(self) -> None: - """Validate the Stores and the limits. - - Raises :exc:`ValueError` for no Store, a limit below one, several Stores - without a :py:attr:`store_selector`, an empty Store name, or a duplicate - name. - """ - if not self.stores: - raise ValueError("StreamConfig.stores must contain at least one Store.") - for limit in ("max_record_bytes", "max_batch_bytes", "max_batch_records"): - if getattr(self, limit) < 1: - raise ValueError( - f"StreamConfig.{limit} must be greater than or equal to one." - ) - if len(self.stores) > 1 and self.store_selector is None: - raise ValueError( - "StreamConfig.store_selector must be specified if multiple Stores " - "are registered." - ) - names: set[str] = set() - for store in self.stores: - name = store.name() - if not name: - raise ValueError( - "StreamConfig.stores contains a Store with an empty name." - ) - if name in names: - raise ValueError( - f"StreamConfig.stores contains multiple Stores with name '{name}'. " - "Each Store must have a unique name." - ) - names.add(name) - - def _store(self, name: str) -> StreamStore: - for store in self.stores: - if store.name() == name: - return store - raise ValueError(f"No Stream Store found with name '{name}'") - - def _store_for(self, ref: 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 @@ -584,7 +320,7 @@ def _too_large(message: str) -> StreamError: async def _call_method( - store: StreamStore, + store: temporalio.streams.StreamStore, operation: str, request: google.protobuf.message.Message, request_id: str | None, @@ -615,7 +351,7 @@ async def _call_method( async def _call_store( # pyright: ignore[reportUnusedFunction] - store: StreamStore, + store: temporalio.streams.StreamStore, limits: tuple[int, int, int], codec: PayloadCodec | None, operation: str, diff --git a/temporalio/contrib/streams/_producer.py b/temporalio/contrib/streams/_producer.py index 6a13cd2429..4fd3aa4c9e 100644 --- a/temporalio/contrib/streams/_producer.py +++ b/temporalio/contrib/streams/_producer.py @@ -22,9 +22,8 @@ def current_producer() -> temporalio.nexus.system.stream_service.Producer: For an Activity of a Workflow, the Producer has the Activity id and the id of its ``ActivityTaskScheduled`` event, so a later Activity that reuses the - Activity id is a separate Producer. For a Local Activity, it has the command - sequence number and the Activity id of the first schedule. Retries keep both, - also when a timer delays the retry. + Activity id is a separate Producer. A Local Activity keeps the identity of its + original schedule across retries, including retries after a Workflow timer. Raises: RuntimeError: The caller isn't in an Activity, or Core didn't give a diff --git a/temporalio/streams.py b/temporalio/streams.py index 382b7523ab..a16be7ed3d 100644 --- a/temporalio/streams.py +++ b/temporalio/streams.py @@ -33,6 +33,7 @@ from collections.abc import Callable, Sequence from dataclasses import dataclass +import temporalio.api.sdk.v1 import temporalio.api.streamservice.v1 @@ -238,3 +239,28 @@ def __post_init__(self) -> None: "Each Store must have a unique name." ) names.add(name) + + def _store(self, name: str) -> StreamStore: + for store in self.stores: + if store.name() == name: + return store + raise ValueError(f"No Stream Store found with name '{name}'") + + def _store_for( + self, ref: temporalio.api.sdk.v1.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 diff --git a/temporalio/testing/_workflow.py b/temporalio/testing/_workflow.py index b8ae33cc25..432fdb3b63 100644 --- a/temporalio/testing/_workflow.py +++ b/temporalio/testing/_workflow.py @@ -25,6 +25,7 @@ import temporalio.exceptions import temporalio.runtime import temporalio.service +import temporalio.streams import temporalio.worker from temporalio.testing._timeskipping import ( SCHEDULE_FAST_FORWARD_POLL_TIMEOUT, @@ -104,7 +105,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, + stream_config: temporalio.streams.StreamConfig | None = None, ) -> WorkflowEnvironment: """Start a full Temporal server locally, downloading if necessary. @@ -222,7 +223,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, + stream_config: temporalio.streams.StreamConfig | None = None, ) -> WorkflowEnvironment: """Start a V1 time skipping workflow environment. @@ -749,7 +750,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, + stream_config: temporalio.streams.StreamConfig | None = None, ) -> tuple[ temporalio.bridge.testing.EphemeralServer, temporalio.client.Client, @@ -888,7 +889,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, + stream_config: temporalio.streams.StreamConfig | None, ) -> _V1WorkflowEnvironment: runtime = runtime or temporalio.runtime.Runtime.default() download_ttl_ms = None diff --git a/tests/helpers/streams.py b/tests/helpers/streams.py index f8c78cdb18..918fc16b2b 100644 --- a/tests/helpers/streams.py +++ b/tests/helpers/streams.py @@ -9,37 +9,21 @@ 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 +import temporalio.api.common.v1 +import temporalio.api.streamservice.v1 +import temporalio.client +import temporalio.converter +import temporalio.streams +import temporalio.testing _T = TypeVar("_T") -CodecCall = tuple[str, SerializationContext | None, int] +CodecCall = tuple[str, temporalio.converter.SerializationContext | None, int] -class ContextCodec(PayloadCodec, WithSerializationContext): +class ContextCodec( + temporalio.converter.PayloadCodec, temporalio.converter.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. @@ -48,35 +32,46 @@ class ContextCodec(PayloadCodec, WithSerializationContext): def __init__( self, calls: list[CodecCall] | None = None, - context: SerializationContext | None = None, + context: temporalio.converter.SerializationContext | None = None, ) -> None: self.calls: list[CodecCall] = [] if calls is None else calls self._context = context - def with_context(self, context: SerializationContext) -> "ContextCodec": + def with_context( + self, context: temporalio.converter.SerializationContext + ) -> "ContextCodec": return ContextCodec(self.calls, context) - async def encode(self, payloads: Sequence[Payload]) -> list[Payload]: + async def encode( + self, payloads: Sequence[temporalio.api.common.v1.Payload] + ) -> list[temporalio.api.common.v1.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]: + async def decode( + self, payloads: Sequence[temporalio.api.common.v1.Payload] + ) -> list[temporalio.api.common.v1.Payload]: self.calls.append(("decode", self._context, len(payloads))) - decoded: list[Payload] = [] + decoded: list[temporalio.api.common.v1.Payload] = [] for payload in payloads: if payload.metadata.get("encoding") == b"test/wrapped": - key = wrapped(Payload(), self._context).metadata["context"] + key = wrapped( + temporalio.api.common.v1.Payload(), self._context + ).metadata["context"] assert payload.metadata["context"] == key, ( f"{payload} isn't for {key!r}" ) - payload = Payload.FromString(payload.data) + payload = temporalio.api.common.v1.Payload.FromString(payload.data) decoded.append(payload) return decoded -def wrapped(payload: Payload, context: SerializationContext | None = None) -> Payload: +def wrapped( + payload: temporalio.api.common.v1.Payload, + context: temporalio.converter.SerializationContext | None = None, +) -> temporalio.api.common.v1.Payload: """Return ``payload`` as a :py:class:`ContextCodec` with ``context`` encodes it.""" - return Payload( + return temporalio.api.common.v1.Payload( metadata={ "encoding": b"test/wrapped", "context": type(context).__name__.encode(), @@ -139,13 +134,13 @@ async def __call__(self, call: Callable[[], Awaitable[Any]]) -> Any: return await call() -class FaultStore(StreamStore): +class FaultStore(temporalio.streams.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.memory = temporalio.testing.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.""" @@ -162,21 +157,29 @@ def name(self) -> str: return self.memory.name() async def create_stream( - self, request: CreateStreamRequest, *, request_id: str - ) -> CreateStreamResponse: + self, + request: temporalio.api.streamservice.v1.CreateStreamRequest, + *, + request_id: str, + ) -> temporalio.api.streamservice.v1.CreateStreamResponse: return await self._call("create_stream", request, request_id) async def append_records( - self, request: AppendRecordsRequest, *, request_id: str - ) -> AppendRecordsResponse: + self, + request: temporalio.api.streamservice.v1.AppendRecordsRequest, + *, + request_id: str, + ) -> temporalio.api.streamservice.v1.AppendRecordsResponse: return await self._call("append_records", request, request_id) - async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: + async def read_records( + self, request: temporalio.api.streamservice.v1.ReadRecordsRequest + ) -> temporalio.api.streamservice.v1.ReadRecordsResponse: return await self._call("read_records", request) async def describe_stream( - self, request: DescribeStreamRequest - ) -> DescribeStreamResponse: + self, request: temporalio.api.streamservice.v1.DescribeStreamRequest + ) -> temporalio.api.streamservice.v1.DescribeStreamResponse: return await self._call("describe_stream", request) async def _call( @@ -195,22 +198,25 @@ async def call() -> Any: def stream_client( - client: Client, - *stores: StreamStore, - store_selector: Callable[[StreamSelectContext], StreamStore] | None = None, - data_converter: DataConverter | None = None, + client: temporalio.client.Client, + *stores: temporalio.streams.StreamStore, + store_selector: Callable[ + [temporalio.streams.StreamSelectContext], temporalio.streams.StreamStore + ] + | None = None, + data_converter: temporalio.converter.DataConverter | None = None, **limits: int, -) -> Client: +) -> temporalio.client.Client: """Return a client on the connection of ``client`` with the given Stream Stores and limits. """ config = client.config() - config["stream_config"] = StreamConfig( + config["stream_config"] = temporalio.streams.StreamConfig( stores, store_selector=store_selector, **limits ) if data_converter: config["data_converter"] = data_converter - return Client(**config) + return temporalio.client.Client(**config) class _JumpingSelector(selectors.DefaultSelector): diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index 7d662712f0..89173eced5 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -13,48 +13,24 @@ from google.protobuf.message import Message from google.protobuf.timestamp_pb2 import Timestamp +import temporalio.activity +import temporalio.api.common.v1 +import temporalio.api.enums.v1 import temporalio.api.sdk.v1 as sdk +import temporalio.api.stream.v1 import temporalio.api.stream.v1 as stream_api import temporalio.api.streamservice.v1 as proto import temporalio.client +import temporalio.client._stream_store +import temporalio.contrib.streams 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 -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.nexus.system.stream_service import ( - ReadRecordsRequest, - ReadRecordsResponse, - StreamRecord, - StreamRef, -) -from temporalio.nexus.system.stream_service import ( - StreamIdConflictPolicy as ConflictPolicy, -) -from temporalio.nexus.system.stream_service import models as stream_models -from temporalio.nexus.system.stream_service.client import Stream as ClientStream -from temporalio.service import ServiceClient -from temporalio.testing import ActivityEnvironment, MemoryStreamStore +import temporalio.exceptions +import temporalio.nexus.system._support +import temporalio.nexus.system.stream_service +import temporalio.nexus.system.stream_service.client +import temporalio.service +import temporalio.streams +import temporalio.testing from temporalio.types import ReturnType from tests.helpers.streams import ( ContextCodec, @@ -66,8 +42,12 @@ run_with_virtual_clock, ) -_UNAVAILABLE = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE -_INVALID_ARGUMENT = StreamErrorReason.STREAM_ERROR_REASON_INVALID_ARGUMENT +_UNAVAILABLE = ( + temporalio.api.enums.v1.StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE +) +_INVALID_ARGUMENT = ( + temporalio.api.enums.v1.StreamErrorReason.STREAM_ERROR_REASON_INVALID_ARGUMENT +) class _Interceptor(temporalio.client.Interceptor): @@ -105,8 +85,8 @@ def __init__( async def _record( self, input: temporalio.client.StartNexusOperationInput[Any, ReturnType], - call: Awaitable[NexusOperationHandle[ReturnType]], - ) -> NexusOperationHandle[ReturnType]: + call: Awaitable[temporalio.client.NexusOperationHandle[ReturnType]], + ) -> temporalio.client.NexusOperationHandle[ReturnType]: ref = getattr(input.arg, "stream_ref", None) or input.arg.ref before = ref.store try: @@ -117,41 +97,50 @@ async def _record( async def start_create_stream( self, input: temporalio.client.StartNexusOperationInput[ - stream_models.CreateStreamRequest[Any], - stream_models.CreateStreamResult[Any], + temporalio.nexus.system.stream_service.models.CreateStreamRequest[Any], + temporalio.nexus.system.stream_service.models.CreateStreamResult[Any], ], - ) -> NexusOperationHandle[stream_models.CreateStreamResult[Any]]: + ) -> temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.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 + temporalio.nexus.system.stream_service.models.AppendRecordsRequest[Any], + temporalio.nexus.system.stream_service.models.AppendRecordsResponse, ], - ) -> NexusOperationHandle[stream_models.AppendRecordsResponse]: + ) -> temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.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], + temporalio.nexus.system.stream_service.models.ReadRecordsRequest[Any], + temporalio.nexus.system.stream_service.models.ReadRecordsResponse[Any], ], - ) -> NexusOperationHandle[stream_models.ReadRecordsResponse[Any]]: + ) -> temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.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, + temporalio.nexus.system.stream_service.models.DescribeStreamRequest[Any], + temporalio.nexus.system.stream_service.models.DescribeStreamResponse, ], - ) -> NexusOperationHandle[stream_models.DescribeStreamResponse]: + ) -> temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.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]: + ) -> temporalio.client.NexusOperationHandle[Any]: raise AssertionError( "Stream calls must bypass generic Nexus start interception" ) @@ -181,34 +170,36 @@ def _producer_proto(producer: Any) -> temporalio.api.stream.v1.Producer: async def test_a_client_call_reaches_the_selected_store( operation: str, routing: str, in_activity: bool ) -> None: - service_client = Mock(spec=ServiceClient) + service_client = Mock(spec=temporalio.service.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] = [] + selects: list[temporalio.streams.StreamSelectContext] = [] - def selector(context: StreamSelectContext) -> FaultStore: + def selector(context: temporalio.streams.StreamSelectContext) -> FaultStore: selects.append(context) return selected ref_store = {"explicit": "a", "unknown": "unknown"}.get(routing) intercepted: list[tuple[str | None, str | None]] = [] - client = Client( + client = temporalio.client.Client( service_client, interceptors=[_Interceptor(lambda next: _RecordingOutbound(next, intercepted))], - stream_config=StreamConfig( + stream_config=temporalio.streams.StreamConfig( stores, store_selector=None if routing == "only" else selector ), ) - activity = ActivityEnvironment() + activity = temporalio.testing.ActivityEnvironment() activity.info = dataclasses.replace( activity.info, activity_id="activity", activity_run_id="run" ) producer = ( - _producer_proto(activity.run(current_producer)) + _producer_proto(activity.run(temporalio.contrib.streams.current_producer)) if in_activity - else Producer( - client=ClientProducer(namespace="default", id=client._stream_producer_id) + else temporalio.api.stream.v1.Producer( + client=temporalio.api.stream.v1.ClientProducer( + namespace="default", id=client._stream_producer_id + ) ) ) for store in stores: @@ -216,19 +207,23 @@ def selector(context: StreamSelectContext) -> FaultStore: 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)) + stream = client.get_stream( + temporalio.nexus.system.stream_service.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, + id_conflict_policy=temporalio.api.enums.v1.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)], + records=[ + temporalio.api.stream.v1.AppendRecord(body=payload(i)) for i in (3, 5) + ], ) elif operation == "read": expected = proto.ReadRecordsRequest( @@ -244,7 +239,7 @@ async def call() -> Any: id="s", store=ref_store, body_type=int, - id_conflict_policy=ConflictPolicy.StreamIdConflictPolicyUseExisting, + id_conflict_policy=temporalio.nexus.system.stream_service.StreamIdConflictPolicy.StreamIdConflictPolicyUseExisting, ) if operation == "append": return await stream.append(3, 5) @@ -264,7 +259,7 @@ async def call() -> Any: result = await (activity.run(call) if in_activity else call()) if operation == "create": assert result.created is False - assert result.ref == StreamRef( + assert result.ref == temporalio.nexus.system.stream_service.StreamRef( id="s", store="b" if routing == "selector" else "a" ) chosen, other = (b, a) if routing == "selector" else (a, b) @@ -277,16 +272,16 @@ async def call() -> Any: assert ids == [None, None] assert intercepted == [(ref_store, ref_store)] * 2 assert selects == ( - [StreamSelectContext(id="s", namespace="default")] * 2 + [temporalio.streams.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) + service_client = Mock(spec=temporalio.service.ServiceClient) with pytest.raises(ValueError): - await Client(service_client).create_stream(id="s") + await temporalio.client.Client(service_client).create_stream(id="s") assert not service_client.mock_calls @@ -299,10 +294,12 @@ class Edit(temporalio.client.OutboundInterceptor): async def start_create_stream( self, input: temporalio.client.StartNexusOperationInput[ - stream_models.CreateStreamRequest[Any], - stream_models.CreateStreamResult[Any], + temporalio.nexus.system.stream_service.models.CreateStreamRequest[Any], + temporalio.nexus.system.stream_service.models.CreateStreamResult[Any], ], - ) -> NexusOperationHandle[stream_models.CreateStreamResult[Any]]: + ) -> temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.models.CreateStreamResult[Any] + ]: received.append( ( str(input._stream_request_id), @@ -327,9 +324,9 @@ async def start_create_stream( return handle store = FaultStore() - client = Client( - Mock(spec=ServiceClient), - stream_config=StreamConfig([store]), + client = temporalio.client.Client( + Mock(spec=temporalio.service.ServiceClient), + stream_config=temporalio.streams.StreamConfig([store]), interceptors=[_Interceptor(Edit)], ) stream = await client.create_stream( @@ -344,7 +341,7 @@ async def start_create_stream( assert received == [ ( store.calls[0][1], - stream_models.CreateStreamResult[int], + temporalio.nexus.system.stream_service.models.CreateStreamResult[int], metadata, timeout, ) @@ -356,21 +353,31 @@ class Cached(temporalio.client.OutboundInterceptor): async def start_describe_stream( self, input: temporalio.client.StartNexusOperationInput[ - stream_models.DescribeStreamRequest[Any], - stream_models.DescribeStreamResponse, + temporalio.nexus.system.stream_service.models.DescribeStreamRequest[ + Any + ], + temporalio.nexus.system.stream_service.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" + ) -> temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.models.DescribeStreamResponse + ]: + handle: temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.models.DescribeStreamResponse + ] = temporalio.client.NexusOperationHandle(Mock(), input.id) + handle._known_outcome = ( + temporalio.nexus.system.stream_service.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() + service_client = Mock(spec=temporalio.service.ServiceClient) + client = temporalio.client.Client( + service_client, interceptors=[_Interceptor(Cached)] + ) + response = await client.get_stream( + temporalio.nexus.system.stream_service.StreamRef[int](id="s") + ).describe() assert response.last_offset == b"cached" assert not service_client.mock_calls @@ -378,8 +385,8 @@ async def start_describe_stream( async def test_stream_hooks_preserve_the_nexus_input_envelope() -> None: seen: list[ temporalio.client.StartNexusOperationInput[ - stream_models.CreateStreamRequest[Any], - stream_models.CreateStreamResult[Any], + temporalio.nexus.system.stream_service.models.CreateStreamRequest[Any], + temporalio.nexus.system.stream_service.models.CreateStreamResult[Any], ] ] = [] @@ -387,22 +394,24 @@ class Inspect(temporalio.client.OutboundInterceptor): async def start_create_stream( self, input: temporalio.client.StartNexusOperationInput[ - stream_models.CreateStreamRequest[Any], - stream_models.CreateStreamResult[Any], + temporalio.nexus.system.stream_service.models.CreateStreamRequest[Any], + temporalio.nexus.system.stream_service.models.CreateStreamResult[Any], ], - ) -> NexusOperationHandle[stream_models.CreateStreamResult[Any]]: + ) -> temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.models.CreateStreamResult[Any] + ]: seen.append(input) return await super().start_create_stream(input) store = FaultStore() - service_client = Mock(spec=ServiceClient) - client = Client( + service_client = Mock(spec=temporalio.service.ServiceClient) + client = temporalio.client.Client( service_client, - stream_config=StreamConfig([store]), + stream_config=temporalio.streams.StreamConfig([store]), interceptors=[_Interceptor(Inspect), _Interceptor(Inspect)], ) - request = stream_models.CreateStreamRequest( - stream_ref=StreamRef[int](id="envelope") + request = temporalio.nexus.system.stream_service.models.CreateStreamRequest( + stream_ref=temporalio.nexus.system.stream_service.StreamRef[int](id="envelope") ) nexus: temporalio.client.NexusClient[Any] = client.create_nexus_client( "temporal.api.streamservice.v1.StreamService", @@ -413,7 +422,9 @@ async def start_create_stream( "CreateStream", request, id="operation-id", - result_type=stream_models.CreateStreamResult[int], + result_type=temporalio.nexus.system.stream_service.models.CreateStreamResult[ + int + ], schedule_to_close_timeout=timedelta(seconds=10), schedule_to_start_timeout=timedelta(seconds=8), start_to_close_timeout=timedelta(seconds=6), @@ -427,7 +438,10 @@ async def start_create_stream( assert first is second assert first.arg is request assert first.id == "operation-id" - assert first.result_type == stream_models.CreateStreamResult[int] + assert ( + first.result_type + == temporalio.nexus.system.stream_service.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) @@ -442,8 +456,8 @@ async def start_create_stream( async def test_unknown_stream_operation_bypasses_generic_nexus() -> None: - service_client = Mock(spec=ServiceClient) - client = Client(service_client) + service_client = Mock(spec=temporalio.service.ServiceClient) + client = temporalio.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, @@ -454,16 +468,27 @@ async def test_unknown_stream_operation_bypasses_generic_nexus() -> None: def test_the_client_gives_the_handle_of_a_ref_with_its_body_type() -> None: - client = Client( - Mock(spec=ServiceClient), stream_config=StreamConfig([FaultStore()]) + client = temporalio.client.Client( + Mock(spec=temporalio.service.ServiceClient), + stream_config=temporalio.streams.StreamConfig([FaultStore()]), + ) + typed = client.get_stream( + temporalio.nexus.system.stream_service.StreamRef[int](id="s", store="a"), + created=True, + ) + by_type = client.get_stream( + temporalio.nexus.system.stream_service.StreamRef(id="s"), body_type=str + ) + any_body = client.get_stream( + temporalio.nexus.system.stream_service.StreamRef[object](id="s"), + body_type=bytes, + ) + assert_type(typed, temporalio.nexus.system.stream_service.client.Stream[int]) + assert_type(by_type, temporalio.nexus.system.stream_service.client.Stream[str]) + assert_type(any_body, temporalio.nexus.system.stream_service.client.Stream[bytes]) + assert typed.ref == temporalio.nexus.system.stream_service.StreamRef( + id="s", store="a" ) - 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), @@ -473,7 +498,7 @@ def test_the_client_gives_the_handle_of_a_ref_with_its_body_type() -> None: 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") + mismatched: Any = temporalio.nexus.system.stream_service.StreamRef[int](id="s") with pytest.raises(TypeError, match="must match the typed ref"): client.get_stream(mismatched, body_type=str) @@ -481,9 +506,11 @@ def test_the_client_gives_the_handle_of_a_ref_with_its_body_type() -> None: 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), + client = temporalio.client.Client( + Mock(spec=temporalio.service.ServiceClient), + stream_config=temporalio.streams.StreamConfig( + [a, b], store_selector=lambda _: selected + ), ) stream = await client.create_stream(id="s", body_type=int) selected = b @@ -503,7 +530,7 @@ class Retry(temporalio.client.OutboundInterceptor): async def _retry(self, call: Callable[[], Awaitable[ReturnType]]) -> ReturnType: try: return await call() - except StreamError as err: + except temporalio.exceptions.StreamError as err: if err.reason != _UNAVAILABLE: raise return await call() @@ -511,10 +538,12 @@ async def _retry(self, call: Callable[[], Awaitable[ReturnType]]) -> ReturnType: async def start_create_stream( self, input: temporalio.client.StartNexusOperationInput[ - stream_models.CreateStreamRequest[Any], - stream_models.CreateStreamResult[Any], + temporalio.nexus.system.stream_service.models.CreateStreamRequest[Any], + temporalio.nexus.system.stream_service.models.CreateStreamResult[Any], ], - ) -> NexusOperationHandle[stream_models.CreateStreamResult[Any]]: + ) -> temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.models.CreateStreamResult[Any] + ]: return await self._retry( lambda: self.next.start_create_stream(dataclasses.replace(input)) ) @@ -522,10 +551,12 @@ async def start_create_stream( async def start_append_records( self, input: temporalio.client.StartNexusOperationInput[ - stream_models.AppendRecordsRequest[Any], - stream_models.AppendRecordsResponse, + temporalio.nexus.system.stream_service.models.AppendRecordsRequest[Any], + temporalio.nexus.system.stream_service.models.AppendRecordsResponse, ], - ) -> NexusOperationHandle[stream_models.AppendRecordsResponse]: + ) -> temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.models.AppendRecordsResponse + ]: return await self._retry( lambda: self.next.start_append_records(dataclasses.replace(input)) ) @@ -533,9 +564,9 @@ async def start_append_records( 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]), + client = temporalio.client.Client( + Mock(spec=temporalio.service.ServiceClient), + stream_config=temporalio.streams.StreamConfig([store]), interceptors=[_Interceptor(Retry)], ) stream = await client.create_stream(id="s", body_type=int) @@ -551,9 +582,14 @@ async def start_append_records( 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() + client = temporalio.client.Client( + Mock(spec=temporalio.service.ServiceClient), + stream_config=temporalio.streams.StreamConfig([store]), + ) + with pytest.raises(temporalio.exceptions.StreamError) as raised: + await client.get_stream( + temporalio.nexus.system.stream_service.StreamRef[int](id="s") + ).append() assert raised.value.reason == _INVALID_ARGUMENT assert not store.calls @@ -590,9 +626,9 @@ async def test_an_empty_client_append_does_not_reach_the_store() -> None: """The fields of a Producer of each kind that a Store takes.""" -def _producer_of(kind: str, **fields: Any) -> Producer: +def _producer_of(kind: str, **fields: Any) -> temporalio.api.stream.v1.Producer: arguments: dict[str, Any] = {kind: {**_PRODUCER_KINDS[kind], **fields}} - return Producer(**arguments) + return temporalio.api.stream.v1.Producer(**arguments) async def test_a_bad_request_fails_before_the_store() -> None: @@ -600,10 +636,10 @@ async def test_a_bad_request_fails_before_the_store() -> None: limits = (1536 * 1024, 4 * 1024 * 1024, 2) invalid, too_large = ( _INVALID_ARGUMENT, - StreamErrorReason.STREAM_ERROR_REASON_TOO_LARGE, + temporalio.api.enums.v1.StreamErrorReason.STREAM_ERROR_REASON_TOO_LARGE, ) ref = sdk.StreamRef(id="s") - body = Payload(data=b"x") + body = temporalio.api.common.v1.Payload(data=b"x") client = _producer_of("client") def create(**fields: Any) -> tuple[str, Message]: @@ -611,9 +647,13 @@ def create(**fields: Any) -> tuple[str, Message]: return "CreateStream", sdk.CreateStreamRequest(**fields) def append( - producer: Producer | None = client, **fields: Any + producer: temporalio.api.stream.v1.Producer | None = client, **fields: Any ) -> tuple[str, Message]: - fields = {"ref": ref, "records": [AppendRecord(body=body)] * 2, **fields} + fields = { + "ref": ref, + "records": [temporalio.api.stream.v1.AppendRecord(body=body)] * 2, + **fields, + } return "AppendRecords", sdk.AppendRecordsRequest(producer=producer, **fields) def read(**fields: Any) -> tuple[str, Message]: @@ -630,13 +670,23 @@ def describe(**fields: Any) -> tuple[str, Message]: # 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]] = [ + cases: list[ + tuple[ + tuple[str, Message], + temporalio.api.enums.v1.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(temporalio.api.stream.v1.Producer()), + invalid, + "The Producer has no kind", + ), ( append(_producer_of("workflow", attempt=None)), invalid, @@ -736,12 +786,17 @@ def describe(**fields: Any) -> tuple[str, Message]: ), (append(records=[]), invalid, "The batch has no Record"), ( - append(records=[AppendRecord(body=body), AppendRecord()]), + append( + records=[ + temporalio.api.stream.v1.AppendRecord(body=body), + temporalio.api.stream.v1.AppendRecord(), + ] + ), invalid, "Record 1 of the batch has no body", ), ( - append(records=[AppendRecord(body=body)] * 3), + append(records=[temporalio.api.stream.v1.AppendRecord(body=body)] * 3), too_large, "The batch has 3 Records, more than 2", ), @@ -770,7 +825,11 @@ def describe(**fields: Any) -> tuple[str, Message]: (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(temporalio.api.stream.v1.Producer(), ref=sdk.StreamRef()), + invalid, + no_id, + ), (append(None, records=[]), invalid, "The request has no Producer"), ( append(_producer_of("workflow", workflow_id="", run_id="")), @@ -808,12 +867,19 @@ def describe(**fields: Any) -> tuple[str, Message]: "The attempt scheduled time is before the Unix epoch", ), ( - append(records=[AppendRecord()] * 3), + append(records=[temporalio.api.stream.v1.AppendRecord()] * 3), invalid, "Record 0 of the batch has no body", ), ( - append(records=[AppendRecord(body=Payload(data=b"x" * limits[0]))] * 3), + append( + records=[ + temporalio.api.stream.v1.AppendRecord( + body=temporalio.api.common.v1.Payload(data=b"x" * limits[0]) + ) + ] + * 3 + ), too_large, "The batch has 3 Records, more than 2", ), @@ -853,8 +919,10 @@ def describe(**fields: Any) -> tuple[str, Message]: 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) + with pytest.raises(temporalio.exceptions.StreamError) as raised: + await temporalio.client._stream_store._call_store( + store, limits, codec, operation, request, None + ) assert (raised.value.reason, raised.value.message) == (reason, message) assert not store.calls @@ -886,21 +954,27 @@ def describe(**fields: Any) -> tuple[str, Message]: describe(ref=longest_id), ] for _, request in taken: - _check_request(_store_request(request), limits) + temporalio.client._stream_store._check_request( + temporalio.client._stream_store._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} + kinds = temporalio.api.stream.v1.Producer.DESCRIPTOR.oneofs_by_name["kind"].fields + assert set(temporalio.client._stream_store._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 + assert [ + name for name, _ in temporalio.client._stream_store._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 + too_large = temporalio.api.enums.v1.StreamErrorReason.STREAM_ERROR_REASON_TOO_LARGE rng = random.Random(0) for case in range(200): kind = rng.choice(list(_PRODUCER_KINDS)) @@ -912,7 +986,7 @@ def test_the_append_check_measures_each_record_in_its_stored_size() -> None: } producer = _producer_of(kind, **ids) bodies = [ - Payload( + temporalio.api.common.v1.Payload( metadata=rng.choice([{}, {"encoding": b"json/plain"}]), data=b"x" * rng.choice([0, 1, 127, 128, 300, 20_000]), ) @@ -921,7 +995,9 @@ def test_the_append_check_measures_each_record_in_its_stored_size() -> None: request = proto.AppendRecordsRequest( stream_id="s", producer=producer, - records=[AppendRecord(body=body) for body in bodies], + records=[ + temporalio.api.stream.v1.AppendRecord(body=body) for body in bodies + ], ) sizes = [ stream_api.StreamRecord(producer=producer, body=body).ByteSize() @@ -929,7 +1005,9 @@ def test_the_append_check_measures_each_record_in_its_stored_size() -> None: ] largest, total, count = max(sizes), sum(sizes), len(sizes) with failure_note(f"case {case}"): - _check_request(request, (largest, total, count)) + temporalio.client._stream_store._check_request( + request, (largest, total, count) + ) over_record = ( (largest - 1, total, count), f"Record {sizes.index(largest)} of the batch has {largest} bytes, " @@ -942,8 +1020,8 @@ def test_the_append_check_measures_each_record_in_its_stored_size() -> None: # 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) + with pytest.raises(temporalio.exceptions.StreamError) as raised: + temporalio.client._stream_store._check_request(request, limits) assert (raised.value.reason, raised.value.message) == ( too_large, message, @@ -960,20 +1038,27 @@ def __init__(self, next: temporalio.client.OutboundInterceptor) -> None: async def start_read_records( self, input: temporalio.client.StartNexusOperationInput[ - ReadRecordsRequest[Any], ReadRecordsResponse[Any] + temporalio.nexus.system.stream_service.ReadRecordsRequest[Any], + temporalio.nexus.system.stream_service.ReadRecordsResponse[Any], ], - ) -> NexusOperationHandle[ReadRecordsResponse[Any]]: + ) -> temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.ReadRecordsResponse[Any] + ]: request = input.arg self.starts.append(int.from_bytes(request.after_offset or b"", "big")) self.waits.append(request.wait) records = [ - StreamRecord(body=at, offset=at.to_bytes(8, "big")) + temporalio.nexus.system.stream_service.StreamRecord( + body=at, offset=at.to_bytes(8, "big") + ) for at in next(self.pages) ] - page = ReadRecordsResponse(records=records) - handle: NexusOperationHandle[ReadRecordsResponse[Any]] = NexusOperationHandle( - Mock(), input.id + page = temporalio.nexus.system.stream_service.ReadRecordsResponse( + records=records ) + handle: temporalio.client.NexusOperationHandle[ + temporalio.nexus.system.stream_service.ReadRecordsResponse[Any] + ] = temporalio.client.NexusOperationHandle(Mock(), input.id) handle._known_outcome = page return handle @@ -988,11 +1073,16 @@ 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")) + client = temporalio.client.Client( + Mock(spec=temporalio.service.ServiceClient), + interceptors=[_Interceptor(outbound)], + ) + stream = client.get_stream( + temporalio.nexus.system.stream_service.StreamRef[int](id="s") + ) [reads] = fake got: list[int] = [] - later = _support.DEFAULT_READ_WAIT if wait is None else wait + later = temporalio.nexus.system._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): @@ -1132,16 +1222,22 @@ def test_a_workflow_producer_preserves_the_task_id_and_attempt() -> None: task.namespace, task.workflow_id, task.run_id = "ns", "workflow", "run" task.workflow_task_id = 11 task.attempt.started_event_id, task.attempt.attempt = 37, 2 - assert _producer_proto(as_producer(proto)) == proto + assert _producer_proto(temporalio.contrib.streams.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)] + service_client = Mock(spec=temporalio.service.ServiceClient) + config = temporalio.streams.StreamConfig(stores=[FaultStore()]) + clients = [ + temporalio.client.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) + temporalio.nexus.system._support.default_producer( + client.get_stream( + temporalio.nexus.system.stream_service.StreamRef(id=id) + )._nexus_client + ) ) for client, id in ((clients[0], "a"), (clients[0], "b"), (clients[1], "a")) ] @@ -1154,9 +1250,14 @@ 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: + client = temporalio.client.Client( + Mock(spec=temporalio.service.ServiceClient), + stream_config=temporalio.streams.StreamConfig([store]), + ) + stream = client.get_stream( + temporalio.nexus.system.stream_service.StreamRef[str](id="s") + ) + with pytest.raises(temporalio.exceptions.StreamError) as timed_out: await stream.describe(rpc_timeout=timedelta(seconds=5)) assert timed_out.value.reason == _UNAVAILABLE assert loop.time() == 5 @@ -1167,7 +1268,7 @@ async def script() -> None: def test_a_client_iterator_on_an_idle_stream_waits_between_reads() -> None: - class ReadLog(MemoryStreamStore): + class ReadLog(temporalio.testing.MemoryStreamStore): def __init__(self) -> None: super().__init__() self.reads: list[proto.ReadRecordsRequest] = [] @@ -1187,9 +1288,12 @@ def waits(store: ReadLog) -> list[timedelta | None]: async def script() -> None: loop = asyncio.get_running_loop() store = ReadLog() - client = Client(Mock(spec=ServiceClient), stream_config=StreamConfig([store])) + client = temporalio.client.Client( + Mock(spec=temporalio.service.ServiceClient), + stream_config=temporalio.streams.StreamConfig([store]), + ) stream = await client.create_stream(id="s", body_type=int) - minute = _support.DEFAULT_READ_WAIT + minute = temporalio.nexus.system._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 @@ -1243,11 +1347,15 @@ async def append_later() -> None: 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( + request = temporalio.nexus.system.stream_service.ReadRecordsRequest( + ref=temporalio.nexus.system.stream_service.StreamRef[int](id="s"), + after_offset=b"a", + ) + page = temporalio.nexus.system.stream_service.ReadRecordsResponse( records=[ - StreamRecord(body=i, offset=offset) for i, offset in enumerate(offsets) + temporalio.nexus.system.stream_service.StreamRecord(body=i, offset=offset) + for i, offset in enumerate(offsets) ], ) - next_request = _support.next_read_request(request, page) + next_request = temporalio.nexus.system._support.next_read_request(request, page) assert next_request is not None and next_request.after_offset == expected From f208279152ab2ddbd3e94833e82e310c7e3ae4fa Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Thu, 3 Dec 2026 20:54:47 -0700 Subject: [PATCH 12/15] Update the Stream Core pin after the API rebase --- changelog/fixed/unchanced-alfredia.md | 1 + temporalio/api/enums/v1/stream_pb2.pyi | 8 ++--- temporalio/api/stream/v1/message_pb2.py | 32 +++++++++---------- temporalio/api/stream/v1/message_pb2.pyi | 7 ++-- .../streamservice/v1/request_response_pb2.pyi | 6 ++-- temporalio/bridge/sdk-core | 2 +- 6 files changed, 29 insertions(+), 27 deletions(-) create mode 100644 changelog/fixed/unchanced-alfredia.md diff --git a/changelog/fixed/unchanced-alfredia.md b/changelog/fixed/unchanced-alfredia.md new file mode 100644 index 0000000000..410ceb31f4 --- /dev/null +++ b/changelog/fixed/unchanced-alfredia.md @@ -0,0 +1 @@ +Core skips Local Activities when replay ends in an unfinished Workflow Task. Local Activity heartbeats preserve the Workflow versioning behavior. diff --git a/temporalio/api/enums/v1/stream_pb2.pyi b/temporalio/api/enums/v1/stream_pb2.pyi index 4c0f9134b9..c7d5df2d23 100644 --- a/temporalio/api/enums/v1/stream_pb2.pyi +++ b/temporalio/api/enums/v1/stream_pb2.pyi @@ -32,7 +32,7 @@ class _StreamIdConflictPolicyEnumTypeWrapper( STREAM_ID_CONFLICT_POLICY_FAIL: _StreamIdConflictPolicy.ValueType # 1 """The create fails with `ALREADY_EXISTS`.""" STREAM_ID_CONFLICT_POLICY_USE_EXISTING: _StreamIdConflictPolicy.ValueType # 2 - """The create returns the existing Stream without changing its expiry.""" + """The create returns `created` false for the existing Stream.""" class StreamIdConflictPolicy( _StreamIdConflictPolicy, metaclass=_StreamIdConflictPolicyEnumTypeWrapper @@ -45,7 +45,7 @@ STREAM_ID_CONFLICT_POLICY_UNSPECIFIED: StreamIdConflictPolicy.ValueType # 0 STREAM_ID_CONFLICT_POLICY_FAIL: StreamIdConflictPolicy.ValueType # 1 """The create fails with `ALREADY_EXISTS`.""" STREAM_ID_CONFLICT_POLICY_USE_EXISTING: StreamIdConflictPolicy.ValueType # 2 -"""The create returns the existing Stream without changing its expiry.""" +"""The create returns `created` false for the existing Stream.""" global___StreamIdConflictPolicy = StreamIdConflictPolicy class _StreamErrorReason: @@ -63,7 +63,7 @@ class _StreamErrorReasonEnumTypeWrapper( STREAM_ERROR_REASON_NOT_FOUND: _StreamErrorReason.ValueType # 1 """The Stream was never created (`NOT_FOUND`).""" STREAM_ERROR_REASON_EXPIRED: _StreamErrorReason.ValueType # 2 - """Retention has passed since create or the last append of a new batch (`NOT_FOUND`).""" + """The Store's retention policy removed the Records (`NOT_FOUND`).""" STREAM_ERROR_REASON_FENCED: _StreamErrorReason.ValueType # 3 """A later attempt of this Producer has written, and fencing is enabled (`FAILED_PRECONDITION`).""" STREAM_ERROR_REASON_FORMAT_TOO_NEW: _StreamErrorReason.ValueType # 4 @@ -96,7 +96,7 @@ STREAM_ERROR_REASON_UNSPECIFIED: StreamErrorReason.ValueType # 0 STREAM_ERROR_REASON_NOT_FOUND: StreamErrorReason.ValueType # 1 """The Stream was never created (`NOT_FOUND`).""" STREAM_ERROR_REASON_EXPIRED: StreamErrorReason.ValueType # 2 -"""Retention has passed since create or the last append of a new batch (`NOT_FOUND`).""" +"""The Store's retention policy removed the Records (`NOT_FOUND`).""" STREAM_ERROR_REASON_FENCED: StreamErrorReason.ValueType # 3 """A later attempt of this Producer has written, and fencing is enabled (`FAILED_PRECONDITION`).""" STREAM_ERROR_REASON_FORMAT_TOO_NEW: StreamErrorReason.ValueType # 4 diff --git a/temporalio/api/stream/v1/message_pb2.py b/temporalio/api/stream/v1/message_pb2.py index 2fe7bd7e9c..36f7c7ee60 100644 --- a/temporalio/api/stream/v1/message_pb2.py +++ b/temporalio/api/stream/v1/message_pb2.py @@ -23,7 +23,7 @@ ) DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n$temporal/api/stream/v1/message.proto\x12\x16temporal.api.stream.v1\x1a\x1fgoogle/protobuf/timestamp.proto\x1a$temporal/api/common/v1/message.proto\x1a"temporal/api/enums/v1/stream.proto"r\n\x13WorkflowTaskAttempt\x12\x18\n\x10started_event_id\x18\x01 \x01(\x03\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\x05\x12\x30\n\x0cstarted_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"b\n\x14LocalActivityAttempt\x12\x39\n\x04task\x18\x01 \x01(\x0b\x32+.temporal.api.stream.v1.WorkflowTaskAttempt\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\x05"^\n\x0f\x41\x63tivityAttempt\x12:\n\x16\x61ttempt_scheduled_time\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\x05"\xa2\x01\n\x10WorkflowProducer\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\x12\x18\n\x10workflow_task_id\x18\x04 \x01(\x03\x12<\n\x07\x61ttempt\x18\x05 \x01(\x0b\x32+.temporal.api.stream.v1.WorkflowTaskAttempt"\xc8\x01\n\x15LocalActivityProducer\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\x12\x13\n\x0b\x61\x63tivity_id\x18\x05 \x01(\t\x12=\n\x07\x61ttempt\x18\x06 \x01(\x0b\x32,.temporal.api.stream.v1.LocalActivityAttempt\x12\x0b\n\x03seq\x18\x07 \x01(\rJ\x04\x08\x04\x10\x05R\x10workflow_task_id"\xbd\x01\n\x18WorkflowActivityProducer\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\x12\x13\n\x0b\x61\x63tivity_id\x18\x04 \x01(\t\x12\x1a\n\x12scheduled_event_id\x18\x05 \x01(\x03\x12\x38\n\x07\x61ttempt\x18\x06 \x01(\x0b\x32\'.temporal.api.stream.v1.ActivityAttempt"\x8e\x01\n\x1aStandaloneActivityProducer\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x0e\n\x06run_id\x18\x03 \x01(\t\x12\x38\n\x07\x61ttempt\x18\x04 \x01(\x0b\x32\'.temporal.api.stream.v1.ActivityAttempt"/\n\x0e\x43lientProducer\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\n\n\x02id\x18\x02 \x01(\t"\xf5\x02\n\x08Producer\x12<\n\x08workflow\x18\x01 \x01(\x0b\x32(.temporal.api.stream.v1.WorkflowProducerH\x00\x12G\n\x0elocal_activity\x18\x02 \x01(\x0b\x32-.temporal.api.stream.v1.LocalActivityProducerH\x00\x12M\n\x11workflow_activity\x18\x03 \x01(\x0b\x32\x30.temporal.api.stream.v1.WorkflowActivityProducerH\x00\x12Q\n\x13standalone_activity\x18\x04 \x01(\x0b\x32\x32.temporal.api.stream.v1.StandaloneActivityProducerH\x00\x12\x38\n\x06\x63lient\x18\x05 \x01(\x0b\x32&.temporal.api.stream.v1.ClientProducerH\x00\x42\x06\n\x04kind"=\n\x0c\x41ppendRecord\x12-\n\x04\x62ody\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"\x81\x01\n\x0cStreamRecord\x12\x32\n\x08producer\x18\x01 \x01(\x0b\x32 .temporal.api.stream.v1.Producer\x12-\n\x04\x62ody\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x0e\n\x06offset\x18\x03 \x01(\x0c"N\n\x12StreamErrorDetails\x12\x38\n\x06reason\x18\x01 \x01(\x0e\x32(.temporal.api.enums.v1.StreamErrorReasonB\x89\x01\n\x19io.temporal.api.stream.v1B\x0cMessageProtoP\x01Z#go.temporal.io/api/stream/v1;stream\xaa\x02\x18Temporalio.Api.Stream.V1\xea\x02\x1bTemporalio::Api::Stream::V1b\x06proto3' + b'\n$temporal/api/stream/v1/message.proto\x12\x16temporal.api.stream.v1\x1a\x1fgoogle/protobuf/timestamp.proto\x1a$temporal/api/common/v1/message.proto\x1a"temporal/api/enums/v1/stream.proto"r\n\x13WorkflowTaskAttempt\x12\x18\n\x10started_event_id\x18\x01 \x01(\x03\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\x05\x12\x30\n\x0cstarted_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"b\n\x14LocalActivityAttempt\x12\x39\n\x04task\x18\x01 \x01(\x0b\x32+.temporal.api.stream.v1.WorkflowTaskAttempt\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\x05"^\n\x0f\x41\x63tivityAttempt\x12:\n\x16\x61ttempt_scheduled_time\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\x05"\xa2\x01\n\x10WorkflowProducer\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\x12\x18\n\x10workflow_task_id\x18\x04 \x01(\x03\x12<\n\x07\x61ttempt\x18\x05 \x01(\x0b\x32+.temporal.api.stream.v1.WorkflowTaskAttempt"\xb0\x01\n\x15LocalActivityProducer\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\x12\x13\n\x0b\x61\x63tivity_id\x18\x05 \x01(\t\x12=\n\x07\x61ttempt\x18\x06 \x01(\x0b\x32,.temporal.api.stream.v1.LocalActivityAttempt\x12\x0b\n\x03seq\x18\x07 \x01(\r"\xbd\x01\n\x18WorkflowActivityProducer\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\x12\x13\n\x0b\x61\x63tivity_id\x18\x04 \x01(\t\x12\x1a\n\x12scheduled_event_id\x18\x05 \x01(\x03\x12\x38\n\x07\x61ttempt\x18\x06 \x01(\x0b\x32\'.temporal.api.stream.v1.ActivityAttempt"\x8e\x01\n\x1aStandaloneActivityProducer\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x0e\n\x06run_id\x18\x03 \x01(\t\x12\x38\n\x07\x61ttempt\x18\x04 \x01(\x0b\x32\'.temporal.api.stream.v1.ActivityAttempt"/\n\x0e\x43lientProducer\x12\x11\n\tnamespace\x18\x01 \x01(\t\x12\n\n\x02id\x18\x02 \x01(\t"\xf5\x02\n\x08Producer\x12<\n\x08workflow\x18\x01 \x01(\x0b\x32(.temporal.api.stream.v1.WorkflowProducerH\x00\x12G\n\x0elocal_activity\x18\x02 \x01(\x0b\x32-.temporal.api.stream.v1.LocalActivityProducerH\x00\x12M\n\x11workflow_activity\x18\x03 \x01(\x0b\x32\x30.temporal.api.stream.v1.WorkflowActivityProducerH\x00\x12Q\n\x13standalone_activity\x18\x04 \x01(\x0b\x32\x32.temporal.api.stream.v1.StandaloneActivityProducerH\x00\x12\x38\n\x06\x63lient\x18\x05 \x01(\x0b\x32&.temporal.api.stream.v1.ClientProducerH\x00\x42\x06\n\x04kind"=\n\x0c\x41ppendRecord\x12-\n\x04\x62ody\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"\x81\x01\n\x0cStreamRecord\x12\x32\n\x08producer\x18\x01 \x01(\x0b\x32 .temporal.api.stream.v1.Producer\x12-\n\x04\x62ody\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x0e\n\x06offset\x18\x03 \x01(\x0c"N\n\x12StreamErrorDetails\x12\x38\n\x06reason\x18\x01 \x01(\x0e\x32(.temporal.api.enums.v1.StreamErrorReasonB\x89\x01\n\x19io.temporal.api.stream.v1B\x0cMessageProtoP\x01Z#go.temporal.io/api/stream/v1;stream\xaa\x02\x18Temporalio.Api.Stream.V1\xea\x02\x1bTemporalio::Api::Stream::V1b\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -40,19 +40,19 @@ _WORKFLOWPRODUCER._serialized_start = 484 _WORKFLOWPRODUCER._serialized_end = 646 _LOCALACTIVITYPRODUCER._serialized_start = 649 - _LOCALACTIVITYPRODUCER._serialized_end = 849 - _WORKFLOWACTIVITYPRODUCER._serialized_start = 852 - _WORKFLOWACTIVITYPRODUCER._serialized_end = 1041 - _STANDALONEACTIVITYPRODUCER._serialized_start = 1044 - _STANDALONEACTIVITYPRODUCER._serialized_end = 1186 - _CLIENTPRODUCER._serialized_start = 1188 - _CLIENTPRODUCER._serialized_end = 1235 - _PRODUCER._serialized_start = 1238 - _PRODUCER._serialized_end = 1611 - _APPENDRECORD._serialized_start = 1613 - _APPENDRECORD._serialized_end = 1674 - _STREAMRECORD._serialized_start = 1677 - _STREAMRECORD._serialized_end = 1806 - _STREAMERRORDETAILS._serialized_start = 1808 - _STREAMERRORDETAILS._serialized_end = 1886 + _LOCALACTIVITYPRODUCER._serialized_end = 825 + _WORKFLOWACTIVITYPRODUCER._serialized_start = 828 + _WORKFLOWACTIVITYPRODUCER._serialized_end = 1017 + _STANDALONEACTIVITYPRODUCER._serialized_start = 1020 + _STANDALONEACTIVITYPRODUCER._serialized_end = 1162 + _CLIENTPRODUCER._serialized_start = 1164 + _CLIENTPRODUCER._serialized_end = 1211 + _PRODUCER._serialized_start = 1214 + _PRODUCER._serialized_end = 1587 + _APPENDRECORD._serialized_start = 1589 + _APPENDRECORD._serialized_end = 1650 + _STREAMRECORD._serialized_start = 1653 + _STREAMRECORD._serialized_end = 1782 + _STREAMERRORDETAILS._serialized_start = 1784 + _STREAMERRORDETAILS._serialized_end = 1862 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/api/stream/v1/message_pb2.pyi b/temporalio/api/stream/v1/message_pb2.pyi index bd2f68cd4a..a66e8f5947 100644 --- a/temporalio/api/stream/v1/message_pb2.pyi +++ b/temporalio/api/stream/v1/message_pb2.pyi @@ -207,8 +207,8 @@ class LocalActivityProducer(google.protobuf.message.Message): run_id: builtins.str """Required.""" activity_id: builtins.str - """Required. The Activity id of the first schedule, for display. The SDK keeps it across - retries. + """Required. The Activity id of the first schedule. It is part of the Producer identity, + so the SDK keeps it across retries. """ seq: builtins.int """The sequence number of the command that first scheduled the Local Activity. It identifies @@ -396,7 +396,8 @@ global___ClientProducer = ClientProducer class Producer(google.protobuf.message.Message): """Experimental. Might change in the future. The kind and ids identify a Producer. The attempt does not. - With fencing enabled, a write fails with `FENCED` after a later attempt of that Producer writes. + A Store can reject an older attempt with `FENCED` after a later attempt of that Producer writes. + A remembered resend still returns its original offsets. Records retain their Producer and attempt so that readers can apply their own retry policy. Attempts of different Producers have no order. A reset run cannot fence its base run. """ diff --git a/temporalio/api/streamservice/v1/request_response_pb2.pyi b/temporalio/api/streamservice/v1/request_response_pb2.pyi index 2762fcae61..3ca63ba470 100644 --- a/temporalio/api/streamservice/v1/request_response_pb2.pyi +++ b/temporalio/api/streamservice/v1/request_response_pb2.pyi @@ -24,8 +24,8 @@ class CreateStreamRequest(google.protobuf.message.Message): A retry with the original create request id returns `created` true, even with `FAIL`. Either policy returns `EXPIRED` while the Store remembers an expired Stream. - Retention is a Store setting. It starts at create and restarts when an append writes a new batch. - Reads and resends keep the existing expiry. + Retention is a Store policy. Keep Records for as long as a Workflow History can replay them, + including after a Workflow reset. (-- api-linter: core::0133=disabled aip.dev/not-precedent: The request identifies a Stream by its id. --) """ @@ -77,7 +77,7 @@ global___CreateStreamResponse = CreateStreamResponse class AppendRecordsRequest(google.protobuf.message.Message): """Experimental. Might change in the future. Retries must use the same Producer, attempt, request id and batch. A remembered request id - returns the original offsets without writing again. The Store sets its resend window per + returns the original offsets without duplicating Records. The Store sets its resend window per Producer. An empty or forgotten request id permits a second write. """ diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index 239b8b7d90..9f57f2481f 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit 239b8b7d90057d45b274fd9261c6d3b264cc3e61 +Subproject commit 9f57f2481f708d6e2d30bd246f5b25940bb03d3f From 11f1a962bed760e04af4eca502e7dd0485d220b2 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Thu, 3 Dec 2026 23:08:02 -0700 Subject: [PATCH 13/15] Use the shared Stream names from Core --- temporalio/bridge/sdk-core | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index 9f57f2481f..cc5ca9584d 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit 9f57f2481f708d6e2d30bd246f5b25940bb03d3f +Subproject commit cc5ca9584d79c33f4f1bc14c8e3892f902f95669 From fffcba0dfe0438f2dbf15a0373ed738defb754be Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Fri, 4 Dec 2026 01:54:48 -0700 Subject: [PATCH 14/15] Pin Core appends with the rewritten Stream comments The bridge stubs take the new proto comments. No generated code changes. --- .../proto/external_data/external_data_pb2.pyi | 42 ++++++++++++------- .../workflow_activation_pb2.pyi | 21 +++++----- .../workflow_commands_pb2.pyi | 31 ++++++++------ temporalio/bridge/sdk-core | 2 +- 4 files changed, 58 insertions(+), 38 deletions(-) diff --git a/temporalio/bridge/proto/external_data/external_data_pb2.pyi b/temporalio/bridge/proto/external_data/external_data_pb2.pyi index 452a492875..0ef68ee498 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.pyi +++ b/temporalio/bridge/proto/external_data/external_data_pb2.pyi @@ -159,9 +159,12 @@ global___PatchedMarkerData = PatchedMarkerData @typing.final class StreamAppendMarkerData(google.protobuf.message.Message): - """JSON data of a `core_stream_append` marker. Its `bytes` fields are Base64. A marker with no - result keeps a task that has an open append apart from the next task in a replay with chunking - on. + """The JSON data of a `core_stream_append` marker. Core records one marker for each activation + that gives Workflow code the result of an append. A replay takes the results from the marker and + gives them in the same activation. The `bytes` fields are Base64 in the JSON. + + A marker can have no result. Core records one when a Workflow Task completes while an append is + still running. See `pending_origin`. """ DESCRIPTOR: google.protobuf.descriptor.Descriptor @@ -173,11 +176,15 @@ class StreamAppendMarkerData(google.protobuf.message.Message): self, ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ global___StreamAppendResult - ]: ... + ]: + """The results that Workflow code got in the activation.""" + @property def pending_origin(self) -> global___StreamAppendOrigin: - """Set if the task completed with an open append that it issued. A new Worker resends each of - them with this Producer attempt and the same request id. + """Set when the Workflow Task completed before Workflow code got the result of an append that + started in it. If another Worker takes over the run, it sends that append again with the same + Producer attempt and the same request id. The Store can then recognize a write that it + already has. """ def __init__( @@ -200,8 +207,8 @@ global___StreamAppendMarkerData = StreamAppendMarkerData @typing.final class StreamAppendOrigin(google.protobuf.message.Message): - """The Workflow Task that issued the appends that had no result when it completed. They are the - open appends that have no origin from an earlier task. + """The Workflow Task attempt in which an append started. Its fields are the task fields of the + `WorkflowProducer` that writes the append. """ DESCRIPTOR: google.protobuf.descriptor.Descriptor @@ -244,6 +251,8 @@ global___StreamAppendOrigin = StreamAppendOrigin @typing.final class StreamAppendResult(google.protobuf.message.Message): + """The result of one append, as Workflow code got it.""" + DESCRIPTOR: google.protobuf.descriptor.Descriptor SEQ_FIELD_NUMBER: builtins.int @@ -253,13 +262,16 @@ class StreamAppendResult(google.protobuf.message.Message): APPENDED_FIELD_NUMBER: builtins.int FAILURE_FIELD_NUMBER: builtins.int seq: builtins.int + """The `seq` of the `AppendToStream` command.""" stream_id: builtins.str store: builtins.str - """The Store that the append used. A ref with no Store name uses the runtime under the empty name, - else the only runtime. + """The name of the Store that the append used. For a command with no Store name, it's the name + that Core chose (see `AppendToStream`). """ activation_index: builtins.int - """The activation, counted within its Workflow Task, that delivered the result.""" + """The activation that gave Workflow code the result. Activations count from 0 in each Workflow + Task. + """ @property def appended(self) -> global___StreamAppendOffsets: ... @property @@ -330,18 +342,18 @@ global___StreamAppendOffsets = StreamAppendOffsets @typing.final class StreamFailure(google.protobuf.message.Message): - """Why a Stream call failed. Core builds the failure for Workflow code from these two fields.""" + """Why a Stream call failed. Core builds the failure that Workflow code gets from these two fields.""" DESCRIPTOR: google.protobuf.descriptor.Descriptor REASON_FIELD_NUMBER: builtins.int MESSAGE_FIELD_NUMBER: builtins.int reason: builtins.str - """A `temporalio.api.enums.v1.StreamErrorReason` name, such as `STREAM_ERROR_REASON_FENCED`. History - stores it, so a reason can never be renamed. + """The name of a `temporalio.api.enums.v1.StreamErrorReason` value, such as + `STREAM_ERROR_REASON_FENCED`. History keeps the name, so the enum can't rename a value. """ message: builtins.str - """The failure message, at most 4096 bytes.""" + """The failure message. Core cuts it to 4096 bytes.""" def __init__( self, *, diff --git a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi index f148a88948..07d3bd2b02 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi @@ -65,12 +65,11 @@ class WorkflowActivation(google.protobuf.message.Message): in that same activation (prime example: cancelling not-wait-for-cancel activities). So, we do this to ensure the LA resolution happens after that cancel (or whatever else it may be) as it normally would have when executing. - * Stream results share this slot with local activity resolutions, for the same reason. Both - are recorded in markers that replay scans ahead for, and each marker entry has the index of - the activation that delivered it. Both kinds share that index. A task with a Stream marker - replays in its recorded activations, and so does each task of a History with chunking off. - Within one activation, Stream results go first in `seq` order, then local activity - resolutions. + * Stream results go in the same slot as local activity resolutions, for the same reason. Core + records both kinds in markers. A marker entry has the index of the activation that gave the + result, counted from 0 in its workflow task. When replaying a workflow task that has a Stream + marker, Core gives each result in the activation with that index. Inside one activation, + Stream results come first, in `seq` order, and local activity resolutions follow. * Queries always go last (and, in fact, always come in their own activation) * Evictions also always come in their own activation @@ -1673,14 +1672,14 @@ class ResolveStreamAppend(google.protobuf.message.Message): APPENDED_FIELD_NUMBER: builtins.int FAILED_FIELD_NUMBER: builtins.int seq: builtins.int - """The `seq` of the `AppendToStream`.""" + """The `seq` of the `AppendToStream` command.""" @property def appended(self) -> global___StreamAppended: ... @property def failed(self) -> temporalio.api.failure.v1.message_pb2.Failure: - """An `ApplicationFailureInfo` of type `stream_`, such as `stream_fenced`, with - `non_retryable` set. Its details are one `binary/protobuf` payload of a - `temporalio.api.stream.v1.StreamErrorDetails`. + """Why the append failed. It's an `ApplicationFailureInfo` with the type `stream_`, + such as `stream_fenced`, and with `non_retryable` set. Its details are one + `binary/protobuf` payload that holds a `temporalio.api.stream.v1.StreamErrorDetails`. """ def __init__( @@ -1717,6 +1716,8 @@ global___ResolveStreamAppend = ResolveStreamAppend @typing.final class StreamAppended(google.protobuf.message.Message): + """The offsets of the first and the last Record that the append wrote.""" + DESCRIPTOR: google.protobuf.descriptor.Descriptor FIRST_OFFSET_FIELD_NUMBER: builtins.int diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi index e1436a6ff4..99a25a278b 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi @@ -1959,16 +1959,21 @@ global___RequestCancelNexusOperation = RequestCancelNexusOperation @typing.final class AppendToStream(google.protobuf.message.Message): - """Appends Records as the Workflow Producer and resolves with `ResolveStreamAppend`. Appends to one - Stream go out in command order. A task retry can write a batch again if History has no result for - it. - - With no Store name, the append uses the runtime under the empty name, else the only runtime. A - bad seq or Stream ref, a missing runtime, or a Store outage at the task heartbeat fails the - Workflow Task. An invalid batch resolves with a failure. - - Lang must accept results for appends that it no longer awaits. The terminal Workflow command - drops unresolved appends. Replay matches on seq and Stream and returns the result in History. + """Appends Records to a Stream. Core writes them as the Workflow Producer of the run and gives + the result in a `ResolveStreamAppend` job. + + * Order. The appends to one Stream reach the Store one at a time, in command order. + * Store. A `stream` with no Store name uses the Stream runtime that the Worker has under the + empty name. If the Worker has none, it uses the Worker's only runtime. + * Failures. An append that the Store refuses resolves with a failure. A `seq` or `stream` that + isn't valid fails the Workflow Task. So does a Worker with no runtime for the Store, and a + Store that is still unavailable at the heartbeat of the Workflow Task. + * Retries. When a Workflow Task fails or times out before History has the result of an append, + its retry sends the append again. + * Replay. Core gives the result that History has for the `seq`, and makes no Store call. A + command for another Stream than History has is a nondeterminism error. + * End of the Workflow. The command that ends the Workflow drops each append that has no result + yet. Lang must also accept a result that it no longer waits for. """ DESCRIPTOR: google.protobuf.descriptor.Descriptor @@ -1977,7 +1982,7 @@ class AppendToStream(google.protobuf.message.Message): STREAM_FIELD_NUMBER: builtins.int BODIES_FIELD_NUMBER: builtins.int seq: builtins.int - """Lang's incremental sequence number for appends, starting at 1.""" + """Lang's incremental sequence number for appends. It starts at 1.""" @property def stream(self) -> temporalio.api.sdk.v1.stream_pb2.StreamRef: ... @property @@ -1985,7 +1990,9 @@ class AppendToStream(google.protobuf.message.Message): self, ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ temporalio.api.common.v1.message_pb2.Payload - ]: ... + ]: + """The bodies of the Records, one Record for each body.""" + def __init__( self, *, diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index cc5ca9584d..ebc220967c 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit cc5ca9584d79c33f4f1bc14c8e3892f902f95669 +Subproject commit ebc220967cecdb67bcbb57fdbd57ef1b84085b8c From ebe9f7b8241be021bcb994d55b3d8c14a183e2a3 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Sun, 6 Dec 2026 00:34:15 -0700 Subject: [PATCH 15/15] Say why in the docs and comments of client Stream calls Explain how a client or Activity Stream call reaches a Store, why retries keep the request id, why Store errors become reasons, and why Stream bodies skip external storage. Only docstrings and comments change. --- temporalio/client/_client.py | 13 ++++--- temporalio/client/_interceptor.py | 16 +++++---- temporalio/client/_nexus.py | 3 +- temporalio/client/_stream_store.py | 40 ++++++++++++++------- temporalio/worker/_command_aware_visitor.py | 10 +++--- tests/helpers/streams.py | 2 +- tests/nexus/test_streams.py | 17 ++++----- 7 files changed, 62 insertions(+), 39 deletions(-) diff --git a/temporalio/client/_client.py b/temporalio/client/_client.py index 05ccab86e3..bbaea1bd58 100644 --- a/temporalio/client/_client.py +++ b/temporalio/client/_client.py @@ -125,8 +125,9 @@ class _StreamCalls(StreamServiceClientExtension): - """Starts the Stream operations of a client, so that the generated extension - stays out of the bases of :py:class:`Client`. + """Start the Stream calls of a client. This class, not :py:class:`Client`, + inherits the generated extension, so the extension's methods stay out of the + client's API. """ def __init__(self, client: Client) -> None: @@ -253,7 +254,7 @@ 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 for this client and the workers that use + stream_config: Stream Stores for this client and the Workers that use it. Each Stream call goes to one of these Stores. Without it, a Stream call raises :exc:`ValueError`. @@ -2954,6 +2955,9 @@ async def create_stream( ) -> Stream[Any]: """Create a Stream on a Store of the client's ``stream_config``. + The ref of the returned Stream names that Store, so later calls on the + Stream go to it even if the selector would pick another. + .. warning:: This API is experimental and unstable. @@ -3005,7 +3009,8 @@ def get_stream( created: bool | None = None, body_type: Any = None, ) -> Stream[Any]: - """Return the handle of the Stream of ``ref``, with no call. + """Return a handle for the Stream of ``ref``. It makes no Store call, so it + doesn't check that the Stream exists. .. warning:: This API is experimental and unstable. diff --git a/temporalio/client/_interceptor.py b/temporalio/client/_interceptor.py index 86ec05197e..b17938dafb 100644 --- a/temporalio/client/_interceptor.py +++ b/temporalio/client/_interceptor.py @@ -625,7 +625,8 @@ 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. + # A `dataclasses.replace` copy keeps this id, so a resend has the same request id + # and the Store can skip a write that it already made. _stream_request_id: uuid.UUID = field( default_factory=uuid.uuid4, repr=False, compare=False, kw_only=True ) @@ -747,12 +748,13 @@ class OutboundInterceptor(_SystemNexusClientOutboundInterceptorBase): 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. + Stream calls go to a Store, not to the server, so they have their own hooks: + ``start_create_stream``, ``start_append_records``, ``start_read_records`` and + ``start_describe_stream``. Each takes a typed :py:class:`StartNexusOperationInput` + and returns a :py:class:`NexusOperationHandle`. Stream calls don't reach the + generic Nexus start or result hooks. To retry a call, pass the same input or a + dataclass copy of it. Both keep the request id, so the Store can skip a write + that it already made when only its answer got lost. """ def __init__(self, next: OutboundInterceptor) -> None: diff --git a/temporalio/client/_nexus.py b/temporalio/client/_nexus.py index 914856ff5e..50d8ccea5b 100644 --- a/temporalio/client/_nexus.py +++ b/temporalio/client/_nexus.py @@ -1180,7 +1180,8 @@ async def start_operation( rpc_timeout=rpc_timeout, completion_callbacks=completion_callbacks, ) - # Stream operations use their typed hooks, not the generic Nexus chain. + # Stream calls go to a Store, not to the server, so they take their typed hooks + # rather than the generic Nexus chain. if ( temporalio.nexus.system.is_system_endpoint(input.endpoint) and input.service == _STREAM_SERVICE.name diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 1d9c8f808f..af2fe661b3 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -1,4 +1,11 @@ -"""Client request validation and Store dispatch.""" +"""Send the Stream calls of client and Activity code to a Store. + +The server doesn't run Stream calls. The generated Stream client starts each call +as a system Nexus operation, and the end of the client's interceptor chain sends it +here instead, to a Store of the client's ``StreamConfig``. This module checks each +request the way Core checks the calls of Workflow code, so both paths refuse the +same requests. +""" from __future__ import annotations @@ -11,8 +18,8 @@ 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. +# Worker modules import this module, so pydoctor can read it before the client package. +# A `from` import of a sibling here would then lose the package's re-exports. import temporalio.client import temporalio.nexus.system._support import temporalio.streams @@ -44,8 +51,9 @@ _STREAM_SERVICE: nexusrpc.ServiceDefinition = _definition _READ_ANSWER_TIME = timedelta(seconds=1) -"""Time reserved for the Store's answer before ``rpc_timeout`` ends a client read. -A shorter timeout reserves a tenth of itself.""" +"""How much of a client read's ``rpc_timeout`` the client keeps for the Store's +answer, so that a Store that waits the whole ``wait`` still answers in time. A +timeout under ten seconds keeps a tenth of itself.""" def _request_ref(request: google.protobuf.message.Message) -> sdk.StreamRef: @@ -144,13 +152,14 @@ def _store_request( ), "client": (("namespace", "namespace"), ("id", "client id")), } -"""The ids of each kind of Producer, with the words of their errors.""" +"""The ids of each kind of Producer, with the words that name each id in an error.""" def _check_request( request: google.protobuf.message.Message, limits: tuple[int, int, int] ) -> None: - """Check a Store request the way SDK Core's Stream runtime does. + """Check a Store request the way SDK Core's Stream runtime does, so that client + and Workflow code get the same error for the same request. ``limits`` are the ``max_record_bytes``, ``max_batch_bytes`` and ``max_batch_records`` of a Stream config. @@ -190,7 +199,7 @@ def _check_append( 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. + # The limits count a Record in its stored form: a `StreamRecord` with no offset. producer_bytes = _field_bytes(request.producer.ByteSize()) total = 0 for at, record in enumerate(records): @@ -272,7 +281,7 @@ def _check_producer(request: AppendRecordsRequest) -> None: def _check_task(task: WorkflowTaskAttempt) -> None: - # Tasks are ordered by their started event id first, so an attempt without one + # Stores order tasks 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") @@ -325,7 +334,12 @@ async def _call_method( request: google.protobuf.message.Message, request_id: str | None, ) -> google.protobuf.message.Message: - """Translate Store exceptions before Core decides whether to retry.""" + """Call one Store method, and turn what goes wrong into a ``StreamError``. + + An Activity's retry policy goes by the reason, so an unknown exception becomes + ``STORE_UNAVAILABLE``, which the policy retries, and a response of the wrong type + becomes ``STORE_CORRUPT``, which it doesn't. + """ method, _, response_type = _store_operation(operation) call = getattr(store, method) try: @@ -359,10 +373,10 @@ async def _call_store( # pyright: ignore[reportUnusedFunction] request_id: str | None, timeout: timedelta | None = None, ) -> google.protobuf.message.Message: - """Keep client codec and request checks consistent with Workflow calls. + """Run one Stream call of client or Activity code against ``store``. - Records have no serialization context because any client or Workflow can - read them. Each codec call receives one Record body. + Records have no serialization context, because any client or Workflow can read + them. The codec gets one Record body per call. """ store_request = _store_request(request) if codec and isinstance(store_request, AppendRecordsRequest): diff --git a/temporalio/worker/_command_aware_visitor.py b/temporalio/worker/_command_aware_visitor.py index a75c42d754..224cb1018b 100644 --- a/temporalio/worker/_command_aware_visitor.py +++ b/temporalio/worker/_command_aware_visitor.py @@ -215,7 +215,7 @@ async def _visit_coresdk_workflow_activation_ResolveNexusOperation( ) # Stream commands and activation jobs. Core builds the failure of a Stream job with no - # codec, so nothing visits it. + # codec, so a codec must not decode it. async def _visit_coresdk_workflow_commands_AppendToStream( self, fs: VisitorFunctions, o: AppendToStream ) -> None: @@ -229,8 +229,8 @@ async def _visit_coresdk_workflow_activation_ResolveStreamAppend( 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. + # Any writer can append a Record, so the visitor doesn't treat its body as a + # system Nexus envelope. A codec gets each body alone, as in client code. with current_command(CommandType.COMMAND_TYPE_UNSPECIFIED, seq): for payload in payloads: await fs.visit_payload(payload) @@ -239,8 +239,8 @@ async def _visit_stream_payloads( 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. + These passes skip Stream bodies. A Stream body is its writer's value, and it can + look like a reference into this Worker's external storage. """ async def _visit_stream_payloads( diff --git a/tests/helpers/streams.py b/tests/helpers/streams.py index 918fc16b2b..cc94883184 100644 --- a/tests/helpers/streams.py +++ b/tests/helpers/streams.py @@ -70,7 +70,7 @@ def wrapped( payload: temporalio.api.common.v1.Payload, context: temporalio.converter.SerializationContext | None = None, ) -> temporalio.api.common.v1.Payload: - """Return ``payload`` as a :py:class:`ContextCodec` with ``context`` encodes it.""" + """Return ``payload`` as a :py:class:`ContextCodec` encodes it with ``context``.""" return temporalio.api.common.v1.Payload( metadata={ "encoding": b"test/wrapped", diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index 89173eced5..70efece33e 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -904,7 +904,7 @@ def describe(**fields: Any) -> tuple[str, Message]: "wait must be 0 or more", ), ] - # Each text id of each kind of Producer, with the words of its error. + # The words that an error uses for each text id of each kind of Producer. words = { "namespace": "namespace", "workflow_id": "Workflow id", @@ -1295,10 +1295,11 @@ async def script() -> None: stream = await client.create_stream(id="s", body_type=int) minute = temporalio.nexus.system._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. + # With no wait, the first read returns immediately and each later one waits + # the default wait. A wait of zero means the caller chose to read in a loop. + # The Store gets no wait for it, because a Store may take a zero wait as one + # with no end. The client caps a wait below 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), @@ -1306,8 +1307,8 @@ async def script() -> None: (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. + # Under ten seconds, the client keeps a tenth of the timeout for the + # Store's answer. A timeout of zero is no timeout. (ten, timedelta(seconds=2), [timedelta(seconds=1.8)] * 5), (ten, timedelta(0), [ten] * 5), ] @@ -1324,7 +1325,7 @@ async def script() -> None: 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. + # A Record that arrives during a wait ends it immediately, and the caller stops. async def append_later() -> None: await asyncio.sleep(90) await stream.append(1)