diff --git a/changelog/added/nonstretchable-jamie.md b/changelog/added/nonstretchable-jamie.md new file mode 100644 index 0000000000..036a7c38e7 --- /dev/null +++ b/changelog/added/nonstretchable-jamie.md @@ -0,0 +1 @@ +Core: Stream metrics record Store calls by `stream_store` and failures by `failure_reason`. Live append and read counters exclude replay. Replay Store reads have separate `stream_replay_read_total`, `stream_replay_read_execution_failed`, `stream_replay_read_records` and `stream_replay_read_execution_latency` instruments. diff --git a/changelog/added/steady-stream-heron.md b/changelog/added/steady-stream-heron.md new file mode 100644 index 0000000000..3cd4bb8330 --- /dev/null +++ b/changelog/added/steady-stream-heron.md @@ -0,0 +1,3 @@ +Add experimental Streams for client, Activity and Workflow code, with configurable Stores and append limits. `MemoryStreamStore` supports tests and local runs. +Add Workflow Stream reads and replay through `Replayer(stream_config=...)`. Replay reads Records from the Store again, so retention must cover later replays and queries. +Add `BufferedAppender` for client and Activity batching, plus `current_producer` and `as_producer` for Activity attempts. diff --git a/changelog/changed/unhurried-replay-tortoise.md b/changelog/changed/unhurried-replay-tortoise.md new file mode 100644 index 0000000000..ae9c794997 --- /dev/null +++ b/changelog/changed/unhurried-replay-tortoise.md @@ -0,0 +1 @@ +A Workflow that starts on this version replays each Workflow Task separately, which keeps the grouping and the timestamps of the activations of its first run. A Workflow that started on an earlier version replays as before. diff --git a/changelog/fixed/blockier-mathias.md b/changelog/fixed/blockier-mathias.md new file mode 100644 index 0000000000..8863932c02 --- /dev/null +++ b/changelog/fixed/blockier-mathias.md @@ -0,0 +1,2 @@ +Core: A Workflow Stream read returns an unsupported-read error for a single Record over 16 MiB. New read markers preserve the Producer's optional timestamps and signed values during replay. Workers can still replay the original marker format, including previously delivered oversized Records. Older Workers cannot interpret the new digest format. +Core: Workflow replay now skips timed-out tasks consistently when a History page ends at the task start. diff --git a/changelog/fixed/nonstretchable-jamie.md b/changelog/fixed/nonstretchable-jamie.md new file mode 100644 index 0000000000..7b531db416 --- /dev/null +++ b/changelog/fixed/nonstretchable-jamie.md @@ -0,0 +1 @@ +Core: Workflow queries retain task results when replay needs another History page. diff --git a/changelog/fixed/patient-poll.md b/changelog/fixed/patient-poll.md new file mode 100644 index 0000000000..1de5adcc2f --- /dev/null +++ b/changelog/fixed/patient-poll.md @@ -0,0 +1,2 @@ +Client and Activity Stream polling yields to asyncio between empty pages, including when the caller sets a zero wait. +Stream iterators resume from the last Record when a page omits its cursor. diff --git a/changelog/fixed/punctual-puffin.md b/changelog/fixed/punctual-puffin.md new file mode 100644 index 0000000000..bd18de3a1f --- /dev/null +++ b/changelog/fixed/punctual-puffin.md @@ -0,0 +1 @@ +`ActivityEnvironment` defaults to the Unix epoch for Activity timestamps in every time zone. diff --git a/changelog/fixed/sleepy-signal-finch.md b/changelog/fixed/sleepy-signal-finch.md new file mode 100644 index 0000000000..a0d3f0d669 --- /dev/null +++ b/changelog/fixed/sleepy-signal-finch.md @@ -0,0 +1,2 @@ +Prevent unawaited Workflow and Signal coroutines when an activation fails before their tasks start. +Close replay iterators when replay returns early so cleanup finishes before the event loop stops. diff --git a/scripts/gen_payload_visitor.py b/scripts/gen_payload_visitor.py index ba5ddc112b..7cf8816e48 100644 --- a/scripts/gen_payload_visitor.py +++ b/scripts/gen_payload_visitor.py @@ -23,21 +23,38 @@ from temporalio.converter._payload_converter import _get_transfer_type_converter -def discover_system_nexus_roots() -> list[Descriptor]: - module_path = base_dir / "temporalio" / "nexus" / "system" / "workflow_service" - spec = spec_from_file_location( - "temporalio_nexus_system_workflow_service", - module_path / "__init__.py", - submodule_search_locations=[str(module_path)], - ) - if spec is None or spec.loader is None: - raise RuntimeError(f"Cannot load generated system service from {module_path}") - module = module_from_spec(spec) - sys.modules[spec.name] = module - spec.loader.exec_module(module) +def discover_system_nexus_services() -> list[type]: + services: list[type] = [] + system_dir = base_dir / "temporalio" / "nexus" / "system" + for module_path in sorted(path.parent for path in system_dir.glob("*/services.py")): + spec = spec_from_file_location( + f"temporalio_nexus_system_{module_path.name}", + module_path / "__init__.py", + submodule_search_locations=[str(module_path)], + ) + if spec is None or spec.loader is None: + raise RuntimeError( + f"Cannot load generated system service from {module_path}" + ) + module = module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + services.extend( + value + for value in vars(module.services).values() + if isinstance(value, type) and nexusrpc.get_service_definition(value) + ) + return services + +def discover_system_nexus_roots() -> list[Descriptor]: roots: list[Descriptor] = [] - for annotation in get_type_hints(module._services.WorkflowService).values(): + annotations = [ + annotation + for service in discover_system_nexus_services() + for annotation in get_type_hints(service).values() + ] + for annotation in annotations: if get_origin(annotation) is not nexusrpc.Operation: continue for operation_type in get_args(annotation): diff --git a/temporalio/bridge/Cargo.lock b/temporalio/bridge/Cargo.lock index d0304f3887..0b34830004 100644 --- a/temporalio/bridge/Cargo.lock +++ b/temporalio/bridge/Cargo.lock @@ -181,6 +181,15 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "bon" version = "3.10.3" @@ -309,6 +318,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "constant_time_eq" version = "0.6.2" @@ -376,6 +391,15 @@ version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "darling" version = "0.24.1" @@ -433,6 +457,17 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + [[package]] name = "dirs" version = "7.0.0" @@ -871,6 +906,15 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.13.0" @@ -2422,6 +2466,17 @@ dependencies = [ "serde", ] +[[package]] +name = "sha2" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "sharded-slab" version = "0.1.7" @@ -2626,6 +2681,7 @@ dependencies = [ "temporalio-client", "temporalio-common", "temporalio-sdk-core", + "temporalio-streams", "tokio", "tokio-rustls", "tokio-stream", @@ -2791,6 +2847,7 @@ dependencies = [ "reqwest", "serde", "serde_json", + "sha2", "siphasher", "slotmap", "sysinfo", @@ -2798,6 +2855,7 @@ dependencies = [ "temporalio-client", "temporalio-common", "temporalio-macros", + "temporalio-streams", "thiserror", "tokio", "tokio-stream", @@ -2809,6 +2867,17 @@ dependencies = [ "zip", ] +[[package]] +name = "temporalio-streams" +version = "0.1.0" +dependencies = [ + "enum-iterator", + "futures-util", + "prost", + "temporalio-common", + "thiserror", +] + [[package]] name = "termtree" version = "0.5.1" @@ -2918,6 +2987,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "futures-util", "libc", "pin-project-lite", "tokio", @@ -3186,6 +3256,12 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "typetag" version = "0.2.23" diff --git a/temporalio/bridge/Cargo.toml b/temporalio/bridge/Cargo.toml index 3d63f69cdf..1d6bad33c7 100644 --- a/temporalio/bridge/Cargo.toml +++ b/temporalio/bridge/Cargo.toml @@ -72,7 +72,10 @@ temporalio-sdk-core = { version = "0.12.0", path = "./sdk-core/crates/sdk-core", "ephemeral-server", "envconfig", "prometheus", + # Replay must retain the result groups of Stream create and describe Local Activities. + "disable_workflow_task_chunking", ] } +temporalio-streams = { version = "0.1.0", path = "./sdk-core/crates/streams" } tokio = "1.26" # Matches the sdk-core client crate's rustls stack; used to build the custom # server certificate verifier for TLSConfig.verification_server_name. diff --git a/temporalio/bridge/_visitor.py b/temporalio/bridge/_visitor.py index ead09a986f..ab059e9642 100644 --- a/temporalio/bridge/_visitor.py +++ b/temporalio/bridge/_visitor.py @@ -308,6 +308,32 @@ async def _visit_coresdk_workflow_activation_ResolveNexusOperation( if o.HasField("result"): await self._visit_coresdk_nexus_NexusOperationResult(fs, o.result) + async def _visit_coresdk_workflow_activation_ResolveStreamAppend( + self, fs: VisitorFunctions, o: Any + ): + if o.HasField("failed"): + await self._visit_temporal_api_failure_v1_Failure(fs, o.failed) + + async def _visit_temporal_api_stream_v1_StreamRecord( + self, fs: VisitorFunctions, o: Any + ): + if o.HasField("body"): + await self._visit_temporal_api_common_v1_Payload(fs, o.body) + + async def _visit_coresdk_workflow_activation_StreamPage( + self, fs: VisitorFunctions, o: Any + ): + for v in o.records: + await self._visit_temporal_api_stream_v1_StreamRecord(fs, v) + + async def _visit_coresdk_workflow_activation_ResolveStreamRead( + self, fs: VisitorFunctions, o: Any + ): + if o.HasField("page"): + await self._visit_coresdk_workflow_activation_StreamPage(fs, o.page) + elif o.HasField("failed"): + await self._visit_temporal_api_failure_v1_Failure(fs, o.failed) + async def _visit_coresdk_workflow_activation_WorkflowActivationJob( self, fs: VisitorFunctions, o: Any ): @@ -353,6 +379,14 @@ async def _visit_coresdk_workflow_activation_WorkflowActivationJob( await self._visit_coresdk_workflow_activation_ResolveNexusOperation( fs, o.resolve_nexus_operation ) + elif o.HasField("resolve_stream_append"): + await self._visit_coresdk_workflow_activation_ResolveStreamAppend( + fs, o.resolve_stream_append + ) + elif o.HasField("resolve_stream_read"): + await self._visit_coresdk_workflow_activation_ResolveStreamRead( + fs, o.resolve_stream_read + ) async def _visit_coresdk_workflow_activation_WorkflowActivation( self, fs: VisitorFunctions, o: Any @@ -492,6 +526,11 @@ async def _visit_coresdk_workflow_commands_ScheduleNexusOperation( if o.HasField("input"): await self._visit_nexus_operation_input_payload(fs, o.input) + async def _visit_coresdk_workflow_commands_AppendToStream( + self, fs: VisitorFunctions, o: Any + ): + await self._visit_payload_container(fs, o.bodies) + async def _visit_coresdk_workflow_commands_WorkflowCommand( self, fs: VisitorFunctions, o: Any ): @@ -551,6 +590,10 @@ async def _visit_coresdk_workflow_commands_WorkflowCommand( await self._visit_coresdk_workflow_commands_ScheduleNexusOperation( fs, o.schedule_nexus_operation ) + elif o.HasField("append_to_stream"): + await self._visit_coresdk_workflow_commands_AppendToStream( + fs, o.append_to_stream + ) async def _visit_coresdk_workflow_completion_Success( self, fs: VisitorFunctions, o: Any @@ -639,6 +682,54 @@ async def _visit_temporal_api_notificationservice_v1_OnCompleteResponse( ) -> None: pass + async def _visit_temporal_api_sdk_v1_CreateStreamRequest( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_sdk_v1_CreateStreamResponse( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_stream_v1_AppendRecord( + self, fs: VisitorFunctions, o: Any + ): + if o.HasField("body"): + await self._visit_temporal_api_common_v1_Payload(fs, o.body) + + async def _visit_temporal_api_sdk_v1_AppendRecordsRequest( + self, fs: VisitorFunctions, o: Any + ): + for v in o.records: + await self._visit_temporal_api_stream_v1_AppendRecord(fs, v) + + async def _visit_temporal_api_streamservice_v1_AppendRecordsResponse( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_sdk_v1_ReadRecordsRequest( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_streamservice_v1_ReadRecordsResponse( + self, fs: VisitorFunctions, o: Any + ): + for v in o.records: + await self._visit_temporal_api_stream_v1_StreamRecord(fs, v) + + async def _visit_temporal_api_sdk_v1_DescribeStreamRequest( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + + async def _visit_temporal_api_streamservice_v1_DescribeStreamResponse( + self, fs: VisitorFunctions, o: Any + ) -> None: + pass + async def _visit_temporal_api_common_v1_Header(self, fs: VisitorFunctions, o: Any): for v in o.fields.values(): await self._visit_temporal_api_common_v1_Payload(fs, v) diff --git a/temporalio/bridge/proto/activity_task/activity_task_pb2.py b/temporalio/bridge/proto/activity_task/activity_task_pb2.py index 25233f5241..fd2ce8c211 100644 --- a/temporalio/bridge/proto/activity_task/activity_task_pb2.py +++ b/temporalio/bridge/proto/activity_task/activity_task_pb2.py @@ -27,7 +27,7 @@ ) DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n3temporal/sdk/core/activity_task/activity_task.proto\x12\x15\x63oresdk.activity_task\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a$temporal/api/common/v1/message.proto\x1a#temporal/api/nexus/v1/message.proto\x1a%temporal/sdk/core/common/common.proto"\x8d\x01\n\x0c\x41\x63tivityTask\x12\x12\n\ntask_token\x18\x01 \x01(\x0c\x12-\n\x05start\x18\x03 \x01(\x0b\x32\x1c.coresdk.activity_task.StartH\x00\x12/\n\x06\x63\x61ncel\x18\x04 \x01(\x0b\x32\x1d.coresdk.activity_task.CancelH\x00\x42\t\n\x07variant"\xdb\x08\n\x05Start\x12\x1a\n\x12workflow_namespace\x18\x01 \x01(\t\x12\x15\n\rworkflow_type\x18\x02 \x01(\t\x12\x45\n\x12workflow_execution\x18\x03 \x01(\x0b\x32).temporal.api.common.v1.WorkflowExecution\x12\x13\n\x0b\x61\x63tivity_id\x18\x04 \x01(\t\x12\x15\n\ractivity_type\x18\x05 \x01(\t\x12\x45\n\rheader_fields\x18\x06 \x03(\x0b\x32..coresdk.activity_task.Start.HeaderFieldsEntry\x12.\n\x05input\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12:\n\x11heartbeat_details\x18\x08 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x32\n\x0escheduled_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x42\n\x1e\x63urrent_attempt_scheduled_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x30\n\x0cstarted_time\x18\x0b \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07\x61ttempt\x18\x0c \x01(\r\x12<\n\x19schedule_to_close_timeout\x18\r \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\x0e \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x34\n\x11heartbeat_timeout\x18\x0f \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x10 \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x32\n\x08priority\x18\x12 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12\x10\n\x08is_local\x18\x11 \x01(\x08\x12\x0e\n\x06run_id\x18\x13 \x01(\t\x12\x65\n&propagated_nexus_serialization_context\x18\x14 \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x12\x41\n\rworkflow_task\x18\x15 \x01(\x0b\x32*.coresdk.activity_task.WorkflowTaskAttempt\x1aT\n\x11HeaderFieldsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x80\x02\n\x13WorkflowTaskAttempt\x12\x18\n\x10started_event_id\x18\x01 \x01(\x03\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\r\x12\x30\n\x0cstarted_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12!\n\x19previous_started_event_id\x18\x04 \x01(\x03\x12\x14\n\x0c\x66\x61iled_tasks\x18\x05 \x03(\x03\x12\x18\n\x10previous_attempt\x18\x06 \x01(\r\x12\x39\n\x15previous_started_time\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"\x8a\x01\n\x06\x43\x61ncel\x12;\n\x06reason\x18\x01 \x01(\x0e\x32+.coresdk.activity_task.ActivityCancelReason\x12\x43\n\x07\x64\x65tails\x18\x02 \x01(\x0b\x32\x32.coresdk.activity_task.ActivityCancellationDetails"\xa0\x01\n\x1b\x41\x63tivityCancellationDetails\x12\x14\n\x0cis_not_found\x18\x01 \x01(\x08\x12\x14\n\x0cis_cancelled\x18\x02 \x01(\x08\x12\x11\n\tis_paused\x18\x03 \x01(\x08\x12\x14\n\x0cis_timed_out\x18\x04 \x01(\x08\x12\x1a\n\x12is_worker_shutdown\x18\x05 \x01(\x08\x12\x10\n\x08is_reset\x18\x06 \x01(\x08*o\n\x14\x41\x63tivityCancelReason\x12\r\n\tNOT_FOUND\x10\x00\x12\r\n\tCANCELLED\x10\x01\x12\r\n\tTIMED_OUT\x10\x02\x12\x13\n\x0fWORKER_SHUTDOWN\x10\x03\x12\n\n\x06PAUSED\x10\x04\x12\t\n\x05RESET\x10\x05\x42\x32\xea\x02/Temporalio::Internal::Bridge::Api::ActivityTaskb\x06proto3' + b'\n3temporal/sdk/core/activity_task/activity_task.proto\x12\x15\x63oresdk.activity_task\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a$temporal/api/common/v1/message.proto\x1a#temporal/api/nexus/v1/message.proto\x1a%temporal/sdk/core/common/common.proto"\x8d\x01\n\x0c\x41\x63tivityTask\x12\x12\n\ntask_token\x18\x01 \x01(\x0c\x12-\n\x05start\x18\x03 \x01(\x0b\x32\x1c.coresdk.activity_task.StartH\x00\x12/\n\x06\x63\x61ncel\x18\x04 \x01(\x0b\x32\x1d.coresdk.activity_task.CancelH\x00\x42\t\n\x07variant"\xf7\x08\n\x05Start\x12\x1a\n\x12workflow_namespace\x18\x01 \x01(\t\x12\x15\n\rworkflow_type\x18\x02 \x01(\t\x12\x45\n\x12workflow_execution\x18\x03 \x01(\x0b\x32).temporal.api.common.v1.WorkflowExecution\x12\x13\n\x0b\x61\x63tivity_id\x18\x04 \x01(\t\x12\x15\n\ractivity_type\x18\x05 \x01(\t\x12\x45\n\rheader_fields\x18\x06 \x03(\x0b\x32..coresdk.activity_task.Start.HeaderFieldsEntry\x12.\n\x05input\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12:\n\x11heartbeat_details\x18\x08 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x32\n\x0escheduled_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x42\n\x1e\x63urrent_attempt_scheduled_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x30\n\x0cstarted_time\x18\x0b \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07\x61ttempt\x18\x0c \x01(\r\x12<\n\x19schedule_to_close_timeout\x18\r \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\x0e \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x34\n\x11heartbeat_timeout\x18\x0f \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x10 \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x32\n\x08priority\x18\x12 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12\x10\n\x08is_local\x18\x11 \x01(\x08\x12\x0e\n\x06run_id\x18\x13 \x01(\t\x12\x65\n&propagated_nexus_serialization_context\x18\x14 \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x12\x41\n\rworkflow_task\x18\x15 \x01(\x0b\x32*.coresdk.activity_task.WorkflowTaskAttempt\x12\x1a\n\x12scheduled_event_id\x18\x16 \x01(\x03\x1aT\n\x11HeaderFieldsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x80\x02\n\x13WorkflowTaskAttempt\x12\x18\n\x10started_event_id\x18\x01 \x01(\x03\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\r\x12\x30\n\x0cstarted_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12!\n\x19previous_started_event_id\x18\x04 \x01(\x03\x12\x14\n\x0c\x66\x61iled_tasks\x18\x05 \x03(\x03\x12\x18\n\x10previous_attempt\x18\x06 \x01(\r\x12\x39\n\x15previous_started_time\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"\x8a\x01\n\x06\x43\x61ncel\x12;\n\x06reason\x18\x01 \x01(\x0e\x32+.coresdk.activity_task.ActivityCancelReason\x12\x43\n\x07\x64\x65tails\x18\x02 \x01(\x0b\x32\x32.coresdk.activity_task.ActivityCancellationDetails"\xa0\x01\n\x1b\x41\x63tivityCancellationDetails\x12\x14\n\x0cis_not_found\x18\x01 \x01(\x08\x12\x14\n\x0cis_cancelled\x18\x02 \x01(\x08\x12\x11\n\tis_paused\x18\x03 \x01(\x08\x12\x14\n\x0cis_timed_out\x18\x04 \x01(\x08\x12\x1a\n\x12is_worker_shutdown\x18\x05 \x01(\x08\x12\x10\n\x08is_reset\x18\x06 \x01(\x08*o\n\x14\x41\x63tivityCancelReason\x12\r\n\tNOT_FOUND\x10\x00\x12\r\n\tCANCELLED\x10\x01\x12\r\n\tTIMED_OUT\x10\x02\x12\x13\n\x0fWORKER_SHUTDOWN\x10\x03\x12\n\n\x06PAUSED\x10\x04\x12\t\n\x05RESET\x10\x05\x42\x32\xea\x02/Temporalio::Internal::Bridge::Api::ActivityTaskb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -39,18 +39,18 @@ ) _START_HEADERFIELDSENTRY._options = None _START_HEADERFIELDSENTRY._serialized_options = b"8\001" - _ACTIVITYCANCELREASON._serialized_start = 2082 - _ACTIVITYCANCELREASON._serialized_end = 2193 + _ACTIVITYCANCELREASON._serialized_start = 2110 + _ACTIVITYCANCELREASON._serialized_end = 2221 _ACTIVITYTASK._serialized_start = 258 _ACTIVITYTASK._serialized_end = 399 _START._serialized_start = 402 - _START._serialized_end = 1517 - _START_HEADERFIELDSENTRY._serialized_start = 1433 - _START_HEADERFIELDSENTRY._serialized_end = 1517 - _WORKFLOWTASKATTEMPT._serialized_start = 1520 - _WORKFLOWTASKATTEMPT._serialized_end = 1776 - _CANCEL._serialized_start = 1779 - _CANCEL._serialized_end = 1917 - _ACTIVITYCANCELLATIONDETAILS._serialized_start = 1920 - _ACTIVITYCANCELLATIONDETAILS._serialized_end = 2080 + _START._serialized_end = 1545 + _START_HEADERFIELDSENTRY._serialized_start = 1461 + _START_HEADERFIELDSENTRY._serialized_end = 1545 + _WORKFLOWTASKATTEMPT._serialized_start = 1548 + _WORKFLOWTASKATTEMPT._serialized_end = 1804 + _CANCEL._serialized_start = 1807 + _CANCEL._serialized_end = 1945 + _ACTIVITYCANCELLATIONDETAILS._serialized_start = 1948 + _ACTIVITYCANCELLATIONDETAILS._serialized_end = 2108 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/activity_task/activity_task_pb2.pyi b/temporalio/bridge/proto/activity_task/activity_task_pb2.pyi index 345b0a6b1e..63b1711bf8 100644 --- a/temporalio/bridge/proto/activity_task/activity_task_pb2.pyi +++ b/temporalio/bridge/proto/activity_task/activity_task_pb2.pyi @@ -167,6 +167,7 @@ class Start(google.protobuf.message.Message): RUN_ID_FIELD_NUMBER: builtins.int PROPAGATED_NEXUS_SERIALIZATION_CONTEXT_FIELD_NUMBER: builtins.int WORKFLOW_TASK_FIELD_NUMBER: builtins.int + SCHEDULED_EVENT_ID_FIELD_NUMBER: builtins.int workflow_namespace: builtins.str """The namespace the workflow lives in""" workflow_type: builtins.str @@ -182,6 +183,10 @@ class Start(google.protobuf.message.Message): """ run_id: builtins.str """Run ID of this activity execution. Only set for standalone activities.""" + scheduled_event_id: builtins.int + """For an activity that a workflow scheduled, the event id of its ActivityTaskScheduled event. + 0 for a local activity, for a standalone activity, and when Core can't read it. + """ @property def workflow_execution( self, @@ -294,6 +299,7 @@ class Start(google.protobuf.message.Message): propagated_nexus_serialization_context: temporalio.api.nexus.v1.message_pb2.PropagatedSerializationContext | None = ..., workflow_task: global___WorkflowTaskAttempt | None = ..., + scheduled_event_id: builtins.int = ..., ) -> None: ... def HasField( self, @@ -353,6 +359,8 @@ class Start(google.protobuf.message.Message): b"run_id", "schedule_to_close_timeout", b"schedule_to_close_timeout", + "scheduled_event_id", + b"scheduled_event_id", "scheduled_time", b"scheduled_time", "start_to_close_timeout", diff --git a/temporalio/bridge/proto/external_data/__init__.py b/temporalio/bridge/proto/external_data/__init__.py index 836e97ef43..ef6671d8e6 100644 --- a/temporalio/bridge/proto/external_data/__init__.py +++ b/temporalio/bridge/proto/external_data/__init__.py @@ -1,6 +1,23 @@ -from .external_data_pb2 import LocalActivityMarkerData, PatchedMarkerData +from .external_data_pb2 import ( + LocalActivityMarkerData, + PatchedMarkerData, + StreamAppendMarkerData, + StreamAppendOffsets, + StreamAppendResult, + StreamFailure, + StreamReadMarkerData, + StreamReadPage, + StreamReadResult, +) __all__ = [ "LocalActivityMarkerData", "PatchedMarkerData", + "StreamAppendMarkerData", + "StreamAppendOffsets", + "StreamAppendResult", + "StreamFailure", + "StreamReadMarkerData", + "StreamReadPage", + "StreamReadResult", ] diff --git a/temporalio/bridge/proto/external_data/external_data_pb2.py b/temporalio/bridge/proto/external_data/external_data_pb2.py index 4bda6f5144..02f99d0120 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.py +++ b/temporalio/bridge/proto/external_data/external_data_pb2.py @@ -17,7 +17,7 @@ from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n3temporal/sdk/core/external_data/external_data.proto\x12\x15\x63oresdk.external_data\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xb2\x02\n\x17LocalActivityMarkerData\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x03 \x01(\t\x12\x15\n\ractivity_type\x18\x04 \x01(\t\x12\x31\n\rcomplete_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12*\n\x07\x62\x61\x63koff\x18\x06 \x01(\x0b\x32\x19.google.protobuf.Duration\x12:\n\x16original_schedule_time\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x1d\n\x10\x61\x63tivation_index\x18\x08 \x01(\x04H\x00\x88\x01\x01\x42\x13\n\x11_activation_index"3\n\x11PatchedMarkerData\x12\n\n\x02id\x18\x01 \x01(\t\x12\x12\n\ndeprecated\x18\x02 \x01(\x08\x42\x32\xea\x02/Temporalio::Internal::Bridge::Api::ExternalDatab\x06proto3' + b'\n3temporal/sdk/core/external_data/external_data.proto\x12\x15\x63oresdk.external_data\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xb2\x02\n\x17LocalActivityMarkerData\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x0f\n\x07\x61ttempt\x18\x02 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x03 \x01(\t\x12\x15\n\ractivity_type\x18\x04 \x01(\t\x12\x31\n\rcomplete_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12*\n\x07\x62\x61\x63koff\x18\x06 \x01(\x0b\x32\x19.google.protobuf.Duration\x12:\n\x16original_schedule_time\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x1d\n\x10\x61\x63tivation_index\x18\x08 \x01(\x04H\x00\x88\x01\x01\x42\x13\n\x11_activation_index"3\n\x11PatchedMarkerData\x12\n\n\x02id\x18\x01 \x01(\t\x12\x12\n\ndeprecated\x18\x02 \x01(\x08"T\n\x16StreamAppendMarkerData\x12:\n\x07\x61ppends\x18\x01 \x03(\x0b\x32).coresdk.external_data.StreamAppendResult"\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"\xea\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\x13\n\x0b\x66rom_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"s\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\x13\n\x0blast_offset\x18\x04 \x01(\x0c\x12\x10\n\x08wait_cut\x18\x05 \x01(\x08\x42\x32\xea\x02/Temporalio::Internal::Bridge::Api::ExternalDatab\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -31,4 +31,18 @@ _LOCALACTIVITYMARKERDATA._serialized_end = 450 _PATCHEDMARKERDATA._serialized_start = 452 _PATCHEDMARKERDATA._serialized_end = 503 + _STREAMAPPENDMARKERDATA._serialized_start = 505 + _STREAMAPPENDMARKERDATA._serialized_end = 589 + _STREAMAPPENDRESULT._serialized_start = 592 + _STREAMAPPENDRESULT._serialized_end = 816 + _STREAMAPPENDOFFSETS._serialized_start = 818 + _STREAMAPPENDOFFSETS._serialized_end = 882 + _STREAMFAILURE._serialized_start = 884 + _STREAMFAILURE._serialized_end = 932 + _STREAMREADMARKERDATA._serialized_start = 934 + _STREAMREADMARKERDATA._serialized_end = 1012 + _STREAMREADRESULT._serialized_start = 1015 + _STREAMREADRESULT._serialized_end = 1249 + _STREAMREADPAGE._serialized_start = 1251 + _STREAMREADPAGE._serialized_end = 1366 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/external_data/external_data_pb2.pyi b/temporalio/bridge/proto/external_data/external_data_pb2.pyi index edcd4581a1..d153ec2389 100644 --- a/temporalio/bridge/proto/external_data/external_data_pb2.pyi +++ b/temporalio/bridge/proto/external_data/external_data_pb2.pyi @@ -4,10 +4,12 @@ isort:skip_file """ import builtins +import collections.abc import typing import google.protobuf.descriptor import google.protobuf.duration_pb2 +import google.protobuf.internal.containers import google.protobuf.message import google.protobuf.timestamp_pb2 @@ -139,3 +141,289 @@ class PatchedMarkerData(google.protobuf.message.Message): ) -> None: ... global___PatchedMarkerData = PatchedMarkerData + +@typing.final +class StreamAppendMarkerData(google.protobuf.message.Message): + """The data of a `core_stream_append` marker, as JSON with `bytes` fields in lower-case hex. An + empty marker keeps a task with an open append apart from the next task when chunking is on. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + APPENDS_FIELD_NUMBER: builtins.int + @property + def appends( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___StreamAppendResult + ]: ... + def __init__( + self, + *, + appends: collections.abc.Iterable[global___StreamAppendResult] | None = ..., + ) -> None: ... + def ClearField(self, field_name: typing.Literal["appends", b"appends"]) -> None: ... + +global___StreamAppendMarkerData = StreamAppendMarkerData + +@typing.final +class StreamAppendResult(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + STREAM_ID_FIELD_NUMBER: builtins.int + STORE_FIELD_NUMBER: builtins.int + ACTIVATION_INDEX_FIELD_NUMBER: builtins.int + APPENDED_FIELD_NUMBER: builtins.int + FAILURE_FIELD_NUMBER: builtins.int + seq: builtins.int + stream_id: builtins.str + store: builtins.str + """The name of the Store that the append used. For a ref with no Store name, it is the empty + name if the Worker has a Stream runtime under it, else the name of its only runtime. + """ + activation_index: builtins.int + """The index of the activation, within its Workflow Task, in which Workflow code got the result.""" + @property + def appended(self) -> global___StreamAppendOffsets: ... + @property + def failure(self) -> global___StreamFailure: ... + def __init__( + self, + *, + seq: builtins.int = ..., + stream_id: builtins.str = ..., + store: builtins.str = ..., + activation_index: builtins.int = ..., + appended: global___StreamAppendOffsets | None = ..., + failure: global___StreamFailure | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "appended", b"appended", "failure", b"failure", "result", b"result" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "activation_index", + b"activation_index", + "appended", + b"appended", + "failure", + b"failure", + "result", + b"result", + "seq", + b"seq", + "store", + b"store", + "stream_id", + b"stream_id", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["result", b"result"] + ) -> typing.Literal["appended", "failure"] | None: ... + +global___StreamAppendResult = StreamAppendResult + +@typing.final +class StreamAppendOffsets(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FIRST_OFFSET_FIELD_NUMBER: builtins.int + LAST_OFFSET_FIELD_NUMBER: builtins.int + first_offset: builtins.bytes + last_offset: builtins.bytes + def __init__( + self, + *, + first_offset: builtins.bytes = ..., + last_offset: builtins.bytes = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "first_offset", b"first_offset", "last_offset", b"last_offset" + ], + ) -> None: ... + +global___StreamAppendOffsets = StreamAppendOffsets + +@typing.final +class StreamFailure(google.protobuf.message.Message): + """Why a Stream call failed. Core builds the failure that Workflow code gets from these two.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REASON_FIELD_NUMBER: builtins.int + MESSAGE_FIELD_NUMBER: builtins.int + reason: builtins.str + """The name of the `temporalio.api.enums.v1.StreamErrorReason`, such as + `STREAM_ERROR_REASON_FENCED`. History stores the name, so a reason must never change its name. + """ + message: builtins.str + """The message of the failure, of at most 4096 bytes.""" + def __init__( + self, + *, + reason: builtins.str = ..., + message: builtins.str = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["message", b"message", "reason", b"reason"] + ) -> None: ... + +global___StreamFailure = StreamFailure + +@typing.final +class StreamReadMarkerData(google.protobuf.message.Message): + """The data of a `core_stream_read` marker. Core records one in each activation in which Workflow + code got the page of a read. An empty marker keeps a task with an open read and no open append + apart from the next task when chunking is on. The marker keeps the offsets, the count and a + digest of each page, never its Records. A replay reads the Records from the Store again. Its + JSON has `bytes` fields in lower-case hex, as for appends. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + READS_FIELD_NUMBER: builtins.int + @property + def reads( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___StreamReadResult + ]: ... + def __init__( + self, + *, + reads: collections.abc.Iterable[global___StreamReadResult] | None = ..., + ) -> None: ... + def ClearField(self, field_name: typing.Literal["reads", b"reads"]) -> None: ... + +global___StreamReadMarkerData = StreamReadMarkerData + +@typing.final +class StreamReadResult(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + STREAM_ID_FIELD_NUMBER: builtins.int + STORE_FIELD_NUMBER: builtins.int + ACTIVATION_INDEX_FIELD_NUMBER: builtins.int + FROM_OFFSET_FIELD_NUMBER: builtins.int + PAGE_FIELD_NUMBER: builtins.int + FAILURE_FIELD_NUMBER: builtins.int + seq: builtins.int + stream_id: builtins.str + store: builtins.str + """The name of the Store that the read used. For a ref with no Store name, it is the empty name + if the Worker has a Stream runtime under it, else the name of its only runtime. + """ + activation_index: builtins.int + """The index of the activation, within its Workflow Task, in which Workflow code got the result.""" + from_offset: builtins.bytes + """The `from_offset` of the read. A replay reads the Records of the page after it.""" + @property + def page(self) -> global___StreamReadPage: ... + @property + def failure(self) -> global___StreamFailure: ... + def __init__( + self, + *, + seq: builtins.int = ..., + stream_id: builtins.str = ..., + store: builtins.str = ..., + activation_index: builtins.int = ..., + from_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", + "failure", + b"failure", + "from_offset", + b"from_offset", + "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 + LAST_OFFSET_FIELD_NUMBER: builtins.int + WAIT_CUT_FIELD_NUMBER: builtins.int + record_count: builtins.int + digest: builtins.bytes + """The first 16 bytes of SHA-256 over the Records in a Core-owned encoding. New markers prefix + these bytes with version 1. Original markers contain just the legacy hash. + Empty for no Records. + """ + record_bytes: builtins.int + """The size of the Records, as the `max_bytes` of a read measures it. A replay asks the Store for + this much. + """ + last_offset: builtins.bytes + """The `last_offset` that Workflow code got. A replay gives the same value, since another read of + the Store can end at another offset. + """ + 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 = ..., + last_offset: builtins.bytes = ..., + wait_cut: builtins.bool = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "digest", + b"digest", + "last_offset", + b"last_offset", + "record_bytes", + b"record_bytes", + "record_count", + b"record_count", + "wait_cut", + b"wait_cut", + ], + ) -> None: ... + +global___StreamReadPage = StreamReadPage diff --git a/temporalio/bridge/proto/workflow_activation/__init__.py b/temporalio/bridge/proto/workflow_activation/__init__.py index 5c178e2185..decfcf1474 100644 --- a/temporalio/bridge/proto/workflow_activation/__init__.py +++ b/temporalio/bridge/proto/workflow_activation/__init__.py @@ -16,7 +16,11 @@ ResolveNexusOperationStart, ResolveRequestCancelExternalWorkflow, ResolveSignalExternalWorkflow, + ResolveStreamAppend, + ResolveStreamRead, SignalWorkflow, + StreamAppended, + StreamPage, UpdateRandomSeed, WorkflowActivation, WorkflowActivationJob, @@ -40,7 +44,11 @@ "ResolveNexusOperationStart", "ResolveRequestCancelExternalWorkflow", "ResolveSignalExternalWorkflow", + "ResolveStreamAppend", + "ResolveStreamRead", "SignalWorkflow", + "StreamAppended", + "StreamPage", "UpdateRandomSeed", "WorkflowActivation", "WorkflowActivationJob", diff --git a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py index 589119c72b..1794fc18e9 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.py @@ -32,6 +32,9 @@ from temporalio.api.nexus.v1 import ( message_pb2 as temporal_dot_api_dot_nexus_dot_v1_dot_message__pb2, ) +from temporalio.api.stream.v1 import ( + message_pb2 as temporal_dot_api_dot_stream_dot_v1_dot_message__pb2, +) from temporalio.api.update.v1 import ( message_pb2 as temporal_dot_api_dot_update_dot_v1_dot_message__pb2, ) @@ -49,7 +52,7 @@ ) DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n?temporal/sdk/core/workflow_activation/workflow_activation.proto\x12\x1b\x63oresdk.workflow_activation\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a%temporal/api/failure/v1/message.proto\x1a#temporal/api/nexus/v1/message.proto\x1a$temporal/api/update/v1/message.proto\x1a$temporal/api/common/v1/message.proto\x1a(temporal/api/enums/v1/failed_cause.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a\x37temporal/sdk/core/activity_result/activity_result.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a%temporal/sdk/core/common/common.proto\x1a#temporal/sdk/core/nexus/nexus.proto"\xa2\x04\n\x12WorkflowActivation\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x14\n\x0cis_replaying\x18\x03 \x01(\x08\x12\x16\n\x0ehistory_length\x18\x04 \x01(\r\x12@\n\x04jobs\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.WorkflowActivationJob\x12 \n\x18\x61vailable_internal_flags\x18\x06 \x03(\r\x12\x1a\n\x12history_size_bytes\x18\x07 \x01(\x04\x12!\n\x19\x63ontinue_as_new_suggested\x18\x08 \x01(\x08\x12T\n#deployment_version_for_current_task\x18\t \x01(\x0b\x32\'.coresdk.common.WorkerDeploymentVersion\x12\x18\n\x10last_sdk_version\x18\n \x01(\t\x12Z\n\x1fsuggest_continue_as_new_reasons\x18\x0b \x03(\x0e\x32\x31.temporal.api.enums.v1.SuggestContinueAsNewReason\x12\x30\n(target_worker_deployment_version_changed\x18\x0c \x01(\x08"\xe0\n\n\x15WorkflowActivationJob\x12N\n\x13initialize_workflow\x18\x01 \x01(\x0b\x32/.coresdk.workflow_activation.InitializeWorkflowH\x00\x12<\n\nfire_timer\x18\x02 \x01(\x0b\x32&.coresdk.workflow_activation.FireTimerH\x00\x12K\n\x12update_random_seed\x18\x04 \x01(\x0b\x32-.coresdk.workflow_activation.UpdateRandomSeedH\x00\x12\x44\n\x0equery_workflow\x18\x05 \x01(\x0b\x32*.coresdk.workflow_activation.QueryWorkflowH\x00\x12\x46\n\x0f\x63\x61ncel_workflow\x18\x06 \x01(\x0b\x32+.coresdk.workflow_activation.CancelWorkflowH\x00\x12\x46\n\x0fsignal_workflow\x18\x07 \x01(\x0b\x32+.coresdk.workflow_activation.SignalWorkflowH\x00\x12H\n\x10resolve_activity\x18\x08 \x01(\x0b\x32,.coresdk.workflow_activation.ResolveActivityH\x00\x12G\n\x10notify_has_patch\x18\t \x01(\x0b\x32+.coresdk.workflow_activation.NotifyHasPatchH\x00\x12q\n&resolve_child_workflow_execution_start\x18\n \x01(\x0b\x32?.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartH\x00\x12\x66\n resolve_child_workflow_execution\x18\x0b \x01(\x0b\x32:.coresdk.workflow_activation.ResolveChildWorkflowExecutionH\x00\x12\x66\n resolve_signal_external_workflow\x18\x0c \x01(\x0b\x32:.coresdk.workflow_activation.ResolveSignalExternalWorkflowH\x00\x12u\n(resolve_request_cancel_external_workflow\x18\r \x01(\x0b\x32\x41.coresdk.workflow_activation.ResolveRequestCancelExternalWorkflowH\x00\x12:\n\tdo_update\x18\x0e \x01(\x0b\x32%.coresdk.workflow_activation.DoUpdateH\x00\x12`\n\x1dresolve_nexus_operation_start\x18\x0f \x01(\x0b\x32\x37.coresdk.workflow_activation.ResolveNexusOperationStartH\x00\x12U\n\x17resolve_nexus_operation\x18\x10 \x01(\x0b\x32\x32.coresdk.workflow_activation.ResolveNexusOperationH\x00\x12I\n\x11remove_from_cache\x18\x32 \x01(\x0b\x32,.coresdk.workflow_activation.RemoveFromCacheH\x00\x42\t\n\x07variant"\xe3\x0b\n\x12InitializeWorkflow\x12\x15\n\rworkflow_type\x18\x01 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x17\n\x0frandomness_seed\x18\x04 \x01(\x04\x12M\n\x07headers\x18\x05 \x03(\x0b\x32<.coresdk.workflow_activation.InitializeWorkflow.HeadersEntry\x12\x10\n\x08identity\x18\x06 \x01(\t\x12I\n\x14parent_workflow_info\x18\x07 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecution\x12=\n\x1aworkflow_execution_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14workflow_run_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\'\n\x1f\x63ontinued_from_execution_run_id\x18\x0b \x01(\t\x12J\n\x13\x63ontinued_initiator\x18\x0c \x01(\x0e\x32-.temporal.api.enums.v1.ContinueAsNewInitiator\x12;\n\x11\x63ontinued_failure\x18\r \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12@\n\x16last_completion_result\x18\x0e \x01(\x0b\x32 .temporal.api.common.v1.Payloads\x12\x1e\n\x16\x66irst_execution_run_id\x18\x0f \x01(\t\x12\x39\n\x0cretry_policy\x18\x10 \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x0f\n\x07\x61ttempt\x18\x11 \x01(\x05\x12\x15\n\rcron_schedule\x18\x12 \x01(\t\x12\x46\n"workflow_execution_expiration_time\x18\x13 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x45\n"cron_schedule_to_schedule_interval\x18\x14 \x01(\x0b\x32\x19.google.protobuf.Duration\x12*\n\x04memo\x18\x15 \x01(\x0b\x32\x1c.temporal.api.common.v1.Memo\x12\x43\n\x11search_attributes\x18\x16 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12.\n\nstart_time\x18\x17 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12@\n\rroot_workflow\x18\x18 \x01(\x0b\x32).temporal.api.common.v1.WorkflowExecution\x12\x32\n\x08priority\x18\x19 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12!\n\x19original_execution_run_id\x18\x1a \x01(\t\x12\x65\n&propagated_nexus_serialization_context\x18\x1b \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x18\n\tFireTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r"m\n\x0fResolveActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12;\n\x06result\x18\x02 \x01(\x0b\x32+.coresdk.activity_result.ActivityResolution\x12\x10\n\x08is_local\x18\x03 \x01(\x08"\xd1\x02\n"ResolveChildWorkflowExecutionStart\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12[\n\tsucceeded\x18\x02 \x01(\x0b\x32\x46.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartSuccessH\x00\x12X\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32\x46.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartFailureH\x00\x12]\n\tcancelled\x18\x04 \x01(\x0b\x32H.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartCancelledH\x00\x42\x08\n\x06status";\n)ResolveChildWorkflowExecutionStartSuccess\x12\x0e\n\x06run_id\x18\x01 \x01(\t"\xa6\x01\n)ResolveChildWorkflowExecutionStartFailure\x12\x13\n\x0bworkflow_id\x18\x01 \x01(\t\x12\x15\n\rworkflow_type\x18\x02 \x01(\t\x12M\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32>.coresdk.child_workflow.StartChildWorkflowExecutionFailedCause"`\n+ResolveChildWorkflowExecutionStartCancelled\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"i\n\x1dResolveChildWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12;\n\x06result\x18\x02 \x01(\x0b\x32+.coresdk.child_workflow.ChildWorkflowResult"+\n\x10UpdateRandomSeed\x12\x17\n\x0frandomness_seed\x18\x01 \x01(\x04"\x84\x02\n\rQueryWorkflow\x12\x10\n\x08query_id\x18\x01 \x01(\t\x12\x12\n\nquery_type\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12H\n\x07headers\x18\x05 \x03(\x0b\x32\x37.coresdk.workflow_activation.QueryWorkflow.HeadersEntry\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01" \n\x0e\x43\x61ncelWorkflow\x12\x0e\n\x06reason\x18\x01 \x01(\t"\xa1\x02\n\x0eSignalWorkflow\x12\x13\n\x0bsignal_name\x18\x01 \x01(\t\x12.\n\x05input\x18\x02 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x10\n\x08identity\x18\x03 \x01(\t\x12I\n\x07headers\x18\x05 \x03(\x0b\x32\x38.coresdk.workflow_activation.SignalWorkflow.HeadersEntry\x12\x1c\n\x14originating_event_id\x18\x06 \x01(\x03\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01""\n\x0eNotifyHasPatch\x12\x10\n\x08patch_id\x18\x01 \x01(\t"\xb1\x01\n\x1dResolveSignalExternalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x07\x66\x61ilure\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12P\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32\x41.temporal.api.enums.v1.SignalExternalWorkflowExecutionFailedCause"\xb8\x01\n$ResolveRequestCancelExternalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x07\x66\x61ilure\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12P\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32\x41.temporal.api.enums.v1.CancelExternalWorkflowExecutionFailedCause"\xb2\x03\n\x08\x44oUpdate\x12\n\n\x02id\x18\x01 \x01(\t\x12\x1c\n\x14protocol_instance_id\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12.\n\x05input\x18\x04 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x43\n\x07headers\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.DoUpdate.HeadersEntry\x12*\n\x04meta\x18\x06 \x01(\x0b\x32\x1c.temporal.api.update.v1.Meta\x12\x15\n\rrun_validator\x18\x07 \x01(\x08\x12\x65\n&propagated_nexus_serialization_context\x18\x08 \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x9a\x01\n\x1aResolveNexusOperationStart\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x19\n\x0foperation_token\x18\x02 \x01(\tH\x00\x12\x16\n\x0cstarted_sync\x18\x03 \x01(\x08H\x00\x12\x32\n\x06\x66\x61iled\x18\x04 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status"Y\n\x15ResolveNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x33\n\x06result\x18\x02 \x01(\x0b\x32#.coresdk.nexus.NexusOperationResult"\xe0\x02\n\x0fRemoveFromCache\x12\x0f\n\x07message\x18\x01 \x01(\t\x12K\n\x06reason\x18\x02 \x01(\x0e\x32;.coresdk.workflow_activation.RemoveFromCache.EvictionReason"\xee\x01\n\x0e\x45victionReason\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nCACHE_FULL\x10\x01\x12\x0e\n\nCACHE_MISS\x10\x02\x12\x12\n\x0eNONDETERMINISM\x10\x03\x12\r\n\tLANG_FAIL\x10\x04\x12\x12\n\x0eLANG_REQUESTED\x10\x05\x12\x12\n\x0eTASK_NOT_FOUND\x10\x06\x12\x15\n\x11UNHANDLED_COMMAND\x10\x07\x12\t\n\x05\x46\x41TAL\x10\x08\x12\x1f\n\x1bPAGINATION_OR_HISTORY_FETCH\x10\t\x12\x1d\n\x19WORKFLOW_EXECUTION_ENDING\x10\nB8\xea\x02\x35Temporalio::Internal::Bridge::Api::WorkflowActivationb\x06proto3' + b'\n?temporal/sdk/core/workflow_activation/workflow_activation.proto\x12\x1b\x63oresdk.workflow_activation\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a%temporal/api/failure/v1/message.proto\x1a#temporal/api/nexus/v1/message.proto\x1a$temporal/api/update/v1/message.proto\x1a$temporal/api/common/v1/message.proto\x1a(temporal/api/enums/v1/failed_cause.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a$temporal/api/stream/v1/message.proto\x1a\x37temporal/sdk/core/activity_result/activity_result.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a%temporal/sdk/core/common/common.proto\x1a#temporal/sdk/core/nexus/nexus.proto"\xa2\x04\n\x12WorkflowActivation\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x14\n\x0cis_replaying\x18\x03 \x01(\x08\x12\x16\n\x0ehistory_length\x18\x04 \x01(\r\x12@\n\x04jobs\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.WorkflowActivationJob\x12 \n\x18\x61vailable_internal_flags\x18\x06 \x03(\r\x12\x1a\n\x12history_size_bytes\x18\x07 \x01(\x04\x12!\n\x19\x63ontinue_as_new_suggested\x18\x08 \x01(\x08\x12T\n#deployment_version_for_current_task\x18\t \x01(\x0b\x32\'.coresdk.common.WorkerDeploymentVersion\x12\x18\n\x10last_sdk_version\x18\n \x01(\t\x12Z\n\x1fsuggest_continue_as_new_reasons\x18\x0b \x03(\x0e\x32\x31.temporal.api.enums.v1.SuggestContinueAsNewReason\x12\x30\n(target_worker_deployment_version_changed\x18\x0c \x01(\x08"\x82\x0c\n\x15WorkflowActivationJob\x12N\n\x13initialize_workflow\x18\x01 \x01(\x0b\x32/.coresdk.workflow_activation.InitializeWorkflowH\x00\x12<\n\nfire_timer\x18\x02 \x01(\x0b\x32&.coresdk.workflow_activation.FireTimerH\x00\x12K\n\x12update_random_seed\x18\x04 \x01(\x0b\x32-.coresdk.workflow_activation.UpdateRandomSeedH\x00\x12\x44\n\x0equery_workflow\x18\x05 \x01(\x0b\x32*.coresdk.workflow_activation.QueryWorkflowH\x00\x12\x46\n\x0f\x63\x61ncel_workflow\x18\x06 \x01(\x0b\x32+.coresdk.workflow_activation.CancelWorkflowH\x00\x12\x46\n\x0fsignal_workflow\x18\x07 \x01(\x0b\x32+.coresdk.workflow_activation.SignalWorkflowH\x00\x12H\n\x10resolve_activity\x18\x08 \x01(\x0b\x32,.coresdk.workflow_activation.ResolveActivityH\x00\x12G\n\x10notify_has_patch\x18\t \x01(\x0b\x32+.coresdk.workflow_activation.NotifyHasPatchH\x00\x12q\n&resolve_child_workflow_execution_start\x18\n \x01(\x0b\x32?.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartH\x00\x12\x66\n resolve_child_workflow_execution\x18\x0b \x01(\x0b\x32:.coresdk.workflow_activation.ResolveChildWorkflowExecutionH\x00\x12\x66\n resolve_signal_external_workflow\x18\x0c \x01(\x0b\x32:.coresdk.workflow_activation.ResolveSignalExternalWorkflowH\x00\x12u\n(resolve_request_cancel_external_workflow\x18\r \x01(\x0b\x32\x41.coresdk.workflow_activation.ResolveRequestCancelExternalWorkflowH\x00\x12:\n\tdo_update\x18\x0e \x01(\x0b\x32%.coresdk.workflow_activation.DoUpdateH\x00\x12`\n\x1dresolve_nexus_operation_start\x18\x0f \x01(\x0b\x32\x37.coresdk.workflow_activation.ResolveNexusOperationStartH\x00\x12U\n\x17resolve_nexus_operation\x18\x10 \x01(\x0b\x32\x32.coresdk.workflow_activation.ResolveNexusOperationH\x00\x12Q\n\x15resolve_stream_append\x18\x11 \x01(\x0b\x32\x30.coresdk.workflow_activation.ResolveStreamAppendH\x00\x12M\n\x13resolve_stream_read\x18\x12 \x01(\x0b\x32..coresdk.workflow_activation.ResolveStreamReadH\x00\x12I\n\x11remove_from_cache\x18\x32 \x01(\x0b\x32,.coresdk.workflow_activation.RemoveFromCacheH\x00\x42\t\n\x07variant"\xe3\x0b\n\x12InitializeWorkflow\x12\x15\n\rworkflow_type\x18\x01 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x17\n\x0frandomness_seed\x18\x04 \x01(\x04\x12M\n\x07headers\x18\x05 \x03(\x0b\x32<.coresdk.workflow_activation.InitializeWorkflow.HeadersEntry\x12\x10\n\x08identity\x18\x06 \x01(\t\x12I\n\x14parent_workflow_info\x18\x07 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecution\x12=\n\x1aworkflow_execution_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14workflow_run_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\'\n\x1f\x63ontinued_from_execution_run_id\x18\x0b \x01(\t\x12J\n\x13\x63ontinued_initiator\x18\x0c \x01(\x0e\x32-.temporal.api.enums.v1.ContinueAsNewInitiator\x12;\n\x11\x63ontinued_failure\x18\r \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12@\n\x16last_completion_result\x18\x0e \x01(\x0b\x32 .temporal.api.common.v1.Payloads\x12\x1e\n\x16\x66irst_execution_run_id\x18\x0f \x01(\t\x12\x39\n\x0cretry_policy\x18\x10 \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x0f\n\x07\x61ttempt\x18\x11 \x01(\x05\x12\x15\n\rcron_schedule\x18\x12 \x01(\t\x12\x46\n"workflow_execution_expiration_time\x18\x13 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x45\n"cron_schedule_to_schedule_interval\x18\x14 \x01(\x0b\x32\x19.google.protobuf.Duration\x12*\n\x04memo\x18\x15 \x01(\x0b\x32\x1c.temporal.api.common.v1.Memo\x12\x43\n\x11search_attributes\x18\x16 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12.\n\nstart_time\x18\x17 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12@\n\rroot_workflow\x18\x18 \x01(\x0b\x32).temporal.api.common.v1.WorkflowExecution\x12\x32\n\x08priority\x18\x19 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12!\n\x19original_execution_run_id\x18\x1a \x01(\t\x12\x65\n&propagated_nexus_serialization_context\x18\x1b \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x18\n\tFireTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r"m\n\x0fResolveActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12;\n\x06result\x18\x02 \x01(\x0b\x32+.coresdk.activity_result.ActivityResolution\x12\x10\n\x08is_local\x18\x03 \x01(\x08"\xd1\x02\n"ResolveChildWorkflowExecutionStart\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12[\n\tsucceeded\x18\x02 \x01(\x0b\x32\x46.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartSuccessH\x00\x12X\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32\x46.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartFailureH\x00\x12]\n\tcancelled\x18\x04 \x01(\x0b\x32H.coresdk.workflow_activation.ResolveChildWorkflowExecutionStartCancelledH\x00\x42\x08\n\x06status";\n)ResolveChildWorkflowExecutionStartSuccess\x12\x0e\n\x06run_id\x18\x01 \x01(\t"\xa6\x01\n)ResolveChildWorkflowExecutionStartFailure\x12\x13\n\x0bworkflow_id\x18\x01 \x01(\t\x12\x15\n\rworkflow_type\x18\x02 \x01(\t\x12M\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32>.coresdk.child_workflow.StartChildWorkflowExecutionFailedCause"`\n+ResolveChildWorkflowExecutionStartCancelled\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"i\n\x1dResolveChildWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12;\n\x06result\x18\x02 \x01(\x0b\x32+.coresdk.child_workflow.ChildWorkflowResult"+\n\x10UpdateRandomSeed\x12\x17\n\x0frandomness_seed\x18\x01 \x01(\x04"\x84\x02\n\rQueryWorkflow\x12\x10\n\x08query_id\x18\x01 \x01(\t\x12\x12\n\nquery_type\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12H\n\x07headers\x18\x05 \x03(\x0b\x32\x37.coresdk.workflow_activation.QueryWorkflow.HeadersEntry\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01" \n\x0e\x43\x61ncelWorkflow\x12\x0e\n\x06reason\x18\x01 \x01(\t"\xa1\x02\n\x0eSignalWorkflow\x12\x13\n\x0bsignal_name\x18\x01 \x01(\t\x12.\n\x05input\x18\x02 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x10\n\x08identity\x18\x03 \x01(\t\x12I\n\x07headers\x18\x05 \x03(\x0b\x32\x38.coresdk.workflow_activation.SignalWorkflow.HeadersEntry\x12\x1c\n\x14originating_event_id\x18\x06 \x01(\x03\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01""\n\x0eNotifyHasPatch\x12\x10\n\x08patch_id\x18\x01 \x01(\t"\xb1\x01\n\x1dResolveSignalExternalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x07\x66\x61ilure\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12P\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32\x41.temporal.api.enums.v1.SignalExternalWorkflowExecutionFailedCause"\xb8\x01\n$ResolveRequestCancelExternalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x31\n\x07\x66\x61ilure\x18\x02 \x01(\x0b\x32 .temporal.api.failure.v1.Failure\x12P\n\x05\x63\x61use\x18\x03 \x01(\x0e\x32\x41.temporal.api.enums.v1.CancelExternalWorkflowExecutionFailedCause"\xb2\x03\n\x08\x44oUpdate\x12\n\n\x02id\x18\x01 \x01(\t\x12\x1c\n\x14protocol_instance_id\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12.\n\x05input\x18\x04 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x43\n\x07headers\x18\x05 \x03(\x0b\x32\x32.coresdk.workflow_activation.DoUpdate.HeadersEntry\x12*\n\x04meta\x18\x06 \x01(\x0b\x32\x1c.temporal.api.update.v1.Meta\x12\x15\n\rrun_validator\x18\x07 \x01(\x08\x12\x65\n&propagated_nexus_serialization_context\x18\x08 \x01(\x0b\x32\x35.temporal.api.nexus.v1.PropagatedSerializationContext\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x9a\x01\n\x1aResolveNexusOperationStart\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x19\n\x0foperation_token\x18\x02 \x01(\tH\x00\x12\x16\n\x0cstarted_sync\x18\x03 \x01(\x08H\x00\x12\x32\n\x06\x66\x61iled\x18\x04 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status"Y\n\x15ResolveNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x33\n\x06result\x18\x02 \x01(\x0b\x32#.coresdk.nexus.NexusOperationResult"\xe0\x02\n\x0fRemoveFromCache\x12\x0f\n\x07message\x18\x01 \x01(\t\x12K\n\x06reason\x18\x02 \x01(\x0e\x32;.coresdk.workflow_activation.RemoveFromCache.EvictionReason"\xee\x01\n\x0e\x45victionReason\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nCACHE_FULL\x10\x01\x12\x0e\n\nCACHE_MISS\x10\x02\x12\x12\n\x0eNONDETERMINISM\x10\x03\x12\r\n\tLANG_FAIL\x10\x04\x12\x12\n\x0eLANG_REQUESTED\x10\x05\x12\x12\n\x0eTASK_NOT_FOUND\x10\x06\x12\x15\n\x11UNHANDLED_COMMAND\x10\x07\x12\t\n\x05\x46\x41TAL\x10\x08\x12\x1f\n\x1bPAGINATION_OR_HISTORY_FETCH\x10\t\x12\x1d\n\x19WORKFLOW_EXECUTION_ENDING\x10\n"\xa1\x01\n\x13ResolveStreamAppend\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12?\n\x08\x61ppended\x18\x02 \x01(\x0b\x32+.coresdk.workflow_activation.StreamAppendedH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status";\n\x0eStreamAppended\x12\x14\n\x0c\x66irst_offset\x18\x01 \x01(\x0c\x12\x13\n\x0blast_offset\x18\x02 \x01(\x0c"\x97\x01\n\x11ResolveStreamRead\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x37\n\x04page\x18\x02 \x01(\x0b\x32\'.coresdk.workflow_activation.StreamPageH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\x08\n\x06status"j\n\nStreamPage\x12\x35\n\x07records\x18\x01 \x03(\x0b\x32$.temporal.api.stream.v1.StreamRecord\x12\x13\n\x0blast_offset\x18\x02 \x01(\x0c\x12\x10\n\x08wait_cut\x18\x03 \x01(\x08\x42\x38\xea\x02\x35Temporalio::Internal::Bridge::Api::WorkflowActivationb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -67,56 +70,64 @@ _SIGNALWORKFLOW_HEADERSENTRY._serialized_options = b"8\001" _DOUPDATE_HEADERSENTRY._options = None _DOUPDATE_HEADERSENTRY._serialized_options = b"8\001" - _WORKFLOWACTIVATION._serialized_start = 611 - _WORKFLOWACTIVATION._serialized_end = 1157 - _WORKFLOWACTIVATIONJOB._serialized_start = 1160 - _WORKFLOWACTIVATIONJOB._serialized_end = 2536 - _INITIALIZEWORKFLOW._serialized_start = 2539 - _INITIALIZEWORKFLOW._serialized_end = 4046 - _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_start = 3967 - _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_end = 4046 - _FIRETIMER._serialized_start = 4048 - _FIRETIMER._serialized_end = 4072 - _RESOLVEACTIVITY._serialized_start = 4074 - _RESOLVEACTIVITY._serialized_end = 4183 - _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_start = 4186 - _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_end = 4523 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_start = 4525 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_end = 4584 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_start = 4587 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_end = 4753 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_start = 4755 - _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_end = 4851 - _RESOLVECHILDWORKFLOWEXECUTION._serialized_start = 4853 - _RESOLVECHILDWORKFLOWEXECUTION._serialized_end = 4958 - _UPDATERANDOMSEED._serialized_start = 4960 - _UPDATERANDOMSEED._serialized_end = 5003 - _QUERYWORKFLOW._serialized_start = 5006 - _QUERYWORKFLOW._serialized_end = 5266 - _QUERYWORKFLOW_HEADERSENTRY._serialized_start = 3967 - _QUERYWORKFLOW_HEADERSENTRY._serialized_end = 4046 - _CANCELWORKFLOW._serialized_start = 5268 - _CANCELWORKFLOW._serialized_end = 5300 - _SIGNALWORKFLOW._serialized_start = 5303 - _SIGNALWORKFLOW._serialized_end = 5592 - _SIGNALWORKFLOW_HEADERSENTRY._serialized_start = 3967 - _SIGNALWORKFLOW_HEADERSENTRY._serialized_end = 4046 - _NOTIFYHASPATCH._serialized_start = 5594 - _NOTIFYHASPATCH._serialized_end = 5628 - _RESOLVESIGNALEXTERNALWORKFLOW._serialized_start = 5631 - _RESOLVESIGNALEXTERNALWORKFLOW._serialized_end = 5808 - _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_start = 5811 - _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_end = 5995 - _DOUPDATE._serialized_start = 5998 - _DOUPDATE._serialized_end = 6432 - _DOUPDATE_HEADERSENTRY._serialized_start = 3967 - _DOUPDATE_HEADERSENTRY._serialized_end = 4046 - _RESOLVENEXUSOPERATIONSTART._serialized_start = 6435 - _RESOLVENEXUSOPERATIONSTART._serialized_end = 6589 - _RESOLVENEXUSOPERATION._serialized_start = 6591 - _RESOLVENEXUSOPERATION._serialized_end = 6680 - _REMOVEFROMCACHE._serialized_start = 6683 - _REMOVEFROMCACHE._serialized_end = 7035 - _REMOVEFROMCACHE_EVICTIONREASON._serialized_start = 6797 - _REMOVEFROMCACHE_EVICTIONREASON._serialized_end = 7035 + _WORKFLOWACTIVATION._serialized_start = 649 + _WORKFLOWACTIVATION._serialized_end = 1195 + _WORKFLOWACTIVATIONJOB._serialized_start = 1198 + _WORKFLOWACTIVATIONJOB._serialized_end = 2736 + _INITIALIZEWORKFLOW._serialized_start = 2739 + _INITIALIZEWORKFLOW._serialized_end = 4246 + _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_start = 4167 + _INITIALIZEWORKFLOW_HEADERSENTRY._serialized_end = 4246 + _FIRETIMER._serialized_start = 4248 + _FIRETIMER._serialized_end = 4272 + _RESOLVEACTIVITY._serialized_start = 4274 + _RESOLVEACTIVITY._serialized_end = 4383 + _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_start = 4386 + _RESOLVECHILDWORKFLOWEXECUTIONSTART._serialized_end = 4723 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_start = 4725 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTSUCCESS._serialized_end = 4784 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_start = 4787 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTFAILURE._serialized_end = 4953 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_start = 4955 + _RESOLVECHILDWORKFLOWEXECUTIONSTARTCANCELLED._serialized_end = 5051 + _RESOLVECHILDWORKFLOWEXECUTION._serialized_start = 5053 + _RESOLVECHILDWORKFLOWEXECUTION._serialized_end = 5158 + _UPDATERANDOMSEED._serialized_start = 5160 + _UPDATERANDOMSEED._serialized_end = 5203 + _QUERYWORKFLOW._serialized_start = 5206 + _QUERYWORKFLOW._serialized_end = 5466 + _QUERYWORKFLOW_HEADERSENTRY._serialized_start = 4167 + _QUERYWORKFLOW_HEADERSENTRY._serialized_end = 4246 + _CANCELWORKFLOW._serialized_start = 5468 + _CANCELWORKFLOW._serialized_end = 5500 + _SIGNALWORKFLOW._serialized_start = 5503 + _SIGNALWORKFLOW._serialized_end = 5792 + _SIGNALWORKFLOW_HEADERSENTRY._serialized_start = 4167 + _SIGNALWORKFLOW_HEADERSENTRY._serialized_end = 4246 + _NOTIFYHASPATCH._serialized_start = 5794 + _NOTIFYHASPATCH._serialized_end = 5828 + _RESOLVESIGNALEXTERNALWORKFLOW._serialized_start = 5831 + _RESOLVESIGNALEXTERNALWORKFLOW._serialized_end = 6008 + _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_start = 6011 + _RESOLVEREQUESTCANCELEXTERNALWORKFLOW._serialized_end = 6195 + _DOUPDATE._serialized_start = 6198 + _DOUPDATE._serialized_end = 6632 + _DOUPDATE_HEADERSENTRY._serialized_start = 4167 + _DOUPDATE_HEADERSENTRY._serialized_end = 4246 + _RESOLVENEXUSOPERATIONSTART._serialized_start = 6635 + _RESOLVENEXUSOPERATIONSTART._serialized_end = 6789 + _RESOLVENEXUSOPERATION._serialized_start = 6791 + _RESOLVENEXUSOPERATION._serialized_end = 6880 + _REMOVEFROMCACHE._serialized_start = 6883 + _REMOVEFROMCACHE._serialized_end = 7235 + _REMOVEFROMCACHE_EVICTIONREASON._serialized_start = 6997 + _REMOVEFROMCACHE_EVICTIONREASON._serialized_end = 7235 + _RESOLVESTREAMAPPEND._serialized_start = 7238 + _RESOLVESTREAMAPPEND._serialized_end = 7399 + _STREAMAPPENDED._serialized_start = 7401 + _STREAMAPPENDED._serialized_end = 7460 + _RESOLVESTREAMREAD._serialized_start = 7463 + _RESOLVESTREAMREAD._serialized_end = 7614 + _STREAMPAGE._serialized_start = 7616 + _STREAMPAGE._serialized_end = 7722 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi index e55917d810..0fbd803777 100644 --- a/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi +++ b/temporalio/bridge/proto/workflow_activation/workflow_activation_pb2.pyi @@ -23,6 +23,7 @@ import temporalio.api.enums.v1.failed_cause_pb2 import temporalio.api.enums.v1.workflow_pb2 import temporalio.api.failure.v1.message_pb2 import temporalio.api.nexus.v1.message_pb2 +import temporalio.api.stream.v1.message_pb2 import temporalio.api.update.v1.message_pb2 import temporalio.bridge.proto.activity_result.activity_result_pb2 import temporalio.bridge.proto.child_workflow.child_workflow_pb2 @@ -49,7 +50,7 @@ class WorkflowActivation(google.protobuf.message.Message): 3. random-seed-updates 4. signals/updates 5. all others - 6. local activity resolutions + 6. Stream results and local activity resolutions 7. queries 8. evictions @@ -65,6 +66,14 @@ class WorkflowActivation(google.protobuf.message.Message): in that same activation (prime example: cancelling not-wait-for-cancel activities). So, we do this to ensure the LA resolution happens after that cancel (or whatever else it may be) as it normally would have when executing. + * Stream results go with the local activity resolutions, for the same reason. Core records a + Stream result in a `core_stream_append` or `core_stream_read` marker, which History has after + the `WorkflowTaskCompleted` event of its task. A replay must give the result before it reaches + that event, so it scans ahead in History for the marker, as for a local activity marker. Each + result in the marker has the index of the activation that got it, so the replay gives it in + that same activation. In one activation, the Stream results go first, appends before reads, + each in `seq` order, and then the local activity resolutions. A task with a Stream marker + retains its recorded activation groups. * Queries always go last (and, in fact, always come in their own activation) * Evictions also always come in their own activation @@ -250,6 +259,8 @@ class WorkflowActivationJob(google.protobuf.message.Message): DO_UPDATE_FIELD_NUMBER: builtins.int RESOLVE_NEXUS_OPERATION_START_FIELD_NUMBER: builtins.int RESOLVE_NEXUS_OPERATION_FIELD_NUMBER: builtins.int + RESOLVE_STREAM_APPEND_FIELD_NUMBER: builtins.int + RESOLVE_STREAM_READ_FIELD_NUMBER: builtins.int REMOVE_FROM_CACHE_FIELD_NUMBER: builtins.int @property def initialize_workflow(self) -> global___InitializeWorkflow: @@ -324,6 +335,14 @@ class WorkflowActivationJob(google.protobuf.message.Message): def resolve_nexus_operation(self) -> global___ResolveNexusOperation: """A nexus operation resolved.""" + @property + def resolve_stream_append(self) -> global___ResolveStreamAppend: + """An append to a Stream finished.""" + + @property + def resolve_stream_read(self) -> global___ResolveStreamRead: + """A read of a Stream finished.""" + @property def remove_from_cache(self) -> global___RemoveFromCache: """Remove the workflow identified by the [WorkflowActivation] containing this job from the @@ -353,6 +372,8 @@ class WorkflowActivationJob(google.protobuf.message.Message): do_update: global___DoUpdate | None = ..., resolve_nexus_operation_start: global___ResolveNexusOperationStart | None = ..., resolve_nexus_operation: global___ResolveNexusOperation | None = ..., + resolve_stream_append: global___ResolveStreamAppend | None = ..., + resolve_stream_read: global___ResolveStreamRead | None = ..., remove_from_cache: global___RemoveFromCache | None = ..., ) -> None: ... def HasField( @@ -386,6 +407,10 @@ class WorkflowActivationJob(google.protobuf.message.Message): b"resolve_request_cancel_external_workflow", "resolve_signal_external_workflow", b"resolve_signal_external_workflow", + "resolve_stream_append", + b"resolve_stream_append", + "resolve_stream_read", + b"resolve_stream_read", "signal_workflow", b"signal_workflow", "update_random_seed", @@ -425,6 +450,10 @@ class WorkflowActivationJob(google.protobuf.message.Message): b"resolve_request_cancel_external_workflow", "resolve_signal_external_workflow", b"resolve_signal_external_workflow", + "resolve_stream_append", + b"resolve_stream_append", + "resolve_stream_read", + b"resolve_stream_read", "signal_workflow", b"signal_workflow", "update_random_seed", @@ -452,6 +481,8 @@ class WorkflowActivationJob(google.protobuf.message.Message): "do_update", "resolve_nexus_operation_start", "resolve_nexus_operation", + "resolve_stream_append", + "resolve_stream_read", "remove_from_cache", ] | None @@ -1645,3 +1676,176 @@ class RemoveFromCache(google.protobuf.message.Message): ) -> None: ... global___RemoveFromCache = RemoveFromCache + +@typing.final +class ResolveStreamAppend(google.protobuf.message.Message): + """Core delivers the result in the next activation, or in the next task when the Store answers + during completion. Stream and Local Activity markers share an activation index. Replay + preserves the recorded activation groups for tasks that contain a Stream marker. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + APPENDED_FIELD_NUMBER: builtins.int + FAILED_FIELD_NUMBER: builtins.int + seq: builtins.int + """The `seq` of the `AppendToStream`.""" + @property + def appended(self) -> global___StreamAppended: ... + @property + def failed(self) -> temporalio.api.failure.v1.message_pb2.Failure: + """An `ApplicationFailureInfo` of the type `stream_`, such as `stream_fenced`, with + `non_retryable` set. Its details have one `binary/protobuf` payload of a + `temporalio.api.stream.v1.StreamErrorDetails`. + """ + + def __init__( + self, + *, + seq: builtins.int = ..., + appended: global___StreamAppended | None = ..., + failed: temporalio.api.failure.v1.message_pb2.Failure | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "appended", b"appended", "failed", b"failed", "status", b"status" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "appended", + b"appended", + "failed", + b"failed", + "seq", + b"seq", + "status", + b"status", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["status", b"status"] + ) -> typing.Literal["appended", "failed"] | None: ... + +global___ResolveStreamAppend = ResolveStreamAppend + +@typing.final +class StreamAppended(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FIRST_OFFSET_FIELD_NUMBER: builtins.int + LAST_OFFSET_FIELD_NUMBER: builtins.int + first_offset: builtins.bytes + last_offset: builtins.bytes + def __init__( + self, + *, + first_offset: builtins.bytes = ..., + last_offset: builtins.bytes = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "first_offset", b"first_offset", "last_offset", b"last_offset" + ], + ) -> None: ... + +global___StreamAppended = StreamAppended + +@typing.final +class ResolveStreamRead(google.protobuf.message.Message): + """The result of a `ReadStream`. Each read gets exactly one, unless Core drops the read (see + `ReadStream`). The activation rules of `ResolveStreamAppend` apply to it too, with the + `core_stream_read` marker in place of the `core_stream_append` one. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + PAGE_FIELD_NUMBER: builtins.int + FAILED_FIELD_NUMBER: builtins.int + seq: builtins.int + """The `seq` of the `ReadStream`.""" + @property + def page(self) -> global___StreamPage: ... + @property + def failed(self) -> temporalio.api.failure.v1.message_pb2.Failure: + """The failure of the read. It has the parts of the `failed` of a `ResolveStreamAppend`.""" + + def __init__( + self, + *, + seq: builtins.int = ..., + page: global___StreamPage | None = ..., + failed: temporalio.api.failure.v1.message_pb2.Failure | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "failed", b"failed", "page", b"page", "status", b"status" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "failed", b"failed", "page", b"page", "seq", b"seq", "status", b"status" + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["status", b"status"] + ) -> typing.Literal["page", "failed"] | None: ... + +global___ResolveStreamRead = ResolveStreamRead + +@typing.final +class StreamPage(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RECORDS_FIELD_NUMBER: builtins.int + LAST_OFFSET_FIELD_NUMBER: builtins.int + WAIT_CUT_FIELD_NUMBER: builtins.int + last_offset: builtins.bytes + """The offset where the page ends, also for a page with no Record. The next read can pass it as + its `from_offset`. + """ + wait_cut: builtins.bool + """True if the page has no Record because the read time of the Workflow Task ended the wait + before the `wait` of the read. A reader that waits for a Record can read again from + `last_offset`. It's false for a page that ends a whole wait. + """ + @property + def records( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + temporalio.api.stream.v1.message_pb2.StreamRecord + ]: + """The Records of the page, in the order of the Stream. It's empty if no Record came while the + read waited. + """ + + def __init__( + self, + *, + records: collections.abc.Iterable[ + temporalio.api.stream.v1.message_pb2.StreamRecord + ] + | None = ..., + last_offset: builtins.bytes = ..., + wait_cut: builtins.bool = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "last_offset", + b"last_offset", + "records", + b"records", + "wait_cut", + b"wait_cut", + ], + ) -> None: ... + +global___StreamPage = StreamPage diff --git a/temporalio/bridge/proto/workflow_commands/__init__.py b/temporalio/bridge/proto/workflow_commands/__init__.py index f599917afa..280eb77ab2 100644 --- a/temporalio/bridge/proto/workflow_commands/__init__.py +++ b/temporalio/bridge/proto/workflow_commands/__init__.py @@ -1,5 +1,6 @@ from .workflow_commands_pb2 import ( ActivityCancellationType, + AppendToStream, CancelChildWorkflowExecution, CancelSignalWorkflow, CancelTimer, @@ -10,6 +11,7 @@ ModifyWorkflowProperties, QueryResult, QuerySuccess, + ReadStream, RequestCancelActivity, RequestCancelExternalWorkflowExecution, RequestCancelLocalActivity, @@ -28,6 +30,7 @@ __all__ = [ "ActivityCancellationType", + "AppendToStream", "CancelChildWorkflowExecution", "CancelSignalWorkflow", "CancelTimer", @@ -38,6 +41,7 @@ "ModifyWorkflowProperties", "QueryResult", "QuerySuccess", + "ReadStream", "RequestCancelActivity", "RequestCancelExternalWorkflowExecution", "RequestCancelLocalActivity", diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py index 3573f36b11..047d40dc0c 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.py @@ -29,6 +29,9 @@ from temporalio.api.sdk.v1 import ( event_group_marker_pb2 as temporal_dot_api_dot_sdk_dot_v1_dot_event__group__marker__pb2, ) +from temporalio.api.sdk.v1 import ( + stream_pb2 as temporal_dot_api_dot_sdk_dot_v1_dot_stream__pb2, +) from temporalio.api.sdk.v1 import ( user_metadata_pb2 as temporal_dot_api_dot_sdk_dot_v1_dot_user__metadata__pb2, ) @@ -46,7 +49,7 @@ ) DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( - b'\n;temporal/sdk/core/workflow_commands/workflow_commands.proto\x12\x19\x63oresdk.workflow_commands\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a$temporal/api/common/v1/message.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a%temporal/api/failure/v1/message.proto\x1a\'temporal/api/sdk/v1/user_metadata.proto\x1a,temporal/api/sdk/v1/event_group_marker.proto\x1a&temporal/api/workflow/v1/message.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a#temporal/sdk/core/nexus/nexus.proto\x1a%temporal/sdk/core/common/common.proto"\xa9\x10\n\x0fWorkflowCommand\x12\x38\n\ruser_metadata\x18\x64 \x01(\x0b\x32!.temporal.api.sdk.v1.UserMetadata\x12\x42\n\x13\x65vent_group_markers\x18\x65 \x03(\x0b\x32%.temporal.api.sdk.v1.EventGroupMarker\x12<\n\x0bstart_timer\x18\x01 \x01(\x0b\x32%.coresdk.workflow_commands.StartTimerH\x00\x12H\n\x11schedule_activity\x18\x02 \x01(\x0b\x32+.coresdk.workflow_commands.ScheduleActivityH\x00\x12\x42\n\x10respond_to_query\x18\x03 \x01(\x0b\x32&.coresdk.workflow_commands.QueryResultH\x00\x12S\n\x17request_cancel_activity\x18\x04 \x01(\x0b\x32\x30.coresdk.workflow_commands.RequestCancelActivityH\x00\x12>\n\x0c\x63\x61ncel_timer\x18\x05 \x01(\x0b\x32&.coresdk.workflow_commands.CancelTimerH\x00\x12[\n\x1b\x63omplete_workflow_execution\x18\x06 \x01(\x0b\x32\x34.coresdk.workflow_commands.CompleteWorkflowExecutionH\x00\x12S\n\x17\x66\x61il_workflow_execution\x18\x07 \x01(\x0b\x32\x30.coresdk.workflow_commands.FailWorkflowExecutionH\x00\x12g\n"continue_as_new_workflow_execution\x18\x08 \x01(\x0b\x32\x39.coresdk.workflow_commands.ContinueAsNewWorkflowExecutionH\x00\x12W\n\x19\x63\x61ncel_workflow_execution\x18\t \x01(\x0b\x32\x32.coresdk.workflow_commands.CancelWorkflowExecutionH\x00\x12\x45\n\x10set_patch_marker\x18\n \x01(\x0b\x32).coresdk.workflow_commands.SetPatchMarkerH\x00\x12`\n\x1estart_child_workflow_execution\x18\x0b \x01(\x0b\x32\x36.coresdk.workflow_commands.StartChildWorkflowExecutionH\x00\x12\x62\n\x1f\x63\x61ncel_child_workflow_execution\x18\x0c \x01(\x0b\x32\x37.coresdk.workflow_commands.CancelChildWorkflowExecutionH\x00\x12w\n*request_cancel_external_workflow_execution\x18\r \x01(\x0b\x32\x41.coresdk.workflow_commands.RequestCancelExternalWorkflowExecutionH\x00\x12h\n"signal_external_workflow_execution\x18\x0e \x01(\x0b\x32:.coresdk.workflow_commands.SignalExternalWorkflowExecutionH\x00\x12Q\n\x16\x63\x61ncel_signal_workflow\x18\x0f \x01(\x0b\x32/.coresdk.workflow_commands.CancelSignalWorkflowH\x00\x12S\n\x17schedule_local_activity\x18\x10 \x01(\x0b\x32\x30.coresdk.workflow_commands.ScheduleLocalActivityH\x00\x12^\n\x1drequest_cancel_local_activity\x18\x11 \x01(\x0b\x32\x35.coresdk.workflow_commands.RequestCancelLocalActivityH\x00\x12\x66\n!upsert_workflow_search_attributes\x18\x12 \x01(\x0b\x32\x39.coresdk.workflow_commands.UpsertWorkflowSearchAttributesH\x00\x12Y\n\x1amodify_workflow_properties\x18\x13 \x01(\x0b\x32\x33.coresdk.workflow_commands.ModifyWorkflowPropertiesH\x00\x12\x44\n\x0fupdate_response\x18\x14 \x01(\x0b\x32).coresdk.workflow_commands.UpdateResponseH\x00\x12U\n\x18schedule_nexus_operation\x18\x15 \x01(\x0b\x32\x31.coresdk.workflow_commands.ScheduleNexusOperationH\x00\x12`\n\x1erequest_cancel_nexus_operation\x18\x16 \x01(\x0b\x32\x36.coresdk.workflow_commands.RequestCancelNexusOperationH\x00\x42\t\n\x07variant"S\n\nStartTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x38\n\x15start_to_fire_timeout\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration"\x1a\n\x0b\x43\x61ncelTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r"\xb8\x06\n\x10ScheduleActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x15\n\ractivity_type\x18\x03 \x01(\t\x12\x12\n\ntask_queue\x18\x05 \x01(\t\x12I\n\x07headers\x18\x06 \x03(\x0b\x32\x38.coresdk.workflow_commands.ScheduleActivity.HeadersEntry\x12\x32\n\targuments\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x34\n\x11heartbeat_timeout\x18\x0b \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x0c \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12N\n\x11\x63\x61ncellation_type\x18\r \x01(\x0e\x32\x33.coresdk.workflow_commands.ActivityCancellationType\x12\x1e\n\x16\x64o_not_eagerly_execute\x18\x0e \x01(\x08\x12;\n\x11versioning_intent\x18\x0f \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12\x32\n\x08priority\x18\x10 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x93\x06\n\x15ScheduleLocalActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x15\n\ractivity_type\x18\x03 \x01(\t\x12\x0f\n\x07\x61ttempt\x18\x04 \x01(\r\x12:\n\x16original_schedule_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12N\n\x07headers\x18\x06 \x03(\x0b\x32=.coresdk.workflow_commands.ScheduleLocalActivity.HeadersEntry\x12\x32\n\targuments\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x0b \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x38\n\x15local_retry_threshold\x18\x0c \x01(\x0b\x32\x19.google.protobuf.Duration\x12N\n\x11\x63\x61ncellation_type\x18\r \x01(\x0e\x32\x33.coresdk.workflow_commands.ActivityCancellationType\x12#\n\x1binclude_arguments_in_marker\x18\x0e \x01(\x08\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"$\n\x15RequestCancelActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r")\n\x1aRequestCancelLocalActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r"\x9c\x01\n\x0bQueryResult\x12\x10\n\x08query_id\x18\x01 \x01(\t\x12<\n\tsucceeded\x18\x02 \x01(\x0b\x32\'.coresdk.workflow_commands.QuerySuccessH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\t\n\x07variant"A\n\x0cQuerySuccess\x12\x31\n\x08response\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"L\n\x19\x43ompleteWorkflowExecution\x12/\n\x06result\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"J\n\x15\x46\x61ilWorkflowExecution\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"\x92\x07\n\x1e\x43ontinueAsNewWorkflowExecution\x12\x15\n\rworkflow_type\x18\x01 \x01(\t\x12\x12\n\ntask_queue\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x37\n\x14workflow_run_timeout\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12Q\n\x04memo\x18\x06 \x03(\x0b\x32\x43.coresdk.workflow_commands.ContinueAsNewWorkflowExecution.MemoEntry\x12W\n\x07headers\x18\x07 \x03(\x0b\x32\x46.coresdk.workflow_commands.ContinueAsNewWorkflowExecution.HeadersEntry\x12\x43\n\x11search_attributes\x18\x08 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12\x39\n\x0cretry_policy\x18\t \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12;\n\x11versioning_intent\x18\n \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12[\n\x1binitial_versioning_behavior\x18\x0b \x01(\x0e\x32\x36.temporal.api.enums.v1.ContinueAsNewVersioningBehavior\x12\x39\n\x16\x62\x61\x63koff_start_interval\x18\x0c \x01(\x0b\x32\x19.google.protobuf.Duration\x1aL\n\tMemoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"L\n\x17\x43\x61ncelWorkflowExecution\x12\x31\n\x07\x64\x65tails\x18\x01 \x01(\x0b\x32 .temporal.api.common.v1.Payloads"6\n\x0eSetPatchMarker\x12\x10\n\x08patch_id\x18\x01 \x01(\t\x12\x12\n\ndeprecated\x18\x02 \x01(\x08"\xe1\t\n\x1bStartChildWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x11\n\tnamespace\x18\x02 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x03 \x01(\t\x12\x15\n\rworkflow_type\x18\x04 \x01(\t\x12\x12\n\ntask_queue\x18\x05 \x01(\t\x12.\n\x05input\x18\x06 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12=\n\x1aworkflow_execution_timeout\x18\x07 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14workflow_run_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x46\n\x13parent_close_policy\x18\n \x01(\x0e\x32).coresdk.child_workflow.ParentClosePolicy\x12N\n\x18workflow_id_reuse_policy\x18\x0c \x01(\x0e\x32,.temporal.api.enums.v1.WorkflowIdReusePolicy\x12\x39\n\x0cretry_policy\x18\r \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x15\n\rcron_schedule\x18\x0e \x01(\t\x12T\n\x07headers\x18\x0f \x03(\x0b\x32\x43.coresdk.workflow_commands.StartChildWorkflowExecution.HeadersEntry\x12N\n\x04memo\x18\x10 \x03(\x0b\x32@.coresdk.workflow_commands.StartChildWorkflowExecution.MemoEntry\x12\x43\n\x11search_attributes\x18\x11 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12P\n\x11\x63\x61ncellation_type\x18\x12 \x01(\x0e\x32\x35.coresdk.child_workflow.ChildWorkflowCancellationType\x12;\n\x11versioning_intent\x18\x13 \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12\x32\n\x08priority\x18\x14 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12I\n\x13versioning_override\x18\x15 \x01(\x0b\x32,.temporal.api.workflow.v1.VersioningOverride\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x1aL\n\tMemoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"J\n\x1c\x43\x61ncelChildWorkflowExecution\x12\x1a\n\x12\x63hild_workflow_seq\x18\x01 \x01(\r\x12\x0e\n\x06reason\x18\x02 \x01(\t"\x8e\x01\n&RequestCancelExternalWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12G\n\x12workflow_execution\x18\x02 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecution\x12\x0e\n\x06reason\x18\x03 \x01(\t"\x8f\x03\n\x1fSignalExternalWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12I\n\x12workflow_execution\x18\x02 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecutionH\x00\x12\x1b\n\x11\x63hild_workflow_id\x18\x03 \x01(\tH\x00\x12\x13\n\x0bsignal_name\x18\x04 \x01(\t\x12-\n\x04\x61rgs\x18\x05 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12X\n\x07headers\x18\x06 \x03(\x0b\x32G.coresdk.workflow_commands.SignalExternalWorkflowExecution.HeadersEntry\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x42\x08\n\x06target"#\n\x14\x43\x61ncelSignalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r"e\n\x1eUpsertWorkflowSearchAttributes\x12\x43\n\x11search_attributes\x18\x01 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes"O\n\x18ModifyWorkflowProperties\x12\x33\n\rupserted_memo\x18\x01 \x01(\x0b\x32\x1c.temporal.api.common.v1.Memo"\xd2\x01\n\x0eUpdateResponse\x12\x1c\n\x14protocol_instance_id\x18\x01 \x01(\t\x12*\n\x08\x61\x63\x63\x65pted\x18\x02 \x01(\x0b\x32\x16.google.protobuf.EmptyH\x00\x12\x34\n\x08rejected\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x12\x34\n\tcompleted\x18\x04 \x01(\x0b\x32\x1f.temporal.api.common.v1.PayloadH\x00\x42\n\n\x08response"\x9a\x04\n\x16ScheduleNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x10\n\x08\x65ndpoint\x18\x02 \x01(\t\x12\x0f\n\x07service\x18\x03 \x01(\t\x12\x11\n\toperation\x18\x04 \x01(\t\x12.\n\x05input\x18\x05 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x06 \x01(\x0b\x32\x19.google.protobuf.Duration\x12X\n\x0cnexus_header\x18\x07 \x03(\x0b\x32\x42.coresdk.workflow_commands.ScheduleNexusOperation.NexusHeaderEntry\x12H\n\x11\x63\x61ncellation_type\x18\x08 \x01(\x0e\x32-.coresdk.nexus.NexusOperationCancellationType\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x1a\x32\n\x10NexusHeaderEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"*\n\x1bRequestCancelNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r*X\n\x18\x41\x63tivityCancellationType\x12\x0e\n\nTRY_CANCEL\x10\x00\x12\x1f\n\x1bWAIT_CANCELLATION_COMPLETED\x10\x01\x12\x0b\n\x07\x41\x42\x41NDON\x10\x02\x42\x36\xea\x02\x33Temporalio::Internal::Bridge::Api::WorkflowCommandsb\x06proto3' + b'\n;temporal/sdk/core/workflow_commands/workflow_commands.proto\x12\x19\x63oresdk.workflow_commands\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a$temporal/api/common/v1/message.proto\x1a$temporal/api/enums/v1/workflow.proto\x1a%temporal/api/failure/v1/message.proto\x1a\'temporal/api/sdk/v1/user_metadata.proto\x1a,temporal/api/sdk/v1/event_group_marker.proto\x1a temporal/api/sdk/v1/stream.proto\x1a&temporal/api/workflow/v1/message.proto\x1a\x35temporal/sdk/core/child_workflow/child_workflow.proto\x1a#temporal/sdk/core/nexus/nexus.proto\x1a%temporal/sdk/core/common/common.proto"\xae\x11\n\x0fWorkflowCommand\x12\x38\n\ruser_metadata\x18\x64 \x01(\x0b\x32!.temporal.api.sdk.v1.UserMetadata\x12\x42\n\x13\x65vent_group_markers\x18\x65 \x03(\x0b\x32%.temporal.api.sdk.v1.EventGroupMarker\x12<\n\x0bstart_timer\x18\x01 \x01(\x0b\x32%.coresdk.workflow_commands.StartTimerH\x00\x12H\n\x11schedule_activity\x18\x02 \x01(\x0b\x32+.coresdk.workflow_commands.ScheduleActivityH\x00\x12\x42\n\x10respond_to_query\x18\x03 \x01(\x0b\x32&.coresdk.workflow_commands.QueryResultH\x00\x12S\n\x17request_cancel_activity\x18\x04 \x01(\x0b\x32\x30.coresdk.workflow_commands.RequestCancelActivityH\x00\x12>\n\x0c\x63\x61ncel_timer\x18\x05 \x01(\x0b\x32&.coresdk.workflow_commands.CancelTimerH\x00\x12[\n\x1b\x63omplete_workflow_execution\x18\x06 \x01(\x0b\x32\x34.coresdk.workflow_commands.CompleteWorkflowExecutionH\x00\x12S\n\x17\x66\x61il_workflow_execution\x18\x07 \x01(\x0b\x32\x30.coresdk.workflow_commands.FailWorkflowExecutionH\x00\x12g\n"continue_as_new_workflow_execution\x18\x08 \x01(\x0b\x32\x39.coresdk.workflow_commands.ContinueAsNewWorkflowExecutionH\x00\x12W\n\x19\x63\x61ncel_workflow_execution\x18\t \x01(\x0b\x32\x32.coresdk.workflow_commands.CancelWorkflowExecutionH\x00\x12\x45\n\x10set_patch_marker\x18\n \x01(\x0b\x32).coresdk.workflow_commands.SetPatchMarkerH\x00\x12`\n\x1estart_child_workflow_execution\x18\x0b \x01(\x0b\x32\x36.coresdk.workflow_commands.StartChildWorkflowExecutionH\x00\x12\x62\n\x1f\x63\x61ncel_child_workflow_execution\x18\x0c \x01(\x0b\x32\x37.coresdk.workflow_commands.CancelChildWorkflowExecutionH\x00\x12w\n*request_cancel_external_workflow_execution\x18\r \x01(\x0b\x32\x41.coresdk.workflow_commands.RequestCancelExternalWorkflowExecutionH\x00\x12h\n"signal_external_workflow_execution\x18\x0e \x01(\x0b\x32:.coresdk.workflow_commands.SignalExternalWorkflowExecutionH\x00\x12Q\n\x16\x63\x61ncel_signal_workflow\x18\x0f \x01(\x0b\x32/.coresdk.workflow_commands.CancelSignalWorkflowH\x00\x12S\n\x17schedule_local_activity\x18\x10 \x01(\x0b\x32\x30.coresdk.workflow_commands.ScheduleLocalActivityH\x00\x12^\n\x1drequest_cancel_local_activity\x18\x11 \x01(\x0b\x32\x35.coresdk.workflow_commands.RequestCancelLocalActivityH\x00\x12\x66\n!upsert_workflow_search_attributes\x18\x12 \x01(\x0b\x32\x39.coresdk.workflow_commands.UpsertWorkflowSearchAttributesH\x00\x12Y\n\x1amodify_workflow_properties\x18\x13 \x01(\x0b\x32\x33.coresdk.workflow_commands.ModifyWorkflowPropertiesH\x00\x12\x44\n\x0fupdate_response\x18\x14 \x01(\x0b\x32).coresdk.workflow_commands.UpdateResponseH\x00\x12U\n\x18schedule_nexus_operation\x18\x15 \x01(\x0b\x32\x31.coresdk.workflow_commands.ScheduleNexusOperationH\x00\x12`\n\x1erequest_cancel_nexus_operation\x18\x16 \x01(\x0b\x32\x36.coresdk.workflow_commands.RequestCancelNexusOperationH\x00\x12\x45\n\x10\x61ppend_to_stream\x18\x17 \x01(\x0b\x32).coresdk.workflow_commands.AppendToStreamH\x00\x12<\n\x0bread_stream\x18\x18 \x01(\x0b\x32%.coresdk.workflow_commands.ReadStreamH\x00\x42\t\n\x07variant"S\n\nStartTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x38\n\x15start_to_fire_timeout\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration"\x1a\n\x0b\x43\x61ncelTimer\x12\x0b\n\x03seq\x18\x01 \x01(\r"\xb8\x06\n\x10ScheduleActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x15\n\ractivity_type\x18\x03 \x01(\t\x12\x12\n\ntask_queue\x18\x05 \x01(\t\x12I\n\x07headers\x18\x06 \x03(\x0b\x32\x38.coresdk.workflow_commands.ScheduleActivity.HeadersEntry\x12\x32\n\targuments\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x34\n\x11heartbeat_timeout\x18\x0b \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x0c \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12N\n\x11\x63\x61ncellation_type\x18\r \x01(\x0e\x32\x33.coresdk.workflow_commands.ActivityCancellationType\x12\x1e\n\x16\x64o_not_eagerly_execute\x18\x0e \x01(\x08\x12;\n\x11versioning_intent\x18\x0f \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12\x32\n\x08priority\x18\x10 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"\x93\x06\n\x15ScheduleLocalActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x13\n\x0b\x61\x63tivity_id\x18\x02 \x01(\t\x12\x15\n\ractivity_type\x18\x03 \x01(\t\x12\x0f\n\x07\x61ttempt\x18\x04 \x01(\r\x12:\n\x16original_schedule_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12N\n\x07headers\x18\x06 \x03(\x0b\x32=.coresdk.workflow_commands.ScheduleLocalActivity.HeadersEntry\x12\x32\n\targuments\x18\x07 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x0cretry_policy\x18\x0b \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x38\n\x15local_retry_threshold\x18\x0c \x01(\x0b\x32\x19.google.protobuf.Duration\x12N\n\x11\x63\x61ncellation_type\x18\r \x01(\x0e\x32\x33.coresdk.workflow_commands.ActivityCancellationType\x12#\n\x1binclude_arguments_in_marker\x18\x0e \x01(\x08\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"$\n\x15RequestCancelActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r")\n\x1aRequestCancelLocalActivity\x12\x0b\n\x03seq\x18\x01 \x01(\r"\x9c\x01\n\x0bQueryResult\x12\x10\n\x08query_id\x18\x01 \x01(\t\x12<\n\tsucceeded\x18\x02 \x01(\x0b\x32\'.coresdk.workflow_commands.QuerySuccessH\x00\x12\x32\n\x06\x66\x61iled\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x42\t\n\x07variant"A\n\x0cQuerySuccess\x12\x31\n\x08response\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"L\n\x19\x43ompleteWorkflowExecution\x12/\n\x06result\x18\x01 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload"J\n\x15\x46\x61ilWorkflowExecution\x12\x31\n\x07\x66\x61ilure\x18\x01 \x01(\x0b\x32 .temporal.api.failure.v1.Failure"\x92\x07\n\x1e\x43ontinueAsNewWorkflowExecution\x12\x15\n\rworkflow_type\x18\x01 \x01(\t\x12\x12\n\ntask_queue\x18\x02 \x01(\t\x12\x32\n\targuments\x18\x03 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12\x37\n\x14workflow_run_timeout\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12Q\n\x04memo\x18\x06 \x03(\x0b\x32\x43.coresdk.workflow_commands.ContinueAsNewWorkflowExecution.MemoEntry\x12W\n\x07headers\x18\x07 \x03(\x0b\x32\x46.coresdk.workflow_commands.ContinueAsNewWorkflowExecution.HeadersEntry\x12\x43\n\x11search_attributes\x18\x08 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12\x39\n\x0cretry_policy\x18\t \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12;\n\x11versioning_intent\x18\n \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12[\n\x1binitial_versioning_behavior\x18\x0b \x01(\x0e\x32\x36.temporal.api.enums.v1.ContinueAsNewVersioningBehavior\x12\x39\n\x16\x62\x61\x63koff_start_interval\x18\x0c \x01(\x0b\x32\x19.google.protobuf.Duration\x1aL\n\tMemoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"L\n\x17\x43\x61ncelWorkflowExecution\x12\x31\n\x07\x64\x65tails\x18\x01 \x01(\x0b\x32 .temporal.api.common.v1.Payloads"6\n\x0eSetPatchMarker\x12\x10\n\x08patch_id\x18\x01 \x01(\t\x12\x12\n\ndeprecated\x18\x02 \x01(\x08"\xe1\t\n\x1bStartChildWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x11\n\tnamespace\x18\x02 \x01(\t\x12\x13\n\x0bworkflow_id\x18\x03 \x01(\t\x12\x15\n\rworkflow_type\x18\x04 \x01(\t\x12\x12\n\ntask_queue\x18\x05 \x01(\t\x12.\n\x05input\x18\x06 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12=\n\x1aworkflow_execution_timeout\x18\x07 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14workflow_run_timeout\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x38\n\x15workflow_task_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x46\n\x13parent_close_policy\x18\n \x01(\x0e\x32).coresdk.child_workflow.ParentClosePolicy\x12N\n\x18workflow_id_reuse_policy\x18\x0c \x01(\x0e\x32,.temporal.api.enums.v1.WorkflowIdReusePolicy\x12\x39\n\x0cretry_policy\x18\r \x01(\x0b\x32#.temporal.api.common.v1.RetryPolicy\x12\x15\n\rcron_schedule\x18\x0e \x01(\t\x12T\n\x07headers\x18\x0f \x03(\x0b\x32\x43.coresdk.workflow_commands.StartChildWorkflowExecution.HeadersEntry\x12N\n\x04memo\x18\x10 \x03(\x0b\x32@.coresdk.workflow_commands.StartChildWorkflowExecution.MemoEntry\x12\x43\n\x11search_attributes\x18\x11 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes\x12P\n\x11\x63\x61ncellation_type\x18\x12 \x01(\x0e\x32\x35.coresdk.child_workflow.ChildWorkflowCancellationType\x12;\n\x11versioning_intent\x18\x13 \x01(\x0e\x32 .coresdk.common.VersioningIntent\x12\x32\n\x08priority\x18\x14 \x01(\x0b\x32 .temporal.api.common.v1.Priority\x12I\n\x13versioning_override\x18\x15 \x01(\x0b\x32,.temporal.api.workflow.v1.VersioningOverride\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x1aL\n\tMemoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01"J\n\x1c\x43\x61ncelChildWorkflowExecution\x12\x1a\n\x12\x63hild_workflow_seq\x18\x01 \x01(\r\x12\x0e\n\x06reason\x18\x02 \x01(\t"\x8e\x01\n&RequestCancelExternalWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12G\n\x12workflow_execution\x18\x02 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecution\x12\x0e\n\x06reason\x18\x03 \x01(\t"\x8f\x03\n\x1fSignalExternalWorkflowExecution\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12I\n\x12workflow_execution\x18\x02 \x01(\x0b\x32+.coresdk.common.NamespacedWorkflowExecutionH\x00\x12\x1b\n\x11\x63hild_workflow_id\x18\x03 \x01(\tH\x00\x12\x13\n\x0bsignal_name\x18\x04 \x01(\t\x12-\n\x04\x61rgs\x18\x05 \x03(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12X\n\x07headers\x18\x06 \x03(\x0b\x32G.coresdk.workflow_commands.SignalExternalWorkflowExecution.HeadersEntry\x1aO\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload:\x02\x38\x01\x42\x08\n\x06target"#\n\x14\x43\x61ncelSignalWorkflow\x12\x0b\n\x03seq\x18\x01 \x01(\r"e\n\x1eUpsertWorkflowSearchAttributes\x12\x43\n\x11search_attributes\x18\x01 \x01(\x0b\x32(.temporal.api.common.v1.SearchAttributes"O\n\x18ModifyWorkflowProperties\x12\x33\n\rupserted_memo\x18\x01 \x01(\x0b\x32\x1c.temporal.api.common.v1.Memo"\xd2\x01\n\x0eUpdateResponse\x12\x1c\n\x14protocol_instance_id\x18\x01 \x01(\t\x12*\n\x08\x61\x63\x63\x65pted\x18\x02 \x01(\x0b\x32\x16.google.protobuf.EmptyH\x00\x12\x34\n\x08rejected\x18\x03 \x01(\x0b\x32 .temporal.api.failure.v1.FailureH\x00\x12\x34\n\tcompleted\x18\x04 \x01(\x0b\x32\x1f.temporal.api.common.v1.PayloadH\x00\x42\n\n\x08response"\x9a\x04\n\x16ScheduleNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r\x12\x10\n\x08\x65ndpoint\x18\x02 \x01(\t\x12\x0f\n\x07service\x18\x03 \x01(\t\x12\x11\n\toperation\x18\x04 \x01(\t\x12.\n\x05input\x18\x05 \x01(\x0b\x32\x1f.temporal.api.common.v1.Payload\x12<\n\x19schedule_to_close_timeout\x18\x06 \x01(\x0b\x32\x19.google.protobuf.Duration\x12X\n\x0cnexus_header\x18\x07 \x03(\x0b\x32\x42.coresdk.workflow_commands.ScheduleNexusOperation.NexusHeaderEntry\x12H\n\x11\x63\x61ncellation_type\x18\x08 \x01(\x0e\x32-.coresdk.nexus.NexusOperationCancellationType\x12<\n\x19schedule_to_start_timeout\x18\t \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x39\n\x16start_to_close_timeout\x18\n \x01(\x0b\x32\x19.google.protobuf.Duration\x1a\x32\n\x10NexusHeaderEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"*\n\x1bRequestCancelNexusOperation\x12\x0b\n\x03seq\x18\x01 \x01(\r"~\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"\xaf\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\x13\n\x0b\x66rom_offset\x18\x03 \x01(\x0c\x12\'\n\x04wait\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x13\n\x0bmax_records\x18\x05 \x01(\x05\x12\x11\n\tmax_bytes\x18\x06 \x01(\x03*X\n\x18\x41\x63tivityCancellationType\x12\x0e\n\nTRY_CANCEL\x10\x00\x12\x1f\n\x1bWAIT_CANCELLATION_COMPLETED\x10\x01\x12\x0b\n\x07\x41\x42\x41NDON\x10\x02\x42\x36\xea\x02\x33Temporalio::Internal::Bridge::Api::WorkflowCommandsb\x06proto3' ) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) @@ -72,70 +75,74 @@ _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_options = b"8\001" _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._options = None _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_options = b"8\001" - _ACTIVITYCANCELLATIONTYPE._serialized_start = 8785 - _ACTIVITYCANCELLATIONTYPE._serialized_end = 8873 - _WORKFLOWCOMMAND._serialized_start = 558 - _WORKFLOWCOMMAND._serialized_end = 2647 - _STARTTIMER._serialized_start = 2649 - _STARTTIMER._serialized_end = 2732 - _CANCELTIMER._serialized_start = 2734 - _CANCELTIMER._serialized_end = 2760 - _SCHEDULEACTIVITY._serialized_start = 2763 - _SCHEDULEACTIVITY._serialized_end = 3587 - _SCHEDULEACTIVITY_HEADERSENTRY._serialized_start = 3508 - _SCHEDULEACTIVITY_HEADERSENTRY._serialized_end = 3587 - _SCHEDULELOCALACTIVITY._serialized_start = 3590 - _SCHEDULELOCALACTIVITY._serialized_end = 4377 - _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_start = 3508 - _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_end = 3587 - _REQUESTCANCELACTIVITY._serialized_start = 4379 - _REQUESTCANCELACTIVITY._serialized_end = 4415 - _REQUESTCANCELLOCALACTIVITY._serialized_start = 4417 - _REQUESTCANCELLOCALACTIVITY._serialized_end = 4458 - _QUERYRESULT._serialized_start = 4461 - _QUERYRESULT._serialized_end = 4617 - _QUERYSUCCESS._serialized_start = 4619 - _QUERYSUCCESS._serialized_end = 4684 - _COMPLETEWORKFLOWEXECUTION._serialized_start = 4686 - _COMPLETEWORKFLOWEXECUTION._serialized_end = 4762 - _FAILWORKFLOWEXECUTION._serialized_start = 4764 - _FAILWORKFLOWEXECUTION._serialized_end = 4838 - _CONTINUEASNEWWORKFLOWEXECUTION._serialized_start = 4841 - _CONTINUEASNEWWORKFLOWEXECUTION._serialized_end = 5755 - _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5598 - _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5674 - _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3508 - _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3587 - _CANCELWORKFLOWEXECUTION._serialized_start = 5757 - _CANCELWORKFLOWEXECUTION._serialized_end = 5833 - _SETPATCHMARKER._serialized_start = 5835 - _SETPATCHMARKER._serialized_end = 5889 - _STARTCHILDWORKFLOWEXECUTION._serialized_start = 5892 - _STARTCHILDWORKFLOWEXECUTION._serialized_end = 7141 - _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3508 - _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3587 - _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5598 - _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5674 - _CANCELCHILDWORKFLOWEXECUTION._serialized_start = 7143 - _CANCELCHILDWORKFLOWEXECUTION._serialized_end = 7217 - _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_start = 7220 - _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_end = 7362 - _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_start = 7365 - _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_end = 7764 - _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3508 - _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3587 - _CANCELSIGNALWORKFLOW._serialized_start = 7766 - _CANCELSIGNALWORKFLOW._serialized_end = 7801 - _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_start = 7803 - _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_end = 7904 - _MODIFYWORKFLOWPROPERTIES._serialized_start = 7906 - _MODIFYWORKFLOWPROPERTIES._serialized_end = 7985 - _UPDATERESPONSE._serialized_start = 7988 - _UPDATERESPONSE._serialized_end = 8198 - _SCHEDULENEXUSOPERATION._serialized_start = 8201 - _SCHEDULENEXUSOPERATION._serialized_end = 8739 - _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_start = 8689 - _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_end = 8739 - _REQUESTCANCELNEXUSOPERATION._serialized_start = 8741 - _REQUESTCANCELNEXUSOPERATION._serialized_end = 8783 + _ACTIVITYCANCELLATIONTYPE._serialized_start = 9258 + _ACTIVITYCANCELLATIONTYPE._serialized_end = 9346 + _WORKFLOWCOMMAND._serialized_start = 592 + _WORKFLOWCOMMAND._serialized_end = 2814 + _STARTTIMER._serialized_start = 2816 + _STARTTIMER._serialized_end = 2899 + _CANCELTIMER._serialized_start = 2901 + _CANCELTIMER._serialized_end = 2927 + _SCHEDULEACTIVITY._serialized_start = 2930 + _SCHEDULEACTIVITY._serialized_end = 3754 + _SCHEDULEACTIVITY_HEADERSENTRY._serialized_start = 3675 + _SCHEDULEACTIVITY_HEADERSENTRY._serialized_end = 3754 + _SCHEDULELOCALACTIVITY._serialized_start = 3757 + _SCHEDULELOCALACTIVITY._serialized_end = 4544 + _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_start = 3675 + _SCHEDULELOCALACTIVITY_HEADERSENTRY._serialized_end = 3754 + _REQUESTCANCELACTIVITY._serialized_start = 4546 + _REQUESTCANCELACTIVITY._serialized_end = 4582 + _REQUESTCANCELLOCALACTIVITY._serialized_start = 4584 + _REQUESTCANCELLOCALACTIVITY._serialized_end = 4625 + _QUERYRESULT._serialized_start = 4628 + _QUERYRESULT._serialized_end = 4784 + _QUERYSUCCESS._serialized_start = 4786 + _QUERYSUCCESS._serialized_end = 4851 + _COMPLETEWORKFLOWEXECUTION._serialized_start = 4853 + _COMPLETEWORKFLOWEXECUTION._serialized_end = 4929 + _FAILWORKFLOWEXECUTION._serialized_start = 4931 + _FAILWORKFLOWEXECUTION._serialized_end = 5005 + _CONTINUEASNEWWORKFLOWEXECUTION._serialized_start = 5008 + _CONTINUEASNEWWORKFLOWEXECUTION._serialized_end = 5922 + _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5765 + _CONTINUEASNEWWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5841 + _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3675 + _CONTINUEASNEWWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3754 + _CANCELWORKFLOWEXECUTION._serialized_start = 5924 + _CANCELWORKFLOWEXECUTION._serialized_end = 6000 + _SETPATCHMARKER._serialized_start = 6002 + _SETPATCHMARKER._serialized_end = 6056 + _STARTCHILDWORKFLOWEXECUTION._serialized_start = 6059 + _STARTCHILDWORKFLOWEXECUTION._serialized_end = 7308 + _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3675 + _STARTCHILDWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3754 + _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_start = 5765 + _STARTCHILDWORKFLOWEXECUTION_MEMOENTRY._serialized_end = 5841 + _CANCELCHILDWORKFLOWEXECUTION._serialized_start = 7310 + _CANCELCHILDWORKFLOWEXECUTION._serialized_end = 7384 + _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_start = 7387 + _REQUESTCANCELEXTERNALWORKFLOWEXECUTION._serialized_end = 7529 + _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_start = 7532 + _SIGNALEXTERNALWORKFLOWEXECUTION._serialized_end = 7931 + _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_start = 3675 + _SIGNALEXTERNALWORKFLOWEXECUTION_HEADERSENTRY._serialized_end = 3754 + _CANCELSIGNALWORKFLOW._serialized_start = 7933 + _CANCELSIGNALWORKFLOW._serialized_end = 7968 + _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_start = 7970 + _UPSERTWORKFLOWSEARCHATTRIBUTES._serialized_end = 8071 + _MODIFYWORKFLOWPROPERTIES._serialized_start = 8073 + _MODIFYWORKFLOWPROPERTIES._serialized_end = 8152 + _UPDATERESPONSE._serialized_start = 8155 + _UPDATERESPONSE._serialized_end = 8365 + _SCHEDULENEXUSOPERATION._serialized_start = 8368 + _SCHEDULENEXUSOPERATION._serialized_end = 8906 + _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_start = 8856 + _SCHEDULENEXUSOPERATION_NEXUSHEADERENTRY._serialized_end = 8906 + _REQUESTCANCELNEXUSOPERATION._serialized_start = 8908 + _REQUESTCANCELNEXUSOPERATION._serialized_end = 8950 + _APPENDTOSTREAM._serialized_start = 8952 + _APPENDTOSTREAM._serialized_end = 9078 + _READSTREAM._serialized_start = 9081 + _READSTREAM._serialized_end = 9256 # @@protoc_insertion_point(module_scope) diff --git a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi index 81c47c0b03..aa64aa718b 100644 --- a/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi +++ b/temporalio/bridge/proto/workflow_commands/workflow_commands_pb2.pyi @@ -24,6 +24,7 @@ import temporalio.api.common.v1.message_pb2 import temporalio.api.enums.v1.workflow_pb2 import temporalio.api.failure.v1.message_pb2 import temporalio.api.sdk.v1.event_group_marker_pb2 +import temporalio.api.sdk.v1.stream_pb2 import temporalio.api.sdk.v1.user_metadata_pb2 import temporalio.api.workflow.v1.message_pb2 import temporalio.bridge.proto.child_workflow.child_workflow_pb2 @@ -105,6 +106,8 @@ class WorkflowCommand(google.protobuf.message.Message): UPDATE_RESPONSE_FIELD_NUMBER: builtins.int SCHEDULE_NEXUS_OPERATION_FIELD_NUMBER: builtins.int REQUEST_CANCEL_NEXUS_OPERATION_FIELD_NUMBER: builtins.int + APPEND_TO_STREAM_FIELD_NUMBER: builtins.int + READ_STREAM_FIELD_NUMBER: builtins.int @property def user_metadata(self) -> temporalio.api.sdk.v1.user_metadata_pb2.UserMetadata: """User metadata that may or may not be persisted into history depending on the command type. @@ -181,6 +184,10 @@ class WorkflowCommand(google.protobuf.message.Message): def request_cancel_nexus_operation( self, ) -> global___RequestCancelNexusOperation: ... + @property + def append_to_stream(self) -> global___AppendToStream: ... + @property + def read_stream(self) -> global___ReadStream: ... def __init__( self, *, @@ -219,10 +226,14 @@ class WorkflowCommand(google.protobuf.message.Message): schedule_nexus_operation: global___ScheduleNexusOperation | None = ..., request_cancel_nexus_operation: global___RequestCancelNexusOperation | None = ..., + append_to_stream: global___AppendToStream | None = ..., + read_stream: global___ReadStream | None = ..., ) -> None: ... def HasField( self, field_name: typing.Literal[ + "append_to_stream", + b"append_to_stream", "cancel_child_workflow_execution", b"cancel_child_workflow_execution", "cancel_signal_workflow", @@ -239,6 +250,8 @@ class WorkflowCommand(google.protobuf.message.Message): b"fail_workflow_execution", "modify_workflow_properties", b"modify_workflow_properties", + "read_stream", + b"read_stream", "request_cancel_activity", b"request_cancel_activity", "request_cancel_external_workflow_execution", @@ -276,6 +289,8 @@ class WorkflowCommand(google.protobuf.message.Message): def ClearField( self, field_name: typing.Literal[ + "append_to_stream", + b"append_to_stream", "cancel_child_workflow_execution", b"cancel_child_workflow_execution", "cancel_signal_workflow", @@ -294,6 +309,8 @@ class WorkflowCommand(google.protobuf.message.Message): b"fail_workflow_execution", "modify_workflow_properties", b"modify_workflow_properties", + "read_stream", + b"read_stream", "request_cancel_activity", b"request_cancel_activity", "request_cancel_external_workflow_execution", @@ -354,6 +371,8 @@ class WorkflowCommand(google.protobuf.message.Message): "update_response", "schedule_nexus_operation", "request_cancel_nexus_operation", + "append_to_stream", + "read_stream", ] | None ): ... @@ -1931,3 +1950,146 @@ class RequestCancelNexusOperation(google.protobuf.message.Message): def ClearField(self, field_name: typing.Literal["seq", b"seq"]) -> None: ... global___RequestCancelNexusOperation = RequestCancelNexusOperation + +@typing.final +class AppendToStream(google.protobuf.message.Message): + """Appends Records as the Workflow Producer and returns ResolveStreamAppend. A retry of a task + whose append has no result in History can write the batch again. Core sends appends to each + Stream in command order. + + An empty Store name selects the runtime under the empty name, or the only runtime if there + is no such entry. Invalid seq or Stream references, missing runtimes and a Store outage at + the task heartbeat fail the Workflow Task. Invalid batches return a failed job. + + Lang must accept results for appends it no longer awaits. The terminal Workflow command drops + unresolved appends. Replay matches seq and Stream and uses the result in History. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + STREAM_FIELD_NUMBER: builtins.int + BODIES_FIELD_NUMBER: builtins.int + seq: builtins.int + """Lang's incremental sequence number for appends, starting at 1.""" + @property + def stream(self) -> temporalio.api.sdk.v1.stream_pb2.StreamRef: ... + @property + def bodies( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + temporalio.api.common.v1.message_pb2.Payload + ]: ... + def __init__( + self, + *, + seq: builtins.int = ..., + stream: temporalio.api.sdk.v1.stream_pb2.StreamRef | None = ..., + bodies: collections.abc.Iterable[temporalio.api.common.v1.message_pb2.Payload] + | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["stream", b"stream"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "bodies", b"bodies", "seq", b"seq", "stream", b"stream" + ], + ) -> None: ... + +global___AppendToStream = AppendToStream + +@typing.final +class ReadStream(google.protobuf.message.Message): + """Reads one page after from_offset. A reader continues from the page's last_offset until an + application Record tells it to stop. + ResolveStreamRead follows the ordering of ResolveStreamAppend. + + A page returns as soon as Records are available. For an empty page Core polls from the Store's + returned offset at most once per 100 ms until wait expires or the task reaches its read time. + StreamSettings.read_time defaults to half the task timeout and starts when replay ends. + An empty page reports wait_cut when the task read time shortens the wait. + + Before completing a task, Core checks unanswered reads with a nonblocking Store call and a + one-second deadline. If the task has a command or a server message, it waits only for this check. + Core carries available Records into the next task when a command must go first. An empty + blocking read resumes on a later task. An idle Stream alone does not request another task. + A nonblocking read can return an empty page in the current task, even after the read deadline. + + Each task delivers at most 16 MiB of encoded Records. After 256 read results, new reads wait + for the next task. Reads already running can finish. A single Record over 16 MiB gives a failed + job with stream_unsupported. A Store outage or an unanswered check fails the Workflow Task with + StreamStoreUnavailable. Lang must accept results it no longer awaits. The terminal Workflow + command drops unresolved reads. + + Replay matches seq, Stream and from_offset. It rereads the recorded range and verifies the + Record count and digest. Retention must cover Workflow replay and later queries. Missing or + changed Records give a StreamReplay error. A missing runtime or unavailable Store fails the + Workflow Task, or the legacy query. Replay loads History in parts. The Store selection rules + are the same as for AppendToStream. + + Negative limits or wait, an offset over 1024 bytes, or an invalid seq or Stream reference + fail the Workflow Task. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SEQ_FIELD_NUMBER: builtins.int + STREAM_FIELD_NUMBER: builtins.int + FROM_OFFSET_FIELD_NUMBER: builtins.int + WAIT_FIELD_NUMBER: builtins.int + MAX_RECORDS_FIELD_NUMBER: builtins.int + MAX_BYTES_FIELD_NUMBER: builtins.int + seq: builtins.int + """Lang's incremental sequence number for reads, starting at 1.""" + from_offset: builtins.bytes + """The page has the Records after this offset. If it's empty, the page starts at the beginning + of the Stream. + """ + max_records: builtins.int + """The maximum number of Records in the page, which is 256 if this is zero.""" + max_bytes: builtins.int + """Page size in encoded Record bytes. Zero selects 4 MiB. A single Record may exceed this + request limit up to the Workflow Task limit of 16 MiB. + """ + @property + def stream(self) -> temporalio.api.sdk.v1.stream_pb2.StreamRef: ... + @property + def wait(self) -> google.protobuf.duration_pb2.Duration: + """How long the read waits for a Record if the Stream has none after `from_offset`. If it's + unset, the read doesn't wait. + """ + + def __init__( + self, + *, + seq: builtins.int = ..., + stream: temporalio.api.sdk.v1.stream_pb2.StreamRef | None = ..., + from_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[ + "from_offset", + b"from_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 cc22dcdeef..5c01cbf94a 160000 --- a/temporalio/bridge/sdk-core +++ b/temporalio/bridge/sdk-core @@ -1 +1 @@ -Subproject commit cc22dcdeef9349365e2bd8be4215761db4ffb3c9 +Subproject commit 5c01cbf94a5d136cc5173c96e1dfae9e792d04c8 diff --git a/temporalio/bridge/src/lib.rs b/temporalio/bridge/src/lib.rs index 867da998ec..71a4d66d55 100644 --- a/temporalio/bridge/src/lib.rs +++ b/temporalio/bridge/src/lib.rs @@ -6,6 +6,7 @@ mod client_rpc_generated; mod envconfig; mod metric; mod runtime; +mod streams; mod testing; mod worker; @@ -53,6 +54,9 @@ fn temporal_sdk_bridge(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { (wrap_pyfunction!(runtime::shutdown_runtimes, m)?,), )?; + m.add_function(wrap_pyfunction!(streams::call_stream_store, m)?)?; + m.add_function(wrap_pyfunction!(streams::check_stream_append, m)?)?; + // Testing stuff m.add_class::()?; m.add_function(wrap_pyfunction!(start_dev_server, m)?)?; diff --git a/temporalio/bridge/src/streams.rs b/temporalio/bridge/src/streams.rs new file mode 100644 index 0000000000..224ca23bcd --- /dev/null +++ b/temporalio/bridge/src/streams.rs @@ -0,0 +1,342 @@ +use futures::future::BoxFuture; +use prost::Message; +use pyo3::exceptions::asyncio::CancelledError; +use pyo3::exceptions::PyValueError; +use pyo3::prelude::*; +use pyo3::sync::PyOnceLock; +use pyo3::types::{IntoPyDict, PyBytes, PyType}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError}; +use std::time::Duration; +use temporalio_sdk_core::StreamRuntimes; +use temporalio_streams::proto::{ + sdk, AppendRecordsRequest, AppendRecordsResponse, CreateStreamRequest, CreateStreamResponse, + DescribeStreamRequest, DescribeStreamResponse, ReadRecordsRequest, ReadRecordsResponse, + StreamErrorReason, +}; +use temporalio_streams::record::StoreLimits; +use temporalio_streams::{ + AppendError, CreateError, DescribeError, ReadError, StreamError, StreamRuntime, StreamStore, + WireReason, +}; + +use crate::runtime; + +struct PythonStore { + caller: Py, + event_loop_task_locals: Arc>, +} + +enum CallState { + Pending, + Running(Py), + Dropped, + Done, +} + +// Release this lock before acquiring the GIL to avoid a deadlock with `OnTask`. +fn lock(state: &Mutex) -> MutexGuard<'_, CallState> { + state.lock().unwrap_or_else(PoisonError::into_inner) +} + +#[pyclass] +struct OnTask { + state: Arc>, +} + +#[pymethods] +impl OnTask { + fn __call__(&self, task: Py) -> PyResult<()> { + let mut state = lock(&self.state); + if matches!(*state, CallState::Dropped) { + drop(state); + return Err(CancelledError::new_err(())); + } + *state = CallState::Running(task); + Ok(()) + } +} + +// Dropping a Core future must also stop its Python Store task. +struct CallGuard<'a> { + state: Arc>, + task_locals: &'a pyo3_async_runtimes::TaskLocals, +} + +impl Drop for CallGuard<'_> { + fn drop(&mut self) { + let state = std::mem::replace(&mut *lock(&self.state), CallState::Dropped); + if let CallState::Running(task) = state { + // `asyncio` requires cross-thread cancellation to run through its event loop. + let _ = Python::try_attach(|py| { + let cancel = task.getattr(py, "cancel")?; + let event_loop = self.task_locals.event_loop(py); + event_loop.call_method1("call_soon_threadsafe", (cancel,))?; + PyResult::Ok(()) + }); + } + } +} + +impl PythonStore { + async fn call( + &self, + operation: &'static str, + request: Request, + request_id: Option, + ) -> Result> + where + Request: Message, + Response: Message + Default, + R: WireReason, + { + let Some(task_locals) = self.event_loop_task_locals.get() else { + return Err(StreamError::store_unavailable( + "The Worker hasn't set the event loop of its Stream Stores yet", + )); + }; + let state = Arc::new(Mutex::new(CallState::Pending)); + let _guard = CallGuard { + state: state.clone(), + task_locals, + }; + let called = Python::try_attach(|py| { + let on_task = OnTask { + state: state.clone(), + }; + let request = PyBytes::new(py, &request.encode_to_vec()); + let arguments = (operation, request, request_id, on_task); + let coroutine = (self.caller.bind(py)).call_method1("call", arguments)?; + pyo3_async_runtimes::into_future_with_locals(task_locals, coroutine) + }); + let answer = match called { + Some(Ok(answer)) => answer.await, + Some(Err(err)) => Err(err), + None => return Err(interpreter_gone(operation)), + }; + let done = Python::try_attach(|py| { + let _task = std::mem::replace(&mut *lock(&state), CallState::Done); + match answer { + Ok(response) => (response.bind(py).cast::().ok()) + .and_then(|bytes| Response::decode(bytes.as_bytes()).ok()) + .ok_or_else(|| { + StreamError::store_corrupt(format!( + "The Store didn't answer the {operation} call with its encoded \ + response message" + )) + }), + Err(err) => Err(store_error(py, err)), + } + }); + done.unwrap_or_else(|| Err(interpreter_gone(operation))) + } +} + +fn interpreter_gone(operation: &str) -> StreamError { + StreamError::store_unavailable(format!( + "The Python interpreter is shutting down, so the Store can't take the {operation} call" + )) +} + +// Only Store refusals retain their reason. Other exceptions can be retried. +fn store_error(py: Python<'_>, err: PyErr) -> StreamError { + let refusal = || -> PyResult> { + let value = err.value(py); + if !value.is_instance(stream_error_type(py)?)? { + return Ok(None); + } + let reason = value.getattr("reason")?.extract()?; + Ok(Some((reason, value.getattr("message")?.extract()?))) + }; + match refusal() { + Ok(Some((reason, message))) => StreamError::from_wire(reason, message), + _ => StreamError::store_unavailable(err.to_string()), + } +} + +fn stream_error_type(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> { + static STREAM_ERROR: PyOnceLock> = PyOnceLock::new(); + STREAM_ERROR.import(py, "temporalio.exceptions", "StreamError") +} + +impl StreamStore for PythonStore { + fn create_stream( + &self, + request: CreateStreamRequest, + request_id: String, + ) -> BoxFuture<'_, Result> { + Box::pin(self.call("CreateStream", request, Some(request_id))) + } + + fn append_records( + &self, + request: AppendRecordsRequest, + request_id: String, + ) -> BoxFuture<'_, Result> { + Box::pin(self.call("AppendRecords", request, Some(request_id))) + } + + fn read_records( + &self, + request: ReadRecordsRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(self.call("ReadRecords", request, None)) + } + + fn describe_stream( + &self, + request: DescribeStreamRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(self.call("DescribeStream", request, None)) + } +} + +// Stores use Core's request and response checks without duplicating its validation rules. +// The calling SDK checks batch limits from its Stream config. +#[pyfunction] +#[pyo3(signature = (runtime_ref, caller, operation, request, request_id=None))] +pub fn call_stream_store<'p>( + py: Python<'p>, + runtime_ref: &runtime::RuntimeRef, + caller: Py, + operation: &str, + request: &Bound<'_, PyBytes>, + request_id: Option, +) -> PyResult> { + let task_locals = pyo3_async_runtimes::TaskLocals::with_running_loop(py)?.copy_context(py)?; + let store = PythonStore { + caller, + event_loop_task_locals: Arc::new(OnceLock::from(task_locals)), + }; + let stream_runtime = StreamRuntime::new(Arc::new(store), StoreLimits::UNBOUNDED); + let with_request_id = || { + request_id + .clone() + .ok_or_else(|| PyValueError::new_err(format!("A {operation} call needs a request id"))) + }; + macro_rules! run { + (|$request:ident: $type:ty| $call:expr) => {{ + let $request: $type = Message::decode(request.as_bytes()) + .map_err(|err| PyValueError::new_err(format!("Invalid proto: {err}")))?; + runtime_ref.runtime.future_into_py(py, async move { + let response = $call.await; + response + .map(|response| response.encode_to_vec()) + .map_err(|err| stream_error(err.reason.into(), err.message)) + }) + }}; + } + match operation { + "CreateStream" => { + let request_id = with_request_id()?; + run!(|decoded: CreateStreamRequest| async { + let request = sdk::CreateStreamRequest { + stream_ref: Some(stream_ref(decoded.stream_id)), + id_conflict_policy: decoded.id_conflict_policy, + }; + let response = stream_runtime.create_stream(request, request_id).await?; + Ok::<_, CreateError>(CreateStreamResponse { + created: response.created, + }) + }) + } + "AppendRecords" => { + let request_id = with_request_id()?; + run!(|decoded: AppendRecordsRequest| { + let request = sdk::AppendRecordsRequest { + r#ref: Some(stream_ref(decoded.stream_id)), + producer: decoded.producer, + records: decoded.records, + }; + stream_runtime.append_records(request, request_id) + }) + } + "ReadRecords" => run!(|decoded: ReadRecordsRequest| { + let request = sdk::ReadRecordsRequest { + r#ref: Some(stream_ref(decoded.stream_id)), + from_offset: decoded.from_offset, + max_records: decoded.max_records, + max_bytes: decoded.max_bytes, + wait: decoded.wait, + }; + stream_runtime.read_records(request) + }), + "DescribeStream" => run!(|decoded: DescribeStreamRequest| { + let request = sdk::DescribeStreamRequest { + r#ref: Some(stream_ref(decoded.stream_id)), + }; + stream_runtime.describe_stream(request) + }), + _ => Err(PyValueError::new_err(format!( + "Unknown Stream operation: {operation}" + ))), + } +} + +fn stream_ref(id: String) -> sdk::StreamRef { + sdk::StreamRef { + id, + store: String::new(), + } +} + +fn store_limits( + (max_record_bytes, max_batch_bytes, max_batch_records): (usize, usize, usize), +) -> PyResult { + StoreLimits::default() + .with_max_record_bytes(max_record_bytes) + .and_then(|limits| limits.with_max_batch_bytes(max_batch_bytes)) + .and_then(|limits| limits.with_max_batch_records(max_batch_records)) + .map_err(|err| PyValueError::new_err(err.message)) +} + +#[derive(FromPyObject)] +pub(crate) struct WorkerStreams { + limits: Option<(usize, usize, usize)>, + stores: Vec<(String, Py)>, + read_time_millis: Option, +} + +impl WorkerStreams { + pub(crate) fn into_runtimes( + self, + task_locals: &Arc>, + ) -> PyResult { + let limits = (self.limits.map(store_limits).transpose()?).unwrap_or_default(); + let runtimes = self.stores.into_iter().map(|(name, caller)| { + let store = PythonStore { + caller, + event_loop_task_locals: task_locals.clone(), + }; + let runtime = StreamRuntime::new(Arc::new(store), limits); + (name, Arc::new(runtime)) + }); + let mut runtimes = StreamRuntimes::new(runtimes); + if let Some(millis) = self.read_time_millis { + runtimes.settings.read_time = Some(Duration::from_millis(millis)); + } + Ok(runtimes) + } +} + +// Client and Workflow appends must enforce the same limits. +#[pyfunction] +pub fn check_stream_append( + limits: (usize, usize, usize), + request: &Bound<'_, PyBytes>, +) -> PyResult<()> { + let request = Message::decode(request.as_bytes()) + .map_err(|err| PyValueError::new_err(format!("Invalid proto: {err}")))?; + store_limits(limits)? + .validate_append(&request) + .map_err(|err| stream_error(err.reason.into(), err.message)) +} + +fn stream_error(reason: StreamErrorReason, message: String) -> PyErr { + Python::attach(|py| { + let error = || { + let reason = [("reason", reason as i32)].into_py_dict(py)?; + stream_error_type(py)?.call((message,), Some(&reason)) + }; + error().map_or_else(|err| err, PyErr::from_value) + }) +} diff --git a/temporalio/bridge/src/worker.rs b/temporalio/bridge/src/worker.rs index 46b6c00de9..335fa0e8a1 100644 --- a/temporalio/bridge/src/worker.rs +++ b/temporalio/bridge/src/worker.rs @@ -5,7 +5,7 @@ use prost::Message; use pyo3::exceptions::{PyException, PyRuntimeError, PyValueError}; use pyo3::prelude::*; use pyo3::types::{PyBytes, PyTuple}; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::marker::PhantomData; use std::sync::{Arc, OnceLock}; use std::time::Duration; @@ -27,6 +27,7 @@ use tracing::error; use crate::client; use crate::runtime; +use crate::streams::WorkerStreams; pyo3::create_exception!(temporal_sdk_bridge, PollShutdownError, PyException); @@ -65,6 +66,9 @@ pub struct WorkerConfig { plugins: Vec<(String, String)>, storage_drivers: HashSet, disable_payload_error_limit: bool, + streams: WorkerStreams, + stream_replay_as_workflow_fail: bool, + stream_replay_as_workflow_fail_for_types: HashSet, } #[derive(FromPyObject)] @@ -522,7 +526,11 @@ pub fn new_replay_worker<'a>( runtime_ref .runtime .assert_same_process("create replay worker")?; - let event_loop_task_locals = Arc::new(OnceLock::new()); + // A replay Worker gets no `validate` call, and a replay reads its Python Stores on the + // loop that created it. + let event_loop_task_locals = Arc::new(OnceLock::from( + pyo3_async_runtimes::TaskLocals::with_running_loop(py)?.copy_context(py)?, + )); let config = convert_worker_config(config, event_loop_task_locals.clone())?; let (history_pusher, stream) = HistoryPusher::new(runtime_ref.runtime.clone()); let worker = WorkerRef { @@ -532,7 +540,7 @@ pub fn new_replay_worker<'a>( PyValueError::new_err(format!("Failed creating replay worker: {err}")) })?, )), - event_loop_task_locals: Default::default(), + event_loop_task_locals, runtime: runtime_ref.runtime.clone(), }; PyTuple::new( @@ -720,6 +728,23 @@ fn convert_worker_config( conf: WorkerConfig, task_locals: Arc>, ) -> PyResult { + let stream_runtimes = conf.streams.into_runtimes(&task_locals)?; + let mut failure_errors = HashSet::new(); + if conf.nondeterminism_as_workflow_fail { + failure_errors.insert(WorkflowErrorType::Nondeterminism); + } + if conf.stream_replay_as_workflow_fail { + failure_errors.insert(WorkflowErrorType::StreamReplay); + } + let mut type_failure_errors = HashMap::>::new(); + for workflow_type in conf.nondeterminism_as_workflow_fail_for_types { + let errors = type_failure_errors.entry(workflow_type).or_default(); + errors.insert(WorkflowErrorType::Nondeterminism); + } + for workflow_type in conf.stream_replay_as_workflow_fail_for_types { + let errors = type_failure_errors.entry(workflow_type).or_default(); + errors.insert(WorkflowErrorType::StreamReplay); + } let converted_tuner = convert_tuner_holder(conf.tuner, task_locals)?; let converted_versioning_strategy = convert_versioning_strategy(conf.versioning_strategy); temporalio_sdk_core::WorkerConfig::builder() @@ -751,22 +776,8 @@ fn convert_worker_config( // auto-cancel-activity behavior of shutdown will not occur, so we // always set it even if 0. .graceful_shutdown_period(Duration::from_millis(conf.graceful_shutdown_period_millis)) - .workflow_failure_errors(if conf.nondeterminism_as_workflow_fail { - HashSet::from([WorkflowErrorType::Nondeterminism]) - } else { - HashSet::new() - }) - .workflow_types_to_failure_errors( - conf.nondeterminism_as_workflow_fail_for_types - .iter() - .map(|s| { - ( - s.to_owned(), - HashSet::from([WorkflowErrorType::Nondeterminism]), - ) - }) - .collect(), - ) + .workflow_failure_errors(failure_errors) + .workflow_types_to_failure_errors(type_failure_errors) .maybe_nexus_task_poller_behavior(conf.nexus_task_poller_behavior.map(Into::into)) .plugins( conf.plugins @@ -781,6 +792,7 @@ fn convert_worker_config( .collect::>(), ) .disable_payload_error_limit(conf.disable_payload_error_limit) + .stream_runtimes(stream_runtimes) .build() .map_err(|err| PyValueError::new_err(format!("Invalid worker config: {err}"))) } diff --git a/temporalio/bridge/streams.py b/temporalio/bridge/streams.py new file mode 100644 index 0000000000..1c6823b507 --- /dev/null +++ b/temporalio/bridge/streams.py @@ -0,0 +1,75 @@ +"""Stream Store calls through SDK Core. (unstable) + +Nothing in this module should be considered stable. The API may change. +""" + +from __future__ import annotations + +import asyncio +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from typing import Any, Protocol + +import temporalio.bridge.runtime +import temporalio.bridge.temporal_sdk_bridge + + +class StoreCaller(Protocol): + """What SDK Core calls to reach a Stream Store that is a Python object.""" + + async def call( + self, + operation: str, + request: bytes, + request_id: str | None, + on_task: Callable[[asyncio.Task[Any]], None], + ) -> bytes: + """Call the Store for a Stream operation with its encoded request, and + return its encoded response. + + ``request_id`` is that of a create or an append, and ``None`` for the + other operations. + """ + ... + + +@dataclass +class WorkerStreams: + """Python representation of the Rust struct for the Stream Stores of a worker.""" + + limits: tuple[int, int, int] | None + """The ``max_record_bytes``, the ``max_batch_bytes`` and the ``max_batch_records`` + of the Stream config, or ``None`` with no Stream config.""" + stores: Sequence[tuple[str, StoreCaller]] + """The caller of each Stream Store that Workflow code can use, by Store name.""" + read_time_millis: int | None + + +async def call_stream_store( + runtime: temporalio.bridge.runtime.Runtime, + caller: StoreCaller, + operation: str, + request: bytes, + request_id: str | None = None, +) -> bytes: + """Call a Stream Store through the Stream runtime of SDK Core, which checks + the request and the response. + + A create and an append need their ``request_id``, and the other operations + take none. + """ + return await temporalio.bridge.temporal_sdk_bridge.call_stream_store( + runtime._ref, caller, operation, request, request_id + ) + + +def check_append(limits: tuple[int, int, int], request: bytes) -> None: + """Check an encoded append as SDK Core checks one of Workflow code. + + ``limits`` are the ``max_record_bytes``, the ``max_batch_bytes`` and the + ``max_batch_records`` of a Stream config. + + Raises: + temporalio.exceptions.StreamError: The check refuses the append. + """ + temporalio.bridge.temporal_sdk_bridge.check_stream_append(limits, request) diff --git a/temporalio/bridge/worker.py b/temporalio/bridge/worker.py index fa5f337ca7..c5f6eb8a6c 100644 --- a/temporalio/bridge/worker.py +++ b/temporalio/bridge/worker.py @@ -18,6 +18,7 @@ import temporalio.bridge.proto.workflow_activation import temporalio.bridge.proto.workflow_completion import temporalio.bridge.runtime +import temporalio.bridge.streams import temporalio.bridge.temporal_sdk_bridge import temporalio.converter import temporalio.converter._extstore @@ -29,7 +30,10 @@ from temporalio.bridge.temporal_sdk_bridge import ( PollShutdownError, # type: ignore # noqa: F401 ) -from temporalio.worker._command_aware_visitor import CommandAwarePayloadVisitor +from temporalio.worker._command_aware_visitor import ( + CommandAwarePayloadVisitor, + StoragePayloadVisitor, +) @dataclass @@ -60,6 +64,9 @@ class WorkerConfig: plugins: Sequence[tuple[str, str]] storage_drivers: set[str] disable_payload_error_limit: bool + streams: temporalio.bridge.streams.WorkerStreams + stream_replay_as_workflow_fail: bool + stream_replay_as_workflow_fail_for_types: set[str] @dataclass @@ -315,14 +322,14 @@ async def decode_activation( Returns: Metrics from any external storage retrieval operations that occurred. """ - await CommandAwarePayloadVisitor( + await StoragePayloadVisitor( skip_search_attributes=True, skip_headers=not decode_headers, ).visit(_Visitor(data_converter._decode_reference_payload_sequence), activation) metrics = temporalio.converter._extstore.StorageOperationMetrics() with metrics.track(): - await CommandAwarePayloadVisitor( + await StoragePayloadVisitor( skip_search_attributes=True, skip_headers=not decode_headers, concurrency_limit=storage_concurrency_limit, @@ -364,7 +371,7 @@ async def encode_completion( if data_converter.external_storage: with metrics.track(): - await CommandAwarePayloadVisitor( + await StoragePayloadVisitor( skip_search_attributes=True, skip_headers=not encode_headers, concurrency_limit=storage_concurrency_limit, @@ -373,7 +380,7 @@ async def encode_completion( completion, ) - await CommandAwarePayloadVisitor( + await StoragePayloadVisitor( skip_search_attributes=True, skip_headers=not encode_headers, ).visit( diff --git a/temporalio/client/__init__.py b/temporalio/client/__init__.py index 2eef41a39d..75e32e5e2c 100644 --- a/temporalio/client/__init__.py +++ b/temporalio/client/__init__.py @@ -185,6 +185,11 @@ ScheduleUpdate, ScheduleUpdateInput, ) +from ._stream_store import ( + StreamConfig, + StreamSelectContext, + StreamStore, +) from ._worker_versioning import ( BuildIdOp, BuildIdOpAddNewCompatible, @@ -350,6 +355,9 @@ "TaskReachabilityType", "CloudOperationsClient", "Plugin", + "StreamConfig", + "StreamSelectContext", + "StreamStore", "Callback", "_ClientImpl", "_apply_headers", diff --git a/temporalio/client/_client.py b/temporalio/client/_client.py index 18c9d27a58..f4cd1b9161 100644 --- a/temporalio/client/_client.py +++ b/temporalio/client/_client.py @@ -29,6 +29,7 @@ import temporalio.runtime import temporalio.service import temporalio.workflow +from temporalio.nexus.system.stream_service.client import StreamServiceClientExtension from temporalio.service import ( ConnectConfig, DnsLoadBalancingConfig, @@ -95,6 +96,7 @@ ScheduleBackfill, ScheduleHandle, ) +from ._stream_store import StreamConfig from ._worker_versioning import ( BuildIdOp, TaskReachabilityType, @@ -115,7 +117,7 @@ from ._plugin import Plugin -class Client: +class Client(StreamServiceClientExtension): """Client for accessing Temporal. Most users will use :py:meth:`connect` to create a client. The @@ -157,6 +159,7 @@ async def connect( grpc_compression: GrpcCompression = GrpcCompression.GZIP, payload_limits: PayloadLimitsConfig = PayloadLimitsConfig(), header_codec_behavior: HeaderCodecBehavior = HeaderCodecBehavior.NO_CODEC, + stream_config: StreamConfig | None = None, ) -> Self: """Connect to a Temporal server. @@ -226,6 +229,13 @@ async def connect( payload_limits: Warning thresholds for outbound payload/memo sizes. Over-threshold fields are logged but still sent. Set a threshold to 0 to disable it. header_codec_behavior: Encoding behavior for headers sent by the client. + stream_config: Stream Stores of this client and of each worker that + uses it. The client sends each Stream call to one of these + Stores, so a Stream call of a client with none raises + :exc:`ValueError`. + + .. warning:: + This API is experimental and subject to change. """ connect_config = temporalio.service.ConnectConfig( target_host=target_host, @@ -263,6 +273,7 @@ def make_lambda( default_workflow_query_reject_condition=default_workflow_query_reject_condition, header_codec_behavior=header_codec_behavior, plugins=plugins, + stream_config=stream_config, ) def __init__( @@ -276,6 +287,7 @@ def __init__( default_workflow_query_reject_condition: None | (temporalio.common.QueryRejectCondition) = None, header_codec_behavior: HeaderCodecBehavior = HeaderCodecBehavior.NO_CODEC, + stream_config: StreamConfig | None = None, ): """Create a Temporal client from a service client. @@ -290,6 +302,7 @@ def __init__( interceptors=interceptors, default_workflow_query_reject_condition=default_workflow_query_reject_condition, header_codec_behavior=header_codec_behavior, + stream_config=stream_config, ) self._initial_config = config.copy() self._stream_producer_id = str(uuid.uuid4()) @@ -3031,6 +3044,7 @@ class ClientConnectConfig(TypedDict, total=False): grpc_compression: GrpcCompression payload_limits: PayloadLimitsConfig header_codec_behavior: HeaderCodecBehavior + stream_config: StreamConfig | None class ClientConfig(TypedDict, total=False): @@ -3045,3 +3059,4 @@ class ClientConfig(TypedDict, total=False): temporalio.common.QueryRejectCondition | None ] header_codec_behavior: Required[HeaderCodecBehavior] + stream_config: Required[StreamConfig | None] diff --git a/temporalio/client/_impl.py b/temporalio/client/_impl.py index e6424c15eb..d647abc5e9 100644 --- a/temporalio/client/_impl.py +++ b/temporalio/client/_impl.py @@ -34,6 +34,7 @@ import temporalio.exceptions import temporalio.nexus import temporalio.nexus._operation_context +import temporalio.nexus.system from temporalio.activity import ActivityCancellationDetails from temporalio.converter import ( ActivitySerializationContext, @@ -126,6 +127,7 @@ ScheduleUpdate, ScheduleUpdateInput, ) +from ._stream_store import _STREAM_SERVICE, _call_stream_store from ._worker_versioning import WorkerBuildIdVersionSets, WorkerTaskReachability from ._workflow import ( WorkflowExecutionAsyncIterator, @@ -1581,6 +1583,11 @@ async def start_nexus_operation( self, input: StartNexusOperationInput ) -> NexusOperationHandle[Any]: """Start a nexus operation and return a handle to it.""" + if ( + temporalio.nexus.system.is_system_endpoint(input.endpoint) + and input.service == _STREAM_SERVICE.name + ): + return await _call_stream_store(self._client, input) nexus_context = temporalio.converter.NexusSerializationContext( endpoint=input.endpoint, service=input.service, diff --git a/temporalio/client/_interceptor.py b/temporalio/client/_interceptor.py index 75463b4971..c6cc6bd3ab 100644 --- a/temporalio/client/_interceptor.py +++ b/temporalio/client/_interceptor.py @@ -2,13 +2,14 @@ from __future__ import annotations +import uuid from collections.abc import ( Awaitable, Callable, Mapping, Sequence, ) -from dataclasses import dataclass +from dataclasses import dataclass, field from datetime import timedelta from typing import ( TYPE_CHECKING, @@ -609,6 +610,10 @@ class StartNexusOperationInput: rpc_metadata: Mapping[str, str | bytes] rpc_timeout: timedelta | None completion_callbacks: Sequence[temporalio.nexus.CompletionCallback[Any]] = () + # Interceptors can retry a Store write with a copy of this input after losing its answer. + _stream_request_id: uuid.UUID = field( + default_factory=uuid.uuid4, repr=False, compare=False, kw_only=True + ) @dataclass diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py new file mode 100644 index 0000000000..c34fb2519a --- /dev/null +++ b/temporalio/client/_stream_store.py @@ -0,0 +1,630 @@ +"""Stream Stores and the Stream config of a client.""" + +from __future__ import annotations + +import asyncio +import logging +from abc import ABC, abstractmethod +from collections.abc import Callable, Sequence +from dataclasses import dataclass, field +from datetime import timedelta +from typing import Any + +import google.protobuf.message +import nexusrpc + +import temporalio.activity +import temporalio.api.sdk.v1 as sdk +import temporalio.bridge.streams + +# pydoctor reads this module before the client package, for the worker modules that +# import it. A `from` import of a sibling here would lose the package's re-exports. +import temporalio.client +import temporalio.nexus.system._support +from temporalio.api.enums.v1 import StreamErrorReason +from temporalio.api.streamservice.v1 import ( + AppendRecordsRequest, + AppendRecordsResponse, + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, +) +from temporalio.converter import ( + PayloadCodec, + StorageDriverActivityInfo, + StorageDriverWorkflowInfo, +) +from temporalio.converter._payload_converter import _get_transfer_type_converter +from temporalio.exceptions import StreamError +from temporalio.nexus.system.stream_service import StreamService + +logger = logging.getLogger(__name__) + +_definition = nexusrpc.get_service_definition(StreamService) +assert _definition +_STREAM_SERVICE: nexusrpc.ServiceDefinition = _definition + +_READ_ANSWER_TIME = timedelta(seconds=1) +"""The time that a client read leaves its Store to answer before the +``rpc_timeout``. A tenth of a shorter timeout is used instead.""" + + +class StreamStore(ABC): + """Base class for a Store that keeps Stream Records. + + Methods use request and response messages from + :py:mod:`temporalio.api.streamservice.v1`. Requests contain a Stream id. + The SDK routes each ``StreamRef`` to its registered Store and sets the Store + name on refs returned by create. Stores don't read or set ``StreamRef.store``. + + Workflow execution and replay depend on these contracts. + + Retention: + + * Retention starts at create and restarts after an append that writes a batch. + Retries and reads don't extend it. The Store sets the retention period. + * An expired Stream has no Records and rejects calls with ``EXPIRED``. + * Streams have no stored end. Applications use their own terminal Record. + + Records and offsets: + + * Keep each body as received. The payload codec has already encoded it. + * Write each append batch atomically, with contiguous Records in request order. + * Record offsets are nonempty and sort bytewise in Record order. + * After a response returns an offset, no later write can insert a Record at + or below it. This also applies to concurrent writes. + * Keep Records unchanged until the Stream expires. + + Producers and attempts: + + * A Producer identifies a Workflow run, Activity, Local Activity or client. + Its kind and ids determine its identity. + * An attempt identifies a Producer's execution attempt, such as a Workflow + Task or Activity attempt. Every Record retains its Producer and attempt. + * Fencing is optional. A Store that fences rejects an earlier attempt once + a later attempt of that Producer has written to the Stream. + + Reject calls with :py:class:`temporalio.exceptions.StreamError` and its reason. + These docs omit the ``STREAM_ERROR_REASON_`` prefix from reason names. + Other exceptions become ``STORE_UNAVAILABLE`` errors. Workflow append and + read refusals record messages of at most 4 KiB in History. All Stream marker + data in an activation must fit within 1 MiB. Keep messages short to avoid + failing the Workflow Task with ``StreamMarkerTooLarge``. + + Calls can run concurrently on the event loop. Cancellation can follow a + timeout, eviction or Worker shutdown. A cancelled call may have taken effect. + The Store must remain usable, and overlapping retries must not duplicate a + batch. + + SDK Core validates and retries Workflow appends and reads during outages. + Other calls make one attempt. For those calls, the SDK checks only append + limits from :py:class:`StreamConfig`. Stores must perform any other checks + they require. + + .. warning:: + This API is experimental and subject to change. + """ + + @abstractmethod + def name(self) -> str: + """Return the Store name registered in :py:class:`StreamConfig`. + + The name must remain stable. Separate instances of one Store class can + use different names. + """ + raise NotImplementedError + + @abstractmethod + async def create_stream( + self, request: CreateStreamRequest, *, request_id: str + ) -> CreateStreamResponse: + """Create a Stream, or reuse it if the conflict policy permits. + + Retries use the same ``request_id``. An empty id never identifies a retry. + The response contains only ``created``. + + For an existing Stream, check these conditions in order. + + 1. An expired Stream fails with ``EXPIRED``. + 2. A matching create ``request_id`` returns ``created=True``. + 3. ``USE_EXISTING`` returns ``created=False``. ``FAIL`` or an unset policy + fails with ``ALREADY_EXISTS``. + + Only a new Stream starts retention. Reusing a Stream doesn't extend it. + """ + raise NotImplementedError + + @abstractmethod + async def append_records( + self, request: AppendRecordsRequest, *, request_id: str + ) -> AppendRecordsResponse: + """Append one batch from one Producer. + + Retries of one append use the same ``request_id``. + Retain recent request ids for each Producer, including at least its last + batch. Matching Producer, attempt and ``request_id`` identify a resend. + An empty request id never identifies a resend. + + Check these conditions in order. + + 1. Missing or expired Streams fail with ``NOT_FOUND`` or ``EXPIRED``. + 2. A resend returns the original offsets without comparing or writing + Records. + 3. If fencing is enabled, an attempt older than the latest writer attempt + fails with ``FENCED``. + + Return the first and last Record offsets. Only a new batch extends + retention. A resend doesn't extend it. + """ + raise NotImplementedError + + @abstractmethod + async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: + """Read one page after ``from_offset``, in Stream order. + + * Apply ``max_records`` and ``max_bytes``. Zero uses the Store's default. + Include the first Record even if it exceeds ``max_bytes``. + * ``last_offset`` is the cursor for the next read. If omitted, the SDK + uses the last Record's offset, or ``from_offset`` for an empty page. + * If no Records are available, wait until one arrives or ``wait`` expires. + An unset wait returns immediately. The SDK converts zero to an unset + wait. Returning empty pages before a requested wait expires can cause + callers to poll repeatedly. + * Accept any offset returned by a response. Reject ``from_offset`` with + ``OFFSET_TOO_HIGH`` only if it exceeds the end of the Stream. + """ + raise NotImplementedError + + @abstractmethod + async def describe_stream( + self, request: DescribeStreamRequest + ) -> DescribeStreamResponse: + """Return a ``last_offset`` at or beyond the newest Record's offset.""" + raise NotImplementedError + + +@dataclass(frozen=True) +class StreamSelectContext: + """Context passed to :py:attr:`StreamConfig.store_selector` calls. + + .. warning:: + This API is experimental and subject to change. + """ + + id: str + """The id of the Stream of the call.""" + + target: StorageDriverActivityInfo | StorageDriverWorkflowInfo | None = None + """The Workflow or the Activity that makes the call, or ``None`` for other + client code.""" + + namespace: str | None = None + """The namespace of the client or Worker that makes the call. + + It is set even when :py:attr:`target` is ``None``, so that a selector can pick a + Store by namespace for plain client code too.""" + + +@dataclass(frozen=True) +class StreamConfig: + """Stream Stores shared by a client and its Workers. + + Appends that exceed :py:attr:`max_record_bytes`, :py:attr:`max_batch_bytes` + or :py:attr:`max_batch_records` fail with ``STREAM_ERROR_REASON_TOO_LARGE`` + before reaching the Store. ``rpc_metadata`` has no effect on Store calls. + + Streams have no close. Retention starts at create and restarts after each + append that writes a batch. Applications use their own terminal Record. + + In client, Activity and Workflow code, ``read`` and ``read_pages`` continue + after empty pages. ``read_pages`` yields those pages. Callers must stop the + iterator, for example with ``break`` or a timeout. An unset ``wait`` makes the + first request immediate. Later requests wait up to one minute. An explicit + wait applies to every request. Zero disables waiting, so an idle Stream can + cause repeated empty reads. ``read_page`` has no default wait. After a page, + the ``read`` iterator's ``next_request`` includes the next request's wait. + + A positive ``rpc_timeout`` caps client and Activity waits below the timeout, + leaving time for the Store to answer. An Activity that heartbeats between + Records needs a wait below its heartbeat timeout, or a separate heartbeat task. + + Workflow calls: + + * The SDK selects a Store before each call, including replay. SDK Core handles + append and read. Create and describe use SDK Local Activities, which pass + through Worker interceptors. + * Appends are at-least-once. A Workflow Task retry can write its batch again. + * Store outages fail the Workflow Task. Workflow code gets no outage error. + * A missing Store fails the Workflow Task even if Workflow code catches the + error. A call not awaited before Workflow completion may not run. + * Workers read the limits at startup. A replacement client must have the same + limits and Store names. + * Pages default to 256 Records and 4 MiB, with a 16 MiB byte cap. A live read + rejects a Record over :py:attr:`max_record_bytes` with + ``STREAM_ERROR_REASON_UNSUPPORTED``. Reader limits must cover writer limits. + Replay accepts recorded successes even if the limits decrease. + * An immediate read can return an empty page. A waiting read stops at its + wait or the Worker's ``stream_read_time`` limit, whichever comes first. + At the task limit, ``read_page`` returns an empty page. + * Iterators can continue across Workflow Tasks. Each page adds a result to + History, so zero or short waits can cause rapid History growth. The default + wait limits empty pages, and an idle Stream doesn't create new tasks. + * A waiting read holds its task and delays Signals until its page or the read + limit. A server command waits for at most one immediate Store call per read, + bounded by one second. + * An unfinished waiting read restarts in the next task. It requests that task + only when Core knows more Records are available. A task returns at most + 256 read results. Later reads start in the next task. + * Replay reads the Records from the Store again. Retention must cover the + Workflow's life and any later replay or query. + * A body that can't convert to the Stream's type fails the Workflow Task. + + .. warning:: + This API is experimental and subject to change. + """ + + stores: Sequence[StreamStore] + """Stores available for Stream calls. At least one Store must be provided, + and each Store must have a unique :py:meth:`StreamStore.name` that isn't + empty. + """ + + store_selector: Callable[[StreamSelectContext], StreamStore] | None = None + """Select the Store for a call whose ``StreamRef`` has no Store name. + + Return an instance from :py:attr:`stores`. A selector is required with + multiple Stores. Without one, the sole Store handles these calls. + + Workflow calls invoke the selector before each command, including creates, + describes and replay. The selector must return the same Store for the same + call, must not block or perform I/O, and must be safe across threads. Core + receives the selected Store name with each command. + + Replayed appends and reads fail with nondeterminism if their selected Store + differs from History. Create and describe use their recorded results. A + created Stream's ref includes its Store name, so later calls skip selection. + """ + + max_record_bytes: int = 1536 * 1024 + """Maximum stored Record size for an append or a live Workflow read. + + Includes its Producer. Defaults to 1.5 MiB and must be at least one. + """ + + max_batch_bytes: int = 4 * 1024 * 1024 + """Maximum size in bytes of the Records of one append, each in its stored + size. Defaults to 4 MiB. Must be greater than or equal to one. + """ + + max_batch_records: int = 1000 + """Maximum number of Records of one append. Defaults to 1000. Must be + greater than or equal to one. + """ + + _by_name: dict[str, StreamStore] = field( + init=False, repr=False, compare=False, default_factory=dict + ) + """Snapshot Store names so later name changes can't change routing.""" + + def __post_init__(self) -> None: + """Validate the Stores and the limits. + + Raises :exc:`ValueError` if no Store is provided, if a limit is less + than one, if more than one Store is registered without a + :py:attr:`store_selector`, if a Store has an empty name, or if any two + Stores have the same name. + """ + if not self.stores: + raise ValueError("StreamConfig.stores must contain at least one Store.") + for limit in ("max_record_bytes", "max_batch_bytes", "max_batch_records"): + if getattr(self, limit) < 1: + raise ValueError( + f"StreamConfig.{limit} must be greater than or equal to one." + ) + if len(self.stores) > 1 and self.store_selector is None: + raise ValueError( + "StreamConfig.store_selector must be specified if multiple Stores " + "are registered." + ) + by_name: dict[str, StreamStore] = {} + for store in self.stores: + name = store.name() + if not name: + raise ValueError( + "StreamConfig.stores contains a Store with an empty name." + ) + if name in by_name: + raise ValueError( + f"StreamConfig.stores contains multiple Stores with name '{name}'. " + "Each Store must have a unique name." + ) + by_name[name] = store + object.__setattr__(self, "_by_name", by_name) + + def _store(self, name: str) -> StreamStore: + store = self._by_name.get(name) + if store is None: + raise ValueError(f"No Stream Store found with name '{name}'") + return store + + def _store_for( + self, + ref: sdk.StreamRef, + target: StorageDriverActivityInfo | StorageDriverWorkflowInfo | None, + namespace: str, + ) -> StreamStore: + if ref.store: + return self._store(ref.store) + if self.store_selector is None: + return self.stores[0] + selected = self.store_selector( + StreamSelectContext(id=ref.id, target=target, namespace=namespace) + ) + if not any(selected is store for store in self.stores): + raise ValueError( + "Store returned by store_selector is not registered in StreamConfig.stores" + ) + return selected + + def _limits(self) -> tuple[int, int, int]: + return self.max_record_bytes, self.max_batch_bytes, self.max_batch_records + + +def _request_ref(request: google.protobuf.message.Message) -> sdk.StreamRef: + if isinstance(request, sdk.CreateStreamRequest): + return request.stream_ref + assert isinstance( + request, + (sdk.AppendRecordsRequest, sdk.ReadRecordsRequest, sdk.DescribeStreamRequest), + ) + return request.ref + + +_Message = type[google.protobuf.message.Message] + +_STORE_OPERATIONS: dict[str, tuple[str, _Message, _Message]] = { + "CreateStream": ("create_stream", CreateStreamRequest, CreateStreamResponse), + "AppendRecords": ("append_records", AppendRecordsRequest, AppendRecordsResponse), + "ReadRecords": ("read_records", ReadRecordsRequest, ReadRecordsResponse), + "DescribeStream": ( + "describe_stream", + DescribeStreamRequest, + DescribeStreamResponse, + ), +} + + +def _store_operation(name: str) -> tuple[str, _Message, _Message]: + return _STORE_OPERATIONS[name] + + +def _sdk_request_type( # pyright: ignore[reportUnusedFunction] + name: str, +) -> _Message: + operation = _STREAM_SERVICE.operation_definitions[name] + converter = _get_transfer_type_converter(operation.input_type) + assert converter and converter.transfer_type + return converter.transfer_type + + +def _store_request( + request: google.protobuf.message.Message, +) -> google.protobuf.message.Message: + stream_id = _request_ref(request).id + if isinstance(request, sdk.CreateStreamRequest): + return CreateStreamRequest( + stream_id=stream_id, id_conflict_policy=request.id_conflict_policy + ) + if isinstance(request, sdk.AppendRecordsRequest): + append = AppendRecordsRequest(stream_id=stream_id, records=request.records) + if request.HasField("producer"): + append.producer.CopyFrom(request.producer) + return append + if isinstance(request, sdk.ReadRecordsRequest): + read = ReadRecordsRequest( + stream_id=stream_id, + from_offset=request.from_offset, + max_records=request.max_records, + max_bytes=request.max_bytes, + ) + # A Store may take a zero wait as one with no end, such as Redis BLOCK 0. + if request.HasField("wait") and (request.wait.seconds or request.wait.nanos): + read.wait.CopyFrom(request.wait) + return read + return DescribeStreamRequest(stream_id=stream_id) + + +async def _call_method( + store: StreamStore, + operation: str, + request: google.protobuf.message.Message, + request_id: str | None, +) -> google.protobuf.message.Message: + """Translate Store exceptions before Core decides whether to retry.""" + method, _, response_type = _store_operation(operation) + call = getattr(store, method) + try: + if request_id is None: + response = await call(request) + else: + response = await call(request, request_id=request_id) + except StreamError: + raise + except Exception as err: + raise StreamError( + f"The Stream Store '{store.name()}' failed the {operation} call " + f"with {type(err).__name__}: {err}", + reason=StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE, + ) from err + if not isinstance(response, response_type): + raise StreamError( + f"The Stream Store '{store.name()}' answered the {operation} call with " + f"{type(response).__name__}, not with {response_type.__name__}", + reason=StreamErrorReason.STREAM_ERROR_REASON_STORE_CORRUPT, + ) + return response + + +async def _call_store( # pyright: ignore[reportUnusedFunction] + store: StreamStore, + limits: tuple[int, int, int], + codec: PayloadCodec | None, + operation: str, + request: google.protobuf.message.Message, + request_id: str | None, + timeout: timedelta | None = None, +) -> google.protobuf.message.Message: + """Keep client codec and append checks consistent with Workflow calls. + + Records have no serialization context because any client or Workflow can + read them. Each codec call receives one Record body. + """ + store_request = _store_request(request) + if ( + isinstance(store_request, ReadRecordsRequest) + and store_request.HasField("wait") + and timeout is not None + and timeout > timedelta(0) + ): + # A wait is only a bound, and a Store that waits all of it must still answer + # before the timeout fails the read. + longest = timeout - min(_READ_ANSWER_TIME, timeout / 10) + if store_request.wait.ToTimedelta() > longest: + store_request.wait.FromTimedelta(longest) + if isinstance(store_request, AppendRecordsRequest): + if codec: + for appended in store_request.records: + [body] = await codec.encode([appended.body]) + appended.body.CopyFrom(body) + # SDK Core checks an append of Workflow code the same way, so each path refuses + # the same batch before its Store gets it. + temporalio.bridge.streams.check_append( + limits, store_request.SerializeToString() + ) + try: + # A timeout of zero is no timeout, as for an RPC of the client. + async with asyncio.timeout(timeout.total_seconds() if timeout else None): + response = await _call_method(store, operation, store_request, request_id) + except TimeoutError as err: + raise StreamError( + f"The Stream Store '{store.name()}' didn't answer the {operation} call " + "within its rpc_timeout", + reason=StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE, + ) from err + if isinstance(response, ReadRecordsResponse) and not response.last_offset: + assert isinstance(store_request, ReadRecordsRequest) + # Stores may omit the cursor when the page already identifies it. + records = response.records + response.last_offset = ( + records[-1].offset if records else store_request.from_offset + ) + if codec and isinstance(response, ReadRecordsResponse): + for record in response.records: + [body] = await codec.decode([record.body]) + record.body.CopyFrom(body) + if isinstance(response, CreateStreamResponse): + # Each later call of the created Stream goes to this Store, whatever the + # selector picks then. + ref = sdk.StreamRef(id=_request_ref(request).id, store=store.name()) + return sdk.CreateStreamResponse(ref=ref, created=response.created) + return response + + +def _activity_target() -> StorageDriverActivityInfo | None: + if not temporalio.activity.in_activity(): + return None + info = temporalio.activity.info() + return StorageDriverActivityInfo( + id=info.activity_id, + type=info.activity_type, + run_id=info.activity_run_id, + namespace=info.namespace, + ) + + +async def _call_stream_store( # pyright: ignore[reportUnusedFunction] + client: temporalio.client.Client, + input: temporalio.client.StartNexusOperationInput, +) -> temporalio.client.NexusOperationHandle[Any]: + stream_config = client._config["stream_config"] + if stream_config is None: + raise ValueError( + "Client has no stream_config, which every Stream call requires." + ) + data_converter = client.data_converter + converters = ( + data_converter.payload_converter, + data_converter.failure_converter, + ) + request = temporalio.nexus.system._support.model_to_proto(input.arg, *converters) + store = stream_config._store_for( + _request_ref(request), _activity_target(), client.namespace + ) + request_id = None + if isinstance(request, (sdk.CreateStreamRequest, sdk.AppendRecordsRequest)): + request_id = str(input._stream_request_id) + response = await _call_store( + store, + stream_config._limits(), + data_converter.payload_codec, + input.operation, + request, + request_id, + input.rpc_timeout, + ) + result_type: Any = input.result_type + handle: temporalio.client.NexusOperationHandle[Any] = ( + temporalio.client.NexusOperationHandle( + client, + input.id, + result_type=result_type, + endpoint=input.endpoint, + service=input.service, + operation=input.operation, + ) + ) + handle._known_outcome = temporalio.nexus.system._support.model_from_proto( + response, result_type, *converters + ) + return handle + + +class _StoreCaller: # pyright: ignore[reportUnusedClass] + """Keep Store calls on the Python event loop so Core can cancel them.""" + + def __init__(self, store: Callable[[], StreamStore]) -> None: + """Resolve the Store at each call so client replacement takes effect.""" + self._store = store + + async def call( + self, + operation: str, + request: bytes, + request_id: str | None, + on_task: Callable[[asyncio.Task[Any]], None], + ) -> bytes: + """Register the Python task before any Store work can start. + + ``on_task`` raises :py:class:`asyncio.CancelledError` if Core already + dropped the call. + """ + task = asyncio.current_task() + assert task + on_task(task) + _, request_type, _ = _store_operation(operation) + try: + response = await _call_method( + self._store(), operation, request_type.FromString(request), request_id + ) + except StreamError as err: + unavailable = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE + if err.reason == unavailable and err.__cause__: + # Core keeps only the text of the error, so the traceback is logged here. + logger.warning( + "Stream Store failed the %s call", operation, exc_info=err.__cause__ + ) + raise + return response.SerializeToString() diff --git a/temporalio/contrib/streams/README.md b/temporalio/contrib/streams/README.md new file mode 100644 index 0000000000..0f8628d027 --- /dev/null +++ b/temporalio/contrib/streams/README.md @@ -0,0 +1,77 @@ +# Stream helpers + +> This package is experimental. Its API can change. + +`temporalio.contrib.streams` supports the SDK's Stream API. Configure Stores with +`stream_config=StreamConfig(stores=[...])`. Use `create_stream` or `get_stream` +on the client or `temporalio.workflow` to get a `Stream`. + +`temporalio.contrib.workflow_streams` is a separate API that stores events in +Workflow state. + +## `BufferedAppender` + +Use `BufferedAppender` in client or Activity code to combine frequent appends. + +```python +from temporalio.contrib.streams import BufferedAppender + +async with BufferedAppender(stream) as tokens: + async for token in model_tokens(): + tokens.append(token) +``` + +`append` returns immediately. The appender starts a batch within `max_delay` +when no write is active. The default is 100 milliseconds. Writes are sequential. + +`async with` flushes before exit. Without it, call `await tokens.flush()` before +the Activity ends. Otherwise a delayed write can follow a later Activity attempt, +and its error has no caller. + +The buffer has no size limit. Await `flush()` periodically if the producer is +faster than the Store. Set the appender's `max_batch_records` to stay within the +client's batch count limit. The client's byte limits still apply. + +A failed batch stops later writes. Later `append` and `flush` calls raise that +error, or `RuntimeError` if the write was cancelled. `unwritten` counts Records +in the failed batch and the remaining buffer. The Store may have accepted the +failed batch if only its response was lost. + +Workflow code batches values in one Stream `append` call. + +## Store a Producer + +`current_producer()` returns the running Activity attempt's Producer. Use +`as_producer` to restore it from heartbeat details. Pass the restored value as +`append(..., producer=...)` when resumed work must retain that Producer. + +## Read a Stream + +Pass `body_type=` or a typed ref such as `StreamRef[str](id=...)` to `get_stream`. +A ref without a body type raises `TypeError` when read. A Stream from +`create_stream` without a body type accepts any body. + +A Stream has no close. Stop at the application's terminal Record or cancel the +iterator. `read` and `read_pages` continue after empty pages. `read_pages` yields +those pages. `read_page` returns one page and has no default wait. + +With no `wait`, an iterator requests its first page immediately. Later requests +wait up to one minute. An explicit `wait` applies to every page. Zero disables +waiting, so an idle Stream produces repeated empty pages. Client iterators yield +to the event loop between them so cancellation can run. + +A positive `rpc_timeout` caps client and Activity waits below the timeout. An +Activity that heartbeats between Records needs a shorter `wait` than its +heartbeat timeout, or a separate heartbeat task. + +Workflow reads can span Workflow Tasks. `stream_read_time` bounds how long a +read keeps its task open. Each page adds a result to History. Short waits on an +idle Stream can make History grow quickly. Store outages fail the Workflow Task +without returning an error to Workflow code. + +Live Workflow pages default to 256 Records and 4 MiB, with a 16 MiB cap. A live +read fails if a Record exceeds the Worker's `max_record_bytes`. Replay preserves +recorded successes under smaller limits. + +Replay reads Records from the Store again. Retention must cover every replay +and query. Values in Workflow state do not remove this Store dependency. diff --git a/temporalio/contrib/streams/__init__.py b/temporalio/contrib/streams/__init__.py new file mode 100644 index 0000000000..fd05faea41 --- /dev/null +++ b/temporalio/contrib/streams/__init__.py @@ -0,0 +1,15 @@ +"""Helpers on top of the Streams API. + +:py:class:`BufferedAppender` batches the appends of one Stream, in client and +Activity code. :py:func:`current_producer` gives the Producer that a write of +the running Activity sends by default, and :py:func:`as_producer` gives back a +Producer that code stored. + +.. warning:: + This package is experimental and may change in future versions. +""" + +from temporalio.contrib.streams._appender import BufferedAppender +from temporalio.contrib.streams._producer import as_producer, current_producer + +__all__ = ["BufferedAppender", "as_producer", "current_producer"] diff --git a/temporalio/contrib/streams/_appender.py b/temporalio/contrib/streams/_appender.py new file mode 100644 index 0000000000..197c1a65bc --- /dev/null +++ b/temporalio/contrib/streams/_appender.py @@ -0,0 +1,205 @@ +"""A helper that batches the appends of one Stream. + +.. warning:: + This module is experimental and subject to change. +""" + +from __future__ import annotations + +import asyncio +from datetime import timedelta +from types import TracebackType +from typing import Generic, TypeVar + +from typing_extensions import Self + +import temporalio.nexus.system.stream_service.client +import temporalio.workflow + +BodyT = TypeVar("BodyT") + + +class BufferedAppender(Generic[BodyT]): + """A buffer that writes the appends of one Stream in batches. + + Use it in code that appends often, such as an Activity that streams model + tokens. :py:meth:`append` returns immediately and does no I/O. The appender + writes the buffered Records as one batch, at most ``max_delay`` after the + first of them. One write runs at a time, and the Records keep their order. + + Use it in ``async with``, or await :py:meth:`flush` before the code that + appends ends. Otherwise the last Records are written up to ``max_delay`` + later, and nobody gets the error of that write. For an Activity that has + ended, that write can come after a write of the next attempt. + + ``await flush()`` is the backpressure point. The buffer has no bound, so code + that appends faster than the Store takes Records must await it from time to + time. + + After a batch fails, the appender writes nothing more, so a reader sees no + gap. Each later :py:meth:`append` and :py:meth:`flush` raises the error of + that batch, or :exc:`RuntimeError` if the write was cancelled. + + The appender is for client and Activity code. Workflow code passes its + Records to one ``append`` call of its Stream. + + .. warning:: + This API is experimental and subject to change. + """ + + def __init__( + self, + stream: temporalio.nexus.system.stream_service.client.Stream[BodyT], + *, + max_delay: timedelta | None = None, + max_batch_records: int | None = None, + ) -> None: + """Create an appender. It starts no write before the first append. + + Args: + stream: The Stream to append to, from a client or from the client of + an Activity. + max_delay: The longest time that a Record waits in the buffer before + its batch starts to write, while no write runs. ``None`` means + 100 milliseconds. + max_batch_records: The maximum number of Records of one batch. A + buffer with this many Records is written immediately. ``None`` + means no maximum of the appender, and a batch over a limit of + the client's ``StreamConfig`` then fails. + + Raises: + RuntimeError: The appender is created in Workflow code. + ValueError: ``max_batch_records`` is below 1. + """ + if temporalio.workflow.in_workflow(): + raise RuntimeError( + "BufferedAppender is for client and Activity code. In Workflow code, " + "pass the Records to one append call." + ) + if max_batch_records is not None and max_batch_records < 1: + raise ValueError("max_batch_records must be 1 or more") + self._stream = stream + self._max_delay = ( + timedelta(milliseconds=100) if max_delay is None else max_delay + ) + self._max_batch_records = max_batch_records + self._buffer: list[BodyT] = [] + self._first_at = 0.0 + self._timer: asyncio.TimerHandle | None = None + self._writing: asyncio.Task[None] | None = None + self._appended = 0 + # Failed batches also settle buffered Records, so flush cannot wait forever. + self._settled = 0 + self._error: Exception | None = None + self._last_offset: bytes | None = None + self._unwritten = 0 + + def append(self, *records: BodyT) -> None: + """Add one Record for each value to the buffer, and return immediately. + + Raises: + temporalio.exceptions.StreamError: A batch failed, so the appender + takes no more Records. + RuntimeError: The write of a batch was cancelled. + """ + if self._error: + raise self._error + if not self._buffer: + self._first_at = asyncio.get_running_loop().time() + self._buffer.extend(records) + self._appended += len(records) + self._schedule() + + async def flush(self) -> bytes | None: + """Write every Record that was appended before the call. + + Returns: + The offset of the last written Record, or ``None`` if the appender + has written nothing. + + Raises: + temporalio.exceptions.StreamError: A batch failed. + RuntimeError: The write of a batch was cancelled before the call. + """ + target = self._appended + while self._settled < target: + if not self._writing: + self._start() + assert self._writing + # A write is one batch at the Store, so a cancel of the caller doesn't stop it. + await asyncio.shield(self._writing) + if self._error: + raise self._error + return self._last_offset + + @property + def unwritten(self) -> int: + """Number of Records of the failed batch and of the buffer behind it. + + The appender wrote none of the buffer. The Store may still have taken the + failed batch, if only its answer was lost. + """ + return self._unwritten + + async def __aenter__(self) -> Self: + """Use the appender in ``async with``.""" + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + """Write the buffered Records. An error of the block wins over a write error.""" + try: + await self.flush() + except asyncio.CancelledError: + if exc is None or self._error is None: + raise + except Exception: + if exc is None: + raise + + def _schedule(self) -> None: + if self._writing or not self._buffer: + return + if self._max_batch_records and len(self._buffer) >= self._max_batch_records: + self._start() + elif not self._timer: + self._timer = asyncio.get_running_loop().call_at( + self._first_at + self._max_delay.total_seconds(), self._start + ) + + def _start(self) -> None: + if self._timer: + self._timer.cancel() + self._timer = None + batch = self._buffer[: self._max_batch_records] + del self._buffer[: self._max_batch_records] + self._writing = asyncio.get_running_loop().create_task(self._write(batch)) + + async def _write(self, batch: list[BodyT]) -> None: + try: + # An eager task factory must let append return before the Store call starts. + await asyncio.sleep(0) + response = await self._stream.append(*batch) + self._last_offset = response.last_offset + except BaseException as err: + # Later batches must not create a gap after this failed batch. + self._unwritten = len(batch) + len(self._buffer) + self._settled += len(self._buffer) + self._buffer.clear() + if isinstance(err, Exception): + self._error = err + else: + # Nobody cancelled a later caller, so it gets no `CancelledError`. + self._error = RuntimeError( + "The write of a batch was cancelled, so the appender takes no " + "more Records." + ) + raise + finally: + self._settled += len(batch) + self._writing = None + self._schedule() diff --git a/temporalio/contrib/streams/_producer.py b/temporalio/contrib/streams/_producer.py new file mode 100644 index 0000000000..c8d89c0c9c --- /dev/null +++ b/temporalio/contrib/streams/_producer.py @@ -0,0 +1,57 @@ +"""The Producer of a Stream write. + +.. warning:: + This module is experimental and subject to change. +""" + +from __future__ import annotations + +import temporalio.activity +import temporalio.api.stream.v1 +import temporalio.converter +from temporalio.nexus.system import _support +from temporalio.nexus.system.stream_service import Producer + + +def current_producer() -> Producer: + """Return the Producer of the running attempt of an Activity. + + An append of that attempt sends it by default. Code that stores + it, such as in heartbeat details, gets it back from :py:func:`as_producer`. + + The Producer of an Activity of a Workflow has the Activity id and the id of + its ``ActivityTaskScheduled`` event. So a later Activity of the run that uses + the same Activity id is a separate Producer. A Local Activity whose retry + waits longer than its ``local_retry_threshold`` runs under a new sequence + number, and then writes as a new Producer unless the Workflow set + ``activity_id``. + + Raises: + RuntimeError: The caller isn't an Activity. + + .. warning:: + This API is experimental and subject to change. + """ + return _support.activity_producer(temporalio.activity.info()) + + +def as_producer(value: object) -> Producer: + """Return the Producer that code stored, such as in heartbeat details. + + The default data converter gives a stored Producer back as its proto + message, since such a value has no type hint. + + Raises: + TypeError: ``value`` is neither a Producer nor its proto message. + + .. warning:: + This API is experimental and subject to change. + """ + if isinstance(value, Producer): + return value + if not isinstance(value, temporalio.api.stream.v1.Producer): + raise TypeError(f"Expected a Producer, got {type(value).__name__}") + converter = temporalio.converter.DataConverter.default + return _support.model_from_proto( + value, Producer, converter.payload_converter, converter.failure_converter + ) diff --git a/temporalio/converter/_payload_converter.py b/temporalio/converter/_payload_converter.py index ff7d477cc2..424e0ee8ec 100644 --- a/temporalio/converter/_payload_converter.py +++ b/temporalio/converter/_payload_converter.py @@ -584,6 +584,26 @@ def from_payload( raise RuntimeError("Failed parsing") from err +# Restrict new decoding rules to new types to preserve existing Workflow histories. +_typed_decode_types: set[type] = set() + + +def _is_typed_decode_type(hint: Any) -> bool: + origin = typing.get_origin(hint) or hint + return any(origin is typed for typed in _typed_decode_types) + + +def _non_none_arg(hint: Any) -> Any: + origin = typing.get_origin(hint) + if origin is typing.Union or origin is UnionType: # type:ignore[reportDeprecated] + args = typing.get_args(hint) + if len(args) == 2 and type(None) in args: + arg = args[0] if args[1] is type(None) else args[1] + if _is_typed_decode_type(arg): + return arg + return hint + + class _TemporalTransferTypePayloadConverter(PayloadConverter, WithSerializationContext): """Payload converter wrapper for registered Temporal transfer type converters. @@ -591,7 +611,9 @@ class _TemporalTransferTypePayloadConverter(PayloadConverter, WithSerializationC transfer type value, then encoded by the wrapped payload converter. When decoding to a type with a registered transfer type converter, the wrapped converter first decodes the payload to the transfer type value and this wrapper - constructs the requested user-facing type from it. + constructs the requested user-facing type from it. For a type of + ``_typed_decode_types``, a hint of the type or ``None`` decodes the same way, and a + null payload gives ``None``. """ _inner_payload_converter: PayloadConverter @@ -627,21 +649,33 @@ def from_payloads( """See base class.""" if type_hints is None: return self._inner_payload_converter.from_payloads(payloads, None) + value_hints = [_non_none_arg(type_hint) for type_hint in type_hints] converters = [ - _get_transfer_type_converter(type_hint) for type_hint in type_hints - ] - inner_type_hints = [ - converter.transfer_type if converter is not None else type_hint - for converter, type_hint in zip(converters, type_hints) + _get_transfer_type_converter(value_hint) for value_hint in value_hints ] + inner_type_hints: list[Any] = [] + for converter, value_hint, type_hint in zip( + converters, value_hints, type_hints + ): + if converter is None: + inner_type_hints.append(type_hint) + elif value_hint is type_hint or converter.transfer_type is None: + inner_type_hints.append(converter.transfer_type) + else: + # A transfer type can be a value with no `|`, such as a string. + inner_type_hints.append( + typing.Optional[converter.transfer_type] # type:ignore[reportDeprecated] + ) values = self._inner_payload_converter.from_payloads( payloads, typing.cast("list[type]", inner_type_hints) ) return [ - converter.from_transfer_type(value, type_hint) - if converter is not None - else value - for value, converter, type_hint in zip(values, converters, type_hints) + value + if converter is None or (value is None and value_hint is not type_hint) + else converter.from_transfer_type(value, value_hint) + for value, converter, value_hint, type_hint in zip( + values, converters, value_hints, type_hints + ) ] def with_context(self, context: SerializationContext) -> Self: @@ -822,6 +856,18 @@ def _get_iso_datetime_parser() -> Callable[[str], datetime]: return datetime.fromisoformat +def _with_type_args(hint: Any, type_var_args: Mapping[Any, Any]) -> Any: + if not type_var_args: + return hint + if isinstance(hint, TypeVar): + return type_var_args.get(hint, hint) + # Only an alias takes arguments. A bare generic class keeps its own variables. + parameters = getattr(hint, "__parameters__", ()) + if parameters and typing.get_origin(hint) is not None: + return hint[tuple(type_var_args.get(param, param) for param in parameters)] + return hint + + def value_to_type( hint: type, value: Any, @@ -993,8 +1039,14 @@ def value_to_type( ret_dict = hint(**ret_dict) return ret_dict - # Dataclass - if dataclasses.is_dataclass(hint): + dataclass_type: Any = hint + type_var_args: dict[Any, Any] = {} + alias_origin = typing.get_origin(hint) + if _is_typed_decode_type(alias_origin) and dataclasses.is_dataclass(alias_origin): + dataclass_type = alias_origin + parameters = getattr(alias_origin, "__parameters__", ()) + type_var_args = dict(zip(parameters, type_args)) + if dataclasses.is_dataclass(dataclass_type): if not isinstance(value, dict): raise TypeError( f"Cannot convert to dataclass {hint}, value is {type(value)} not dict" @@ -1002,8 +1054,8 @@ def value_to_type( # Obtain dataclass fields and check that all dict fields are there and # that no required fields are missing. Unknown fields are silently # ignored. - fields = dataclasses.fields(hint) - field_hints = get_type_hints(hint) + fields = dataclasses.fields(dataclass_type) + field_hints = get_type_hints(dataclass_type) field_values = {} non_init_field_values = {} for field in fields: @@ -1016,7 +1068,9 @@ def value_to_type( # rejects this dataclass when trying union members try: converted = value_to_type( - field_hints[field.name], field_value, custom_converters + _with_type_args(field_hints[field.name], type_var_args), + field_value, + custom_converters, ) except Exception as err: raise TypeError( @@ -1029,6 +1083,7 @@ def value_to_type( # Simply instantiate the dataclass. This will fail as expected when # missing required fields. # TODO(cretz): Want way to convert snake case to camel case? + # The alias retains type arguments that its dataclass origin would lose. obj = hint(**field_values) # init=False fields cannot be passed to __init__ but are serialized, so # restore them afterwards. object.__setattr__ also works on frozen diff --git a/temporalio/exceptions.py b/temporalio/exceptions.py index 03a623c21e..5bec57528c 100644 --- a/temporalio/exceptions.py +++ b/temporalio/exceptions.py @@ -1,6 +1,7 @@ """Common Temporal exceptions.""" import asyncio +import functools from collections.abc import Sequence from datetime import timedelta from enum import IntEnum @@ -8,6 +9,7 @@ import temporalio.api.enums.v1 import temporalio.api.failure.v1 +import temporalio.api.stream.v1 class TemporalError(Exception): @@ -474,6 +476,48 @@ def operation_token(self) -> str: return self._operation_token +class StreamError(ApplicationError): + """Error raised when a Stream call fails. + + Client, Activity and Workflow code all get this class for a failed Stream + call, with no other error around it, and :py:attr:`reason` says why the call + failed. A call that fails with ``STREAM_ERROR_REASON_STORE_UNAVAILABLE`` may + succeed on another try, so it's the only reason that isn't ``non_retryable``. + + .. warning:: + This API is experimental and subject to change. + """ + + def __init__( + self, + message: str, + *, + reason: temporalio.api.enums.v1.StreamErrorReason.ValueType, + ) -> None: + """Initialize a Stream error.""" + reasons = temporalio.api.enums.v1.StreamErrorReason + super().__init__( + message, + temporalio.api.stream.v1.StreamErrorDetails(reason=reason), + # The form of the type in a failure that Core builds + type="stream_" + + reasons.Name(reason).removeprefix("STREAM_ERROR_REASON_").lower(), + non_retryable=reason != reasons.STREAM_ERROR_REASON_STORE_UNAVAILABLE, + ) + self._reason = reason + + @property + def reason(self) -> temporalio.api.enums.v1.StreamErrorReason.ValueType: + """Why the Stream call failed.""" + return self._reason + + def __reduce__(self) -> Any: + """Return the parts that ``copy`` and ``pickle`` build the error from.""" + # The default calls the class with `args` alone, which has no reason. + _, *rest = tuple(super().__reduce__()) + return functools.partial(type(self), reason=self._reason), *rest + + def is_cancelled_exception(exception: BaseException) -> bool: """Check whether the given exception is considered a cancellation exception according to Temporal. diff --git a/temporalio/nexus/system/__init__.py b/temporalio/nexus/system/__init__.py index da102bd304..e2e2086a56 100644 --- a/temporalio/nexus/system/__init__.py +++ b/temporalio/nexus/system/__init__.py @@ -20,6 +20,7 @@ from temporalio.converter import BinaryProtoPayloadConverter, CompositePayloadConverter from temporalio.converter._payload_converter import ( _TemporalTransferTypePayloadConverter, + _typed_decode_types, ) TEMPORAL_SYSTEM_ENDPOINT = "__temporal_system" @@ -198,3 +199,8 @@ def _get_serialization_context( # pyright: ignore[reportUnusedFunction] # `temporalio.workflow` and the generated Workflow modules of a system service import each # other. It's loaded here last, so that any of those modules can be the first import. import temporalio.workflow # noqa: E402 # pyright: ignore[reportUnusedImport] +from temporalio.nexus.system.stream_service.models import StreamRef # noqa: E402 + +# Workflow code can decode a `StreamRef` only on an SDK with this rule, so the rule can't +# change a replay. Any import of the generated class runs this module first. +_typed_decode_types.add(StreamRef) diff --git a/temporalio/testing/__init__.py b/temporalio/testing/__init__.py index 0cd652d86b..5574a0a39b 100644 --- a/temporalio/testing/__init__.py +++ b/temporalio/testing/__init__.py @@ -1,11 +1,13 @@ """Test framework for workflows and activities.""" from ._activity import ActivityEnvironment +from ._stream_store import MemoryStreamStore from ._timeskipping import TimeSkipper, TimeSkippingConfig from ._workflow import WorkflowEnvironment __all__ = [ "ActivityEnvironment", + "MemoryStreamStore", "TimeSkipper", "WorkflowEnvironment", "TimeSkippingConfig", diff --git a/temporalio/testing/_activity.py b/temporalio/testing/_activity.py index 6f0a9ab5d5..63fb08c588 100644 --- a/temporalio/testing/_activity.py +++ b/temporalio/testing/_activity.py @@ -67,7 +67,7 @@ def default_info() -> temporalio.activity.Info: Returns a new default Info instance that can be modified using :py:func:`dataclasses.replace` before assigning to the info attribute. """ - utc_zero = datetime.fromtimestamp(0).replace(tzinfo=timezone.utc) + utc_zero = datetime.fromtimestamp(0, tz=timezone.utc) return temporalio.activity.Info( activity_id="test", activity_type="unknown", diff --git a/temporalio/testing/_stream_store.py b/temporalio/testing/_stream_store.py new file mode 100644 index 0000000000..6a42282d92 --- /dev/null +++ b/temporalio/testing/_stream_store.py @@ -0,0 +1,362 @@ +"""Stream Store that keeps its Streams in memory.""" + +from __future__ import annotations + +import asyncio +import bisect +import collections +from dataclasses import dataclass, field +from datetime import timedelta + +import google.protobuf.message + +import temporalio.bridge.streams +import temporalio.runtime +from temporalio.api.enums.v1 import StreamErrorReason, StreamIdConflictPolicy +from temporalio.api.stream.v1 import ( + ActivityAttempt, + LocalActivityAttempt, + Producer, + StreamRecord, + WorkflowTaskAttempt, +) +from temporalio.api.streamservice.v1 import ( + AppendRecordsRequest, + AppendRecordsResponse, + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, +) +from temporalio.client._stream_store import StreamStore, _StoreCaller +from temporalio.exceptions import StreamError + +_Attempt = tuple[int, ...] + + +class MemoryStreamStore(StreamStore): + """Stream Store that keeps its Streams in the memory of this process. + + It's for tests and local runs. A client and a Worker see the same Streams + only through the same instance, in one event loop. + + The Store runs the checks of SDK Core on each request and on each response, + also for a call of client or Activity code. So a call fails on it as it fails + on a Store package that runs those checks. The Store has no limit of a batch, + since the limits are those of the + :py:class:`temporalio.client.StreamConfig` of the caller. + + .. warning:: + This API is experimental and subject to change. + """ + + def __init__( + self, + *, + name: str = "memory", + retention: timedelta | None = None, + resend_window: int | None = None, + fence: bool = False, + runtime: temporalio.runtime.Runtime | None = None, + ) -> None: + """Create a memory Store. + + Args: + name: The name of the Store in a + :py:class:`temporalio.client.StreamConfig`. + retention: How long after its create, or after its last append that + wrote a batch, a Stream expires. Defaults to 7 days. A resend and + a create of a Stream that exists don't start it again. + resend_window: The number of recent batches of each Producer of a + Stream whose request ids the Store remembers, so that it writes + a resend of one of them only once. Defaults to 16, and must be + at least 1, since a Store remembers the last batch of a Producer. + fence: Whether the Store fences. If true, an append of an attempt + fails with ``STREAM_ERROR_REASON_FENCED`` once a later attempt of + its Producer has written to the Stream. + runtime: The runtime whose threads run the checks of SDK Core. + Defaults to :py:meth:`temporalio.runtime.Runtime.default`. + """ + if resend_window is not None and resend_window < 1: + raise ValueError("resend_window must be greater than zero.") + self._name = name + self._runtime = runtime + streams = _MemoryStreams( + name, + retention=timedelta(days=7) if retention is None else retention, + resend_window=16 if resend_window is None else resend_window, + fence=fence, + ) + self._caller = _StoreCaller(lambda: streams) + + def name(self) -> str: + """See base class.""" + return self._name + + async def create_stream( + self, request: CreateStreamRequest, *, request_id: str + ) -> CreateStreamResponse: + """See base class.""" + return CreateStreamResponse.FromString( + await self._call("CreateStream", request, request_id) + ) + + async def append_records( + self, request: AppendRecordsRequest, *, request_id: str + ) -> AppendRecordsResponse: + """See base class.""" + return AppendRecordsResponse.FromString( + await self._call("AppendRecords", request, request_id) + ) + + async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: + """See base class.""" + return ReadRecordsResponse.FromString(await self._call("ReadRecords", request)) + + async def describe_stream( + self, request: DescribeStreamRequest + ) -> DescribeStreamResponse: + """See base class.""" + return DescribeStreamResponse.FromString( + await self._call("DescribeStream", request) + ) + + async def _call( + self, + operation: str, + request: google.protobuf.message.Message, + request_id: str | None = None, + ) -> bytes: + runtime = self._runtime or temporalio.runtime.Runtime.default() + return await temporalio.bridge.streams.call_stream_store( + runtime._core_runtime, + self._caller, + operation, + request.SerializeToString(), + request_id, + ) + + +@dataclass +class _Batch: + attempt: _Attempt + request_id: str + response: AppendRecordsResponse + + +@dataclass +class _Writer: + """What a Stream keeps of one of its Producers.""" + + window: collections.deque[_Batch] + """The last batches that the Producer wrote, oldest first.""" + + newest: _Attempt = () + """The latest attempt of the Producer that wrote.""" + + +@dataclass +class _Stream: + request_id: str + """The request id of the create that made the Stream.""" + + expires_at: float + """The time of the event loop at which the Stream expires.""" + + records: list[StreamRecord] = field(default_factory=list) + writers: dict[bytes, _Writer] = field(default_factory=dict) + changed: asyncio.Event = field(default_factory=asyncio.Event) + """Set at the next append that writes, which then puts a new event here.""" + + @property + def last_offset(self) -> bytes: + return self.records[-1].offset if self.records else b"" + + +class _MemoryStreams(StreamStore): + """The Streams of a :py:class:`MemoryStreamStore`, which checks no request.""" + + def __init__( + self, + name: str, + *, + retention: timedelta, + resend_window: int, + fence: bool, + ) -> None: + self._name = name + self._retention = retention + self._resend_window = resend_window + self._fence = fence + self._streams: dict[str, _Stream] = {} + + def name(self) -> str: + return self._name + + async def create_stream( + self, request: CreateStreamRequest, *, request_id: str + ) -> CreateStreamResponse: + stream_id = request.stream_id + if stream_id not in self._streams: + self._streams[stream_id] = _Stream(request_id, self._expiry()) + return CreateStreamResponse(created=True) + stream = self._stream(stream_id) + # An empty request id identifies no create, so it never matches. + if request_id and request_id == stream.request_id: + return CreateStreamResponse(created=True) + use_existing = StreamIdConflictPolicy.STREAM_ID_CONFLICT_POLICY_USE_EXISTING + if request.id_conflict_policy == use_existing: + return CreateStreamResponse(created=False) + raise StreamError( + f"The Stream '{stream_id}' already exists", + reason=StreamErrorReason.STREAM_ERROR_REASON_ALREADY_EXISTS, + ) + + async def append_records( + self, request: AppendRecordsRequest, *, request_id: str + ) -> AppendRecordsResponse: + stream = self._stream(request.stream_id) + key, attempt = _producer_key(request.producer), _attempt(request.producer) + writer = stream.writers.get(key) + if writer is None: + writer = _Writer(collections.deque(maxlen=self._resend_window)) + if request_id: + for batch in writer.window: + if (batch.attempt, batch.request_id) == (attempt, request_id): + return batch.response + if self._fence and attempt < writer.newest: + raise _fenced(request.stream_id) + first = len(stream.records) + 1 + stream.records.extend( + StreamRecord( + producer=request.producer, + body=record.body, + offset=(first + at).to_bytes(8, "big"), + ) + for at, record in enumerate(request.records) + ) + response = AppendRecordsResponse( + first_offset=first.to_bytes(8, "big"), last_offset=stream.last_offset + ) + writer.newest = attempt + writer.window.append(_Batch(attempt, request_id, response)) + stream.writers[key] = writer + stream.expires_at = self._expiry() + self._notify(stream) + return response + + async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: + stream = self._stream(request.stream_id) + if request.from_offset > stream.last_offset: + raise StreamError( + f"The from_offset of the read is past the newest offset of the " + f"Stream '{request.stream_id}'", + reason=StreamErrorReason.STREAM_ERROR_REASON_OFFSET_TOO_HIGH, + ) + start = bisect.bisect_right( + stream.records, request.from_offset, key=lambda record: record.offset + ) + wait = request.wait.ToTimedelta().total_seconds() + until = self._now() + wait + while start == len(stream.records) and self._now() < until: + try: + async with asyncio.timeout_at(min(until, stream.expires_at)): + await stream.changed.wait() + except TimeoutError: + pass + self._stream(request.stream_id) + end = len(stream.records) + if request.max_records > 0: + end = min(end, start + request.max_records) + records = stream.records[start:end] + return ReadRecordsResponse( + records=records, + last_offset=records[-1].offset if records else request.from_offset, + ) + + async def describe_stream( + self, request: DescribeStreamRequest + ) -> DescribeStreamResponse: + stream = self._stream(request.stream_id) + return DescribeStreamResponse(last_offset=stream.last_offset) + + def _stream(self, stream_id: str) -> _Stream: + stream = self._streams.get(stream_id) + if stream is None: + raise StreamError( + f"The Stream '{stream_id}' doesn't exist", + reason=StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND, + ) + if self._now() >= stream.expires_at: + raise StreamError( + f"The Stream '{stream_id}' expired", + reason=StreamErrorReason.STREAM_ERROR_REASON_EXPIRED, + ) + return stream + + def _now(self) -> float: + return asyncio.get_running_loop().time() + + def _expiry(self) -> float: + return self._now() + self._retention.total_seconds() + + def _notify(self, stream: _Stream) -> None: + stream.changed.set() + stream.changed = asyncio.Event() + + +def _fenced(stream_id: str) -> StreamError: + return StreamError( + f"A later attempt of the Producer has written to the Stream '{stream_id}'", + reason=StreamErrorReason.STREAM_ERROR_REASON_FENCED, + ) + + +def _kind(producer: Producer) -> google.protobuf.message.Message: + name = producer.WhichOneof("kind") + assert name, "SDK Core refuses a Producer with no kind" + return getattr(producer, name) + + +def _producer_key(producer: Producer) -> bytes: + """Return what identifies a Producer, which is its kind with the ids of that + kind and without its attempt. + """ + key = Producer() + key.CopyFrom(producer) + kind = _kind(key) + if "attempt" in kind.DESCRIPTOR.fields_by_name: + kind.ClearField("attempt") + return key.SerializeToString(deterministic=True) + + +def _attempt(producer: Producer) -> _Attempt: + """Return a value that orders the attempts of one Producer, as the attempt key + of SDK Core does. + + Two attempts compare by the Workflow Task first (its started event id, its + attempt number, its started time), and then by the Activity attempt (its + scheduled time, its attempt number). A field that the kind of the Producer + doesn't have, or that is negative, is zero. So every write of a client has + the same attempt. + """ + attempt = getattr(_kind(producer), "attempt", None) + task, scheduled, number = WorkflowTaskAttempt(), ActivityAttempt(), 0 + if isinstance(attempt, WorkflowTaskAttempt): + task = attempt + elif isinstance(attempt, LocalActivityAttempt): + task, number = attempt.task, attempt.attempt + elif isinstance(attempt, ActivityAttempt): + scheduled, number = attempt, attempt.attempt + fields = ( + task.started_event_id, + task.attempt, + task.started_time.seconds, + task.started_time.nanos, + scheduled.attempt_scheduled_time.seconds, + scheduled.attempt_scheduled_time.nanos, + number, + ) + return tuple(max(0, value) for value in fields) diff --git a/temporalio/testing/_workflow.py b/temporalio/testing/_workflow.py index 6c8354162c..54add4e363 100644 --- a/temporalio/testing/_workflow.py +++ b/temporalio/testing/_workflow.py @@ -102,6 +102,7 @@ async def start_local( dev_server_download_ttl: timedelta | None = None, dev_server_startup_timeout: timedelta | None = None, ui_port: int | None = None, + stream_config: temporalio.client.StreamConfig | None = None, ) -> WorkflowEnvironment: """Start a full Temporal server locally, downloading if necessary. @@ -165,6 +166,8 @@ async def start_local( become ready after spawning. Defaults to 5 seconds and does not include download time. ui_port: UI port to use if UI is enabled. + stream_config: See parameter of the same name on + :py:meth:`temporalio.client.Client.connect`. Returns: The started CLI dev server workflow environment. @@ -194,6 +197,7 @@ async def start_local( dev_server_download_ttl=dev_server_download_ttl, dev_server_startup_timeout=dev_server_startup_timeout, ui_port=ui_port, + stream_config=stream_config, ) @classmethod @@ -216,6 +220,7 @@ async def start_time_skipping( test_server_extra_args: Sequence[str] = [], test_server_download_ttl: timedelta | None = None, test_server_startup_timeout: timedelta | None = None, + stream_config: temporalio.client.StreamConfig | None = None, ) -> WorkflowEnvironment: """Start a V1 time skipping workflow environment. @@ -276,6 +281,8 @@ async def start_time_skipping( test_server_startup_timeout: Maximum time to wait for the test server to become ready after spawning. Defaults to 5 seconds and does not include download time. + stream_config: See parameter of the same name on + :py:meth:`temporalio.client.Client.connect`. Returns: The started workflow environment with time skipping. @@ -296,6 +303,7 @@ async def start_time_skipping( test_server_extra_args=test_server_extra_args, test_server_download_ttl=test_server_download_ttl, test_server_startup_timeout=test_server_startup_timeout, + stream_config=stream_config, ) @classmethod @@ -582,6 +590,7 @@ async def _bootstrap_dev_server( dev_server_download_ttl: timedelta | None = None, dev_server_startup_timeout: timedelta | None = None, ui_port: int | None = None, + stream_config: temporalio.client.StreamConfig | None = None, ) -> tuple[ temporalio.bridge.testing.EphemeralServer, temporalio.client.Client, @@ -649,6 +658,7 @@ async def _bootstrap_dev_server( rpc_metadata=rpc_metadata, identity=identity, runtime=runtime, + stream_config=stream_config, ) except: try: @@ -719,6 +729,7 @@ async def _create( test_server_extra_args: Sequence[str], test_server_download_ttl: timedelta | None, test_server_startup_timeout: timedelta | None, + stream_config: temporalio.client.StreamConfig | None, ) -> _V1WorkflowEnvironment: runtime = runtime or temporalio.runtime.Runtime.default() download_ttl_ms = None @@ -753,6 +764,7 @@ async def _create( rpc_metadata=rpc_metadata, identity=identity, runtime=runtime, + stream_config=stream_config, ) except: try: diff --git a/temporalio/worker/_activity.py b/temporalio/worker/_activity.py index 7c95449df8..b3af7d45e9 100644 --- a/temporalio/worker/_activity.py +++ b/temporalio/worker/_activity.py @@ -709,6 +709,7 @@ async def _execute_activity( ) if start.HasField("workflow_task") else None, + _scheduled_event_id=start.scheduled_event_id, ) if self._encode_headers: diff --git a/temporalio/worker/_command_aware_visitor.py b/temporalio/worker/_command_aware_visitor.py index 888c06f298..68f4459011 100644 --- a/temporalio/worker/_command_aware_visitor.py +++ b/temporalio/worker/_command_aware_visitor.py @@ -1,10 +1,11 @@ """Visitor that sets command context during payload traversal.""" import contextvars -from collections.abc import Iterator +from collections.abc import Iterable, Iterator from contextlib import contextmanager from dataclasses import dataclass +from temporalio.api.common.v1.message_pb2 import Payload from temporalio.api.enums.v1.command_type_pb2 import CommandType from temporalio.bridge._visitor import PayloadVisitor from temporalio.bridge._visitor_functions import VisitorFunctions @@ -16,8 +17,11 @@ ResolveNexusOperationStart, ResolveRequestCancelExternalWorkflow, ResolveSignalExternalWorkflow, + ResolveStreamAppend, + ResolveStreamRead, ) from temporalio.bridge.proto.workflow_commands.workflow_commands_pb2 import ( + AppendToStream, CompleteWorkflowExecution, FailWorkflowExecution, ScheduleActivity, @@ -211,6 +215,47 @@ async def _visit_coresdk_workflow_activation_ResolveNexusOperation( fs, o ) + # Stream commands and activation jobs. Core builds the failure of a Stream job with no + # codec, so nothing visits it. + async def _visit_coresdk_workflow_commands_AppendToStream( + self, fs: VisitorFunctions, o: AppendToStream + ) -> None: + await self._visit_stream_payloads(fs, o.seq, o.bodies) + + async def _visit_coresdk_workflow_activation_ResolveStreamRead( + self, fs: VisitorFunctions, o: ResolveStreamRead + ) -> None: + await self._visit_stream_payloads( + fs, o.seq, [record.body for record in o.page.records] + ) + + async def _visit_coresdk_workflow_activation_ResolveStreamAppend( + self, fs: VisitorFunctions, o: ResolveStreamAppend + ) -> None: + pass + + async def _visit_stream_payloads( + self, fs: VisitorFunctions, seq: int, payloads: Iterable[Payload] + ) -> None: + # A Record can come from any writer, so its body isn't trusted to be a system Nexus + # envelope, and a codec gets each body alone as it does in client code. + with current_command(CommandType.COMMAND_TYPE_UNSPECIFIED, seq): + for payload in payloads: + await fs.visit_payload(payload) + + +class StoragePayloadVisitor(CommandAwarePayloadVisitor): + """Payload visitor for the passes of external storage and of its references. + + These passes skip the payloads of a Stream. A Stream body is a value of its + writer, which can look like a reference to the storage of this Worker. + """ + + async def _visit_stream_payloads( + self, fs: VisitorFunctions, seq: int, payloads: Iterable[Payload] + ) -> None: + pass + @contextmanager def current_command( @@ -220,6 +265,8 @@ def current_command( update_protocol_instance_id: str | None = None, ) -> Iterator[None]: """Context manager for setting command info.""" + # `COMMAND_TYPE_UNSPECIFIED` marks the body of a Stream Record, which gets no + # serialization context. No other command may use that type. token = current_command_info.set( CommandInfo( command_type=command_type, diff --git a/temporalio/worker/_interceptor.py b/temporalio/worker/_interceptor.py index 09d49884db..f164103a09 100644 --- a/temporalio/worker/_interceptor.py +++ b/temporalio/worker/_interceptor.py @@ -21,6 +21,9 @@ import temporalio.nexus import temporalio.nexus._util import temporalio.workflow +from temporalio.nexus.system.stream_service.workflow._system_nexus_interceptor import ( + _SystemNexusWorkflowOutboundInterceptorBase as _StreamOutboundInterceptorBase, +) from temporalio.nexus.system.workflow_service._system_nexus_interceptor import ( _SystemNexusWorkflowOutboundInterceptorBase, ) @@ -455,7 +458,9 @@ async def handle_update_handler(self, input: HandleUpdateInput) -> Any: return await self.next.handle_update_handler(input) -class WorkflowOutboundInterceptor(_SystemNexusWorkflowOutboundInterceptorBase): +class WorkflowOutboundInterceptor( + _SystemNexusWorkflowOutboundInterceptorBase, _StreamOutboundInterceptorBase +): """Outbound interceptor to wrap calls made from within workflows. This should be extended by any workflow outbound interceptors. @@ -472,9 +477,7 @@ def __init__(self, next: WorkflowOutboundInterceptor) -> None: """ self.next = next - def _next_system_nexus_interceptor( - self, - ) -> _SystemNexusWorkflowOutboundInterceptorBase: + def _next_system_nexus_interceptor(self) -> WorkflowOutboundInterceptor: return self.next def continue_as_new(self, input: ContinueAsNewInput) -> NoReturn: diff --git a/temporalio/worker/_replayer.py b/temporalio/worker/_replayer.py index 1542b3e0f2..8f122f0e1b 100644 --- a/temporalio/worker/_replayer.py +++ b/temporalio/worker/_replayer.py @@ -5,8 +5,8 @@ import asyncio import concurrent.futures import logging -from collections.abc import AsyncIterator, Mapping, Sequence -from contextlib import AbstractAsyncContextManager, asynccontextmanager +from collections.abc import AsyncGenerator, AsyncIterator, Mapping, Sequence +from contextlib import AbstractAsyncContextManager, aclosing, asynccontextmanager from dataclasses import dataclass from typing_extensions import TypedDict @@ -32,6 +32,7 @@ UnsandboxedWorkflowRunner, WorkflowRunner, ) +from ._workflow_streams import _bridge_streams from .workflow_sandbox import SandboxedWorkflowRunner logger = logging.getLogger(__name__) @@ -58,6 +59,7 @@ def __init__( runtime: temporalio.runtime.Runtime | None = None, disable_safe_workflow_eviction: bool = False, header_codec_behavior: HeaderCodecBehavior = HeaderCodecBehavior.NO_CODEC, + stream_config: temporalio.client.StreamConfig | None = None, ) -> None: """Create a replayer to replay workflows from history. @@ -70,6 +72,13 @@ def __init__( will default to a new thread pool executor with no max_workers set that will be shared across all replay calls and never explicitly shut down. Users are encouraged to provide their own if needing more control. + + ``stream_config`` must preserve the Worker's Store names and selector + choices because replay selects the Store of each call again. Append, + create and describe use recorded results without calling the Store. + A :py:class:`temporalio.testing.MemoryStreamStore` with the same name can + serve those operations during replay. Reads fetch Records from the Store + again and fail if the recorded Records are unavailable or changed. """ self._config = ReplayerConfig( workflows=list(workflows), @@ -88,6 +97,7 @@ def __init__( runtime=runtime, disable_safe_workflow_eviction=disable_safe_workflow_eviction, header_codec_behavior=header_codec_behavior, + stream_config=stream_config, ) self._initial_config = self._config.copy() self._default_workflow_logic_flags = set(_DEFAULT_ENABLED_WORKFLOW_LOGIC_FLAGS) @@ -143,7 +153,10 @@ async def replay_workflow( async def history_iterator(): yield history - async with self.workflow_replay_iterator(history_iterator()) as replay_iterator: + async with ( + aclosing(history_iterator()) as histories, + self.workflow_replay_iterator(histories) as replay_iterator, + ): async for result in replay_iterator: if raise_on_replay_failure and result.replay_failure: raise result.replay_failure @@ -253,6 +266,7 @@ def on_eviction_hook( self._config.get("data_converter") or temporalio.converter.DataConverter.default ) + stream_config = self._config.get("stream_config") workflow_worker = _WorkflowWorker( bridge_worker=lambda: bridge_worker, namespace=self._config.get("namespace", "ReplayNamespace"), @@ -281,6 +295,7 @@ def on_eviction_hook( ), should_enforce_versioning_behavior=False, assert_local_activity_valid=lambda a: None, + stream_config=lambda: stream_config, encode_headers=self._config.get( "header_codec_behavior", HeaderCodecBehavior.NO_CODEC ) @@ -309,6 +324,10 @@ def on_eviction_hook( # per workflow type nondeterminism_as_workflow_fail=workflow_worker.nondeterminism_as_workflow_fail(), nondeterminism_as_workflow_fail_for_types=workflow_worker.nondeterminism_as_workflow_fail_for_types(), + stream_replay_as_workflow_fail=workflow_worker.stream_replay_as_workflow_fail(), + stream_replay_as_workflow_fail_for_types=( + workflow_worker.stream_replay_as_workflow_fail_for_types() + ), # All values below are ignored but required by Core max_cached_workflows=2, tuner=temporalio.bridge.worker.TunerHolder( @@ -358,6 +377,7 @@ def on_eviction_hook( (plugin.name(), plugin.version()) for plugin in self.plugins ], storage_drivers=storage_driver_types, + streams=_bridge_streams(lambda: stream_config, None), ), ) bridge_worker_scope = bridge_worker @@ -366,7 +386,7 @@ def on_eviction_hook( workflow_worker_task = asyncio.create_task(workflow_worker.run()) # Yield iterator - async def replay_iterator() -> AsyncIterator[WorkflowReplayResult]: + async def replay_iterator() -> AsyncGenerator[WorkflowReplayResult, None]: async for history in histories: # Clear last complete and push history last_replay_complete.clear() @@ -399,7 +419,8 @@ async def replay_iterator() -> AsyncIterator[WorkflowReplayResult]: replay_failure=last_replay_failure, ) - yield replay_iterator() + async with aclosing(replay_iterator()) as results: + yield results finally: # Close the pusher if pusher is not None: @@ -437,6 +458,7 @@ class ReplayerConfig(TypedDict, total=False): runtime: temporalio.runtime.Runtime | None disable_safe_workflow_eviction: bool header_codec_behavior: HeaderCodecBehavior + stream_config: temporalio.client.StreamConfig | None @dataclass(frozen=True) diff --git a/temporalio/worker/_worker.py b/temporalio/worker/_worker.py index cf8125d819..7c09f31ebc 100644 --- a/temporalio/worker/_worker.py +++ b/temporalio/worker/_worker.py @@ -45,6 +45,7 @@ UnsandboxedWorkflowRunner, WorkflowRunner, ) +from ._workflow_streams import _bridge_streams, _check_stream_swap, _stream_store_call from .workflow_sandbox import SandboxedWorkflowRunner logger = logging.getLogger(__name__) @@ -147,6 +148,7 @@ def __init__( nexus_task_poller_behavior: PollerBehavior | None = None, disable_payload_error_limit: bool = False, max_workflow_task_external_storage_concurrency: int = _DEFAULT_WORKFLOW_TASK_EXTERNAL_STORAGE_CONCURRENCY, + stream_read_time: timedelta | None = None, ) -> None: """Create a worker to process workflows and/or activities. @@ -346,6 +348,15 @@ def __init__( Please report any issues you encounter with this setting or if you feel the default should be changed. WARNING: This setting is experimental. + stream_read_time: Maximum time that Stream reads can keep a Workflow + Task open, measured from its start or the end of replay. Defaults + to half the task timeout and always ends before its heartbeat. + Reads alone don't cause task heartbeats. Appends have no such limit. + At the limit, waiting reads return empty pages. Iterators continue + with a new wait, possibly in another task. Unset iterator waits + default to one minute after the first page. Immediate reads can + continue without holding the task open until the Store answers. + WARNING: This setting is experimental. """ config = WorkerConfig( @@ -395,6 +406,7 @@ def __init__( nexus_task_poller_behavior=nexus_task_poller_behavior, disable_payload_error_limit=disable_payload_error_limit, max_workflow_task_external_storage_concurrency=max_workflow_task_external_storage_concurrency, + stream_read_time=stream_read_time, ) plugins_from_client = cast( @@ -498,7 +510,9 @@ def _init_from_config(self, client: temporalio.client.Client, config: WorkerConf or bridge_client.config.runtime or temporalio.runtime.Runtime.default() ) - activities = config.get("activities") + activities = list(config.get("activities") or []) + if client_config["stream_config"] and config.get("workflows"): + activities.append(_stream_store_call) if activities: _warn_if_activity_executor_max_workers_is_inconsistent(config) self._activity_worker = _ActivityWorker( @@ -575,6 +589,7 @@ def check_activity(activity: str): disable_safe_eviction=config["disable_safe_workflow_eviction"], # type: ignore[reportTypedDictNotRequiredAccess] should_enforce_versioning_behavior=should_enforce_versioning_behavior, assert_local_activity_valid=check_activity, + stream_config=lambda: self.client._config["stream_config"], encode_headers=client_config["header_codec_behavior"] != HeaderCodecBehavior.NO_CODEC, max_workflow_task_external_storage_concurrency=max_workflow_task_external_storage_concurrency, @@ -667,7 +682,7 @@ def check_activity(activity: str): enable_workflows=self._workflow_worker is not None, enable_local_activities=self._activity_worker is not None and self._workflow_worker is not None, - enable_remote_activities=self._activity_worker is not None + enable_remote_activities=bool(config.get("activities")) and not config.get("no_remote_activities"), enable_nexus=self._nexus_worker is not None, ), @@ -716,6 +731,17 @@ def check_activity(activity: str): disable_payload_error_limit=config.get( "disable_payload_error_limit", False ), + streams=_bridge_streams( + lambda: self.client._config["stream_config"], + config.get("stream_read_time"), + ), + stream_replay_as_workflow_fail=self._workflow_worker is not None + and self._workflow_worker.stream_replay_as_workflow_fail(), + stream_replay_as_workflow_fail_for_types=( + self._workflow_worker.stream_replay_as_workflow_fail_for_types() + if self._workflow_worker + else set() + ), ), ) @@ -758,6 +784,9 @@ def client(self, value: temporalio.client.Client) -> None: raise ValueError( "New client is not on the same runtime as the existing client" ) + _check_stream_swap( + self.client._config["stream_config"], value._config["stream_config"] + ) assert bridge_client._bridge_client self._bridge_worker.replace_client(bridge_client._bridge_client) self._config["client"] = value @@ -1062,6 +1091,7 @@ class WorkerConfig(TypedDict, total=False): nexus_task_poller_behavior: PollerBehavior | None disable_payload_error_limit: bool max_workflow_task_external_storage_concurrency: int + stream_read_time: timedelta | None def _poller_behavior_to_bridge( diff --git a/temporalio/worker/_workflow.py b/temporalio/worker/_workflow.py index b0f18b7b8c..58fd845371 100644 --- a/temporalio/worker/_workflow.py +++ b/temporalio/worker/_workflow.py @@ -27,6 +27,7 @@ import temporalio.exceptions import temporalio.workflow from temporalio.bridge.worker import PollShutdownError +from temporalio.client._stream_store import StreamConfig from temporalio.converter import StorageDriverStoreContext, StorageDriverWorkflowInfo from temporalio.worker.workflow_sandbox._runner import SandboxedWorkflowRunner @@ -136,6 +137,7 @@ def __init__( encode_headers: bool, max_workflow_task_external_storage_concurrency: int, default_workflow_logic_flags: frozenset[_WorkflowLogicFlag] | None = None, + stream_config: Callable[[], StreamConfig | None] = lambda: None, ) -> None: # Debug mode is enabled if specified or if the TEMPORAL_DEBUG env var is truthy debug_mode = debug_mode or bool(os.environ.get("TEMPORAL_DEBUG")) @@ -192,6 +194,7 @@ def __init__( **_WorkflowExternFunctions( # type: ignore __temporal_get_metric_meter=lambda: metric_meter, __temporal_assert_local_activity_valid=assert_local_activity_valid, + __temporal_stream_config=stream_config, ) ) @@ -865,6 +868,22 @@ def nondeterminism_as_workflow_fail_for_types(self) -> set[str]: ) } + def stream_replay_as_workflow_fail(self) -> bool: + return any( + issubclass(temporalio.workflow.StreamReplayError, typ) + for typ in self._workflow_failure_exception_types + ) + + def stream_replay_as_workflow_fail_for_types(self) -> set[str]: + return { + k + for k, v in self._workflows.items() + if any( + issubclass(temporalio.workflow.StreamReplayError, typ) + for typ in v.failure_exception_types + ) + } + class _DeadlockError(Exception): """Exception class for deadlocks. Contains functionality to swap the default traceback for another.""" diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index bcca2648a8..ceeccaf6d1 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -58,7 +58,14 @@ import temporalio.exceptions import temporalio.nexus.system import temporalio.workflow +from temporalio.client._stream_store import _STREAM_SERVICE, StreamConfig from temporalio.converter import StorageDriverStoreContext, StorageDriverWorkflowInfo +from temporalio.nexus.system.stream_service.workflow._system_nexus_interceptor import ( + _start_system_nexus_operation as _start_stream_nexus_operation, +) +from temporalio.nexus.system.stream_service.workflow._system_nexus_interceptor import ( + _SystemNexusWorkflowOutboundInterceptorTerminal as _StreamOutboundInterceptorTerminal, +) from temporalio.nexus.system.workflow_service._system_nexus_interceptor import ( _start_system_nexus_operation, _SystemNexusWorkflowOutboundInterceptorTerminal, @@ -92,6 +99,7 @@ WorkflowInboundInterceptor, WorkflowOutboundInterceptor, ) +from ._workflow_streams import _WorkflowStreams logger = logging.getLogger(__name__) @@ -352,6 +360,7 @@ def __init__(self, det: WorkflowInstanceDetails) -> None: self._pending_nexus_operations: dict[int, _NexusOperationHandle] = {} self._pending_external_signals: dict[int, tuple[asyncio.Future, str]] = {} self._pending_external_cancels: dict[int, tuple[asyncio.Future, str]] = {} + self._streams = _WorkflowStreams(self) # Keyed by type self._curr_seqs: dict[str, int] = {} # TODO(cretz): Any concerns about not sharing this? Maybe the types I @@ -497,6 +506,7 @@ def _activate( self._finished_nexus_update_ids.clear() self._current_activation_error: Exception | None = None + self._streams.task_error = None self._deployment_version_for_current_task = ( act.deployment_version_for_current_task ) @@ -575,10 +585,13 @@ def _activate( check_conditions=index == 1 or index == 2, jobs=act.jobs ) except Exception as err: + # Store outages must remain retryable even when Workflow failure types include them. + if self._streams.task_error: + activation_err = self._streams.task_error # We want some errors during activation, like those that can happen # during payload conversion, to be able to fail the workflow not the # task - if self.workflow_is_failure_exception(err): + elif self.workflow_is_failure_exception(err): try: self._set_workflow_failure(err) except Exception as inner_err: @@ -695,6 +708,10 @@ def _apply( self._apply_resolve_signal_external_workflow( job.resolve_signal_external_workflow ) + elif job.HasField("resolve_stream_append"): + self._streams.resolve_append(job.resolve_stream_append) + elif job.HasField("resolve_stream_read"): + self._streams.resolve_read(job.resolve_stream_read) elif job.HasField("signal_workflow"): self._apply_signal_workflow(job.signal_workflow) elif job.HasField("initialize_workflow"): @@ -1252,12 +1269,13 @@ async def run_workflow(input: ExecuteWorkflowInput) -> None: return raise - if not self._workflow_input: + workflow_input = self._workflow_input + if not workflow_input: raise RuntimeError( "Expected workflow input to be set. This is an SDK Python bug." ) self._primary_task = self.create_task( - self._run_top_level_workflow_function(run_workflow(self._workflow_input)), + self._run_top_level_workflow_function(lambda: run_workflow(workflow_input)), name="run", ) if self._cancel_primary_task_pending: @@ -1848,7 +1866,12 @@ async def workflow_start_nexus_operation( event_groups: Sequence[temporalio.workflow.EventGroup] | None = None, ) -> temporalio.workflow.NexusOperationHandle[OutputT]: if temporalio.nexus.system.is_system_endpoint(endpoint): - return await _start_system_nexus_operation( + start = ( + _start_stream_nexus_operation + if service == _STREAM_SERVICE.name + else _start_system_nexus_operation + ) + return await start( self._outbound, StartNexusOperationInput( endpoint=temporalio.nexus.system.TEMPORAL_SYSTEM_ENDPOINT, @@ -2547,6 +2570,13 @@ def get_serialization_context( # The update's result and failure go back to the Nexus caller return self._nexus_update_contexts[command_info.update_protocol_instance_id] + if ( + command_info.command_type + == temporalio.api.enums.v1.command_type_pb2.CommandType.COMMAND_TYPE_UNSPECIFIED + ): + # The body of a Stream Record, which any code may read, so it has no context + return None + if ( command_info.command_type == temporalio.api.enums.v1.command_type_pb2.CommandType.COMMAND_TYPE_SCHEDULE_ACTIVITY_TASK @@ -2835,7 +2865,7 @@ async def run_signal() -> None: await self._inbound.handle_signal(input) task = self.create_task( - self._run_top_level_workflow_function(run_signal()), + self._run_top_level_workflow_function(run_signal), name=f"signal: {job.signal_name}", ) task.add_done_callback(done_callback) @@ -2916,9 +2946,12 @@ def _run_once( # This is used for the primary workflow function and signal handlers in # order to apply common exception handling to each - async def _run_top_level_workflow_function(self, coro: Awaitable[None]) -> None: + async def _run_top_level_workflow_function( + self, create_coro: Callable[[], Awaitable[None]] + ) -> None: try: - await coro + # Eviction can cancel this task before it starts, so defer the inner coroutine. + await create_coro() except _ContinueAsNewError as err: logger.debug("Workflow requested continue as new") err._apply_command() @@ -3381,7 +3414,9 @@ async def handle_update_handler(self, input: HandleUpdateInput) -> Any: class _WorkflowOutboundImpl( - _SystemNexusWorkflowOutboundInterceptorTerminal, WorkflowOutboundInterceptor + _SystemNexusWorkflowOutboundInterceptorTerminal, + _StreamOutboundInterceptorTerminal, + WorkflowOutboundInterceptor, ): def __init__(self, instance: _WorkflowInstanceImpl) -> None: # type: ignore # We are intentionally not calling the base class's __init__ here @@ -3423,7 +3458,9 @@ async def start_nexus_operation( async def _schedule_system_nexus_operation( self, input: StartNexusOperationInput[Any, OutputT] - ) -> _NexusOperationHandle[OutputT]: + ) -> temporalio.workflow.NexusOperationHandle[OutputT]: + if input.service == _STREAM_SERVICE.name: + return self._instance._streams.start(input) return await self._instance._outbound_start_nexus_operation(input) def start_local_activity( @@ -4052,6 +4089,7 @@ def _encode_search_attributes( class _WorkflowExternFunctions(TypedDict): __temporal_get_metric_meter: Callable[[], temporalio.common.MetricMeter] __temporal_assert_local_activity_valid: Callable[[str], None] + __temporal_stream_config: Callable[[], StreamConfig | None] class _ReplaySafeMetricMeter(temporalio.common.MetricMeter): diff --git a/temporalio/worker/_workflow_streams.py b/temporalio/worker/_workflow_streams.py new file mode 100644 index 0000000000..2d701b8b38 --- /dev/null +++ b/temporalio/worker/_workflow_streams.py @@ -0,0 +1,417 @@ +"""Stream calls of Workflow code.""" + +from __future__ import annotations + +import asyncio +import functools +import typing +from collections.abc import Callable, Generator +from dataclasses import dataclass +from datetime import timedelta +from typing import TYPE_CHECKING, Any, cast + +import google.protobuf.json_format +import google.protobuf.message +from nexusrpc import OutputT + +import temporalio.activity +import temporalio.api.failure.v1 +import temporalio.api.sdk.v1 as sdk +import temporalio.api.stream.v1 +import temporalio.api.streamservice.v1 as proto +import temporalio.bridge.proto.workflow_activation +import temporalio.bridge.proto.workflow_commands +import temporalio.bridge.streams +import temporalio.common +import temporalio.exceptions +import temporalio.nexus.system._support +import temporalio.workflow +from temporalio.api.enums.v1 import StreamErrorReason +from temporalio.client._stream_store import ( + StreamConfig, + StreamStore, + _call_store, + _request_ref, + _sdk_request_type, + _StoreCaller, +) +from temporalio.converter import StorageDriverWorkflowInfo +from temporalio.exceptions import StreamError + +from ._interceptor import StartLocalActivityInput, StartNexusOperationInput + +if TYPE_CHECKING: + from ._workflow_instance import _WorkflowInstanceImpl + +_STORE_CALL_ACTIVITY = "__temporal_stream_store_call" + + +@dataclass +class _Read: + waiter: asyncio.Future[Any] + page_type: Any + + +class _WorkflowStreams: # pyright: ignore[reportUnusedClass] + """Use Local Activities for create and describe because Core has no commands + for those operations. + """ + + def __init__(self, instance: _WorkflowInstanceImpl) -> None: + self._instance = instance + self._appends: dict[int, asyncio.Future[Any]] = {} + self.task_error: Exception | None = None + # Cancelled reads still receive one result from Core. + self._reads: dict[int, _Read] = {} + + def start( + self, input: StartNexusOperationInput[Any, OutputT] + ) -> temporalio.workflow.NexusOperationHandle[OutputT]: + """Schedule before returning so command order matches call order. + + Cancellation stops the caller's wait. Core still completes appends and + reads, so their later results must be discarded. + """ + instance = self._instance + instance._assert_not_read_only("start a Stream call") + operation = input.operation_name + converters = ( + instance._context_free_payload_converter, + instance._context_free_failure_converter, + ) + model = input.input + result_type: Any = input.output_type + request = temporalio.nexus.system._support.model_to_proto(model, *converters) + # Reject missing type information before a result could fail the task. + if isinstance(request, sdk.ReadRecordsRequest) and typing.get_args( + result_type + ) == (object,): + raise TypeError( + "Cannot read a Stream with no body type. Give get_stream a " + "body_type, or a StreamRef with a type argument." + ) + store = self._store(_request_ref(request)).name() + result = _start_call(self, store, operation, request, result_type) + + async def call() -> OutputT: + # `asyncio.wait` ends at a cancel of this task. `await result` would pass the + # cancel on and wait for the cancelled Local Activity. + await asyncio.wait([result]) + if isinstance(request, sdk.ReadRecordsRequest): + return result.result() + return temporalio.nexus.system._support.model_from_proto( + self._response(operation, request, result), + result_type, + *converters, + ) + + def stop(_: asyncio.Task[OutputT]) -> None: + if result.done(): + return + result.cancel() + + task = instance.create_task(call(), name=f"stream: {operation}") + # A callback also runs for a task that is cancelled before its first step. + task.add_done_callback(stop) + return _StreamCall(task) + + def _store(self, ref: sdk.StreamRef) -> StreamStore: + config = self._stream_config() + if config is None: + raise self._fail_task( + ValueError( + "Worker or Replayer has no stream_config, which every " + "Stream call requires, also in a replay." + ) + ) + info = self._instance._info + target = StorageDriverWorkflowInfo( + id=info.workflow_id, + run_id=info.run_id, + type=info.workflow_type, + namespace=info.namespace, + ) + try: + return config._store_for(ref, target, info.namespace) + except Exception as err: + raise self._fail_task(err) + + def resolve_append( + self, job: temporalio.bridge.proto.workflow_activation.ResolveStreamAppend + ) -> None: + future = self._appends.pop(job.seq, None) + if future is None: + raise RuntimeError(f"Failed finding Stream append for sequence {job.seq}") + # Core completes writes even after their caller is cancelled. + if future.done(): + return + if job.HasField("failed"): + future.set_exception(self._error(job.failed)) + else: + future.set_result(job.appended) + + def resolve_read( + self, job: temporalio.bridge.proto.workflow_activation.ResolveStreamRead + ) -> None: + read = self._reads.pop(job.seq, None) + if read is None: + raise RuntimeError(f"Failed finding Stream read for sequence {job.seq}") + if read.waiter.done(): + return + if job.HasField("failed"): + read.waiter.set_exception(self._error(job.failed)) + return + page = proto.ReadRecordsResponse( + records=job.page.records, last_offset=job.page.last_offset + ) + # Conversion failures must fail the task before Workflow code resumes. + read.waiter.set_result( + temporalio.nexus.system._support.model_from_proto( + page, + read.page_type, + self._instance._context_free_payload_converter, + self._instance._context_free_failure_converter, + ) + ) + + def _error(self, failure: temporalio.api.failure.v1.Failure) -> BaseException: + instance = self._instance + return _stream_error_from_failure(failure) or ( + instance._context_free_failure_converter.from_failure( + failure, instance._context_free_payload_converter + ) + ) + + def _schedule_store_call( + self, + store: str, + operation: str, + request: google.protobuf.message.Message, + request_id: str | None, + ) -> asyncio.Future[Any]: + instance = self._instance + activity = instance._outbound.start_local_activity( + StartLocalActivityInput( + activity=_STORE_CALL_ACTIVITY, + args=(operation, store, request.SerializeToString(), request_id), + activity_id=None, + # A call that hangs ends before the heartbeat of the Workflow Task, and an + # outage fails the task immediately, so neither writes into History. + schedule_to_close_timeout=instance._info.task_timeout / 2, + schedule_to_start_timeout=None, + start_to_close_timeout=None, + retry_policy=temporalio.common.RetryPolicy(maximum_attempts=1), + local_retry_threshold=None, + cancellation_type=temporalio.workflow.ActivityCancellationType.TRY_CANCEL, + headers={}, + summary=None, + arg_types=None, + ret_type=None, + ) + ) + # Nothing awaits the Activity once its call is cancelled. + activity.add_done_callback(lambda done: done.cancelled() or done.exception()) + return activity + + def _response( + self, + operation: str, + request: google.protobuf.message.Message, + result: asyncio.Future[Any], + ) -> google.protobuf.message.Message: + if isinstance(request, sdk.AppendRecordsRequest): + appended = result.result() + return proto.AppendRecordsResponse( + first_offset=appended.first_offset, last_offset=appended.last_offset + ) + try: + answer = result.result() + except temporalio.exceptions.FailureError as err: + # A refusal of the Store comes as the failure of the attempt. A timeout comes + # inside an Activity failure, which has no Stream details. + error = _stream_error_from_failure(err.failure) if err.failure else None + if ( + error is None + or error.reason + == StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE + ): + # Workflow code could catch an error of this call, so the task fails and + # nothing goes into History, as for an outage during an append. + outage = RuntimeError(f"Stream Store call {operation} failed") + outage.__cause__ = err + raise self._fail_task(outage) + raise error from err + # Replay must retain the Store recorded by create. + if isinstance(request, sdk.CreateStreamRequest): + return sdk.CreateStreamResponse.FromString(answer) + return proto.DescribeStreamResponse.FromString(answer) + + def _fail_task(self, error: Exception) -> Exception: + """Prevent caught errors from recording an unserved call as successful.""" + self.task_error = self._instance._current_activation_error = error + return error + + def _stream_config(self) -> StreamConfig | None: + functions = self._instance._extern_functions + return cast( + Callable[[], StreamConfig | None], functions["__temporal_stream_config"] + )() + + +def _start_call( + streams: _WorkflowStreams, + store: str, + operation: str, + request: google.protobuf.message.Message, + result_type: Any, +) -> asyncio.Future[Any]: + """Use the selected Store in commands so replay can detect routing changes.""" + instance = streams._instance + stream = sdk.StreamRef(id=_request_ref(request).id, store=store) + if isinstance(request, sdk.AppendRecordsRequest): + seq = instance._next_seq("stream_append") + append = instance._add_command().append_to_stream + append.seq = seq + append.stream.CopyFrom(stream) + append.bodies.extend(record.body for record in request.records) + result = streams._appends[seq] = instance.create_future() + return result + if isinstance(request, sdk.ReadRecordsRequest): + seq = instance._next_seq("stream_read") + instance._add_command().read_stream.CopyFrom( + temporalio.bridge.proto.workflow_commands.ReadStream( + seq=seq, + stream=stream, + from_offset=request.from_offset, + wait=request.wait if request.HasField("wait") else None, + max_records=request.max_records, + max_bytes=request.max_bytes, + ) + ) + result = instance.create_future() + streams._reads[seq] = _Read(result, result_type) + return result + # Runs in a chain must retry the same create. + request_id = None + if isinstance(request, sdk.CreateStreamRequest): + request_id = instance._info.first_execution_run_id + return streams._schedule_store_call(store, operation, request, request_id) + + +class _StreamCall(temporalio.workflow.NexusOperationHandle[OutputT]): + """Cancel the caller's wait without waiting for the Store call to finish.""" + + def __init__(self, task: asyncio.Task[OutputT]) -> None: + self._task = task + + @property + def operation_token(self) -> str | None: + return None + + def __await__(self) -> Generator[Any, Any, OutputT]: + return self._task.__await__() + + def cancel(self) -> bool: + return self._task.cancel() + + +@temporalio.activity.defn(name=_STORE_CALL_ACTIVITY) +async def _stream_store_call( # pyright: ignore[reportUnusedFunction] + operation: str, store: str, request: bytes, request_id: str | None +) -> bytes: + """Record the selected Store in create results so replay keeps the same ref.""" + info = temporalio.activity.info() + if not info.is_local or operation not in ("CreateStream", "DescribeStream"): + raise temporalio.exceptions.ApplicationError( + f"{_STORE_CALL_ACTIVITY} is an Activity of the SDK, which only runs " + "a create or a describe of a Stream as a Local Activity", + non_retryable=True, + ) + client = temporalio.activity.client() + stream_config = client._config["stream_config"] + if stream_config is None: + raise ValueError("Client of this Worker has no stream_config.") + stream_request = _sdk_request_type(operation).FromString(request) + response = await _call_store( + stream_config._store(store), + stream_config._limits(), + client.data_converter.payload_codec, + operation, + stream_request, + request_id, + ) + return response.SerializeToString() + + +def _stream_error_from_failure( + failure: temporalio.api.failure.v1.Failure, +) -> StreamError | None: + """Accept Core's binary details and the default converter's JSON details.""" + details = temporalio.api.stream.v1.StreamErrorDetails() + for payload in failure.application_failure_info.details.payloads: + if payload.metadata.get("messageType") != details.DESCRIPTOR.full_name.encode(): + continue + # Core writes the details as binary, and the default converter as JSON. + if payload.metadata.get("encoding") == b"json/protobuf": + try: + google.protobuf.json_format.Parse(payload.data, details) + except google.protobuf.json_format.ParseError: + # The JSON has a reason by a name that this SDK doesn't know. + pass + else: + details.ParseFromString(payload.data) + reason = details.reason + if reason not in StreamErrorReason.values(): + reason = StreamErrorReason.STREAM_ERROR_REASON_UNSPECIFIED + error = StreamError(failure.message, reason=reason) + error._failure = failure + return error + return None + + +def _for_core( + stream_config: StreamConfig | None, +) -> tuple[set[str], tuple[int, int, int] | None]: + if stream_config is None: + return set(), None + return set(stream_config._by_name), stream_config._limits() + + +def _bridge_streams( # pyright: ignore[reportUnusedFunction] + stream_config: Callable[[], StreamConfig | None], + read_time: timedelta | None, +) -> temporalio.bridge.streams.WorkerStreams: + """Resolve Store instances at call time so client replacement takes effect.""" + + def store(name: str) -> StreamStore: + current = stream_config() + assert current + return current._store(name) + + names, limits = _for_core(stream_config()) + return temporalio.bridge.streams.WorkerStreams( + limits=limits, + # Client swaps must affect later Store calls. + stores=[ + (name, _StoreCaller(functools.partial(store, name))) + for name in sorted(names) + ], + read_time_millis=int(1000 * read_time.total_seconds()) + if read_time is not None + else None, + ) + + +def _check_stream_swap( # pyright: ignore[reportUnusedFunction] + existing: StreamConfig | None, new: StreamConfig | None +) -> None: + names, limits = _for_core(existing) + new_names, new_limits = _for_core(new) + if new_names != names: + raise ValueError( + "New client does not have the Stream Stores of the existing client" + ) + if new_limits != limits: + raise ValueError( + "New client does not have the Stream limits of the existing client" + ) diff --git a/temporalio/workflow/__init__.py b/temporalio/workflow/__init__.py index 60b02cc543..3ddb444b30 100644 --- a/temporalio/workflow/__init__.py +++ b/temporalio/workflow/__init__.py @@ -119,6 +119,7 @@ ContinueAsNewVersioningBehavior, NondeterminismError, ReadOnlyContextError, + StreamReplayError, VersioningIntent, _NotInWorkflowEventLoopError, ) @@ -246,6 +247,7 @@ "ContinueAsNewVersioningBehavior", "NondeterminismError", "ReadOnlyContextError", + "StreamReplayError", "VersioningIntent", "HandlerUnfinishedPolicy", "UnfinishedSignalHandlersWarning", diff --git a/temporalio/workflow/_exceptions.py b/temporalio/workflow/_exceptions.py index 2d34c2fedd..1542959878 100644 --- a/temporalio/workflow/_exceptions.py +++ b/temporalio/workflow/_exceptions.py @@ -9,6 +9,7 @@ __all__ = [ "NondeterminismError", "ReadOnlyContextError", + "StreamReplayError", "VersioningIntent", "ContinueAsNewVersioningBehavior", ] @@ -23,6 +24,18 @@ def __init__(self, message: str) -> None: self.message = message +class StreamReplayError(temporalio.exceptions.TemporalError): + """Error of a Workflow replay whose Stream Store no longer has the Records of + a read as the first run read them. + + SDK Core fails the Workflow Task with it. A Worker or a Workflow that has this + class in its failure exception types fails the Workflow instead. + + .. warning:: + This API is experimental and subject to change. + """ + + class ReadOnlyContextError(temporalio.exceptions.TemporalError): """Error thrown when trying to do mutable workflow calls in a read-only context like a query or update validator. diff --git a/tests/contrib/streams/__init__.py b/tests/contrib/streams/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/contrib/streams/test_appender.py b/tests/contrib/streams/test_appender.py new file mode 100644 index 0000000000..51597af82e --- /dev/null +++ b/tests/contrib/streams/test_appender.py @@ -0,0 +1,149 @@ +"""Tests of the buffered appender, with no server.""" + +import asyncio +from datetime import timedelta +from typing import Any +from unittest.mock import AsyncMock, Mock, call + +import pytest + +from temporalio.api.enums.v1 import StreamErrorReason +from temporalio.contrib.streams import BufferedAppender +from temporalio.exceptions import StreamError +from temporalio.nexus.system.stream_service import AppendRecordsResponse +from tests.helpers.streams import run_with_virtual_clock + + +class _FakeStream: + """Stream whose append takes time on the clock of the loop, and whose batch + number ``fails_at`` fails, or has its write cancelled. + """ + + def __init__( + self, write_time: float, fails_at: int | None = None, cancelled: bool = False + ) -> None: + self._write_time = write_time + self._fails_at = fails_at + self._cancelled = cancelled + self.written: list[int] = [] + self.batches: list[tuple[float, float, tuple[int, ...]]] = [] + """The start time, the end time and the Records of each batch.""" + + async def append(self, *records: int) -> AppendRecordsResponse: + loop = asyncio.get_running_loop() + started = loop.time() + try: + await asyncio.sleep(self._write_time) + if len(self.batches) == self._fails_at: + if self._cancelled: + raise asyncio.CancelledError() + raise StreamError( + "The Store is down", + reason=StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE, + ) + self.written.extend(records) + offset = len(self.written).to_bytes(8, "big") + return AppendRecordsResponse(first_offset=offset, last_offset=offset) + finally: + self.batches.append((started, loop.time(), records)) + + +@pytest.mark.parametrize("delay,seconds", [(None, 0.1), (timedelta(0), 0.0)]) +def test_the_batch_delay_starts_with_the_first_record( + delay: timedelta | None, seconds: float +) -> None: + async def script() -> None: + stream: Any = _FakeStream(0) + appender = BufferedAppender[int](stream, max_delay=delay) + appender.append(1) + if seconds: + await asyncio.sleep(seconds / 2) + appender.append(2) + await asyncio.sleep(1) + assert stream.batches == [(seconds, seconds, (1, 2))] + + run_with_virtual_clock(script()) + + +def test_full_batches_wait_for_the_previous_write() -> None: + async def script() -> None: + stream: Any = _FakeStream(2) + appender = BufferedAppender[int]( + stream, max_delay=timedelta(seconds=3), max_batch_records=2 + ) + assert await appender.flush() is None + appender.append(1, 2) + await asyncio.sleep(1) + appender.append(3, 4, 5) + await asyncio.sleep(6) + assert stream.batches == [(0, 2, (1, 2)), (2, 4, (3, 4)), (4, 6, (5,))] + assert await appender.flush() == (5).to_bytes(8, "big") + + run_with_virtual_clock(script()) + + +def test_cancelling_a_flush_preserves_the_write_and_buffer() -> None: + async def script() -> None: + stream: Any = _FakeStream(2) + async with BufferedAppender[int]( + stream, max_delay=timedelta(seconds=90) + ) as appender: + appender.append(1) + flushing = asyncio.create_task(appender.flush()) + await asyncio.sleep(1) + appender.append(2) + flushing.cancel() + with pytest.raises(asyncio.CancelledError): + await flushing + assert stream.batches == [(0, 2, (1,)), (2, 4, (2,))] + + run_with_virtual_clock(script()) + + +@pytest.mark.parametrize("cancelled", [False, True]) +async def test_a_failed_batch_stops_later_writes(cancelled: bool) -> None: + stream: Any = _FakeStream(0, fails_at=1, cancelled=cancelled) + appender = BufferedAppender[int](stream, max_batch_records=2) + appender.append(1, 2, 3, 4, 5) + with pytest.raises(asyncio.CancelledError if cancelled else StreamError): + await appender.flush() + assert stream.written == [1, 2] + assert appender.unwritten == 3 + later = RuntimeError if cancelled else StreamError + with pytest.raises(later) as raised: + appender.append(6) + with pytest.raises(later) as again: + await appender.flush() + assert raised.value is again.value + + +async def test_append_defers_immediate_writes_with_an_eager_task_factory() -> None: + eager = getattr(asyncio, "eager_task_factory", None) + if eager is None: + pytest.skip("Eager task factories require Python 3.12") + loop = asyncio.get_running_loop() + previous = loop.get_task_factory() + stream = Mock() + stream.append = AsyncMock(return_value=AppendRecordsResponse(last_offset=b"last")) + try: + loop.set_task_factory(eager) + appender = BufferedAppender[int](stream, max_batch_records=1) + appender.append(1) + appender.append(2) + stream.append.assert_not_awaited() + assert await appender.flush() == b"last" + assert stream.append.await_args_list == [call(1), call(2)] + finally: + loop.set_task_factory(previous) + + +@pytest.mark.parametrize("cancelled", [False, True]) +def test_async_with_keeps_the_error_of_its_block(cancelled: bool) -> None: + async def block() -> None: + stream: Any = _FakeStream(0.0, fails_at=0, cancelled=cancelled) + async with BufferedAppender[int](stream) as appender: + appender.append(1) + raise KeyError("The block failed") + + with pytest.raises(KeyError): + run_with_virtual_clock(block()) diff --git a/tests/helpers/streams.py b/tests/helpers/streams.py new file mode 100644 index 0000000000..674ee63c3b --- /dev/null +++ b/tests/helpers/streams.py @@ -0,0 +1,368 @@ +"""Helpers for the tests of Streams.""" + +import asyncio +import collections +import selectors +import uuid +from collections.abc import Awaitable, Callable, Coroutine, Iterator, Mapping, Sequence +from contextlib import contextmanager +from dataclasses import dataclass, field +from datetime import timedelta +from typing import Any, TypeVar + +from google.protobuf.message import Message + +from temporalio.api.common.v1 import Payload, Payloads +from temporalio.api.enums.v1 import StreamErrorReason +from temporalio.api.failure.v1 import ApplicationFailureInfo, Failure +from temporalio.api.stream.v1 import StreamErrorDetails +from temporalio.api.streamservice.v1 import ( + AppendRecordsRequest, + AppendRecordsResponse, + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, +) +from temporalio.client import ( + Client, + StreamConfig, + StreamSelectContext, + StreamStore, + WorkflowFailureError, + WorkflowHandle, + WorkflowHistory, +) +from temporalio.converter import ( + DataConverter, + PayloadCodec, + SerializationContext, + WithSerializationContext, +) +from temporalio.testing import MemoryStreamStore +from temporalio.worker import Replayer, Worker +from tests.helpers import new_worker + +_T = TypeVar("_T") + +CodecCall = tuple[str, SerializationContext | None, int] + + +class ContextCodec(PayloadCodec, WithSerializationContext): + """Wraps each payload with the kind of its serialization context as a key, and + refuses to unwrap a payload with another key. ``calls`` logs the context and the + payload count of each call. + """ + + def __init__( + self, + calls: list[CodecCall] | None = None, + context: SerializationContext | None = None, + ) -> None: + self.calls: list[CodecCall] = [] if calls is None else calls + self._context = context + + def with_context(self, context: SerializationContext) -> "ContextCodec": + return ContextCodec(self.calls, context) + + async def encode(self, payloads: Sequence[Payload]) -> list[Payload]: + self.calls.append(("encode", self._context, len(payloads))) + return [wrapped(payload, self._context) for payload in payloads] + + async def decode(self, payloads: Sequence[Payload]) -> list[Payload]: + self.calls.append(("decode", self._context, len(payloads))) + decoded: list[Payload] = [] + for payload in payloads: + if payload.metadata.get("encoding") == b"test/wrapped": + key = wrapped(Payload(), self._context).metadata["context"] + assert payload.metadata["context"] == key, ( + f"{payload} isn't for {key!r}" + ) + payload = Payload.FromString(payload.data) + decoded.append(payload) + return decoded + + +def wrapped(payload: Payload, context: SerializationContext | None = None) -> Payload: + """Return ``payload`` as a :py:class:`ContextCodec` with ``context`` encodes it.""" + return Payload( + metadata={ + "encoding": b"test/wrapped", + "context": type(context).__name__.encode(), + }, + data=payload.SerializeToString(), + ) + + +Fault = Callable[[Callable[[], Awaitable[Any]]], Awaitable[Any]] +"""What a :py:class:`FaultStore` does with one call. It gets the call of the memory Store.""" + + +@contextmanager +def failure_note(note: str) -> Iterator[None]: + """Add ``note`` to a failure in the block, such as the seed of a generated case.""" + try: + yield + except BaseException as err: + err.add_note(note) + raise + + +def raises(error: BaseException) -> Fault: + """Return a fault that fails a call, and doesn't call the memory Store.""" + + async def fault(_call: Callable[[], Awaitable[Any]]) -> Any: + raise error + + return fault + + +def answers(response: Message) -> Fault: + """Return a fault that answers a call with ``response``, with no Store call.""" + + async def fault(_call: Callable[[], Awaitable[Any]]) -> Any: + return response + + return fault + + +def loses_answer() -> Fault: + """Return a fault that calls the memory Store and then fails as an outage.""" + + async def fault(call: Callable[[], Awaitable[Any]]) -> Any: + await call() + raise ConnectionError("The answer of the Store was lost") + + return fault + + +class Hold: + """A fault that holds a call until :py:meth:`release`, before the memory Store.""" + + def __init__(self) -> None: + self.started = asyncio.Event() + self.cancelled = asyncio.Event() + self._released = asyncio.Event() + + def release(self) -> None: + self._released.set() + + async def __call__(self, call: Callable[[], Awaitable[Any]]) -> Any: + self.started.set() + try: + await self._released.wait() + except asyncio.CancelledError: + self.cancelled.set() + raise + return await call() + + +class FaultStore(StreamStore): + """Stream Store around a :py:class:`MemoryStreamStore`, which logs each request + and runs the next fault of its method, if one is queued. + """ + + def __init__(self, name: str = "memory", **options: Any) -> None: + self.memory = MemoryStreamStore(name=name, **options) + self.calls: list[tuple[Any, str | None]] = [] + """Each request, with its request id, which is ``None`` for a read and a + describe.""" + self.faults: dict[str, collections.deque[Fault]] = collections.defaultdict( + collections.deque + ) + + @property + def requests(self) -> list[Any]: + """Each request of :py:attr:`calls`.""" + return [request for request, _ in self.calls] + + def name(self) -> str: + return self.memory.name() + + async def create_stream( + self, request: CreateStreamRequest, *, request_id: str + ) -> CreateStreamResponse: + return await self._call("create_stream", request, request_id) + + async def append_records( + self, request: AppendRecordsRequest, *, request_id: str + ) -> AppendRecordsResponse: + return await self._call("append_records", request, request_id) + + async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: + return await self._call("read_records", request) + + async def describe_stream( + self, request: DescribeStreamRequest + ) -> DescribeStreamResponse: + return await self._call("describe_stream", request) + + async def _call( + self, method: str, request: Message, request_id: str | None = None + ) -> Any: + self.calls.append((request, request_id)) + + async def call() -> Any: + if request_id is None: + return await getattr(self.memory, method)(request) + return await getattr(self.memory, method)(request, request_id=request_id) + + if self.faults[method]: + return await self.faults[method].popleft()(call) + return await call() + + +def core_failure(reason: int, message: str = "The Store refused the call") -> Failure: + """Return the failure of a Stream job as SDK Core builds it, also for a reason + number that this SDK doesn't know. + """ + unavailable = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE + details = StreamErrorDetails(reason=reason) # type: ignore[arg-type] + return Failure( + message=message, + application_failure_info=ApplicationFailureInfo( + type="stream_token", + non_retryable=reason != unavailable, + details=Payloads( + payloads=[ + Payload( + metadata={ + "encoding": b"binary/protobuf", + "messageType": details.DESCRIPTOR.full_name.encode(), + }, + data=details.SerializeToString(), + ) + ] + ), + ), + ) + + +def stream_client( + client: Client, + *stores: StreamStore, + store_selector: Callable[[StreamSelectContext], StreamStore] | None = None, + data_converter: DataConverter | None = None, + **limits: int, +) -> Client: + """Return a client on the connection of ``client`` with the given Stream Stores + and limits. + """ + config = client.config() + config["stream_config"] = StreamConfig( + stores, store_selector=store_selector, **limits + ) + if data_converter: + config["data_converter"] = data_converter + return Client(**config) + + +@dataclass +class RunOptions: + """What :py:func:`run` runs, and on which Worker.""" + + workflow: Any + """The Workflow class.""" + + args: Sequence[Any] = () + activities: Sequence[Callable[..., Any]] = () + cached: bool = True + """If false, the Worker caches no run, so each Workflow Task replays its run.""" + + replay: bool = False + """Whether a ``Replayer`` with the Stream config of the client replays the History.""" + + task_timeout: timedelta | None = None + worker: Mapping[str, Any] = field(default_factory=dict) + """More options of the Worker.""" + + during: Callable[[WorkflowHandle[Any, Any], Worker], Awaitable[None]] | None = None + """Called once the Workflow has started, while its Worker runs.""" + + +@dataclass +class Run: + """What a Workflow of :py:func:`run` did.""" + + result: Any + """The result of the Workflow, or the error that it failed with.""" + + history: WorkflowHistory + + +async def run(client: Client, options: RunOptions) -> Run: + """Run a Workflow to its end on a new Worker.""" + async with new_worker( + client, + options.workflow, + activities=options.activities, + max_cached_workflows=1000 if options.cached else 0, + **options.worker, + ) as worker: + handle = await client.start_workflow( + options.workflow.run, + args=options.args, + id=f"wf-{uuid.uuid4()}", + task_queue=worker.task_queue, + task_timeout=options.task_timeout, + ) + if options.during: + await options.during(handle, worker) + result: Any + try: + result = await handle.result() + except WorkflowFailureError as err: + result = err + history = await handle.fetch_history() + if options.replay: + await Replayer( + workflows=[options.workflow], + data_converter=client.data_converter, + stream_config=client._config["stream_config"], + ).replay_workflow(history) + return Run(result, history) + + +class _JumpingSelector(selectors.DefaultSelector): + """Selector that moves the clock of its loop past a wait and doesn't wait.""" + + def __init__(self, loop: "VirtualClockLoop") -> None: + super().__init__() + self._loop = loop + + def select( + self, timeout: float | None = None + ) -> list[tuple[selectors.SelectorKey, int]]: + # With no timer, only another thread can wake the loop, so this waits for it. + if timeout is None: + return super().select(None) + events = super().select(0) + if not events: + self._loop.now += max(timeout, 0) + return events + + +class VirtualClockLoop(asyncio.SelectorEventLoop): + """Event loop whose clock jumps to its next timer when no task can run. + + A test on it must not wait for another thread while a timer is pending, since + the clock then jumps past the wait. + """ + + def __init__(self) -> None: + self.now = 0.0 + super().__init__(_JumpingSelector(self)) + # asyncio runs a timer that is due within the resolution of the real clock, which is + # about 16 ms on Windows. This clock is exact, so its timers run when they are due. + self._clock_resolution = 1e-9 + + def time(self) -> float: + return self.now + + +def run_with_virtual_clock(main: Coroutine[Any, Any, _T]) -> _T: + """Run ``main`` on a new :py:class:`VirtualClockLoop` and return its result.""" + with asyncio.Runner(loop_factory=VirtualClockLoop) as runner: + return runner.run(main) diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py new file mode 100644 index 0000000000..b032755a3a --- /dev/null +++ b/tests/nexus/test_streams.py @@ -0,0 +1,779 @@ +"""Tests of the client path of Streams, with no server.""" + +import asyncio +import concurrent.futures +import copy +import dataclasses +import pickle +import pkgutil +import subprocess +import sys +from collections.abc import Awaitable, Callable +from datetime import datetime, timedelta, timezone +from types import SimpleNamespace +from typing import Any, cast +from unittest.mock import Mock, patch + +import pytest +from google.protobuf.message import Message +from google.protobuf.timestamp_pb2 import Timestamp + +import temporalio.api.streamservice.v1 as proto +import temporalio.client +import temporalio.converter +import temporalio.nexus.system +import temporalio.workflow +from temporalio.activity import WorkflowTaskAttempt +from temporalio.api.enums.v1 import StreamErrorReason, StreamIdConflictPolicy +from temporalio.api.failure.v1 import Failure +from temporalio.api.stream.v1 import ( + AppendRecord, + ClientProducer, + Producer, + StreamErrorDetails, +) +from temporalio.client import ( + Client, + NexusOperationHandle, + StreamConfig, + StreamSelectContext, +) +from temporalio.contrib.streams import as_producer, current_producer +from temporalio.converter import StorageDriverActivityInfo +from temporalio.exceptions import ApplicationError, StreamError +from temporalio.nexus.system import _support +from temporalio.nexus.system.stream_service import ( + ReadRecordsRequest, + ReadRecordsResponse, + StreamRecord, + StreamRef, +) +from temporalio.nexus.system.stream_service import ( + StreamIdConflictPolicy as ConflictPolicy, +) +from temporalio.service import ServiceClient +from temporalio.testing import ActivityEnvironment +from temporalio.testing._stream_store import _MemoryStreams +from temporalio.worker._workflow_streams import _stream_error_from_failure +from tests.helpers.streams import ( + FaultStore, + Hold, + answers, + core_failure, + failure_note, + loses_answer, + run_with_virtual_clock, +) + +_UNAVAILABLE = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE +_INVALID_ARGUMENT = StreamErrorReason.STREAM_ERROR_REASON_INVALID_ARGUMENT + + +class _Interceptor(temporalio.client.Interceptor): + """Gives a client the outbound interceptor that ``outbound`` makes.""" + + def __init__( + self, + outbound: Callable[ + [temporalio.client.OutboundInterceptor], + temporalio.client.OutboundInterceptor, + ], + ) -> None: + super().__init__() + self._outbound = outbound + + def intercept_client( + self, next: temporalio.client.OutboundInterceptor + ) -> temporalio.client.OutboundInterceptor: + return self._outbound(next) + + +class _RecordingOutbound(temporalio.client.OutboundInterceptor): + """Logs the Store name of the ref of each Stream request before and after its + call. + """ + + def __init__( + self, + next: temporalio.client.OutboundInterceptor, + stores: list[tuple[str | None, str | None]], + ) -> None: + super().__init__(next) + self._stores = stores + + async def start_nexus_operation( + self, input: temporalio.client.StartNexusOperationInput + ) -> NexusOperationHandle[Any]: + ref = getattr(input.arg, "stream_ref", None) or input.arg.ref + before = ref.store + try: + return await self.next.start_nexus_operation(input) + finally: + self._stores.append((before, ref.store)) + + +def _producer_proto(producer: Any) -> Producer: + converter = temporalio.converter.DataConverter.default + message = _support.model_to_proto( + producer, converter.payload_converter, converter.failure_converter + ) + assert isinstance(message, Producer) + return message + + +@pytest.mark.parametrize("operation", ["create", "append", "read", "describe"]) +@pytest.mark.parametrize( + "routing", ["only", "selector", "explicit", "unknown", "unregistered"] +) +@pytest.mark.parametrize("in_activity", [False, True]) +async def test_a_client_call_reaches_the_selected_store( + operation: str, routing: str, in_activity: bool +) -> None: + service_client = Mock(spec=ServiceClient) + a, b = FaultStore("a"), FaultStore("b") + stores = [a] if routing == "only" else [a, b] + selected = FaultStore("other") if routing == "unregistered" else b + selects: list[StreamSelectContext] = [] + + def selector(context: StreamSelectContext) -> FaultStore: + selects.append(context) + return selected + + ref_store = {"explicit": "a", "unknown": "unknown"}.get(routing) + intercepted: list[tuple[str | None, str | None]] = [] + client = Client( + service_client, + interceptors=[_Interceptor(lambda next: _RecordingOutbound(next, intercepted))], + stream_config=StreamConfig( + stores, store_selector=None if routing == "only" else selector + ), + ) + activity = ActivityEnvironment() + activity.info = dataclasses.replace( + activity.info, activity_id="activity", activity_run_id="run" + ) + producer = ( + _producer_proto(activity.run(current_producer)) + if in_activity + else Producer( + client=ClientProducer(namespace="default", id=client._stream_producer_id) + ) + ) + for store in stores: + await store.memory.create_stream( + proto.CreateStreamRequest(stream_id="s"), request_id="setup" + ) + store.faults["read_records"].extend([answers(proto.ReadRecordsResponse())] * 2) + stream = client.get_stream(StreamRef[int](id="s", store=ref_store)) + payload = temporalio.converter.PayloadConverter.default.to_payload + expected: Message + if operation == "create": + expected = proto.CreateStreamRequest( + stream_id="s", + id_conflict_policy=StreamIdConflictPolicy.STREAM_ID_CONFLICT_POLICY_USE_EXISTING, + ) + elif operation == "append": + expected = proto.AppendRecordsRequest( + stream_id="s", + producer=producer, + records=[AppendRecord(body=payload(i)) for i in (3, 5)], + ) + elif operation == "read": + expected = proto.ReadRecordsRequest( + stream_id="s", max_records=2, max_bytes=4096 + ) + expected.wait.FromSeconds(5) + else: + expected = proto.DescribeStreamRequest(stream_id="s") + + async def call() -> Any: + if operation == "create": + return await client.create_stream( + id="s", + store=ref_store, + body_type=int, + id_conflict_policy=ConflictPolicy.StreamIdConflictPolicyUseExisting, + ) + if operation == "append": + return await stream.append(3, 5) + if operation == "read": + return await stream.read_page( + max_records=2, max_bytes=4096, wait=timedelta(seconds=5) + ) + return await stream.describe() + + if routing in ("unknown", "unregistered"): + with pytest.raises(ValueError): + await (activity.run(call) if in_activity else call()) + assert not a.calls and not b.calls and not service_client.mock_calls + return + + for _ in range(2): + result = await (activity.run(call) if in_activity else call()) + if operation == "create": + assert result.created is False + assert result.ref == StreamRef( + id="s", store="b" if routing == "selector" else "a" + ) + chosen, other = (b, a) if routing == "selector" else (a, b) + assert chosen.requests == [expected, expected] + assert not other.calls and not service_client.mock_calls + ids = [request_id for _, request_id in chosen.calls] + if operation in ("create", "append"): + assert all(ids) and ids[0] != ids[1] + else: + assert ids == [None, None] + assert intercepted == [(ref_store, ref_store)] * 2 + target = ( + StorageDriverActivityInfo( + namespace="default", id="activity", run_id="run", type="unknown" + ) + if in_activity + else None + ) + assert selects == ( + [StreamSelectContext(id="s", target=target, namespace="default")] * 2 + if routing == "selector" + else [] + ) + + +async def test_a_client_without_stream_config_does_not_call_the_server() -> None: + service_client = Mock(spec=ServiceClient) + with pytest.raises(ValueError): + await Client(service_client).create_stream(id="s") + assert not service_client.mock_calls + + +async def test_a_created_stream_keeps_its_selected_store() -> None: + a, b = FaultStore("a"), FaultStore("b") + selected = a + client = Client( + Mock(spec=ServiceClient), + stream_config=StreamConfig([a, b], store_selector=lambda _: selected), + ) + stream = await client.create_stream(id="s", body_type=int) + selected = b + await stream.append(1) + await stream.describe() + assert stream.ref.store == "a" + assert [type(request) for request in a.requests] == [ + proto.CreateStreamRequest, + proto.AppendRecordsRequest, + proto.DescribeStreamRequest, + ] + assert not b.calls + + +async def test_a_client_retry_recovers_a_lost_store_answer() -> None: + class Retry(temporalio.client.OutboundInterceptor): + async def start_nexus_operation( + self, input: temporalio.client.StartNexusOperationInput + ) -> NexusOperationHandle[Any]: + try: + return await self.next.start_nexus_operation(dataclasses.replace(input)) + except StreamError as err: + if err.reason != _UNAVAILABLE: + raise + return await self.next.start_nexus_operation(dataclasses.replace(input)) + + store = FaultStore() + store.faults["create_stream"].append(loses_answer()) + store.faults["append_records"].append(loses_answer()) + client = Client( + Mock(spec=ServiceClient), + stream_config=StreamConfig([store]), + interceptors=[_Interceptor(Retry)], + ) + stream = await client.create_stream(id="s", body_type=int) + assert stream.created is True + await stream.append(1) + await stream.append(2) + create, create_retry, append, append_retry, second = (key for _, key in store.calls) + assert create == create_retry + assert append == append_retry + assert len({create, append, second}) == 3 + assert [record.body for record in (await stream.read_page()).records] == [1, 2] + + +async def test_an_empty_client_append_does_not_reach_the_store() -> None: + store = FaultStore() + client = Client(Mock(spec=ServiceClient), stream_config=StreamConfig([store])) + with pytest.raises(StreamError) as raised: + await client.get_stream(StreamRef[int](id="s")).append() + assert raised.value.reason == _INVALID_ARGUMENT + assert not store.calls + + +async def test_a_stream_error_keeps_its_reason_on_every_path() -> None: + converter = temporalio.converter.DataConverter.default + for number in [*StreamErrorReason.values(), 99]: + known = number in StreamErrorReason.values() + reason = StreamErrorReason.ValueType(number if known else 0) + token = ( + "stream_" + + StreamErrorReason.Name(reason) + .removeprefix("STREAM_ERROR_REASON_") + .lower() + ) + message = f"The call failed with {number}" + expected = (reason, token, message, reason != _UNAVAILABLE) + details = StreamErrorDetails(reason=number) # type: ignore[arg-type] + + # Through an Activity, which gives its error to the default failure converter. + raised: ApplicationError = ( + StreamError(message, reason=reason) + if known + else ApplicationError(message, details, type=token, non_retryable=True) + ) + failure = Failure() + converter.failure_converter.to_failure( + raised, converter.payload_converter, failure + ) + # From Core, which builds the failure of a Stream job itself. + from_core = core_failure(number, message) + for form in (failure, from_core): + error = _stream_error_from_failure(form) + assert error is not None, number + # A copy of the error, also one from another process, is the same error. + for same in (error, copy.copy(error), pickle.loads(pickle.dumps(error))): + assert ( + same.reason, + same.type, + same.message, + same.non_retryable, + ) == expected, number + if not known: + # A newer Worker can record a reason by a name that this SDK doesn't have. + named = failure.application_failure_info.details.payloads[0] + named.data = b'{"reason": "STREAM_ERROR_REASON_ADDED_LATER"}' + later = _stream_error_from_failure(failure) + assert later and (later.reason, later.message) == (reason, message) + assert _stream_error_from_failure(Failure(message="other")) is None + + +class _FakeReads(temporalio.client.OutboundInterceptor): + def __init__(self, next: temporalio.client.OutboundInterceptor) -> None: + super().__init__(next) + self.pages = iter([(1, 2), (), (3, 4), (), (4, 5)]) + self.starts: list[int] = [] + self.waits: list[timedelta | None] = [] + + async def start_nexus_operation( + self, input: temporalio.client.StartNexusOperationInput + ) -> NexusOperationHandle[Any]: + request: ReadRecordsRequest[int] = input.arg + self.starts.append(int.from_bytes(request.from_offset or b"", "big")) + self.waits.append(request.wait) + records = [ + StreamRecord(body=at, offset=at.to_bytes(8, "big")) + for at in next(self.pages) + ] + page = ReadRecordsResponse( + records=records, + last_offset=records[-1].offset if records else request.from_offset, + ) + handle: NexusOperationHandle[Any] = NexusOperationHandle(Mock(), input.id) + handle._known_outcome = page + return handle + + +@pytest.mark.parametrize("wait", [None, timedelta(0), timedelta(seconds=5)]) +async def test_a_read_resumes_after_a_partial_page_and_skips_empty_pages( + wait: timedelta | None, +) -> None: + fake: list[_FakeReads] = [] + + def outbound(next: temporalio.client.OutboundInterceptor) -> _FakeReads: + fake.append(_FakeReads(next)) + return fake[0] + + client = Client(Mock(spec=ServiceClient), interceptors=[_Interceptor(outbound)]) + stream = client.get_stream(StreamRef[int](id="s")) + [reads] = fake + got: list[int] = [] + later = _support.DEFAULT_READ_WAIT if wait is None else wait + for stop_at in (3, 5): + offset = got[-1].to_bytes(8, "big") if got else None + async for record in stream.read(from_offset=offset, wait=wait): + got.append(record.body) + if record.body == stop_at: + break + assert got == [1, 2, 3, 4, 5] + assert reads.starts == [0, 2, 2, 3, 3] + assert reads.waits == [wait, later, later, wait, later] + + +@dataclasses.dataclass(frozen=True) +class _WriterInfo: + kind: str + namespace: str + workflow_id: str + run_id: str + activity_id: str + attempt: int + time: datetime + event_id: int + + +def _default_producer(writer: _WriterInfo) -> Any: + """Return the default Producer of a write of ``writer``.""" + if writer.kind == "workflow": + info = SimpleNamespace( + namespace=writer.namespace, + workflow_id=writer.workflow_id, + run_id=writer.run_id, + ) + with patch("temporalio.workflow.info", lambda: info): + return _support.workflow_producer() + in_workflow = writer.kind != "standalone_activity" + activity = ActivityEnvironment() + activity.info = dataclasses.replace( + activity.info, + namespace=writer.namespace, + activity_id=writer.activity_id, + attempt=writer.attempt, + current_attempt_scheduled_time=writer.time, + is_local=writer.kind == "local_activity", + workflow_id=writer.workflow_id if in_workflow else None, + workflow_run_id=writer.run_id if in_workflow else None, + activity_run_id=None if in_workflow else writer.run_id, + workflow_task=WorkflowTaskAttempt( + writer.event_id, writer.attempt + 1, writer.time + ) + if writer.kind == "local_activity" + else None, + _scheduled_event_id=writer.event_id + if writer.kind == "workflow_activity" + else 0, + ) + producer = activity.run(current_producer) + # The default of a write in an Activity is that Producer, and it reads no client. + assert activity.run(_support.default_producer, cast(Any, None)) == producer + return producer + + +def _expected_producer(writer: _WriterInfo) -> Producer: + """Return the whole Producer of ``writer``, built field by field.""" + time = Timestamp() + time.FromDatetime(writer.time) + producer = Producer() + kind = getattr(producer, writer.kind) + kind.namespace, kind.run_id = writer.namespace, writer.run_id + if writer.kind != "standalone_activity": + kind.workflow_id = writer.workflow_id + if writer.kind == "workflow": + return producer + kind.activity_id = writer.activity_id + kind.attempt.attempt = writer.attempt + if writer.kind == "local_activity": + task = kind.attempt.task + task.started_event_id, task.attempt = writer.event_id, writer.attempt + 1 + task.started_time.CopyFrom(time) + else: + kind.attempt.attempt_scheduled_time.CopyFrom(time) + if writer.kind == "workflow_activity": + kind.scheduled_event_id = writer.event_id + return producer + + +@pytest.mark.parametrize( + ("kind", "event_id"), + [ + ("workflow", 7), + ("local_activity", 9), + ("workflow_activity", 0), + ("workflow_activity", 17), + ("standalone_activity", 0), + ], +) +def test_a_writer_keeps_its_identity_and_attempt(kind: str, event_id: int) -> None: + writer = _WriterInfo( + kind=kind, + namespace="ns:/é", + workflow_id="workflow", + run_id="run", + activity_id="activity", + attempt=3, + time=datetime(2026, 1, 1, tzinfo=timezone.utc), + event_id=event_id, + ) + producer = _default_producer(writer) + assert _producer_proto(producer) == _expected_producer(writer) + converter = temporalio.converter.PayloadConverter.default + # Heartbeat details can be decoded without a type hint. + [stored] = converter.from_payloads(converter.to_payloads([producer])) + assert as_producer(stored) == producer + assert as_producer(producer) is producer + + +def test_a_client_uses_one_producer_for_all_its_streams() -> None: + service_client = Mock(spec=ServiceClient) + config = StreamConfig(stores=[FaultStore()]) + clients = [Client(service_client, stream_config=config) for _ in range(2)] + [first, second, third] = [ + _producer_proto( + _support.default_producer(client.get_stream(StreamRef(id=id))._nexus_client) + ) + for client, id in ((clients[0], "a"), (clients[0], "b"), (clients[1], "a")) + ] + assert first == second != third + assert first.client.namespace == "default" and first.client.id + + +@dataclasses.dataclass +class _Turn: + text: str + + +@pytest.mark.parametrize( + ("hint", "ref", "body_type"), + [ + (StreamRef[int], StreamRef[int](id="count", store="a"), int), + (StreamRef[str], StreamRef[str](id="text"), str), + (StreamRef[_Turn], StreamRef[_Turn](id="turn", store="b"), _Turn), + (StreamRef, StreamRef(id="untyped"), object), + (StreamRef[int] | None, None, None), + (StreamRef[str] | None, StreamRef[str](id="optional"), str), + ], +) +def test_a_stream_ref_keeps_its_body_type( + hint: Any, ref: StreamRef[Any] | None, body_type: type | None +) -> None: + converter = temporalio.converter.DataConverter.default.payload_converter + client = Client( + Mock(spec=ServiceClient), stream_config=StreamConfig([FaultStore()]) + ) + [decoded] = converter.from_payloads(converter.to_payloads([ref]), [hint]) + assert decoded == ref + if decoded is not None: + for get_stream in (client.get_stream, temporalio.workflow.get_stream): + assert get_stream(decoded).body_type is body_type + + +@dataclasses.dataclass +class _RefFields: + typed: StreamRef[_Turn] + untyped: StreamRef + nested: list[StreamRef[int] | None] + + +def test_stream_ref_fields_keep_their_body_types_inside_lists() -> None: + value = [ + _RefFields( + typed=StreamRef[_Turn](id="turn", store="a"), + untyped=StreamRef(id="untyped"), + nested=[StreamRef[int](id="count"), None], + ) + ] + converter = temporalio.converter.DataConverter.default.payload_converter + client = Client( + Mock(spec=ServiceClient), stream_config=StreamConfig([FaultStore()]) + ) + [decoded] = converter.from_payloads( + converter.to_payloads([value]), [list[_RefFields]] + ) + assert decoded == value + [fields] = decoded + assert fields.nested[1] is None + for get_stream in (client.get_stream, temporalio.workflow.get_stream): + assert get_stream(fields.typed).body_type is _Turn + assert get_stream(fields.untyped).body_type is object + assert get_stream(fields.nested[0]).body_type is int + + +def test_each_stream_module_can_be_the_first_import() -> None: + system = temporalio.nexus.system + modules = [ + "temporalio.client._stream_store", + "temporalio.testing._stream_store", + "temporalio.contrib.streams", + "temporalio.workflow", + system.__name__, + *( + module.name + for module in pkgutil.walk_packages(system.__path__, system.__name__ + ".") + ), + ] + + def first_import(module: str) -> str: + imported = subprocess.run( + [sys.executable, "-c", f"import {module}"], capture_output=True, text=True + ) + return imported.stderr if imported.returncode else "" + + with concurrent.futures.ThreadPoolExecutor(8) as pool: + for module, error in zip(modules, pool.map(first_import, modules)): + assert not error, f"{module}: {error}" + + +def test_a_client_call_past_its_rpc_timeout_cancels_the_store_call() -> None: + async def script() -> None: + loop = asyncio.get_running_loop() + store, hold = FaultStore(), Hold() + store.faults["describe_stream"].append(hold) + client = Client(Mock(spec=ServiceClient), stream_config=StreamConfig([store])) + stream = client.get_stream(StreamRef[str](id="s")) + with pytest.raises(StreamError) as timed_out: + await stream.describe(rpc_timeout=timedelta(seconds=5)) + assert timed_out.value.reason == _UNAVAILABLE + assert loop.time() == 5 + assert hold.cancelled.is_set() + assert asyncio.all_tasks() == {asyncio.current_task()} + + run_with_virtual_clock(script()) + + +def test_a_client_iterator_on_an_idle_stream_waits_between_reads() -> None: + # The Streams of a MemoryStreamStore with no call through the threads of Core, so + # the virtual clock doesn't jump past a wait while an append is on its way. + class ReadLog(_MemoryStreams): + def __init__(self) -> None: + super().__init__( + "memory", retention=timedelta(days=1), resend_window=16, fence=False + ) + self.reads: list[proto.ReadRecordsRequest] = [] + + async def read_records( + self, request: proto.ReadRecordsRequest + ) -> proto.ReadRecordsResponse: + self.reads.append(request) + return await super().read_records(request) + + def waits(store: ReadLog) -> list[timedelta | None]: + return [ + request.wait.ToTimedelta() if request.HasField("wait") else None + for request in store.reads + ] + + async def script() -> None: + loop = asyncio.get_running_loop() + store = ReadLog() + client = Client(Mock(spec=ServiceClient), stream_config=StreamConfig([store])) + stream = await client.create_stream(id="s", body_type=int) + minute = _support.DEFAULT_READ_WAIT + ten, nine = timedelta(seconds=10), timedelta(seconds=9) + # With no wait, the first read answers at once and each later one waits the + # default wait. A wait of zero is the caller's choice to read in a loop, and + # the Store gets no wait for it. A wait ends before the rpc_timeout, so the + # Store answers in time. + cases: list[tuple[timedelta | None, timedelta | None, list[Any]]] = [ + (None, None, [None, minute, minute, minute, minute]), + (ten, None, [ten] * 5), + (timedelta(0), None, [None] * 5), + (None, ten, [None, nine, nine, nine, nine]), + (minute, ten, [nine] * 5), + (timedelta(seconds=5), ten, [timedelta(seconds=5)] * 5), + # A Store has a tenth of a short timeout to answer, and a timeout of + # zero is no timeout. + (ten, timedelta(seconds=2), [timedelta(seconds=1.8)] * 5), + (ten, timedelta(0), [ten] * 5), + ] + for wait, rpc_timeout, expected in cases: + with failure_note(f"wait {wait}, rpc_timeout {rpc_timeout}"): + store.reads.clear() + start = loop.time() + pages = stream.read_pages(wait=wait, rpc_timeout=rpc_timeout) + for _ in expected: + assert not (await anext(pages)).records + await pages.aclose() + assert waits(store) == expected + assert loop.time() - start == pytest.approx( + sum(w.total_seconds() for w in expected if w) + ) + + # A Record that comes during a wait ends it at once, and the caller stops. + async def append_later() -> None: + await asyncio.sleep(90) + await stream.append(1) + + store.reads.clear() + start = loop.time() + appending = asyncio.create_task(append_later()) + async with asyncio.timeout(600): + async for record in stream.read(): + assert record.body == 1 + break + await appending + assert loop.time() - start == pytest.approx(90) + assert waits(store) == [None, minute, minute] + + run_with_virtual_clock(script()) + + +@pytest.mark.parametrize( + "offsets, last_offset, expected", + [ + ([b"b", b"c"], b"d", b"d"), + ([b"b", b"c"], None, b"c"), + ([], None, b"a"), + ], +) +def test_the_next_read_uses_the_position_covered_by_the_page( + offsets: list[bytes], last_offset: bytes | None, expected: bytes +) -> None: + request = ReadRecordsRequest(ref=StreamRef[int](id="s"), from_offset=b"a") + page = ReadRecordsResponse( + records=[ + StreamRecord(body=i, offset=offset) for i, offset in enumerate(offsets) + ], + last_offset=last_offset, + ) + next_request = _support.next_read_request(request, page) + assert next_request is not None and next_request.from_offset == expected + + +def test_a_page_with_no_last_offset_ends_at_its_last_record() -> None: + async def unset(call: Callable[[], Awaitable[Any]]) -> Any: + page = await call() + page.ClearField("last_offset") + return page + + async def script() -> None: + store = FaultStore() + client = Client(Mock(spec=ServiceClient), stream_config=StreamConfig([store])) + stream = await client.create_stream(id="s", body_type=int) + await stream.append(1, 2) + store.faults["read_records"].extend([unset, unset]) + page = await stream.read_page() + assert page.last_offset == page.records[-1].offset + # A page with no Record ends where its read started. + empty = await stream.read_page(from_offset=page.last_offset) + assert (empty.records, empty.last_offset) == ([], page.last_offset) + + run_with_virtual_clock(script()) + + +@pytest.mark.parametrize("by_page", [False, True]) +async def test_zero_wait_poll_can_be_cancelled_after_an_empty_page( + by_page: bool, +) -> None: + class IdleStore(_MemoryStreams): + reads: int = 0 + + async def read_records( + self, request: proto.ReadRecordsRequest + ) -> proto.ReadRecordsResponse: + assert not request.HasField("wait") + self.reads += 1 + assert self.reads == 1, "another poll ran before the pending cancellation" + return proto.ReadRecordsResponse() + + store = IdleStore( + "memory", retention=timedelta(days=1), resend_window=16, fence=False + ) + client = Client(Mock(spec=ServiceClient), stream_config=StreamConfig([store])) + stream = await client.create_stream(id="s", body_type=int) + + async def consume() -> None: + if by_page: + async for page in stream.read_pages(wait=timedelta(0)): + assert not page.records + else: + _ = await anext(stream.read(wait=timedelta(0))) + + task = asyncio.create_task(consume()) + _ = asyncio.get_running_loop().call_soon(task.cancel) + with pytest.raises(asyncio.CancelledError): + await task + assert store.reads == 1 diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py new file mode 100644 index 0000000000..b6a2a001a6 --- /dev/null +++ b/tests/nexus/test_streams_with_worker.py @@ -0,0 +1,1499 @@ +"""Tests of Streams with a Worker on the test server.""" + +import asyncio +import dataclasses +import hashlib +import itertools +import random +from collections.abc import Sequence +from datetime import timedelta +from typing import Any + +import pytest +from google.protobuf.message import Message + +from temporalio import activity, workflow +from temporalio.api.enums.v1 import EventType, StreamErrorReason, TaskQueueType +from temporalio.api.sdk.v1.external_storage_pb2 import ExternalStorageReference +from temporalio.api.streamservice.v1 import ( + AppendRecordsRequest, + CreateStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, +) +from temporalio.api.taskqueue.v1 import TaskQueue +from temporalio.api.workflowservice.v1 import DescribeTaskQueueRequest +from temporalio.client import Client, StreamConfig, WorkflowFailureError +from temporalio.converter import ( + DataConverter, + ExternalStorage, +) +from temporalio.exceptions import ApplicationError, StreamError +from temporalio.nexus.system.stream_service import StreamIdConflictPolicy, StreamRef +from temporalio.testing import MemoryStreamStore +from temporalio.worker import ( + ActivityInboundInterceptor, + Interceptor, + Replayer, + Worker, +) +from tests.helpers import assert_eventually, assert_task_fail_eventually +from tests.helpers.streams import ( + ContextCodec, + FaultStore, + Hold, + RunOptions, + answers, + failure_note, + loses_answer, + raises, + run, + stream_client, +) +from tests.test_extstore import InMemoryTestDriver + + +async def _answers( + api: Any, calls: Sequence[Sequence[Any]], store: str | None = None +) -> list[Any]: + """Make each generated Stream call in turn and return what each one gave. + + ``api`` is a client or the ``temporalio.workflow`` module, which both have + ``create_stream`` and ``get_stream``. ``store`` is the Store name of each ref. + """ + streams: dict[str, Any] = {} + answers: list[Any] = [] + for operation, stream_id, *args in calls: + stream = streams.get(stream_id) or api.get_stream( + StreamRef[int](id=stream_id, store=store) + ) + try: + if operation == "create": + policy = StreamIdConflictPolicy(args[0]) if args and args[0] else None + stream = await api.create_stream( + id=stream_id, store=store, id_conflict_policy=policy, body_type=int + ) + streams[stream_id] = stream + answers.append([stream.ref.store, stream.created]) + elif operation == "append": + appended = await stream.append(*args[0]) + answers.append( + [appended.first_offset.hex(), appended.last_offset.hex()] + ) + elif operation == "read": + page = await stream.read_page() + bodies = [record.body for record in page.records] + answers.append([bodies, (page.last_offset or b"").hex()]) + else: + described = await stream.describe() + answers.append([(described.last_offset or b"").hex()]) + except StreamError as err: + answers.append(["error", err.reason, err.message]) + return answers + + +@activity.defn +async def _calls_activity(calls: list[list[Any]]) -> list[Any]: + return await _answers(activity.client(), calls) + + +@workflow.defn +class _CallsWorkflow: + @workflow.run + async def run(self, calls: list[list[Any]], in_activity: bool = False) -> list[Any]: + if in_activity: + return await workflow.execute_activity( + _calls_activity, calls, start_to_close_timeout=timedelta(seconds=10) + ) + return await _answers(workflow, calls) + + +def _writes(store: FaultStore) -> list[Message]: + """Return each request of a Store but its reads, which Core pages in its own way, + without the Producer, which differs between two writers of the same call. + """ + writes: list[Message] = [] + for request in store.requests: + if isinstance(request, ReadRecordsRequest): + continue + copy = type(request)() + copy.CopyFrom(request) + if "producer" in copy.DESCRIPTOR.fields_by_name: + copy.ClearField("producer") + writes.append(copy) + return writes + + +async def test_workflow_code_and_a_client_get_the_same_answers(client: Client) -> None: + for seed in range(8): + with failure_note(f"seed {seed}"): + rng = random.Random(seed) + # One run sends one request id with each of its creates, so a second create + # of a Stream would be the first one again for a Workflow and not for a client. + calls: list[list[Any]] = [ + ["create", f"s-{seed}-{number}", rng.randrange(3)] for number in (0, 1) + ] + operations = ["append", "append", "append", "describe"] + reads = seed % 2 == 1 + if reads: + operations += ["read", "read"] + for _ in range(rng.randrange(4, 12)): + # The third Stream is never created. + stream_id = f"s-{seed}-{rng.choice([0, 0, 0, 1, 1, 2])}" + operation = rng.choice(operations) + if operation == "append": + bodies = [rng.randrange(100) for _ in range(rng.randrange(1, 4))] + calls.append(["append", stream_id, bodies]) + else: + calls.append([operation, stream_id]) + if reads: + calls += [["read", f"s-{seed}-0"], ["read", f"s-{seed}-1"]] + # The two Stores have one name and the same Stream ids, so a call is the same + # request in both. + for_client, for_workflow = FaultStore(), FaultStore() + from_client = await _answers(stream_client(client, for_client), calls) + workflow_client = stream_client(client, for_workflow) + ran = await run(workflow_client, RunOptions(_CallsWorkflow, [calls])) + assert ran.result == from_client + assert _writes(for_workflow) == _writes(for_client) + appends = [ + request_id + for request, request_id in for_workflow.calls + if isinstance(request, AppendRecordsRequest) + ] + assert all(appends) and len(set(appends)) == len(appends) + # A replay with the Stores of the run writes nothing. A replay chooses the + # Store of each call again, so one with no Stream config fails. + written = _writes(for_workflow) + await Replayer( + workflows=[_CallsWorkflow], + stream_config=workflow_client._config["stream_config"], + ).replay_workflow(ran.history) + assert _writes(for_workflow) == written + with pytest.raises(Exception, match="no stream_config"): + await Replayer(workflows=[_CallsWorkflow]).replay_workflow(ran.history) + + +def _bodies(writer: str) -> list[Any]: + """Return the bodies that a writer appends. One is a value that a pass of external + storage would take for a reference into the storage of the Worker. + """ + claim = ExternalStorageReference( + driver_name="test-driver", claim_data={"key": "payload-0"} + ) + return [f"{writer} plain", {"writer": writer}, claim] + + +def _digest(bodies: Sequence[Any]) -> str: + """Return a digest of bodies, so that a Workflow result has no body in it.""" + return hashlib.sha256(repr(bodies).encode()).hexdigest() + + +@activity.defn +async def _append_bodies(stream_id: str) -> None: + stream = activity.client().get_stream(StreamRef(id=stream_id)) + await stream.append(*_bodies("activity")) + + +@workflow.defn +class _BodiesWorkflow: + @workflow.run + async def run(self, stream_id: str) -> str: + await workflow.execute_activity( + _append_bodies, stream_id, start_to_close_timeout=timedelta(seconds=10) + ) + stream = workflow.get_stream(StreamRef[Any](id=stream_id)) + await stream.append(*_bodies("workflow")) + bodies: list[Any] = [] + async for record in stream.read(): + bodies.append(record.body) + # A Stream has no end, so the reader stops at the Records of the 3 writers. + if len(bodies) == 3 * len(_bodies("workflow")): + break + return _digest(bodies) + + +async def test_a_body_reads_the_same_on_every_path(client: Client) -> None: + store, driver = FaultStore(), InMemoryTestDriver() + converter = dataclasses.replace( + DataConverter.default, + payload_codec=ContextCodec(), + external_storage=ExternalStorage(drivers=[driver], payload_size_threshold=0), + ) + client = stream_client(client, store, data_converter=converter) + stream = await client.create_stream(id="bodies") + await stream.append(*_bodies("client")) + options = RunOptions(_BodiesWorkflow, ["bodies"], activities=[_append_bodies]) + ran = await run(client, options) + + expected = [*_bodies("client"), *_bodies("activity"), *_bodies("workflow")] + # A Stream has no end, so the reader takes the Records that it knows of. + records = stream.read() + async with asyncio.timeout(10): + assert [(await anext(records)).body for _ in expected] == expected + assert ran.result == _digest(expected) + # The Store has each body as the codec gave it with no context, and the storage of + # the Worker has none of them. + stored = await store.memory.read_records(ReadRecordsRequest(stream_id="bodies")) + assert [dict(record.body.metadata) for record in stored.records] == [ + {"encoding": b"test/wrapped", "context": b"NoneType"} + ] * len(expected) + assert driver._storage and not any( + b" plain" in value for value in driver._storage.values() + ) + + +@activity.defn +async def _append_one(stream_id: str) -> None: + await activity.client().get_stream(StreamRef[int](id=stream_id)).append(1) + + +@workflow.defn +class _OneActivityIdWorkflow: + @workflow.run + async def run(self, stream_id: str) -> None: + for _ in range(2): + await workflow.execute_activity( + _append_one, + stream_id, + activity_id="one id", + start_to_close_timeout=timedelta(seconds=10), + ) + + +async def test_two_activities_with_one_id_write_as_two_producers( + client: Client, +) -> None: + store = FaultStore() + client = stream_client(client, store) + await client.create_stream(id="one id", body_type=int) + options = RunOptions(_OneActivityIdWorkflow, ["one id"], activities=[_append_one]) + ran = await run(client, options) + # The Producer of each Activity has the id of the Activity's scheduled event. + scheduled = _events(ran.history, EventType.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED) + page = await store.memory.read_records(ReadRecordsRequest(stream_id="one id")) + producers = [record.producer.workflow_activity for record in page.records] + assert [(p.activity_id, p.scheduled_event_id) for p in producers] == [ + ("one id", event.event_id) for event in scheduled + ] + + +def _events(history: Any, event_type: EventType.ValueType) -> list[Any]: + return [event for event in history.events if event.event_type == event_type] + + +def _stream_markers(history: Any, kind: str) -> list[Any]: + """Return the markers in which Core records the Stream calls of ``kind``, which + is ``append`` or ``read``. + """ + return [ + event + for event in _events(history, EventType.EVENT_TYPE_MARKER_RECORDED) + if event.marker_recorded_event_attributes.marker_name == f"core_stream_{kind}" + ] + + +async def test_a_store_error_is_the_same_error_on_every_path(client: Client) -> None: + store = FaultStore() + client = stream_client(client, store) + await client.create_stream(id="errors", body_type=int) + append: list[Any] = ["append", "errors", [1]] + appends = store.faults["append_records"] + unavailable = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE + + async def answers_on( + path: str, calls: list[list[Any]], on: Client = client, **options: Any + ) -> Any: + if path == "client": + return await _answers(on, calls) + args = [calls, path == "activity"] + run_options = RunOptions( + _CallsWorkflow, args, activities=[_calls_activity], **options + ) + return (await run(on, run_options)).result + + def append_request_ids() -> list[str | None]: + calls, store.calls = store.calls, [] + return [i for r, i in calls if isinstance(r, AppendRecordsRequest)] + + # Core tries an append again in an outage of the Store, with one request id, so the + # Store writes it once. Workflow code gets no error, and History has no failure. + outages = [ + [raises(StreamError("The Store is down", reason=unavailable))] * 2, + [loses_answer()], + [raises(ConnectionError("The connection is gone"))], + ] + for at, faults in enumerate(outages): + with failure_note(f"outage {at}"): + appends.extend(faults) + ran = await run(client, RunOptions(_CallsWorkflow, [[append]])) + offset = (at + 1).to_bytes(8, "big").hex() + assert ran.result == [[offset, offset]] + request_ids = append_request_ids() + assert len(request_ids) == len(faults) + 1 + assert len(set(request_ids)) == 1 + assert not _events(ran.history, EventType.EVENT_TYPE_WORKFLOW_TASK_FAILED) + # A client and an Activity get the outage as the error of their call. + for path in ("client", "activity"): + appends.append(raises(ConnectionError("The connection is gone"))) + [[error, reason, _]] = await answers_on(path, [append]) + assert (error, reason, len(append_request_ids())) == ("error", unavailable, 1) + + # An answer of the wrong message fails the call, and nothing tries it again. + corrupt = StreamErrorReason.STREAM_ERROR_REASON_STORE_CORRUPT + for path in ("client", "activity", "workflow"): + with failure_note(path): + appends.append(answers(DescribeStreamResponse())) + [[error, reason, _]] = await answers_on(path, [append]) + assert (error, reason, len(append_request_ids())) == ("error", corrupt, 1) + + # A refusal is the same error for a client, an Activity and Workflow code. Workflow + # code gets it again in each task that replays the call. + not_found = StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND + calls: list[list[Any]] = [ + ["append", "missing", [1]], + ["describe", "errors"], + ["describe", "missing"], + ["read", "missing"], + ] + refused = await answers_on("client", calls) + assert [answer[:2] for answer in refused] == [ + ["error", not_found], + [(3).to_bytes(8, "big").hex()], + ["error", not_found], + ["error", not_found], + ] + for path in ("activity", "workflow"): + with failure_note(path): + assert await answers_on(path, calls, cached=False, replay=True) == refused + + # When its Retention has passed since its last append, a Stream refuses each call + # as expired, on each path. + expiring = stream_client(client, FaultStore(retention=timedelta(seconds=2))) + stream = await expiring.create_stream(id="expires", body_type=int) + await stream.append(1) + await asyncio.sleep(2.5) + expired = StreamErrorReason.STREAM_ERROR_REASON_EXPIRED + calls = [["append", "expires", [2]], ["describe", "expires"], ["read", "expires"]] + for path in ("client", "activity", "workflow"): + with failure_note(f"expired, {path}"): + answered = await answers_on(path, calls, on=expiring, replay=True) + assert [answer[:2] for answer in answered] == [["error", expired]] * 3 + + # An outage during a create fails the Workflow Task, also on a Worker that fails a + # Workflow for any exception. The create runs in the next task, with the Store back. + for failure_types in ([], [Exception]): + with failure_note(f"failure types {failure_types}"): + store.faults["create_stream"].append(raises(ConnectionError("down"))) + options = RunOptions( + _CallsWorkflow, + [[["create", f"after an outage {len(failure_types)}"]]], + worker={"workflow_failure_exception_types": failure_types}, + ) + ran = await run(client, options) + assert ran.result == [["memory", True]] + # History has nothing of the outage but the task failure. + events = [event.event_type for event in ran.history.events] + task_done = events.index(EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED) + assert set(events[1:task_done]) == { + EventType.EVENT_TYPE_WORKFLOW_TASK_SCHEDULED, + EventType.EVENT_TYPE_WORKFLOW_TASK_STARTED, + EventType.EVENT_TYPE_WORKFLOW_TASK_FAILED, + } + assert events[task_done + 1 :] == [ + EventType.EVENT_TYPE_MARKER_RECORDED, + EventType.EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED, + ] + + +class _DownReadsStore(FaultStore): + """A Store whose reads fail as an outage until :py:attr:`up` is true.""" + + def __init__(self) -> None: + super().__init__() + self.up = False + + async def read_records(self, request: ReadRecordsRequest) -> Any: + if not self.up: + self.calls.append((request, None)) + raise ConnectionError("The connection is gone") + return await super().read_records(request) + + +async def test_a_store_outage_at_a_workflow_read_fails_the_workflow_task( + client: Client, +) -> None: + store = _DownReadsStore() + client = stream_client(client, store) + await (await client.create_stream(id="down", body_type=int)).append(1) + + async def back_after_a_task_failure(handle: Any, _worker: Any) -> None: + await assert_task_fail_eventually(handle) + store.up = True + + # SDK Core tries the read again up to the read limit, and then fails the task, as + # for an append. Workflow code gets no error, also on a Worker that fails a + # Workflow for any exception, and the read runs in the next task. + for failure_types in ([], [Exception]): + with failure_note(f"failure types {failure_types}"): + store.up = False + options = RunOptions( + _CallsWorkflow, + [[["read", "down"]]], + task_timeout=timedelta(seconds=2), + worker={"workflow_failure_exception_types": failure_types}, + during=back_after_a_task_failure, + ) + ran = await run(client, options) + assert ran.result == [[[1], (1).to_bytes(8, "big").hex()]] + failed = _events(ran.history, EventType.EVENT_TYPE_WORKFLOW_TASK_FAILED) + assert failed + for event in failed: + message = event.workflow_task_failed_event_attributes.failure.message + assert message.startswith("StreamStoreUnavailable:"), message + + +@workflow.defn +class _CatchingWorkflow: + @workflow.run + async def run(self, call: list[Any], store: str | None) -> str: + try: + await _answers(workflow, [call], store) + except Exception: + pass + return "caught" + + +async def test_a_stream_call_with_no_store_fails_the_workflow_task( + client: Client, +) -> None: + async def task_fails(handle: Any, _worker: Any) -> None: + await assert_task_fail_eventually(handle) + await handle.terminate() + + cases = { + "no Stream config": (client, None), + "a ref of a Store that the Worker lacks": ( + stream_client(client, FaultStore()), + "other", + ), + } + calls: list[list[Any]] = [ + ["create", "s"], + ["append", "s", [1]], + ["describe", "s"], + ["read", "s"], + ] + # The task fails also on a Worker that fails a Workflow for any exception. + for (case, (worker_client, store)), call, failure_types in itertools.product( + cases.items(), calls, ([], [Exception]) + ): + with failure_note(f"{call[0]} with {case} and {failure_types}"): + options = RunOptions( + _CatchingWorkflow, + [call, store], + worker={"workflow_failure_exception_types": failure_types}, + during=task_fails, + ) + ran = await run(worker_client, options) + # The Workflow didn't go on after the error that it caught, and History + # has nothing of the call. + assert isinstance(ran.result, WorkflowFailureError) + assert not _events(ran.history, EventType.EVENT_TYPE_MARKER_RECORDED) + + +class _ActivityTypes(Interceptor): + """Logs the type of each Activity that its Worker runs.""" + + def __init__(self) -> None: + super().__init__() + self.types: list[str] = [] + + def intercept_activity( + self, next: ActivityInboundInterceptor + ) -> ActivityInboundInterceptor: + self.types.append(activity.info().activity_type) + return next + + +async def test_a_worker_with_only_workflows_creates_a_stream(client: Client) -> None: + client = stream_client(client, FaultStore()) + interceptor = _ActivityTypes() + pollers: list[Any] = [] + + async def activity_pollers(handle: Any, worker: Worker) -> None: + await handle.result() + described = await client.workflow_service.describe_task_queue( + DescribeTaskQueueRequest( + namespace=client.namespace, + task_queue=TaskQueue(name=worker.task_queue), + task_queue_type=TaskQueueType.TASK_QUEUE_TYPE_ACTIVITY, + ) + ) + pollers.extend(described.pollers) + + options = RunOptions( + _CallsWorkflow, + [[["create", "alone"], ["describe", "alone"]]], + worker={"interceptors": [interceptor]}, + during=activity_pollers, + ) + ran = await run(client, options) + assert ran.result == [["memory", True], [""]] + assert interceptor.types == ["__temporal_stream_store_call"] * 2 + assert not pollers + + +@activity.defn +async def _append_to(stream_id: str) -> None: + stream = activity.client().get_stream(StreamRef[int](id=stream_id)) + await stream.append(3) + + +@workflow.defn +class _SwapWorkflow: + def __init__(self) -> None: + self._swapped = False + + @workflow.signal + def swapped(self) -> None: + self._swapped = True + + @workflow.run + async def run(self, own: str, shared: str) -> str | None: + created = await workflow.create_stream(id=own, body_type=int) + await workflow.wait_condition(lambda: self._swapped) + await created.append(1) + stream = workflow.get_stream(StreamRef[int](id=shared)) + await stream.append(2) + await workflow.execute_activity( + _append_to, shared, start_to_close_timeout=timedelta(seconds=10) + ) + return created.ref.store + + +def _calls(store: FaultStore) -> list[tuple[str, str]]: + """Return the request type and the Stream id of each call of a Store.""" + return [(type(r).__name__, r.stream_id) for r in store.requests] + + +# On a server with worker commands, a lone Worker polls in a loop after a new client. Marked as +# `test_workflow_replace_worker_client` and `test_nexus_client_updates_when_worker_client_changes`. +@pytest.mark.requires_local_server +async def test_a_worker_uses_the_stream_config_of_its_new_client( + client: Client, +) -> None: + for cached in (True, False): + with failure_note(f"cached {cached}"): + first, second = FaultStore("first"), FaultStore("second") + # The new client has other Store objects, with the Streams of the first ones. + new_first, new_second = FaultStore("first"), FaultStore("second") + new_first.memory = first.memory + selects: list[tuple[str, str | None]] = [] + + def pick_first(context: Any) -> FaultStore: + selects.append((type(context.target).__name__, context.namespace)) + return first + + before = stream_client(client, first, second, store_selector=pick_first) + after = stream_client( + client, new_first, new_second, store_selector=lambda _: new_second + ) + await after.create_stream(id="shared", body_type=int) + + async def swap(handle: Any, worker: Worker) -> None: + async def created() -> None: + assert first.requests + + await assert_eventually(created) + # A client with other Store names or other limits is refused. + for other in ( + stream_client(client, FaultStore("third")), + stream_client( + client, + first, + second, + store_selector=pick_first, + max_batch_records=1, + ), + ): + with pytest.raises(ValueError): + worker.client = other + worker.client = after + await handle.signal(_SwapWorkflow.swapped) + + options = RunOptions( + _SwapWorkflow, + ["own", "shared"], + activities=[_append_to], + cached=cached, + during=swap, + ) + # The created Stream stays on its Store. A ref with no Store name goes to the + # Store that the new selector picks, in Workflow code as in an Activity. + assert (await run(before, options)).result == "first" + assert _calls(first) == [("CreateStreamRequest", "own")] + # After the swap, Core calls the Store objects of the new client. + assert _calls(new_first) == [("AppendRecordsRequest", "own")] + assert _calls(new_second) == [ + ("CreateStreamRequest", "shared"), + ("AppendRecordsRequest", "shared"), + ("AppendRecordsRequest", "shared"), + ] + assert not second.requests + # The selector of the Workflow's create got the Workflow as its target, and the + # namespace of the Worker. + assert selects == [("StorageDriverWorkflowInfo", client.namespace)] + + +@workflow.defn +class _AppendOnceWorkflow: + @workflow.run + async def run(self, stream_id: str) -> None: + await workflow.get_stream(StreamRef[int](id=stream_id)).append(1) + + +async def test_a_replay_fails_when_the_selector_picks_another_store( + client: Client, +) -> None: + first, second = FaultStore("first"), FaultStore("second") + for store in (first, second): + await stream_client(client, store).create_stream(id="picked", body_type=int) + options = RunOptions(_AppendOnceWorkflow, ["picked"]) + ran = await run( + stream_client(client, first, second, store_selector=lambda _: first), options + ) + assert ran.result is None + for picked in (first, second): + with failure_note(f"replay picks {picked.name()}"): + + def select(_: Any) -> FaultStore: + return picked + + config = StreamConfig([first, second], store_selector=select) + replay = Replayer(workflows=[_AppendOnceWorkflow], stream_config=config) + if picked is first: + await replay.replay_workflow(ran.history) + continue + # SDK Core compares the Store of a replayed append with History. + with pytest.raises(workflow.NondeterminismError, match="Store `first`"): + await replay.replay_workflow(ran.history) + + +async def test_an_append_over_a_limit_of_the_config_never_reaches_the_store( + client: Client, +) -> None: + too_large = StreamErrorReason.STREAM_ERROR_REASON_TOO_LARGE + unsupported = StreamErrorReason.STREAM_ERROR_REASON_UNSUPPORTED + default_bytes = 4 * 1024 * 1024 + for seed in range(12): + with failure_note(f"seed {seed}"): + rng = random.Random(seed) + # One seed in four has limits over the defaults, which only the config bounds. + larger = seed % 4 == 0 + record = rng.choice([1000, 3000, 1536 * 1024]) + batch = ( + default_bytes if larger else rng.choice([4000, 20_000, default_bytes]) + ) + count = 1200 if larger else rng.choice([1, 3, 1000]) + # The body sizes of each batch, and whether the batch is within every limit. + # A stored Record counts its Producer, so no size is within 500 bytes of a + # limit, and the test needs no size logic. + batches: list[tuple[list[int], bool]] = [] + if larger: + batches.append(([0] * 1100, True)) + for _ in range(6): + match rng.choice(["fits", "fits", "records", "record", "batch"]): + case "records": + batches.append(([0] * (count + 1), False)) + case "record" if record <= 3000: + batches.append(([2 * record], False)) + case "batch" if batch <= 20_000: + size = min(record, batch) - 500 + batches.append(([size] * (batch // size + 1), False)) + case _: + fits = [rng.randrange(40)] * rng.randrange(1, min(count, 3) + 1) + batches.append((fits, True)) + store = FaultStore() + streams = stream_client( + client, + store, + max_record_bytes=record, + max_batch_bytes=batch, + max_batch_records=count, + ) + + def calls(stream_id: str) -> list[list[Any]]: + appends = [["x" * size for size in sizes] for sizes, _ in batches] + return [["create", stream_id]] + [ + ["append", stream_id, bodies] for bodies in appends + ] + + from_client = await _answers(streams, calls(f"client {seed}")) + workflow_calls = calls(f"workflow {seed}") + if record <= 3000: + # A client with a larger limit writes a Record over the limit of the + # Worker, and a read of Workflow code refuses that Record. + writer = stream_client(client, store) + large = await writer.create_stream(id=f"large {seed}", body_type=str) + await large.append("x" * 2 * record) + workflow_calls.append(["read", f"large {seed}"]) + options = RunOptions(_CallsWorkflow, [workflow_calls], replay=True) + from_workflow = (await run(streams, options)).result + if record <= 3000: + assert from_workflow.pop()[:2] == ["error", unsupported] + for answers in (from_client, from_workflow): + assert [ + "written" if answer[0] != "error" else answer[1] + for answer in answers[1:] + ] == ["written" if fits else too_large for _, fits in batches] + # The Store got the batches within the limits from each path, and no other. + assert [ + len(request.records) + for request in store.requests + if isinstance(request, AppendRecordsRequest) + and request.stream_id != f"large {seed}" + ] == [len(sizes) for sizes, fits in batches if fits] * 2 + + +@workflow.defn +class _ChainWorkflow: + @workflow.run + async def run(self, stream_id: str, runs: int) -> bool | None: + stream = await workflow.create_stream(id=stream_id) + if runs > 1: + workflow.continue_as_new(args=[stream_id, runs - 1]) + return stream.created + + +async def test_a_create_in_a_later_run_of_the_chain_is_the_same_create( + client: Client, +) -> None: + store = FaultStore() + # The Store loses the answer of the first create of each run, so the Workflow Task + # fails after its create ran, and its next attempt makes the create again. + faults = [loses_answer(), lambda call: call(), loses_answer()] + store.faults["create_stream"].extend(faults) + ran = await run( + stream_client(client, store), RunOptions(_ChainWorkflow, ["chain", 2]) + ) + # Each run makes its create twice, and the Store takes all four for one create. + assert ran.result is True + creates = [i for r, i in store.calls if isinstance(r, CreateStreamRequest)] + assert len(creates) == 4 and len(set(creates)) == 1 + + +_handled: dict[int, asyncio.Event] = {} +"""An event for each Record of the writing Activity, set once the Workflow handled it.""" + + +@activity.defn +async def _write_one_by_one(stream_id: str, count: int) -> None: + client = activity.client() + stream = client.get_stream(StreamRef[str](id=stream_id)) + workflow_id = activity.info().workflow_id or "" + for number in range(count): + await stream.append(f"a body, number {number}") + # A read makes no Workflow Task for a Record that SDK Core doesn't know of, so + # the writer signals the Workflow. + await client.get_workflow_handle(workflow_id).signal(_ReadingWorkflow.wake) + # The next Record comes only once the Workflow has handled this one. + await _handled[number].wait() + + +@activity.defn +async def _handle(number: int) -> None: + _handled[number].set() + + +@workflow.defn +class _ReadingWorkflow: + @workflow.signal + def wake(self) -> None: + pass + + @workflow.run + async def run(self, stream_id: str, count: int) -> list[int]: + stream = await workflow.create_stream(id=stream_id, body_type=str) + writer = workflow.start_activity( + _write_one_by_one, + args=[stream_id, count], + start_to_close_timeout=timedelta(seconds=30), + ) + numbers: list[int] = [] + async for record in stream.read(wait=timedelta(seconds=30)): + number = int(record.body.rsplit(" ", 1)[1]) + await workflow.execute_activity( + _handle, number, start_to_close_timeout=timedelta(seconds=30) + ) + numbers.append(number) + # A Stream has no end, so the reader stops at the writer's last Record. + if number == count - 1: + break + await writer + return numbers + + +async def test_a_workflow_reads_the_records_of_an_activity_that_still_runs( + client: Client, +) -> None: + count = 5 + for cached in (True, False): + with failure_note(f"cached {cached}"): + _handled.clear() + _handled.update({number: asyncio.Event() for number in range(count)}) + options = RunOptions( + _ReadingWorkflow, + [f"read while written, cached {cached}", count], + activities=[_write_one_by_one, _handle], + cached=cached, + replay=True, + ) + ran = await run(stream_client(client, FaultStore()), options) + assert ran.result == list(range(count)) + assert not any( + b"a body" in event.SerializeToString() for event in ran.history.events + ) + + +@workflow.defn +class _EndingWorkflow: + """Starts a Stream call that nothing awaits, and ends in the way of ``how``.""" + + def __init__(self) -> None: + self._signals = 0 + + @workflow.signal + def go_on(self) -> None: + self._signals += 1 + + @workflow.run + async def run(self, stream_id: str, how: str) -> None: + stream = await workflow.create_stream(id=stream_id, body_type=int) + if how == "append": + asyncio.ensure_future(stream.append(1)) + elif how == "page": + await stream.append(1) + await stream.read_page(wait=timedelta(minutes=5)) + return + else: + asyncio.ensure_future(stream.read_page(wait=timedelta(minutes=5))) + await workflow.wait_condition(lambda: self._signals > 0) + # The task of the call makes its call in its first step. + await asyncio.sleep(0) + + +async def test_a_read_that_core_stops_leaves_no_store_task(client: Client) -> None: + # The read limit of the task stops a held Store call, also while the Worker shuts + # down, since the shutdown waits for the task. + for how in ("read limit", "shutdown"): + with failure_note(how): + store, hold = FaultStore(), Hold() + store.faults["read_records"].append(hold) + + async def end(handle: Any, worker: Worker) -> None: + await hold.started.wait() + if how == "shutdown": + await worker.shutdown() + else: + await handle.signal(_EndingWorkflow.go_on) + await asyncio.wait_for(hold.cancelled.wait(), 10) + if how == "shutdown": + await handle.terminate() + + # A task timeout of 2 seconds gives a read limit of 1 second. + options = RunOptions( + _EndingWorkflow, + [f"ends by {how}", how], + task_timeout=timedelta(seconds=2), + during=end, + replay=True, + ) + ran = await run(stream_client(client, store), options) + assert (ran.result is None) == (how == "read limit") + reads = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] + assert len(reads) == 1 + + +@pytest.mark.parametrize("how", ["page", "append"]) +async def test_a_stream_call_does_not_hold_the_last_command( + client: Client, how: str +) -> None: + # A read that gave a page, and an append that nothing awaits, don't hold + # the last command, so the Workflow ends in the task of the call. + options = RunOptions(_EndingWorkflow, [f"ends after its {how}", how], replay=True) + ran = await run(stream_client(client, FaultStore()), options) + assert ran.result is None + assert len(_events(ran.history, EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED)) == 1 + + +@workflow.defn +class _LatePagesWorkflow: + """Reads Records that come in a later Workflow Task than the one of its reads.""" + + @workflow.signal + def wake(self) -> None: + pass + + @workflow.run + async def run(self, how: str) -> list[list[str]]: + s = workflow.get_stream(StreamRef[str](id=f"s of {how}")) + t = workflow.get_stream(StreamRef[str](id=f"t of {how}")) + if how == "two readers": + # One reader takes a page of `s` and stops. The other waits for a page of + # `t`, and then reads `s` on from the offset of the first one. + first = asyncio.ensure_future(self._page(s)) + await self._page(t) + offset = (await first).last_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(from_offset=offset, wait=timedelta(seconds=30)) + pages.append([record.body for record in page.records]) + offset = page.last_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( + from_offset=offset, wait=timedelta(seconds=30) + ) + if page.records: + return page + offset = page.last_offset + + +@pytest.mark.parametrize("how", ["a loop", "two readers"]) +async def test_a_replay_gives_a_read_the_pages_of_the_first_run( + client: Client, how: str +) -> None: + store = FaultStore() + client = stream_client(client, store) + s = await client.create_stream(id=f"s of {how}", body_type=str) + t = await client.create_stream(id=f"t of {how}", body_type=str) + writes, expected = { + "a loop": ([(s, "a"), (s, "b")], ["a", "b"]), + "two readers": ([(s, "a"), (t, "x"), (s, "b")], ["a", "b"]), + }[how] + + async def write(handle: Any, _worker: Any) -> None: + async def first_task() -> None: + history = await handle.fetch_history() + completed = EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED + assert _events(history, completed) + + # The reads of the first task end with no Record, and a read of an idle Stream + # makes no task. A Signal opens the next task, whose reads start again. The + # pages then come in several activations of that task, and a replay gives each + # page in its activation. + await assert_eventually(first_task) + await handle.signal(_LatePagesWorkflow.wake) + for stream, body in writes: + await stream.append(body) + # The page of this Record gets an activation before the next Record comes. + await asyncio.sleep(0.3) + + # The default read limit is half the task timeout, so a read with no Record + # is cut at 3 s, and a slow host still doesn't time out the task. + options = RunOptions( + _LatePagesWorkflow, + [how], + task_timeout=timedelta(seconds=6), + during=write, + replay=True, + ) + ran = await run(client, options) + assert [body for page in ran.result for body in page] == expected + events = [event.event_type for event in ran.history.events] + completed = events.index(EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED) + marker = EventType.EVENT_TYPE_MARKER_RECORDED + later = [event for event in events[completed + 1 :] if event != marker] + assert later[0] == EventType.EVENT_TYPE_WORKFLOW_EXECUTION_SIGNALED + + +@workflow.defn +class _TwoReadsWorkflow: + @workflow.run + async def run(self, first: str, second: str) -> list[list[str]]: + wait = timedelta(seconds=30) + streams = [workflow.get_stream(StreamRef[str](id=id)) for id in (first, second)] + pages = await asyncio.gather( + *(stream.read_page(wait=wait) for stream in streams) + ) + return [[record.body for record in page.records] for page in pages] + + +async def test_a_replay_gives_each_result_in_the_activation_of_the_first_run( + client: Client, +) -> None: + # A local import, so that the sandbox of each Workflow here doesn't import that module. + from tests.worker.test_workflow import CustomWorkflowRunner + + store, holds = FaultStore(), [Hold(), Hold()] + store.faults["read_records"].extend(holds) + client = stream_client(client, store) + for stream_id in ("first", "second"): + stream = await client.create_stream(id=stream_id, body_type=str) + await stream.append(stream_id) + live, replayed = CustomWorkflowRunner(), CustomWorkflowRunner() + + def read_results(runner: CustomWorkflowRunner) -> list[list[int]]: + """Return the seqs of the read results of each activation that has one.""" + activations = [ + [ + job.resolve_stream_read.seq + for job in activation.jobs + if job.HasField("resolve_stream_read") + ] + for activation, _ in runner._pairs + ] + return [seqs for seqs in activations if seqs] + + async def release(_handle: Any, _worker: Any) -> None: + # Both reads wait in the first task, and each page comes before its read limit. + for hold in holds: + await hold.started.wait() + for count, hold in enumerate(holds, 1): + hold.release() + + async def given() -> None: + assert len(read_results(live)) == count + + # This page gets its activation before the Store answers the other read. + await assert_eventually(given) + + options = RunOptions( + _TwoReadsWorkflow, + ["first", "second"], + worker={"workflow_runner": live}, + during=release, + ) + ran = await run(client, options) + assert ran.result == [["first"], ["second"]] + await Replayer( + workflows=[_TwoReadsWorkflow], + workflow_runner=replayed, + stream_config=client._config["stream_config"], + ).replay_workflow(ran.history) + assert len(read_results(live)) == 2 + assert read_results(replayed) == read_results(live) + + +@workflow.defn +class _ReadOnceWorkflow: + def __init__(self) -> None: + self._go_on = False + + @workflow.signal + def go_on(self) -> None: + self._go_on = True + + @workflow.run + async def run(self, stream_id: str) -> list[int]: + stream = workflow.get_stream(StreamRef[int](id=stream_id)) + bodies: list[int] = [] + async for record in stream.read(): + bodies.append(record.body) + # A Stream has no end, so the reader stops at the writer's last Record. + if record.body == 3: + break + await workflow.wait_condition(lambda: self._go_on) + return bodies + + +@workflow.defn(failure_exception_types=[workflow.StreamReplayError]) +class _ReadOnceOptedInWorkflow(_ReadOnceWorkflow): + @workflow.run + async def run(self, stream_id: str) -> list[int]: + return await super().run(stream_id) + + +async def test_a_replay_reads_its_python_stores(client: Client) -> None: + store = FaultStore() + stream = await stream_client(client, store).create_stream( + id="replayed", body_type=int + ) + await stream.append(1, 2, 3) + + async def go_on(handle: Any, _worker: Any) -> None: + await handle.signal(_ReadOnceWorkflow.go_on) + + options = RunOptions(_ReadOnceWorkflow, ["replayed"], during=go_on) + ran = await run(stream_client(client, store), options) + assert ran.result == [1, 2, 3] + # A `Replayer` reads the Records again from the Store, and fails without them. + replayer = Replayer( + workflows=[_ReadOnceWorkflow], stream_config=StreamConfig([store]) + ) + reads = len(store.requests) + await replayer.replay_workflow(ran.history) + assert isinstance(store.requests[reads], ReadRecordsRequest) + store.memory = MemoryStreamStore() + with pytest.raises(RuntimeError): + await replayer.replay_workflow(ran.history) + + # A Worker with no cache replays the read in its second task. With the Records gone + # the task fails, or the Workflow with the opt-in of the Worker or of the Workflow. + cases: dict[str, tuple[type, list[type[BaseException]]]] = { + "no opt-in": (_ReadOnceWorkflow, []), + "the Worker option": (_ReadOnceWorkflow, [workflow.StreamReplayError]), + "the Workflow option": (_ReadOnceOptedInWorkflow, []), + } + for case, (workflow_class, failure_types) in cases.items(): + with failure_note(case): + store = FaultStore() + stream_id = f"gone with {case}" + stream = await stream_client(client, store).create_stream( + id=stream_id, body_type=int + ) + await stream.append(1, 2, 3) + + async def lose_the_records(handle: Any, _worker: Any) -> None: + async def has_read() -> None: + history = await handle.fetch_history() + assert _stream_markers(history, "read") + + await assert_eventually(has_read) + store.memory = MemoryStreamStore() + await handle.signal(_ReadOnceWorkflow.go_on) + if case == "no opt-in": + await assert_task_fail_eventually(handle) + await handle.terminate() + + options = RunOptions( + workflow_class, + [stream_id], + cached=False, + worker={"workflow_failure_exception_types": failure_types}, + during=lose_the_records, + ) + ran = await run(stream_client(client, store), options) + assert isinstance(ran.result, WorkflowFailureError) + if case != "no opt-in": + cause = ran.result.cause + assert isinstance(cause, ApplicationError) + assert cause.type == "StreamReplayError" + failed = _events(ran.history, EventType.EVENT_TYPE_WORKFLOW_TASK_FAILED) + assert not failed + + +@workflow.defn +class _ReadAllWorkflow: + @workflow.run + async def run(self, stream_id: str, limits: dict[str, int]) -> list[int]: + stream = workflow.get_stream(StreamRef[int](id=stream_id)) + records = stream.read( + wait=timedelta(minutes=5), + max_records=limits.get("max_records"), + max_bytes=limits.get("max_bytes"), + ) + bodies: list[int] = [] + async for record in records: + bodies.append(record.body) + # A Stream has no end, so the reader stops at the writer's last Record. + if record.body == 3: + break + return bodies + + +async def test_a_workflow_read_asks_the_store_with_its_limits(client: Client) -> None: + store = FaultStore() + client = stream_client(client, store) + stream = await client.create_stream(id="paged", body_type=int) + await stream.append(1, 2, 3) + + # A read with no limit asks for 256 Records and 4 MiB. SDK Core asks the Store for + # room for one Record more, since it acts on whether the Stream has more. That + # Record has at most the Record size of the config and an offset of 1024 bytes, + # each in its field. A Store call waits no longer than the read time of the + # Worker, which is shorter than the wait of the read. + def field(size: int) -> int: + return 1 + (size.bit_length() + 6) // 7 + size + + one_more = field(StreamConfig([store]).max_record_bytes + field(1024)) + cases: list[tuple[dict[str, int], tuple[int, int]]] = [ + ({"max_records": 1, "max_bytes": 100}, (2, 100 + one_more)), + ({}, (257, 4 * 1024 * 1024 + one_more)), + ] + read_time = timedelta(seconds=2) + for limits, expected in cases: + with failure_note(f"limits {limits}"): + store.calls.clear() + options = RunOptions( + _ReadAllWorkflow, + ["paged", limits], + worker={"stream_read_time": read_time}, + ) + ran = await run(client, options) + assert ran.result == [1, 2, 3] + reads = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] + asked = [(r.max_records, r.max_bytes) for r in reads] + # With one Record in a page, the read of each Record is one Store call. + assert asked == [expected] * (3 if limits else 1) + waits = [r.wait.ToTimedelta() for r in reads] + assert timedelta(0) < waits[0] and max(waits) <= read_time + # A replay asks for the Records that History recorded, and no more. + store.calls.clear() + await Replayer( + workflows=[_ReadAllWorkflow], + stream_config=client._config["stream_config"], + ).replay_workflow(ran.history) + replayed = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] + assert [r.max_records for r in replayed] == ([1] * 3 if limits else [3]) + + +@workflow.defn +class _QuietReadWorkflow: + @workflow.signal + def wake(self) -> None: + pass + + @workflow.run + async def run(self, stream_id: str) -> list[int]: + stream = workflow.get_stream(StreamRef[int](id=stream_id)) + bodies: list[int] = [] + offset = None + # The writer's last Record is 2, since a Stream has no end. + while 2 not in bodies: + page = await stream.read_page(from_offset=offset, wait=timedelta(minutes=5)) + bodies.extend(record.body for record in page.records) + offset = page.last_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.from_offset for r in quiet) + # The read starts again from the same offset in the task of a Signal. + await stream.append(1, 2) + await handle.signal(_QuietReadWorkflow.wake) + + options = RunOptions( + _QuietReadWorkflow, + ["quiet"], + worker={"stream_read_time": timedelta(milliseconds=300)}, + during=write, + replay=True, + ) + assert (await run(client, options)).result == [1, 2] + + +@workflow.defn +class _FirstRecordWorkflow: + @workflow.signal + def wake(self) -> None: + pass + + @workflow.run + async def run(self, stream_id: str, seconds: float | None = 5) -> list[int]: + stream = workflow.get_stream(StreamRef[int](id=stream_id)) + wait = None if seconds is None else timedelta(seconds=seconds) + async for record in stream.read(wait=wait): + return [record.body] + raise AssertionError("A Workflow reader never ends by itself") + + +async def test_a_workflow_read_goes_on_after_the_read_limit_cut_its_wait( + client: Client, +) -> None: + store = FaultStore() + client = stream_client(client, store) + stream = await client.create_stream(id="cut", body_type=int) + + async def write(handle: Any, _worker: Any) -> None: + async def cut_page() -> None: + history = await handle.fetch_history() + markers = _stream_markers(history, "read") + assert any(b'"wait_cut":true' in m.SerializeToString() for m in markers) + assert _events(history, EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED) + + # The read limit cuts the wait of 5 s at 1 s. The iterator reads again, and + # that read waits for the next task, which a Signal opens. + await assert_eventually(cut_page) + await stream.append(1) + await handle.signal(_FirstRecordWorkflow.wake) + + options = RunOptions( + _FirstRecordWorkflow, + ["cut"], + worker={"stream_read_time": timedelta(seconds=1)}, + during=write, + replay=True, + ) + assert (await run(client, options)).result == [1] + + +async def test_a_workflow_iterator_with_no_wait_parks_on_an_idle_stream( + client: Client, +) -> None: + store = FaultStore() + client = stream_client(client, store) + stream = await client.create_stream(id="idle", body_type=int) + + async def write(handle: Any, _worker: Any) -> None: + async def first_task() -> None: + completed = EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED + assert _events(await handle.fetch_history(), completed) + + # The first read gives the empty answer of the Store at once. The later ones + # have the default wait. The read limit cuts a few of them, then one parks, + # so the idle Stream makes no new task over several read limits. + await assert_eventually(first_task) + await asyncio.sleep(4) + history = await handle.fetch_history() + tasks = _events(history, EventType.EVENT_TYPE_WORKFLOW_TASK_STARTED) + markers = _stream_markers(history, "read") + assert len(tasks) == 1, len(tasks) + assert 2 <= len(markers) <= 6, len(markers) + await stream.append(1) + await handle.signal(_FirstRecordWorkflow.wake) + + options = RunOptions( + _FirstRecordWorkflow, + ["idle", None], + task_timeout=timedelta(seconds=10), + worker={"stream_read_time": timedelta(seconds=1)}, + during=write, + replay=True, + ) + ran = await asyncio.wait_for(run(client, options), 30) + assert ran.result == [1] + + +async def test_a_workflow_read_with_no_wait_reads_again_in_the_next_task( + client: Client, +) -> None: + store, hold = FaultStore(), Hold() + stream = await stream_client(client, store).create_stream(id="slow", body_type=int) + await stream.append(1, 2, 3) + store.faults["read_records"].append(hold) + + async def release(handle: Any, _worker: Any) -> None: + async def task_completed() -> None: + history = await handle.fetch_history() + completed = EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED + assert _events(history, completed) + + # The read goes on at the read limit, since only the Store can say that the + # Stream has no Record. The task then completes, which stops the held read, + # and the read starts again in the task of the Signal. + await assert_eventually(task_completed) + await asyncio.wait_for(hold.cancelled.wait(), 10) + await handle.signal(_ReadOnceWorkflow.go_on) + + options = RunOptions( + _ReadOnceWorkflow, + ["slow"], + task_timeout=timedelta(seconds=2), + during=release, + replay=True, + ) + assert (await run(stream_client(client, store), options)).result == [1, 2, 3] + reads = [r for r in store.requests if isinstance(r, ReadRecordsRequest)] + assert len([r for r in reads if not r.from_offset]) >= 2 + + +@dataclasses.dataclass +class _Turn: + text: str + + +@dataclasses.dataclass +class _AgentInput: + turns: StreamRef[_Turn] | None = None + + +@dataclasses.dataclass +class _TurnsInput: + turns: StreamRef[_Turn] + texts: list[str] + + +@activity.defn +async def _append_turns(input: _TurnsInput) -> None: + stream = activity.client().get_stream(input.turns) + await stream.append(*(_Turn(text) for text in input.texts)) + + +@workflow.defn +class _AgentWorkflow: + def __init__(self) -> None: + self._turns: StreamRef[_Turn] | None = None + self._go_on = False + + @workflow.query + def turns(self) -> StreamRef[_Turn] | None: + return self._turns + + @workflow.signal + def go_on(self) -> None: + self._go_on = True + + @workflow.run + async def run(self, input: _AgentInput) -> list[str]: + self._turns = input.turns + await workflow.wait_condition(lambda: self._go_on) + if self._turns is None: + created = await workflow.create_stream(id="turns", body_type=_Turn) + self._turns = created.ref + await workflow.execute_activity( + _append_turns, + _TurnsInput(self._turns, ["a", "b"]), + start_to_close_timeout=timedelta(seconds=10), + ) + page = await workflow.get_stream(self._turns).read_page() + # Only a body that the read converted to its type has the attribute. + return [record.body.text for record in page.records] + + +async def test_a_stream_ref_keeps_its_type_through_a_workflow(client: Client) -> None: + streams = stream_client(client, MemoryStreamStore()) + ref: Any = None + # The first run gets no ref and creates the Stream. The second one gets that ref. + for texts in (["a", "b"], ["a", "b", "a", "b"]): + with failure_note(f"texts {texts}"): + + async def answer(handle: Any, _worker: Any) -> None: + nonlocal ref + assert await handle.query(_AgentWorkflow.turns) == ref + await handle.signal(_AgentWorkflow.go_on) + await handle.result() + ref = await handle.query(_AgentWorkflow.turns) + + options = RunOptions( + _AgentWorkflow, + [_AgentInput(ref)], + activities=[_append_turns], + during=answer, + replay=True, + ) + assert (await run(streams, options)).result == texts + assert ref == StreamRef(id="turns", store="memory") + # The ref of the query has the body type, so the read needs no `body_type=`. + page = await streams.get_stream(ref).read_page() + assert [record.body for record in page.records] == [ + _Turn(text) for text in texts + ] diff --git a/tests/test_converter.py b/tests/test_converter.py index b47cadbdd0..5c48a36215 100644 --- a/tests/test_converter.py +++ b/tests/test_converter.py @@ -59,6 +59,7 @@ ) from temporalio.converter._payload_converter import ( _TemporalTransferTypePayloadConverter, + _typed_decode_types, ) from temporalio.exceptions import ( ApplicationError, @@ -388,6 +389,28 @@ def from_transfer_type( ) +class TemporalTransferTypeJSONValueConverter( + TransferTypeConverter["TemporalTransferTypeJSONValue", dict[str, str]] +): + transfer_type = dict[str, str] + + def to_transfer_type(self, value: TemporalTransferTypeJSONValue) -> dict[str, str]: + return {"id": value.value} + + def from_transfer_type( + self, + value: dict[str, str], + type_hint: type[TemporalTransferTypeJSONValue], + ) -> TemporalTransferTypeJSONValue: + return TemporalTransferTypeJSONValue(value=value["id"]) + + +@transfer_type_convertible(TemporalTransferTypeJSONValueConverter) +@dataclass +class TemporalTransferTypeJSONValue: + value: str + + class CustomDefaultPayloadConverter(DefaultPayloadConverter): pass @@ -455,6 +478,54 @@ def test_temporal_transfer_type_payload_converter_with_generic_value( assert converter.from_payload(payload, type_hint) == value +def _decode_typed(monkeypatch: pytest.MonkeyPatch, *types: type) -> None: + """Let ``types`` decode by their type arguments and under ``T | None`` in one test.""" + monkeypatch.setattr( + "temporalio.converter._payload_converter._typed_decode_types", + _typed_decode_types | set(types), + ) + + +@pytest.mark.parametrize( + ("value", "type_hint"), + [ + (TemporalTransferTypeValue("workflow-id"), TemporalTransferTypeValue | None), + (None, TemporalTransferTypeValue | None), + ( + TemporalTransferTypeValueWithoutHint("workflow-id"), + TemporalTransferTypeValueWithoutHint | None, + ), + ( + TemporalTransferTypeGenericValue(123), + TemporalTransferTypeGenericValue[int] | None, + ), + (None, TemporalTransferTypeGenericValue[int] | None), + (TemporalTransferTypeValue("workflow-id"), None | TemporalTransferTypeValue), + (TemporalTransferTypeJSONValue("id"), TemporalTransferTypeJSONValue | None), + (None, TemporalTransferTypeJSONValue | None), + ], +) +def test_temporal_transfer_type_payload_converter_with_optional_hint( + value: Any, type_hint: Any, monkeypatch: pytest.MonkeyPatch +): + _decode_typed( + monkeypatch, + TemporalTransferTypeValue, + TemporalTransferTypeValueWithoutHint, + TemporalTransferTypeGenericValue, + TemporalTransferTypeJSONValue, + ) + converter = DataConverter.default.payload_converter + + payloads = [converter.to_payload(value)] + if value is None: + # A converter of another SDK can write None as a JSON null. + payloads.append(Payload(metadata={"encoding": b"json/plain"}, data=b"null")) + + for payload in payloads: + assert converter.from_payload(payload, type_hint) == value + + def test_transfer_type_convertible_rejects_existing_converter(): with pytest.raises(TypeError, match="already has a transfer type converter"): transfer_type_convertible(TemporalTransferTypeValueConverter)( @@ -564,6 +635,14 @@ class InitFalseIntDataClass: bar: int = dataclasses.field(default=0, init=False) +@dataclass +class GenericDataClass(Generic[T]): + value: T + items: list[T] = dataclasses.field(default_factory=list) + nested: GenericDataClass[T] | None = None + maybe: T | None = None + + class MyTypedDict(TypedDict): foo: str bar: MyDataClass @@ -605,6 +684,61 @@ def test_json_nested_frozenset_round_trip(): assert converter.from_payload(payload, set[frozenset[int]]) == value +K = TypeVar("K") + + +@dataclass +class GenericPairDataClass(Generic[K, T]): + key: K + value: T + + +def test_json_generic_dataclass_round_trip(monkeypatch: pytest.MonkeyPatch): + converter = JSONPlainPayloadConverter() + # mypy takes a type argument from a variable only on a value of type Any + generic_type: Any = GenericDataClass + pair_type: Any = GenericPairDataClass + + # A generic dataclass that isn't registered keeps its decoding, which the replay of + # an existing History needs. + payload = converter.to_payload(GenericDataClass(1)) + assert payload + with pytest.raises(TypeError): + converter.from_payload(payload, generic_type[int]) + generic_or_dict: Any = generic_type[int] | dict + assert converter.from_payload(payload, generic_or_dict) == { + "value": 1, + "items": [], + "nested": None, + "maybe": None, + } + + _decode_typed(monkeypatch, GenericDataClass, GenericPairDataClass) + + for argument, value in [ + (int, GenericDataClass(1, items=[2], nested=GenericDataClass(3), maybe=4)), + (str, GenericDataClass("text")), + (list[int], GenericDataClass([1], items=[[2], []], maybe=[3])), + (MyDataClass, GenericDataClass(MyDataClass("foo", 1, SerializableEnum.FOO))), + (GenericDataClass[str], GenericDataClass(GenericDataClass("nested"))), + ]: + payload = converter.to_payload(value) + assert payload + decoded = converter.from_payload(payload, generic_type[argument]) + assert decoded == value + assert decoded.__orig_class__ == generic_type[argument] + + payload = converter.to_payload({"value": "not an integer"}) + assert payload + with pytest.raises(TypeError): + converter.from_payload(payload, generic_type[int]) + + pair = GenericPairDataClass(key=1, value="text") + payload = converter.to_payload(pair) + assert payload + assert converter.from_payload(payload, pair_type[int, str]) == pair + + def test_json_type_hints(): converter = JSONPlainPayloadConverter() diff --git a/tests/testing/test_activity.py b/tests/testing/test_activity.py index 71ba7f5907..d7941d05a0 100644 --- a/tests/testing/test_activity.py +++ b/tests/testing/test_activity.py @@ -2,6 +2,7 @@ import threading import time from contextvars import copy_context +from datetime import datetime, timezone from unittest.mock import Mock import pytest @@ -38,6 +39,10 @@ async def via_create_task(): return "done" env = ActivityEnvironment() + epoch = datetime(1970, 1, 1, tzinfo=timezone.utc) + assert env.info.scheduled_time == epoch + assert env.info.current_attempt_scheduled_time == epoch + assert env.info.started_time == epoch # Set heartbeat handler to add to list heartbeats = [] env.on_heartbeat = lambda *args: heartbeats.append(args[0]) diff --git a/tests/testing/test_stream_store.py b/tests/testing/test_stream_store.py new file mode 100644 index 0000000000..9a6e54b98d --- /dev/null +++ b/tests/testing/test_stream_store.py @@ -0,0 +1,473 @@ +"""Tests of the memory Stream Store.""" + +import asyncio +import random +import time +from collections.abc import Awaitable +from dataclasses import dataclass, field +from datetime import timedelta +from typing import Any +from unittest.mock import patch + +import pytest +from google.protobuf.duration_pb2 import Duration +from google.protobuf.message import Message +from google.protobuf.timestamp_pb2 import Timestamp + +from temporalio.api.common.v1 import Payload +from temporalio.api.enums.v1 import ( + StreamErrorReason, + StreamIdConflictPolicy, +) +from temporalio.api.stream.v1 import ( + ActivityAttempt, + AppendRecord, + LocalActivityAttempt, + Producer, + StreamRecord, + WorkflowTaskAttempt, +) +from temporalio.api.streamservice.v1 import ( + AppendRecordsRequest, + AppendRecordsResponse, + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, +) +from temporalio.bridge.streams import call_stream_store +from temporalio.client._stream_store import _StoreCaller +from temporalio.exceptions import StreamError +from temporalio.runtime import Runtime, TelemetryConfig +from temporalio.testing import MemoryStreamStore +from temporalio.testing._stream_store import _MemoryStreams +from tests.helpers.streams import failure_note, run_with_virtual_clock + +_NOT_FOUND = StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND +_EXPIRED = StreamErrorReason.STREAM_ERROR_REASON_EXPIRED +_FENCED = StreamErrorReason.STREAM_ERROR_REASON_FENCED + +# Attempts of each attempt message, earliest first. Where a later attempt wins by one field, +# its fields after that one are lower, so a comparison in another order of the fields differs. +_TASKS = [ + WorkflowTaskAttempt(started_event_id=3, attempt=2), + WorkflowTaskAttempt( + started_event_id=3, attempt=2, started_time=Timestamp(seconds=9) + ), + WorkflowTaskAttempt( + started_event_id=3, attempt=3, started_time=Timestamp(seconds=1) + ), + WorkflowTaskAttempt(started_event_id=5, attempt=1), +] +_ATTEMPTS: dict[type[Message], list[Any]] = { + WorkflowTaskAttempt: _TASKS, + LocalActivityAttempt: [ + LocalActivityAttempt(task=_TASKS[0], attempt=2), + LocalActivityAttempt(task=_TASKS[0], attempt=3), + LocalActivityAttempt(task=_TASKS[1], attempt=1), + LocalActivityAttempt(task=_TASKS[3], attempt=1), + ], + ActivityAttempt: [ + ActivityAttempt( + attempt_scheduled_time=Timestamp(seconds=4, nanos=7), attempt=2 + ), + ActivityAttempt( + attempt_scheduled_time=Timestamp(seconds=4, nanos=7), attempt=3 + ), + ActivityAttempt( + attempt_scheduled_time=Timestamp(seconds=4, nanos=8), attempt=1 + ), + ActivityAttempt(attempt_scheduled_time=Timestamp(seconds=5), attempt=1), + ], +} + + +@dataclass(frozen=True) +class _Writer: + """A generated Producer, with what a Store tells Producers and attempts apart by.""" + + producer: Producer + ids: tuple[str | int, ...] + """The kind and each id of the Producer.""" + rank: int + """The place of the attempt among the attempts of the Producer.""" + + +def _writer(rng: random.Random, same: _Writer | None = None) -> _Writer: + """Return a new Producer, or the Producer of ``same``, with an attempt.""" + producer = Producer() + if same: + producer.CopyFrom(same.producer) + name = ( + str(same.ids[0]) + if same + else rng.choice(list(Producer.DESCRIPTOR.fields_by_name)) + ) + kind = getattr(producer, name) + kind.SetInParent() + ids: list[str | int] = [name] + for id_field in kind.DESCRIPTOR.fields: + # A number id, such as the scheduled event id of an Activity, can be zero. + values = {id_field.TYPE_STRING: "aab", id_field.TYPE_INT64: [0, 0, 5]} + if id_field.type in values: + if not same: + setattr(kind, id_field.name, rng.choice(values[id_field.type])) + ids.append(getattr(kind, id_field.name)) + rank = 0 + if attempt := kind.DESCRIPTOR.fields_by_name.get("attempt"): + attempts = _ATTEMPTS[type(getattr(kind, attempt.name))] + rank = rng.randrange(len(attempts)) + getattr(kind, attempt.name).CopyFrom(attempts[rank]) + return _Writer(producer, tuple(ids), rank) + + +@dataclass +class _ModelBatch: + writer: _Writer + request_id: str + response: AppendRecordsResponse + + +@dataclass +class _ModelStream: + request_id: str + records: list[StreamRecord] = field(default_factory=list) + batches: list[_ModelBatch] = field(default_factory=list) + + def fenced(self, writer: _Writer) -> bool: + return any( + batch.writer.ids == writer.ids and batch.writer.rank > writer.rank + for batch in self.batches + ) + + +@dataclass +class _Model: + """What a Store with the rules of ``StreamStore`` answers, from all that it wrote.""" + + resend_window: int + fence: bool + streams: dict[str, _ModelStream] = field(default_factory=dict) + + def create(self, request: CreateStreamRequest, request_id: str) -> Any: + stream = self.streams.get(request.stream_id) + if stream is None: + self.streams[request.stream_id] = _ModelStream(request_id) + return CreateStreamResponse(created=True) + if request_id and request_id == stream.request_id: + return CreateStreamResponse(created=True) + use_existing = StreamIdConflictPolicy.STREAM_ID_CONFLICT_POLICY_USE_EXISTING + if request.id_conflict_policy == use_existing: + return CreateStreamResponse() + return StreamErrorReason.STREAM_ERROR_REASON_ALREADY_EXISTS + + def append( + self, request: AppendRecordsRequest, writer: _Writer, request_id: str + ) -> Any: + # SDK Core refuses a batch with no Record before the Store gets it. + if not request.records: + return StreamErrorReason.STREAM_ERROR_REASON_INVALID_ARGUMENT + stream = self.streams.get(request.stream_id) + if stream is None: + return _NOT_FOUND + own = [batch for batch in stream.batches if batch.writer.ids == writer.ids] + for batch in own[len(own) - min(len(own), self.resend_window) :]: + if request_id and (batch.writer.rank, batch.request_id) == ( + writer.rank, + request_id, + ): + return batch.response + if self.fence and stream.fenced(writer): + return _FENCED + response = AppendRecordsResponse() + for record in request.records: + offset = (len(stream.records) + 1).to_bytes(8, "big") + response.first_offset = response.first_offset or offset + response.last_offset = offset + stream.records.append( + StreamRecord(producer=request.producer, body=record.body, offset=offset) + ) + stream.batches.append(_ModelBatch(writer, request_id, response)) + return response + + def read(self, request: ReadRecordsRequest) -> Any: + stream = self.streams.get(request.stream_id) + if stream is None: + return _NOT_FOUND + start = int.from_bytes(request.from_offset, "big") + if start > len(stream.records): + return StreamErrorReason.STREAM_ERROR_REASON_OFFSET_TOO_HIGH + records = stream.records[start:][: request.max_records or None] + return ReadRecordsResponse( + records=records, + last_offset=records[-1].offset if records else request.from_offset, + ) + + +_OPERATIONS = ["create", "append", "again", "read"] +_WEIGHTS = [3, 10, 6, 4] + + +async def _answer(call: Awaitable[Message]) -> Any: + """Return the response of a Store call, or the reason of its refusal.""" + try: + return await call + except StreamError as err: + return err.reason + + +async def test_the_memory_store_keeps_the_rules_of_the_redis_store() -> None: + own = Runtime(telemetry=TelemetryConfig()) + for seed in range(150): + with failure_note(f"seed {seed}"): + await _store_script(random.Random(seed), None) + # A Store with a runtime of its own runs its checks there, and not on the default one. + with patch.object(Runtime, "default", side_effect=AssertionError("The default")): + await _store_script(random.Random(0), own) + + +async def _store_script(rng: random.Random, runtime: Runtime | None) -> None: + model = _Model(resend_window=rng.randrange(1, 4), fence=rng.random() < 0.5) + store = MemoryStreamStore( + resend_window=model.resend_window, fence=model.fence, runtime=runtime + ) + appends: list[tuple[AppendRecordsRequest, _Writer, str]] = [] + writers: list[_Writer] = [] + for step in range(50): + stream_id = rng.choice("xy") + # Most writes come from another attempt of a Producer that the script already has. + writer = _writer( + rng, rng.choice(writers) if rng.random() < 0.7 * bool(writers) else None + ) + writers.append(writer) + request: Message + match rng.choices(_OPERATIONS, _WEIGHTS)[0]: + case "create": + request = CreateStreamRequest( + stream_id=stream_id, + id_conflict_policy=rng.choice( + list(StreamIdConflictPolicy.values()) + ), + ) + request_id = rng.choice(["", "r1", "r2"]) + expected = model.create(request, request_id) + answer = await _answer( + store.create_stream(request, request_id=request_id) + ) + case "append" | "again" as op: + request = AppendRecordsRequest( + stream_id=stream_id, producer=writer.producer + ) + request_id = rng.choice(["", "r1", "r2", "r3"]) + if op == "again" and appends: + # A late or a repeated try has the Producer, the attempt and the + # request id of an earlier append, and it may have other Records. + earlier, writer, request_id = rng.choice(appends) + request.CopyFrom(earlier) + del request.records[:] + for _ in range(rng.randrange(3)): + body = Payload(data=bytes([rng.randrange(256)])) + request.records.append(AppendRecord(body=body)) + appends.append((request, writer, request_id)) + expected = model.append(request, writer, request_id) + answer = await _answer( + store.append_records(request, request_id=request_id) + ) + case _: + request = ReadRecordsRequest( + stream_id=stream_id, + from_offset=rng.choice( + [b"", *(i.to_bytes(8, "big") for i in range(1, 9))] + ), + max_records=rng.randrange(4), + ) + expected = model.read(request) + answer = await _answer(store.read_records(request)) + assert answer == expected, f"step {step}: {request}" + + +def _streams(retention: int = 1) -> _MemoryStreams: + return _MemoryStreams( + "memory", retention=timedelta(seconds=retention), resend_window=1, fence=False + ) + + +_S = "s" + + +def _client_append() -> AppendRecordsRequest: + request = AppendRecordsRequest(stream_id=_S, records=[AppendRecord()]) + request.producer.client.SetInParent() + return request + + +def test_a_stream_expires_after_its_retention_from_its_create_or_last_write() -> None: + async def script(rng: random.Random) -> None: + loop = asyncio.get_running_loop() + retention = rng.randrange(1, 50) + streams = _streams(retention) + await streams.create_stream(CreateStreamRequest(stream_id=_S), request_id="c") + expires_at = loop.time() + retention + # The window of the client Producer has its last batch, so an append with the + # request id of that batch is a resend, which writes nothing. + last_batch: str | None = None + for step in range(12): + await asyncio.sleep(rng.randrange(40)) + expired = loop.time() >= expires_at + match rng.choice(["append", "append", "read", "describe", "create"]): + case "append": + request_id = rng.choice(["", "r"]) + append = streams.append_records( + _client_append(), request_id=request_id + ) + answer = await _answer(append) + expected: Any = AppendRecordsResponse + resend = bool(request_id) and request_id == last_batch + if not expired and not resend: + expires_at, last_batch = loop.time() + retention, request_id + case "read": + read = ReadRecordsRequest(stream_id=_S) + answer = await _answer(streams.read_records(read)) + expected = ReadRecordsResponse + case "describe": + describe = DescribeStreamRequest(stream_id=_S) + answer = await _answer(streams.describe_stream(describe)) + expected = DescribeStreamResponse + case _: + use_existing = ( + StreamIdConflictPolicy.STREAM_ID_CONFLICT_POLICY_USE_EXISTING + ) + create = CreateStreamRequest( + stream_id=_S, id_conflict_policy=use_existing + ) + answer = await _answer( + streams.create_stream(create, request_id=rng.choice("cd")) + ) + expected = CreateStreamResponse + if expired: + expected = _EXPIRED + assert answer == expected or type(answer) is expected, ( + f"step {step}: {answer} at {loop.time()}" + ) + + for seed in range(200): + with failure_note(f"seed {seed}"): + run_with_virtual_clock(script(random.Random(seed))) + + +@pytest.mark.parametrize( + "wait,write_in,answered_at,outcome", + [ + (5, 3, 3, "record"), + (5, 7, 5, "empty"), + (5, None, 5, "empty"), + (20, None, 10, "expired"), + (10, None, 10, "expired"), + ], +) +def test_a_read_waits_for_a_write_its_timeout_or_expiry( + wait: int, write_in: int | None, answered_at: int, outcome: str +) -> None: + async def script() -> None: + loop = asyncio.get_running_loop() + streams = _streams(retention=10) + await streams.create_stream(CreateStreamRequest(stream_id=_S), request_id="") + first = await streams.append_records(_client_append(), request_id="") + request = ReadRecordsRequest( + stream_id=_S, from_offset=first.last_offset, wait=Duration(seconds=wait) + ) + + async def read() -> tuple[float, Any]: + response = await _answer(streams.read_records(request)) + return loop.time(), response + + reader = asyncio.create_task(read()) + if write_in is not None: + await asyncio.sleep(write_in) + await streams.append_records(_client_append(), request_id="") + ended, page = await reader + assert ended == answered_at + if outcome == "expired": + assert page == _EXPIRED + elif outcome == "empty": + assert page == ReadRecordsResponse(last_offset=first.last_offset) + else: + [record] = page.records + assert page.last_offset == record.offset > first.last_offset + + run_with_virtual_clock(script()) + + +async def test_a_store_call_of_the_bridge_gives_the_store_the_caps_of_the_read() -> ( + None +): + asked: list[ReadRecordsRequest] = [] + + class Asked(_MemoryStreams): + async def read_records( + self, request: ReadRecordsRequest + ) -> ReadRecordsResponse: + asked.append(request) + return await super().read_records(request) + + streams = Asked("memory", retention=timedelta(days=1), resend_window=1, fence=False) + await streams.create_stream(CreateStreamRequest(stream_id=_S), request_id="c") + await streams.append_records(_client_append(), request_id="a") + await streams.append_records(_client_append(), request_id="b") + read = ReadRecordsRequest(stream_id=_S, max_records=1, max_bytes=100) + answer = await call_stream_store( + Runtime.default()._core_runtime, + _StoreCaller(lambda: streams), + "ReadRecords", + read.SerializeToString(), + ) + # Only SDK Core asks for one Record more, since only it acts on whether the + # Stream has more after the page. Client and Activity code don't. + assert asked == [read] + assert len(ReadRecordsResponse.FromString(answer).records) == 1 + + +async def test_a_dropped_store_call_never_reaches_the_store() -> None: + asked: list[str] = [] + + class Waiting(MemoryStreamStore): + async def describe_stream( + self, request: DescribeStreamRequest + ) -> DescribeStreamResponse: + asked.append("call") + try: + return await asyncio.Future() + finally: + asked.append("cancel") + + def store() -> MemoryStreamStore: + asked.append("store") + return Waiting() + + def on_task(_task: asyncio.Task[Any]) -> None: + raise asyncio.CancelledError + + request = DescribeStreamRequest(stream_id=_S).SerializeToString() + with pytest.raises(asyncio.CancelledError): + await _StoreCaller(store).call("DescribeStream", request, None, on_task) + assert not asked + + # Core drops this call after it made the task of the call and before the task ran, + # since the loop is blocked in between. A task that ran anyway is cancelled. + loop = asyncio.get_running_loop() + call = asyncio.ensure_future( + call_stream_store( + Runtime.default()._core_runtime, + _StoreCaller(store), + "DescribeStream", + request, + ) + ) + time.sleep(0.05) + await asyncio.sleep(0) + call.cancel() + loop.call_soon(time.sleep, 0.2) + await asyncio.sleep(0.3) + assert asked in ([], ["store", "call", "cancel"]) diff --git a/tests/worker/test_replayer.py b/tests/worker/test_replayer.py index 8f4b1fd507..e1bbc4dee9 100644 --- a/tests/worker/test_replayer.py +++ b/tests/worker/test_replayer.py @@ -3,6 +3,7 @@ import re import sys import uuid +from contextlib import aclosing from dataclasses import dataclass from datetime import timedelta from pathlib import Path @@ -131,6 +132,22 @@ async def test_replayer_workflow_complete_json() -> None: ) +async def test_replay_iterator_closes_after_an_early_exit() -> None: + path = Path(__file__).with_name("test_replayer_complete_history.json") + history = WorkflowHistory.from_json("fake", path.read_text()) + + async def histories(): + yield history + yield history + + replayer = Replayer(workflows=[SayHelloWorkflow]) + async with aclosing(histories()) as source: + async with replayer.workflow_replay_iterator(source) as results: + assert (await anext(results)).replay_failure is None + assert await anext(results, None) is None + assert await anext(source) is history + + async def test_replayer_workflow_incomplete(client: Client) -> None: # Run workflow to wait point async with new_say_hello_worker(client) as worker: diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py new file mode 100644 index 0000000000..86113207bc --- /dev/null +++ b/tests/worker/test_workflow_streams.py @@ -0,0 +1,1156 @@ +"""Tests of the Stream calls of one Workflow instance, with no server.""" + +import asyncio +import dataclasses +from collections.abc import Sequence +from dataclasses import dataclass +from datetime import datetime, timedelta, timezone +from typing import Any + +import pytest +from google.protobuf.duration_pb2 import Duration +from google.protobuf.message import Message + +import temporalio.api.common.v1 +import temporalio.bridge.worker +import temporalio.common +import temporalio.converter +import temporalio.converter._extstore +import temporalio.nexus.system +import temporalio.worker +from temporalio import workflow +from temporalio.api.common.v1 import ActivityType, Payload +from temporalio.api.enums.v1 import RetryState, StreamErrorReason, TimeoutType +from temporalio.api.failure.v1 import ( + ActivityFailureInfo, + ApplicationFailureInfo, + Failure, + TimeoutFailureInfo, +) +from temporalio.api.sdk.v1 import ( + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + StreamRef, +) +from temporalio.api.sdk.v1.external_storage_pb2 import ExternalStorageReference +from temporalio.api.stream.v1 import StreamRecord +from temporalio.api.streamservice.v1 import DescribeStreamResponse +from temporalio.bridge.proto.activity_result import ( + ActivityResolution, +) +from temporalio.bridge.proto.activity_result import Success as ActivitySuccess +from temporalio.bridge.proto.workflow_activation import ( + InitializeWorkflow, + RemoveFromCache, + ResolveActivity, + ResolveStreamAppend, + ResolveStreamRead, + SignalWorkflow, + StreamAppended, + StreamPage, + WorkflowActivation, + WorkflowActivationJob, +) +from temporalio.bridge.proto.workflow_commands import ( + AppendToStream, + CompleteWorkflowExecution, + ReadStream, + RequestCancelLocalActivity, + WorkflowCommand, +) +from temporalio.bridge.proto.workflow_completion import ( + Success, + WorkflowActivationCompletion, +) +from temporalio.client import StreamConfig, StreamSelectContext, StreamStore +from temporalio.converter import ( + ExternalStorage, + StorageDriverWorkflowInfo, + WorkflowSerializationContext, +) +from temporalio.exceptions import ApplicationError, StreamError +from temporalio.nexus.system import _support +from temporalio.nexus.system.stream_service import StreamRef as ModelRef +from temporalio.nexus.system.stream_service.models import ( + CreateStreamResult, + StreamIdConflictPolicy, +) +from temporalio.testing import MemoryStreamStore +from temporalio.worker._workflow import _CommandAwareDataConverter +from temporalio.worker._workflow_instance import ( + _WorkflowInstanceImpl, + _WorkflowLogicFlag, # type: ignore[reportPrivateLocalImportUsage] +) +from tests.helpers.streams import ( + CodecCall, + ContextCodec, + core_failure, + failure_note, + wrapped, +) +from tests.test_extstore import InMemoryTestDriver + + +@workflow.defn +class _StreamWorkflow: + @workflow.run + async def run(self) -> None: + pass + + +def _new_instance( + workflow_class: type, + stream_config: StreamConfig | None = None, + interceptor_classes: Sequence[ + type[temporalio.worker.WorkflowInboundInterceptor] + ] = (), + failure_exception_types: Sequence[type[BaseException]] = (), +) -> _WorkflowInstanceImpl: + defn = workflow._Definition.must_from_class(workflow_class) + start_time = datetime(2026, 1, 1, tzinfo=timezone.utc) + instance = temporalio.worker.UnsandboxedWorkflowRunner().create_instance( + temporalio.worker.WorkflowInstanceDetails( + payload_converter_factory=temporalio.converter.DefaultPayloadConverter, + failure_converter_class=temporalio.converter.DefaultFailureConverter, + interceptor_classes=interceptor_classes, + defn=defn, + info=workflow.Info( + attempt=1, + continued_run_id=None, + cron_schedule=None, + execution_timeout=None, + first_execution_run_id="first-run", + headers={}, + namespace="ns", + original_execution_run_id="run", + parent=None, + root=None, + priority=temporalio.common.Priority(), + raw_memo={}, + retry_policy=None, + run_id="run", + run_timeout=None, + search_attributes={}, + start_time=start_time, + task_queue="tq", + task_timeout=timedelta(seconds=10), + typed_search_attributes=temporalio.common.TypedSearchAttributes.empty, + workflow_id="wf", + workflow_start_time=start_time, + workflow_type=defn.name or "", + ), + randomness_seed=1, + extern_functions={"__temporal_stream_config": lambda: stream_config}, + disable_eager_activity_execution=False, + worker_level_failure_exception_types=failure_exception_types, + patch_activation_callback=None, + last_completion_result=temporalio.api.common.v1.Payloads(), + last_failure=None, + ) + ) + assert isinstance(instance, _WorkflowInstanceImpl) + return instance + + +async def _activate( + instance: _WorkflowInstanceImpl, + *jobs: WorkflowActivationJob, + replaying: bool = False, + flags: Sequence[int] = (), +) -> WorkflowActivationCompletion: + # A Worker runs an activation in another thread too, so that the tasks of the + # Workflow don't run inside the task of the caller. + activation = WorkflowActivation( + run_id="run", jobs=jobs, is_replaying=replaying, available_internal_flags=flags + ) + return await asyncio.to_thread(instance.activate, activation) + + +async def test_stream_payloads_take_the_codec_with_no_context_and_no_storage() -> None: + calls: list[CodecCall] = [] + driver = InMemoryTestDriver() + converter = dataclasses.replace( + temporalio.converter.DataConverter.default, + payload_codec=ContextCodec(calls), + external_storage=ExternalStorage(drivers=[driver], payload_size_threshold=0), + ) + context = WorkflowSerializationContext(namespace="ns", workflow_id="wf") + command_aware = _CommandAwareDataConverter.create( + instance=_new_instance(_StreamWorkflow), + context_free_dc=converter, + workflow_context_dc=converter.with_context(context), + workflow_context=context, + ) + to_payload = temporalio.converter.PayloadConverter.default.to_payload + reference = to_payload(ExternalStorageReference(driver_name=driver.name())) + bodies = [to_payload("plain"), reference] + result = to_payload("result") + + completion = WorkflowActivationCompletion( + successful=Success( + commands=[ + WorkflowCommand( + append_to_stream=AppendToStream( + seq=1, stream=StreamRef(id="s", store="memory"), bodies=bodies + ) + ), + WorkflowCommand( + complete_workflow_execution=CompleteWorkflowExecution(result=result) + ), + ] + ) + ) + await temporalio.bridge.worker.encode_completion( + completion, command_aware, encode_headers=True, storage_concurrency_limit=1 + ) + append, complete = completion.successful.commands + assert list(append.append_to_stream.bodies) == [wrapped(body) for body in bodies] + stored = complete.complete_workflow_execution.result + assert stored.metadata["messageType"] == reference.metadata["messageType"] + assert driver._store_calls == 1 + assert calls == [("encode", None, 1)] * 2 + [("encode", context, 1)] + + # A writer with no codec can write a claim of a payload in this Worker's storage, and + # a body that has the mark of a system Nexus envelope. + claim = Payload() + claim.CopyFrom(stored) + claim.metadata[temporalio.converter._extstore._REFERENCE_MARKER_KEY] = b"true" + envelope = to_payload("envelope") + envelope.metadata[temporalio.nexus.system._SYSTEM_PAYLOAD_METADATA_KEY] = b"true" + failure = Failure( + message="A later attempt has written to the Stream", + application_failure_info=ApplicationFailureInfo( + type="stream_fenced", + details=temporalio.api.common.v1.Payloads(payloads=[wrapped(result)]), + ), + ) + records = [*append.append_to_stream.bodies, claim, envelope] + activation = WorkflowActivation( + jobs=[ + WorkflowActivationJob( + resolve_stream_read=ResolveStreamRead( + seq=1, + page=StreamPage( + records=[ + StreamRecord(body=body, offset=bytes([at + 1])) + for at, body in enumerate(records) + ] + ), + ) + ), + WorkflowActivationJob( + resolve_stream_read=ResolveStreamRead(seq=2, failed=failure) + ), + WorkflowActivationJob( + resolve_stream_append=ResolveStreamAppend(seq=1, failed=failure) + ), + WorkflowActivationJob( + resolve_activity=ResolveActivity( + seq=1, + result=ActivityResolution(completed=ActivitySuccess(result=stored)), + ) + ), + ] + ) + calls.clear() + await temporalio.bridge.worker.decode_activation( + activation, command_aware, decode_headers=True, storage_concurrency_limit=1 + ) + read, failed_read, appended, activity = activation.jobs + assert [record.body for record in read.resolve_stream_read.page.records] == [ + *bodies, + claim, + envelope, + ] + assert failed_read.resolve_stream_read.failed == failure + assert appended.resolve_stream_append.failed == failure + assert activity.resolve_activity.result.completed.result == result + assert driver._retrieve_calls == 1 + assert calls == [("decode", None, 1)] * 4 + [("decode", context, 1)] + + +_REFUSALS = [ + StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND, + StreamErrorReason.STREAM_ERROR_REASON_ALREADY_EXISTS, + StreamErrorReason.STREAM_ERROR_REASON_EXPIRED, + StreamErrorReason.STREAM_ERROR_REASON_FENCED, +] +_UNAVAILABLE = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE +_STORE_CALL = "__temporal_stream_store_call" + + +@dataclass +class _Call: + operation: str + stream: str + store: str | None = None + bodies: Sequence[int] = () + cancel: bool = False + refusal: StreamErrorReason.ValueType | None = None + timeout: bool = False + unserved: bool = False + outcome: Any = None + + +class _Script: + phases: list[list[_Call]] = [] + late_cancels = False + intercepted: list[tuple[str, Any]] = [] + local_activities: list[str] = [] + + +@workflow.defn +class _ScriptWorkflow: + @workflow.run + async def run(self) -> None: + streams: dict[str, Any] = {} + for phase in _Script.phases: + tasks = [asyncio.ensure_future(self._call(streams, call)) for call in phase] + # Each task makes its call in its first step, and the task of the call runs + # one step later. + await asyncio.sleep(0) + if _Script.late_cancels: + await asyncio.sleep(0) + for call, task in zip(phase, tasks): + if call.cancel: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + + async def _call(self, streams: dict[str, Any], call: _Call) -> None: + try: + if call.operation == "create": + stream = await workflow.create_stream( + id=call.stream, store=call.store, body_type=int + ) + streams[call.stream] = stream + call.outcome = (stream.ref.store, stream.created) + return + stream = streams.get(call.stream) or workflow.get_stream( + ModelRef[int](id=call.stream, store=call.store) + ) + if call.operation == "append": + appended = await stream.append(*call.bodies) + call.outcome = (appended.first_offset, appended.last_offset) + else: + described = await stream.describe() + call.outcome = described.last_offset + except StreamError as err: + call.outcome = err.reason + except asyncio.CancelledError: + call.outcome = "cancelled" + raise + + +class _RecordingInbound(temporalio.worker.WorkflowInboundInterceptor): + def init(self, outbound: temporalio.worker.WorkflowOutboundInterceptor) -> None: + super().init(_RecordingOutbound(outbound)) + + +class _RecordingOutbound(temporalio.worker.WorkflowOutboundInterceptor): + def start_local_activity( + self, input: temporalio.worker.StartLocalActivityInput + ) -> workflow.ActivityHandle[Any]: + _Script.local_activities.append(input.activity) + return super().start_local_activity(input) + + async def start_create_stream(self, request: Any, output_type: Any = None) -> Any: + _Script.intercepted.append(("create", request)) + return await super().start_create_stream(request, output_type) + + async def start_append_records(self, request: Any) -> Any: + _Script.intercepted.append(("append", request)) + return await super().start_append_records(request) + + async def start_describe_stream(self, request: Any) -> Any: + _Script.intercepted.append(("describe", request)) + return await super().start_describe_stream(request) + + +def _resolve_call( + call: _Call, seq: int, *, created: bool = True +) -> WorkflowActivationJob: + converter = temporalio.converter.DefaultPayloadConverter() + job = WorkflowActivationJob() + if call.operation == "append": + job.resolve_stream_append.seq = seq + if call.refusal is not None: + job.resolve_stream_append.failed.CopyFrom(core_failure(call.refusal)) + else: + job.resolve_stream_append.appended.CopyFrom( + StreamAppended( + first_offset=b"first%d" % seq, last_offset=b"last%d" % seq + ) + ) + return job + + job.resolve_activity.seq = seq + job.resolve_activity.is_local = True + result = job.resolve_activity.result + if call.cancel: + result.cancelled.failure.canceled_failure_info.SetInParent() + elif call.refusal is not None: + result.failed.failure.CopyFrom(core_failure(call.refusal)) + elif call.unserved: + result.failed.failure.CopyFrom( + Failure( + message="No Stream Store", + application_failure_info=ApplicationFailureInfo(type="ValueError"), + ) + ) + elif call.timeout: + result.failed.failure.CopyFrom( + Failure( + message="Local Activity timed out", + cause=Failure( + timeout_failure_info=TimeoutFailureInfo( + timeout_type=TimeoutType.TIMEOUT_TYPE_SCHEDULE_TO_CLOSE + ) + ), + activity_failure_info=ActivityFailureInfo( + activity_type=ActivityType(name=_STORE_CALL), + retry_state=RetryState.RETRY_STATE_CANCEL_REQUESTED, + ), + ) + ) + else: + answer: Message = ( + CreateStreamResponse( + ref=StreamRef(id=call.stream, store="b"), created=created + ) + if call.operation == "create" + else DescribeStreamResponse(last_offset=b"last%d" % seq) + ) + result.completed.result.CopyFrom( + converter.to_payload(answer.SerializeToString()) + ) + return job + + +@workflow.defn +class _ReuseStreamWorkflow: + @workflow.run + async def run(self) -> bool | None: + stream = await workflow.create_stream( + id="s", + store="b", + id_conflict_policy=StreamIdConflictPolicy.StreamIdConflictPolicyUseExisting, + ) + return stream.created + + +@pytest.mark.parametrize("intercepted", [False, True]) +async def test_create_preserves_the_recorded_existing_stream_result( + intercepted: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + async def existing(_self: Any, request: Any, _output_type: Any = None) -> Any: + answer = asyncio.get_running_loop().create_future() + answer.set_result(CreateStreamResult(ref=request.stream_ref, created=False)) + return answer + + if intercepted: + monkeypatch.setattr(_RecordingOutbound, "start_create_stream", existing) + flag = _WorkflowLogicFlag.REPORT_EXISTING_STREAM_AS_FALSE + for replaying, flags, expected in [ + (False, (), False), + (True, (), None), + (True, (flag,), False), + ]: + instance = _new_instance( + _ReuseStreamWorkflow, + StreamConfig([MemoryStreamStore(name="b")]), + [_RecordingInbound], + ) + completion = await _activate( + instance, + WorkflowActivationJob(initialize_workflow=InitializeWorkflow()), + replaying=replaying, + flags=flags, + ) + if not intercepted: + [schedule] = completion.successful.commands + completion = await _activate( + instance, + _resolve_call( + _Call("create", "s"), + schedule.schedule_local_activity.seq, + created=False, + ), + replaying=replaying, + flags=flags, + ) + [command] = completion.successful.commands + assert command.HasField("complete_workflow_execution") + payload = command.complete_workflow_execution.result + assert ( + temporalio.converter.PayloadConverter.default.from_payload(payload) + is expected + ) + assert (flag in completion.successful.used_internal_flags) == (not replaying) + + +@pytest.mark.parametrize("replaying", [False, True]) +@pytest.mark.parametrize("late_cancels", [False, True]) +async def test_stream_calls_keep_their_results_when_jobs_arrive_in_reverse_order( + replaying: bool, late_cancels: bool +) -> None: + a, b = MemoryStreamStore(name="a"), MemoryStreamStore(name="b") + selects: list[StreamSelectContext] = [] + + def selector(context: StreamSelectContext) -> StreamStore: + selects.append(context) + return a + + phases = [ + [ + _Call("create", "created"), + _Call("append", "appended", "a", [1, 2]), + _Call("describe", "described", "a"), + ], + [ + _Call("append", "created", bodies=[3]), + _Call("create", "cancelled", cancel=True), + _Call("append", "cancelled-append", "a", [4], cancel=True), + _Call("describe", "refused", "a", refusal=_REFUSALS[0]), + ], + ] + _Script.phases, _Script.intercepted, _Script.local_activities = phases, [], [] + _Script.late_cancels = late_cancels + instance = _new_instance( + _ScriptWorkflow, + StreamConfig([a, b], store_selector=selector), + [_RecordingInbound], + ) + converter = temporalio.converter.DefaultPayloadConverter() + jobs = [WorkflowActivationJob(initialize_workflow=InitializeWorkflow())] + seqs = {"append": 0, "activity": 0} + for phase in phases: + completion = await _activate(instance, *jobs, replaying=replaying) + commands = completion.successful.commands + jobs = [] + cancelled: list[int] = [] + for call, command in zip(phase, commands[: len(phase)], strict=True): + kind = "append" if call.operation == "append" else "activity" + seqs[kind] += 1 + seq = seqs[kind] + if kind == "append": + assert command.append_to_stream.seq == seq + assert command.append_to_stream.stream == StreamRef( + id=call.stream, store="b" if call.stream == "created" else "a" + ) + assert converter.from_payloads(command.append_to_stream.bodies) == list( + call.bodies + ) + else: + activity = command.schedule_local_activity + assert activity.seq == seq and activity.activity_type == _STORE_CALL + operation, store, raw, request_id = converter.from_payloads( + activity.arguments + ) + assert operation == ( + "CreateStream" if call.operation == "create" else "DescribeStream" + ) + assert store == "a" + assert request_id == ( + "first-run" if call.operation == "create" else None + ) + if call.operation == "create": + assert CreateStreamRequest.FromString(raw).stream_ref == StreamRef( + id=call.stream + ) + else: + assert DescribeStreamRequest.FromString(raw).ref == StreamRef( + id=call.stream, store="a" + ) + if call.cancel: + cancelled.append(seq) + jobs.append(_resolve_call(call, seq)) + assert list(commands[len(phase) :]) == [ + WorkflowCommand( + request_cancel_local_activity=RequestCancelLocalActivity(seq=seq) + ) + for seq in cancelled + ] + jobs.reverse() + completion = await _activate(instance, *jobs, replaying=replaying) + [command] = completion.successful.commands + assert command.HasField("complete_workflow_execution") + calls = [call for phase in phases for call in phase] + assert [call.outcome for call in calls] == [ + ("b", True), + (b"first1", b"last1"), + b"last2", + (b"first2", b"last2"), + "cancelled", + "cancelled", + _REFUSALS[0], + ] + assert not instance._streams._appends + target = StorageDriverWorkflowInfo( + namespace="ns", id="wf", run_id="run", type="_ScriptWorkflow" + ) + assert selects == [ + StreamSelectContext(id=id, target=target, namespace="ns") + for id in ("created", "cancelled") + ] + assert [operation for operation, _ in _Script.intercepted] == [ + call.operation for call in calls + ] + assert _Script.local_activities == [_STORE_CALL] * 4 + for operation, request in _Script.intercepted: + if operation == "create": + assert request.stream_ref.store is None + assert ( + await _activate( + instance, WorkflowActivationJob(remove_from_cache=RemoveFromCache()) + ) + ).HasField("successful") + + +@pytest.mark.parametrize("replaying", [False, True]) +@pytest.mark.parametrize( + ("operation", "failure"), + [ + (op, failure) + for op in ("create", "describe") + for failure in ("outage", "timeout", "unserved") + ] + + [(op, "selector") for op in ("create", "append", "describe")], +) +async def test_store_failures_fail_the_task_even_when_workflow_errors_are_enabled( + operation: str, failure: str, replaying: bool +) -> None: + store = MemoryStreamStore(name="a") + + def selector(_context: StreamSelectContext) -> StreamStore: + if failure == "selector": + raise ApplicationError("The selector has no Store for this Stream") + return store + + call = _Call( + operation, + "s", + bodies=[1], + refusal=_UNAVAILABLE if failure == "outage" else None, + timeout=failure == "timeout", + unserved=failure == "unserved", + ) + _Script.phases, _Script.late_cancels = [[call]], False + instance = _new_instance( + _ScriptWorkflow, + StreamConfig([store], store_selector=selector), + failure_exception_types=[Exception], + ) + completion = await _activate( + instance, + WorkflowActivationJob(initialize_workflow=InitializeWorkflow()), + replaying=replaying, + ) + if failure != "selector": + assert len(completion.successful.commands) == 1 + completion = await _activate( + instance, _resolve_call(call, 1), replaying=replaying + ) + assert completion.HasField("failed") + assert ( + await _activate( + instance, WorkflowActivationJob(remove_from_cache=RemoveFromCache()) + ) + ).HasField("successful") + + +class _EachCall: + """The calls of :py:class:`_EachCallWorkflow`, and what its selector saw.""" + + operations: list[str] = [] + instance: _WorkflowInstanceImpl | None = None + selects: list[tuple[str, int]] = [] + """The Stream id of each selector call, with the number of commands before it.""" + + +@workflow.defn +class _EachCallWorkflow: + @workflow.run + async def run(self) -> None: + calls: list[Any] = [] + for at, operation in enumerate(_EachCall.operations): + stream = workflow.get_stream(ModelRef[int](id=f"s{at}")) + if operation == "create": + calls.append(workflow.create_stream(id=f"s{at}", body_type=int)) + elif operation == "append": + calls.append(stream.append(at)) + elif operation == "read": + calls.append(stream.read_page()) + else: + calls.append(stream.describe()) + if len(calls) == 1: + # The run gets the error of its one call, so no task holds an error that + # no one reads. + await calls[0] + return + tasks = [asyncio.ensure_future(call) for call in calls] + # Each task makes its call in its first step. + await asyncio.sleep(0) + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + + +def _store_of(command: WorkflowCommand) -> str: + """Return the Store name that the command of a Stream call has.""" + variant = command.WhichOneof("variant") + if variant == "append_to_stream": + return command.append_to_stream.stream.store + if variant == "read_stream": + return command.read_stream.stream.store + # The Local Activity of a create or a describe has the Store name second. + [_, store, *_] = command.schedule_local_activity.arguments + return temporalio.converter.DefaultPayloadConverter().from_payload(store, str) + + +async def test_the_store_of_a_call_is_chosen_before_its_command() -> None: + operations = ["create", "append", "read", "describe"] + a, b = MemoryStreamStore(name="a"), MemoryStreamStore(name="b") + for on_b in ([False, True, False, True], [True, False, True, False]): + + def selector(context: StreamSelectContext) -> StreamStore: + assert _EachCall.instance + sent = _EachCall.instance._current_completion.successful.commands + _EachCall.selects.append((context.id, len(sent))) + return b if on_b[int(context.id[1:])] else a + + config = StreamConfig([a, b], store_selector=selector) + _EachCall.operations = operations + for replaying in (False, True): + with failure_note(f"on b {on_b}, replaying {replaying}"): + _EachCall.selects = [] + instance = _EachCall.instance = _new_instance(_EachCallWorkflow, config) + initialize = WorkflowActivationJob( + initialize_workflow=InitializeWorkflow() + ) + completion = await _activate(instance, initialize, replaying=replaying) + # The selector runs once for each call, before the command of the call. + assert _EachCall.selects == [ + (f"s{at}", at) for at in range(len(operations)) + ] + commands = completion.successful.commands + assert [command.WhichOneof("variant") for command in commands] == [ + "schedule_local_activity", + "append_to_stream", + "read_stream", + "schedule_local_activity", + # A cancel sends a command only for a Local Activity. + "request_cancel_local_activity", + "request_cancel_local_activity", + "complete_workflow_execution", + ] + assert [_store_of(command) for command in commands[:4]] == [ + "b" if mine else "a" for mine in on_b + ] + + +# SDK Core uses the only Store of a Worker for a ref with no Store name. The SDK +# picks that Store itself, so each command has its name. +async def test_a_ref_with_no_store_name_goes_to_the_only_store() -> None: + operations = ["create", "append", "read", "describe"] + config = StreamConfig([MemoryStreamStore(name="only")]) + _EachCall.operations = operations + for replaying in (False, True): + with failure_note(f"replaying {replaying}"): + instance = _new_instance(_EachCallWorkflow, config) + initialize = WorkflowActivationJob(initialize_workflow=InitializeWorkflow()) + completion = await _activate(instance, initialize, replaying=replaying) + commands = completion.successful.commands[: len(operations)] + assert [command.WhichOneof("variant") for command in commands] == [ + "schedule_local_activity", + "append_to_stream", + "read_stream", + "schedule_local_activity", + ] + stores = [_store_of(command) for command in commands] + assert stores == ["only"] * len(operations) + + +async def test_a_ref_with_no_store_name_needs_a_selector_for_two_stores() -> None: + a, b = MemoryStreamStore(name="a"), MemoryStreamStore(name="b") + with pytest.raises(ValueError, match="store_selector must be specified"): + StreamConfig([a, b]) + unregistered = MemoryStreamStore(name="c") + config = StreamConfig([a, b], store_selector=lambda _: unregistered) + for operation in ["create", "append", "read", "describe"]: + _EachCall.operations = [operation] + for replaying in (False, True): + with failure_note(f"{operation}, replaying {replaying}"): + instance = _new_instance(_EachCallWorkflow, config) + initialize = WorkflowActivationJob( + initialize_workflow=InitializeWorkflow() + ) + completion = await _activate(instance, initialize, replaying=replaying) + message = completion.failed.failure.message + assert "not registered in StreamConfig.stores" in message + + +async def test_a_stream_call_with_no_stream_config_fails_the_task() -> None: + for operation in ["create", "append", "read", "describe"]: + _EachCall.operations = [operation] + for replaying in (False, True): + instance = _new_instance(_EachCallWorkflow) + initialize = WorkflowActivationJob(initialize_workflow=InitializeWorkflow()) + completion = await _activate(instance, initialize, replaying=replaying) + assert "no stream_config" in completion.failed.failure.message, operation + + +@dataclass +class _ReadCall: + stream: str + start: int + """The offset that the first page comes after. Zero is the start of the Stream.""" + wait: timedelta | None + max_records: int | None + max_bytes: int | None + pages: int + """The maximum number of pages that the reader asks for.""" + body_type: Any + """The body type of the reader's Stream, which is ``int``, ``Any`` or none.""" + outcome: list[Any] = dataclasses.field(default_factory=list) + + +class _ReadScript: + calls: list[_ReadCall] = [] + steps: list[tuple[list[int], list[int]]] = [] + + +@workflow.defn +class _ReadsWorkflow: + def __init__(self) -> None: + self._readers: dict[int, asyncio.Future[None]] = {} + + @workflow.run + async def run(self) -> None: + await workflow.wait_condition(lambda: False) + + @workflow.signal + def step(self) -> None: + cancels, starts = _ReadScript.steps.pop(0) + for call in cancels: + self._readers[call].cancel() + for call in starts: + reader = self._read(_ReadScript.calls[call]) + self._readers[call] = asyncio.ensure_future(reader) + + async def _read(self, call: _ReadCall) -> None: + body_type: Any = call.body_type + ref: Any = ModelRef(id=call.stream, store="a") + if body_type: + ref = ModelRef[body_type](id=call.stream, store="a") + stream = workflow.get_stream(ref) + offset = _offset(call.start) or None + try: + for _ in range(call.pages): + page = await stream.read_page( + from_offset=offset, + wait=call.wait, + max_records=call.max_records, + max_bytes=call.max_bytes, + ) + bodies = [record.body for record in page.records] + offset = page.last_offset + call.outcome.append((bodies, offset or b"")) + except StreamError as err: + call.outcome.append(err.reason) + except TypeError: + call.outcome.append("TypeError") + except asyncio.CancelledError: + call.outcome.append("cancelled") + raise + + +def _offset(number: int) -> bytes: + return number.to_bytes(8, "big") if number else b"" + + +_READ_FLAGS = [ + (), + (_WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH,), +] + + +async def _start_readers( + calls: list[_ReadCall], flags: Sequence[int], replaying: bool +) -> tuple[_WorkflowInstanceImpl, WorkflowActivationCompletion]: + _ReadScript.calls = calls + _ReadScript.steps = [([], list(range(len(calls))))] + instance = _new_instance( + _ReadsWorkflow, StreamConfig([MemoryStreamStore(name="a")]) + ) + completion = await _activate( + instance, + WorkflowActivationJob(initialize_workflow=InitializeWorkflow()), + WorkflowActivationJob(signal_workflow=SignalWorkflow(signal_name="step")), + flags=flags, + replaying=replaying, + ) + return instance, completion + + +def _read_result(seq: int, bodies: Sequence[Any], last: int) -> 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 enumerate(bodies, 1) + ], + last_offset=_offset(last), + ), + ) + ) + + +@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"), + from_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, ["text"], 3), + _read_result(1, [], 4), + flags=flags, + replaying=replaying, + ) + assert [call.outcome for call in calls] == [ + [([], _offset(4))], + [(["text"], _offset(3))], + ["TypeError"], + ] + next_read = expected[0] + next_read.seq, next_read.from_offset = 3, _offset(4) + 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(4)), 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] if when == "with result" else ["not an integer"], 2), + 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, ["not an integer"], 1)) + 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 [page.records, page.last_offset] + # 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"), + from_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], last: int, wait_cut: bool = False + ) -> WorkflowActivationJob: + stream_page = StreamPage( + records=[ + StreamRecord(offset=_offset(number), body=converter.to_payload(number)) + for number in records + ], + last_offset=_offset(last), + wait_cut=wait_cut, + ) + job = ResolveStreamRead(seq=seq, page=stream_page) + return WorkflowActivationJob(resolve_stream_read=job) + + def start(how: str, seconds: int | None = 5) -> WorkflowActivationJob: + arguments = [converter.to_payload(how), converter.to_payload(seconds)] + return WorkflowActivationJob( + initialize_workflow=InitializeWorkflow(arguments=arguments) + ) + + def result(completion: WorkflowActivationCompletion) -> Any: + [complete] = completion.successful.commands + return converter.from_payload(complete.complete_workflow_execution.result) + + config = StreamConfig([MemoryStreamStore(name="a")]) + # A single read gives a page with no Record as it is, also a cut one. + for wait_cut in (True, False): + with failure_note(f"wait_cut {wait_cut}"): + instance = _new_instance(_ReadToTwoWorkflow, config) + completion = await _activate(instance, start("read_page")) + assert list(completion.successful.commands) == [read(1, 0)] + completion = await _activate(instance, page(1, [], 0, wait_cut=wait_cut)) + assert result(completion) == [[], None] + + 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], 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, [], 1, wait_cut=True)) + assert list(completion.successful.commands) == [read(3, 1)] + completion = await _activate(instance, page(3, [], 1)) + assert list(completion.successful.commands) == [read(4, 1)] + completion = await _activate(instance, page(4, [2], 2)) + expected = [1, 2] if how == "read" else [[1], [], [], [2]] + assert result(completion) == expected + + flag = _WorkflowLogicFlag.USE_LAST_STREAM_RECORD_OFFSET + for replaying, flags, after in [(False, (), 1), (True, (), 0), (True, (flag,), 1)]: + instance = _new_instance(_ReadToTwoWorkflow, config) + await _activate(instance, start("read_pages"), replaying=replaying, flags=flags) + completion = await _activate( + instance, page(1, [1], 0), replaying=replaying, flags=flags + ) + assert list(completion.successful.commands) == [read(2, after)] + assert (flag in completion.successful.used_internal_flags) == (not replaying) + + # 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], 1)) + assert list(completion.successful.commands) == [read(2, 1, later)] + completion = await _activate(instance, page(2, [], 1)) + 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)]