diff --git a/changelog/added/steady-stream-heron.md b/changelog/added/steady-stream-heron.md new file mode 100644 index 000000000..caaa895e2 --- /dev/null +++ b/changelog/added/steady-stream-heron.md @@ -0,0 +1 @@ +Add experimental Stream reads in Workflows with replay checks for changed or missing Records. diff --git a/temporalio/bridge/Cargo.lock b/temporalio/bridge/Cargo.lock index 23e9ffff3..bc3eaaa22 100644 --- a/temporalio/bridge/Cargo.lock +++ b/temporalio/bridge/Cargo.lock @@ -181,6 +181,15 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "bon" version = "3.10.3" @@ -309,6 +318,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "constant_time_eq" version = "0.6.2" @@ -376,6 +391,15 @@ version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "darling" version = "0.24.1" @@ -433,6 +457,17 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + [[package]] name = "dirs" version = "7.0.0" @@ -871,6 +906,15 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.13.0" @@ -2422,6 +2466,17 @@ dependencies = [ "serde", ] +[[package]] +name = "sha2" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "sharded-slab" version = "0.1.7" @@ -2792,6 +2847,7 @@ dependencies = [ "reqwest", "serde", "serde_json", + "sha2", "siphasher", "slotmap", "sysinfo", @@ -2931,6 +2987,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "futures-util", "libc", "pin-project-lite", "tokio", @@ -3199,6 +3256,12 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "typetag" version = "0.2.23" diff --git a/temporalio/bridge/_visitor.py b/temporalio/bridge/_visitor.py index 06f5b4346..ab059e964 100644 --- a/temporalio/bridge/_visitor.py +++ b/temporalio/bridge/_visitor.py @@ -314,6 +314,26 @@ async def _visit_coresdk_workflow_activation_ResolveStreamAppend( if o.HasField("failed"): await self._visit_temporal_api_failure_v1_Failure(fs, o.failed) + async def _visit_temporal_api_stream_v1_StreamRecord( + self, fs: VisitorFunctions, o: Any + ): + if o.HasField("body"): + await self._visit_temporal_api_common_v1_Payload(fs, o.body) + + async def _visit_coresdk_workflow_activation_StreamPage( + self, fs: VisitorFunctions, o: Any + ): + for v in o.records: + await self._visit_temporal_api_stream_v1_StreamRecord(fs, v) + + async def _visit_coresdk_workflow_activation_ResolveStreamRead( + self, fs: VisitorFunctions, o: Any + ): + if o.HasField("page"): + await self._visit_coresdk_workflow_activation_StreamPage(fs, o.page) + elif o.HasField("failed"): + await self._visit_temporal_api_failure_v1_Failure(fs, o.failed) + async def _visit_coresdk_workflow_activation_WorkflowActivationJob( self, fs: VisitorFunctions, o: Any ): @@ -363,6 +383,10 @@ async def _visit_coresdk_workflow_activation_WorkflowActivationJob( await self._visit_coresdk_workflow_activation_ResolveStreamAppend( fs, o.resolve_stream_append ) + elif o.HasField("resolve_stream_read"): + await self._visit_coresdk_workflow_activation_ResolveStreamRead( + fs, o.resolve_stream_read + ) async def _visit_coresdk_workflow_activation_WorkflowActivation( self, fs: VisitorFunctions, o: Any @@ -690,12 +714,6 @@ async def _visit_temporal_api_sdk_v1_ReadRecordsRequest( ) -> None: pass - async def _visit_temporal_api_stream_v1_StreamRecord( - self, fs: VisitorFunctions, o: Any - ): - if o.HasField("body"): - await self._visit_temporal_api_common_v1_Payload(fs, o.body) - async def _visit_temporal_api_streamservice_v1_ReadRecordsResponse( self, fs: VisitorFunctions, o: Any ): diff --git a/temporalio/bridge/proto/external_data/__init__.py b/temporalio/bridge/proto/external_data/__init__.py index 1d221dc4b..4537c6612 100644 --- a/temporalio/bridge/proto/external_data/__init__.py +++ b/temporalio/bridge/proto/external_data/__init__.py @@ -6,6 +6,9 @@ StreamAppendOrigin, StreamAppendResult, StreamFailure, + StreamReadMarkerData, + StreamReadPage, + StreamReadResult, ) __all__ = [ @@ -16,4 +19,7 @@ "StreamAppendOrigin", "StreamAppendResult", "StreamFailure", + "StreamReadMarkerData", + "StreamReadPage", + "StreamReadResult", ] diff --git a/temporalio/bridge/proto/external_data/external_data_pb2.py b/temporalio/bridge/proto/external_data/external_data_pb2.py index a4b6cd4f3..3ab8c53bc 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"\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' + 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(\t"N\n\x14StreamReadMarkerData\x12\x36\n\x05reads\x18\x01 \x03(\x0b\x32\'.coresdk.external_data.StreamReadResult"\xeb\x01\n\x10StreamReadResult\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x11\n\tstream_id\x18\x02 \x01(\t\x12\r\n\x05store\x18\x03 \x01(\t\x12\x18\n\x10\x61\x63tivation_index\x18\x04 \x01(\x04\x12\x14\n\x0c\x61\x66ter_offset\x18\x05 \x01(\x0c\x12\x35\n\x04page\x18\x06 \x01(\x0b\x32%.coresdk.external_data.StreamReadPageH\x00\x12\x37\n\x07\x66\x61ilure\x18\x07 \x01(\x0b\x32$.coresdk.external_data.StreamFailureH\x00\x42\x08\n\x06result"^\n\x0eStreamReadPage\x12\x14\n\x0crecord_count\x18\x01 \x01(\r\x12\x0e\n\x06\x64igest\x18\x02 \x01(\x0c\x12\x14\n\x0crecord_bytes\x18\x03 \x01(\x04\x12\x10\n\x08wait_cut\x18\x05 \x01(\x08\x42\x32\xea\x02/Temporalio::Internal::Bridge::Api::ExternalDatab\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -45,4 +45,10 @@ _STREAMAPPENDOFFSETS._serialized_end = 1199 _STREAMFAILURE._serialized_start = 1201 _STREAMFAILURE._serialized_end = 1249 + _STREAMREADMARKERDATA._serialized_start = 1251 + _STREAMREADMARKERDATA._serialized_end = 1329 + _STREAMREADRESULT._serialized_start = 1332 + _STREAMREADRESULT._serialized_end = 1567 + _STREAMREADPAGE._serialized_start = 1569 + _STREAMREADPAGE._serialized_end = 1663 # @@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 0ef68ee49..e761726a7 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.pyi +++ b/temporalio/bridge/proto/external_data/external_data_pb2.pyi @@ -365,3 +365,156 @@ class StreamFailure(google.protobuf.message.Message): ) -> None: ... global___StreamFailure = StreamFailure + +@typing.final +class StreamReadMarkerData(google.protobuf.message.Message): + """The JSON data of a `core_stream_read` marker. Core records one marker for each activation that + gives Workflow code the result of a read. The marker doesn't hold the Records of a page. It + holds the offset that the page starts after, the number of its Records and a digest of them. A + replay reads the Records from the Store again and checks them against the digest. The `bytes` + fields are Base64 in the JSON. + + A marker can have no result. Core records one when a Workflow Task completes with no other + event while Workflow code waits for a read. Without an event, a replay can't see where that + task ended. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + READS_FIELD_NUMBER: builtins.int + @property + def reads( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___StreamReadResult + ]: + """The results that Workflow code got in the activation.""" + + def __init__( + self, + *, + reads: collections.abc.Iterable[global___StreamReadResult] | None = ..., + ) -> None: ... + def ClearField(self, field_name: typing.Literal["reads", b"reads"]) -> None: ... + +global___StreamReadMarkerData = StreamReadMarkerData + +@typing.final +class StreamReadResult(google.protobuf.message.Message): + """The result of one read, as Workflow code got it, without the Records.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + STREAM_ID_FIELD_NUMBER: builtins.int + STORE_FIELD_NUMBER: builtins.int + ACTIVATION_INDEX_FIELD_NUMBER: builtins.int + AFTER_OFFSET_FIELD_NUMBER: builtins.int + PAGE_FIELD_NUMBER: builtins.int + FAILURE_FIELD_NUMBER: builtins.int + seq: builtins.int + """The `seq` of the `ReadStream` command.""" + stream_id: builtins.str + store: builtins.str + """The name of the Store that the read used. For a command with no Store name, it's the name + that Core chose (see `AppendToStream`). + """ + activation_index: builtins.int + """The activation that gave Workflow code the result. Activations count from 0 in each Workflow + Task. + """ + after_offset: builtins.bytes + """The `after_offset` of the command. A replay reads the Records of the page after it.""" + @property + def page(self) -> global___StreamReadPage: ... + @property + def failure(self) -> global___StreamFailure: ... + def __init__( + self, + *, + seq: builtins.int = ..., + stream_id: builtins.str = ..., + store: builtins.str = ..., + activation_index: builtins.int = ..., + after_offset: builtins.bytes = ..., + page: global___StreamReadPage | None = ..., + failure: global___StreamFailure | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "failure", b"failure", "page", b"page", "result", b"result" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "activation_index", + b"activation_index", + "after_offset", + b"after_offset", + "failure", + b"failure", + "page", + b"page", + "result", + b"result", + "seq", + b"seq", + "store", + b"store", + "stream_id", + b"stream_id", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["result", b"result"] + ) -> typing.Literal["page", "failure"] | None: ... + +global___StreamReadResult = StreamReadResult + +@typing.final +class StreamReadPage(google.protobuf.message.Message): + """A page that a read gave Workflow code, without its Records.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RECORD_COUNT_FIELD_NUMBER: builtins.int + DIGEST_FIELD_NUMBER: builtins.int + RECORD_BYTES_FIELD_NUMBER: builtins.int + WAIT_CUT_FIELD_NUMBER: builtins.int + record_count: builtins.int + """The number of Records in the page.""" + digest: builtins.bytes + """A digest of the Records. It's a version byte, which is 1, and the first 16 bytes of a SHA-256 + hash of the Records in an encoding that Core owns. It's empty for a page with no Record. + """ + record_bytes: builtins.int + """The size of the Records in bytes, counted as the `max_bytes` of a read counts them. A replay + asks the Store for that many bytes. + """ + wait_cut: builtins.bool + """The `wait_cut` that Workflow code got with the page.""" + def __init__( + self, + *, + record_count: builtins.int = ..., + digest: builtins.bytes = ..., + record_bytes: builtins.int = ..., + wait_cut: builtins.bool = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "digest", + b"digest", + "record_bytes", + b"record_bytes", + "record_count", + b"record_count", + "wait_cut", + b"wait_cut", + ], + ) -> None: ... + +global___StreamReadPage = StreamReadPage diff --git a/temporalio/bridge/proto/workflow_activation/__init__.py b/temporalio/bridge/proto/workflow_activation/__init__.py index 453c0eefe..decfcf147 100644 --- a/temporalio/bridge/proto/workflow_activation/__init__.py +++ b/temporalio/bridge/proto/workflow_activation/__init__.py @@ -17,8 +17,10 @@ ResolveRequestCancelExternalWorkflow, ResolveSignalExternalWorkflow, ResolveStreamAppend, + ResolveStreamRead, SignalWorkflow, StreamAppended, + StreamPage, UpdateRandomSeed, WorkflowActivation, WorkflowActivationJob, @@ -43,8 +45,10 @@ "ResolveRequestCancelExternalWorkflow", "ResolveSignalExternalWorkflow", "ResolveStreamAppend", + "ResolveStreamRead", "SignalWorkflow", "StreamAppended", + "StreamPage", "UpdateRandomSeed", "WorkflowActivation", "WorkflowActivationJob", diff --git a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py index bfae7abbd..c37c592d9 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py @@ -32,6 +32,9 @@ from temporalio.api.nexus.v1 import ( message_pb2 as temporal_dot_api_dot_nexus_dot_v1_dot_message__pb2, ) +from temporalio.api.stream.v1 import ( + message_pb2 as temporal_dot_api_dot_stream_dot_v1_dot_message__pb2, +) from temporalio.api.update.v1 import ( message_pb2 as temporal_dot_api_dot_update_dot_v1_dot_message__pb2, ) @@ -49,7 +52,7 @@ ) DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n?temporal/sdk/core/workflow_activation/workflow_activation.proto\x12\x1b\x63oresdk.workflow_activation\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a%temporal/api/failure/v1/message.proto\x1a#temporal/api/nexus/v1/message.proto\x1a$temporal/api/update/v1/message.proto\x1a$temporal/api/common/v1/message.proto\x1a(temporal/api/enums/v1/failed_cause.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a\x37temporal/sdk/core/activity_result/activity_result.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a%temporal/sdk/core/common/common.proto\x1a#temporal/sdk/core/nexus/nexus.proto"\xa2\x04\n\x12WorkflowActivation\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x14\n\x0cis_replaying\x18\x03 \x01(\x08\x12\x16\n\x0ehistory_length\x18\x04 \x01(\r\x12@\n\x04jobs\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.WorkflowActivationJob\x12 \n\x18\x61vailable_internal_flags\x18\x06 \x03(\r\x12\x1a\n\x12history_size_bytes\x18\x07 \x01(\x04\x12!\n\x19\x63ontinue_as_new_suggested\x18\x08 \x01(\x08\x12T\n#deployment_version_for_current_task\x18\t \x01(\x0b\x32\'.coresdk.common.WorkerDeploymentVersion\x12\x18\n\x10last_sdk_version\x18\n \x01(\t\x12Z\n\x1fsuggest_continue_as_new_reasons\x18\x0b \x03(\x0e\x32\x31.temporal.api.enums.v1.SuggestContinueAsNewReason\x12\x30\n(target_worker_deployment_version_changed\x18\x0c \x01(\x08"\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' + b'\n?temporal/sdk/core/workflow_activation/workflow_activation.proto\x12\x1b\x63oresdk.workflow_activation\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a%temporal/api/failure/v1/message.proto\x1a#temporal/api/nexus/v1/message.proto\x1a$temporal/api/update/v1/message.proto\x1a$temporal/api/common/v1/message.proto\x1a(temporal/api/enums/v1/failed_cause.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a$temporal/api/stream/v1/message.proto\x1a\x37temporal/sdk/core/activity_result/activity_result.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a%temporal/sdk/core/common/common.proto\x1a#temporal/sdk/core/nexus/nexus.proto"\xa2\x04\n\x12WorkflowActivation\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x14\n\x0cis_replaying\x18\x03 \x01(\x08\x12\x16\n\x0ehistory_length\x18\x04 \x01(\r\x12@\n\x04jobs\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.WorkflowActivationJob\x12 \n\x18\x61vailable_internal_flags\x18\x06 \x03(\r\x12\x1a\n\x12history_size_bytes\x18\x07 \x01(\x04\x12!\n\x19\x63ontinue_as_new_suggested\x18\x08 \x01(\x08\x12T\n#deployment_version_for_current_task\x18\t \x01(\x0b\x32\'.coresdk.common.WorkerDeploymentVersion\x12\x18\n\x10last_sdk_version\x18\n \x01(\t\x12Z\n\x1fsuggest_continue_as_new_reasons\x18\x0b \x03(\x0e\x32\x31.temporal.api.enums.v1.SuggestContinueAsNewReason\x12\x30\n(target_worker_deployment_version_changed\x18\x0c \x01(\x08"\x82\x0c\n\x15WorkflowActivationJob\x12N\n\x13initialize_workflow\x18\x01 \x01(\x0b\x32/.coresdk.workflow_activation.InitializeWorkflowH\x00\x12<\n\nfire_timer\x18\x02 \x01(\x0b\x32&.coresdk.workflow_activation.FireTimerH\x00\x12K\n\x12update_random_seed\x18\x04 \x01(\x0b\x32-.coresdk.workflow_activation.UpdateRandomSeedH\x00\x12\x44\n\x0equery_workflow\x18\x05 \x01(\x0b\x32*.coresdk.workflow_activation.QueryWorkflowH\x00\x12\x46\n\x0f\x63\x61ncel_workflow\x18\x06 \x01(\x0b\x32+.coresdk.workflow_activation.CancelWorkflowH\x00\x12\x46\n\x0fsignal_workflow\x18\x07 \x01(\x0b\x32+.coresdk.workflow_activation.SignalWorkflowH\x00\x12H\n\x10resolve_activity\x18\x08 \x01(\x0b\x32,.coresdk.workflow_activation.ResolveActivityH\x00\x12G\n\x10notify_has_patch\x18\t \x01(\x0b\x32+.coresdk.workflow_activation.NotifyHasPatchH\x00\x12q\n&resolve_child_workflow_execution_start\x18\n \x01(\x0b\x32?.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartH\x00\x12\x66\n resolve_child_workflow_execution\x18\x0b \x01(\x0b\x32:.coresdk.workflow_activation.ResolveChildWorkflowExecutionH\x00\x12\x66\n resolve_signal_external_workflow\x18\x0c \x01(\x0b\x32:.coresdk.workflow_activation.ResolveSignalExternalWorkflowH\x00\x12u\n(resolve_request_cancel_external_workflow\x18\r \x01(\x0b\x32\x41.coresdk.workflow_activation.ResolveRequestCancelExternalWorkflowH\x00\x12:\n\tdo_update\x18\x0e \x01(\x0b\x32%.coresdk.workflow_activation.DoUpdateH\x00\x12`\n\x1dresolve_nexus_operation_start\x18\x0f \x01(\x0b\x32\x37.coresdk.workflow_activation.ResolveNexusOperationStartH\x00\x12U\n\x17resolve_nexus_operation\x18\x10 \x01(\x0b\x32\x32.coresdk.workflow_activation.ResolveNexusOperationH\x00\x12Q\n\x15resolve_stream_append\x18\x11 \x01(\x0b\x32\x30.coresdk.workflow_activation.ResolveStreamAppendH\x00\x12M\n\x13resolve_stream_read\x18\x12 \x01(\x0b\x32..coresdk.workflow_activation.ResolveStreamReadH\x00\x12I\n\x11remove_from_cache\x18\x32 \x01(\x0b\x32,.coresdk.workflow_activation.RemoveFromCacheH\x00\x42\t\n\x07variant"\xe3\x0b\n\x12InitializeWorkflow\x12\x15\n\rworkflow_type\x18\x01 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x17\n\x0frandomness_seed\x18\x04 \x01(\x04\x12M\n\x07headers\x18\x05 \x03(\x0b\x32<.coresdk.workflow_activation.InitializeWorkflow.HeadersEntry\x12\x10\n\x08identity\x18\x06 \x01(\t\x12I\n\x14parent_workflow_info\x18\x07 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecution\x12=\n\x1aworkflow_execution_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14workflow_run_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\'\n\x1f\x63ontinued_from_execution_run_id\x18\x0b \x01(\t\x12J\n\x13\x63ontinued_initiator\x18\x0c \x01(\x0e\x32-.temporal.api.enums.v1.ContinueAsNewInitiator\x12;\n\x11\x63ontinued_failure\x18\r \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12@\n\x16last_completion_result\x18\x0e \x01(\x0b\x32 .temporal.api.common.v1.Payloads\x12\x1e\n\x16\x66irst_execution_run_id\x18\x0f \x01(\t\x12\x39\n\x0cretry_policy\x18\x10 \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x0f\n\x07\x61ttempt\x18\x11 \x01(\x05\x12\x15\n\rcron_schedule\x18\x12 \x01(\t\x12\x46\n"workflow_execution_expiration_time\x18\x13 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x45\n"cron_schedule_to_schedule_interval\x18\x14 \x01(\x0b\x32\x19.google.protobuf.Duration\x12*\n\x04memo\x18\x15 \x01(\x0b\x32\x1c.temporal.api.common.v1.Memo\x12\x43\n\x11search_attributes\x18\x16 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12.\n\nstart_time\x18\x17 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12@\n\rroot_workflow\x18\x18 \x01(\x0b\x32).temporal.api.common.v1.WorkflowExecution\x12\x32\n\x08priority\x18\x19 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12!\n\x19original_execution_run_id\x18\x1a \x01(\t\x12\x65\n&propagated_nexus_serialization_context\x18\x1b \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x18\n\tFireTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r"m\n\x0fResolveActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12;\n\x06result\x18\x02 \x01(\x0b\x32+.coresdk.activity_result.ActivityResolution\x12\x10\n\x08is_local\x18\x03 \x01(\x08"\xd1\x02\n"ResolveChildWorkflowExecutionStart\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12[\n\tsucceeded\x18\x02 \x01(\x0b\x32\x46.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartSuccessH\x00\x12X\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32\x46.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartFailureH\x00\x12]\n\tcancelled\x18\x04 \x01(\x0b\x32H.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartCancelledH\x00\x42\x08\n\x06status";\n)ResolveChildWorkflowExecutionStartSuccess\x12\x0e\n\x06run_id\x18\x01 \x01(\t"\xa6\x01\n)ResolveChildWorkflowExecutionStartFailure\x12\x13\n\x0bworkflow_id\x18\x01 \x01(\t\x12\x15\n\rworkflow_type\x18\x02 \x01(\t\x12M\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32>.coresdk.child_workflow.StartChildWorkflowExecutionFailedCause"`\n+ResolveChildWorkflowExecutionStartCancelled\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"i\n\x1dResolveChildWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12;\n\x06result\x18\x02 \x01(\x0b\x32+.coresdk.child_workflow.ChildWorkflowResult"+\n\x10UpdateRandomSeed\x12\x17\n\x0frandomness_seed\x18\x01 \x01(\x04"\x84\x02\n\rQueryWorkflow\x12\x10\n\x08query_id\x18\x01 \x01(\t\x12\x12\n\nquery_type\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12H\n\x07headers\x18\x05 \x03(\x0b\x32\x37.coresdk.workflow_activation.QueryWorkflow.HeadersEntry\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01" \n\x0e\x43\x61ncelWorkflow\x12\x0e\n\x06reason\x18\x01 \x01(\t"\xa1\x02\n\x0eSignalWorkflow\x12\x13\n\x0bsignal_name\x18\x01 \x01(\t\x12.\n\x05input\x18\x02 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x10\n\x08identity\x18\x03 \x01(\t\x12I\n\x07headers\x18\x05 \x03(\x0b\x32\x38.coresdk.workflow_activation.SignalWorkflow.HeadersEntry\x12\x1c\n\x14originating_event_id\x18\x06 \x01(\x03\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01""\n\x0eNotifyHasPatch\x12\x10\n\x08patch_id\x18\x01 \x01(\t"\xb1\x01\n\x1dResolveSignalExternalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x07\x66\x61ilure\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12P\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32\x41.temporal.api.enums.v1.SignalExternalWorkflowExecutionFailedCause"\xb8\x01\n$ResolveRequestCancelExternalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x07\x66\x61ilure\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12P\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32\x41.temporal.api.enums.v1.CancelExternalWorkflowExecutionFailedCause"\xb2\x03\n\x08\x44oUpdate\x12\n\n\x02id\x18\x01 \x01(\t\x12\x1c\n\x14protocol_instance_id\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12.\n\x05input\x18\x04 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x43\n\x07headers\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.DoUpdate.HeadersEntry\x12*\n\x04meta\x18\x06 \x01(\x0b\x32\x1c.temporal.api.update.v1.Meta\x12\x15\n\rrun_validator\x18\x07 \x01(\x08\x12\x65\n&propagated_nexus_serialization_context\x18\x08 \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x9a\x01\n\x1aResolveNexusOperationStart\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x19\n\x0foperation_token\x18\x02 \x01(\tH\x00\x12\x16\n\x0cstarted_sync\x18\x03 \x01(\x08H\x00\x12\x32\n\x06\x66\x61iled\x18\x04 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status"Y\n\x15ResolveNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x33\n\x06result\x18\x02 \x01(\x0b\x32#.coresdk.nexus.NexusOperationResult"\xe0\x02\n\x0fRemoveFromCache\x12\x0f\n\x07message\x18\x01 \x01(\t\x12K\n\x06reason\x18\x02 \x01(\x0e\x32;.coresdk.workflow_activation.RemoveFromCache.EvictionReason"\xee\x01\n\x0e\x45victionReason\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nCACHE_FULL\x10\x01\x12\x0e\n\nCACHE_MISS\x10\x02\x12\x12\n\x0eNONDETERMINISM\x10\x03\x12\r\n\tLANG_FAIL\x10\x04\x12\x12\n\x0eLANG_REQUESTED\x10\x05\x12\x12\n\x0eTASK_NOT_FOUND\x10\x06\x12\x15\n\x11UNHANDLED_COMMAND\x10\x07\x12\t\n\x05\x46\x41TAL\x10\x08\x12\x1f\n\x1bPAGINATION_OR_HISTORY_FETCH\x10\t\x12\x1d\n\x19WORKFLOW_EXECUTION_ENDING\x10\n"\xa1\x01\n\x13ResolveStreamAppend\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12?\n\x08\x61ppended\x18\x02 \x01(\x0b\x32+.coresdk.workflow_activation.StreamAppendedH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status";\n\x0eStreamAppended\x12\x14\n\x0c\x66irst_offset\x18\x01 \x01(\x0c\x12\x13\n\x0blast_offset\x18\x02 \x01(\x0c"\x97\x01\n\x11ResolveStreamRead\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x37\n\x04page\x18\x02 \x01(\x0b\x32\'.coresdk.workflow_activation.StreamPageH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status"U\n\nStreamPage\x12\x35\n\x07records\x18\x01 \x03(\x0b\x32$.temporal.api.stream.v1.StreamRecord\x12\x10\n\x08wait_cut\x18\x03 \x01(\x08\x42\x38\xea\x02\x35Temporalio::Internal::Bridge::Api::WorkflowActivationb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -67,60 +70,64 @@ _SIGNALWORKFLOW_HEADERSENTRY._serialized_options = b"8\001" _DOUPDATE_HEADERSENTRY._options = None _DOUPDATE_HEADERSENTRY._serialized_options = b"8\001" - _WORKFLOWACTIVATION._serialized_start = 611 - _WORKFLOWACTIVATION._serialized_end = 1157 - _WORKFLOWACTIVATIONJOB._serialized_start = 1160 - _WORKFLOWACTIVATIONJOB._serialized_end = 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 + _WORKFLOWACTIVATION._serialized_start = 649 + _WORKFLOWACTIVATION._serialized_end = 1195 + _WORKFLOWACTIVATIONJOB._serialized_start = 1198 + _WORKFLOWACTIVATIONJOB._serialized_end = 2736 + _INITIALIZEWORKFLOW._serialized_start = 2739 + _INITIALIZEWORKFLOW._serialized_end = 4246 + _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_start = 4167 + _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_end = 4246 + _FIRETIMER._serialized_start = 4248 + _FIRETIMER._serialized_end = 4272 + _RESOLVEACTIVITY._serialized_start = 4274 + _RESOLVEACTIVITY._serialized_end = 4383 + _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_start = 4386 + _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_end = 4723 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_start = 4725 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_end = 4784 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_start = 4787 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_end = 4953 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_start = 4955 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_end = 5051 + _RESOLVECHILDWORKFLOWEXECUTION._serialized_start = 5053 + _RESOLVECHILDWORKFLOWEXECUTION._serialized_end = 5158 + _UPDATERANDOMSEED._serialized_start = 5160 + _UPDATERANDOMSEED._serialized_end = 5203 + _QUERYWORKFLOW._serialized_start = 5206 + _QUERYWORKFLOW._serialized_end = 5466 + _QUERYWORKFLOW_HEADERSENTRY._serialized_start = 4167 + _QUERYWORKFLOW_HEADERSENTRY._serialized_end = 4246 + _CANCELWORKFLOW._serialized_start = 5468 + _CANCELWORKFLOW._serialized_end = 5500 + _SIGNALWORKFLOW._serialized_start = 5503 + _SIGNALWORKFLOW._serialized_end = 5792 + _SIGNALWORKFLOW_HEADERSENTRY._serialized_start = 4167 + _SIGNALWORKFLOW_HEADERSENTRY._serialized_end = 4246 + _NOTIFYHASPATCH._serialized_start = 5794 + _NOTIFYHASPATCH._serialized_end = 5828 + _RESOLVESIGNALEXTERNALWORKFLOW._serialized_start = 5831 + _RESOLVESIGNALEXTERNALWORKFLOW._serialized_end = 6008 + _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_start = 6011 + _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_end = 6195 + _DOUPDATE._serialized_start = 6198 + _DOUPDATE._serialized_end = 6632 + _DOUPDATE_HEADERSENTRY._serialized_start = 4167 + _DOUPDATE_HEADERSENTRY._serialized_end = 4246 + _RESOLVENEXUSOPERATIONSTART._serialized_start = 6635 + _RESOLVENEXUSOPERATIONSTART._serialized_end = 6789 + _RESOLVENEXUSOPERATION._serialized_start = 6791 + _RESOLVENEXUSOPERATION._serialized_end = 6880 + _REMOVEFROMCACHE._serialized_start = 6883 + _REMOVEFROMCACHE._serialized_end = 7235 + _REMOVEFROMCACHE_EVICTIONREASON._serialized_start = 6997 + _REMOVEFROMCACHE_EVICTIONREASON._serialized_end = 7235 + _RESOLVESTREAMAPPEND._serialized_start = 7238 + _RESOLVESTREAMAPPEND._serialized_end = 7399 + _STREAMAPPENDED._serialized_start = 7401 + _STREAMAPPENDED._serialized_end = 7460 + _RESOLVESTREAMREAD._serialized_start = 7463 + _RESOLVESTREAMREAD._serialized_end = 7614 + _STREAMPAGE._serialized_start = 7616 + _STREAMPAGE._serialized_end = 7701 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi index 07d3bd2b0..6e533fe5d 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi @@ -23,6 +23,7 @@ import temporalio.api.enums.v1.failed_cause_pb2 import temporalio.api.enums.v1.workflow_pb2 import temporalio.api.failure.v1.message_pb2 import temporalio.api.nexus.v1.message_pb2 +import temporalio.api.stream.v1.message_pb2 import temporalio.api.update.v1.message_pb2 import temporalio.bridge.proto.activity_result.activity_result_pb2 import temporalio.bridge.proto.child_workflow.child_workflow_pb2 @@ -69,7 +70,8 @@ class WorkflowActivation(google.protobuf.message.Message): 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. + Stream results come first, appends before reads and each kind 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 @@ -256,6 +258,7 @@ class WorkflowActivationJob(google.protobuf.message.Message): RESOLVE_NEXUS_OPERATION_START_FIELD_NUMBER: builtins.int RESOLVE_NEXUS_OPERATION_FIELD_NUMBER: builtins.int RESOLVE_STREAM_APPEND_FIELD_NUMBER: builtins.int + RESOLVE_STREAM_READ_FIELD_NUMBER: builtins.int REMOVE_FROM_CACHE_FIELD_NUMBER: builtins.int @property def initialize_workflow(self) -> global___InitializeWorkflow: @@ -334,6 +337,10 @@ class WorkflowActivationJob(google.protobuf.message.Message): def resolve_stream_append(self) -> global___ResolveStreamAppend: """An append to a Stream finished.""" + @property + def resolve_stream_read(self) -> global___ResolveStreamRead: + """A read of a Stream finished.""" + @property def remove_from_cache(self) -> global___RemoveFromCache: """Remove the workflow identified by the [WorkflowActivation] containing this job from the @@ -364,6 +371,7 @@ class WorkflowActivationJob(google.protobuf.message.Message): resolve_nexus_operation_start: global___ResolveNexusOperationStart | None = ..., resolve_nexus_operation: global___ResolveNexusOperation | None = ..., resolve_stream_append: global___ResolveStreamAppend | None = ..., + resolve_stream_read: global___ResolveStreamRead | None = ..., remove_from_cache: global___RemoveFromCache | None = ..., ) -> None: ... def HasField( @@ -399,6 +407,8 @@ class WorkflowActivationJob(google.protobuf.message.Message): b"resolve_signal_external_workflow", "resolve_stream_append", b"resolve_stream_append", + "resolve_stream_read", + b"resolve_stream_read", "signal_workflow", b"signal_workflow", "update_random_seed", @@ -440,6 +450,8 @@ class WorkflowActivationJob(google.protobuf.message.Message): b"resolve_signal_external_workflow", "resolve_stream_append", b"resolve_stream_append", + "resolve_stream_read", + b"resolve_stream_read", "signal_workflow", b"signal_workflow", "update_random_seed", @@ -468,6 +480,7 @@ class WorkflowActivationJob(google.protobuf.message.Message): "resolve_nexus_operation_start", "resolve_nexus_operation", "resolve_stream_append", + "resolve_stream_read", "remove_from_cache", ] | None @@ -1738,3 +1751,85 @@ class StreamAppended(google.protobuf.message.Message): ) -> None: ... global___StreamAppended = StreamAppended + +@typing.final +class ResolveStreamRead(google.protobuf.message.Message): + """The result of a `ReadStream` command. Each command gets one result, unless the command that ends + the Workflow drops the read. The ordering rule for these jobs is in `WorkflowActivation`. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + PAGE_FIELD_NUMBER: builtins.int + FAILED_FIELD_NUMBER: builtins.int + seq: builtins.int + """The `seq` of the `ReadStream` command.""" + @property + def page(self) -> global___StreamPage: ... + @property + def failed(self) -> temporalio.api.failure.v1.message_pb2.Failure: + """Why the read failed. It has the same form as the `failed` of a `ResolveStreamAppend`.""" + + def __init__( + self, + *, + seq: builtins.int = ..., + page: global___StreamPage | None = ..., + failed: temporalio.api.failure.v1.message_pb2.Failure | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "failed", b"failed", "page", b"page", "status", b"status" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "failed", b"failed", "page", b"page", "seq", b"seq", "status", b"status" + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["status", b"status"] + ) -> typing.Literal["page", "failed"] | None: ... + +global___ResolveStreamRead = ResolveStreamRead + +@typing.final +class StreamPage(google.protobuf.message.Message): + """One page of Records.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RECORDS_FIELD_NUMBER: builtins.int + WAIT_CUT_FIELD_NUMBER: builtins.int + wait_cut: builtins.bool + """True if the page has no Record because the read time of the Workflow Task ended the wait of + the read early. A reader that still wants a Record reads again from the same `after_offset`. + It's false for a page that comes at the end of the whole `wait`. + """ + @property + def records( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + temporalio.api.stream.v1.message_pb2.StreamRecord + ]: + """The Records of the page, in the order of the Stream. The page has no Record if none came + while the read waited. + """ + + def __init__( + self, + *, + records: collections.abc.Iterable[ + temporalio.api.stream.v1.message_pb2.StreamRecord + ] + | None = ..., + wait_cut: builtins.bool = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["records", b"records", "wait_cut", b"wait_cut"] + ) -> None: ... + +global___StreamPage = StreamPage diff --git a/temporalio/bridge/proto/workflow_commands/__init__.py b/temporalio/bridge/proto/workflow_commands/__init__.py index 0b2f25566..280eb77ab 100644 --- a/temporalio/bridge/proto/workflow_commands/__init__.py +++ b/temporalio/bridge/proto/workflow_commands/__init__.py @@ -11,6 +11,7 @@ ModifyWorkflowProperties, QueryResult, QuerySuccess, + ReadStream, RequestCancelActivity, RequestCancelExternalWorkflowExecution, RequestCancelLocalActivity, @@ -40,6 +41,7 @@ "ModifyWorkflowProperties", "QueryResult", "QuerySuccess", + "ReadStream", "RequestCancelActivity", "RequestCancelExternalWorkflowExecution", "RequestCancelLocalActivity", diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py index 64a58bbb3..6c0bf51cc 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py @@ -49,7 +49,7 @@ ) DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n;temporal/sdk/core/workflow_commands/workflow_commands.proto\x12\x19\x63oresdk.workflow_commands\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a$temporal/api/common/v1/message.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a%temporal/api/failure/v1/message.proto\x1a\'temporal/api/sdk/v1/user_metadata.proto\x1a,temporal/api/sdk/v1/event_group_marker.proto\x1a temporal/api/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' + b'\n;temporal/sdk/core/workflow_commands/workflow_commands.proto\x12\x19\x63oresdk.workflow_commands\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a$temporal/api/common/v1/message.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a%temporal/api/failure/v1/message.proto\x1a\'temporal/api/sdk/v1/user_metadata.proto\x1a,temporal/api/sdk/v1/event_group_marker.proto\x1a temporal/api/sdk/v1/stream.proto\x1a&temporal/api/workflow/v1/message.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a#temporal/sdk/core/nexus/nexus.proto\x1a%temporal/sdk/core/common/common.proto"\xae\x11\n\x0fWorkflowCommand\x12\x38\n\ruser_metadata\x18\x64 \x01(\x0b\x32!.temporal.api.sdk.v1.UserMetadata\x12\x42\n\x13\x65vent_group_markers\x18\x65 \x03(\x0b\x32%.temporal.api.sdk.v1.EventGroupMarker\x12<\n\x0bstart_timer\x18\x01 \x01(\x0b\x32%.coresdk.workflow_commands.StartTimerH\x00\x12H\n\x11schedule_activity\x18\x02 \x01(\x0b\x32+.coresdk.workflow_commands.ScheduleActivityH\x00\x12\x42\n\x10respond_to_query\x18\x03 \x01(\x0b\x32&.coresdk.workflow_commands.QueryResultH\x00\x12S\n\x17request_cancel_activity\x18\x04 \x01(\x0b\x32\x30.coresdk.workflow_commands.RequestCancelActivityH\x00\x12>\n\x0c\x63\x61ncel_timer\x18\x05 \x01(\x0b\x32&.coresdk.workflow_commands.CancelTimerH\x00\x12[\n\x1b\x63omplete_workflow_execution\x18\x06 \x01(\x0b\x32\x34.coresdk.workflow_commands.CompleteWorkflowExecutionH\x00\x12S\n\x17\x66\x61il_workflow_execution\x18\x07 \x01(\x0b\x32\x30.coresdk.workflow_commands.FailWorkflowExecutionH\x00\x12g\n"continue_as_new_workflow_execution\x18\x08 \x01(\x0b\x32\x39.coresdk.workflow_commands.ContinueAsNewWorkflowExecutionH\x00\x12W\n\x19\x63\x61ncel_workflow_execution\x18\t \x01(\x0b\x32\x32.coresdk.workflow_commands.CancelWorkflowExecutionH\x00\x12\x45\n\x10set_patch_marker\x18\n \x01(\x0b\x32).coresdk.workflow_commands.SetPatchMarkerH\x00\x12`\n\x1estart_child_workflow_execution\x18\x0b \x01(\x0b\x32\x36.coresdk.workflow_commands.StartChildWorkflowExecutionH\x00\x12\x62\n\x1f\x63\x61ncel_child_workflow_execution\x18\x0c \x01(\x0b\x32\x37.coresdk.workflow_commands.CancelChildWorkflowExecutionH\x00\x12w\n*request_cancel_external_workflow_execution\x18\r \x01(\x0b\x32\x41.coresdk.workflow_commands.RequestCancelExternalWorkflowExecutionH\x00\x12h\n"signal_external_workflow_execution\x18\x0e \x01(\x0b\x32:.coresdk.workflow_commands.SignalExternalWorkflowExecutionH\x00\x12Q\n\x16\x63\x61ncel_signal_workflow\x18\x0f \x01(\x0b\x32/.coresdk.workflow_commands.CancelSignalWorkflowH\x00\x12S\n\x17schedule_local_activity\x18\x10 \x01(\x0b\x32\x30.coresdk.workflow_commands.ScheduleLocalActivityH\x00\x12^\n\x1drequest_cancel_local_activity\x18\x11 \x01(\x0b\x32\x35.coresdk.workflow_commands.RequestCancelLocalActivityH\x00\x12\x66\n!upsert_workflow_search_attributes\x18\x12 \x01(\x0b\x32\x39.coresdk.workflow_commands.UpsertWorkflowSearchAttributesH\x00\x12Y\n\x1amodify_workflow_properties\x18\x13 \x01(\x0b\x32\x33.coresdk.workflow_commands.ModifyWorkflowPropertiesH\x00\x12\x44\n\x0fupdate_response\x18\x14 \x01(\x0b\x32).coresdk.workflow_commands.UpdateResponseH\x00\x12U\n\x18schedule_nexus_operation\x18\x15 \x01(\x0b\x32\x31.coresdk.workflow_commands.ScheduleNexusOperationH\x00\x12`\n\x1erequest_cancel_nexus_operation\x18\x16 \x01(\x0b\x32\x36.coresdk.workflow_commands.RequestCancelNexusOperationH\x00\x12\x45\n\x10\x61ppend_to_stream\x18\x17 \x01(\x0b\x32).coresdk.workflow_commands.AppendToStreamH\x00\x12<\n\x0bread_stream\x18\x18 \x01(\x0b\x32%.coresdk.workflow_commands.ReadStreamH\x00\x42\t\n\x07variant"S\n\nStartTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x38\n\x15start_to_fire_timeout\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration"\x1a\n\x0b\x43\x61ncelTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r"\xb8\x06\n\x10ScheduleActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x15\n\ractivity_type\x18\x03 \x01(\t\x12\x12\n\ntask_queue\x18\x05 \x01(\t\x12I\n\x07headers\x18\x06 \x03(\x0b\x32\x38.coresdk.workflow_commands.ScheduleActivity.HeadersEntry\x12\x32\n\targuments\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x34\n\x11heartbeat_timeout\x18\x0b \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x0c \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12N\n\x11\x63\x61ncellation_type\x18\r \x01(\x0e\x32\x33.coresdk.workflow_commands.ActivityCancellationType\x12\x1e\n\x16\x64o_not_eagerly_execute\x18\x0e \x01(\x08\x12;\n\x11versioning_intent\x18\x0f \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12\x32\n\x08priority\x18\x10 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\xd7\x06\n\x15ScheduleLocalActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x15\n\ractivity_type\x18\x03 \x01(\t\x12\x0f\n\x07\x61ttempt\x18\x04 \x01(\r\x12:\n\x16original_schedule_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12N\n\x07headers\x18\x06 \x03(\x0b\x32=.coresdk.workflow_commands.ScheduleLocalActivity.HeadersEntry\x12\x32\n\targuments\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x0b \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x38\n\x15local_retry_threshold\x18\x0c \x01(\x0b\x32\x19.google.protobuf.Duration\x12N\n\x11\x63\x61ncellation_type\x18\r \x01(\x0e\x32\x33.coresdk.workflow_commands.ActivityCancellationType\x12#\n\x1binclude_arguments_in_marker\x18\x0e \x01(\x08\x12\x42\n\x15local_activity_origin\x18\x0f \x01(\x0b\x32#.coresdk.common.LocalActivityOrigin\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"$\n\x15RequestCancelActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r")\n\x1aRequestCancelLocalActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r"\x9c\x01\n\x0bQueryResult\x12\x10\n\x08query_id\x18\x01 \x01(\t\x12<\n\tsucceeded\x18\x02 \x01(\x0b\x32\'.coresdk.workflow_commands.QuerySuccessH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\t\n\x07variant"A\n\x0cQuerySuccess\x12\x31\n\x08response\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"L\n\x19\x43ompleteWorkflowExecution\x12/\n\x06result\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"J\n\x15\x46\x61ilWorkflowExecution\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"\x92\x07\n\x1e\x43ontinueAsNewWorkflowExecution\x12\x15\n\rworkflow_type\x18\x01 \x01(\t\x12\x12\n\ntask_queue\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x37\n\x14workflow_run_timeout\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12Q\n\x04memo\x18\x06 \x03(\x0b\x32\x43.coresdk.workflow_commands.ContinueAsNewWorkflowExecution.MemoEntry\x12W\n\x07headers\x18\x07 \x03(\x0b\x32\x46.coresdk.workflow_commands.ContinueAsNewWorkflowExecution.HeadersEntry\x12\x43\n\x11search_attributes\x18\x08 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12\x39\n\x0cretry_policy\x18\t \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12;\n\x11versioning_intent\x18\n \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12[\n\x1binitial_versioning_behavior\x18\x0b \x01(\x0e\x32\x36.temporal.api.enums.v1.ContinueAsNewVersioningBehavior\x12\x39\n\x16\x62\x61\x63koff_start_interval\x18\x0c \x01(\x0b\x32\x19.google.protobuf.Duration\x1aL\n\tMemoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"L\n\x17\x43\x61ncelWorkflowExecution\x12\x31\n\x07\x64\x65tails\x18\x01 \x01(\x0b\x32 .temporal.api.common.v1.Payloads"6\n\x0eSetPatchMarker\x12\x10\n\x08patch_id\x18\x01 \x01(\t\x12\x12\n\ndeprecated\x18\x02 \x01(\x08"\xe1\t\n\x1bStartChildWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x11\n\tnamespace\x18\x02 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x03 \x01(\t\x12\x15\n\rworkflow_type\x18\x04 \x01(\t\x12\x12\n\ntask_queue\x18\x05 \x01(\t\x12.\n\x05input\x18\x06 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12=\n\x1aworkflow_execution_timeout\x18\x07 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14workflow_run_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x46\n\x13parent_close_policy\x18\n \x01(\x0e\x32).coresdk.child_workflow.ParentClosePolicy\x12N\n\x18workflow_id_reuse_policy\x18\x0c \x01(\x0e\x32,.temporal.api.enums.v1.WorkflowIdReusePolicy\x12\x39\n\x0cretry_policy\x18\r \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x15\n\rcron_schedule\x18\x0e \x01(\t\x12T\n\x07headers\x18\x0f \x03(\x0b\x32\x43.coresdk.workflow_commands.StartChildWorkflowExecution.HeadersEntry\x12N\n\x04memo\x18\x10 \x03(\x0b\x32@.coresdk.workflow_commands.StartChildWorkflowExecution.MemoEntry\x12\x43\n\x11search_attributes\x18\x11 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12P\n\x11\x63\x61ncellation_type\x18\x12 \x01(\x0e\x32\x35.coresdk.child_workflow.ChildWorkflowCancellationType\x12;\n\x11versioning_intent\x18\x13 \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12\x32\n\x08priority\x18\x14 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12I\n\x13versioning_override\x18\x15 \x01(\x0b\x32,.temporal.api.workflow.v1.VersioningOverride\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x1aL\n\tMemoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"J\n\x1c\x43\x61ncelChildWorkflowExecution\x12\x1a\n\x12\x63hild_workflow_seq\x18\x01 \x01(\r\x12\x0e\n\x06reason\x18\x02 \x01(\t"\x8e\x01\n&RequestCancelExternalWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12G\n\x12workflow_execution\x18\x02 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecution\x12\x0e\n\x06reason\x18\x03 \x01(\t"\x8f\x03\n\x1fSignalExternalWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12I\n\x12workflow_execution\x18\x02 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecutionH\x00\x12\x1b\n\x11\x63hild_workflow_id\x18\x03 \x01(\tH\x00\x12\x13\n\x0bsignal_name\x18\x04 \x01(\t\x12-\n\x04\x61rgs\x18\x05 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12X\n\x07headers\x18\x06 \x03(\x0b\x32G.coresdk.workflow_commands.SignalExternalWorkflowExecution.HeadersEntry\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x42\x08\n\x06target"#\n\x14\x43\x61ncelSignalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r"e\n\x1eUpsertWorkflowSearchAttributes\x12\x43\n\x11search_attributes\x18\x01 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes"O\n\x18ModifyWorkflowProperties\x12\x33\n\rupserted_memo\x18\x01 \x01(\x0b\x32\x1c.temporal.api.common.v1.Memo"\xd2\x01\n\x0eUpdateResponse\x12\x1c\n\x14protocol_instance_id\x18\x01 \x01(\t\x12*\n\x08\x61\x63\x63\x65pted\x18\x02 \x01(\x0b\x32\x16.google.protobuf.EmptyH\x00\x12\x34\n\x08rejected\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x12\x34\n\tcompleted\x18\x04 \x01(\x0b\x32\x1f.temporal.api.common.v1.PayloadH\x00\x42\n\n\x08response"\x9a\x04\n\x16ScheduleNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x10\n\x08\x65ndpoint\x18\x02 \x01(\t\x12\x0f\n\x07service\x18\x03 \x01(\t\x12\x11\n\toperation\x18\x04 \x01(\t\x12.\n\x05input\x18\x05 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x06 \x01(\x0b\x32\x19.google.protobuf.Duration\x12X\n\x0cnexus_header\x18\x07 \x03(\x0b\x32\x42.coresdk.workflow_commands.ScheduleNexusOperation.NexusHeaderEntry\x12H\n\x11\x63\x61ncellation_type\x18\x08 \x01(\x0e\x32-.coresdk.nexus.NexusOperationCancellationType\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x1a\x32\n\x10NexusHeaderEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"*\n\x1bRequestCancelNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r"~\n\x0e\x41ppendToStream\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12.\n\x06stream\x18\x02 \x01(\x0b\x32\x1e.temporal.api.sdk.v1.StreamRef\x12/\n\x06\x62odies\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload"\xb0\x01\n\nReadStream\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12.\n\x06stream\x18\x02 \x01(\x0b\x32\x1e.temporal.api.sdk.v1.StreamRef\x12\x14\n\x0c\x61\x66ter_offset\x18\x03 \x01(\x0c\x12\'\n\x04wait\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x13\n\x0bmax_records\x18\x05 \x01(\x05\x12\x11\n\tmax_bytes\x18\x06 \x01(\x03*X\n\x18\x41\x63tivityCancellationType\x12\x0e\n\nTRY_CANCEL\x10\x00\x12\x1f\n\x1bWAIT_CANCELLATION_COMPLETED\x10\x01\x12\x0b\n\x07\x41\x42\x41NDON\x10\x02\x42\x36\xea\x02\x33Temporalio::Internal::Bridge::Api::WorkflowCommandsb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -75,72 +75,74 @@ _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_options = b"8\001" _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._options = None _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_options = b"8\001" - _ACTIVITYCANCELLATIONTYPE._serialized_start = 9086 - _ACTIVITYCANCELLATIONTYPE._serialized_end = 9174 + _ACTIVITYCANCELLATIONTYPE._serialized_start = 9327 + _ACTIVITYCANCELLATIONTYPE._serialized_end = 9415 _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 + _WORKFLOWCOMMAND._serialized_end = 2814 + _STARTTIMER._serialized_start = 2816 + _STARTTIMER._serialized_end = 2899 + _CANCELTIMER._serialized_start = 2901 + _CANCELTIMER._serialized_end = 2927 + _SCHEDULEACTIVITY._serialized_start = 2930 + _SCHEDULEACTIVITY._serialized_end = 3754 + _SCHEDULEACTIVITY_HEADERSENTRY._serialized_start = 3675 + _SCHEDULEACTIVITY_HEADERSENTRY._serialized_end = 3754 + _SCHEDULELOCALACTIVITY._serialized_start = 3757 + _SCHEDULELOCALACTIVITY._serialized_end = 4612 + _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_start = 3675 + _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_end = 3754 + _REQUESTCANCELACTIVITY._serialized_start = 4614 + _REQUESTCANCELACTIVITY._serialized_end = 4650 + _REQUESTCANCELLOCALACTIVITY._serialized_start = 4652 + _REQUESTCANCELLOCALACTIVITY._serialized_end = 4693 + _QUERYRESULT._serialized_start = 4696 + _QUERYRESULT._serialized_end = 4852 + _QUERYSUCCESS._serialized_start = 4854 + _QUERYSUCCESS._serialized_end = 4919 + _COMPLETEWORKFLOWEXECUTION._serialized_start = 4921 + _COMPLETEWORKFLOWEXECUTION._serialized_end = 4997 + _FAILWORKFLOWEXECUTION._serialized_start = 4999 + _FAILWORKFLOWEXECUTION._serialized_end = 5073 + _CONTINUEASNEWWORKFLOWEXECUTION._serialized_start = 5076 + _CONTINUEASNEWWORKFLOWEXECUTION._serialized_end = 5990 + _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5833 + _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5909 + _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3675 + _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3754 + _CANCELWORKFLOWEXECUTION._serialized_start = 5992 + _CANCELWORKFLOWEXECUTION._serialized_end = 6068 + _SETPATCHMARKER._serialized_start = 6070 + _SETPATCHMARKER._serialized_end = 6124 + _STARTCHILDWORKFLOWEXECUTION._serialized_start = 6127 + _STARTCHILDWORKFLOWEXECUTION._serialized_end = 7376 + _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3675 + _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3754 + _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5833 + _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5909 + _CANCELCHILDWORKFLOWEXECUTION._serialized_start = 7378 + _CANCELCHILDWORKFLOWEXECUTION._serialized_end = 7452 + _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_start = 7455 + _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_end = 7597 + _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_start = 7600 + _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_end = 7999 + _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3675 + _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3754 + _CANCELSIGNALWORKFLOW._serialized_start = 8001 + _CANCELSIGNALWORKFLOW._serialized_end = 8036 + _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_start = 8038 + _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_end = 8139 + _MODIFYWORKFLOWPROPERTIES._serialized_start = 8141 + _MODIFYWORKFLOWPROPERTIES._serialized_end = 8220 + _UPDATERESPONSE._serialized_start = 8223 + _UPDATERESPONSE._serialized_end = 8433 + _SCHEDULENEXUSOPERATION._serialized_start = 8436 + _SCHEDULENEXUSOPERATION._serialized_end = 8974 + _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_start = 8924 + _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_end = 8974 + _REQUESTCANCELNEXUSOPERATION._serialized_start = 8976 + _REQUESTCANCELNEXUSOPERATION._serialized_end = 9018 + _APPENDTOSTREAM._serialized_start = 9020 + _APPENDTOSTREAM._serialized_end = 9146 + _READSTREAM._serialized_start = 9149 + _READSTREAM._serialized_end = 9325 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi index 99a25a278..58295be55 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi @@ -107,6 +107,7 @@ class WorkflowCommand(google.protobuf.message.Message): SCHEDULE_NEXUS_OPERATION_FIELD_NUMBER: builtins.int REQUEST_CANCEL_NEXUS_OPERATION_FIELD_NUMBER: builtins.int APPEND_TO_STREAM_FIELD_NUMBER: builtins.int + READ_STREAM_FIELD_NUMBER: builtins.int @property def user_metadata(self) -> temporalio.api.sdk.v1.user_metadata_pb2.UserMetadata: """User metadata that may or may not be persisted into history depending on the command type. @@ -185,6 +186,8 @@ class WorkflowCommand(google.protobuf.message.Message): ) -> global___RequestCancelNexusOperation: ... @property def append_to_stream(self) -> global___AppendToStream: ... + @property + def read_stream(self) -> global___ReadStream: ... def __init__( self, *, @@ -224,6 +227,7 @@ class WorkflowCommand(google.protobuf.message.Message): request_cancel_nexus_operation: global___RequestCancelNexusOperation | None = ..., append_to_stream: global___AppendToStream | None = ..., + read_stream: global___ReadStream | None = ..., ) -> None: ... def HasField( self, @@ -246,6 +250,8 @@ class WorkflowCommand(google.protobuf.message.Message): b"fail_workflow_execution", "modify_workflow_properties", b"modify_workflow_properties", + "read_stream", + b"read_stream", "request_cancel_activity", b"request_cancel_activity", "request_cancel_external_workflow_execution", @@ -303,6 +309,8 @@ class WorkflowCommand(google.protobuf.message.Message): b"fail_workflow_execution", "modify_workflow_properties", b"modify_workflow_properties", + "read_stream", + b"read_stream", "request_cancel_activity", b"request_cancel_activity", "request_cancel_external_workflow_execution", @@ -364,6 +372,7 @@ class WorkflowCommand(google.protobuf.message.Message): "schedule_nexus_operation", "request_cancel_nexus_operation", "append_to_stream", + "read_stream", ] | None ): ... @@ -2012,3 +2021,104 @@ class AppendToStream(google.protobuf.message.Message): ) -> None: ... global___AppendToStream = AppendToStream + +@typing.final +class ReadStream(google.protobuf.message.Message): + """Reads one page of Records from a Stream. Core gives the page in a `ResolveStreamRead` job. To + read on, lang sends the next `ReadStream` with the offset of the last Record that it got. An + application Record tells a reader where to stop. + + * Order. `ResolveStreamRead` jobs follow the ordering rule of `ResolveStreamAppend` jobs. + * Wait. A read gives its page as soon as the Stream has a Record after `after_offset`. A read + with a `wait` on a Stream that has none asks the Store again, at most once in 100 ms, until a + Record comes or the wait is over. A read with no `wait` gives the answer of the Store, which + can be a page with no Record. + * Read time. The reads of a Workflow Task keep the task waiting only for its read time, + `StreamSettings.read_time`. The default is half the Workflow Task timeout, and the time + starts when the replay of the task is over. A read whose wait the read time ends gives a page + with no Record and with `wait_cut` set. The read time doesn't end a read with no `wait`. + * Completion. Before a Workflow Task completes, each read with no answer gets one Store call + with no wait and with a deadline of one second. A task with a command or a message for the + server waits for nothing else. Records that this call gives while such a command waits come + in the next Workflow Task. A read with a `wait` that still has no Record goes on in a later + Workflow Task. A Stream with no new Record never makes Core ask for a Workflow Task. + * Limits. One Workflow Task gives at most 16 MiB of Records. After 256 read results in one + Workflow Task, a new read starts in the next one, and a read that already runs can finish. A + Record over 16 MiB resolves its read with a `stream_unsupported` failure. + * Failures. A read that the Store refuses resolves with a failure. A Store outage, or a Store + that doesn't answer the call before the completion, fails the Workflow Task with + `StreamStoreUnavailable`. So does a Worker with no runtime for the Store. A negative + `max_records`, `max_bytes` or `wait`, an `after_offset` over 1024 bytes, and a `seq` or + `stream` that isn't valid also fail the Workflow Task. + * Replay. Core takes the result that History has for the `seq`. A command with another Stream + or another `after_offset` than History has is a nondeterminism error. Core reads the Records + of the page from the Store again and checks their count and their digest. So the Store must + keep the Records for as long as the Workflow can replay or answer a query. Records that are + gone or changed give a `StreamReplayError`. A Store that is unavailable, and a Worker with no + runtime for the Store, fail the Workflow Task or the legacy query. Core reads the Records of + a long History in parts. + * Store. A `stream` with no Store name gets its Store as for `AppendToStream`. + * End of the Workflow. The command that ends the Workflow drops each read that has no result + yet. Lang must also accept a result that it no longer waits for. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + STREAM_FIELD_NUMBER: builtins.int + AFTER_OFFSET_FIELD_NUMBER: builtins.int + WAIT_FIELD_NUMBER: builtins.int + MAX_RECORDS_FIELD_NUMBER: builtins.int + MAX_BYTES_FIELD_NUMBER: builtins.int + seq: builtins.int + """Lang's incremental sequence number for reads. It starts at 1.""" + after_offset: builtins.bytes + """The page has the Records after this offset. With no offset, the page starts at the beginning + of the Stream. + """ + max_records: builtins.int + """The maximum number of Records in the page. Zero is 256.""" + max_bytes: builtins.int + """The maximum size of the Records in the page, in bytes. Zero is 4 MiB. A page can have one + Record over this size, up to the 16 MiB of a Workflow Task. + """ + @property + def stream(self) -> temporalio.api.sdk.v1.stream_pb2.StreamRef: ... + @property + def wait(self) -> google.protobuf.duration_pb2.Duration: + """How long the read waits for a Record if the Stream has none after `after_offset`. With no + `wait`, the read doesn't wait. + """ + + def __init__( + self, + *, + seq: builtins.int = ..., + stream: temporalio.api.sdk.v1.stream_pb2.StreamRef | None = ..., + after_offset: builtins.bytes = ..., + wait: google.protobuf.duration_pb2.Duration | None = ..., + max_records: builtins.int = ..., + max_bytes: builtins.int = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["stream", b"stream", "wait", b"wait"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "after_offset", + b"after_offset", + "max_bytes", + b"max_bytes", + "max_records", + b"max_records", + "seq", + b"seq", + "stream", + b"stream", + "wait", + b"wait", + ], + ) -> None: ... + +global___ReadStream = ReadStream diff --git a/temporalio/bridge/sdk-core b/temporalio/bridge/sdk-core index ebc220967..995a018fd 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit ebc220967cecdb67bcbb57fdbd57ef1b84085b8c +Subproject commit 995a018fd6f3dbe8ad0a3d843defcf2b62b4f861 diff --git a/temporalio/bridge/src/streams.rs b/temporalio/bridge/src/streams.rs index 82fd9efca..ab8a30f50 100644 --- a/temporalio/bridge/src/streams.rs +++ b/temporalio/bridge/src/streams.rs @@ -6,6 +6,7 @@ use pyo3::prelude::*; use pyo3::sync::PyOnceLock; use pyo3::types::{PyBytes, PyType}; use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError}; +use std::time::Duration; use temporalio_sdk_core::StreamRuntimes; use temporalio_streams::proto::{ AppendRecordsRequest, AppendRecordsResponse, CreateStreamRequest, CreateStreamResponse, @@ -203,6 +204,7 @@ fn store_limits( pub(crate) struct WorkerStreams { limits: Option<(usize, usize, usize)>, stores: Vec<(String, Py)>, + read_time_millis: Option, } impl WorkerStreams { @@ -219,6 +221,10 @@ impl WorkerStreams { let runtime = StreamRuntime::new(Arc::new(store), limits); (name, Arc::new(runtime)) }); - Ok(StreamRuntimes::new(runtimes)) + let mut runtimes = StreamRuntimes::new(runtimes); + if let Some(millis) = self.read_time_millis { + runtimes.settings.read_time = Some(Duration::from_millis(millis)); + } + Ok(runtimes) } } diff --git a/temporalio/bridge/src/worker.rs b/temporalio/bridge/src/worker.rs index 4c8de98da..3c7bfde20 100644 --- a/temporalio/bridge/src/worker.rs +++ b/temporalio/bridge/src/worker.rs @@ -5,7 +5,7 @@ use prost::Message; use pyo3::exceptions::{PyException, PyRuntimeError, PyValueError}; use pyo3::prelude::*; use pyo3::types::{PyBytes, PyTuple}; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::marker::PhantomData; use std::sync::{Arc, OnceLock}; use std::time::Duration; @@ -67,6 +67,8 @@ pub struct WorkerConfig { storage_drivers: HashSet, disable_payload_error_limit: bool, streams: WorkerStreams, + stream_replay_as_workflow_fail: bool, + stream_replay_as_workflow_fail_for_types: HashSet, } #[derive(FromPyObject)] @@ -524,7 +526,11 @@ pub fn new_replay_worker<'a>( runtime_ref .runtime .assert_same_process("create replay worker")?; - let event_loop_task_locals = Arc::new(OnceLock::new()); + // A Worker takes its event loop in `validate`, but a replay Worker gets no `validate` call. A + // replay reads its Python Stores on a loop, so it takes the loop that creates it. + let event_loop_task_locals = Arc::new(OnceLock::from( + pyo3_async_runtimes::TaskLocals::with_running_loop(py)?.copy_context(py)?, + )); let config = convert_worker_config(config, event_loop_task_locals.clone())?; let (history_pusher, stream) = HistoryPusher::new(runtime_ref.runtime.clone()); let worker = WorkerRef { @@ -534,7 +540,7 @@ pub fn new_replay_worker<'a>( PyValueError::new_err(format!("Failed creating replay worker: {err}")) })?, )), - event_loop_task_locals: Default::default(), + event_loop_task_locals, runtime: runtime_ref.runtime.clone(), }; PyTuple::new( @@ -723,6 +729,22 @@ fn convert_worker_config( task_locals: Arc>, ) -> PyResult { let stream_runtimes = conf.streams.into_runtimes(&task_locals)?; + let mut failure_errors = HashSet::new(); + if conf.nondeterminism_as_workflow_fail { + failure_errors.insert(WorkflowErrorType::Nondeterminism); + } + if conf.stream_replay_as_workflow_fail { + failure_errors.insert(WorkflowErrorType::StreamReplay); + } + let mut type_failure_errors = HashMap::>::new(); + for workflow_type in conf.nondeterminism_as_workflow_fail_for_types { + let errors = type_failure_errors.entry(workflow_type).or_default(); + errors.insert(WorkflowErrorType::Nondeterminism); + } + for workflow_type in conf.stream_replay_as_workflow_fail_for_types { + let errors = type_failure_errors.entry(workflow_type).or_default(); + errors.insert(WorkflowErrorType::StreamReplay); + } let converted_tuner = convert_tuner_holder(conf.tuner, task_locals)?; let converted_versioning_strategy = convert_versioning_strategy(conf.versioning_strategy); temporalio_sdk_core::WorkerConfig::builder() @@ -754,22 +776,8 @@ fn convert_worker_config( // auto-cancel-activity behavior of shutdown will not occur, so we // always set it even if 0. .graceful_shutdown_period(Duration::from_millis(conf.graceful_shutdown_period_millis)) - .workflow_failure_errors(if conf.nondeterminism_as_workflow_fail { - HashSet::from([WorkflowErrorType::Nondeterminism]) - } else { - HashSet::new() - }) - .workflow_types_to_failure_errors( - conf.nondeterminism_as_workflow_fail_for_types - .iter() - .map(|s| { - ( - s.to_owned(), - HashSet::from([WorkflowErrorType::Nondeterminism]), - ) - }) - .collect(), - ) + .workflow_failure_errors(failure_errors) + .workflow_types_to_failure_errors(type_failure_errors) .maybe_nexus_task_poller_behavior(conf.nexus_task_poller_behavior.map(Into::into)) .plugins( conf.plugins diff --git a/temporalio/bridge/streams.py b/temporalio/bridge/streams.py index 9458a0fe6..11a2c63bd 100644 --- a/temporalio/bridge/streams.py +++ b/temporalio/bridge/streams.py @@ -39,3 +39,4 @@ class WorkerStreams: of the Stream config, or ``None`` with no Stream config.""" stores: Sequence[tuple[str, StoreCaller]] """The caller of each Stream Store that Workflow code can use, by Store name.""" + read_time_millis: int | None diff --git a/temporalio/bridge/worker.py b/temporalio/bridge/worker.py index ca8f54dd0..960b27221 100644 --- a/temporalio/bridge/worker.py +++ b/temporalio/bridge/worker.py @@ -65,6 +65,8 @@ class WorkerConfig: storage_drivers: set[str] disable_payload_error_limit: bool streams: temporalio.bridge.streams.WorkerStreams + stream_replay_as_workflow_fail: bool + stream_replay_as_workflow_fail_for_types: set[str] @dataclass diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index fd1dda4f8..bb4c22073 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -352,7 +352,7 @@ async def _call_method( Three callers retry on ``STORE_UNAVAILABLE`` and on no other reason: - * Core resends a Workflow append. + * Core resends a Workflow append or read. * An Activity's retry policy runs the Activity again. * A Workflow create or describe runs as a Local Activity with one attempt, so the SDK fails the Workflow Task instead, and the task's next attempt calls the diff --git a/temporalio/contrib/streams/README.md b/temporalio/contrib/streams/README.md index 88757aefb..98381b788 100644 --- a/temporalio/contrib/streams/README.md +++ b/temporalio/contrib/streams/README.md @@ -50,7 +50,7 @@ Workflow code doesn't use the appender. It passes all its values to one `append` `append(..., producer=...)` when resumed work must keep that Producer. A `WorkflowProducer` includes `workflow_task_id` so readers can distinguish -retries from separate Workflow Tasks. Core sets it to the started event ID of the +retries from separate Workflow Tasks. The SDK sets it to the started event ID of the last completed Workflow Task, or zero for the first task. Each retry has its own `attempt`. @@ -89,3 +89,22 @@ separate heartbeat task. pass through Worker interceptors. - Await each call before the Workflow completes. Core can drop a call that's still pending when the Workflow completes. + +## Workflow reads + +A read that waits keeps its Workflow Task open, so it can delay Signal handling until +it returns or the Worker's `stream_read_time` runs out. At that limit, `read_page` +returns an empty page. Iterators go on across Workflow Tasks. Each page adds a result +to History, so short waits on an idle Stream can make History grow fast. + +A live page has at most 256 Records and 4 MiB by default. The reads of one Workflow +Task get at most 16 MiB in all. A live read fails if a Record is larger than +`StreamConfig.max_record_bytes`. A replay keeps the pages that the first run got, even +if the Worker's limits are lower at replay. + +History keeps a digest of each page, not its Records. So a replay reads the same +Records from the Store again and checks them against the digest. Keep Records for the +Workflow's life and for any later replay, query or reset. Values in Workflow state +don't remove this need, because the replay reads the Store all the same. + +A body that doesn't match the declared type fails the Workflow Task. diff --git a/temporalio/converter/_payload_converter.py b/temporalio/converter/_payload_converter.py index ff7d477cc..078ace511 100644 --- a/temporalio/converter/_payload_converter.py +++ b/temporalio/converter/_payload_converter.py @@ -584,6 +584,27 @@ def from_payload( raise RuntimeError("Failed parsing") from err +# Only the types here decode by their type arguments and under `T | None`. Other +# types keep their decoding, so the Histories of existing Workflows replay as before. +_typed_decode_types: set[type] = set() + + +def _is_typed_decode_type(hint: Any) -> bool: + origin = typing.get_origin(hint) or hint + return any(origin is typed for typed in _typed_decode_types) + + +def _non_none_arg(hint: Any) -> Any: + origin = typing.get_origin(hint) + if origin is typing.Union or origin is UnionType: # type:ignore[reportDeprecated] + args = typing.get_args(hint) + if len(args) == 2 and type(None) in args: + arg = args[0] if args[1] is type(None) else args[1] + if _is_typed_decode_type(arg): + return arg + return hint + + class _TemporalTransferTypePayloadConverter(PayloadConverter, WithSerializationContext): """Payload converter wrapper for registered Temporal transfer type converters. @@ -591,7 +612,9 @@ class _TemporalTransferTypePayloadConverter(PayloadConverter, WithSerializationC transfer type value, then encoded by the wrapped payload converter. When decoding to a type with a registered transfer type converter, the wrapped converter first decodes the payload to the transfer type value and this wrapper - constructs the requested user-facing type from it. + constructs the requested user-facing type from it. For a type ``T`` in + ``_typed_decode_types``, a hint of ``T | None`` decodes as ``T`` does, and a null + payload gives ``None``. """ _inner_payload_converter: PayloadConverter @@ -627,21 +650,34 @@ def from_payloads( """See base class.""" if type_hints is None: return self._inner_payload_converter.from_payloads(payloads, None) + value_hints = [_non_none_arg(type_hint) for type_hint in type_hints] converters = [ - _get_transfer_type_converter(type_hint) for type_hint in type_hints - ] - inner_type_hints = [ - converter.transfer_type if converter is not None else type_hint - for converter, type_hint in zip(converters, type_hints) + _get_transfer_type_converter(value_hint) for value_hint in value_hints ] + inner_type_hints: list[Any] = [] + for converter, value_hint, type_hint in zip( + converters, value_hints, type_hints + ): + if converter is None: + inner_type_hints.append(type_hint) + elif value_hint is type_hint or converter.transfer_type is None: + inner_type_hints.append(converter.transfer_type) + else: + # `typing.Optional` also takes a transfer type that has no `|`, such + # as a string. + inner_type_hints.append( + typing.Optional[converter.transfer_type] # type:ignore[reportDeprecated] + ) values = self._inner_payload_converter.from_payloads( payloads, typing.cast("list[type]", inner_type_hints) ) return [ - converter.from_transfer_type(value, type_hint) - if converter is not None - else value - for value, converter, type_hint in zip(values, converters, type_hints) + value + if converter is None or (value is None and value_hint is not type_hint) + else converter.from_transfer_type(value, value_hint) + for value, converter, value_hint, type_hint in zip( + values, converters, value_hints, type_hints + ) ] def with_context(self, context: SerializationContext) -> Self: @@ -822,6 +858,18 @@ def _get_iso_datetime_parser() -> Callable[[str], datetime]: return datetime.fromisoformat +def _with_type_args(hint: Any, type_var_args: Mapping[Any, Any]) -> Any: + if not type_var_args: + return hint + if isinstance(hint, TypeVar): + return type_var_args.get(hint, hint) + # Only an alias takes arguments. A bare generic class keeps its own variables. + parameters = getattr(hint, "__parameters__", ()) + if parameters and typing.get_origin(hint) is not None: + return hint[tuple(type_var_args.get(param, param) for param in parameters)] + return hint + + def value_to_type( hint: type, value: Any, @@ -993,8 +1041,14 @@ def value_to_type( ret_dict = hint(**ret_dict) return ret_dict - # Dataclass - if dataclasses.is_dataclass(hint): + dataclass_type: Any = hint + type_var_args: dict[Any, Any] = {} + alias_origin = typing.get_origin(hint) + if _is_typed_decode_type(alias_origin) and dataclasses.is_dataclass(alias_origin): + dataclass_type = alias_origin + parameters = getattr(alias_origin, "__parameters__", ()) + type_var_args = dict(zip(parameters, type_args)) + if dataclasses.is_dataclass(dataclass_type): if not isinstance(value, dict): raise TypeError( f"Cannot convert to dataclass {hint}, value is {type(value)} not dict" @@ -1002,8 +1056,8 @@ def value_to_type( # Obtain dataclass fields and check that all dict fields are there and # that no required fields are missing. Unknown fields are silently # ignored. - fields = dataclasses.fields(hint) - field_hints = get_type_hints(hint) + fields = dataclasses.fields(dataclass_type) + field_hints = get_type_hints(dataclass_type) field_values = {} non_init_field_values = {} for field in fields: @@ -1016,7 +1070,9 @@ def value_to_type( # rejects this dataclass when trying union members try: converted = value_to_type( - field_hints[field.name], field_value, custom_converters + _with_type_args(field_hints[field.name], type_var_args), + field_value, + custom_converters, ) except Exception as err: raise TypeError( @@ -1029,6 +1085,8 @@ def value_to_type( # Simply instantiate the dataclass. This will fail as expected when # missing required fields. # TODO(cretz): Want way to convert snake case to camel case? + # Build from the alias, not its dataclass origin, so that the object keeps + # its type arguments. obj = hint(**field_values) # init=False fields cannot be passed to __init__ but are serialized, so # restore them afterwards. object.__setattr__ also works on frozen diff --git a/temporalio/nexus/system/__init__.py b/temporalio/nexus/system/__init__.py index 7bc7c24d0..563d80b2b 100644 --- a/temporalio/nexus/system/__init__.py +++ b/temporalio/nexus/system/__init__.py @@ -20,6 +20,7 @@ from temporalio.converter import BinaryProtoPayloadConverter, CompositePayloadConverter from temporalio.converter._payload_converter import ( _TemporalTransferTypePayloadConverter, + _typed_decode_types, ) TEMPORAL_SYSTEM_ENDPOINT = "__temporal_system" @@ -198,3 +199,9 @@ def _get_serialization_context( # pyright: ignore[reportUnusedFunction] # `temporalio.workflow` and the generated Workflow modules of a system service import each # other. This module imports it last, so a program can import any of them first. import temporalio.workflow # noqa: E402 # pyright: ignore[reportUnusedImport] +from temporalio.nexus.system.stream_service.models import StreamRef # noqa: E402 + +# Only an SDK with this rule lets Workflow code decode a `StreamRef`, so the rule +# can't change the replay of an older History. Any import of the generated class +# runs this module first, so the rule is always in place. +_typed_decode_types.add(StreamRef) diff --git a/temporalio/streams.py b/temporalio/streams.py index aa85cd767..2a9d6d6c1 100644 --- a/temporalio/streams.py +++ b/temporalio/streams.py @@ -196,8 +196,8 @@ class StreamConfig: A replay of Workflow code calls the selector again. So return the same Store for the same call. Clients and Workflow code both call the selector, Workflow code on the Worker's Workflow threads, so make it thread-safe, and don't block - or do I/O in it. Replayed appends fail if the selected Store differs from - History. + or do I/O in it. Replayed appends and reads fail if the selected Store differs + from History. """ max_record_bytes: int = 1536 * 1024 diff --git a/temporalio/worker/_command_aware_visitor.py b/temporalio/worker/_command_aware_visitor.py index 224cb1018..1288aa4fd 100644 --- a/temporalio/worker/_command_aware_visitor.py +++ b/temporalio/worker/_command_aware_visitor.py @@ -18,6 +18,7 @@ ResolveRequestCancelExternalWorkflow, ResolveSignalExternalWorkflow, ResolveStreamAppend, + ResolveStreamRead, ) from temporalio.bridge.proto.workflow_commands.workflow_commands_pb2 import ( AppendToStream, @@ -221,6 +222,13 @@ async def _visit_coresdk_workflow_commands_AppendToStream( ) -> None: await self._visit_stream_payloads(fs, o.seq, o.bodies) + async def _visit_coresdk_workflow_activation_ResolveStreamRead( + self, fs: VisitorFunctions, o: ResolveStreamRead + ) -> None: + await self._visit_stream_payloads( + fs, o.seq, [record.body for record in o.page.records] + ) + async def _visit_coresdk_workflow_activation_ResolveStreamAppend( self, fs: VisitorFunctions, o: ResolveStreamAppend ) -> None: diff --git a/temporalio/worker/_replayer.py b/temporalio/worker/_replayer.py index de66d19a6..c422f0073 100644 --- a/temporalio/worker/_replayer.py +++ b/temporalio/worker/_replayer.py @@ -322,6 +322,10 @@ def on_eviction_hook( # per workflow type nondeterminism_as_workflow_fail=workflow_worker.nondeterminism_as_workflow_fail(), nondeterminism_as_workflow_fail_for_types=workflow_worker.nondeterminism_as_workflow_fail_for_types(), + stream_replay_as_workflow_fail=workflow_worker.stream_replay_as_workflow_fail(), + stream_replay_as_workflow_fail_for_types=( + workflow_worker.stream_replay_as_workflow_fail_for_types() + ), # All values below are ignored but required by Core max_cached_workflows=2, tuner=temporalio.bridge.worker.TunerHolder( @@ -371,7 +375,7 @@ def on_eviction_hook( (plugin.name(), plugin.version()) for plugin in self.plugins ], storage_drivers=storage_driver_types, - streams=_bridge_streams(lambda: stream_config), + streams=_bridge_streams(lambda: stream_config, None), ), ) bridge_worker_scope = bridge_worker diff --git a/temporalio/worker/_worker.py b/temporalio/worker/_worker.py index bbe056abc..0509ac4db 100644 --- a/temporalio/worker/_worker.py +++ b/temporalio/worker/_worker.py @@ -148,6 +148,7 @@ def __init__( nexus_task_poller_behavior: PollerBehavior | None = None, disable_payload_error_limit: bool = False, max_workflow_task_external_storage_concurrency: int = _DEFAULT_WORKFLOW_TASK_EXTERNAL_STORAGE_CONCURRENCY, + stream_read_time: timedelta | None = None, ) -> None: """Create a worker to process workflows and/or activities. @@ -347,6 +348,17 @@ def __init__( Please report any issues you encounter with this setting or if you feel the default should be changed. WARNING: This setting is experimental. + stream_read_time: Longest time that Stream reads can keep a Workflow + Task open, from the start of the task or the end of its replay. A + read that waits holds the task open and delays Signals, so this caps + the wait. Defaults to half the task timeout, and always ends before + the task's heartbeat. Reads alone don't make the task heartbeat. + Appends have no such limit. At the limit, waiting reads return empty + pages, and iterators go on with a new wait, maybe in another task. + An iterator with no wait uses a one-minute wait for each page after + the first. A read with no wait doesn't hold the task open until the + Store answers, and can go on in a later task. + WARNING: This setting is experimental. """ config = WorkerConfig( @@ -396,6 +408,7 @@ def __init__( nexus_task_poller_behavior=nexus_task_poller_behavior, disable_payload_error_limit=disable_payload_error_limit, max_workflow_task_external_storage_concurrency=max_workflow_task_external_storage_concurrency, + stream_read_time=stream_read_time, ) plugins_from_client = cast( @@ -722,6 +735,14 @@ def check_activity(activity: str): ), streams=_bridge_streams( lambda: self.client._config["stream_config"], + config.get("stream_read_time"), + ), + stream_replay_as_workflow_fail=self._workflow_worker is not None + and self._workflow_worker.stream_replay_as_workflow_fail(), + stream_replay_as_workflow_fail_for_types=( + self._workflow_worker.stream_replay_as_workflow_fail_for_types() + if self._workflow_worker + else set() ), ), ) @@ -1072,6 +1093,7 @@ class WorkerConfig(TypedDict, total=False): nexus_task_poller_behavior: PollerBehavior | None disable_payload_error_limit: bool max_workflow_task_external_storage_concurrency: int + stream_read_time: timedelta | None def _poller_behavior_to_bridge( diff --git a/temporalio/worker/_workflow.py b/temporalio/worker/_workflow.py index eb228a797..9b7b16e92 100644 --- a/temporalio/worker/_workflow.py +++ b/temporalio/worker/_workflow.py @@ -870,6 +870,22 @@ def nondeterminism_as_workflow_fail_for_types(self) -> set[str]: ) } + def stream_replay_as_workflow_fail(self) -> bool: + return any( + issubclass(temporalio.workflow.StreamReplayError, typ) + for typ in self._workflow_failure_exception_types + ) + + def stream_replay_as_workflow_fail_for_types(self) -> set[str]: + return { + k + for k, v in self._workflows.items() + if any( + issubclass(temporalio.workflow.StreamReplayError, typ) + for typ in v.failure_exception_types + ) + } + class _DeadlockError(Exception): """Exception class for deadlocks. Contains functionality to swap the default traceback for another.""" diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index 3f10cf574..f9027abca 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -712,6 +712,8 @@ def _apply( ) elif job.HasField("resolve_stream_append"): self._streams.resolve_append(job.resolve_stream_append) + elif job.HasField("resolve_stream_read"): + self._streams.resolve_read(job.resolve_stream_read) elif job.HasField("signal_workflow"): self._apply_signal_workflow(job.signal_workflow) elif job.HasField("initialize_workflow"): diff --git a/temporalio/worker/_workflow_streams.py b/temporalio/worker/_workflow_streams.py index 71b146946..8c738c507 100644 --- a/temporalio/worker/_workflow_streams.py +++ b/temporalio/worker/_workflow_streams.py @@ -7,12 +7,18 @@ open, gives Workflow code the result in an activation, and records the result in a ``core_stream_append`` marker in History. A replay takes the result from the marker and doesn't call the Store, so it writes nothing. +* A read is a command too. Core reads one page from the Store, and its + ``core_stream_read`` marker keeps where the page starts, how many Records it has + and a digest of them, not the Records. A replay reads the same Records from the + Store again and checks them against the digest. If they changed or are gone, the + replay can't go the same way, so Core fails the Workflow Task with + :py:class:`temporalio.workflow.StreamReplayError`. * Core has no command for create and describe, so they run as Local Activities of the SDK. History records their results as it does for any Local Activity. -Each append command names its Store: the one that the call's ref names, or else -the one that the selector picks, or the only Store. So Core fails a replay that ends -up with another Store. A create or describe passes the Store name to its Local +Each append and read command names its Store: the one that the call's ref names, or +else the one that the selector picks, or the only Store. So Core fails a replay that +ends up with another Store. A create or describe passes the Store name to its Local Activity, and a create returns a ref with that name, so later calls on the Stream keep that Store. """ @@ -21,7 +27,10 @@ import asyncio import functools +import typing from collections.abc import Callable, Generator +from dataclasses import dataclass +from datetime import timedelta from typing import TYPE_CHECKING, Any, cast import google.protobuf.json_format @@ -34,6 +43,7 @@ import temporalio.api.stream.v1 import temporalio.api.streamservice.v1 as proto import temporalio.bridge.proto.workflow_activation +import temporalio.bridge.proto.workflow_commands import temporalio.bridge.streams import temporalio.common import temporalio.exceptions @@ -57,16 +67,24 @@ _STORE_CALL_ACTIVITY = "__temporal_stream_store_call" +@dataclass +class _Read: + waiter: asyncio.Future[Any] + page_type: Any + + class _WorkflowStreams: # pyright: ignore[reportUnusedClass] - """The Stream calls of one Workflow run. Appends become Core commands, and - create and describe become Local Activities, because Core has no commands for - them. + """The Stream calls of one Workflow run. Appends and reads become Core commands, + and create and describe become Local Activities, because Core has no commands + for them. """ def __init__(self, instance: _WorkflowInstanceImpl) -> None: self._instance = instance self._appends: dict[int, asyncio.Future[Any]] = {} self.task_error: Exception | None = None + # Core still gives a cancelled read its one result, so keep the read until then. + self._reads: dict[int, _Read] = {} def start( self, input: StartNexusOperationInput[Any, OutputT] @@ -87,13 +105,24 @@ def start( model = input.input result_type: Any = input.output_type request = temporalio.nexus.system._support.model_to_proto(model, *converters) + # Without a body type, the page would fail the task when it comes, so fail the + # caller here, before the command. + if isinstance(request, sdk.ReadRecordsRequest) and typing.get_args( + result_type + ) == (object,): + raise TypeError( + "Cannot read a Stream with no body type. Give get_stream a " + "body_type, or a StreamRef with a type argument." + ) store = self._store(_request_ref(request)).name() - result = _start_call(self, store, operation, request) + result = _start_call(self, store, operation, request, result_type) async def call() -> OutputT: # `asyncio.wait` ends at a cancel of this task. `await result` would pass the # cancel on and wait for the cancelled Local Activity. await asyncio.wait([result]) + if isinstance(request, sdk.ReadRecordsRequest): + return result.result() return temporalio.nexus.system._support.model_from_proto( self._response(operation, request, result), result_type, @@ -138,6 +167,29 @@ def resolve_append( else: future.set_result(job.appended) + def resolve_read( + self, job: temporalio.bridge.proto.workflow_activation.ResolveStreamRead + ) -> None: + read = self._reads.pop(job.seq, None) + if read is None: + raise RuntimeError(f"Failed finding Stream read for sequence {job.seq}") + if read.waiter.done(): + return + if job.HasField("failed"): + read.waiter.set_exception(self._error(job.failed)) + return + page = proto.ReadRecordsResponse(records=job.page.records) + # Convert in the activation, so a body that doesn't fit its type fails the task + # before Workflow code goes on. + read.waiter.set_result( + temporalio.nexus.system._support.model_from_proto( + page, + read.page_type, + self._instance._context_free_payload_converter, + self._instance._context_free_failure_converter, + ) + ) + def _error(self, failure: temporalio.api.failure.v1.Failure) -> BaseException: instance = self._instance return _stream_error_from_failure(failure) or ( @@ -235,6 +287,7 @@ def _start_call( store: str, operation: str, request: google.protobuf.message.Message, + result_type: Any, ) -> asyncio.Future[Any]: """Add the command or Local Activity of one call, with the selected Store's name. @@ -251,6 +304,21 @@ def _start_call( append.bodies.extend(record.body for record in request.records) result = streams._appends[seq] = instance.create_future() return result + if isinstance(request, sdk.ReadRecordsRequest): + seq = instance._next_seq("stream_read") + instance._add_command().read_stream.CopyFrom( + temporalio.bridge.proto.workflow_commands.ReadStream( + seq=seq, + stream=stream, + after_offset=request.after_offset, + wait=request.wait if request.HasField("wait") else None, + max_records=request.max_records, + max_bytes=request.max_bytes, + ) + ) + result = instance.create_future() + streams._reads[seq] = _Read(result, result_type) + return result # Each run of a chain has the same first execution run id. A later run that # creates the Stream again sends the first request id, and the Store takes it # as a resend. @@ -350,6 +418,7 @@ def _for_core( def _bridge_streams( # pyright: ignore[reportUnusedFunction] stream_config: Callable[[], temporalio.streams.StreamConfig | None], + read_time: timedelta | None, ) -> temporalio.bridge.streams.WorkerStreams: """Give Core a caller for each Store. A caller finds its Store at each call, so a Worker's new client takes effect for later calls. @@ -367,6 +436,9 @@ def store(name: str) -> temporalio.streams.StreamStore: (name, _StoreCaller(functools.partial(store, name))) for name in sorted(names) ], + read_time_millis=int(1000 * read_time.total_seconds()) + if read_time is not None + else None, ) diff --git a/temporalio/workflow/__init__.py b/temporalio/workflow/__init__.py index 60b02cc54..3ddb444b3 100644 --- a/temporalio/workflow/__init__.py +++ b/temporalio/workflow/__init__.py @@ -119,6 +119,7 @@ ContinueAsNewVersioningBehavior, NondeterminismError, ReadOnlyContextError, + StreamReplayError, VersioningIntent, _NotInWorkflowEventLoopError, ) @@ -246,6 +247,7 @@ "ContinueAsNewVersioningBehavior", "NondeterminismError", "ReadOnlyContextError", + "StreamReplayError", "VersioningIntent", "HandlerUnfinishedPolicy", "UnfinishedSignalHandlersWarning", diff --git a/temporalio/workflow/_exceptions.py b/temporalio/workflow/_exceptions.py index 2d34c2fed..3aa4aba52 100644 --- a/temporalio/workflow/_exceptions.py +++ b/temporalio/workflow/_exceptions.py @@ -9,6 +9,7 @@ __all__ = [ "NondeterminismError", "ReadOnlyContextError", + "StreamReplayError", "VersioningIntent", "ContinueAsNewVersioningBehavior", ] @@ -23,6 +24,18 @@ def __init__(self, message: str) -> None: self.message = message +class StreamReplayError(temporalio.exceptions.TemporalError): + """Error raised when a replay can't read the same Stream Records as the first + run did, because the Store changed or lost them. + + SDK Core fails the Workflow Task with it. If a Worker or a Workflow lists this + class in its failure exception types, the Workflow fails instead. + + .. warning:: + This API is experimental and subject to change. + """ + + class ReadOnlyContextError(temporalio.exceptions.TemporalError): """Error thrown when trying to do mutable workflow calls in a read-only context like a query or update validator. diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index 55c8b6deb..6252c61b7 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -1,10 +1,14 @@ """Tests of the client path of Streams, with no server.""" import asyncio +import concurrent.futures import copy import dataclasses import pickle +import pkgutil import random +import subprocess +import sys from collections.abc import Awaitable, Callable from datetime import datetime, timedelta, timezone from types import SimpleNamespace @@ -35,6 +39,7 @@ import temporalio.streams import temporalio.testing import temporalio.worker._workflow_streams +import temporalio.workflow from temporalio.types import ReturnType from tests.helpers.streams import ( ContextCodec, @@ -1308,6 +1313,125 @@ def test_a_client_uses_one_producer_for_all_its_streams() -> None: assert first.client.namespace == "default" and first.client.id +@dataclasses.dataclass +class _Turn: + text: str + + +@pytest.mark.parametrize( + ("hint", "ref", "body_type"), + [ + ( + temporalio.nexus.system.stream_service.StreamRef[int], + temporalio.nexus.system.stream_service.StreamRef[int]( + id="count", store="a" + ), + int, + ), + ( + temporalio.nexus.system.stream_service.StreamRef[str], + temporalio.nexus.system.stream_service.StreamRef[str](id="text"), + str, + ), + ( + temporalio.nexus.system.stream_service.StreamRef[_Turn], + temporalio.nexus.system.stream_service.StreamRef[_Turn]( + id="turn", store="b" + ), + _Turn, + ), + ( + temporalio.nexus.system.stream_service.StreamRef, + temporalio.nexus.system.stream_service.StreamRef(id="untyped"), + object, + ), + (temporalio.nexus.system.stream_service.StreamRef[int] | None, None, None), + ( + temporalio.nexus.system.stream_service.StreamRef[str] | None, + temporalio.nexus.system.stream_service.StreamRef[str](id="optional"), + str, + ), + ], +) +def test_a_stream_ref_keeps_its_body_type( + hint: Any, + ref: temporalio.nexus.system.stream_service.StreamRef[Any] | None, + body_type: type | None, +) -> None: + converter = temporalio.converter.DataConverter.default.payload_converter + client = temporalio.client.Client( + Mock(spec=temporalio.service.ServiceClient), + stream_config=temporalio.streams.StreamConfig([FaultStore()]), + ) + [decoded] = converter.from_payloads(converter.to_payloads([ref]), [hint]) + assert decoded == ref + if decoded is not None: + for get_stream in (client.get_stream, temporalio.workflow.get_stream): + assert get_stream(decoded).body_type is body_type + + +@dataclasses.dataclass +class _RefFields: + typed: temporalio.nexus.system.stream_service.StreamRef[_Turn] + untyped: temporalio.nexus.system.stream_service.StreamRef + nested: list[temporalio.nexus.system.stream_service.StreamRef[int] | None] + + +def test_stream_ref_fields_keep_their_body_types_inside_lists() -> None: + value = [ + _RefFields( + typed=temporalio.nexus.system.stream_service.StreamRef[_Turn]( + id="turn", store="a" + ), + untyped=temporalio.nexus.system.stream_service.StreamRef(id="untyped"), + nested=[ + temporalio.nexus.system.stream_service.StreamRef[int](id="count"), + None, + ], + ) + ] + converter = temporalio.converter.DataConverter.default.payload_converter + client = temporalio.client.Client( + Mock(spec=temporalio.service.ServiceClient), + stream_config=temporalio.streams.StreamConfig([FaultStore()]), + ) + [decoded] = converter.from_payloads( + converter.to_payloads([value]), [list[_RefFields]] + ) + assert decoded == value + [fields] = decoded + assert fields.nested[1] is None + for get_stream in (client.get_stream, temporalio.workflow.get_stream): + assert get_stream(fields.typed).body_type is _Turn + assert get_stream(fields.untyped).body_type is object + assert get_stream(fields.nested[0]).body_type is int + + +def test_each_stream_module_can_be_the_first_import() -> None: + system = temporalio.nexus.system + modules = [ + "temporalio.client._stream_store", + "temporalio.testing._stream_store", + "temporalio.contrib.streams", + "temporalio.workflow", + system.__name__, + *( + module.name + for module in pkgutil.walk_packages(system.__path__, system.__name__ + ".") + ), + ] + + def first_import(module: str) -> str: + imported = subprocess.run( + [sys.executable, "-c", f"import {module}"], capture_output=True, text=True + ) + return imported.stderr if imported.returncode else "" + + with concurrent.futures.ThreadPoolExecutor(8) as pool: + for module, error in zip(modules, pool.map(first_import, modules)): + assert not error, f"{module}: {error}" + + def test_a_client_call_past_its_rpc_timeout_cancels_the_store_call() -> None: async def script() -> None: loop = asyncio.get_running_loop() diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py index dc9da9f47..029d44066 100644 --- a/tests/nexus/test_streams_with_worker.py +++ b/tests/nexus/test_streams_with_worker.py @@ -1,24 +1,36 @@ """Tests of Streams with a Worker on the test server.""" import asyncio +import dataclasses +import hashlib +import itertools +import random from collections.abc import Sequence from datetime import timedelta from typing import Any import pytest +from google.protobuf.message import Message import temporalio.streams from temporalio import activity, workflow -from temporalio.api.enums.v1 import EventType, TaskQueueType +from temporalio.api.enums.v1 import EventType, StreamErrorReason, TaskQueueType +from temporalio.api.sdk.v1.external_storage_pb2 import ExternalStorageReference from temporalio.api.streamservice.v1 import ( + AppendRecordsRequest, CreateStreamRequest, + DescribeStreamResponse, ReadRecordsRequest, ) from temporalio.api.taskqueue.v1 import TaskQueue from temporalio.api.workflowservice.v1 import DescribeTaskQueueRequest -from temporalio.client import Client +from temporalio.client import Client, WorkflowFailureError from temporalio.common import RetryPolicy from temporalio.contrib.streams import current_producer +from temporalio.converter import ( + DataConverter, + ExternalStorage, +) from temporalio.exceptions import ApplicationError, StreamError from temporalio.nexus.system.stream_service import ( ProducerKindLocalActivity, @@ -26,23 +38,27 @@ StreamIdConflictPolicy, StreamRef, ) +from temporalio.testing import MemoryStreamStore from temporalio.worker import ( ActivityInboundInterceptor, Interceptor, Replayer, Worker, ) -from tests.helpers import assert_eventually, new_worker +from tests.helpers import assert_eventually, assert_task_fail_eventually, new_worker from tests.helpers.streams import ( + ContextCodec, FaultStore, Hold, RunOptions, + answers, failure_note, loses_answer, raises, run, stream_client, ) +from tests.test_extstore import InMemoryTestDriver async def _answers( @@ -101,6 +117,141 @@ async def run(self, calls: list[list[Any]], in_activity: bool = False) -> list[A return await _answers(workflow, calls) +def _writes(store: FaultStore) -> list[Message]: + """Return each request of a Store but its reads, which Core pages in its own way, + without the Producer, which differs between two writers of the same call. + """ + writes: list[Message] = [] + for request in store.requests: + if isinstance(request, ReadRecordsRequest): + continue + copy = type(request)() + copy.CopyFrom(request) + if "producer" in copy.DESCRIPTOR.fields_by_name: + copy.ClearField("producer") + writes.append(copy) + return writes + + +async def test_workflow_code_and_a_client_get_the_same_answers(client: Client) -> None: + for seed in range(8): + with failure_note(f"seed {seed}"): + rng = random.Random(seed) + # One run sends one request id with each of its creates. So a second create + # of a Stream is the first one again for a Workflow, and not for a client. + calls: list[list[Any]] = [ + ["create", f"s-{seed}-{number}", rng.randrange(3)] for number in (0, 1) + ] + operations = ["append", "append", "append", "describe"] + reads = seed % 2 == 1 + if reads: + operations += ["read", "read"] + for _ in range(rng.randrange(4, 12)): + # The third Stream is never created. + stream_id = f"s-{seed}-{rng.choice([0, 0, 0, 1, 1, 2])}" + operation = rng.choice(operations) + if operation == "append": + bodies = [rng.randrange(100) for _ in range(rng.randrange(1, 4))] + calls.append(["append", stream_id, bodies]) + else: + calls.append([operation, stream_id]) + if reads: + calls += [["read", f"s-{seed}-0"], ["read", f"s-{seed}-1"]] + # The two Stores have one name and the same Stream ids, so a call is the + # same request in both. + for_client, for_workflow = FaultStore(), FaultStore() + from_client = await _answers(stream_client(client, for_client), calls) + workflow_client = stream_client(client, for_workflow) + ran = await run(workflow_client, RunOptions(_CallsWorkflow, [calls])) + assert ran.result == from_client + assert _writes(for_workflow) == _writes(for_client) + appends = [ + request_id + for request, request_id in for_workflow.calls + if isinstance(request, AppendRecordsRequest) + ] + assert all(appends) and len(set(appends)) == len(appends) + # A replay with the Stores of the run writes nothing. A replay chooses the + # Store of each call again, so one with no Stream config fails. + written = _writes(for_workflow) + await Replayer( + workflows=[_CallsWorkflow], + stream_config=workflow_client._config["stream_config"], + ).replay_workflow(ran.history) + assert _writes(for_workflow) == written + with pytest.raises(Exception, match="no stream_config"): + await Replayer(workflows=[_CallsWorkflow]).replay_workflow(ran.history) + + +def _bodies(writer: str) -> list[Any]: + """Return the bodies that a writer appends. One is a value that a pass of external + storage would take for a reference into the storage of the Worker. + """ + claim = ExternalStorageReference( + driver_name="test-driver", claim_data={"key": "payload-0"} + ) + return [f"{writer} plain", {"writer": writer}, claim] + + +def _digest(bodies: Sequence[Any]) -> str: + """Return a digest of bodies, so that a Workflow result has no body in it.""" + return hashlib.sha256(repr(bodies).encode()).hexdigest() + + +@activity.defn +async def _append_bodies(stream_id: str) -> None: + stream = activity.client().get_stream(StreamRef(id=stream_id)) + await stream.append(*_bodies("activity")) + + +@workflow.defn +class _BodiesWorkflow: + @workflow.run + async def run(self, stream_id: str) -> str: + await workflow.execute_activity( + _append_bodies, stream_id, start_to_close_timeout=timedelta(seconds=10) + ) + stream = workflow.get_stream(StreamRef[Any](id=stream_id)) + await stream.append(*_bodies("workflow")) + bodies: list[Any] = [] + async for record in stream.read(): + bodies.append(record.body) + # A Stream has no end, so the reader stops at the Records of the 3 writers. + if len(bodies) == 3 * len(_bodies("workflow")): + break + return _digest(bodies) + + +async def test_a_body_reads_the_same_on_every_path(client: Client) -> None: + store, driver = FaultStore(), InMemoryTestDriver() + converter = dataclasses.replace( + DataConverter.default, + payload_codec=ContextCodec(), + external_storage=ExternalStorage(drivers=[driver], payload_size_threshold=0), + ) + client = stream_client(client, store, data_converter=converter) + stream = await client.create_stream(id="bodies") + await stream.append(*_bodies("client")) + options = RunOptions(_BodiesWorkflow, ["bodies"], activities=[_append_bodies]) + ran = await run(client, options) + + expected = [*_bodies("client"), *_bodies("activity"), *_bodies("workflow")] + # A Stream has no end, so the reader takes the Records that it knows of. + records = stream.read() + async with asyncio.timeout(10): + assert [(await anext(records)).body for _ in expected] == expected + assert ran.result == _digest(expected) + # The Store has each body as the codec gave it with no context, and the storage of + # the Worker has none of them. + stored = await store.memory.read_records(ReadRecordsRequest(stream_id="bodies")) + assert [dict(record.body.metadata) for record in stored.records] == [ + {"encoding": b"test/wrapped", "context": b"NoneType"} + ] * len(expected) + assert driver._storage and not any( + b" plain" in value for value in driver._storage.values() + ) + + @activity.defn async def _append_one(stream_id: str) -> None: await activity.client().get_stream(StreamRef[int](id=stream_id)).append(1) @@ -281,6 +432,226 @@ def _events(history: Any, event_type: EventType.ValueType) -> list[Any]: return [event for event in history.events if event.event_type == event_type] +def _stream_markers(history: Any, kind: str) -> list[Any]: + """Return the markers in which Core records the Stream calls of ``kind``, which + is ``append`` or ``read``. + """ + return [ + event + for event in _events(history, EventType.EVENT_TYPE_MARKER_RECORDED) + if event.marker_recorded_event_attributes.marker_name == f"core_stream_{kind}" + ] + + +async def test_a_store_error_is_the_same_error_on_every_path(client: Client) -> None: + store = FaultStore() + client = stream_client(client, store) + await client.create_stream(id="errors", body_type=int) + append: list[Any] = ["append", "errors", [1]] + appends = store.faults["append_records"] + unavailable = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE + + async def answers_on( + path: str, calls: list[list[Any]], on: Client = client, **options: Any + ) -> Any: + if path == "client": + return await _answers(on, calls) + args = [calls, path == "activity"] + run_options = RunOptions( + _CallsWorkflow, args, activities=[_calls_activity], **options + ) + return (await run(on, run_options)).result + + def append_request_ids() -> list[str | None]: + calls, store.calls = store.calls, [] + return [i for r, i in calls if isinstance(r, AppendRecordsRequest)] + + # Core tries an append again in an outage of the Store, with one request id, so the + # Store writes it once. Workflow code gets no error, and History has no failure. + outages = [ + [raises(StreamError("The Store is down", reason=unavailable))] * 2, + [loses_answer()], + [raises(ConnectionError("The connection is gone"))], + ] + for at, faults in enumerate(outages): + with failure_note(f"outage {at}"): + appends.extend(faults) + ran = await run(client, RunOptions(_CallsWorkflow, [[append]])) + offset = (at + 1).to_bytes(8, "big").hex() + assert ran.result == [[offset, offset]] + request_ids = append_request_ids() + assert len(request_ids) == len(faults) + 1 + assert len(set(request_ids)) == 1 + assert not _events(ran.history, EventType.EVENT_TYPE_WORKFLOW_TASK_FAILED) + # A client and an Activity get the outage as the error of their call. + for path in ("client", "activity"): + appends.append(raises(ConnectionError("The connection is gone"))) + [[error, reason, _]] = await answers_on(path, [append]) + assert (error, reason, len(append_request_ids())) == ("error", unavailable, 1) + + # An answer of the wrong message fails the call, and nothing tries it again. + corrupt = StreamErrorReason.STREAM_ERROR_REASON_STORE_CORRUPT + for path in ("client", "activity", "workflow"): + with failure_note(path): + appends.append(answers(DescribeStreamResponse())) + [[error, reason, _]] = await answers_on(path, [append]) + assert (error, reason, len(append_request_ids())) == ("error", corrupt, 1) + + # A refusal is the same error for a client, an Activity and Workflow code. Workflow + # code gets it again in each task that replays the call. + not_found = StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND + calls: list[list[Any]] = [ + ["append", "missing", [1]], + ["describe", "errors"], + ["describe", "missing"], + ["read", "missing"], + ] + refused = await answers_on("client", calls) + assert [answer[:2] for answer in refused] == [ + ["error", not_found], + [(3).to_bytes(8, "big").hex()], + ["error", not_found], + ["error", not_found], + ] + for path in ("activity", "workflow"): + with failure_note(path): + assert await answers_on(path, calls, cached=False, replay=True) == refused + + # When its retention has passed since its last append, a Stream refuses each call + # as expired, on each path. + expiring = stream_client(client, FaultStore(retention=timedelta(seconds=2))) + stream = await expiring.create_stream(id="expires", body_type=int) + await stream.append(1) + await asyncio.sleep(2.5) + expired = StreamErrorReason.STREAM_ERROR_REASON_EXPIRED + calls = [["append", "expires", [2]], ["describe", "expires"], ["read", "expires"]] + for path in ("client", "activity", "workflow"): + with failure_note(f"expired, {path}"): + answered = await answers_on(path, calls, on=expiring, replay=True) + assert [answer[:2] for answer in answered] == [["error", expired]] * 3 + + # An outage during a create fails the Workflow Task, also on a Worker that fails a + # Workflow for any exception. The create runs in the next task, with the Store back. + for failure_types in ([], [Exception]): + with failure_note(f"failure types {failure_types}"): + store.faults["create_stream"].append(raises(ConnectionError("down"))) + options = RunOptions( + _CallsWorkflow, + [[["create", f"after an outage {len(failure_types)}"]]], + worker={"workflow_failure_exception_types": failure_types}, + ) + ran = await run(client, options) + assert ran.result == [["memory", True]] + # History has nothing of the outage but the task failure. + events = [event.event_type for event in ran.history.events] + task_done = events.index(EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED) + assert set(events[1:task_done]) == { + EventType.EVENT_TYPE_WORKFLOW_TASK_SCHEDULED, + EventType.EVENT_TYPE_WORKFLOW_TASK_STARTED, + EventType.EVENT_TYPE_WORKFLOW_TASK_FAILED, + } + assert events[task_done + 1 :] == [ + EventType.EVENT_TYPE_MARKER_RECORDED, + EventType.EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED, + ] + + +class _DownReadsStore(FaultStore): + """A Store whose reads fail as an outage until :py:attr:`up` is true.""" + + def __init__(self) -> None: + super().__init__() + self.up = False + + async def read_records(self, request: ReadRecordsRequest) -> Any: + if not self.up: + self.calls.append((request, None)) + raise ConnectionError("The connection is gone") + return await super().read_records(request) + + +async def test_a_store_outage_at_a_workflow_read_fails_the_workflow_task( + client: Client, +) -> None: + store = _DownReadsStore() + client = stream_client(client, store) + await (await client.create_stream(id="down", body_type=int)).append(1) + + async def back_after_a_task_failure(handle: Any, _worker: Any) -> None: + await assert_task_fail_eventually(handle) + store.up = True + + # SDK Core tries the read again up to the read limit, and then fails the task, as + # for an append. Workflow code gets no error, also on a Worker that fails a + # Workflow for any exception, and the read runs in the next task. + for failure_types in ([], [Exception]): + with failure_note(f"failure types {failure_types}"): + store.up = False + options = RunOptions( + _CallsWorkflow, + [[["read", "down"]]], + task_timeout=timedelta(seconds=2), + worker={"workflow_failure_exception_types": failure_types}, + during=back_after_a_task_failure, + ) + ran = await run(client, options) + assert ran.result == [[[1], (1).to_bytes(8, "big").hex()]] + failed = _events(ran.history, EventType.EVENT_TYPE_WORKFLOW_TASK_FAILED) + assert failed + for event in failed: + message = event.workflow_task_failed_event_attributes.failure.message + assert message.startswith("StreamStoreUnavailable:"), message + + +@workflow.defn +class _CatchingWorkflow: + @workflow.run + async def run(self, call: list[Any], store: str | None) -> str: + try: + await _answers(workflow, [call], store) + except Exception: + pass + return "caught" + + +async def test_a_stream_call_with_no_store_fails_the_workflow_task( + client: Client, +) -> None: + async def task_fails(handle: Any, _worker: Any) -> None: + await assert_task_fail_eventually(handle) + await handle.terminate() + + cases = { + "no Stream config": (client, None), + "a ref of a Store that the Worker lacks": ( + stream_client(client, FaultStore()), + "other", + ), + } + calls: list[list[Any]] = [ + ["create", "s"], + ["append", "s", [1]], + ["describe", "s"], + ["read", "s"], + ] + # The task fails also on a Worker that fails a Workflow for any exception. + for (case, (worker_client, store)), call, failure_types in itertools.product( + cases.items(), calls, ([], [Exception]) + ): + with failure_note(f"{call[0]} with {case} and {failure_types}"): + options = RunOptions( + _CatchingWorkflow, + [call, store], + worker={"workflow_failure_exception_types": failure_types}, + during=task_fails, + ) + ran = await run(worker_client, options) + # The Workflow didn't go on after the error that it caught, and History + # has nothing of the call. + assert isinstance(ran.result, WorkflowFailureError) + assert not _events(ran.history, EventType.EVENT_TYPE_MARKER_RECORDED) + + class _ActivityTypes(Interceptor): """Logs the type of each Activity that its Worker runs.""" @@ -462,6 +833,83 @@ def select(_: Any) -> FaultStore: await replay.replay_workflow(ran.history) +async def test_an_append_over_a_limit_of_the_config_never_reaches_the_store( + client: Client, +) -> None: + too_large = StreamErrorReason.STREAM_ERROR_REASON_TOO_LARGE + unsupported = StreamErrorReason.STREAM_ERROR_REASON_UNSUPPORTED + default_bytes = 4 * 1024 * 1024 + for seed in range(12): + with failure_note(f"seed {seed}"): + rng = random.Random(seed) + # One seed in four has limits over the defaults, which only the config + # bounds. + larger = seed % 4 == 0 + record = rng.choice([1000, 3000, 1536 * 1024]) + batch = ( + default_bytes if larger else rng.choice([4000, 20_000, default_bytes]) + ) + count = 1200 if larger else rng.choice([1, 3, 1000]) + # The body sizes of each batch, and whether the batch is within every limit. + # A stored Record counts its Producer, so no size is within 500 bytes of a + # limit, and the test needs no size logic. + batches: list[tuple[list[int], bool]] = [] + if larger: + batches.append(([0] * 1100, True)) + for _ in range(6): + match rng.choice(["fits", "fits", "records", "record", "batch"]): + case "records": + batches.append(([0] * (count + 1), False)) + case "record" if record <= 3000: + batches.append(([2 * record], False)) + case "batch" if batch <= 20_000: + size = min(record, batch) - 500 + batches.append(([size] * (batch // size + 1), False)) + case _: + fits = [rng.randrange(40)] * rng.randrange(1, min(count, 3) + 1) + batches.append((fits, True)) + store = FaultStore() + streams = stream_client( + client, + store, + max_record_bytes=record, + max_batch_bytes=batch, + max_batch_records=count, + ) + + def calls(stream_id: str) -> list[list[Any]]: + appends = [["x" * size for size in sizes] for sizes, _ in batches] + return [["create", stream_id]] + [ + ["append", stream_id, bodies] for bodies in appends + ] + + from_client = await _answers(streams, calls(f"client {seed}")) + workflow_calls = calls(f"workflow {seed}") + if record <= 3000: + # A client with a larger limit writes a Record over the limit of the + # Worker, and a read of Workflow code refuses that Record. + writer = stream_client(client, store) + large = await writer.create_stream(id=f"large {seed}", body_type=str) + await large.append("x" * 2 * record) + workflow_calls.append(["read", f"large {seed}"]) + options = RunOptions(_CallsWorkflow, [workflow_calls], replay=True) + from_workflow = (await run(streams, options)).result + if record <= 3000: + assert from_workflow.pop()[:2] == ["error", unsupported] + for answers in (from_client, from_workflow): + assert [ + "written" if answer[0] != "error" else answer[1] + for answer in answers[1:] + ] == ["written" if fits else too_large for _, fits in batches] + # The Store got the batches within the limits from each path, and no other. + assert [ + len(request.records) + for request in store.requests + if isinstance(request, AppendRecordsRequest) + and request.stream_id != f"large {seed}" + ] == [len(sizes) for sizes, fits in batches if fits] * 2 + + @workflow.defn class _ChainWorkflow: @workflow.run @@ -487,3 +935,726 @@ async def test_a_create_in_a_later_run_of_the_chain_is_the_same_create( assert ran.result is True creates = [i for r, i in store.calls if isinstance(r, CreateStreamRequest)] assert len(creates) == 4 and len(set(creates)) == 1 + + +_handled: dict[int, asyncio.Event] = {} +"""An event for each Record of the writing Activity, set once the Workflow handled +it.""" + + +@activity.defn +async def _write_one_by_one(stream_id: str, count: int) -> None: + client = activity.client() + stream = client.get_stream(StreamRef[str](id=stream_id)) + workflow_id = activity.info().workflow_id or "" + for number in range(count): + await stream.append(f"a body, number {number}") + # A read makes no Workflow Task for a Record that SDK Core doesn't know of, so + # the writer signals the Workflow. + await client.get_workflow_handle(workflow_id).signal(_ReadingWorkflow.wake) + # The next Record comes only once the Workflow has handled this one. + await _handled[number].wait() + + +@activity.defn +async def _handle(number: int) -> None: + _handled[number].set() + + +@workflow.defn +class _ReadingWorkflow: + @workflow.signal + def wake(self) -> None: + pass + + @workflow.run + async def run(self, stream_id: str, count: int) -> list[int]: + stream = await workflow.create_stream(id=stream_id, body_type=str) + writer = workflow.start_activity( + _write_one_by_one, + args=[stream_id, count], + start_to_close_timeout=timedelta(seconds=30), + ) + numbers: list[int] = [] + async for record in stream.read(wait=timedelta(seconds=30)): + number = int(record.body.rsplit(" ", 1)[1]) + await workflow.execute_activity( + _handle, number, start_to_close_timeout=timedelta(seconds=30) + ) + numbers.append(number) + # A Stream has no end, so the reader stops at the writer's last Record. + if number == count - 1: + break + await writer + return numbers + + +async def test_a_workflow_reads_the_records_of_an_activity_that_still_runs( + client: Client, +) -> None: + count = 5 + for cached in (True, False): + with failure_note(f"cached {cached}"): + _handled.clear() + _handled.update({number: asyncio.Event() for number in range(count)}) + options = RunOptions( + _ReadingWorkflow, + [f"read while written, cached {cached}", count], + activities=[_write_one_by_one, _handle], + cached=cached, + replay=True, + ) + ran = await run(stream_client(client, FaultStore()), options) + assert ran.result == list(range(count)) + assert not any( + b"a body" in event.SerializeToString() for event in ran.history.events + ) + + +@workflow.defn +class _EndingWorkflow: + """Starts a Stream call that nothing awaits, and ends in the way of ``how``.""" + + def __init__(self) -> None: + self._signals = 0 + + @workflow.signal + def go_on(self) -> None: + self._signals += 1 + + @workflow.run + async def run(self, stream_id: str, how: str) -> None: + stream = await workflow.create_stream(id=stream_id, body_type=int) + if how == "append": + asyncio.ensure_future(stream.append(1)) + elif how == "page": + await stream.append(1) + await stream.read_page(wait=timedelta(minutes=5)) + return + else: + asyncio.ensure_future(stream.read_page(wait=timedelta(minutes=5))) + await workflow.wait_condition(lambda: self._signals > 0) + # The task of the call makes its call in its first step. + await asyncio.sleep(0) + + +async def test_a_read_that_core_stops_leaves_no_store_task(client: Client) -> None: + # The read limit of the task stops a held Store call, also while the Worker shuts + # down, since the shutdown waits for the task. + for how in ("read limit", "shutdown"): + with failure_note(how): + store, hold = FaultStore(), Hold() + store.faults["read_records"].append(hold) + + async def end(handle: Any, worker: Worker) -> None: + await hold.started.wait() + if how == "shutdown": + await worker.shutdown() + else: + await handle.signal(_EndingWorkflow.go_on) + await asyncio.wait_for(hold.cancelled.wait(), 10) + if how == "shutdown": + await handle.terminate() + + # A task timeout of 2 seconds gives a read limit of 1 second. + options = RunOptions( + _EndingWorkflow, + [f"ends by {how}", how], + task_timeout=timedelta(seconds=2), + during=end, + replay=True, + ) + ran = await run(stream_client(client, store), options) + assert (ran.result is None) == (how == "read limit") + reads = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] + assert len(reads) == 1 + + +@pytest.mark.parametrize("how", ["page", "append"]) +async def test_a_stream_call_does_not_hold_the_last_command( + client: Client, how: str +) -> None: + # A read that gave a page, and an append that nothing awaits, don't hold + # the last command, so the Workflow ends in the task of the call. + options = RunOptions(_EndingWorkflow, [f"ends after its {how}", how], replay=True) + ran = await run(stream_client(client, FaultStore()), options) + assert ran.result is None + assert len(_events(ran.history, EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED)) == 1 + + +@workflow.defn +class _LatePagesWorkflow: + """Reads Records that come in a later Workflow Task than the one of its reads.""" + + @workflow.signal + def wake(self) -> None: + pass + + @workflow.run + async def run(self, how: str) -> list[list[str]]: + s = workflow.get_stream(StreamRef[str](id=f"s of {how}")) + t = workflow.get_stream(StreamRef[str](id=f"t of {how}")) + if how == "two readers": + # One reader takes a page of `s` and stops. The other waits for a page of + # `t`, and then reads `s` on from the offset of the first one. + first = asyncio.ensure_future(self._page(s)) + await self._page(t) + offset = (await first).records[-1].offset + second = await self._page(s, offset) + return [[r.body for r in page.records] for page in (await first, second)] + pages: list[list[str]] = [] + offset = None + while True: + page = await s.read_page(after_offset=offset, wait=timedelta(seconds=30)) + pages.append([record.body for record in page.records]) + if page.records: + offset = page.records[-1].offset + # A Stream has no end, so the loop stops at the writer's last Record. + if "b" in pages[-1]: + return pages + + async def _page(self, stream: Any, offset: bytes | None = None) -> Any: + """Return the first page of ``stream`` after ``offset`` that has a Record.""" + while True: + # At the read limit of its task, a read gives a page with no Record. + page = await stream.read_page( + after_offset=offset, wait=timedelta(seconds=30) + ) + if page.records: + return page + + +@pytest.mark.parametrize("how", ["a loop", "two readers"]) +async def test_a_replay_gives_a_read_the_pages_of_the_first_run( + client: Client, how: str +) -> None: + store = FaultStore() + client = stream_client(client, store) + s = await client.create_stream(id=f"s of {how}", body_type=str) + t = await client.create_stream(id=f"t of {how}", body_type=str) + writes, expected = { + "a loop": ([(s, "a"), (s, "b")], ["a", "b"]), + "two readers": ([(s, "a"), (t, "x"), (s, "b")], ["a", "b"]), + }[how] + + async def write(handle: Any, _worker: Any) -> None: + async def first_task() -> None: + history = await handle.fetch_history() + completed = EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED + assert _events(history, completed) + + # The reads of the first task end with no Record, and a read of an idle Stream + # makes no task. A Signal opens the next task, whose reads start again. The + # pages then come in several activations of that task, and a replay gives each + # page in its activation. + await assert_eventually(first_task) + await handle.signal(_LatePagesWorkflow.wake) + for stream, body in writes: + await stream.append(body) + # The page of this Record gets an activation before the next Record comes. + await asyncio.sleep(0.3) + + # The default read limit is half the task timeout, so a read with no Record + # is cut at 3 s, and a slow host still doesn't time out the task. + options = RunOptions( + _LatePagesWorkflow, + [how], + task_timeout=timedelta(seconds=6), + during=write, + replay=True, + ) + ran = await run(client, options) + assert [body for page in ran.result for body in page] == expected + events = [event.event_type for event in ran.history.events] + completed = events.index(EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED) + marker = EventType.EVENT_TYPE_MARKER_RECORDED + later = [event for event in events[completed + 1 :] if event != marker] + assert later[0] == EventType.EVENT_TYPE_WORKFLOW_EXECUTION_SIGNALED + + +@workflow.defn +class _TwoReadsWorkflow: + @workflow.run + async def run(self, first: str, second: str) -> list[list[str]]: + wait = timedelta(seconds=30) + streams = [workflow.get_stream(StreamRef[str](id=id)) for id in (first, second)] + pages = await asyncio.gather( + *(stream.read_page(wait=wait) for stream in streams) + ) + return [[record.body for record in page.records] for page in pages] + + +async def test_a_replay_gives_each_result_in_the_activation_of_the_first_run( + client: Client, +) -> None: + # A local import, so the sandbox of each Workflow here doesn't import that module. + from tests.worker.test_workflow import CustomWorkflowRunner + + store, holds = FaultStore(), [Hold(), Hold()] + store.faults["read_records"].extend(holds) + client = stream_client(client, store) + for stream_id in ("first", "second"): + stream = await client.create_stream(id=stream_id, body_type=str) + await stream.append(stream_id) + live, replayed = CustomWorkflowRunner(), CustomWorkflowRunner() + + def read_results(runner: CustomWorkflowRunner) -> list[list[int]]: + """Return the seqs of the read results of each activation that has one.""" + activations = [ + [ + job.resolve_stream_read.seq + for job in activation.jobs + if job.HasField("resolve_stream_read") + ] + for activation, _ in runner._pairs + ] + return [seqs for seqs in activations if seqs] + + async def release(_handle: Any, _worker: Any) -> None: + # Both reads wait in the first task, and each page comes before its read limit. + for hold in holds: + await hold.started.wait() + for count, hold in enumerate(holds, 1): + hold.release() + + async def given() -> None: + assert len(read_results(live)) == count + + # This page gets its activation before the Store answers the other read. + await assert_eventually(given) + + options = RunOptions( + _TwoReadsWorkflow, + ["first", "second"], + worker={"workflow_runner": live}, + during=release, + ) + ran = await run(client, options) + assert ran.result == [["first"], ["second"]] + await Replayer( + workflows=[_TwoReadsWorkflow], + workflow_runner=replayed, + stream_config=client._config["stream_config"], + ).replay_workflow(ran.history) + assert len(read_results(live)) == 2 + assert read_results(replayed) == read_results(live) + + +@workflow.defn +class _ReadOnceWorkflow: + def __init__(self) -> None: + self._go_on = False + + @workflow.signal + def go_on(self) -> None: + self._go_on = True + + @workflow.run + async def run(self, stream_id: str) -> list[int]: + stream = workflow.get_stream(StreamRef[int](id=stream_id)) + bodies: list[int] = [] + async for record in stream.read(): + bodies.append(record.body) + # A Stream has no end, so the reader stops at the writer's last Record. + if record.body == 3: + break + await workflow.wait_condition(lambda: self._go_on) + return bodies + + +@workflow.defn(failure_exception_types=[workflow.StreamReplayError]) +class _ReadOnceOptedInWorkflow(_ReadOnceWorkflow): + @workflow.run + async def run(self, stream_id: str) -> list[int]: + return await super().run(stream_id) + + +async def test_a_replay_reads_its_python_stores(client: Client) -> None: + store = FaultStore() + stream = await stream_client(client, store).create_stream( + id="replayed", body_type=int + ) + await stream.append(1, 2, 3) + + async def go_on(handle: Any, _worker: Any) -> None: + await handle.signal(_ReadOnceWorkflow.go_on) + + options = RunOptions(_ReadOnceWorkflow, ["replayed"], during=go_on) + ran = await run(stream_client(client, store), options) + assert ran.result == [1, 2, 3] + # A `Replayer` reads the Records again from the Store, and fails without them. + replayer = Replayer( + workflows=[_ReadOnceWorkflow], + stream_config=temporalio.streams.StreamConfig([store]), + ) + reads = len(store.requests) + await replayer.replay_workflow(ran.history) + assert isinstance(store.requests[reads], ReadRecordsRequest) + store.memory = MemoryStreamStore() + with pytest.raises(RuntimeError): + await replayer.replay_workflow(ran.history) + + # A Worker with no cache replays the read in its second task. With the Records gone + # the task fails, or the Workflow with the opt-in of the Worker or of the Workflow. + cases: dict[str, tuple[type, list[type[BaseException]]]] = { + "no opt-in": (_ReadOnceWorkflow, []), + "the Worker option": (_ReadOnceWorkflow, [workflow.StreamReplayError]), + "the Workflow option": (_ReadOnceOptedInWorkflow, []), + } + for case, (workflow_class, failure_types) in cases.items(): + with failure_note(case): + store = FaultStore() + stream_id = f"gone with {case}" + stream = await stream_client(client, store).create_stream( + id=stream_id, body_type=int + ) + await stream.append(1, 2, 3) + + async def lose_the_records(handle: Any, _worker: Any) -> None: + async def has_read() -> None: + history = await handle.fetch_history() + assert _stream_markers(history, "read") + + await assert_eventually(has_read) + store.memory = MemoryStreamStore() + await handle.signal(_ReadOnceWorkflow.go_on) + if case == "no opt-in": + await assert_task_fail_eventually(handle) + await handle.terminate() + + options = RunOptions( + workflow_class, + [stream_id], + cached=False, + worker={"workflow_failure_exception_types": failure_types}, + during=lose_the_records, + ) + ran = await run(stream_client(client, store), options) + assert isinstance(ran.result, WorkflowFailureError) + if case != "no opt-in": + cause = ran.result.cause + assert isinstance(cause, ApplicationError) + assert cause.type == "StreamReplayError" + failed = _events(ran.history, EventType.EVENT_TYPE_WORKFLOW_TASK_FAILED) + assert not failed + + +@workflow.defn +class _ReadAllWorkflow: + @workflow.run + async def run(self, stream_id: str, limits: dict[str, int]) -> list[int]: + stream = workflow.get_stream(StreamRef[int](id=stream_id)) + records = stream.read( + wait=timedelta(minutes=5), + max_records=limits.get("max_records"), + max_bytes=limits.get("max_bytes"), + ) + bodies: list[int] = [] + async for record in records: + bodies.append(record.body) + # A Stream has no end, so the reader stops at the writer's last Record. + if record.body == 3: + break + return bodies + + +async def test_a_workflow_read_asks_the_store_with_its_limits(client: Client) -> None: + store = FaultStore() + client = stream_client(client, store) + stream = await client.create_stream(id="paged", body_type=int) + await stream.append(1, 2, 3) + + # A read with no limit asks for 256 Records and 4 MiB. SDK Core asks the Store for + # room for one Record more, since it acts on whether the Stream has more. That + # Record has at most the Record size of the config and an offset of 1024 bytes, + # each in its field. A Store call waits at most the read time of the Worker, + # which is shorter than the wait of the read. + def field(size: int) -> int: + return 1 + (size.bit_length() + 6) // 7 + size + + one_more = field( + temporalio.streams.StreamConfig([store]).max_record_bytes + field(1024) + ) + cases: list[tuple[dict[str, int], tuple[int, int]]] = [ + ({"max_records": 1, "max_bytes": 100}, (2, 100 + one_more)), + ({}, (257, 4 * 1024 * 1024 + one_more)), + ] + read_time = timedelta(seconds=2) + for limits, expected in cases: + with failure_note(f"limits {limits}"): + store.calls.clear() + options = RunOptions( + _ReadAllWorkflow, + ["paged", limits], + worker={"stream_read_time": read_time}, + ) + ran = await run(client, options) + assert ran.result == [1, 2, 3] + reads = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] + asked = [(r.max_records, r.max_bytes) for r in reads] + # With one Record in a page, the read of each Record is one Store call. + assert asked == [expected] * (3 if limits else 1) + waits = [r.wait.ToTimedelta() for r in reads] + assert timedelta(0) < waits[0] and max(waits) <= read_time + # A replay asks for the Records that History recorded, and no more. + store.calls.clear() + await Replayer( + workflows=[_ReadAllWorkflow], + stream_config=client._config["stream_config"], + ).replay_workflow(ran.history) + replayed = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] + assert [r.max_records for r in replayed] == ([1] * 3 if limits else [3]) + + +@workflow.defn +class _QuietReadWorkflow: + @workflow.signal + def wake(self) -> None: + pass + + @workflow.run + async def run(self, stream_id: str) -> list[int]: + stream = workflow.get_stream(StreamRef[int](id=stream_id)) + bodies: list[int] = [] + offset = None + # The writer's last Record is 2, since a Stream has no end. + while 2 not in bodies: + page = await stream.read_page( + after_offset=offset, wait=timedelta(minutes=5) + ) + bodies.extend(record.body for record in page.records) + if page.records: + offset = page.records[-1].offset + return bodies + + +async def test_a_workflow_read_of_a_quiet_stream_makes_no_workflow_task( + client: Client, +) -> None: + store = FaultStore() + client = stream_client(client, store) + stream = await client.create_stream(id="quiet", body_type=int) + completed = EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED + + async def write(handle: Any, _worker: Any) -> None: + async def first_task() -> None: + assert _events(await handle.fetch_history(), completed) + + # On a quiet Stream, the reads get pages with no Record until the read limit, + # and the task then completes with no new task, over several read limits. + await assert_eventually(first_task) + await asyncio.sleep(1) + history = await handle.fetch_history() + assert len(_events(history, EventType.EVENT_TYPE_WORKFLOW_TASK_STARTED)) == 1 + quiet = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] + assert quiet and not any(r.after_offset for r in quiet) + # The read starts again from the same offset in the task of a Signal. + await stream.append(1, 2) + await handle.signal(_QuietReadWorkflow.wake) + + options = RunOptions( + _QuietReadWorkflow, + ["quiet"], + worker={"stream_read_time": timedelta(milliseconds=300)}, + during=write, + replay=True, + ) + assert (await run(client, options)).result == [1, 2] + + +@workflow.defn +class _FirstRecordWorkflow: + @workflow.signal + def wake(self) -> None: + pass + + @workflow.run + async def run(self, stream_id: str, seconds: float | None = 5) -> list[int]: + stream = workflow.get_stream(StreamRef[int](id=stream_id)) + wait = None if seconds is None else timedelta(seconds=seconds) + async for record in stream.read(wait=wait): + return [record.body] + raise AssertionError("A Workflow reader never ends by itself") + + +async def test_a_workflow_read_goes_on_after_the_read_limit_cut_its_wait( + client: Client, +) -> None: + store = FaultStore() + client = stream_client(client, store) + stream = await client.create_stream(id="cut", body_type=int) + + async def write(handle: Any, _worker: Any) -> None: + async def cut_page() -> None: + history = await handle.fetch_history() + markers = _stream_markers(history, "read") + assert any(b'"wait_cut":true' in m.SerializeToString() for m in markers) + assert _events(history, EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED) + + # The read limit cuts the wait of 5 s at 1 s. The iterator reads again, and + # that read waits for the next task, which a Signal opens. + await assert_eventually(cut_page) + await stream.append(1) + await handle.signal(_FirstRecordWorkflow.wake) + + options = RunOptions( + _FirstRecordWorkflow, + ["cut"], + worker={"stream_read_time": timedelta(seconds=1)}, + during=write, + replay=True, + ) + assert (await run(client, options)).result == [1] + + +async def test_a_workflow_iterator_with_no_wait_parks_on_an_idle_stream( + client: Client, +) -> None: + store = FaultStore() + client = stream_client(client, store) + stream = await client.create_stream(id="idle", body_type=int) + + async def write(handle: Any, _worker: Any) -> None: + async def first_task() -> None: + completed = EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED + assert _events(await handle.fetch_history(), completed) + + # The first read gives the empty answer of the Store immediately. The later ones + # have the default wait. The read limit cuts a few of them, then one parks, + # so the idle Stream makes no new task over several read limits. + await assert_eventually(first_task) + await asyncio.sleep(4) + history = await handle.fetch_history() + tasks = _events(history, EventType.EVENT_TYPE_WORKFLOW_TASK_STARTED) + markers = _stream_markers(history, "read") + assert len(tasks) == 1, len(tasks) + assert 2 <= len(markers) <= 6, len(markers) + await stream.append(1) + await handle.signal(_FirstRecordWorkflow.wake) + + options = RunOptions( + _FirstRecordWorkflow, + ["idle", None], + task_timeout=timedelta(seconds=10), + worker={"stream_read_time": timedelta(seconds=1)}, + during=write, + replay=True, + ) + ran = await asyncio.wait_for(run(client, options), 30) + assert ran.result == [1] + + +async def test_a_workflow_read_with_no_wait_reads_again_in_the_next_task( + client: Client, +) -> None: + store, hold = FaultStore(), Hold() + stream = await stream_client(client, store).create_stream(id="slow", body_type=int) + await stream.append(1, 2, 3) + store.faults["read_records"].append(hold) + + async def release(handle: Any, _worker: Any) -> None: + async def task_completed() -> None: + history = await handle.fetch_history() + completed = EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED + assert _events(history, completed) + + # The read goes on at the read limit, since only the Store can say that the + # Stream has no Record. The task then completes, which stops the held read, + # and the read starts again in the task of the Signal. + await assert_eventually(task_completed) + await asyncio.wait_for(hold.cancelled.wait(), 10) + await handle.signal(_ReadOnceWorkflow.go_on) + + options = RunOptions( + _ReadOnceWorkflow, + ["slow"], + task_timeout=timedelta(seconds=2), + during=release, + replay=True, + ) + assert (await run(stream_client(client, store), options)).result == [1, 2, 3] + reads = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] + assert len([r for r in reads if not r.after_offset]) >= 2 + + +@dataclasses.dataclass +class _Turn: + text: str + + +@dataclasses.dataclass +class _AgentInput: + turns: StreamRef[_Turn] | None = None + + +@dataclasses.dataclass +class _TurnsInput: + turns: StreamRef[_Turn] + texts: list[str] + + +@activity.defn +async def _append_turns(input: _TurnsInput) -> None: + stream = activity.client().get_stream(input.turns) + await stream.append(*(_Turn(text) for text in input.texts)) + + +@workflow.defn +class _AgentWorkflow: + def __init__(self) -> None: + self._turns: StreamRef[_Turn] | None = None + self._go_on = False + + @workflow.query + def turns(self) -> StreamRef[_Turn] | None: + return self._turns + + @workflow.signal + def go_on(self) -> None: + self._go_on = True + + @workflow.run + async def run(self, input: _AgentInput) -> list[str]: + self._turns = input.turns + await workflow.wait_condition(lambda: self._go_on) + if self._turns is None: + created = await workflow.create_stream(id="turns", body_type=_Turn) + self._turns = created.ref + await workflow.execute_activity( + _append_turns, + _TurnsInput(self._turns, ["a", "b"]), + start_to_close_timeout=timedelta(seconds=10), + ) + page = await workflow.get_stream(self._turns).read_page() + # Only a body that the read converted to its type has the attribute. + return [record.body.text for record in page.records] + + +async def test_a_stream_ref_keeps_its_type_through_a_workflow(client: Client) -> None: + streams = stream_client(client, MemoryStreamStore()) + ref: Any = None + # The first run gets no ref and creates the Stream. The second one gets that ref. + for texts in (["a", "b"], ["a", "b", "a", "b"]): + with failure_note(f"texts {texts}"): + + async def answer(handle: Any, _worker: Any) -> None: + nonlocal ref + assert await handle.query(_AgentWorkflow.turns) == ref + await handle.signal(_AgentWorkflow.go_on) + await handle.result() + ref = await handle.query(_AgentWorkflow.turns) + + options = RunOptions( + _AgentWorkflow, + [_AgentInput(ref)], + activities=[_append_turns], + during=answer, + replay=True, + ) + assert (await run(streams, options)).result == texts + assert ref == StreamRef(id="turns", store="memory") + # The ref of the query has the body type, so the read needs no `body_type=`. + page = await streams.get_stream(ref).read_page() + assert [record.body for record in page.records] == [ + _Turn(text) for text in texts + ] diff --git a/tests/test_converter.py b/tests/test_converter.py index b47cadbdd..8897dbb3a 100644 --- a/tests/test_converter.py +++ b/tests/test_converter.py @@ -59,6 +59,7 @@ ) from temporalio.converter._payload_converter import ( _TemporalTransferTypePayloadConverter, + _typed_decode_types, ) from temporalio.exceptions import ( ApplicationError, @@ -388,6 +389,28 @@ def from_transfer_type( ) +class TemporalTransferTypeJSONValueConverter( + TransferTypeConverter["TemporalTransferTypeJSONValue", dict[str, str]] +): + transfer_type = dict[str, str] + + def to_transfer_type(self, value: TemporalTransferTypeJSONValue) -> dict[str, str]: + return {"id": value.value} + + def from_transfer_type( + self, + value: dict[str, str], + type_hint: type[TemporalTransferTypeJSONValue], + ) -> TemporalTransferTypeJSONValue: + return TemporalTransferTypeJSONValue(value=value["id"]) + + +@transfer_type_convertible(TemporalTransferTypeJSONValueConverter) +@dataclass +class TemporalTransferTypeJSONValue: + value: str + + class CustomDefaultPayloadConverter(DefaultPayloadConverter): pass @@ -455,6 +478,55 @@ def test_temporal_transfer_type_payload_converter_with_generic_value( assert converter.from_payload(payload, type_hint) == value +def _decode_typed(monkeypatch: pytest.MonkeyPatch, *types: type) -> None: + """Let ``types`` decode by their type arguments and under ``T | None`` in one + test.""" + monkeypatch.setattr( + "temporalio.converter._payload_converter._typed_decode_types", + _typed_decode_types | set(types), + ) + + +@pytest.mark.parametrize( + ("value", "type_hint"), + [ + (TemporalTransferTypeValue("workflow-id"), TemporalTransferTypeValue | None), + (None, TemporalTransferTypeValue | None), + ( + TemporalTransferTypeValueWithoutHint("workflow-id"), + TemporalTransferTypeValueWithoutHint | None, + ), + ( + TemporalTransferTypeGenericValue(123), + TemporalTransferTypeGenericValue[int] | None, + ), + (None, TemporalTransferTypeGenericValue[int] | None), + (TemporalTransferTypeValue("workflow-id"), None | TemporalTransferTypeValue), + (TemporalTransferTypeJSONValue("id"), TemporalTransferTypeJSONValue | None), + (None, TemporalTransferTypeJSONValue | None), + ], +) +def test_temporal_transfer_type_payload_converter_with_optional_hint( + value: Any, type_hint: Any, monkeypatch: pytest.MonkeyPatch +): + _decode_typed( + monkeypatch, + TemporalTransferTypeValue, + TemporalTransferTypeValueWithoutHint, + TemporalTransferTypeGenericValue, + TemporalTransferTypeJSONValue, + ) + converter = DataConverter.default.payload_converter + + payloads = [converter.to_payload(value)] + if value is None: + # A converter of another SDK can write None as a JSON null. + payloads.append(Payload(metadata={"encoding": b"json/plain"}, data=b"null")) + + for payload in payloads: + assert converter.from_payload(payload, type_hint) == value + + def test_transfer_type_convertible_rejects_existing_converter(): with pytest.raises(TypeError, match="already has a transfer type converter"): transfer_type_convertible(TemporalTransferTypeValueConverter)( @@ -564,6 +636,14 @@ class InitFalseIntDataClass: bar: int = dataclasses.field(default=0, init=False) +@dataclass +class GenericDataClass(Generic[T]): + value: T + items: list[T] = dataclasses.field(default_factory=list) + nested: GenericDataClass[T] | None = None + maybe: T | None = None + + class MyTypedDict(TypedDict): foo: str bar: MyDataClass @@ -605,6 +685,61 @@ def test_json_nested_frozenset_round_trip(): assert converter.from_payload(payload, set[frozenset[int]]) == value +K = TypeVar("K") + + +@dataclass +class GenericPairDataClass(Generic[K, T]): + key: K + value: T + + +def test_json_generic_dataclass_round_trip(monkeypatch: pytest.MonkeyPatch): + converter = JSONPlainPayloadConverter() + # mypy takes a type argument from a variable only on a value of type Any + generic_type: Any = GenericDataClass + pair_type: Any = GenericPairDataClass + + # A generic dataclass that isn't registered keeps its decoding, which the replay of + # an existing History needs. + payload = converter.to_payload(GenericDataClass(1)) + assert payload + with pytest.raises(TypeError): + converter.from_payload(payload, generic_type[int]) + generic_or_dict: Any = generic_type[int] | dict + assert converter.from_payload(payload, generic_or_dict) == { + "value": 1, + "items": [], + "nested": None, + "maybe": None, + } + + _decode_typed(monkeypatch, GenericDataClass, GenericPairDataClass) + + for argument, value in [ + (int, GenericDataClass(1, items=[2], nested=GenericDataClass(3), maybe=4)), + (str, GenericDataClass("text")), + (list[int], GenericDataClass([1], items=[[2], []], maybe=[3])), + (MyDataClass, GenericDataClass(MyDataClass("foo", 1, SerializableEnum.FOO))), + (GenericDataClass[str], GenericDataClass(GenericDataClass("nested"))), + ]: + payload = converter.to_payload(value) + assert payload + decoded = converter.from_payload(payload, generic_type[argument]) + assert decoded == value + assert decoded.__orig_class__ == generic_type[argument] + + payload = converter.to_payload({"value": "not an integer"}) + assert payload + with pytest.raises(TypeError): + converter.from_payload(payload, generic_type[int]) + + pair = GenericPairDataClass(key=1, value="text") + payload = converter.to_payload(pair) + assert payload + assert converter.from_payload(payload, pair_type[int, str]) == pair + + def test_json_type_hints(): converter = JSONPlainPayloadConverter() diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py index 66b36fd53..fe78ae353 100644 --- a/tests/worker/test_workflow_streams.py +++ b/tests/worker/test_workflow_streams.py @@ -8,16 +8,19 @@ from typing import Any import pytest +from google.protobuf.duration_pb2 import Duration from google.protobuf.message import Message import temporalio.api.common.v1 import temporalio.bridge.worker import temporalio.common import temporalio.converter +import temporalio.converter._extstore +import temporalio.nexus.system import temporalio.streams import temporalio.worker from temporalio import workflow -from temporalio.api.common.v1 import ActivityType +from temporalio.api.common.v1 import ActivityType, Payload from temporalio.api.enums.v1 import RetryState, StreamErrorReason, TimeoutType from temporalio.api.failure.v1 import ( ActivityFailureInfo, @@ -32,6 +35,7 @@ StreamRef, ) from temporalio.api.sdk.v1.external_storage_pb2 import ExternalStorageReference +from temporalio.api.stream.v1 import StreamRecord from temporalio.api.streamservice.v1 import DescribeStreamResponse from temporalio.bridge.proto.activity_result import ( ActivityResolution, @@ -42,13 +46,17 @@ RemoveFromCache, ResolveActivity, ResolveStreamAppend, + ResolveStreamRead, + SignalWorkflow, StreamAppended, + StreamPage, WorkflowActivation, WorkflowActivationJob, ) from temporalio.bridge.proto.workflow_commands import ( AppendToStream, CompleteWorkflowExecution, + ReadStream, RequestCancelLocalActivity, WorkflowCommand, ) @@ -61,6 +69,7 @@ WorkflowSerializationContext, ) from temporalio.exceptions import ApplicationError, StreamError +from temporalio.nexus.system import _support from temporalio.nexus.system.stream_service import StreamRef as ModelRef from temporalio.nexus.system.stream_service.models import ( CreateStreamResult, @@ -70,11 +79,13 @@ from temporalio.worker._workflow import _CommandAwareDataConverter from temporalio.worker._workflow_instance import ( _WorkflowInstanceImpl, + _WorkflowLogicFlag, # type: ignore[reportPrivateLocalImportUsage] ) from tests.helpers.streams import ( CodecCall, ContextCodec, core_failure, + failure_note, wrapped, ) from tests.test_extstore import InMemoryTestDriver @@ -199,6 +210,13 @@ async def test_stream_payloads_take_the_codec_with_no_context_and_no_storage() - assert driver._store_calls == 1 assert calls == [("encode", None, 1)] * 2 + [("encode", context, 1)] + # A writer with no codec can write a claim of a payload in this Worker's storage, + # and a body that has the mark of a system Nexus envelope. + claim = Payload() + claim.CopyFrom(stored) + claim.metadata[temporalio.converter._extstore._REFERENCE_MARKER_KEY] = b"true" + envelope = to_payload("envelope") + envelope.metadata[temporalio.nexus.system._SYSTEM_PAYLOAD_METADATA_KEY] = b"true" failure = Failure( message="A later attempt has written to the Stream", application_failure_info=ApplicationFailureInfo( @@ -206,8 +224,23 @@ async def test_stream_payloads_take_the_codec_with_no_context_and_no_storage() - details=temporalio.api.common.v1.Payloads(payloads=[wrapped(result)]), ), ) + records = [*append.append_to_stream.bodies, claim, envelope] activation = WorkflowActivation( jobs=[ + WorkflowActivationJob( + resolve_stream_read=ResolveStreamRead( + seq=1, + page=StreamPage( + records=[ + StreamRecord(body=body, offset=bytes([at + 1])) + for at, body in enumerate(records) + ] + ), + ) + ), + WorkflowActivationJob( + resolve_stream_read=ResolveStreamRead(seq=2, failed=failure) + ), WorkflowActivationJob( resolve_stream_append=ResolveStreamAppend(seq=1, failed=failure) ), @@ -223,11 +256,17 @@ async def test_stream_payloads_take_the_codec_with_no_context_and_no_storage() - await temporalio.bridge.worker.decode_activation( activation, command_aware, decode_headers=True, storage_concurrency_limit=1 ) - appended, activity = activation.jobs + read, failed_read, appended, activity = activation.jobs + assert [record.body for record in read.resolve_stream_read.page.records] == [ + *bodies, + claim, + envelope, + ] + assert failed_read.resolve_stream_read.failed == failure assert appended.resolve_stream_append.failed == failure assert activity.resolve_activity.result.completed.result == result assert driver._retrieve_calls == 1 - assert calls == [("decode", context, 1)] + assert calls == [("decode", None, 1)] * 4 + [("decode", context, 1)] _REFUSALS = [ @@ -609,3 +648,500 @@ def selector( instance, WorkflowActivationJob(remove_from_cache=RemoveFromCache()) ) ).HasField("successful") + + +class _EachCall: + """The calls of :py:class:`_EachCallWorkflow`, and what its selector saw.""" + + operations: list[str] = [] + instance: _WorkflowInstanceImpl | None = None + selects: list[tuple[str, int]] = [] + """The Stream id of each selector call, with the number of commands before it.""" + + +@workflow.defn +class _EachCallWorkflow: + @workflow.run + async def run(self) -> None: + calls: list[Any] = [] + for at, operation in enumerate(_EachCall.operations): + stream = workflow.get_stream(ModelRef[int](id=f"s{at}")) + if operation == "create": + calls.append(workflow.create_stream(id=f"s{at}", body_type=int)) + elif operation == "append": + calls.append(stream.append(at)) + elif operation == "read": + calls.append(stream.read_page()) + else: + calls.append(stream.describe()) + if len(calls) == 1: + # The run gets the error of its one call, so no task holds an error that + # no one reads. + await calls[0] + return + tasks = [asyncio.ensure_future(call) for call in calls] + # Each task makes its call in its first step. + await asyncio.sleep(0) + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + + +def _store_of(command: WorkflowCommand) -> str: + """Return the Store name that the command of a Stream call has.""" + variant = command.WhichOneof("variant") + if variant == "append_to_stream": + return command.append_to_stream.stream.store + if variant == "read_stream": + return command.read_stream.stream.store + # The Local Activity of a create or a describe has the Store name second. + [_, store, *_] = command.schedule_local_activity.arguments + return temporalio.converter.DefaultPayloadConverter().from_payload(store, str) + + +async def test_the_store_of_a_call_is_chosen_before_its_command() -> None: + operations = ["create", "append", "read", "describe"] + a, b = MemoryStreamStore(name="a"), MemoryStreamStore(name="b") + for on_b in ([False, True, False, True], [True, False, True, False]): + + def selector( + context: temporalio.streams.StreamSelectContext, + ) -> temporalio.streams.StreamStore: + assert _EachCall.instance + sent = _EachCall.instance._current_completion.successful.commands + _EachCall.selects.append((context.id, len(sent))) + return b if on_b[int(context.id[1:])] else a + + config = temporalio.streams.StreamConfig([a, b], store_selector=selector) + _EachCall.operations = operations + for replaying in (False, True): + with failure_note(f"on b {on_b}, replaying {replaying}"): + _EachCall.selects = [] + instance = _EachCall.instance = _new_instance(_EachCallWorkflow, config) + initialize = WorkflowActivationJob( + initialize_workflow=InitializeWorkflow() + ) + completion = await _activate(instance, initialize, replaying=replaying) + # The selector runs once for each call, before the command of the call. + assert _EachCall.selects == [ + (f"s{at}", at) for at in range(len(operations)) + ] + commands = completion.successful.commands + assert [command.WhichOneof("variant") for command in commands] == [ + "schedule_local_activity", + "append_to_stream", + "read_stream", + "schedule_local_activity", + # A cancel sends a command only for a Local Activity. + "request_cancel_local_activity", + "request_cancel_local_activity", + "complete_workflow_execution", + ] + assert [_store_of(command) for command in commands[:4]] == [ + "b" if mine else "a" for mine in on_b + ] + + +# SDK Core uses the only Store of a Worker for a ref with no Store name. The SDK +# picks that Store itself, so each command has its name. +async def test_a_ref_with_no_store_name_goes_to_the_only_store() -> None: + operations = ["create", "append", "read", "describe"] + config = temporalio.streams.StreamConfig([MemoryStreamStore(name="only")]) + _EachCall.operations = operations + for replaying in (False, True): + with failure_note(f"replaying {replaying}"): + instance = _new_instance(_EachCallWorkflow, config) + initialize = WorkflowActivationJob(initialize_workflow=InitializeWorkflow()) + completion = await _activate(instance, initialize, replaying=replaying) + commands = completion.successful.commands[: len(operations)] + assert [command.WhichOneof("variant") for command in commands] == [ + "schedule_local_activity", + "append_to_stream", + "read_stream", + "schedule_local_activity", + ] + stores = [_store_of(command) for command in commands] + assert stores == ["only"] * len(operations) + + +async def test_a_ref_with_no_store_name_needs_a_selector_for_two_stores() -> None: + a, b = MemoryStreamStore(name="a"), MemoryStreamStore(name="b") + with pytest.raises(ValueError, match="store_selector must be specified"): + temporalio.streams.StreamConfig([a, b]) + unregistered = MemoryStreamStore(name="c") + config = temporalio.streams.StreamConfig( + [a, b], store_selector=lambda _: unregistered + ) + for operation in ["create", "append", "read", "describe"]: + _EachCall.operations = [operation] + for replaying in (False, True): + with failure_note(f"{operation}, replaying {replaying}"): + instance = _new_instance(_EachCallWorkflow, config) + initialize = WorkflowActivationJob( + initialize_workflow=InitializeWorkflow() + ) + completion = await _activate(instance, initialize, replaying=replaying) + message = completion.failed.failure.message + assert "not registered in StreamConfig.stores" in message + + +async def test_a_stream_call_with_no_stream_config_fails_the_task() -> None: + for operation in ["create", "append", "read", "describe"]: + _EachCall.operations = [operation] + for replaying in (False, True): + instance = _new_instance(_EachCallWorkflow) + initialize = WorkflowActivationJob(initialize_workflow=InitializeWorkflow()) + completion = await _activate(instance, initialize, replaying=replaying) + assert "no stream_config" in completion.failed.failure.message, operation + + +@dataclass +class _ReadCall: + stream: str + start: int + """The offset that the first page comes after. Zero is the start of the Stream.""" + wait: timedelta | None + max_records: int | None + max_bytes: int | None + pages: int + """The maximum number of pages that the reader asks for.""" + body_type: Any + """The body type of the reader's Stream, which is ``int``, ``Any`` or none.""" + outcome: list[Any] = dataclasses.field(default_factory=list) + + +class _ReadScript: + calls: list[_ReadCall] = [] + steps: list[tuple[list[int], list[int]]] = [] + + +@workflow.defn +class _ReadsWorkflow: + def __init__(self) -> None: + self._readers: dict[int, asyncio.Future[None]] = {} + + @workflow.run + async def run(self) -> None: + await workflow.wait_condition(lambda: False) + + @workflow.signal + def step(self) -> None: + cancels, starts = _ReadScript.steps.pop(0) + for call in cancels: + self._readers[call].cancel() + for call in starts: + reader = self._read(_ReadScript.calls[call]) + self._readers[call] = asyncio.ensure_future(reader) + + async def _read(self, call: _ReadCall) -> None: + body_type: Any = call.body_type + ref: Any = ModelRef(id=call.stream, store="a") + if body_type: + ref = ModelRef[body_type](id=call.stream, store="a") + stream = workflow.get_stream(ref) + offset = _offset(call.start) or None + try: + for _ in range(call.pages): + page = await stream.read_page( + after_offset=offset, + wait=call.wait, + max_records=call.max_records, + max_bytes=call.max_bytes, + ) + bodies = [record.body for record in page.records] + if page.records: + offset = page.records[-1].offset + call.outcome.append((bodies, offset or b"")) + except StreamError as err: + call.outcome.append(err.reason) + except TypeError: + call.outcome.append("TypeError") + except asyncio.CancelledError: + call.outcome.append("cancelled") + raise + + +def _offset(number: int) -> bytes: + return number.to_bytes(8, "big") if number else b"" + + +_READ_FLAGS = [ + (), + (_WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH,), +] + + +async def _start_readers( + calls: list[_ReadCall], flags: Sequence[int], replaying: bool +) -> tuple[_WorkflowInstanceImpl, WorkflowActivationCompletion]: + _ReadScript.calls = calls + _ReadScript.steps = [([], list(range(len(calls))))] + instance = _new_instance( + _ReadsWorkflow, temporalio.streams.StreamConfig([MemoryStreamStore(name="a")]) + ) + completion = await _activate( + instance, + WorkflowActivationJob(initialize_workflow=InitializeWorkflow()), + WorkflowActivationJob(signal_workflow=SignalWorkflow(signal_name="step")), + flags=flags, + replaying=replaying, + ) + return instance, completion + + +def _read_result(seq: int, *records: tuple[int, Any]) -> WorkflowActivationJob: + converter = temporalio.converter.DefaultPayloadConverter() + return WorkflowActivationJob( + resolve_stream_read=ResolveStreamRead( + seq=seq, + page=StreamPage( + records=[ + StreamRecord(offset=_offset(at), body=converter.to_payload(body)) + for at, body in records + ], + ), + ) + ) + + +@pytest.mark.parametrize("flags", _READ_FLAGS) +@pytest.mark.parametrize("replaying", [False, True]) +async def test_read_pages_keep_their_sequence_and_cursor( + flags: Sequence[int], replaying: bool +) -> None: + calls = [ + _ReadCall("first", 1, timedelta(seconds=5), 2, 100, 2, int), + _ReadCall("second", 0, timedelta(0), None, None, 1, Any), + _ReadCall("untyped", 0, None, None, None, 1, None), + ] + instance, completion = await _start_readers(calls, flags, replaying) + expected = [ + ReadStream( + seq=1, + stream=StreamRef(id="first", store="a"), + after_offset=_offset(1), + wait=Duration(seconds=5), + max_records=2, + max_bytes=100, + ), + ReadStream(seq=2, stream=StreamRef(id="second", store="a"), wait=Duration()), + ] + assert list(completion.successful.commands) == [ + WorkflowCommand(read_stream=read) for read in expected + ] + assert calls[2].outcome == ["TypeError"] + + completion = await _activate( + instance, + _read_result(2, (3, "text")), + _read_result(1), + flags=flags, + replaying=replaying, + ) + assert [call.outcome for call in calls] == [ + [([], _offset(1))], + [(["text"], _offset(3))], + ["TypeError"], + ] + next_read = expected[0] + next_read.seq = 3 + assert list(completion.successful.commands) == [ + WorkflowCommand(read_stream=next_read) + ] + + reason = StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND + completion = await _activate( + instance, + WorkflowActivationJob( + resolve_stream_read=ResolveStreamRead(seq=3, failed=core_failure(reason)) + ), + flags=flags, + replaying=replaying, + ) + assert not completion.successful.commands + assert calls[0].outcome == [([], _offset(1)), reason] + assert not instance._streams._reads + assert not ( + await _activate( + instance, WorkflowActivationJob(remove_from_cache=RemoveFromCache()) + ) + ).successful.commands + + +@pytest.mark.parametrize("flags", _READ_FLAGS) +@pytest.mark.parametrize("replaying", [False, True]) +@pytest.mark.parametrize("when", ["before result", "with result", "after a page"]) +async def test_cancelled_reads_discard_later_results( + flags: Sequence[int], replaying: bool, when: str +) -> None: + call = _ReadCall("s", 0, None, None, None, 2, int) + instance, _ = await _start_readers([call], flags, replaying) + seq = 1 + expected: list[Any] = [] + if when == "after a page": + await _activate( + instance, _read_result(1, (1, 1)), flags=flags, replaying=replaying + ) + expected.append(([1], _offset(1))) + seq = 2 + _ReadScript.steps = [([0], [])] + cancel = WorkflowActivationJob(signal_workflow=SignalWorkflow(signal_name="step")) + if when != "with result": + completion = await _activate(instance, cancel, flags=flags, replaying=replaying) + assert not completion.successful.commands + completion = await _activate( + instance, + *([cancel] if when == "with result" else []), + _read_result(seq, (2, 2 if when == "with result" else "not an integer")), + flags=flags, + replaying=replaying, + ) + assert not completion.successful.commands + assert call.outcome == [*expected, "cancelled"] + assert not instance._streams._reads + assert not ( + await _activate( + instance, WorkflowActivationJob(remove_from_cache=RemoveFromCache()) + ) + ).successful.commands + + +@pytest.mark.parametrize("flags", _READ_FLAGS) +@pytest.mark.parametrize("replaying", [False, True]) +@pytest.mark.parametrize("cancelled", [False, True]) +async def test_invalid_read_bodies_follow_recorded_activation_order( + flags: Sequence[int], replaying: bool, cancelled: bool +) -> None: + call = _ReadCall("s", 0, None, None, None, 1, int) + instance, _ = await _start_readers([call], flags, replaying) + jobs = [] + if cancelled: + _ReadScript.steps = [([0], [])] + jobs.append( + WorkflowActivationJob(signal_workflow=SignalWorkflow(signal_name="step")) + ) + jobs.append(_read_result(1, (1, "not an integer"))) + completion = await _activate(instance, *jobs, flags=flags, replaying=replaying) + # Single-batch Histories convert the body before the Signal can cancel its reader. + failed = not cancelled or bool(flags) + assert completion.HasField("failed") == failed + assert call.outcome == ([] if failed else ["cancelled"]) + assert not instance._streams._reads + assert not ( + await _activate( + instance, WorkflowActivationJob(remove_from_cache=RemoveFromCache()) + ) + ).successful.commands + + +@workflow.defn +class _ReadToTwoWorkflow: + @workflow.run + async def run(self, how: str, seconds: float | None = 5) -> list[Any]: + stream = workflow.get_stream(ModelRef[int](id="s", store="a")) + wait = None if seconds is None else timedelta(seconds=seconds) + if how == "read_page": + page = await stream.read_page(wait=wait) + return list(page.records) + # A Stream has no end, so the reader stops at the writer's last Record, 2. + found: list[Any] = [] + if how == "read": + async for record in stream.read(wait=wait): + found.append(record.body) + if record.body == 2: + break + return found + async for page in stream.read_pages(wait=wait): + found.append([record.body for record in page.records]) + if 2 in found[-1]: + break + return found + + +async def test_a_read_goes_on_after_a_page_with_no_record() -> None: + converter = temporalio.converter.DefaultPayloadConverter() + + def read(seq: int, after: int, seconds: int | None = 5) -> WorkflowCommand: + command = ReadStream( + seq=seq, + stream=StreamRef(id="s", store="a"), + after_offset=_offset(after), + wait=None if seconds is None else Duration(seconds=seconds), + ) + return WorkflowCommand(read_stream=command) + + def page( + seq: int, records: Sequence[int], wait_cut: bool = False + ) -> WorkflowActivationJob: + stream_page = StreamPage( + records=[ + StreamRecord(offset=_offset(number), body=converter.to_payload(number)) + for number in records + ], + wait_cut=wait_cut, + ) + job = ResolveStreamRead(seq=seq, page=stream_page) + return WorkflowActivationJob(resolve_stream_read=job) + + def start(how: str, seconds: int | None = 5) -> WorkflowActivationJob: + arguments = [converter.to_payload(how), converter.to_payload(seconds)] + return WorkflowActivationJob( + initialize_workflow=InitializeWorkflow(arguments=arguments) + ) + + def result(completion: WorkflowActivationCompletion) -> Any: + [complete] = completion.successful.commands + return converter.from_payload(complete.complete_workflow_execution.result) + + config = temporalio.streams.StreamConfig([MemoryStreamStore(name="a")]) + # A single read gives a page with no Record as it is, also a cut one. + for wait_cut in (True, False): + with failure_note(f"wait_cut {wait_cut}"): + instance = _new_instance(_ReadToTwoWorkflow, config) + completion = await _activate(instance, start("read_page")) + assert list(completion.successful.commands) == [read(1, 0)] + completion = await _activate(instance, page(1, [], wait_cut=wait_cut)) + assert result(completion) == [] + + for how in ("read", "read_pages"): + with failure_note(how): + instance = _new_instance(_ReadToTwoWorkflow, config) + completion = await _activate(instance, start(how)) + assert list(completion.successful.commands) == [read(1, 0)] + completion = await _activate(instance, page(1, [1])) + assert list(completion.successful.commands) == [read(2, 1)] + # A page with no Record doesn't end the reader, whether the read limit of + # the task cut its wait or the whole wait passed. + completion = await _activate(instance, page(2, [], wait_cut=True)) + assert list(completion.successful.commands) == [read(3, 1)] + completion = await _activate(instance, page(3, [])) + assert list(completion.successful.commands) == [read(4, 1)] + completion = await _activate(instance, page(4, [2])) + expected = [1, 2] if how == "read" else [[1], [], [], [2]] + assert result(completion) == expected + + instance = _new_instance(_ReadToTwoWorkflow, config) + await _activate(instance, start("read_pages"), replaying=True) + completion = await _activate(instance, page(1, [1]), replaying=True) + assert list(completion.successful.commands) == [read(2, 1)] + completion = await _activate(instance, page(2, []), replaying=True) + assert list(completion.successful.commands) == [read(3, 1)] + + # The first read of an iterator has the caller's wait. A later read has it too, + # or the default of 1 minute when the caller gave none. A wait of zero stays. + default = int(_support.DEFAULT_READ_WAIT.total_seconds()) + cases: list[tuple[int | None, int | None]] = [(None, default), (0, 0), (5, 5)] + for how in ("read", "read_pages"): + for given, later in cases: + with failure_note(f"{how} with wait {given}"): + instance = _new_instance(_ReadToTwoWorkflow, config) + completion = await _activate(instance, start(how, given)) + assert list(completion.successful.commands) == [read(1, 0, given)] + completion = await _activate(instance, page(1, [1])) + assert list(completion.successful.commands) == [read(2, 1, later)] + completion = await _activate(instance, page(2, [])) + assert list(completion.successful.commands) == [read(3, 1, later)] + # A single read has no default wait. + instance = _new_instance(_ReadToTwoWorkflow, config) + completion = await _activate(instance, start("read_page", None)) + assert list(completion.successful.commands) == [read(1, 0, None)]