From df9280de937e05ac6200db23e48ada47f4ce6596 Mon Sep 17 00:00:00 2001 From: nvasiu Date: Tue, 20 Oct 2026 23:14:58 +0000 Subject: [PATCH] feat(dmap): add the distributed map operation Add ctx.distributed_map, which runs a processor function over a large item source and resolves with a summary when the run reaches a terminal state. Covers the configuration types, the handler decorators, the result types and the checkpoint translation. --- .../__init__.py | 40 +- .../config.py | 692 ++++++- .../context.py | 88 +- .../dmap/__init__.py | 0 .../dmap/helpers.py | 727 +++++++ .../dmap/models.py | 327 +++ .../exceptions.py | 5 + .../lambda_service.py | 920 +++++++++ .../operation/dmap.py | 330 +++ .../plugin.py | 2 + .../serdes.py | 9 + .../aws_durable_execution_sdk_python/state.py | 3 + .../aws_durable_execution_sdk_python/types.py | 48 + .../tests/config_test.py | 363 ++++ .../tests/context_test.py | 271 +++ .../tests/dmap/helpers_test.py | 1086 ++++++++++ .../tests/dmap/models_test.py | 617 ++++++ .../tests/dmap/typing_test.py | 159 ++ .../e2e/dmap_durable_item_replay_test.py | 274 +++ .../tests/e2e/dmap_helpers_int_test.py | 376 ++++ .../tests/e2e/dmap_int_test.py | 593 ++++++ .../tests/exceptions_test.py | 6 + .../tests/lambda_service_test.py | 237 ++- .../tests/operation/dmap_test.py | 1781 +++++++++++++++++ .../tests/plugin_test.py | 20 + 25 files changed, 8968 insertions(+), 6 deletions(-) create mode 100644 packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/dmap/__init__.py create mode 100644 packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/dmap/helpers.py create mode 100644 packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/dmap/models.py create mode 100644 packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/operation/dmap.py create mode 100644 packages/aws-durable-execution-sdk-python/tests/dmap/helpers_test.py create mode 100644 packages/aws-durable-execution-sdk-python/tests/dmap/models_test.py create mode 100644 packages/aws-durable-execution-sdk-python/tests/dmap/typing_test.py create mode 100644 packages/aws-durable-execution-sdk-python/tests/e2e/dmap_durable_item_replay_test.py create mode 100644 packages/aws-durable-execution-sdk-python/tests/e2e/dmap_helpers_int_test.py create mode 100644 packages/aws-durable-execution-sdk-python/tests/e2e/dmap_int_test.py create mode 100644 packages/aws-durable-execution-sdk-python/tests/operation/dmap_test.py diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/__init__.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/__init__.py index 69f7bb164..43e13f058 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/__init__.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/__init__.py @@ -16,6 +16,8 @@ CompletionItemStatus, CompletionOutcome, CompletionStatus, + DistributedMapItemStatus, + DistributedMapStatus, ParallelBranch, complete_batch, continue_batch, @@ -27,6 +29,20 @@ durable_wait_for_callback, durable_with_child_context, ) +from aws_durable_execution_sdk_python.dmap.helpers import ( + DistributedMapProcessorEvent, + DistributedMapProcessorRecord, + DistributedMapReaderEvent, + ReaderPage, + process_distributed_map_batch, + process_distributed_map_items, + read_distributed_map_page, +) +from aws_durable_execution_sdk_python.dmap.models import ( + DistributedMapResult, + DistributedMapResultItem, + DistributedMapSummary, +) # Most common exceptions - users need to handle these exceptions from aws_durable_execution_sdk_python.exceptions import ( @@ -35,6 +51,7 @@ CallbackSubmitterError, CallbackTimeoutError, ChildContextError, + DistributedMapError, DurableExecutionsError, DurableOperationError, ExecutionError, @@ -53,7 +70,12 @@ from aws_durable_execution_sdk_python.retries import WithRetryConfig, with_retry # Essential context types - passed to user functions -from aws_durable_execution_sdk_python.types import StepContext +from aws_durable_execution_sdk_python.types import ( + DistributedMapBatchContext, + DistributedMapItemContext, + DistributedMapReaderContext, + StepContext, +) __all__ = [ @@ -69,6 +91,18 @@ "CompletionItemStatus", "CompletionOutcome", "CompletionStatus", + "DistributedMapBatchContext", + "DistributedMapError", + "DistributedMapItemContext", + "DistributedMapItemStatus", + "DistributedMapProcessorEvent", + "DistributedMapProcessorRecord", + "DistributedMapReaderContext", + "DistributedMapReaderEvent", + "DistributedMapResult", + "DistributedMapResultItem", + "DistributedMapStatus", + "DistributedMapSummary", "DurableContext", "DurableExecutionsError", "DurableOperationError", @@ -77,6 +111,7 @@ "InvokeError", "ParallelBranch", "PluginLoadError", + "ReaderPage", "RetryableSerDesError", "SerDesError", "StepContext", @@ -92,5 +127,8 @@ "durable_step", "durable_wait_for_callback", "durable_with_child_context", + "process_distributed_map_batch", + "process_distributed_map_items", + "read_distributed_map_page", "with_retry", ] diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/config.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/config.py index 199d4e89f..6e7fda281 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/config.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/config.py @@ -7,17 +7,64 @@ import string from dataclasses import dataclass, field from enum import Enum, StrEnum -from typing import TYPE_CHECKING, Generic, TypeVar +from typing import TYPE_CHECKING, Any, ClassVar, Generic, Literal, TypeVar from aws_durable_execution_sdk_python.exceptions import ValidationError +class DistributedMapStatus(Enum): + SUCCEEDED = "SUCCEEDED" + FAILED = "FAILED" + STOPPED = "STOPPED" + TIMED_OUT = "TIMED_OUT" + + +class DistributedMapItemStatus(Enum): + """Terminal status of a single map run item.""" + + SUCCEEDED = "SUCCEEDED" + FAILED = "FAILED" + UNKNOWN_TO_SDK_VERSION = "UNKNOWN_TO_SDK_VERSION" + + +class DistributedMapSourceFormat(Enum): + JSON_LINES = "JSON_LINES" + JSON_ARRAY = "JSON_ARRAY" + CSV = "CSV" + + +class DistributedMapS3SourceType(Enum): + """What an S3 distributed map source reads.""" + + OBJECT = "OBJECT" + LISTED_OBJECT_METADATA = "LISTED_OBJECT_METADATA" + LISTED_OBJECTS = "LISTED_OBJECTS" + + +class ProcessorResponseMode(Enum): + """How a processor function reports item outcomes.""" + + BATCH = "BATCH" + ITEM_OUTCOMES = "ITEM_OUTCOMES" + + +class DistributedMapCsvDelimiter(Enum): + """Column delimiter for a CSV distributed map source.""" + + COMMA = "COMMA" + PIPE = "PIPE" + SEMICOLON = "SEMICOLON" + SPACE = "SPACE" + TAB = "TAB" + + P = TypeVar("P") # Payload type R = TypeVar("R") # Result type T = TypeVar("T") +ItemOutput = TypeVar("ItemOutput") # Map run item output type if TYPE_CHECKING: - from collections.abc import Callable + from collections.abc import Callable, Sequence from aws_durable_execution_sdk_python.retries import RetryDecision from aws_durable_execution_sdk_python.serdes import SerDes @@ -546,6 +593,647 @@ def __post_init__(self) -> None: _validate_sub_type(self.sub_type) +# region map run configuration + + +@dataclass(frozen=True) +class S3Uri: + """A parsed ``s3://bucket/path`` URI.""" + + bucket: str + path: str | None = None + + @classmethod + def parse(cls, uri: str) -> S3Uri: + """Parse an ``s3://bucket/path`` URI, rejecting any other scheme.""" + if not uri.startswith("s3://"): + msg = f"S3 URI must start with s3://, got: {uri}" + raise ValidationError(msg) + bucket, _, path = uri.removeprefix("s3://").partition("/") + if not bucket: + msg = f"Invalid S3 URI: {uri}" + raise ValidationError(msg) + return cls(bucket=bucket, path=path or None) + + +def _validate_bucket_owner(value: str | None) -> None: + """Validate an expected bucket owner is a 12-digit account id.""" + if value is not None and ( + len(value) != 12 or not (value.isascii() and value.isdigit()) # noqa: PLR2004 + ): + msg = f"expected_bucket_owner must be a 12-digit account id, got: {value}" + raise ValidationError(msg) + + +def _validate_columns(name: str, columns: list[str] | None) -> None: + """Validate a CSV columns/headers list is non-empty and has no duplicates.""" + if columns is None: + return + if len(columns) == 0: + msg = f"{name} must be non-empty" + raise ValidationError(msg) + if len(set(columns)) != len(columns): + msg = f"{name} must not contain duplicates" + raise ValidationError(msg) + + +def _validate_function_name(name: str) -> None: + """Validate a Lambda function reference is present.""" + if not name: + msg = "function name must be non-empty" + raise ValidationError(msg) + + +def _validate_not_bool(name: str, value: object) -> None: + """Reject a bool, which passes as an int but reaches the wire as true or false.""" + if isinstance(value, bool): + msg = f"{name} must be a number, not a bool, got: {value!r}" + raise ValidationError(msg) + + +@dataclass(frozen=True) +class DistributedMapCompletionConfig: + """Failure-tolerance configuration for a map run.""" + + tolerated_failure_count: int | None = None + tolerated_failure_percentage: int | float | None = None + minimum_sample_size: int | None = None + + def __post_init__(self) -> None: + _validate_not_bool("tolerated_failure_count", self.tolerated_failure_count) + _validate_not_bool( + "tolerated_failure_percentage", self.tolerated_failure_percentage + ) + _validate_not_bool("minimum_sample_size", self.minimum_sample_size) + if ( + self.tolerated_failure_count is not None + and self.tolerated_failure_percentage is not None + ): + msg = ( + "tolerated_failure_count and tolerated_failure_percentage " + "are mutually exclusive" + ) + raise ValidationError(msg) + if ( + self.tolerated_failure_count is None + and self.tolerated_failure_percentage is None + ): + # Omitting the config entirely means zero tolerated failures, so an + # empty one is rejected rather than resolved to the same thing. + msg = ( + "a completion config must set tolerated_failure_count or " + "tolerated_failure_percentage" + ) + raise ValidationError(msg) + if ( + self.minimum_sample_size is not None + and self.tolerated_failure_percentage is None + ): + msg = "minimum_sample_size is only valid with tolerated_failure_percentage" + raise ValidationError(msg) + if ( + self.tolerated_failure_count is not None + and self.tolerated_failure_count < 0 + ): + msg = ( + "tolerated_failure_count must be non-negative, got: " + f"{self.tolerated_failure_count}" + ) + raise ValidationError(msg) + if self.tolerated_failure_percentage is not None and not ( + 0 <= self.tolerated_failure_percentage <= 100 # noqa: PLR2004 + ): + msg = ( + "tolerated_failure_percentage must be between 0 and 100, got: " + f"{self.tolerated_failure_percentage}" + ) + raise ValidationError(msg) + if self.minimum_sample_size is not None and self.minimum_sample_size < 1: + msg = ( + "minimum_sample_size must be at least 1, got: " + f"{self.minimum_sample_size}" + ) + raise ValidationError(msg) + + @staticmethod + def failure_count(count: int) -> DistributedMapCompletionConfig: + """Abort once this many items have permanently failed.""" + return DistributedMapCompletionConfig(tolerated_failure_count=count) + + @staticmethod + def failure_percentage( + percentage: int | float, *, minimum_sample_size: int | None = None + ) -> DistributedMapCompletionConfig: + """Abort once the failure rate exceeds this percentage.""" + return DistributedMapCompletionConfig( + tolerated_failure_percentage=percentage, + minimum_sample_size=minimum_sample_size, + ) + + +@dataclass(frozen=True) +class DistributedMapProcessorRetryConfig: + """Retry policy applied to each failing item of a map run.""" + + UNLIMITED: ClassVar[Literal["unlimited"]] = "unlimited" + + max_retry_attempts: int | Literal["unlimited"] | None = None + max_retry_duration: Duration | None = None + + def __post_init__(self) -> None: + attempts = self.max_retry_attempts + # max_retry_attempts reaches the wire as an int or as UNLIMITED, so anything + # else is rejected here. A bool is an int in Python, so it is named on its + # own: the wire would carry it as true or false. + if ( + attempts is not None + and attempts != self.UNLIMITED + and ( + isinstance(attempts, bool) + or not isinstance(attempts, int) + or attempts < 0 + ) + ): + msg = ( + "max_retry_attempts must be a non-negative integer or " + "DistributedMapProcessorRetryConfig.UNLIMITED, " + f"got: {attempts!r}" + ) + raise ValidationError(msg) + + +@dataclass(frozen=True) +class DistributedMapProcessor: + """Processor configuration for a map run.""" + + function_name: str + response_mode: ProcessorResponseMode = ProcessorResponseMode.BATCH + batch_size: int | None = None + retry: DistributedMapProcessorRetryConfig | None = None + durable_execution_name_prefix: str | None = None + + def __post_init__(self) -> None: + _validate_function_name(self.function_name) + _validate_not_bool("batch_size", self.batch_size) + if self.batch_size is not None and self.batch_size < 1: + msg = f"batch_size must be at least 1, got: {self.batch_size}" + raise ValidationError(msg) + if self.durable_execution_name_prefix == "": + msg = "durable_execution_name_prefix must be non-empty" + raise ValidationError(msg) + + @classmethod + def report_batch_outcome( + cls, + name: str, + *, + batch_size: int | None = None, + retry: DistributedMapProcessorRetryConfig | None = None, + durable_execution_name_prefix: str | None = None, + ) -> DistributedMapProcessor: + """Processor that reports one outcome for the whole batch. Items have no outputs.""" + return cls( + function_name=name, + response_mode=ProcessorResponseMode.BATCH, + batch_size=batch_size, + retry=retry, + durable_execution_name_prefix=durable_execution_name_prefix, + ) + + @classmethod + def report_item_outcomes( + cls, + name: str, + *, + batch_size: int | None = None, + retry: DistributedMapProcessorRetryConfig | None = None, + durable_execution_name_prefix: str | None = None, + ) -> DistributedMapProcessor: + """Processor that may report a failure or an output per item. Unlisted items succeed.""" + return cls( + function_name=name, + response_mode=ProcessorResponseMode.ITEM_OUTCOMES, + batch_size=batch_size, + retry=retry, + durable_execution_name_prefix=durable_execution_name_prefix, + ) + + +def _parse_delimiter( + value: str | DistributedMapCsvDelimiter, +) -> DistributedMapCsvDelimiter: + """Normalize a delimiter passed as a string or enum member.""" + if isinstance(value, DistributedMapCsvDelimiter): + return value + try: + return DistributedMapCsvDelimiter(value) + except ValueError: + allowed = ", ".join(d.value for d in DistributedMapCsvDelimiter) + msg = f"delimiter must be one of ({allowed}), got: {value!r}" + raise ValidationError(msg) from None + + +@dataclass(frozen=True) +class S3Source: + """Resolved S3 source.""" + + source_type: DistributedMapS3SourceType + bucket: str + key: str | None = None + key_prefix: str | None = None + fmt: DistributedMapSourceFormat | None = None + delimiter: DistributedMapCsvDelimiter | None = None + headers: list[str] | None = None + expected_bucket_owner: str | None = None + + def __post_init__(self) -> None: + _validate_bucket_owner(self.expected_bucket_owner) + _validate_columns("headers", self.headers) + if self.source_type is DistributedMapS3SourceType.OBJECT: + if not self.key: + msg = "an OBJECT source requires a key" + raise ValidationError(msg) + if self.fmt is None: + msg = "an OBJECT source requires a format" + raise ValidationError(msg) + else: + if self.key_prefix is None: + msg = f"a {self.source_type.value} source requires a key prefix" + raise ValidationError(msg) + if ( + self.source_type is DistributedMapS3SourceType.LISTED_OBJECTS + and self.fmt is None + ): + msg = "a LISTED_OBJECTS source requires a format" + raise ValidationError(msg) + if ( + self.source_type is DistributedMapS3SourceType.LISTED_OBJECT_METADATA + and self.fmt is not None + ): + msg = "a LISTED_OBJECT_METADATA source reads no contents, so it takes no format" + raise ValidationError(msg) + + +@dataclass(frozen=True) +class ReaderSource: + """Resolved reader-function source.""" + + function_name: str + initial_state: Any = None + state_serdes: SerDes | None = None # None = DEFAULT_JSON_SERDES + + def __post_init__(self) -> None: + _validate_function_name(self.function_name) + + +@dataclass(frozen=True) +class DistributedMapSource: + """Source configuration for a map run.""" + + max_items: int | None = None + inline_items: list[Any] | None = None + inline_serdes: SerDes | None = None # None = DEFAULT_JSON_SERDES + s3: S3Source | None = None + reader: ReaderSource | None = None + + def __post_init__(self) -> None: + _validate_not_bool("max_items", self.max_items) + if self.max_items is not None and self.max_items < 1: + msg = f"max_items must be at least 1, got: {self.max_items}" + raise ValidationError(msg) + populated = sum( + 1 + for value in (self.inline_items, self.s3, self.reader) + if value is not None + ) + if populated != 1: + msg = "exactly one of inline_items, s3 or reader must be set" + raise ValidationError(msg) + + @classmethod + def inline( + cls, + items: Sequence[Any], + *, + serdes: SerDes | None = None, + max_items: int | None = None, + ) -> DistributedMapSource: + """An in-memory list of items embedded in the start checkpoint. + + ``serdes`` serializes each item here, before the map run exists. The + processor deserializes it later under a different context. So the serdes + must write a payload it can read back without the context it wrote + under. See ``aws_durable_execution_sdk_python.serdes``. + """ + return cls( + inline_items=list(items), + inline_serdes=serdes, + max_items=max_items, + ) + + @classmethod + def s3_json_lines( + cls, + uri: str, + *, + expected_bucket_owner: str | None = None, + max_items: int | None = None, + ) -> DistributedMapSource: + """Read a single object, treating each line as an item.""" + parsed_uri = S3Uri.parse(uri) + bucket, key = parsed_uri.bucket, parsed_uri.path + if key is None: + msg = "s3_json_lines requires an S3 object key" + raise ValidationError(msg) + return cls( + max_items=max_items, + s3=S3Source( + source_type=DistributedMapS3SourceType.OBJECT, + bucket=bucket, + key=key, + fmt=DistributedMapSourceFormat.JSON_LINES, + expected_bucket_owner=expected_bucket_owner, + ), + ) + + @classmethod + def s3_json_array( + cls, + uri: str, + *, + expected_bucket_owner: str | None = None, + max_items: int | None = None, + ) -> DistributedMapSource: + """Read a single object holding a JSON array, treating each element as an item.""" + parsed_uri = S3Uri.parse(uri) + bucket, key = parsed_uri.bucket, parsed_uri.path + if key is None: + msg = "s3_json_array requires an S3 object key" + raise ValidationError(msg) + return cls( + max_items=max_items, + s3=S3Source( + source_type=DistributedMapS3SourceType.OBJECT, + bucket=bucket, + key=key, + fmt=DistributedMapSourceFormat.JSON_ARRAY, + expected_bucket_owner=expected_bucket_owner, + ), + ) + + @classmethod + def s3_csv( + cls, + uri: str, + *, + headers: Sequence[str] | None = None, + delimiter: str | DistributedMapCsvDelimiter = DistributedMapCsvDelimiter.COMMA, + expected_bucket_owner: str | None = None, + max_items: int | None = None, + ) -> DistributedMapSource: + """Read a single object, treating each record as an item.""" + parsed_uri = S3Uri.parse(uri) + bucket, key = parsed_uri.bucket, parsed_uri.path + if key is None: + msg = "s3_csv requires an S3 object key" + raise ValidationError(msg) + return cls( + max_items=max_items, + s3=S3Source( + source_type=DistributedMapS3SourceType.OBJECT, + bucket=bucket, + key=key, + fmt=DistributedMapSourceFormat.CSV, + delimiter=_parse_delimiter(delimiter), + headers=list(headers) if headers is not None else None, + expected_bucket_owner=expected_bucket_owner, + ), + ) + + @classmethod + def s3_objects( + cls, + prefix_uri: str, + *, + expected_bucket_owner: str | None = None, + max_items: int | None = None, + ) -> DistributedMapSource: + """Read each object under a prefix as one item, without reading its contents.""" + parsed_uri = S3Uri.parse(prefix_uri) + bucket, prefix = parsed_uri.bucket, parsed_uri.path + return cls( + max_items=max_items, + s3=S3Source( + source_type=DistributedMapS3SourceType.LISTED_OBJECT_METADATA, + bucket=bucket, + key_prefix=prefix or "", + expected_bucket_owner=expected_bucket_owner, + ), + ) + + @classmethod + def s3_flattened_json_lines( + cls, + prefix_uri: str, + *, + expected_bucket_owner: str | None = None, + max_items: int | None = None, + ) -> DistributedMapSource: + """Read every object under a prefix, treating each line as an item.""" + parsed_uri = S3Uri.parse(prefix_uri) + bucket, prefix = parsed_uri.bucket, parsed_uri.path + return cls( + max_items=max_items, + s3=S3Source( + source_type=DistributedMapS3SourceType.LISTED_OBJECTS, + bucket=bucket, + key_prefix=prefix or "", + fmt=DistributedMapSourceFormat.JSON_LINES, + expected_bucket_owner=expected_bucket_owner, + ), + ) + + @classmethod + def s3_flattened_json_array( + cls, + prefix_uri: str, + *, + expected_bucket_owner: str | None = None, + max_items: int | None = None, + ) -> DistributedMapSource: + """Read every object under a prefix, treating each array element as an item.""" + parsed_uri = S3Uri.parse(prefix_uri) + bucket, prefix = parsed_uri.bucket, parsed_uri.path + return cls( + max_items=max_items, + s3=S3Source( + source_type=DistributedMapS3SourceType.LISTED_OBJECTS, + bucket=bucket, + key_prefix=prefix or "", + fmt=DistributedMapSourceFormat.JSON_ARRAY, + expected_bucket_owner=expected_bucket_owner, + ), + ) + + @classmethod + def s3_flattened_csv( + cls, + prefix_uri: str, + *, + headers: Sequence[str] | None = None, + delimiter: str | DistributedMapCsvDelimiter = DistributedMapCsvDelimiter.COMMA, + expected_bucket_owner: str | None = None, + max_items: int | None = None, + ) -> DistributedMapSource: + """Read every object under a prefix, treating each record as an item.""" + parsed_uri = S3Uri.parse(prefix_uri) + bucket, prefix = parsed_uri.bucket, parsed_uri.path + return cls( + max_items=max_items, + s3=S3Source( + source_type=DistributedMapS3SourceType.LISTED_OBJECTS, + bucket=bucket, + key_prefix=prefix or "", + fmt=DistributedMapSourceFormat.CSV, + delimiter=_parse_delimiter(delimiter), + headers=list(headers) if headers is not None else None, + expected_bucket_owner=expected_bucket_owner, + ), + ) + + @classmethod + def reader_function( + cls, + name: str, + *, + initial_state: Any = None, + state_serdes: SerDes | None = None, + max_items: int | None = None, + ) -> DistributedMapSource: + """Page items from a customer-supplied reader Lambda function.""" + return cls( + max_items=max_items, + reader=ReaderSource( + function_name=name, + initial_state=initial_state, + state_serdes=state_serdes, + ), + ) + + +@dataclass(frozen=True) +class SuccessDestination: + """S3 destination for succeeded items.""" + + bucket: str + prefix: str + include_input: bool = False + include_output: bool = True + expected_bucket_owner: str | None = None + + def __post_init__(self) -> None: + _validate_bucket_owner(self.expected_bucket_owner) + if not (self.include_input or self.include_output): + msg = "success destination must include input or output" + raise ValidationError(msg) + + +@dataclass(frozen=True) +class FailureDestination: + """S3 destination for permanently-failed items.""" + + bucket: str + prefix: str + include_input: bool = True + include_error: bool = True + expected_bucket_owner: str | None = None + + def __post_init__(self) -> None: + _validate_bucket_owner(self.expected_bucket_owner) + if not (self.include_input or self.include_error): + msg = "failure destination must include input or error" + raise ValidationError(msg) + + +class DistributedMapDestination: + """Factories for the destinations a map run writes item records to.""" + + @staticmethod + def s3_successes( + prefix_uri: str, + *, + include_input: bool = False, + include_output: bool = True, + expected_bucket_owner: str | None = None, + ) -> SuccessDestination: + """Route succeeded item records to an S3 prefix.""" + parsed_uri = S3Uri.parse(prefix_uri) + return SuccessDestination( + bucket=parsed_uri.bucket, + prefix=parsed_uri.path or "", + include_input=include_input, + include_output=include_output, + expected_bucket_owner=expected_bucket_owner, + ) + + @staticmethod + def s3_failures( + prefix_uri: str, + *, + include_input: bool = True, + include_error: bool = True, + expected_bucket_owner: str | None = None, + ) -> FailureDestination: + """Route permanently-failed item records to an S3 prefix.""" + parsed_uri = S3Uri.parse(prefix_uri) + return FailureDestination( + bucket=parsed_uri.bucket, + prefix=parsed_uri.path or "", + include_input=include_input, + include_error=include_error, + expected_bucket_owner=expected_bucket_owner, + ) + + +@dataclass(frozen=True) +class DistributedMapDestinationConfig: + """Destination routing for map run results.""" + + on_success: SuccessDestination | None = None + on_failure: FailureDestination | None = None + + +@dataclass(frozen=True) +class DistributedMapConfig: + """Configuration for map run operations.""" + + destination: DistributedMapDestinationConfig | None = None + # None tolerates no item failure, so the first permanent item failure fails + # the run. Use DistributedMapCompletionConfig.failure_percentage(100) to + # tolerate every failure. + completion_config: DistributedMapCompletionConfig | None = None + timeout: Duration | None = None + + def __post_init__(self) -> None: + if self.timeout is not None and self.timeout.to_seconds() <= 0: + msg = f"timeout must be positive, got: {self.timeout.to_seconds()}s" + raise ValidationError(msg) + + +@dataclass(frozen=True) +class DistributedMapResultConfig(DistributedMapConfig, Generic[ItemOutput]): + """Configuration that collects per-item results inline. + + Passing this instead of ``DistributedMapConfig`` makes ``ctx.distributed_map`` + return a ``DistributedMapResult``, which carries the per-item outcomes. + """ + + result_serdes: SerDes[ItemOutput] | None = None # None = DEFAULT_JSON_SERDES + + +# endregion map run configuration + + @dataclass(frozen=True) class ChildConfig(Generic[T]): """Configuration options for child context operations. diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/context.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/context.py index e1957932e..c3dd44126 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/context.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/context.py @@ -1,6 +1,7 @@ from __future__ import annotations import logging +from collections.abc import Sequence from contextlib import contextmanager from dataclasses import dataclass from threading import Lock @@ -12,6 +13,7 @@ NoReturn, ParamSpec, TypeVar, + overload, ) from aws_durable_execution_sdk_python.config import ( @@ -20,6 +22,11 @@ Duration, InvokeConfig, MapConfig, + DistributedMapConfig, + DistributedMapProcessor, + DistributedMapResultConfig, + DistributedMapSource, + ItemOutput, ParallelBranch, ParallelConfig, StepConfig, @@ -28,6 +35,10 @@ from aws_durable_execution_sdk_python.concurrency.models import ( envelope_summary_generator, ) +from aws_durable_execution_sdk_python.dmap.models import ( + DistributedMapResult, + DistributedMapSummary, +) from aws_durable_execution_sdk_python.exceptions import ( CallbackError, CallbackExternalError, @@ -57,6 +68,9 @@ ) from aws_durable_execution_sdk_python.operation.invoke import InvokeOperationExecutor from aws_durable_execution_sdk_python.operation.map import map_handler +from aws_durable_execution_sdk_python.operation.dmap import ( + DistributedMapOperationExecutor, +) from aws_durable_execution_sdk_python.operation.parallel import parallel_handler from aws_durable_execution_sdk_python.operation.step import StepOperationExecutor from aws_durable_execution_sdk_python.operation.wait import WaitOperationExecutor @@ -86,7 +100,7 @@ if TYPE_CHECKING: - from collections.abc import Callable, Iterator, Sequence + from collections.abc import Callable, Iterator from aws_durable_execution_sdk_python.concurrency.models import BatchResult from aws_durable_execution_sdk_python.lambda_service import ErrorObject @@ -714,6 +728,78 @@ def invoke( ) return executor.process() + @overload + def distributed_map( + self, + source: DistributedMapSource | Sequence[Any], + processor: DistributedMapProcessor, + max_concurrency: int, + name: str | None = None, + *, + config: DistributedMapResultConfig[ItemOutput], + ) -> DistributedMapResult[ItemOutput]: ... + + @overload + def distributed_map( + self, + source: DistributedMapSource | Sequence[Any], + processor: DistributedMapProcessor, + max_concurrency: int, + name: str | None = None, + *, + config: DistributedMapConfig | None = None, + ) -> DistributedMapSummary: ... + + def distributed_map( + self, + source: DistributedMapSource | Sequence[Any], + processor: DistributedMapProcessor, + max_concurrency: int, + name: str | None = None, + *, + config: DistributedMapConfig | None = None, + ) -> DistributedMapSummary: + """Start a distributed map run and resolve with its summary. + + Args: + source: The items to process (a typed source or a sequence shorthand, + where a str is a sequence of characters) + processor: The processor configuration built via a DistributedMapProcessor factory + max_concurrency: Maximum concurrent processor invocations. Required, + with no service default. + name: Optional name for the operation + config: Optional run-level configuration + + Returns: + The map run's summary, or a DistributedMapResult when a + DistributedMapResultConfig is passed + """ + if not isinstance(source, (DistributedMapSource, Sequence)): + msg = "source must be a DistributedMapSource or a sequence of items" + raise ValidationError(msg) + if isinstance(max_concurrency, bool): + msg = f"max_concurrency must be a number, not a bool, got: {max_concurrency!r}" + raise ValidationError(msg) + if max_concurrency < 1: + msg = f"max_concurrency must be greater than zero, got: {max_concurrency}" + raise ValidationError(msg) + if config is None: + config = DistributedMapConfig() + with self._operation_replay_aware( + OperationSubType.DISTRIBUTED_MAP.value, + name, + operation_type=OperationType.DISTRIBUTED_MAP, + ) as operation_identifier: + executor: DistributedMapOperationExecutor = DistributedMapOperationExecutor( + source=source, + processor=processor, + max_concurrency=max_concurrency, + state=self.state, + operation_identifier=operation_identifier, + config=config, + ) + return executor.process() + def map( self, inputs: Sequence[U], diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/dmap/__init__.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/dmap/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/dmap/helpers.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/dmap/helpers.py new file mode 100644 index 000000000..f8460487b --- /dev/null +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/dmap/helpers.py @@ -0,0 +1,727 @@ +"""Authoring helpers for distributed map processor and reader Lambda functions. + +Helpers that own the request/response format. The customer calls one inside +their own Lambda handler to process items/batches or read pages. Exported from +the package root. + +These helpers deserialize values under a different context than the one they +were serialized with, so the serdes must satisfy the context requirement +documented in ``aws_durable_execution_sdk_python.serdes``. +""" + +from __future__ import annotations + +import logging +from collections.abc import MutableMapping +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Callable, overload + +from aws_durable_execution_sdk_python.config import ( + BatchItemStatus, + CompletionConfig, + MapConfig, + NestingType, +) +from aws_durable_execution_sdk_python.dmap.models import DistributedMapRunArn +from aws_durable_execution_sdk_python.exceptions import ValidationError +from aws_durable_execution_sdk_python.lambda_service import ErrorObject +from aws_durable_execution_sdk_python.logger import Logger +from aws_durable_execution_sdk_python.serdes import ( + DEFAULT_JSON_SERDES, + SerDes, + SerDesContext, +) +from aws_durable_execution_sdk_python.types import ( + DistributedMapBatchContext, + DistributedMapItemContext, + DistributedMapReaderContext, +) + + +if TYPE_CHECKING: + from aws_durable_execution_sdk_python.types import LoggerInterface + + +_LOGGER = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class ReaderPage: + """A page returned by a reader function: its items and the next state.""" + + items: list[Any] = field(default_factory=list) + next_state: Any | None = None + + +@dataclass(frozen=True) +class DistributedMapProcessorRecord: + """One item in a processor event's batch. + + ``item_id`` is the service-assigned id of the item. ``body`` is the item's + serialized body. + """ + + item_id: str + body: Any = None + + @classmethod + def from_dict(cls, data: MutableMapping[str, Any]) -> DistributedMapProcessorRecord: + item_id = data.get("itemId") + # The helpers copy this id onto every outcome they report, so the + # service matches each outcome back to its item by it. An empty id + # would report the outcome against no item at all. + if not isinstance(item_id, str) or not item_id: + msg = ( + "expected each distributed map processor record to have a " + "string 'itemId'" + ) + raise ValidationError(msg) + return cls(item_id=item_id, body=data.get("body")) + + +def _run_arn_from(data: MutableMapping[str, Any]) -> DistributedMapRunArn: + """Parse and validate the envelope's 'distributedMapRunArn'.""" + arn = data.get("distributedMapRunArn") + run_arn = DistributedMapRunArn.from_arn(arn) if isinstance(arn, str) else None + if run_arn is None: + msg = "expected a distributed map envelope with a valid 'distributedMapRunArn'" + raise ValidationError(msg) + return run_arn + + +@dataclass(frozen=True) +class DistributedMapProcessorEvent: + """The event the service sends to a processor Lambda. + + ``distributed_map_run_arn`` is the ARN of the distributed map run. + ``records`` is the batch of items to process. + """ + + distributed_map_run_arn: DistributedMapRunArn + records: list[DistributedMapProcessorRecord] = field(default_factory=list) + + @classmethod + def from_dict(cls, data: MutableMapping[str, Any]) -> DistributedMapProcessorEvent: + records = data.get("records") + if not isinstance(records, list): + msg = "expected a distributed map processor envelope with a 'records' list" + raise ValidationError(msg) + return cls( + distributed_map_run_arn=_run_arn_from(data), + records=[DistributedMapProcessorRecord.from_dict(r) for r in records], + ) + + +@dataclass(frozen=True) +class ItemResult: + """One item's output, reported by an item_outcomes processor.""" + + item_identifier: str + output: str | None = None + + def to_dict(self) -> MutableMapping[str, Any]: + result: MutableMapping[str, Any] = {"itemIdentifier": self.item_identifier} + if self.output is not None: + result["output"] = self.output + return result + + +@dataclass(frozen=True) +class ItemFailure: + """One item's failure, reported by an item_outcomes processor.""" + + item_identifier: str + error: ErrorObject | None = None + + @classmethod + def from_exception(cls, item_identifier: str, exc: Exception) -> ItemFailure: + return cls( + item_identifier=item_identifier, error=ErrorObject.from_exception(exc) + ) + + @classmethod + def from_dict(cls, data: MutableMapping[str, Any]) -> ItemFailure: + error = data.get("error") + return cls( + item_identifier=data.get("itemIdentifier", ""), + error=ErrorObject( + message=error.get("errorMessage"), + type=error.get("errorType"), + data=error.get("errorData"), + stack_trace=error.get("stackTrace"), + ) + if error + else None, + ) + + def to_dict(self) -> MutableMapping[str, Any]: + result: MutableMapping[str, Any] = {"itemIdentifier": self.item_identifier} + error = _error_fields(self.error) + if error: + result["error"] = error + return result + + +@dataclass(frozen=True) +class ItemHandlerResponse: + """What an item handler returns: a failure or a result for each item.""" + + failures: list[ItemFailure] = field(default_factory=list) + results: list[ItemResult] = field(default_factory=list) + + def to_dict(self) -> MutableMapping[str, Any]: + return { + "batchItemFailures": [f.to_dict() for f in self.failures], + "batchItemResults": [r.to_dict() for r in self.results], + } + + +@dataclass(frozen=True) +class DistributedMapReaderEvent: + """The event the service sends to a reader Lambda. + + ``distributed_map_run_arn`` is the ARN of the distributed map run. + ``state`` is the serialized state, absent on the first call and the previous + call's next state afterwards. ``max_items_per_page`` is the maximum number + of items the page may contain. + """ + + distributed_map_run_arn: DistributedMapRunArn + max_items_per_page: int + state: str | None = None + + @classmethod + def from_dict(cls, data: MutableMapping[str, Any]) -> DistributedMapReaderEvent: + max_items_per_page = data.get("maxItemsPerPage") + if not isinstance(max_items_per_page, int): + msg = ( + "expected a distributed map reader envelope with an integer " + "'maxItemsPerPage'" + ) + raise ValidationError(msg) + return cls( + distributed_map_run_arn=_run_arn_from(data), + max_items_per_page=max_items_per_page, + state=data.get("state"), + ) + + +@dataclass(frozen=True) +class ReaderResponse: + """What a reader function returns. A None ``next_state`` exhausts the source.""" + + items: list[str] = field(default_factory=list) + next_state: str | None = None + + def to_dict(self) -> MutableMapping[str, Any]: + result: MutableMapping[str, Any] = {"items": self.items} + if self.next_state is not None: + result["nextState"] = self.next_state + return result + + +def _to_item(serdes: SerDes[Any], body: str, ctx: SerDesContext) -> Any: + """Recover a typed item from a record body.""" + return serdes.deserialize(body, ctx) + + +def _to_output(serdes: SerDes[Any], value: Any, ctx: SerDesContext) -> str | None: + """Serialize an item's output, or None when the handler returned nothing.""" + if value is None: + return None + return serdes.serialize(value, ctx) + + +def _validate_concurrency(concurrency: int) -> None: + if concurrency < 1: + msg = f"concurrency must be at least 1, got: {concurrency}" + raise ValidationError(msg) + + +def _stamped_logger(base: LoggerInterface, **extra: str) -> Logger: + """A logger that adds the map run's identifiers to every line it writes. + + The customer function gets these for free, so it never has to carry the run + ARN or item id into its own log calls. A durable helper passes its branch + logger as the base, so that logger's own fields and replay de-duplication + are kept; a non-durable helper has no owning context and passes this module's + logger, which always logs. + """ + return Logger(logger=base, default_extra=extra) + + +def _item_context( + run_arn: DistributedMapRunArn, + item_id: str, + base: LoggerInterface | None = None, +) -> DistributedMapItemContext: + """Build the context for one item of a processor batch.""" + run = run_arn.to_arn() + return DistributedMapItemContext( + logger=_stamped_logger( + base if base is not None else _LOGGER, + distributedMapRunArn=run, + itemId=item_id, + ), + distributed_map_run_arn=run, + item_id=item_id, + ) + + +def _batch_context( + run_arn: DistributedMapRunArn, + item_ids: tuple[str, ...], + base: LoggerInterface | None = None, +) -> DistributedMapBatchContext: + """Build the context for a whole processor batch. + + The ids are index-aligned with the items the function receives. + """ + run = run_arn.to_arn() + return DistributedMapBatchContext( + logger=_stamped_logger( + base if base is not None else _LOGGER, distributedMapRunArn=run + ), + distributed_map_run_arn=run, + item_ids=item_ids, + ) + + +def _error_fields(error: ErrorObject | None) -> MutableMapping[str, Any]: + """An error's camelCase wire fields, used in the response and in the log line. + + The processor response envelope is camelCase, so ErrorObject.to_dict cannot + be reused. Every member is optional, so an absent member is omitted. All + four are written because the model accepts them, but the service keeps only + the type and the message for the parent. + """ + if error is None: + return {} + fields: MutableMapping[str, Any] = {} + if error.type is not None: + fields["errorType"] = error.type + if error.message is not None: + fields["errorMessage"] = error.message + if error.data is not None: + fields["errorData"] = error.data + if error.stack_trace is not None: + fields["stackTrace"] = error.stack_trace + return fields + + +def _reader_context(run_arn: DistributedMapRunArn) -> DistributedMapReaderContext: + """Build the context for one reader page.""" + run = run_arn.to_arn() + return DistributedMapReaderContext( + logger=_stamped_logger(_LOGGER, distributedMapRunArn=run), + distributed_map_run_arn=run, + ) + + +def _process_items_non_durable( + event: MutableMapping[str, Any], + func: Callable[[Any, DistributedMapItemContext], Any], + item_serdes: SerDes[Any] | None, + result_serdes: SerDes[Any] | None, + concurrency: int, +) -> dict[str, Any]: + _validate_concurrency(concurrency) + serdes = item_serdes or DEFAULT_JSON_SERDES + out_serdes = result_serdes or DEFAULT_JSON_SERDES + processor_event = DistributedMapProcessorEvent.from_dict(event) + run_arn = processor_event.distributed_map_run_arn + records = processor_event.records + + def run(record: DistributedMapProcessorRecord) -> str | None: + item = _to_item( + serdes, record.body, run_arn.serdes_context("body", record.item_id) + ) + # Serializing here, not after the loop, keeps a serialization + # failure on the one item whose output could not be serialized. + return _to_output( + out_serdes, + func(item, _item_context(run_arn, record.item_id)), + run_arn.serdes_context("output", record.item_id), + ) + + outputs: list[str | None] = [None] * len(records) + errors: list[Exception | None] = [None] * len(records) + with ThreadPoolExecutor(max_workers=concurrency) as pool: + futures = {pool.submit(run, r): i for i, r in enumerate(records)} + for future, i in futures.items(): + try: + outputs[i] = future.result() + except Exception as exc: # noqa: BLE001 + errors[i] = exc + + results: list[ItemResult] = [] + failures: list[ItemFailure] = [] + for i, record in enumerate(records): + err = errors[i] + if err is not None: + failure = ItemFailure.from_exception(record.item_id, err) + _item_context(run_arn, record.item_id).logger.error( + "distributed map item failed", extra=_error_fields(failure.error) + ) + failures.append(failure) + else: + results.append( + ItemResult(item_identifier=record.item_id, output=outputs[i]) + ) + + response = ItemHandlerResponse(failures=failures, results=results) + return dict(response.to_dict()) + + +def _process_items_durable( + context: Any, + event: MutableMapping[str, Any], + func: Callable[[Any, Any, DistributedMapItemContext], Any], + item_serdes: SerDes[Any] | None, + result_serdes: SerDes[Any] | None, + concurrency: int, + nesting_type: NestingType, +) -> dict[str, Any]: + _validate_concurrency(concurrency) + serdes = item_serdes or DEFAULT_JSON_SERDES + out_serdes = result_serdes or DEFAULT_JSON_SERDES + processor_event = DistributedMapProcessorEvent.from_dict(event) + run_arn = processor_event.distributed_map_run_arn + records = processor_event.records + + def per_item(inner_ctx: Any, body: Any, index: int, _inputs: Any) -> str | None: + item_id = records[index].item_id + item = _to_item(serdes, body, run_arn.serdes_context("body", item_id)) + # Serializing here, not after the batch, keeps a serialization + # failure on the one item whose output could not be serialized. + return _to_output( + out_serdes, + func( + inner_ctx, + item, + _item_context(run_arn, item_id, inner_ctx.logger), + ), + run_arn.serdes_context("output", item_id), + ) + + batch = context.map( + [record.body for record in records], + per_item, + config=MapConfig( + max_concurrency=concurrency, + nesting_type=nesting_type, + completion_config=CompletionConfig.all_completed(), + ), + ) + + results: list[ItemResult] = [] + failures: list[ItemFailure] = [] + for bi in batch.all: + item_id = records[bi.index].item_id + if bi.status is BatchItemStatus.SUCCEEDED: + results.append(ItemResult(item_identifier=item_id, output=bi.result)) + else: + _item_context(run_arn, item_id, context.logger).logger.error( + "distributed map item failed", extra=_error_fields(bi.error) + ) + failures.append(ItemFailure(item_identifier=item_id, error=bi.error)) + + response = ItemHandlerResponse(failures=failures, results=results) + return dict(response.to_dict()) + + +_ITEM_OPTIONS = ("item_serdes", "result_serdes", "concurrency") + + +def _reject_unknown_options(kwargs: dict[str, Any], accepted: tuple[str, ...]) -> None: + for name in kwargs: + if name not in accepted: + msg = ( + f"process_distributed_map_items got an unexpected keyword " + f"argument '{name}' for this form, accepted: {', '.join(accepted)}" + ) + raise ValidationError(msg) + + +@overload +def process_distributed_map_items( + event: MutableMapping[str, Any], + func: Callable[[Any, DistributedMapItemContext], Any], + /, + *, + item_serdes: SerDes[Any] | None = None, + result_serdes: SerDes[Any] | None = None, + concurrency: int = 1, +) -> dict[str, Any]: + """Process the items of a distributed map batch in a non-durable processor. + + Call this inside the handler of a non-durable processor Lambda. Pass that + Lambda's name to ``DistributedMapProcessor.report_item_outcomes`` in the + parent's ``ctx.distributed_map`` call. + + The handler must return the result of this function. The service reads each + item's outcome from the handler's return value. A handler that returns + nothing makes the service mark every item succeeded, including the items + whose ``func`` raised. + + For each failed item, this function logs one error line through the item's + logger. + + ``func`` receives ``(item, DistributedMapItemContext)`` and returns the + item's output or raises. The context names the run and the item. An item + whose ``func`` returns ``None`` succeeds with no output. Items in a batch + are processed one at a time. Raise ``concurrency`` to run that many items + at once, which requires ``func``, ``item_serdes`` and ``result_serdes`` to + be safe to call from several threads. + + Args: + event: The event the Lambda was invoked with. + func: Called once per item. + item_serdes: Deserializes each item. Defaults to JSON. + result_serdes: Serializes each item's output. Defaults to JSON. + concurrency: Maximum number of items to process concurrently. + + Example: + def handler(event, context): + return process_distributed_map_items( + event, lambda item, item_ctx: item["id"], concurrency=5 + ) + """ + + +@overload +def process_distributed_map_items( + context: Any, + event: MutableMapping[str, Any], + func: Callable[[Any, Any, DistributedMapItemContext], Any], + /, + *, + item_serdes: SerDes[Any] | None = None, + result_serdes: SerDes[Any] | None = None, + concurrency: int = 1, + nesting_type: NestingType = NestingType.FLAT, +) -> dict[str, Any]: + """Process the items of a distributed map batch in a durable processor. + + Call this inside the ``@durable_execution`` handler of a durable processor + Lambda, passing the handler's ``DurableContext`` first. Pass that Lambda's + name to ``DistributedMapProcessor.report_item_outcomes`` in the parent's + ``ctx.distributed_map`` call. + + The handler must return the result of this function. The service reads each + item's outcome from the handler's return value. A handler that returns + nothing makes the service mark every item succeeded, including the items + whose ``func`` raised. + + For each failed item, this function logs one error line through the item's + logger. + + ``func`` receives ``(durable_context, item, DistributedMapItemContext)`` and + returns the item's output or raises. Each item runs through ``context.map``, + so ``durable_context`` is the item's own context. An item whose ``func`` + returns ``None`` succeeds with no output. Items in a batch are processed + one at a time. Raise ``concurrency`` to run that many items at once. + + Args: + context: The handler's ``DurableContext``. + event: The event the Lambda was invoked with. + func: Called once per item. + item_serdes: Deserializes each item. Defaults to JSON. + result_serdes: Serializes each item's output. Defaults to JSON. + concurrency: Maximum number of items to process concurrently. + nesting_type: How child operations should inherit context from their + parent. + - NESTED: Each item runs in its own isolated context + - FLAT: All items share the same parent context (default) + + Example: + @durable_execution + def handler(event, context): + return process_distributed_map_items( + context, + event, + lambda ctx, item, item_ctx: ctx.step( + lambda _: item["id"], name="read-id" + ), + nesting_type=NestingType.NESTED, + ) + """ + + +def process_distributed_map_items(*args: Any, **kwargs: Any) -> dict[str, Any]: + # The two forms are told apart by how many positional arguments the call has. + if len(args) == 2: + _reject_unknown_options(kwargs, _ITEM_OPTIONS) + return _process_items_non_durable( + args[0], + args[1], + kwargs.get("item_serdes"), + kwargs.get("result_serdes"), + kwargs.get("concurrency", 1), + ) + if len(args) == 3: + _reject_unknown_options(kwargs, (*_ITEM_OPTIONS, "nesting_type")) + return _process_items_durable( + args[0], + args[1], + args[2], + kwargs.get("item_serdes"), + kwargs.get("result_serdes"), + kwargs.get("concurrency", 1), + kwargs.get("nesting_type", NestingType.FLAT), + ) + msg = ( + "process_distributed_map_items expects (event, func) for a " + "non-durable processor or (context, event, func) for a durable " + f"processor, got {len(args)} positional arguments" + ) + raise ValidationError(msg) + + +def process_distributed_map_batch( + event: MutableMapping[str, Any], + func: Callable[[list[Any], DistributedMapBatchContext], None], + *, + item_serdes: SerDes[Any] | None = None, +) -> None: + """Process a whole distributed map batch with one call to ``func``. + + Call this inside the handler of a batch processor Lambda, durable or + non-durable. Pass that Lambda's name to + ``DistributedMapProcessor.report_batch_outcome`` in the parent's + ``ctx.distributed_map`` call. + + The service reads the batch outcome from the handler's return value and from + any error the handler raises, so the handler must return the result of this + function. The result is ``None``. + + ``func`` receives ``(items, DistributedMapBatchContext)``, where the + context's ``item_ids`` are index-aligned with the items. Returning succeeds + every item. Raising fails every item. This function does not pass a durable + context to ``func``. In a durable handler, use the handler's own + ``DurableContext`` inside ``func``. + + In Python, an exception raised by ``func`` propagates out of this function + and fails the invocation, whether or not the handler returns the result. + + A batch processor reports no per-item outcome, so it records no output. Use + ``process_distributed_map_items`` to report an output per item. + + Args: + event: The event the Lambda was invoked with. + func: Called once with every item of the batch. + item_serdes: Deserializes each item. Defaults to JSON. + + Example: + def handler(event, context): + return process_distributed_map_batch( + event, lambda items, batch_ctx: save_all(items) + ) + """ + serdes = item_serdes or DEFAULT_JSON_SERDES + processor_event = DistributedMapProcessorEvent.from_dict(event) + run_arn = processor_event.distributed_map_run_arn + func( + [ + _to_item( + serdes, record.body, run_arn.serdes_context("body", record.item_id) + ) + for record in processor_event.records + ], + _batch_context( + run_arn, + tuple(record.item_id for record in processor_event.records), + ), + ) + + +def read_distributed_map_page( + event: MutableMapping[str, Any], + func: Callable[[Any, int, DistributedMapReaderContext], ReaderPage], + *, + item_serdes: SerDes[Any] | None = None, + state_serdes: SerDes[Any] | None = None, +) -> dict[str, Any]: + """Read one page of a distributed map source and return it in service format. + + Call this inside the handler of a reader Lambda. Pass that Lambda's name to + ``DistributedMapSource.reader_function`` in the parent's ``ctx.distributed_map`` call. + + The handler must return the result of this function. The service reads the + page from the handler's return value. + + ``func`` receives ``(state, max_items_per_page, DistributedMapReaderContext)`` + and returns a ``ReaderPage``. A ``next_state`` of ``None`` signals the source + is exhausted. + + ``item_serdes`` serializes each item of the page. It must be the same serdes + the processor is configured with, because the processor deserializes every + item body with its own ``item_serdes``. Neither it nor ``state_serdes`` may + depend on getting back the context it wrote under. + + Args: + event: The event the Lambda was invoked with. + func: Called once per page. + item_serdes: Serializes each item of the page. Defaults to JSON. + state_serdes: Serializes and deserializes the paging state. Defaults to + JSON. + + Example: + def handler(event, context): + return read_distributed_map_page( + event, + lambda state, max_items, reader_ctx: ReaderPage( + items=fetch(state, max_items), next_state=None + ), + ) + """ + item_sd = item_serdes or DEFAULT_JSON_SERDES + state_sd = state_serdes or DEFAULT_JSON_SERDES + reader_event = DistributedMapReaderEvent.from_dict(event) + run_arn = reader_event.distributed_map_run_arn + state = ( + state_sd.deserialize( + reader_event.state, + run_arn.serdes_context("state", reader_event.state), + ) + if reader_event.state is not None + else None + ) + + page = func(state, reader_event.max_items_per_page, _reader_context(run_arn)) + if len(page.items) > reader_event.max_items_per_page: + msg = ( + f"reader returned {len(page.items)} items, exceeding " + f"maxItemsPerPage {reader_event.max_items_per_page}" + ) + raise ValidationError(msg) + + items = [ + item_sd.serialize( + item, run_arn.serdes_context("item", reader_event.state, index) + ) + for index, item in enumerate(page.items) + ] + + next_state: str | None = None + if page.next_state is not None: + next_state = state_sd.serialize( + page.next_state, + run_arn.serdes_context("next-state", reader_event.state), + ) + # next_state becomes the next call's input state, so returning the + # input state repeats the same position instead of advancing. The + # service rejects this as a source failure, empty page included. + # This check and the service compare the serialized strings. A + # serdes that returns a pointer, such as FileSystemSerDes, writes + # each state under its own key. So a repeated state gets a new + # pointer, and neither this check nor the service detects it. + if next_state == reader_event.state: + msg = ( + "reader next_state must differ from the state it was called " + "with, or the next page repeats the same position" + ) + raise ValidationError(msg) + + return dict(ReaderResponse(items=items, next_state=next_state).to_dict()) diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/dmap/models.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/dmap/models.py new file mode 100644 index 000000000..bc0031924 --- /dev/null +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/dmap/models.py @@ -0,0 +1,327 @@ +"""Result models returned by ``ctx.distributed_map``.""" + +from __future__ import annotations + +import hashlib +import json +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Generic, Self, TypedDict + +from aws_durable_execution_sdk_python.exceptions import ( + DistributedMapError, + ExecutionError, + ValidationError, +) +from aws_durable_execution_sdk_python.config import ( + DistributedMapItemStatus, + DistributedMapStatus, + ItemOutput, +) +from aws_durable_execution_sdk_python.lambda_service import ErrorObject, OperationStatus +from aws_durable_execution_sdk_python.serdes import SerDesContext +from aws_durable_execution_sdk_python.types import DurableExecutionArn + +if TYPE_CHECKING: + from aws_durable_execution_sdk_python.lambda_service import Operation + +_STATUS_FOR_OPERATION_STATUS = { + OperationStatus.SUCCEEDED: DistributedMapStatus.SUCCEEDED, + OperationStatus.FAILED: DistributedMapStatus.FAILED, + OperationStatus.STOPPED: DistributedMapStatus.STOPPED, + OperationStatus.TIMED_OUT: DistributedMapStatus.TIMED_OUT, +} + + +def _to_distributed_map_status(operation: Operation | None) -> DistributedMapStatus: + """Derive the map run status from the operation's terminal status.""" + op_status = operation.status if operation else None + resolved = ( + _STATUS_FOR_OPERATION_STATUS.get(op_status) if op_status is not None else None + ) + if resolved is None: + msg = ( + "Cannot derive distributed map status from operation status " + f"{op_status.value if op_status else 'UNKNOWN'}" + ) + raise ExecutionError(msg) + return resolved + + +class _SummaryFields(TypedDict): + """The summary fields both factories pass to the constructor.""" + + status: DistributedMapStatus + success_count: int + failure_count: int + read_count: int + distributed_map_run_arn: str | None + source_exhausted: bool | None + error: ErrorObject | None + total_count: int | None + + +def _require_count(value: int | None, field_name: str) -> int: + """Return a count the service must send at terminal, or raise when absent.""" + if value is None: + msg = f"missing distributed map {field_name} from backend" + raise ExecutionError(msg) + return value + + +def _summary_fields(operation: Operation | None) -> _SummaryFields: + """Read the summary fields a terminal operation must carry.""" + details = operation.distributed_map_details if operation else None + if details is None: + # The raw operation status, not _to_distributed_map_status, which raises + # on a non-terminal status and would replace this error with its own. + op_status = ( + operation.status.value if operation and operation.status else "UNKNOWN" + ) + msg = ( + f"DISTRIBUTED_MAP operation ended {op_status} but carried no " + f"DistributedMapDetails" + ) + raise ExecutionError(msg) + status = _to_distributed_map_status(operation) + # SourceExhausted is required at terminal once a run exists, and is absent + # only when the operation failed before one was created. + if details.distributed_map_run_arn is not None and details.source_exhausted is None: + msg = ( + f"DISTRIBUTED_MAP operation ended {status.value} but carried no " + f"SourceExhausted" + ) + raise ExecutionError(msg) + # These three counts are required at every terminal state. An absent one + # must not read as zero, since an absent FailureCount would then report a + # run with failed items as a run with none. + success_count = _require_count(details.success_count, "SuccessCount") + failure_count = _require_count(details.failure_count, "FailureCount") + read_count = _require_count(details.read_count, "ReadCount") + # TotalCount is required only once the run succeeded, because a run that + # failed, timed out or was stopped may never have counted its source. + if status is DistributedMapStatus.SUCCEEDED and details.total_count is None: + msg = "missing distributed map TotalCount from backend" + raise ExecutionError(msg) + return { + "status": status, + "success_count": success_count, + "failure_count": failure_count, + "read_count": read_count, + "distributed_map_run_arn": details.distributed_map_run_arn, + "source_exhausted": details.source_exhausted, + "error": details.error, + "total_count": details.total_count, + } + + +_RUN_ARN_SEPARATOR = "/distributed-map-run/" + + +@dataclass(frozen=True) +class DistributedMapRunArn: + """Parsed components of a distributed map run ARN. + + Attributes: + durable_execution_arn: The parent durable execution's ARN. + run_id: The map run id, unique per account. + """ + + durable_execution_arn: str + run_id: str + + @classmethod + def from_arn(cls, arn: str) -> DistributedMapRunArn | None: + """Parse a map run ARN, returning ``None`` when it does not match the format.""" + # A run id contains no "/", so the separator is always its last + # occurrence. The parent's execution name or invocation id can itself be + # "distributed-map-run", which partition would split on instead. + parent, _, run_id = arn.rpartition(_RUN_ARN_SEPARATOR) + if not run_id or "/" in run_id or DurableExecutionArn.from_arn(parent) is None: + return None + return cls(durable_execution_arn=parent, run_id=run_id) + + def to_arn(self) -> str: + """Reassemble the ARN this was parsed from. + + ``from_arn`` splits on the last ``/distributed-map-run/`` and refuses a + run id containing ``/``, so joining the two parts back restores the + original string exactly. + """ + return f"{self.durable_execution_arn}{_RUN_ARN_SEPARATOR}{self.run_id}" + + def serdes_context(self, role: str, *parts: str | int | None) -> SerDesContext: + """Address one piece of this run's data so writer and reader agree on it. + + A serdes that stores data outside the payload uses the context it is + handed as the address. FileSystemSerDes writes the file + durable_execution_arn/operation_id. One run hands a serdes every item, + every item's output and every reader state, so each of those needs a + distinct address. The processor writes an item's output and the parent + reads it back, so both must compute the same address. Both call this. + + ``role`` is "body", "output", "item", "state" or "next-state". ``parts`` + tells two of the same role apart, such as an item id. + """ + key = json.dumps([self.run_id, role, *parts]) + return SerDesContext( + operation_id=hashlib.blake2b(key.encode()).hexdigest()[:64], + durable_execution_arn=self.durable_execution_arn, + ) + + +@dataclass(frozen=True) +class DistributedMapSummary: + """Outcome of a map run without per-item results. + + Resolved by ``ctx.distributed_map`` for every terminal state. A non-``SUCCEEDED`` + run resolves rather than raising. Use :meth:`throw_if_error` to opt into raising. + """ + + status: DistributedMapStatus + success_count: int + failure_count: int + read_count: int + distributed_map_run_arn: str | None = None + source_exhausted: bool | None = None + error: ErrorObject | None = None + total_count: int | None = None + + @classmethod + def from_operation(cls, operation: Operation | None) -> Self: + """Rebuild the summary from a terminal DISTRIBUTED_MAP operation.""" + return cls(**_summary_fields(operation)) + + @property + def distributed_map_id(self) -> str | None: + """Run id from :attr:`distributed_map_run_arn`, ``None`` if absent or unparseable.""" + if self.distributed_map_run_arn is None: + return None + parsed = DistributedMapRunArn.from_arn(self.distributed_map_run_arn) + return parsed.run_id if parsed else None + + @property + def has_failure(self) -> bool: + """``True`` when any item permanently failed.""" + return self.failure_count > 0 + + def throw_if_error(self) -> None: + """Raise :class:`DistributedMapError` on any non-success outcome.""" + if self.status is not DistributedMapStatus.SUCCEEDED: + error = self.error + msg = f"Map run ended {self.status.value}" + if error is not None and error.message: + msg = f"{msg}: {error.message}" + # A wholly empty error carries nothing to rebuild, so it gets no cause. + cause = ( + error.to_durable_operation_error() + if error is not None and error.to_dict() + else None + ) + raise DistributedMapError( + message=msg, + error_type=error.type if error else None, + data=error.data if error else None, + stack_trace=error.stack_trace if error else None, + ) from cause + if self.failure_count > 0: + msg = ( + f"Map run succeeded but {self.failure_count} item(s) permanently failed" + ) + raise DistributedMapError(msg) + + +@dataclass(frozen=True) +class DistributedMapResultItem(Generic[ItemOutput]): + """Outcome of a single map run item.""" + + item_id: str + status: DistributedMapItemStatus + output: ItemOutput | None = None + error: ErrorObject | None = None + + +@dataclass(frozen=True) +class DistributedMapResult(DistributedMapSummary, Generic[ItemOutput]): + """Outcome of a map run with per-item results. + + Resolved by ``ctx.distributed_map`` when passed a + :class:`DistributedMapResultConfig`. Extends :class:`DistributedMapSummary` + with the retained per-item results. + """ + + all: list[DistributedMapResultItem[ItemOutput]] = field(default_factory=list) + + @classmethod + def from_operation(cls, operation: Operation | None) -> Self: + """Rebuild a result from a terminal operation that retained no items. + + The inherited summary factory cannot deserialize items, so it leaves + ``all`` empty. That is the right answer for a run that retained + nothing. For a run that did retain results it would return counts that + contradict an empty ``all``, so that call is refused here rather than + answered wrongly. Use :meth:`from_operation_and_items` for those. + + Raises: + ValidationError: if the operation carries retained results. + """ + details = operation.distributed_map_details if operation else None + if details is not None and details.results: + msg = ( + "DistributedMapResult.from_operation cannot carry retained " + "results. Use from_operation_and_items with the deserialized " + "items instead." + ) + raise ValidationError(msg) + return super().from_operation(operation) + + @classmethod + def from_operation_and_items( + cls, + operation: Operation | None, + items: list[DistributedMapResultItem[ItemOutput]], + ) -> Self: + """Rebuild the result from a terminal operation and its deserialized items.""" + return cls(**_summary_fields(operation), all=items) + + def succeeded(self) -> list[DistributedMapResultItem[ItemOutput]]: + """Return the items that succeeded.""" + return [ + item + for item in self.all + if item.status is DistributedMapItemStatus.SUCCEEDED + ] + + def failed(self) -> list[DistributedMapResultItem[ItemOutput]]: + """Return the items that permanently failed.""" + return [ + item for item in self.all if item.status is DistributedMapItemStatus.FAILED + ] + + def get_results(self) -> list[ItemOutput | None]: + """Return one output per succeeded item, None where none was recorded.""" + return [ + item.output + for item in self.all + if item.status is DistributedMapItemStatus.SUCCEEDED + ] + + def get_errors(self) -> list[ErrorObject | None]: + """Return one error per failed item, None where none was recorded.""" + return [ + item.error + for item in self.all + if item.status is DistributedMapItemStatus.FAILED + ] + + def throw_if_error(self) -> None: + """Raise the first failed item's error, otherwise defer to the summary rule.""" + if self.status is DistributedMapStatus.SUCCEEDED and self.failure_count > 0: + failed = self.failed() + if failed: + first = failed[0] + error = first.error + if error is not None and error.to_dict(): + error.raise_as_operation_error(DistributedMapError) + msg = f"item {first.item_id} failed" + raise DistributedMapError(msg) + super().throw_if_error() diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/exceptions.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/exceptions.py index ea3f163f2..69e9c4e59 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/exceptions.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/exceptions.py @@ -330,6 +330,10 @@ class InvokeError(DurableOperationError): """Raised when a durable invoke operation fails.""" +class DistributedMapError(DurableOperationError): + """Raised when a durable map run operation fails.""" + + class ChildContextError(DurableOperationError): """Raised when a child context (run_in_child_context, map, parallel) fails.""" @@ -404,6 +408,7 @@ class CallbackSubmitterError(CallbackError): for cls in [ StepError, InvokeError, + DistributedMapError, ChildContextError, WaitForConditionError, CallbackError, diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/lambda_service.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/lambda_service.py index 21e5b2d5d..558728008 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/lambda_service.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/lambda_service.py @@ -13,7 +13,9 @@ Any, NoReturn, Protocol, + Self, TypeAlias, + TypeVar, cast, runtime_checkable, ) @@ -22,9 +24,28 @@ from botocore.config import Config from aws_durable_execution_sdk_python.__about__ import __version__ +from aws_durable_execution_sdk_python.config import ( + DistributedMapCompletionConfig as ConfigCompletionConfig, +) +from aws_durable_execution_sdk_python.config import ( + DistributedMapDestinationConfig as ConfigDestinationConfig, +) +from aws_durable_execution_sdk_python.config import ( + DistributedMapCsvDelimiter, + DistributedMapItemStatus, + DistributedMapProcessor, + DistributedMapProcessorRetryConfig, + DistributedMapS3SourceType, + DistributedMapSourceFormat, + FailureDestination, + ProcessorResponseMode, + S3Source, + SuccessDestination, +) from aws_durable_execution_sdk_python.exceptions import ( CheckpointError, DurableOperationError, + ExecutionError, GetExecutionStateError, SerDesError, ) @@ -95,6 +116,7 @@ class OperationType(Enum): WAIT = "WAIT" CALLBACK = "CALLBACK" CHAINED_INVOKE = "CHAINED_INVOKE" + DISTRIBUTED_MAP = "DISTRIBUTED_MAP" class CallbackTimeoutType(Enum): @@ -102,6 +124,36 @@ class CallbackTimeoutType(Enum): HEARTBEAT = "Callback.Heartbeat" +class DistributedMapSourceType(Enum): + INLINE = "INLINE" + S3 = "S3" + READER_FUNCTION = "READER_FUNCTION" + + +class DistributedMapCsvHeaderLocation(Enum): + FIRST_ROW = "FIRST_ROW" + GIVEN = "GIVEN" + + +class DistributedMapFunctionResponseType(Enum): + REPORT_BATCH_ITEM_OUTCOMES = "REPORT_BATCH_ITEM_OUTCOMES" + + +class DistributedMapDestinationType(Enum): + S3 = "S3" + + +class DistributedMapDestinationInclude(Enum): + INPUT = "INPUT" + OUTPUT = "OUTPUT" + ERROR = "ERROR" + + +class DistributedMapResultCollectionMode(Enum): + NONE = "NONE" + INLINE = "INLINE" + + class OperationSubType(StrEnum): """The subtypes the SDK records for its own operations. @@ -126,6 +178,7 @@ class OperationSubType(StrEnum): WAIT_FOR_CALLBACK = "WaitForCallback" WAIT_FOR_CONDITION = "WaitForCondition" CHAINED_INVOKE = "ChainedInvoke" + DISTRIBUTED_MAP = "DistributedMap" class InvocationStatus(Enum): @@ -398,6 +451,107 @@ def from_dict(cls, data: MutableMapping[str, Any]) -> ChainedInvokeDetails: ) +_BackendEnumT = TypeVar("_BackendEnumT", bound=Enum) + + +def _parse_enum( + enum_cls: type[_BackendEnumT], + value: str, + field_name: str, + *, + unknown_fallback: _BackendEnumT | None = None, +) -> _BackendEnumT: + """Convert a backend enum string, returning unknown_fallback for an unrecognized value or raising ExecutionError when no fallback is given.""" + try: + return enum_cls(value) + except ValueError as e: + if unknown_fallback is not None: + return unknown_fallback + msg = f"Unknown distributed map {field_name} from the backend: {value!r}" + raise ExecutionError(msg) from e + + +@dataclass(frozen=True) +class DistributedMapResultItem: + """Represent a single map run item's outcome.""" + + item_id: str + status: DistributedMapItemStatus + output: str | None = None + error: ErrorObject | None = None + + @classmethod + def from_dict(cls, data: MutableMapping[str, Any]) -> DistributedMapResultItem: + error_raw = data.get("Error") + item_id = data.get("ItemId") + status_raw = data.get("Status") + # ItemId and Status are both required on every collected result, so an + # absent one breaks the contract and must fail. Substituting an empty + # item id would hand the customer a result they cannot match to an item. + # An unrecognized status value is a status added after this SDK version. + if not item_id: + msg = "missing distributed map item id from backend" + raise ExecutionError(msg) + if not status_raw: + msg = f"Distributed map result item {item_id!r} carried no item status" + raise ExecutionError(msg) + return cls( + item_id=item_id, + status=_parse_enum( + DistributedMapItemStatus, + status_raw, + "item status", + unknown_fallback=DistributedMapItemStatus.UNKNOWN_TO_SDK_VERSION, + ), + output=data.get("Output"), + error=ErrorObject.from_dict(error_raw) if error_raw is not None else None, + ) + + def to_dict(self) -> MutableMapping[str, Any]: + result: MutableMapping[str, Any] = { + "ItemId": self.item_id, + "Status": self.status.value, + } + if self.output is not None: + result["Output"] = self.output + if self.error is not None: + result["Error"] = self.error.to_dict() + return result + + +@dataclass(frozen=True) +class DistributedMapDetails: + distributed_map_run_arn: str | None = None + source_exhausted: bool | None = None + error: ErrorObject | None = None + total_count: int | None = None + # The service is required to send these three on a terminal operation. They + # are held as optional so an omitted count is distinguishable from a count + # of zero. The summary build rejects an omitted one; defaulting it to zero + # here would report a run with failed items as a run with none. + success_count: int | None = None + failure_count: int | None = None + read_count: int | None = None + results: list[DistributedMapResultItem] | None = None + + @classmethod + def from_dict(cls, data: MutableMapping[str, Any]) -> DistributedMapDetails: + results_raw = data.get("Results") + error_raw = data.get("Error") + return cls( + distributed_map_run_arn=data.get("DistributedMapRunArn"), + source_exhausted=data.get("SourceExhausted"), + error=ErrorObject.from_dict(error_raw) if error_raw is not None else None, + total_count=data.get("TotalCount"), + success_count=data.get("SuccessCount"), + failure_count=data.get("FailureCount"), + read_count=data.get("ReadCount"), + results=[DistributedMapResultItem.from_dict(item) for item in results_raw] + if results_raw is not None + else None, + ) + + @dataclass(frozen=True) class StepOptions: next_attempt_delay_seconds: int = 0 @@ -494,6 +648,697 @@ def to_dict(self) -> MutableMapping[str, Any]: return result +@dataclass(frozen=True) +class DistributedMapCsvFormatOptions: + """Represent CSV format options for an S3 source.""" + + header_location: DistributedMapCsvHeaderLocation + headers: list[str] | None = None + delimiter: DistributedMapCsvDelimiter | None = None + + def to_dict(self) -> MutableMapping[str, Any]: + result: MutableMapping[str, Any] = { + "HeaderLocation": self.header_location.value + } + if self.headers is not None: + result["Headers"] = self.headers + if self.delimiter is not None: + result["Delimiter"] = self.delimiter.value + return result + + @classmethod + def from_dict( + cls, data: MutableMapping[str, Any] + ) -> DistributedMapCsvFormatOptions: + headers = data.get("Headers") + delimiter = data.get("Delimiter") + return cls( + header_location=DistributedMapCsvHeaderLocation( + data.get("HeaderLocation", "FIRST_ROW") + ), + headers=list(headers) if headers is not None else None, + delimiter=DistributedMapCsvDelimiter(delimiter) + if delimiter is not None + else None, + ) + + @classmethod + def from_source(cls, s3: S3Source) -> Self | None: + """Build the CSV options for a CSV source, or None for any other format.""" + if s3.fmt is not DistributedMapSourceFormat.CSV: + return None + return cls( + header_location=( + DistributedMapCsvHeaderLocation.GIVEN + if s3.headers is not None + else DistributedMapCsvHeaderLocation.FIRST_ROW + ), + headers=s3.headers, + delimiter=s3.delimiter, + ) + + +@dataclass(frozen=True) +class DistributedMapS3ObjectConfig: + """Represent the object an OBJECT S3 source reads.""" + + key: str + fmt: DistributedMapSourceFormat + csv_format_options: DistributedMapCsvFormatOptions | None = None + + def to_dict(self) -> MutableMapping[str, Any]: + result: MutableMapping[str, Any] = { + "Key": self.key, + "Format": self.fmt.value, + } + if self.csv_format_options is not None: + result["CsvFormatOptions"] = self.csv_format_options.to_dict() + return result + + @classmethod + def from_dict(cls, data: MutableMapping[str, Any]) -> DistributedMapS3ObjectConfig: + csv_raw = data.get("CsvFormatOptions") + return cls( + key=data.get("Key", ""), + fmt=DistributedMapSourceFormat(data["Format"]), + csv_format_options=DistributedMapCsvFormatOptions.from_dict(csv_raw) + if csv_raw is not None + else None, + ) + + +@dataclass(frozen=True) +class DistributedMapS3ListedObjectMetadataConfig: + """Represent the prefix a LISTED_OBJECT_METADATA S3 source lists.""" + + key_prefix: str + + def to_dict(self) -> MutableMapping[str, Any]: + return {"KeyPrefix": self.key_prefix} + + @classmethod + def from_dict( + cls, data: MutableMapping[str, Any] + ) -> DistributedMapS3ListedObjectMetadataConfig: + return cls(key_prefix=data.get("KeyPrefix", "")) + + +@dataclass(frozen=True) +class DistributedMapS3ListedObjectsConfig: + """Represent the prefix a LISTED_OBJECTS S3 source lists and reads.""" + + key_prefix: str + fmt: DistributedMapSourceFormat + csv_format_options: DistributedMapCsvFormatOptions | None = None + + def to_dict(self) -> MutableMapping[str, Any]: + result: MutableMapping[str, Any] = { + "KeyPrefix": self.key_prefix, + "Format": self.fmt.value, + } + if self.csv_format_options is not None: + result["CsvFormatOptions"] = self.csv_format_options.to_dict() + return result + + @classmethod + def from_dict( + cls, data: MutableMapping[str, Any] + ) -> DistributedMapS3ListedObjectsConfig: + csv_raw = data.get("CsvFormatOptions") + return cls( + key_prefix=data.get("KeyPrefix", ""), + fmt=DistributedMapSourceFormat(data["Format"]), + csv_format_options=DistributedMapCsvFormatOptions.from_dict(csv_raw) + if csv_raw is not None + else None, + ) + + +@dataclass(frozen=True) +class DistributedMapS3SourceConfig: + """Represent an S3 distributed map source config. + + ``source_type`` selects which of the three config blocks is present. The + other two are absent. + """ + + source_type: DistributedMapS3SourceType + bucket: str + expected_bucket_owner: str | None = None + object_config: DistributedMapS3ObjectConfig | None = None + listed_object_metadata_config: DistributedMapS3ListedObjectMetadataConfig | None = ( + None + ) + listed_objects_config: DistributedMapS3ListedObjectsConfig | None = None + + def to_dict(self) -> MutableMapping[str, Any]: + result: MutableMapping[str, Any] = { + "Type": self.source_type.value, + "Bucket": self.bucket, + } + if self.expected_bucket_owner is not None: + result["ExpectedBucketOwner"] = self.expected_bucket_owner + if self.object_config is not None: + result["ObjectConfig"] = self.object_config.to_dict() + if self.listed_object_metadata_config is not None: + result["ListedObjectMetadataConfig"] = ( + self.listed_object_metadata_config.to_dict() + ) + if self.listed_objects_config is not None: + result["ListedObjectsConfig"] = self.listed_objects_config.to_dict() + return result + + @classmethod + def from_dict(cls, data: MutableMapping[str, Any]) -> DistributedMapS3SourceConfig: + object_raw = data.get("ObjectConfig") + metadata_raw = data.get("ListedObjectMetadataConfig") + listed_raw = data.get("ListedObjectsConfig") + return cls( + source_type=DistributedMapS3SourceType(data["Type"]), + bucket=data.get("Bucket", ""), + expected_bucket_owner=data.get("ExpectedBucketOwner"), + object_config=DistributedMapS3ObjectConfig.from_dict(object_raw) + if object_raw is not None + else None, + listed_object_metadata_config=( + DistributedMapS3ListedObjectMetadataConfig.from_dict(metadata_raw) + if metadata_raw is not None + else None + ), + listed_objects_config=DistributedMapS3ListedObjectsConfig.from_dict( + listed_raw + ) + if listed_raw is not None + else None, + ) + + @classmethod + def from_source(cls, s3: S3Source) -> Self: + """Translate the S3 source into its matching nested config block. + + The nested config blocks require a key, a key prefix and a format, while + ``S3Source`` holds each of them as optional because which ones apply + depends on the source type. ``S3Source`` is frozen and its + ``__post_init__`` rejects a source missing the fields its own type needs, + so each field read below is already present. The casts narrow the + optional declarations for the type checker. + """ + csv_options = DistributedMapCsvFormatOptions.from_source(s3) + if s3.source_type is DistributedMapS3SourceType.OBJECT: + return cls( + source_type=s3.source_type, + bucket=s3.bucket, + expected_bucket_owner=s3.expected_bucket_owner, + object_config=DistributedMapS3ObjectConfig( + key=cast(str, s3.key), + fmt=cast(DistributedMapSourceFormat, s3.fmt), + csv_format_options=csv_options, + ), + ) + if s3.source_type is DistributedMapS3SourceType.LISTED_OBJECT_METADATA: + return cls( + source_type=s3.source_type, + bucket=s3.bucket, + expected_bucket_owner=s3.expected_bucket_owner, + listed_object_metadata_config=( + DistributedMapS3ListedObjectMetadataConfig( + key_prefix=cast(str, s3.key_prefix) + ) + ), + ) + return cls( + source_type=s3.source_type, + bucket=s3.bucket, + expected_bucket_owner=s3.expected_bucket_owner, + listed_objects_config=DistributedMapS3ListedObjectsConfig( + key_prefix=cast(str, s3.key_prefix), + fmt=cast(DistributedMapSourceFormat, s3.fmt), + csv_format_options=csv_options, + ), + ) + + +@dataclass(frozen=True) +class DistributedMapReaderFunctionSourceConfig: + """Represent a reader-function distributed map source config.""" + + function_name: str + initial_state: str | None = None + + def to_dict(self) -> MutableMapping[str, Any]: + result: MutableMapping[str, Any] = {"FunctionName": self.function_name} + if self.initial_state is not None: + result["InitialState"] = self.initial_state + return result + + @classmethod + def from_dict( + cls, data: MutableMapping[str, Any] + ) -> DistributedMapReaderFunctionSourceConfig: + return cls( + function_name=data.get("FunctionName", ""), + initial_state=data.get("InitialState"), + ) + + +@dataclass(frozen=True) +class DistributedMapInlineSourceConfig: + """Represent the items an inline map run source reads from.""" + + items: list[str] = field(default_factory=list) + + def to_dict(self) -> MutableMapping[str, Any]: + return {"Items": self.items} + + @classmethod + def from_dict( + cls, data: MutableMapping[str, Any] + ) -> DistributedMapInlineSourceConfig: + return cls(items=list(data.get("Items", []))) + + +@dataclass(frozen=True) +class DistributedMapSourceConfig: + """Represent a map run source.""" + + source_type: DistributedMapSourceType + max_items: int | None = None + inline_source_config: DistributedMapInlineSourceConfig | None = None + s3_config: DistributedMapS3SourceConfig | None = None + reader_config: DistributedMapReaderFunctionSourceConfig | None = None + + def to_dict(self) -> MutableMapping[str, Any]: + result: MutableMapping[str, Any] = {"Type": self.source_type.value} + if self.source_type is DistributedMapSourceType.INLINE: + inline = self.inline_source_config or DistributedMapInlineSourceConfig() + result["InlineSourceConfig"] = inline.to_dict() + elif ( + self.source_type is DistributedMapSourceType.S3 + and self.s3_config is not None + ): + result["S3SourceConfig"] = self.s3_config.to_dict() + elif ( + self.source_type is DistributedMapSourceType.READER_FUNCTION + and self.reader_config is not None + ): + result["ReaderFunctionSourceConfig"] = self.reader_config.to_dict() + if self.max_items is not None: + result["MaxItemsToRead"] = self.max_items + return result + + @classmethod + def from_dict(cls, data: MutableMapping[str, Any]) -> DistributedMapSourceConfig: + source_type = DistributedMapSourceType(data.get("Type", "INLINE")) + inline_cfg = data.get("InlineSourceConfig") or {} + s3_raw = data.get("S3SourceConfig") + reader_raw = data.get("ReaderFunctionSourceConfig") + return cls( + source_type=source_type, + max_items=data.get("MaxItemsToRead"), + inline_source_config=DistributedMapInlineSourceConfig.from_dict(inline_cfg) + if source_type is DistributedMapSourceType.INLINE + else None, + s3_config=DistributedMapS3SourceConfig.from_dict(s3_raw) + if s3_raw is not None + else None, + reader_config=DistributedMapReaderFunctionSourceConfig.from_dict(reader_raw) + if reader_raw is not None + else None, + ) + + @classmethod + def create_inline( + cls, items: list[str], *, max_items: int | None = None + ) -> DistributedMapSourceConfig: + """Build an inline source from items the caller already serialized.""" + return cls( + source_type=DistributedMapSourceType.INLINE, + max_items=max_items, + inline_source_config=DistributedMapInlineSourceConfig(items=items), + ) + + @classmethod + def create_s3( + cls, s3: S3Source, *, max_items: int | None = None + ) -> DistributedMapSourceConfig: + """Build an S3 source from its resolved configuration.""" + return cls( + source_type=DistributedMapSourceType.S3, + max_items=max_items, + s3_config=DistributedMapS3SourceConfig.from_source(s3), + ) + + @classmethod + def create_reader( + cls, + function_name: str, + initial_state: str | None, + *, + max_items: int | None = None, + ) -> DistributedMapSourceConfig: + """Build a reader-function source from a state the caller already serialized.""" + return cls( + source_type=DistributedMapSourceType.READER_FUNCTION, + max_items=max_items, + reader_config=DistributedMapReaderFunctionSourceConfig( + function_name=function_name, initial_state=initial_state + ), + ) + + +_UNLIMITED_RETRY_WIRE = -1 + +_RESPONSE_TYPE_FOR_MODE = { + ProcessorResponseMode.ITEM_OUTCOMES: DistributedMapFunctionResponseType.REPORT_BATCH_ITEM_OUTCOMES, +} + + +@dataclass(frozen=True) +class DistributedMapProcessorConfig: + """Represent a map run processor.""" + + function_name: str + function_response_types: list[DistributedMapFunctionResponseType] | None = None + batch_size: int | None = None + max_retry_attempts: int | None = None + max_retry_duration_seconds: int | None = None + durable_execution_name_prefix: str | None = None + + def to_dict(self) -> MutableMapping[str, Any]: + result: MutableMapping[str, Any] = {"FunctionName": self.function_name} + if self.function_response_types: + result["FunctionResponseTypes"] = [ + t.value for t in self.function_response_types + ] + if self.batch_size is not None: + result["BatchSize"] = self.batch_size + if self.max_retry_attempts is not None: + result["MaxRetryAttempts"] = self.max_retry_attempts + if self.max_retry_duration_seconds is not None: + result["MaxRetryDurationSeconds"] = self.max_retry_duration_seconds + if self.durable_execution_name_prefix is not None: + result["DurableExecutionNamePrefix"] = self.durable_execution_name_prefix + return result + + @classmethod + def from_dict(cls, data: MutableMapping[str, Any]) -> DistributedMapProcessorConfig: + response_types = data.get("FunctionResponseTypes") + return cls( + function_name=data.get("FunctionName", ""), + function_response_types=[ + DistributedMapFunctionResponseType(t) for t in response_types + ] + if response_types + else None, + batch_size=data.get("BatchSize"), + max_retry_attempts=data.get("MaxRetryAttempts"), + max_retry_duration_seconds=data.get("MaxRetryDurationSeconds"), + durable_execution_name_prefix=data.get("DurableExecutionNamePrefix"), + ) + + @classmethod + def from_processor(cls, processor: DistributedMapProcessor) -> Self: + """Translate the processor, mapping the response mode and unlimited retries.""" + response_type = _RESPONSE_TYPE_FOR_MODE.get(processor.response_mode) + retry = processor.retry + max_retry_attempts: int | None = None + attempts = retry.max_retry_attempts if retry is not None else None + if attempts == DistributedMapProcessorRetryConfig.UNLIMITED: + max_retry_attempts = _UNLIMITED_RETRY_WIRE + elif isinstance(attempts, int): + max_retry_attempts = attempts + duration = retry.max_retry_duration if retry is not None else None + return cls( + function_name=processor.function_name, + function_response_types=[response_type] if response_type else None, + batch_size=processor.batch_size, + max_retry_attempts=max_retry_attempts, + max_retry_duration_seconds=duration.to_seconds() + if duration is not None + else None, + durable_execution_name_prefix=processor.durable_execution_name_prefix, + ) + + +@dataclass(frozen=True) +class DistributedMapCompletionConfig: + """Represent a map run completion (failure-tolerance) config.""" + + tolerated_failure_count: int | None = None + tolerated_failure_percentage: int | float | None = None + minimum_sample_size: int | None = None + + def to_dict(self) -> MutableMapping[str, Any]: + result: MutableMapping[str, Any] = {} + if self.tolerated_failure_count is not None: + result["ToleratedFailureCount"] = self.tolerated_failure_count + if self.tolerated_failure_percentage is not None: + result["ToleratedFailurePercentage"] = self.tolerated_failure_percentage + if self.minimum_sample_size is not None: + result["MinimumSampleSize"] = self.minimum_sample_size + return result + + @classmethod + def from_dict( + cls, data: MutableMapping[str, Any] + ) -> DistributedMapCompletionConfig: + return cls( + tolerated_failure_count=data.get("ToleratedFailureCount"), + tolerated_failure_percentage=data.get("ToleratedFailurePercentage"), + minimum_sample_size=data.get("MinimumSampleSize"), + ) + + @classmethod + def from_config(cls, completion_config: ConfigCompletionConfig) -> Self: + """Translate the completion config.""" + return cls( + tolerated_failure_count=completion_config.tolerated_failure_count, + tolerated_failure_percentage=completion_config.tolerated_failure_percentage, + minimum_sample_size=completion_config.minimum_sample_size, + ) + + +@dataclass(frozen=True) +class DistributedMapS3DestinationConfig: + """Represent an S3 distributed map destination config.""" + + bucket: str + key_prefix: str + expected_bucket_owner: str | None = None + + def to_dict(self) -> MutableMapping[str, Any]: + result: MutableMapping[str, Any] = { + "Bucket": self.bucket, + "KeyPrefix": self.key_prefix, + } + if self.expected_bucket_owner is not None: + result["ExpectedBucketOwner"] = self.expected_bucket_owner + return result + + @classmethod + def from_dict( + cls, data: MutableMapping[str, Any] + ) -> DistributedMapS3DestinationConfig: + return cls( + bucket=data.get("Bucket", ""), + key_prefix=data.get("KeyPrefix", ""), + expected_bucket_owner=data.get("ExpectedBucketOwner"), + ) + + +@dataclass(frozen=True) +class _DistributedMapDestinationEntry: + """Hold the members the OnSuccess and OnFailure shapes have in common.""" + + type: DistributedMapDestinationType + include: list[DistributedMapDestinationInclude] + s3_destination_config: DistributedMapS3DestinationConfig + + def to_dict(self) -> MutableMapping[str, Any]: + return { + "Type": self.type.value, + "Include": [i.value for i in self.include], + "S3DestinationConfig": self.s3_destination_config.to_dict(), + } + + @classmethod + def from_dict(cls, data: MutableMapping[str, Any]) -> Self: + s3_raw = data.get("S3DestinationConfig") or {} + return cls( + type=DistributedMapDestinationType(data.get("Type", "S3")), + include=[ + DistributedMapDestinationInclude(i) for i in data.get("Include", []) + ], + s3_destination_config=DistributedMapS3DestinationConfig.from_dict(s3_raw), + ) + + @classmethod + def _create( + cls, + destination: SuccessDestination | FailureDestination, + include: list[DistributedMapDestinationInclude], + ) -> Self: + """Build an entry from a destination and the include set its subclass computed.""" + return cls( + type=DistributedMapDestinationType.S3, + include=include, + s3_destination_config=DistributedMapS3DestinationConfig( + bucket=destination.bucket, + key_prefix=destination.prefix, + expected_bucket_owner=destination.expected_bucket_owner, + ), + ) + + +@dataclass(frozen=True) +class DistributedMapOnSuccessConfig(_DistributedMapDestinationEntry): + """Represent where a map run writes the outcome of its succeeded items.""" + + @classmethod + def from_destination(cls, destination: SuccessDestination) -> Self: + """Translate the success destination.""" + include: list[DistributedMapDestinationInclude] = [] + if destination.include_input: + include.append(DistributedMapDestinationInclude.INPUT) + if destination.include_output: + include.append(DistributedMapDestinationInclude.OUTPUT) + return cls._create(destination, include) + + +@dataclass(frozen=True) +class DistributedMapOnFailureConfig(_DistributedMapDestinationEntry): + """Represent where a map run writes the outcome of its failed items.""" + + @classmethod + def from_destination(cls, destination: FailureDestination) -> Self: + """Translate the failure destination.""" + include: list[DistributedMapDestinationInclude] = [] + if destination.include_input: + include.append(DistributedMapDestinationInclude.INPUT) + if destination.include_error: + include.append(DistributedMapDestinationInclude.ERROR) + return cls._create(destination, include) + + +@dataclass(frozen=True) +class DistributedMapDestinationConfig: + """Represent a map run destination config.""" + + on_success: DistributedMapOnSuccessConfig | None = None + on_failure: DistributedMapOnFailureConfig | None = None + + def to_dict(self) -> MutableMapping[str, Any]: + result: MutableMapping[str, Any] = {} + if self.on_success is not None: + result["OnSuccess"] = self.on_success.to_dict() + if self.on_failure is not None: + result["OnFailure"] = self.on_failure.to_dict() + return result + + @classmethod + def from_dict( + cls, data: MutableMapping[str, Any] + ) -> DistributedMapDestinationConfig: + success_raw = data.get("OnSuccess") + failure_raw = data.get("OnFailure") + return cls( + on_success=DistributedMapOnSuccessConfig.from_dict(success_raw) + if success_raw is not None + else None, + on_failure=DistributedMapOnFailureConfig.from_dict(failure_raw) + if failure_raw is not None + else None, + ) + + @classmethod + def from_config(cls, destination: ConfigDestinationConfig) -> Self | None: + """Translate the destination config, or None when neither side is set.""" + if destination.on_success is None and destination.on_failure is None: + return None + return cls( + on_success=DistributedMapOnSuccessConfig.from_destination( + destination.on_success + ) + if destination.on_success is not None + else None, + on_failure=DistributedMapOnFailureConfig.from_destination( + destination.on_failure + ) + if destination.on_failure is not None + else None, + ) + + +@dataclass(frozen=True) +class DistributedMapResultCollectionConfig: + """Represent the map run result-collection setting.""" + + mode: DistributedMapResultCollectionMode + + def to_dict(self) -> MutableMapping[str, Any]: + return {"Mode": self.mode.value} + + @classmethod + def from_dict( + cls, data: MutableMapping[str, Any] + ) -> DistributedMapResultCollectionConfig: + return cls(mode=DistributedMapResultCollectionMode(data.get("Mode", "NONE"))) + + +@dataclass(frozen=True) +class DistributedMapOptions: + """Configuration options for starting a map run.""" + + max_concurrency: int + source: DistributedMapSourceConfig + processor: DistributedMapProcessorConfig + destination: DistributedMapDestinationConfig | None = None + completion_config: DistributedMapCompletionConfig | None = None + result_collection: DistributedMapResultCollectionConfig | None = None + timeout_seconds: int | None = None + + @classmethod + def from_dict(cls, data: MutableMapping[str, Any]) -> DistributedMapOptions: + source_raw = data.get("Source") or {} + processor_raw = data.get("Processor") or {} + destination_raw = data.get("Destination") + completion_raw = data.get("CompletionConfig") + result_collection_raw = data.get("ResultCollection") + return cls( + max_concurrency=data["MaxConcurrency"], + source=DistributedMapSourceConfig.from_dict(source_raw), + processor=DistributedMapProcessorConfig.from_dict(processor_raw), + destination=DistributedMapDestinationConfig.from_dict(destination_raw) + if destination_raw is not None + else None, + completion_config=DistributedMapCompletionConfig.from_dict(completion_raw) + if completion_raw is not None + else None, + result_collection=DistributedMapResultCollectionConfig.from_dict( + result_collection_raw + ) + if result_collection_raw is not None + else None, + timeout_seconds=data.get("TimeoutSeconds"), + ) + + def to_dict(self) -> MutableMapping[str, Any]: + result: MutableMapping[str, Any] = { + "MaxConcurrency": self.max_concurrency, + "Source": self.source.to_dict(), + "Processor": self.processor.to_dict(), + } + if self.destination is not None: + result["Destination"] = self.destination.to_dict() + if self.completion_config is not None: + result["CompletionConfig"] = self.completion_config.to_dict() + if self.result_collection is not None: + result["ResultCollection"] = self.result_collection.to_dict() + if self.timeout_seconds is not None: + result["TimeoutSeconds"] = self.timeout_seconds + return result + + @dataclass(frozen=True) class ContextOptions: replay_children: ReplayChildren = False @@ -526,6 +1371,7 @@ class OperationUpdate: wait_options: WaitOptions | None = None callback_options: CallbackOptions | None = None chained_invoke_options: ChainedInvokeOptions | None = None + distributed_map_options: DistributedMapOptions | None = None def to_dict(self) -> MutableMapping[str, Any]: result: MutableMapping[str, Any] = { @@ -554,6 +1400,8 @@ def to_dict(self) -> MutableMapping[str, Any]: result["CallbackOptions"] = self.callback_options.to_dict() if self.chained_invoke_options: result["ChainedInvokeOptions"] = self.chained_invoke_options.to_dict() + if self.distributed_map_options: + result["DistributedMapOptions"] = self.distributed_map_options.to_dict() return result @@ -582,6 +1430,12 @@ def from_dict(cls, data: MutableMapping[str, Any]) -> OperationUpdate: if invoke_data := data.get("ChainedInvokeOptions"): chained_invoke_options = ChainedInvokeOptions.from_dict(invoke_data) + distributed_map_options = None + if distributed_map_options_data := data.get("DistributedMapOptions"): + distributed_map_options = DistributedMapOptions.from_dict( + distributed_map_options_data + ) + return cls( operation_id=data["Id"], operation_type=OperationType(data["Type"]), @@ -596,6 +1450,7 @@ def from_dict(cls, data: MutableMapping[str, Any]) -> OperationUpdate: wait_options=wait_options, callback_options=callback_options, chained_invoke_options=chained_invoke_options, + distributed_map_options=distributed_map_options, ) @classmethod @@ -776,6 +1631,26 @@ def create_invoke_start( # endregion invoke + # region map run + @classmethod + def create_distributed_map_start( + cls, + identifier: OperationIdentifier, + distributed_map_options: DistributedMapOptions, + ) -> OperationUpdate: + """Create an instance of OperationUpdate for type: DISTRIBUTED_MAP, action: START.""" + return cls( + operation_id=identifier.operation_id, + parent_id=identifier.parent_id, + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=identifier.sub_type, + action=OperationAction.START, + name=identifier.name, + distributed_map_options=distributed_map_options, + ) + + # endregion map run + # region wait for condition @classmethod def create_wait_for_condition_start( @@ -899,6 +1774,7 @@ class Operation: wait_details: WaitDetails | None = None callback_details: CallbackDetails | None = None chained_invoke_details: ChainedInvokeDetails | None = None + distributed_map_details: DistributedMapDetails | None = None @classmethod def from_dict(cls, data: MutableMapping[str, Any]) -> Operation: @@ -941,6 +1817,14 @@ def from_dict(cls, data: MutableMapping[str, Any]) -> Operation: chained_invoke_details ) + distributed_map_details = None + # The service sends this object on every distributed map operation, and it is + # empty until the run starts. Test for the key, not for a truthy value. + if "DistributedMapDetails" in data: + distributed_map_details = DistributedMapDetails.from_dict( + data["DistributedMapDetails"] + ) + return cls( operation_id=data["Id"], operation_type=operation_type, @@ -956,6 +1840,7 @@ def from_dict(cls, data: MutableMapping[str, Any]) -> Operation: wait_details=wait_details, callback_details=callback_details, chained_invoke_details=chained_invoke_details, + distributed_map_details=distributed_map_details, ) def to_dict(self) -> MutableMapping[str, Any]: @@ -1020,6 +1905,41 @@ def to_dict(self) -> MutableMapping[str, Any]: if self.chained_invoke_details.error: invoke_dict["Error"] = self.chained_invoke_details.error.to_dict() result["ChainedInvokeDetails"] = invoke_dict + if self.distributed_map_details is not None: + distributed_map_details_dict: MutableMapping[str, Any] = {} + if self.distributed_map_details.success_count is not None: + distributed_map_details_dict["SuccessCount"] = ( + self.distributed_map_details.success_count + ) + if self.distributed_map_details.failure_count is not None: + distributed_map_details_dict["FailureCount"] = ( + self.distributed_map_details.failure_count + ) + if self.distributed_map_details.read_count is not None: + distributed_map_details_dict["ReadCount"] = ( + self.distributed_map_details.read_count + ) + if self.distributed_map_details.distributed_map_run_arn: + distributed_map_details_dict["DistributedMapRunArn"] = ( + self.distributed_map_details.distributed_map_run_arn + ) + if self.distributed_map_details.source_exhausted is not None: + distributed_map_details_dict["SourceExhausted"] = ( + self.distributed_map_details.source_exhausted + ) + if self.distributed_map_details.error is not None: + distributed_map_details_dict["Error"] = ( + self.distributed_map_details.error.to_dict() + ) + if self.distributed_map_details.total_count is not None: + distributed_map_details_dict["TotalCount"] = ( + self.distributed_map_details.total_count + ) + if self.distributed_map_details.results is not None: + distributed_map_details_dict["Results"] = [ + item.to_dict() for item in self.distributed_map_details.results + ] + result["DistributedMapDetails"] = distributed_map_details_dict return result def to_json_dict(self) -> MutableMapping[str, Any]: diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/operation/dmap.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/operation/dmap.py new file mode 100644 index 000000000..f10d10369 --- /dev/null +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/operation/dmap.py @@ -0,0 +1,330 @@ +"""Implement the Durable map run operation.""" + +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING, Any, cast + +from aws_durable_execution_sdk_python.config import ( + DistributedMapResultConfig, + DistributedMapSource, + ReaderSource, +) +from aws_durable_execution_sdk_python.dmap.models import ( + DistributedMapResult, + DistributedMapResultItem, + DistributedMapRunArn, + DistributedMapSummary, +) +from aws_durable_execution_sdk_python.exceptions import ( + ExecutionError, +) +from aws_durable_execution_sdk_python.identifier import OperationIdNamespace +from aws_durable_execution_sdk_python.lambda_service import ( + DistributedMapCompletionConfig, + DistributedMapDestinationConfig, + DistributedMapOptions, + DistributedMapProcessorConfig, + DistributedMapResultCollectionConfig, + DistributedMapResultCollectionMode, + DistributedMapSourceConfig, + OperationUpdate, +) +from aws_durable_execution_sdk_python.operation.base import ( + CheckResult, + OperationExecutor, +) +from aws_durable_execution_sdk_python.serdes import ( + DEFAULT_JSON_SERDES, + deserialize, + serialize, +) +from aws_durable_execution_sdk_python.suspend import suspend_with_optional_resume_delay + +if TYPE_CHECKING: + from collections.abc import Sequence + + from aws_durable_execution_sdk_python.config import ( + DistributedMapConfig, + DistributedMapProcessor, + ) + from aws_durable_execution_sdk_python.identifier import OperationIdentifier + from aws_durable_execution_sdk_python.lambda_service import ( + DistributedMapDetails, + Operation, + ) + from aws_durable_execution_sdk_python.serdes import SerDes + from aws_durable_execution_sdk_python.state import ( + CheckpointedResult, + ExecutionState, + ) + +logger = logging.getLogger(__name__) + + +class DistributedMapOperationExecutor(OperationExecutor[DistributedMapSummary]): + """Executor for map run operations. + + Creates the START checkpoint if none exists, then suspends until the + backend completes the run and re-invokes the parent. On resume, a + ``DistributedMapSummary`` (or ``DistributedMapResult`` when result collection is enabled) + is built from the checkpointed ``DistributedMapDetails``. + """ + + def __init__( + self, + source: DistributedMapSource | Sequence[Any], + processor: DistributedMapProcessor, + max_concurrency: int, + state: ExecutionState, + operation_identifier: OperationIdentifier, + config: DistributedMapConfig, + ): + """Initialize the map run operation executor. + + Args: + source: The items to process (typed source or sequence shorthand) + processor: The processor configuration + max_concurrency: Maximum concurrent processor invocations + state: The execution state + operation_identifier: The operation identifier + config: Configuration for the map run operation + """ + self.source = source + self.processor = processor + self.max_concurrency = max_concurrency + self.state = state + self.operation_identifier = operation_identifier + self.config = config + + def _serialize(self, serdes: SerDes | None, value: Any, operation_id: str) -> str: + """Serialize a value with the given id and this execution's ARN.""" + return serialize( + serdes=serdes or DEFAULT_JSON_SERDES, + value=value, + operation_id=operation_id, + durable_execution_arn=self.state.durable_execution_arn, + ) + + def _serialize_inline_items( + self, items: Sequence[Any], serdes: SerDes | None + ) -> list[str]: + """Serialize each inline item.""" + # Each item gets its own id, as each map item does, so a serdes that + # stores values under their id keeps one value per item. + namespace = OperationIdNamespace(self.operation_identifier.operation_id) + return [ + self._serialize(serdes, item, namespace.create_id_for_step(index)) + for index, item in enumerate(items) + ] + + def _reader_initial_state(self, reader: ReaderSource) -> str | None: + """Serialize the reader's initial state.""" + if reader.initial_state is None: + return None + state = self._serialize( + reader.state_serdes, + reader.initial_state, + self.operation_identifier.operation_id, + ) + return state + + def _build_source_config(self) -> DistributedMapSourceConfig: + """Translate the source (typed or sequence shorthand) into its source config.""" + source = self.source + if not isinstance(source, DistributedMapSource): + # A sequence is treated as an inline source with the default serializer. + return DistributedMapSourceConfig.create_inline( + self._serialize_inline_items(source, None) + ) + if source.inline_items is not None: + return DistributedMapSourceConfig.create_inline( + self._serialize_inline_items(source.inline_items, source.inline_serdes), + max_items=source.max_items, + ) + if source.s3 is not None: + return DistributedMapSourceConfig.create_s3( + source.s3, max_items=source.max_items + ) + # DistributedMapSource is frozen and its __post_init__ requires exactly one + # kind, so a source with no inline items and no S3 source has a reader. + reader = cast(ReaderSource, source.reader) + return DistributedMapSourceConfig.create_reader( + reader.function_name, + self._reader_initial_state(reader), + max_items=source.max_items, + ) + + def _build_options(self) -> DistributedMapOptions: + """Assemble the DistributedMapOptions payload from the operands and config.""" + config = self.config + return DistributedMapOptions( + max_concurrency=self.max_concurrency, + source=self._build_source_config(), + processor=DistributedMapProcessorConfig.from_processor(self.processor), + destination=( + DistributedMapDestinationConfig.from_config(config.destination) + if config.destination is not None + else None + ), + completion_config=( + DistributedMapCompletionConfig.from_config(config.completion_config) + if config.completion_config is not None + else None + ), + result_collection=( + DistributedMapResultCollectionConfig( + mode=DistributedMapResultCollectionMode.INLINE + ) + if isinstance(config, DistributedMapResultConfig) + else None + ), + timeout_seconds=config.timeout.to_seconds() + if config.timeout is not None + else None, + ) + + def _resolve_summary(self, operation: Operation | None) -> DistributedMapSummary: + """Reconstruct the resolved summary/result from the terminal operation.""" + if not isinstance(self.config, DistributedMapResultConfig): + return DistributedMapSummary.from_operation(operation) + details = operation.distributed_map_details if operation else None + items = ( + self._deserialize_items(details, self.config.result_serdes) + if details is not None + else [] + ) + return DistributedMapResult.from_operation_and_items(operation, items) + + def _deserialize_items( + self, details: DistributedMapDetails, result_serdes: SerDes | None + ) -> list[DistributedMapResultItem]: + """Deserialize the service result items into customer result items.""" + run_arn = DistributedMapRunArn.from_arn(details.distributed_map_run_arn or "") + items: list[DistributedMapResultItem] = [] + for entry in details.results or (): + output: Any | None = None + if entry.output is not None: + # The processor serialized this output under the run and item + # id, so the same context is rebuilt here from the run ARN. + if run_arn is None: + msg = ( + "DISTRIBUTED_MAP result carried an output but no valid " + "DistributedMapRunArn" + ) + raise ExecutionError(msg) + ctx = run_arn.serdes_context("output", entry.item_id) + output = deserialize( + serdes=result_serdes or DEFAULT_JSON_SERDES, + data=entry.output, + operation_id=ctx.operation_id, + durable_execution_arn=ctx.durable_execution_arn, + ) + items.append( + DistributedMapResultItem( + item_id=entry.item_id, + status=entry.status, + output=output, + error=entry.error, + ) + ) + return items + + def check_result_status(self) -> CheckResult[DistributedMapSummary]: + """Check operation status and create the START checkpoint if needed. + + Called twice by process() when creating synchronous checkpoints: once before + and once after, to detect if the operation completed immediately. + + Returns: + CheckResult indicating the next action to take + + Raises: + SuspendExecution: For STARTED operations waiting for completion + """ + checkpointed_result: CheckpointedResult = self._get_checkpoint_result() + + # Terminal success - build the summary/result from the operation + if checkpointed_result.is_succeeded(): + operation = checkpointed_result.operation + summary = self._resolve_summary(operation) + return CheckResult.create_completed(summary) + + # Operation-level terminal failure. Every terminal state resolves with the + # summary, and throw_if_error opts into raising. + if ( + checkpointed_result.is_failed() + or checkpointed_result.is_timed_out() + or checkpointed_result.is_stopped() + ): + operation = checkpointed_result.operation + if operation is not None and operation.distributed_map_details is not None: + return CheckResult.create_completed(self._resolve_summary(operation)) + status_value = ( + checkpointed_result.status.value + if checkpointed_result.status + else "UNKNOWN" + ) + msg = ( + f"DISTRIBUTED_MAP operation ended {status_value} but carried no " + f"DistributedMapDetails" + ) + raise ExecutionError(msg) + + # Started - ready to suspend + if checkpointed_result.is_started(): + logger.debug( + "⏳ Map run %s still in progress, will suspend", + self.operation_identifier.name + or self.operation_identifier.operation_id, + ) + return CheckResult.create_is_ready_to_execute(checkpointed_result) + + # Create START checkpoint if not exists + if not checkpointed_result.is_existent(): + start_operation: OperationUpdate = ( + OperationUpdate.create_distributed_map_start( + identifier=self.operation_identifier, + distributed_map_options=self._build_options(), + ) + ) + # Checkpoint map run START with blocking (is_sync=True). + # Must ensure the map run is recorded before suspending execution. + self.state.create_checkpoint(operation_update=start_operation, is_sync=True) + + logger.debug( + "🚀 Map run %s started, will check for immediate completion", + self.operation_identifier.name + or self.operation_identifier.operation_id, + ) + + # Signal to process() that checkpoint was created - to recheck status + # for immediate completion before proceeding. + return CheckResult.create_started() + + # Ready to suspend (checkpoint exists but not in a terminal or started state) + return CheckResult.create_is_ready_to_execute(checkpointed_result) + + def execute( + self, _checkpointed_result: CheckpointedResult + ) -> DistributedMapSummary: + """Execute map run operation by suspending to wait for async completion. + + The map run operation doesn't execute synchronously - it suspends and + the backend runs the map run asynchronously. + + Args: + checkpointed_result: The checkpoint data (unused, but required by interface) + + Returns: + Never returns - always suspends + + Raises: + Always suspends via suspend_with_optional_resume_delay + ExecutionError: If suspend doesn't raise (should never happen) + """ + msg: str = f"Map run {self.operation_identifier.operation_id} started, suspending for completion" + suspend_with_optional_resume_delay(msg) + # This line should never be reached since suspend_with_optional_resume_delay always raises + error_msg: str = "suspend_with_optional_resume_delay should have raised an exception, but did not." + raise ExecutionError(error_msg) from None diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/plugin.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/plugin.py index 5015faced..4800de358 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/plugin.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/plugin.py @@ -47,6 +47,7 @@ class OperationType(Enum): WAIT = "WAIT" CALLBACK = "CALLBACK" CHAINED_INVOKE = "CHAINED_INVOKE" + DISTRIBUTED_MAP = "DISTRIBUTED_MAP" def _to_invocation_status(status: ServiceInvocationStatus) -> InvocationStatus: @@ -78,6 +79,7 @@ def _extract_error(operation: Operation) -> ErrorObject | None: operation.callback_details, operation.chained_invoke_details, operation.context_details, + operation.distributed_map_details, ): if details and details.error is not None and details.error.to_dict(): return details.error diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/serdes.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/serdes.py index 7f12ac2e6..fbcbec3df 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/serdes.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/serdes.py @@ -17,6 +17,15 @@ Wire Formats: Plain JSON: 42, "hello", [1, 2, 3] Envelope: {"t": "", "v": } + +Context Requirement: +- A SerDesContext is built from the current invocation and never travels with + the payload +- ctx.distributed_map and ctx.invoke serialize and deserialize in different + invocations, so the two sides get different contexts +- A custom SerDes used with the operations above must write a payload it can + read back without the context it was given +- Every SerDes in this SDK already meets this requirement """ from __future__ import annotations diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/state.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/state.py index 0cb53471d..126dacf33 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/state.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/state.py @@ -235,6 +235,9 @@ def create_from_operation(cls, operation: Operation) -> CheckpointedResult: result = context_details.result if context_details else None error = context_details.error if context_details else None + # OperationType.DISTRIBUTED_MAP has no operation-level result/error. + # The operation itself carries the map run's outcome. + return cls( operation=operation, status=operation.status, result=result, error=error ) diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/types.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/types.py index f2e9e917e..c836da4b8 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/types.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/types.py @@ -81,6 +81,54 @@ class WaitForConditionCheckContext(OperationContext): attempt: int +@dataclass(frozen=True) +class DistributedMapItemContext(OperationContext): + """Context provided to distributed map per-item processor functions. + + The wrapper owns the Lambda event, so without this a function could not + reach the run it belongs to or the id of the item it was handed. + + Attributes: + distributed_map_run_arn: ARN of the map run this item belongs to. It is + the handle the distributed map APIs take, so a processor can read + or control its own run. + item_id: The service's id for this item. The wrapper reports this + item's outcome under the same id. + """ + + distributed_map_run_arn: str + item_id: str + + +@dataclass(frozen=True) +class DistributedMapBatchContext(OperationContext): + """Context provided to distributed map batch processor functions. + + Attributes: + distributed_map_run_arn: ARN of the map run this batch belongs to. + item_ids: The ids of the batch's items, in the same order as the items + themselves, so ``item_ids[i]`` is the id of ``items[i]``. A batch + processor reports one outcome for the whole batch and its return + value is discarded, so these identify items in logs rather than + feeding anything the service records. Reordering or filtering the + items breaks the pairing. + """ + + distributed_map_run_arn: str + item_ids: tuple[str, ...] + + +@dataclass(frozen=True) +class DistributedMapReaderContext(OperationContext): + """Context provided to distributed map reader functions. + + Attributes: + distributed_map_run_arn: ARN of the map run this page is read for. + """ + + distributed_map_run_arn: str + + class Callback(Protocol, Generic[C_co]): """Protocol for callback futures.""" diff --git a/packages/aws-durable-execution-sdk-python/tests/config_test.py b/packages/aws-durable-execution-sdk-python/tests/config_test.py index c2fbc78b2..b1cddba5d 100644 --- a/packages/aws-durable-execution-sdk-python/tests/config_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/config_test.py @@ -1,5 +1,6 @@ """Unit tests for config module.""" +import math from unittest.mock import Mock import pytest @@ -19,10 +20,26 @@ WaitForCallbackConfig, ) from aws_durable_execution_sdk_python.exceptions import ValidationError +from aws_durable_execution_sdk_python.lambda_service import ( + DistributedMapCompletionConfig as WireCompletionConfig, +) from aws_durable_execution_sdk_python.waits import ( WaitForConditionConfig, WaitForConditionDecision, ) +from aws_durable_execution_sdk_python.config import ( + DistributedMapCompletionConfig, + DistributedMapConfig, + DistributedMapCsvDelimiter, + DistributedMapDestination, + DistributedMapProcessor, + DistributedMapProcessorRetryConfig, + DistributedMapS3SourceType, + DistributedMapSource, + DistributedMapSourceFormat, + ReaderSource, + S3Source, +) def test_completion_config_defaults(): @@ -341,3 +358,349 @@ def test_configs_reject_a_sub_type_the_service_rejects( def test_sub_type_rejection_names_the_value() -> None: with pytest.raises(ValidationError, match=r"got: 'Order Charge'"): StepConfig(sub_type="Order Charge") + + +# ========================================================================== +# Distributed map config validation +# ========================================================================== + + +def test_expected_bucket_owner_must_be_12_digits(): + with pytest.raises(ValidationError, match="12-digit"): + DistributedMapSource.s3_json_lines( + "s3://b/k.jsonl", expected_bucket_owner="123" + ) + + +def test_csv_delimiter_invalid_string_rejected(): + with pytest.raises(ValidationError, match="delimiter must be one of"): + DistributedMapSource.s3_csv("s3://b/data.csv", delimiter="BAR") + + +def test_csv_headers_duplicates_rejected(): + with pytest.raises(ValidationError, match="duplicates"): + DistributedMapSource.s3_csv("s3://b/k.csv", headers=["a", "a"]) + + +def test_json_lines_requires_key(): + with pytest.raises(ValidationError, match="object key"): + DistributedMapSource.s3_json_lines("s3://bucket-only") + + +def test_timeout_non_positive_rejected(): + with pytest.raises(ValidationError, match="timeout must be positive"): + DistributedMapConfig(timeout=Duration.from_seconds(0)) + + +def test_empty_function_name_rejected(): + with pytest.raises(ValidationError, match="non-empty"): + DistributedMapProcessor.report_batch_outcome("") + + +def test_valid_function_references_accepted(): + for ref in ( + "my-func", + "my-func:PROD", + "123456789012:function:my-func", + "arn:aws:lambda:us-east-1:123456789012:function:my-func", + "arn:aws:lambda:us-east-1:123456789012:function:my-func:1", + ): + # Should not raise. + DistributedMapProcessor.report_batch_outcome(ref) + + +def test_completion_count_and_percentage_mutually_exclusive(): + with pytest.raises(ValidationError, match="mutually exclusive"): + DistributedMapCompletionConfig( + tolerated_failure_count=1, tolerated_failure_percentage=5 + ) + + +def test_completion_config_without_a_threshold_rejected(): + """Omitting the config means zero tolerated failures, so an empty one is an error.""" + with pytest.raises(ValidationError, match="must set tolerated_failure_count"): + DistributedMapCompletionConfig() + + +def test_completion_sample_size_requires_percentage(): + with pytest.raises(ValidationError, match="minimum_sample_size"): + DistributedMapCompletionConfig( + tolerated_failure_count=1, minimum_sample_size=10 + ) + + +def test_completion_negative_count_rejected(): + with pytest.raises(ValidationError, match="non-negative"): + DistributedMapCompletionConfig(tolerated_failure_count=-1) + + +def test_completion_percentage_out_of_range_rejected(): + with pytest.raises(ValidationError, match="between 0 and 100"): + DistributedMapCompletionConfig(tolerated_failure_percentage=150) + + +def test_completion_fractional_percentage_accepted(): + """The service's percentage is a number, so a fraction reaches the wire unchanged.""" + config = DistributedMapCompletionConfig(tolerated_failure_percentage=12.5) + assert config.tolerated_failure_percentage == 12.5 + wire = WireCompletionConfig.from_config(config) + assert wire.to_dict()["ToleratedFailurePercentage"] == 12.5 + + +@pytest.mark.parametrize( + "percentage", + [math.nan, math.inf, -math.inf], + ids=["nan", "inf", "-inf"], +) +def test_completion_non_finite_percentage_rejected(percentage): + """The range check rejects these, since every comparison against NaN is False.""" + with pytest.raises(ValidationError, match="between 0 and 100"): + DistributedMapCompletionConfig(tolerated_failure_percentage=percentage) + + +def test_completion_sample_size_below_one_rejected(): + with pytest.raises(ValidationError, match="at least 1"): + DistributedMapCompletionConfig( + tolerated_failure_percentage=5, minimum_sample_size=0 + ) + + +def test_completion_failure_count_factory(): + assert DistributedMapCompletionConfig.failure_count(3).tolerated_failure_count == 3 + + +def test_max_items_below_one_rejected(): + with pytest.raises(ValidationError, match="max_items must be at least 1"): + DistributedMapSource.s3_json_lines("s3://b/k.jsonl", max_items=0) + + +def test_csv_requires_object_key(): + with pytest.raises(ValidationError, match="csv requires an S3 object key"): + DistributedMapSource.s3_csv("s3://bucket") + + +def test_json_array_requires_key(): + with pytest.raises( + ValidationError, match="s3_json_array requires an S3 object key" + ): + DistributedMapSource.s3_json_array("s3://bucket-only") + + +@pytest.mark.parametrize("key", [None, ""]) +def test_s3_object_source_without_key_rejected(key): + with pytest.raises(ValidationError, match="an OBJECT source requires a key"): + S3Source( + source_type=DistributedMapS3SourceType.OBJECT, + bucket="b", + key=key, + fmt=DistributedMapSourceFormat.JSON_LINES, + ) + + +def test_s3_object_source_without_format_rejected(): + with pytest.raises(ValidationError, match="an OBJECT source requires a format"): + S3Source(source_type=DistributedMapS3SourceType.OBJECT, bucket="b", key="k") + + +@pytest.mark.parametrize( + ("source_type", "fmt"), + [ + ( + DistributedMapS3SourceType.LISTED_OBJECTS, + DistributedMapSourceFormat.JSON_LINES, + ), + (DistributedMapS3SourceType.LISTED_OBJECT_METADATA, None), + ], +) +def test_s3_listed_source_without_key_prefix_rejected(source_type, fmt): + with pytest.raises( + ValidationError, match=f"a {source_type.value} source requires a key prefix" + ): + S3Source(source_type=source_type, bucket="b", fmt=fmt) + + +def test_s3_listed_objects_source_without_format_rejected(): + with pytest.raises( + ValidationError, match="a LISTED_OBJECTS source requires a format" + ): + S3Source( + source_type=DistributedMapS3SourceType.LISTED_OBJECTS, + bucket="b", + key_prefix="p/", + ) + + +def test_s3_listed_object_metadata_source_with_format_rejected(): + with pytest.raises(ValidationError, match="takes no format"): + S3Source( + source_type=DistributedMapS3SourceType.LISTED_OBJECT_METADATA, + bucket="b", + key_prefix="p/", + fmt=DistributedMapSourceFormat.JSON_LINES, + ) + + +_OBJECT = DistributedMapS3SourceType.OBJECT +_LISTED = DistributedMapS3SourceType.LISTED_OBJECTS +_METADATA = DistributedMapS3SourceType.LISTED_OBJECT_METADATA +_FORMAT = DistributedMapSourceFormat +_COMMA = DistributedMapCsvDelimiter.COMMA + + +@pytest.mark.parametrize( + ("factory", "uri", "expected"), + [ + ( + DistributedMapSource.s3_json_lines, + "s3://b/k", + S3Source(_OBJECT, "b", key="k", fmt=_FORMAT.JSON_LINES), + ), + ( + DistributedMapSource.s3_json_array, + "s3://b/k", + S3Source(_OBJECT, "b", key="k", fmt=_FORMAT.JSON_ARRAY), + ), + ( + DistributedMapSource.s3_csv, + "s3://b/k", + S3Source(_OBJECT, "b", key="k", fmt=_FORMAT.CSV, delimiter=_COMMA), + ), + ( + DistributedMapSource.s3_objects, + "s3://b/p/", + S3Source(_METADATA, "b", key_prefix="p/"), + ), + ( + DistributedMapSource.s3_flattened_json_lines, + "s3://b/p/", + S3Source(_LISTED, "b", key_prefix="p/", fmt=_FORMAT.JSON_LINES), + ), + ( + DistributedMapSource.s3_flattened_json_array, + "s3://b/p/", + S3Source(_LISTED, "b", key_prefix="p/", fmt=_FORMAT.JSON_ARRAY), + ), + ( + DistributedMapSource.s3_flattened_csv, + "s3://b/p/", + S3Source(_LISTED, "b", key_prefix="p/", fmt=_FORMAT.CSV, delimiter=_COMMA), + ), + ], + ids=lambda value: getattr(value, "__name__", None), +) +def test_s3_factories_map_to_source_type_and_format(factory, uri, expected): + source = factory(uri) + assert source.s3 == expected + assert source.inline_items is None + assert source.reader is None + + +def test_source_without_any_kind_rejected(): + with pytest.raises(ValidationError, match="exactly one of"): + DistributedMapSource() + + +def test_source_with_two_kinds_rejected(): + with pytest.raises(ValidationError, match="exactly one of"): + DistributedMapSource( + inline_items=("a",), + reader=ReaderSource(function_name="r"), + ) + + +def test_success_destination_all_false_rejected(): + with pytest.raises(ValidationError, match="success destination must include"): + DistributedMapDestination.s3_successes( + "s3://out/ok", include_input=False, include_output=False + ) + + +def test_failure_destination_all_false_rejected(): + with pytest.raises(ValidationError, match="failure destination must include"): + DistributedMapDestination.s3_failures( + "s3://out/bad", include_input=False, include_error=False + ) + + +def test_invalid_s3_uri_rejected(): + with pytest.raises(ValidationError, match="Invalid S3 URI"): + DistributedMapSource.s3_json_lines("s3:///key.jsonl") + + +def test_non_s3_scheme_uri_rejected(): + with pytest.raises(ValidationError, match="must start with s3://"): + DistributedMapSource.s3_json_lines("http://foo/bar") + + +def test_csv_empty_headers_rejected(): + with pytest.raises(ValidationError, match="must be non-empty"): + DistributedMapSource.s3_csv("s3://b/f.csv", headers=[]) + + +def test_negative_retry_attempts_rejected(): + with pytest.raises(ValidationError, match="non-negative"): + DistributedMapProcessorRetryConfig(max_retry_attempts=-5) + + +@pytest.mark.parametrize("attempts", ["5", "forever", "UNLIMITED", 2.5, True, False]) +def test_retry_attempts_that_is_not_an_int_or_unlimited_rejected(attempts): + with pytest.raises(ValidationError, match="non-negative integer"): + DistributedMapProcessorRetryConfig(max_retry_attempts=attempts) + + +@pytest.mark.parametrize("value", [True, False]) +@pytest.mark.parametrize( + ("field", "build"), + [ + ("tolerated_failure_count", DistributedMapCompletionConfig.failure_count), + ( + "tolerated_failure_percentage", + DistributedMapCompletionConfig.failure_percentage, + ), + ( + "minimum_sample_size", + lambda v: DistributedMapCompletionConfig.failure_percentage( + 5, minimum_sample_size=v + ), + ), + ( + "batch_size", + lambda v: DistributedMapProcessor.report_batch_outcome("p", batch_size=v), + ), + ("max_items", lambda v: DistributedMapSource.inline(["a"], max_items=v)), + ], + ids=lambda value: value if isinstance(value, str) else None, +) +def test_distributed_map_numeric_fields_reject_bool(field, build, value): + with pytest.raises(ValidationError, match=f"{field} must be a number, not a bool"): + build(value) + + +def test_unlimited_retry_attempts_accepted() -> None: + # Annotated so mypy checks this body. The constant is the only typed call site + # that would catch UNLIMITED widening back to a plain str. + processor = DistributedMapProcessor.report_batch_outcome( + "p", + retry=DistributedMapProcessorRetryConfig( + max_retry_attempts=DistributedMapProcessorRetryConfig.UNLIMITED + ), + ) + assert processor.retry is not None + assert ( + processor.retry.max_retry_attempts + == DistributedMapProcessorRetryConfig.UNLIMITED + ) + + +def test_batch_size_below_one_rejected(): + with pytest.raises(ValidationError, match="batch_size must be at least 1"): + DistributedMapProcessor.report_batch_outcome("p", batch_size=0) + + +def test_durable_execution_name_prefix_empty_rejected(): + with pytest.raises( + ValidationError, match="durable_execution_name_prefix must be non-empty" + ): + DistributedMapProcessor.report_batch_outcome( + "p", durable_execution_name_prefix="" + ) diff --git a/packages/aws-durable-execution-sdk-python/tests/context_test.py b/packages/aws-durable-execution-sdk-python/tests/context_test.py index beb9df4ad..6b8ef2cb8 100644 --- a/packages/aws-durable-execution-sdk-python/tests/context_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/context_test.py @@ -4,8 +4,10 @@ import json import random import threading +from collections.abc import Sequence from concurrent.futures import ThreadPoolExecutor from itertools import islice +from typing import Any from unittest.mock import ANY, MagicMock, Mock, patch import pytest @@ -17,6 +19,8 @@ Duration, InvokeConfig, MapConfig, + DistributedMapConfig, + DistributedMapProcessor, ParallelBranch, ParallelConfig, StepConfig, @@ -1191,6 +1195,273 @@ def test_wait_with_time_less_than_one(mock_executor_class): # endregion wait +# region distributed_map +@pytest.mark.parametrize("max_concurrency", [0, -1]) +def test_map_run_rejects_max_concurrency_below_one(max_concurrency: int): + """The SDK validates only that max_concurrency is greater than zero.""" + context = create_test_context() + + with pytest.raises( + ValidationError, match="max_concurrency must be greater than zero" + ): + context.distributed_map( + ["a"], + DistributedMapProcessor.report_batch_outcome("test_processor"), + max_concurrency=max_concurrency, + ) + + +@pytest.mark.parametrize("max_concurrency", [True, False]) +def test_map_run_rejects_bool_max_concurrency(max_concurrency: bool): + context = create_test_context() + + with pytest.raises( + ValidationError, match="max_concurrency must be a number, not a bool" + ): + context.distributed_map( + ["a"], + DistributedMapProcessor.report_batch_outcome("test_processor"), + max_concurrency=max_concurrency, + ) + + +@pytest.mark.parametrize( + "source", + [{"a": 1}, {"a", "b"}, (c for c in "ab")], + ids=["dict", "set", "generator"], +) +def test_distributed_map_rejects_non_sequence_source(source): + """A source with no reliable order is rejected.""" + context = create_test_context() + + with pytest.raises(ValidationError, match="sequence of items"): + context.distributed_map( + source, + DistributedMapProcessor.report_batch_outcome("test_processor"), + max_concurrency=1, + ) + + +@pytest.mark.parametrize( + "source", + ["abc", b"ab", bytearray(b"ab"), range(3), ("a",), ["abc"]], + ids=["str", "bytes", "bytearray", "range", "tuple", "list"], +) +@patch("aws_durable_execution_sdk_python.context.DistributedMapOperationExecutor") +def test_distributed_map_accepts_any_sequence_source( + mock_executor_class: MagicMock, source: Sequence[Any] +) -> None: + context = create_test_context() + + context.distributed_map( + source, + DistributedMapProcessor.report_batch_outcome("test_processor"), + max_concurrency=1, + ) + + assert mock_executor_class.call_args[1]["source"] is source + + +@patch("aws_durable_execution_sdk_python.context.DistributedMapOperationExecutor") +def test_distributed_map_basic(mock_executor_class): + """distributed_map builds a DISTRIBUTED_MAP executor and returns its process() result.""" + mock_executor = MagicMock() + mock_executor.process.return_value = "map_summary" + mock_executor_class.return_value = mock_executor + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = ( + "arn:aws:durable:us-east-1:123456789012:execution/test" + ) + processor = DistributedMapProcessor.report_batch_outcome("test_processor") + + context = create_test_context(state=mock_state) + expected_operation_id = next(operation_id_sequence()) + + result = context.distributed_map(["a", "b"], processor, max_concurrency=4) + + assert result == "map_summary" + mock_executor_class.assert_called_once_with( + state=mock_state, + operation_identifier=OperationIdentifier( + expected_operation_id, + OperationSubType.DISTRIBUTED_MAP, + None, + None, + operation_type=OperationType.DISTRIBUTED_MAP, + ), + source=["a", "b"], + processor=processor, + max_concurrency=4, + config=ANY, + ) + mock_executor.process.assert_called_once() + + +@patch("aws_durable_execution_sdk_python.context.DistributedMapOperationExecutor") +def test_distributed_map_with_name_and_config(mock_executor_class): + """distributed_map forwards name into the identifier and passes the given config through.""" + mock_executor = MagicMock() + mock_executor.process.return_value = "configured_summary" + mock_executor_class.return_value = mock_executor + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = ( + "arn:aws:durable:us-east-1:123456789012:execution/test" + ) + processor = DistributedMapProcessor.report_batch_outcome("test_processor") + config = DistributedMapConfig() + + context = create_test_context(state=mock_state) + [context._create_step_id() for _ in range(5)] # Set counter to 5 # noqa: SLF001 + + result = context.distributed_map( + ["a"], processor, max_concurrency=2, name="named_map", config=config + ) + + seq = operation_id_sequence() + [next(seq) for _ in range(5)] + expected_id = next(seq) + + assert result == "configured_summary" + mock_executor_class.assert_called_once_with( + state=mock_state, + operation_identifier=OperationIdentifier( + expected_id, + OperationSubType.DISTRIBUTED_MAP, + None, + "named_map", + operation_type=OperationType.DISTRIBUTED_MAP, + ), + source=["a"], + processor=processor, + max_concurrency=2, + config=config, + ) + mock_executor.process.assert_called_once() + + +@patch("aws_durable_execution_sdk_python.context.DistributedMapOperationExecutor") +def test_distributed_map_with_parent_id(mock_executor_class): + """distributed_map propagates the parent_id into the operation identifier.""" + mock_executor = MagicMock() + mock_executor.process.return_value = "parent_summary" + mock_executor_class.return_value = mock_executor + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = ( + "arn:aws:durable:us-east-1:123456789012:execution/test" + ) + processor = DistributedMapProcessor.report_batch_outcome("test_processor") + + context = create_test_context(state=mock_state, parent_id="parent123") + [context._create_step_id() for _ in range(2)] # Set counter to 2 # noqa: SLF001 + + context.distributed_map(["a"], processor, max_concurrency=1) + + seq = operation_id_sequence("parent123") + [next(seq) for _ in range(2)] + expected_id = next(seq) + + mock_executor_class.assert_called_once_with( + state=mock_state, + operation_identifier=OperationIdentifier( + expected_id, + OperationSubType.DISTRIBUTED_MAP, + "parent123", + None, + operation_type=OperationType.DISTRIBUTED_MAP, + ), + source=["a"], + processor=processor, + max_concurrency=1, + config=ANY, + ) + mock_executor.process.assert_called_once() + + +@patch("aws_durable_execution_sdk_python.context.DistributedMapOperationExecutor") +def test_distributed_map_increments_counter(mock_executor_class): + """distributed_map increments the step counter once per call.""" + mock_executor = MagicMock() + mock_executor.process.return_value = "result" + mock_executor_class.return_value = mock_executor + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = ( + "arn:aws:durable:us-east-1:123456789012:execution/test" + ) + processor = DistributedMapProcessor.report_batch_outcome("test_processor") + + context = create_test_context(state=mock_state) + [context._create_step_id() for _ in range(10)] # Set counter to 10 # noqa: SLF001 + + context.distributed_map(["a"], processor, max_concurrency=1) + context.distributed_map(["b"], processor, max_concurrency=1) + + seq = operation_id_sequence() + [next(seq) for _ in range(10)] + expected_id1 = next(seq) + expected_id2 = next(seq) + + assert context._step_counter.get_current() == 12 # noqa: SLF001 + assert mock_executor_class.call_args_list[0][1][ + "operation_identifier" + ] == OperationIdentifier( + expected_id1, + OperationSubType.DISTRIBUTED_MAP, + None, + None, + operation_type=OperationType.DISTRIBUTED_MAP, + ) + assert mock_executor_class.call_args_list[1][1][ + "operation_identifier" + ] == OperationIdentifier( + expected_id2, + OperationSubType.DISTRIBUTED_MAP, + None, + None, + operation_type=OperationType.DISTRIBUTED_MAP, + ) + + +@patch("aws_durable_execution_sdk_python.context.DistributedMapOperationExecutor") +def test_distributed_map_defaults_config_when_none(mock_executor_class): + """distributed_map builds a default DistributedMapConfig when none is given.""" + mock_executor = MagicMock() + mock_executor.process.return_value = "summary" + mock_executor_class.return_value = mock_executor + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = ( + "arn:aws:durable:us-east-1:123456789012:execution/test" + ) + processor = DistributedMapProcessor.report_batch_outcome("test_processor") + + context = create_test_context(state=mock_state) + context.distributed_map(["a"], processor, max_concurrency=1) + + passed_config = mock_executor_class.call_args[1]["config"] + assert isinstance(passed_config, DistributedMapConfig) + + +@patch("aws_durable_execution_sdk_python.context.DistributedMapOperationExecutor") +def test_distributed_map_returns_process_result(mock_executor_class): + """distributed_map returns whatever executor.process() returns (summary or result).""" + mock_executor = MagicMock() + sentinel = object() + mock_executor.process.return_value = sentinel + mock_executor_class.return_value = mock_executor + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = ( + "arn:aws:durable:us-east-1:123456789012:execution/test" + ) + processor = DistributedMapProcessor.report_batch_outcome("test_processor") + + context = create_test_context(state=mock_state) + result = context.distributed_map(["a"], processor, max_concurrency=1) + + assert result is sentinel + + +# endregion distributed_map + + # region run_in_child_context @patch("aws_durable_execution_sdk_python.context.child_handler") def test_run_in_child_context_basic(mock_handler): diff --git a/packages/aws-durable-execution-sdk-python/tests/dmap/helpers_test.py b/packages/aws-durable-execution-sdk-python/tests/dmap/helpers_test.py new file mode 100644 index 000000000..b40e2a6e5 --- /dev/null +++ b/packages/aws-durable-execution-sdk-python/tests/dmap/helpers_test.py @@ -0,0 +1,1086 @@ +"""Unit tests for the distributed map authoring helpers.""" + +from __future__ import annotations + +import json +import logging +import threading +import time +from types import SimpleNamespace +from typing import Any + +import pytest + +from aws_durable_execution_sdk_python import ( + DistributedMapBatchContext, + DistributedMapItemContext, + DistributedMapReaderContext, +) +from aws_durable_execution_sdk_python.config import ( + BatchItemStatus, + CompletionConfig, + MapConfig, + NestingType, +) +from aws_durable_execution_sdk_python.context import DurableContext +from aws_durable_execution_sdk_python.dmap.helpers import ( + ItemFailure, + ReaderPage, + process_distributed_map_batch, + process_distributed_map_items, + read_distributed_map_page, +) +from aws_durable_execution_sdk_python.exceptions import ( + SerDesError, + StepError, + ValidationError, +) +from aws_durable_execution_sdk_python.execution import ( + InvocationStatus, + durable_execution, +) +from aws_durable_execution_sdk_python.filesystem_serdes import FileSystemSerDes +from aws_durable_execution_sdk_python.lambda_service import ErrorObject +from aws_durable_execution_sdk_python.logger import Logger +from aws_durable_execution_sdk_python.serdes import SerDes, SerDesContext +from aws_durable_execution_sdk_python_testing.runner import DurableFunctionTestRunner + +_RUN_ARN = ( + "arn:aws:lambda:us-east-1:123456789012:function:fn:$LATEST" + "/durable-execution/exec1/invoke1/distributed-map-run/abc" +) + + +class _PrefixSerDes(SerDes[Any]): + """A serdes whose prefix shows which of a helper's serdes options ran.""" + + def __init__(self, prefix: str) -> None: + self.prefix = prefix + + def serialize(self, value: Any, _serdes_context: SerDesContext) -> str: + return self.prefix + json.dumps(value) + + def deserialize(self, data: str, _serdes_context: SerDesContext) -> Any: + return json.loads(data.removeprefix(self.prefix)) + + +def _processor_event(records: list[dict[str, Any]]) -> dict[str, Any]: + return {"distributedMapRunArn": _RUN_ARN, "records": records} + + +def _reader_event( + state: str | None = None, max_items_per_page: int = 10 +) -> dict[str, Any]: + return { + "distributedMapRunArn": _RUN_ARN, + "state": state, + "maxItemsPerPage": max_items_per_page, + } + + +# Which of the two process_distributed_map_items forms a call selects, and the +# rejection of a call that matches neither. +# ============================================================================ + + +class _RecordingMapContext: + """A stand-in DurableContext whose map records its call and runs no item.""" + + def __init__(self) -> None: + self.configs: list[MapConfig] = [] + self.inputs: list[list[Any]] = [] + + def map(self, inputs: list[Any], _func: Any, config: MapConfig) -> Any: + self.inputs.append(inputs) + self.configs.append(config) + return SimpleNamespace(all=[]) + + +def test_process_items_selects_the_non_durable_form_for_a_callable_second_argument(): + seen: list[Any] = [] + response = process_distributed_map_items( + _processor_event([{"itemId": "0", "body": "1"}]), + lambda item, _ctx: seen.append(item), + ) + assert seen == [1] + assert response["batchItemResults"] == [{"itemIdentifier": "0"}] + + +def test_process_items_selects_the_durable_form_for_a_non_callable_second_argument(): + context = _RecordingMapContext() + response = process_distributed_map_items( + context, + _processor_event([{"itemId": "0", "body": "1"}]), + lambda _context, item, _ctx: item, + ) + assert context.inputs == [["1"]] + assert response == {"batchItemFailures": [], "batchItemResults": []} + + +@pytest.mark.parametrize( + "args", + [(), ({},), ({}, {}, None, None)], + ids=["none", "event-only", "four-arguments"], +) +def test_process_items_rejects_a_call_matching_neither_form(args): + with pytest.raises( + ValidationError, match=r"\(event, func\).*\(context, event, func\)" + ): + process_distributed_map_items(*args) + + +def test_process_items_rejects_func_passed_as_a_keyword(): + with pytest.raises( + ValidationError, match=r"\(event, func\).*\(context, event, func\)" + ): + process_distributed_map_items( # type: ignore[call-overload] + _processor_event([]), func=lambda item, _ctx: item + ) + + +def test_process_items_non_durable_form_rejects_nesting_type(): + with pytest.raises(ValidationError, match="nesting_type"): + process_distributed_map_items( # type: ignore[call-overload] + _processor_event([]), + lambda item, _ctx: item, + nesting_type=NestingType.NESTED, + ) + + +@pytest.mark.parametrize("durable", [False, True], ids=["non-durable", "durable"]) +def test_process_items_rejects_an_unknown_keyword(durable): + args: tuple[Any, ...] = ( + (_RecordingMapContext(), _processor_event([]), lambda c, i, x: i) + if durable + else (_processor_event([]), lambda i, x: i) + ) + with pytest.raises(ValidationError, match="concurrenc"): + process_distributed_map_items(*args, concurrenc=5) # type: ignore[call-overload] + + +def test_process_items_durable_form_defaults_to_flat_nesting(): + context = _RecordingMapContext() + process_distributed_map_items( + context, + _processor_event([{"itemId": "0", "body": "1"}]), + lambda _context, item, _ctx: item, + ) + assert context.configs[0].nesting_type is NestingType.FLAT + + +def test_process_items_durable_form_passes_nesting_nested_when_asked(): + context = _RecordingMapContext() + process_distributed_map_items( + context, + _processor_event([{"itemId": "0", "body": "1"}]), + lambda _context, item, _ctx: item, + nesting_type=NestingType.NESTED, + ) + assert context.configs[0].nesting_type is NestingType.NESTED + + +def test_process_items_durable_form_passes_concurrency_as_max_concurrency(): + context = _RecordingMapContext() + process_distributed_map_items( + context, + _processor_event([{"itemId": "0", "body": "1"}]), + lambda _context, item, _ctx: item, + concurrency=3, + ) + assert context.configs[0].max_concurrency == 3 + + +def test_process_items_durable_form_passes_completion_config_all_completed(): + context = _RecordingMapContext() + process_distributed_map_items( + context, + _processor_event([{"itemId": "0", "body": "1"}]), + lambda _context, item, _ctx: item, + ) + assert context.configs[0].completion_config == CompletionConfig.all_completed() + + +def test_process_items_rejects_concurrency_below_one_when_called(): + """The non-durable form raises when it is called, before any item runs.""" + with pytest.raises(ValidationError, match="concurrency must be at least 1"): + process_distributed_map_items( + _processor_event([]), lambda x, _ctx: x, concurrency=0 + ) + with pytest.raises(ValidationError, match="concurrency must be at least 1"): + process_distributed_map_items( + _processor_event([]), lambda x, _ctx: x, concurrency=-1 + ) + + +def test_process_items_durable_form_rejects_concurrency_below_one_when_called(): + """The durable form raises when it is called, before context.map runs.""" + context = _RecordingMapContext() + with pytest.raises(ValidationError, match="concurrency must be at least 1"): + process_distributed_map_items( + context, + _processor_event([]), + lambda _context, item, _ctx: item, + concurrency=0, + ) + with pytest.raises(ValidationError, match="concurrency must be at least 1"): + process_distributed_map_items( + context, + _processor_event([]), + lambda _context, item, _ctx: item, + concurrency=-1, + ) + assert context.configs == [] + + +def test_process_items_runs_items_one_at_a_time_by_default(): + lock = threading.Lock() + in_flight = 0 + peak = 0 + + def process(x, _ctx): + nonlocal in_flight, peak + with lock: + in_flight += 1 + peak = max(peak, in_flight) + # Hold the worker so that a wider pool would overlap this item with the + # next one, which is what makes the peak below meaningful. + time.sleep(0.02) + with lock: + in_flight -= 1 + return x + + process_distributed_map_items( + _processor_event([{"itemId": str(i), "body": "1"} for i in range(4)]), + process, + ) + assert peak == 1 + + +def test_process_items_honors_requested_concurrency(): + # Each item blocks until all four have arrived, so the batch only finishes + # if the pool really runs four items at once. At a smaller pool size the + # first item waits out the timeout and every item fails. + barrier = threading.Barrier(4, timeout=5) + + def process(x, _ctx): + barrier.wait() + return x + + resp = process_distributed_map_items( + _processor_event([{"itemId": str(i), "body": str(i)} for i in range(4)]), + process, + concurrency=4, + ) + assert resp["batchItemFailures"] == [] + # The four items are released together, so completion order is arbitrary + # while the reported results stay in item order. + assert resp["batchItemResults"] == [ + {"itemIdentifier": "0", "output": "0"}, + {"itemIdentifier": "1", "output": "1"}, + {"itemIdentifier": "2", "output": "2"}, + {"itemIdentifier": "3", "output": "3"}, + ] + + +def test_process_items_reports_results_in_order(): + resp = process_distributed_map_items( + _processor_event([{"itemId": "0", "body": "2"}, {"itemId": "1", "body": "3"}]), + lambda x, _ctx: x * 2, + ) + assert resp["batchItemResults"] == [ + {"itemIdentifier": "0", "output": "4"}, + {"itemIdentifier": "1", "output": "6"}, + ] + assert resp["batchItemFailures"] == [] + + +def test_process_items_captures_failures(): + def process(x, _ctx): + if x == "bad": + msg = "boom" + raise ValueError(msg) + return x + + resp = process_distributed_map_items( + _processor_event( + [ + {"itemId": "0", "body": '"ok"'}, + {"itemId": "1", "body": '"bad"'}, + ] + ), + process, + ) + assert resp["batchItemResults"] == [{"itemIdentifier": "0", "output": '"ok"'}] + assert resp["batchItemFailures"] == [ + { + "itemIdentifier": "1", + "error": {"errorType": "ValueError", "errorMessage": "boom"}, + } + ] + + +def test_process_items_reports_every_member_of_a_rich_error(): + """An error carrying data and a stack trace reaches the service with all four members.""" + + def process(_x: Any, _ctx: Any) -> Any: + raise SerDesError( + message="bad payload", + error_type="ignored, SerDesError pins its own type", + data="payload", + stack_trace=["frame one", "frame two"], + ) + + resp = process_distributed_map_items( + _processor_event([{"itemId": "0", "body": "1"}]), process + ) + + error = resp["batchItemFailures"][0]["error"] + assert error["errorMessage"] == "bad payload" + assert error["errorData"] == "payload" + assert error["stackTrace"] == ["frame one", "frame two"] + + +def test_process_items_omits_error_members_the_exception_lacks(): + """A plain exception carries no data or trace, so neither key is written.""" + + def process(_x: Any, _ctx: Any) -> Any: + msg = "boom" + raise ValueError(msg) + + resp = process_distributed_map_items( + _processor_event([{"itemId": "0", "body": "1"}]), process + ) + + assert resp["batchItemFailures"][0]["error"] == { + "errorType": "ValueError", + "errorMessage": "boom", + } + + +def test_item_failure_wire_round_trip_keeps_every_member(): + failure = ItemFailure( + item_identifier="7", + error=ErrorObject( + message="boom", type="E", data="payload", stack_trace=["frame"] + ), + ) + parsed = ItemFailure.from_dict(failure.to_dict()) + assert parsed == failure + + +def test_process_items_omits_the_output_of_a_function_returning_none(): + resp = process_distributed_map_items( + _processor_event([{"itemId": "0", "body": "1"}]), lambda _x, _ctx: None + ) + assert resp == { + "batchItemFailures": [], + "batchItemResults": [{"itemIdentifier": "0"}], + } + + +def test_process_items_fails_only_the_item_whose_output_cannot_be_serialized(): + """A result serdes failure is that item's failure, not the batch's.""" + + class _RejectsBad(SerDes[Any]): + def serialize(self, value: Any, _serdes_context: SerDesContext) -> str: + if value == "bad": + msg = "cannot serialize" + raise TypeError(msg) + return json.dumps(value) + + def deserialize(self, data: str, _serdes_context: SerDesContext) -> Any: + return json.loads(data) + + resp = process_distributed_map_items( + _processor_event( + [ + {"itemId": "0", "body": '"ok"'}, + {"itemId": "1", "body": '"bad"'}, + ] + ), + lambda x, _ctx: x, + result_serdes=_RejectsBad(), + ) + assert resp["batchItemResults"] == [{"itemIdentifier": "0", "output": '"ok"'}] + assert resp["batchItemFailures"] == [ + { + "itemIdentifier": "1", + "error": {"errorType": "TypeError", "errorMessage": "cannot serialize"}, + } + ] + + +def test_process_batch_succeeds_and_propagates_error(): + seen: list = [] + + def process(items, _ctx): + seen.extend(items) + return "ignored" + + # A batch processor reports no output, so the return value is not forwarded. + assert ( + process_distributed_map_batch( + _processor_event( + [{"itemId": "0", "body": "1"}, {"itemId": "1", "body": "2"}] + ), + process, + ) + is None + ) + assert seen == [1, 2] + + def boom(_items, _ctx): + msg = "batch failed" + raise RuntimeError(msg) + + with pytest.raises(RuntimeError, match="batch failed"): + process_distributed_map_batch( + _processor_event([{"itemId": "0", "body": "1"}]), boom + ) + + +def test_reader_returns_items_and_next_state_then_exhausts(): + def read(state, max_items_per_page, _ctx): + if state is None: + return ReaderPage(items=[1, 2][:max_items_per_page], next_state={"page": 1}) + return ReaderPage(items=[3]) + + first = read_distributed_map_page(_reader_event(), read) + assert first["items"] == ["1", "2"] + assert first["nextState"] == '{"page": 1}' + + second = read_distributed_map_page(_reader_event(state='{"page": 1}'), read) + assert second["items"] == ["3"] + assert "nextState" not in second + + +def test_reader_serializes_items_with_the_item_serdes(): + """An item serdes encodes each item, so the processor's can decode it.""" + + class _UpperSerDes(SerDes[Any]): + def serialize(self, value: Any, _serdes_context: SerDesContext) -> str: + return json.dumps(value.upper()) + + def deserialize(self, data: str, _serdes_context: SerDesContext) -> Any: + return json.loads(data).lower() + + serdes = _UpperSerDes() + page = read_distributed_map_page( + _reader_event(), + lambda _s, _max, _ctx: ReaderPage(items=["a", "b"]), + item_serdes=serdes, + ) + assert page["items"] == ['"A"', '"B"'] + + seen = [] + process_distributed_map_batch( + _processor_event( + [{"itemId": str(i), "body": body} for i, body in enumerate(page["items"])] + ), + lambda items, _ctx: seen.extend(items), + item_serdes=serdes, + ) + assert seen == ["a", "b"] + + +def test_reader_item_serdes_is_separate_from_the_state_serdes(): + """Items use the item serdes and next_state uses the state serdes.""" + page = read_distributed_map_page( + _reader_event(state='state:"in"'), + lambda state, _max, _ctx: ReaderPage(items=[state], next_state="s"), + item_serdes=_PrefixSerDes("item:"), + state_serdes=_PrefixSerDes("state:"), + ) + assert page["items"] == ['item:"in"'] + assert page["nextState"] == 'state:"s"' + + +def test_reader_receives_the_page_bound(): + """The page bound reaches func, so a reader can page to it.""" + page = read_distributed_map_page( + _reader_event(max_items_per_page=3), + lambda _s, max_items_per_page, _ctx: ReaderPage( + items=list(range(max_items_per_page)) + ), + ) + assert page["items"] == ["0", "1", "2"] + + +def test_reader_rejects_page_over_max_items_per_page(): + with pytest.raises(ValidationError, match="exceeding maxItemsPerPage"): + read_distributed_map_page( + _reader_event(max_items_per_page=2), + lambda _s, _max, _ctx: ReaderPage(items=[1, 2, 3]), + ) + + +@pytest.mark.parametrize("items", [[1], []], ids=["with_items", "empty_page"]) +def test_reader_rejects_an_unchanged_next_state(items): + """The service fails the run over this, so the helper rejects it at the source.""" + with pytest.raises(ValidationError, match="must differ from the state"): + read_distributed_map_page( + _reader_event(state='{"page": 1}'), + lambda s, _max, _ctx: ReaderPage(items=items, next_state=s), + ) + + +def test_reader_allows_an_advanced_next_state(): + page = read_distributed_map_page( + _reader_event(state='{"page": 1}'), + lambda _s, _max, _ctx: ReaderPage(items=[], next_state={"page": 2}), + ) + assert page == {"items": [], "nextState": '{"page": 2}'} + + +def test_process_items_rejects_non_processor_envelope(): + with pytest.raises(ValidationError, match="processor envelope"): + process_distributed_map_items({}, lambda x, _ctx: x) + + +@pytest.mark.parametrize( + "record", + [ + {"body": "1"}, + {"itemId": None, "body": "1"}, + {"itemId": "", "body": "1"}, + {"itemId": 7, "body": "1"}, + ], + ids=["absent", "null", "empty", "not-a-string"], +) +def test_process_items_rejects_a_record_with_no_item_id(record): + """The helper reports each outcome against its item id, so it must have one.""" + with pytest.raises(ValidationError, match="string 'itemId'"): + process_distributed_map_items(_processor_event([record]), lambda x, _ctx: x) + + +def test_process_batch_rejects_a_record_with_no_item_id(): + """The batch helper validates its invocation input the same way.""" + with pytest.raises(ValidationError, match="string 'itemId'"): + process_distributed_map_batch( + _processor_event([{"body": "1"}]), lambda items, _ctx: items + ) + + +def test_process_items_rejects_a_batch_when_only_one_record_lacks_an_item_id(): + """One unusable record fails the invocation rather than the batch running partly.""" + calls = [] + with pytest.raises(ValidationError, match="string 'itemId'"): + process_distributed_map_items( + _processor_event([{"itemId": "0", "body": "1"}, {"body": "2"}]), + lambda item, _ctx: calls.append(item), + ) + assert calls == [] + + +def test_reader_rejects_non_reader_envelope(): + with pytest.raises(ValidationError, match="reader envelope"): + read_distributed_map_page( + {"distributedMapRunArn": _RUN_ARN, "state": None}, + lambda _state, _max, _ctx: ReaderPage(items=[]), + ) + + +# Each value a helper serializes gets its own serdes context, so a serdes that +# stores values under their context, such as FileSystemSerDes, keeps them all. +# ============================================================================ + + +class _RecordingSerDes(SerDes[Any]): + """A JSON serdes that records every context it is called with.""" + + def __init__(self) -> None: + self.contexts: list[SerDesContext] = [] + self._lock = threading.Lock() + + def serialize(self, value: Any, serdes_context: SerDesContext) -> str: + with self._lock: + self.contexts.append(serdes_context) + return json.dumps(value) + + def deserialize(self, data: str, serdes_context: SerDesContext) -> Any: + with self._lock: + self.contexts.append(serdes_context) + return json.loads(data) + + +def _records(count: int) -> list[dict[str, Any]]: + return [{"itemId": f"item-{i}", "body": json.dumps(i)} for i in range(count)] + + +def _read(fs: FileSystemSerDes, data: str) -> Any: + return fs.deserialize(data, SerDesContext()) + + +def test_process_items_stores_each_output_under_its_own_key(tmp_path): + fs = FileSystemSerDes(str(tmp_path)) + resp = process_distributed_map_items( + _processor_event(_records(3)), lambda i, _ctx: f"out-{i}", result_serdes=fs + ) + outputs = [r["output"] for r in resp["batchItemResults"]] + assert len(set(outputs)) == 3 + assert [_read(fs, o) for o in outputs] == ["out-0", "out-1", "out-2"] + + +def test_process_items_stores_concurrent_outputs_under_their_own_keys(tmp_path): + fs = FileSystemSerDes(str(tmp_path)) + resp = process_distributed_map_items( + _processor_event(_records(8)), + lambda i, _ctx: f"out-{i}", + result_serdes=fs, + concurrency=4, + ) + outputs = [r["output"] for r in resp["batchItemResults"]] + assert [_read(fs, o) for o in outputs] == [f"out-{i}" for i in range(8)] + + +def test_process_items_keeps_the_outputs_of_another_run(tmp_path): + fs = FileSystemSerDes(str(tmp_path)) + other_run_arn = _RUN_ARN.replace("/abc", "/def") + first = process_distributed_map_items( + _processor_event(_records(1)), lambda _i, _ctx: "first", result_serdes=fs + ) + process_distributed_map_items( + {"distributedMapRunArn": other_run_arn, "records": _records(1)}, + lambda _i, _ctx: "second", + result_serdes=fs, + ) + assert _read(fs, first["batchItemResults"][0]["output"]) == "first" + + +def test_process_items_reuses_the_key_when_an_item_is_retried(tmp_path): + fs = FileSystemSerDes(str(tmp_path)) + event = _processor_event(_records(2)) + + def call() -> dict[str, Any]: + return process_distributed_map_items( + event, lambda i, _ctx: f"out-{i}", result_serdes=fs + ) + + first = call() + assert call() == first + outputs = [r["output"] for r in first["batchItemResults"]] + assert [_read(fs, o) for o in outputs] == ["out-0", "out-1"] + + +@pytest.mark.parametrize("batch", [False, True], ids=["item", "batch"]) +def test_processor_reads_and_writes_each_value_under_its_own_context(batch): + serdes = _RecordingSerDes() + event = _processor_event(_records(2)) + if batch: + process_distributed_map_batch( + event, lambda _items, _ctx: None, item_serdes=serdes + ) + else: + process_distributed_map_items( + event, lambda i, _ctx: i, item_serdes=serdes, result_serdes=serdes + ) + keys = {(c.durable_execution_arn, c.operation_id) for c in serdes.contexts} + assert len(keys) == len(serdes.contexts) == (2 if batch else 4) + assert {arn for arn, _ in keys} == {_RUN_ARN.split("/distributed-map-run/")[0]} + + +def test_reader_stores_items_and_next_state_under_their_own_keys(tmp_path): + fs = FileSystemSerDes(str(tmp_path)) + + def read(state, _max, _ctx): + page = 0 if state is None else state["page"] + return ReaderPage( + items=[f"r{page}-0", f"r{page}-1"], next_state={"page": page + 1} + ) + + first = read_distributed_map_page( + {"distributedMapRunArn": _RUN_ARN, "maxItemsPerPage": 10}, + read, + item_serdes=fs, + state_serdes=fs, + ) + assert len({*first["items"], first["nextState"]}) == 3 + assert [_read(fs, i) for i in first["items"]] == ["r0-0", "r0-1"] + assert _read(fs, first["nextState"]) == {"page": 1} + + second = read_distributed_map_page( + _reader_event(state=first["nextState"]), + read, + item_serdes=fs, + state_serdes=fs, + ) + assert [_read(fs, i) for i in second["items"]] == ["r1-0", "r1-1"] + assert _read(fs, second["nextState"]) == {"page": 2} + # Page 2 leaves page 1's items and state in place. + assert [_read(fs, i) for i in first["items"]] == ["r0-0", "r0-1"] + assert _read(fs, first["nextState"]) == {"page": 1} + + +def test_reader_reads_and_writes_each_value_under_its_own_context(): + serdes = _RecordingSerDes() + read_distributed_map_page( + _reader_event(state='"in"'), + lambda _s, _max, _ctx: ReaderPage(items=[1, 2], next_state="next"), + item_serdes=serdes, + state_serdes=serdes, + ) + keys = {(c.durable_execution_arn, c.operation_id) for c in serdes.contexts} + assert len(keys) == len(serdes.contexts) == 4 + + +def test_reader_state_is_read_under_a_different_context_than_it_was_written(): + """next_state is written as one call's output and read as the next call's input. + + So the write context and the read context always differ. Pins the context + requirement documented in the serdes module. + """ + serdes = _RecordingSerDes() + + # The next state has to advance, or the helper rejects it for repeating + # the position it was called with. + def read(state, _max, _ctx): + return ReaderPage(items=[], next_state="page-2" if state else "page-1") + + first = read_distributed_map_page( + {"distributedMapRunArn": _RUN_ARN, "maxItemsPerPage": 10}, + read, + state_serdes=serdes, + ) + # No input state on the first call, so the only context is the write. + assert len(serdes.contexts) == 1 + wrote = serdes.contexts[0] + + serdes.contexts.clear() + read_distributed_map_page( + _reader_event(state=first["nextState"]), read, state_serdes=serdes + ) + # The input state is deserialized before anything else is written. + read_context = serdes.contexts[0] + + assert read_context.durable_execution_arn == wrote.durable_execution_arn + assert read_context.operation_id != wrote.operation_id + + +@pytest.mark.parametrize( + "run_arn", + [None, 7, "not-an-arn"], + ids=["absent", "not-a-string", "malformed"], +) +@pytest.mark.parametrize( + "envelope", + [ + {"records": [{"itemId": "0", "body": "1"}]}, + {"state": None, "maxItemsPerPage": 10}, + ], + ids=["processor", "reader"], +) +def test_helpers_reject_an_envelope_without_a_valid_run_arn(run_arn, envelope): + event = dict(envelope) + if run_arn is not None: + event["distributedMapRunArn"] = run_arn + if "records" in envelope: + calls = [ + lambda: process_distributed_map_items(event, lambda x, _ctx: x), + lambda: process_distributed_map_batch(event, lambda _items, _ctx: None), + ] + else: + calls = [ + lambda: read_distributed_map_page( + event, lambda _s, _max, _ctx: ReaderPage() + ) + ] + for call in calls: + with pytest.raises(ValidationError, match="'distributedMapRunArn'"): + call() + + +# Each helper passes the customer function a context as its last argument. It +# carries the run ARN, and the item id or ids for a processor. +# ============================================================================ + +# The execution name and the invocation id are both "distributed-map-run", so +# splitting on the first separator instead of the last gives the wrong run id. +_RUN_ARN_WITH_SEPARATOR_NAMES = ( + "arn:aws:lambda:us-east-1:123456789012:function:fn:$LATEST" + "/durable-execution/distributed-map-run/distributed-map-run" + "/distributed-map-run/abc" +) + +_ITEM_IDS = ["id-a", "id-b", "id-c"] + + +def _records_named_by_id(item_ids: list[str]) -> list[dict[str, Any]]: + """Records whose body is the item's own id, so an item shows which id it has.""" + return [{"itemId": i, "body": json.dumps(i)} for i in item_ids] + + +def test_process_items_passes_each_item_its_run_arn_and_id() -> None: + seen: dict[str, DistributedMapItemContext] = {} + + def process(item: str, ctx: DistributedMapItemContext) -> None: + seen[item] = ctx + + process_distributed_map_items( + _processor_event(_records_named_by_id(_ITEM_IDS)), process + ) + assert sorted(seen) == _ITEM_IDS + for item, ctx in seen.items(): + assert ctx.item_id == item + assert ctx.distributed_map_run_arn == _RUN_ARN + + +def test_process_items_logger_stamps_the_run_arn_and_item_id( + caplog: pytest.LogCaptureFixture, +) -> None: + """The non-durable form has no durable logger, so it logs through the module logger.""" + + def process(_item: Any, ctx: DistributedMapItemContext) -> None: + ctx.logger.info("processing") + + with caplog.at_level(logging.INFO): + process_distributed_map_items( + _processor_event(_records_named_by_id(["id-a"])), process + ) + (record,) = [r for r in caplog.records if r.getMessage() == "processing"] + assert record.name == "aws_durable_execution_sdk_python.dmap.helpers" + assert record.__dict__["distributedMapRunArn"] == _RUN_ARN + assert record.__dict__["itemId"] == "id-a" + + +def test_process_batch_item_ids_are_index_aligned_with_the_items() -> None: + seen: list[tuple[list[str], DistributedMapBatchContext]] = [] + + def process(items: list[str], ctx: DistributedMapBatchContext) -> None: + seen.append((items, ctx)) + + process_distributed_map_batch( + _processor_event(_records_named_by_id(_ITEM_IDS)), process + ) + ((items, ctx),) = seen + assert items == _ITEM_IDS + assert ctx.item_ids == tuple(_ITEM_IDS) + assert ctx.distributed_map_run_arn == _RUN_ARN + + +def test_reader_passes_its_run_arn() -> None: + seen: list[DistributedMapReaderContext] = [] + + def read(_state: Any, _max: int, ctx: DistributedMapReaderContext) -> ReaderPage: + seen.append(ctx) + return ReaderPage() + + read_distributed_map_page(_reader_event(), read) + ((ctx,),) = [seen] + assert ctx.distributed_map_run_arn == _RUN_ARN + + +@pytest.mark.parametrize( + "run_arn", + [_RUN_ARN, _RUN_ARN_WITH_SEPARATOR_NAMES], + ids=["plain", "separator-in-names"], +) +def test_every_helper_passes_the_envelope_run_arn_unchanged(run_arn: str) -> None: + """The helpers parse the run ARN and rebuild it, which must restore the input.""" + seen: list[str] = [] + processor_event = { + "distributedMapRunArn": run_arn, + "records": _records_named_by_id(["id-a"]), + } + process_distributed_map_items( + processor_event, lambda _item, ctx: seen.append(ctx.distributed_map_run_arn) + ) + process_distributed_map_batch( + processor_event, lambda _items, ctx: seen.append(ctx.distributed_map_run_arn) + ) + + def read(_state: Any, _max: int, ctx: DistributedMapReaderContext) -> ReaderPage: + seen.append(ctx.distributed_map_run_arn) + return ReaderPage() + + read_distributed_map_page( + {"distributedMapRunArn": run_arn, "state": None, "maxItemsPerPage": 10}, read + ) + assert seen == [run_arn, run_arn, run_arn] + + +def _run_durable(handler: Any, item_ids: list[str]) -> None: + """Run a durable handler on one processor batch and require it to succeed.""" + event = { + "distributedMapRunArn": _RUN_ARN_WITH_SEPARATOR_NAMES, + "records": _records_named_by_id(item_ids), + } + with DurableFunctionTestRunner(handler=handler) as runner: + result = runner.run(input=json.dumps(event), execution_timeout=15) + assert result.status is InvocationStatus.SUCCEEDED + + +def test_durable_process_items_passes_each_item_its_run_arn_and_id() -> None: + """The context's logger wraps the branch logger, so replay de-duplication is kept.""" + lock = threading.Lock() + seen: dict[str, tuple[DurableContext, DistributedMapItemContext]] = {} + + def process( + context: DurableContext, item: str, ctx: DistributedMapItemContext + ) -> None: + with lock: + seen[item] = (context, ctx) + + @durable_execution + def handler(event: dict[str, Any], context: DurableContext) -> Any: + return process_distributed_map_items(context, event, process) + + _run_durable(handler, _ITEM_IDS) + assert sorted(seen) == _ITEM_IDS + for item, (context, ctx) in seen.items(): + assert ctx.item_id == item + assert ctx.distributed_map_run_arn == _RUN_ARN_WITH_SEPARATOR_NAMES + assert isinstance(ctx.logger, Logger) + assert ctx.logger.get_logger() is context.logger + + +def test_process_batch_in_a_durable_handler_keeps_item_ids_aligned() -> None: + """The batch helper takes no durable context, so its logger wraps the module logger.""" + seen: list[tuple[list[str], DistributedMapBatchContext]] = [] + + def process(items: list[str], ctx: DistributedMapBatchContext) -> None: + seen.append((items, ctx)) + + @durable_execution + def handler(event: dict[str, Any], _context: DurableContext) -> Any: + return process_distributed_map_batch(event, process) + + _run_durable(handler, _ITEM_IDS) + ((items, ctx),) = seen + assert items == _ITEM_IDS + assert ctx.item_ids == tuple(_ITEM_IDS) + assert ctx.distributed_map_run_arn == _RUN_ARN_WITH_SEPARATOR_NAMES + assert isinstance(ctx.logger, Logger) + + +# A failed item writes one error line through the item's logger, so a log query +# can find it. The line carries the error the helper reports to the service. +# ============================================================================ + + +def _error_records(caplog: pytest.LogCaptureFixture) -> list[logging.LogRecord]: + return [r for r in caplog.records if r.levelno == logging.ERROR] + + +def _failure_stub_context(error: ErrorObject) -> Any: + """A stand-in DurableContext whose map reports item 0 failed and item 1 succeeded.""" + return SimpleNamespace( + logger=Logger(logging.getLogger("durable-test"), {}), + map=lambda _inputs, _func, config: SimpleNamespace( # noqa: ARG005 + all=[ + SimpleNamespace( + index=0, status=BatchItemStatus.FAILED, error=error, result=None + ), + SimpleNamespace( + index=1, status=BatchItemStatus.SUCCEEDED, error=None, result="1" + ), + ] + ), + ) + + +_TWO_RECORDS = [{"itemId": "id-a", "body": "1"}, {"itemId": "id-b", "body": "1"}] + + +def test_process_items_logs_one_error_line_for_a_failed_item( + caplog: pytest.LogCaptureFixture, +) -> None: + def process(item: int, ctx: DistributedMapItemContext) -> int: + if ctx.item_id == "id-a": + msg = "boom" + raise ValueError(msg) + return item + + with caplog.at_level(logging.ERROR): + response = process_distributed_map_items( + _processor_event(_TWO_RECORDS), process + ) + (record,) = _error_records(caplog) + reported = response["batchItemFailures"][0]["error"] + assert record.getMessage() == "distributed map item failed" + assert record.__dict__["distributedMapRunArn"] == _RUN_ARN + assert record.__dict__["itemId"] == "id-a" + assert record.__dict__["errorType"] == reported["errorType"] == "ValueError" + assert record.__dict__["errorMessage"] == reported["errorMessage"] == "boom" + assert not hasattr(record, "errorData") + assert not hasattr(record, "stackTrace") + + +def test_process_items_error_line_carries_error_data_and_stack_trace( + caplog: pytest.LogCaptureFixture, +) -> None: + def process(_item: int, _ctx: DistributedMapItemContext) -> None: + raise StepError("boom", "ValueError", "payload", ["line 1", "line 2"]) + + with caplog.at_level(logging.ERROR): + process_distributed_map_items(_processor_event(_TWO_RECORDS[:1]), process) + (record,) = _error_records(caplog) + assert record.__dict__["errorData"] == "payload" + assert record.__dict__["stackTrace"] == ["line 1", "line 2"] + + +def test_process_items_logs_no_error_line_when_every_item_succeeds( + caplog: pytest.LogCaptureFixture, +) -> None: + with caplog.at_level(logging.DEBUG): + process_distributed_map_items( + _processor_event(_TWO_RECORDS), lambda item, _ctx: item + ) + assert _error_records(caplog) == [] + + +def test_durable_process_items_logs_one_error_line_for_a_failed_item( + caplog: pytest.LogCaptureFixture, +) -> None: + error = ErrorObject(message="boom", type="ValueError", data=None, stack_trace=None) + with caplog.at_level(logging.ERROR): + response = process_distributed_map_items( + _failure_stub_context(error), + _processor_event(_TWO_RECORDS), + lambda _context, item, _ctx: item, + ) + (record,) = _error_records(caplog) + reported = response["batchItemFailures"][0]["error"] + assert record.getMessage() == "distributed map item failed" + assert record.__dict__["distributedMapRunArn"] == _RUN_ARN + assert record.__dict__["itemId"] == "id-a" + assert record.__dict__["errorType"] == reported["errorType"] == "ValueError" + assert record.__dict__["errorMessage"] == reported["errorMessage"] == "boom" + assert not hasattr(record, "errorData") + assert not hasattr(record, "stackTrace") + + +def test_durable_process_items_error_line_carries_error_data_and_stack_trace( + caplog: pytest.LogCaptureFixture, +) -> None: + error = ErrorObject( + message="boom", type="ValueError", data="payload", stack_trace=["line 1"] + ) + with caplog.at_level(logging.ERROR): + process_distributed_map_items( + _failure_stub_context(error), + _processor_event(_TWO_RECORDS), + lambda _context, item, _ctx: item, + ) + (record,) = _error_records(caplog) + assert record.__dict__["errorData"] == "payload" + assert record.__dict__["stackTrace"] == ["line 1"] + + +def test_durable_process_items_logs_no_error_line_when_every_item_succeeds( + caplog: pytest.LogCaptureFixture, +) -> None: + context = SimpleNamespace( + logger=Logger(logging.getLogger("durable-test"), {}), + map=lambda _inputs, _func, config: SimpleNamespace( # noqa: ARG005 + all=[ + SimpleNamespace( + index=0, status=BatchItemStatus.SUCCEEDED, error=None, result="1" + ) + ] + ), + ) + with caplog.at_level(logging.DEBUG): + process_distributed_map_items( + context, _processor_event(_TWO_RECORDS[:1]), lambda _c, item, _ctx: item + ) + assert _error_records(caplog) == [] diff --git a/packages/aws-durable-execution-sdk-python/tests/dmap/models_test.py b/packages/aws-durable-execution-sdk-python/tests/dmap/models_test.py new file mode 100644 index 000000000..9143edda5 --- /dev/null +++ b/packages/aws-durable-execution-sdk-python/tests/dmap/models_test.py @@ -0,0 +1,617 @@ +"""Unit tests for the distributed map result types.""" + +from __future__ import annotations + +import pytest + +from aws_durable_execution_sdk_python.config import ( + DistributedMapItemStatus, + DistributedMapStatus, +) +from aws_durable_execution_sdk_python.dmap.models import ( + DistributedMapResult, + DistributedMapResultItem, + DistributedMapRunArn, + DistributedMapSummary, + _to_distributed_map_status, +) +from aws_durable_execution_sdk_python.exceptions import ( + DistributedMapError, + DurableOperationError, + ExecutionError, + StepError, + ValidationError, +) +from aws_durable_execution_sdk_python.lambda_service import ( + DistributedMapDetails, + ErrorObject, + Operation, + OperationStatus, + OperationType, +) +from aws_durable_execution_sdk_python.lambda_service import ( + DistributedMapResultItem as DistributedMapResultItemApi, +) + + +def _terminal_operation( + status: OperationStatus, details: DistributedMapDetails +) -> Operation: + return Operation( + operation_id="dmap-id", + operation_type=OperationType.DISTRIBUTED_MAP, + status=status, + distributed_map_details=details, + ) + + +def _result(status, failure_count, items): + return DistributedMapResult( + status=status, + success_count=len(items) - failure_count, + failure_count=failure_count, + read_count=len(items), + all=items, + ) + + +def test_summary_throw_if_error(): + ok = DistributedMapSummary( + status=DistributedMapStatus.SUCCEEDED, + success_count=2, + failure_count=0, + read_count=2, + ) + ok.throw_if_error() # no raise + + failed = DistributedMapSummary( + status=DistributedMapStatus.FAILED, + success_count=0, + failure_count=1, + read_count=1, + ) + with pytest.raises(DistributedMapError): + failed.throw_if_error() + + succeeded_with_failures = DistributedMapSummary( + status=DistributedMapStatus.SUCCEEDED, + success_count=1, + failure_count=1, + read_count=2, + ) + with pytest.raises(DistributedMapError): + succeeded_with_failures.throw_if_error() + + +def test_map_run_result_succeeded_failed_filters(): + items = [ + DistributedMapResultItem( + item_id="0", status=DistributedMapItemStatus.SUCCEEDED, output=1 + ), + DistributedMapResultItem( + item_id="1", + status=DistributedMapItemStatus.FAILED, + error=ErrorObject(message="boom", type="E", data=None, stack_trace=None), + ), + ] + result = DistributedMapResult( + status=DistributedMapStatus.SUCCEEDED, + success_count=1, + failure_count=1, + read_count=2, + all=items, + ) + assert [i.item_id for i in result.succeeded()] == ["0"] + assert [i.item_id for i in result.failed()] == ["1"] + assert result.get_results() == [1] + assert result.get_errors()[0].message == "boom" + + +def test_map_run_result_accessors_keep_items_with_nothing_recorded(): + items = [ + DistributedMapResultItem( + item_id="0", status=DistributedMapItemStatus.SUCCEEDED, output=None + ), + DistributedMapResultItem( + item_id="1", status=DistributedMapItemStatus.SUCCEEDED, output=1 + ), + DistributedMapResultItem( + item_id="2", status=DistributedMapItemStatus.FAILED, error=None + ), + DistributedMapResultItem( + item_id="3", + status=DistributedMapItemStatus.FAILED, + error=ErrorObject(message="boom", type="E", data=None, stack_trace=None), + ), + ] + result = DistributedMapResult( + status=DistributedMapStatus.SUCCEEDED, + success_count=2, + failure_count=2, + read_count=4, + all=items, + ) + # One entry per item of that status, so both lists stay aligned with + # succeeded() and failed(). + assert result.get_results() == [None, 1] + assert len(result.get_results()) == len(result.succeeded()) + assert [e.message if e else None for e in result.get_errors()] == [ + None, + "boom", + ] + assert len(result.get_errors()) == len(result.failed()) + + +def test_map_run_result_accessors_omit_an_unknown_item_status(): + """An item of an unrecognized status stays in all and is in no accessor.""" + items = [ + DistributedMapResultItem( + item_id="0", status=DistributedMapItemStatus.SUCCEEDED, output=1 + ), + DistributedMapResultItem( + item_id="1", + status=DistributedMapItemStatus.UNKNOWN_TO_SDK_VERSION, + output=2, + ), + DistributedMapResultItem( + item_id="2", + status=DistributedMapItemStatus.FAILED, + error=ErrorObject(message="boom", type="E", data=None, stack_trace=None), + ), + ] + result = DistributedMapResult( + status=DistributedMapStatus.SUCCEEDED, + success_count=1, + failure_count=1, + read_count=3, + all=items, + ) + assert [i.item_id for i in result.all] == ["0", "1", "2"] + assert [i.item_id for i in result.succeeded()] == ["0"] + assert [i.item_id for i in result.failed()] == ["2"] + assert result.get_results() == [1] + assert [e.message if e else None for e in result.get_errors()] == ["boom"] + + +def test_summary_has_failure_false_without_failures(): + summary = DistributedMapSummary( + status=DistributedMapStatus.SUCCEEDED, + success_count=0, + failure_count=0, + read_count=0, + ) + assert summary.has_failure is False + + +_RUN_ARN = ( + "arn:aws:lambda:us-east-1:123456789012:function:fn:$LATEST" + "/durable-execution/exec1/invoke1/distributed-map-run/abc" +) + + +def _summary_with_arn(arn): + return DistributedMapSummary( + status=DistributedMapStatus.SUCCEEDED, + success_count=0, + failure_count=0, + read_count=0, + distributed_map_run_arn=arn, + source_exhausted=True, + ) + + +def test_run_arn_from_arn_splits_parent_and_run_id(): + parsed = DistributedMapRunArn.from_arn(_RUN_ARN) + assert parsed is not None + assert parsed.run_id == "abc" + assert parsed.durable_execution_arn == ( + "arn:aws:lambda:us-east-1:123456789012:function:fn:$LATEST" + "/durable-execution/exec1/invoke1" + ) + + +@pytest.mark.parametrize( + "parent", + [ + "arn:aws:lambda:us-east-1:123456789012:function:fn:$LATEST" + "/durable-execution/distributed-map-run/invoke1", + "arn:aws:lambda:us-east-1:123456789012:function:fn:$LATEST" + "/durable-execution/exec1/distributed-map-run", + ], +) +def test_run_arn_from_arn_splits_on_the_last_separator(parent): + """A parent whose execution name or invocation id is the separator text still parses.""" + parsed = DistributedMapRunArn.from_arn(parent + "/distributed-map-run/abc") + assert parsed is not None + assert parsed.run_id == "abc" + assert parsed.durable_execution_arn == parent + + +@pytest.mark.parametrize( + "arn", + [ + "arn:aws:lambda:us-east-1:123456789012:function:fn:$LATEST/durable-execution/exec1/invoke1", + "arn:aws:states:us-east-1:123456789012:mapRun:sm/abc", + _RUN_ARN + "/extra", + "not-an-arn/distributed-map-run/abc", + "abc", + "", + ], +) +def test_run_arn_from_arn_returns_none_for_other_shapes(arn): + assert DistributedMapRunArn.from_arn(arn) is None + + +def test_summary_distributed_map_id_parses_run_arn(): + assert _summary_with_arn(_RUN_ARN).distributed_map_id == "abc" + + +def test_summary_distributed_map_id_none_without_arn(): + assert _summary_with_arn(None).distributed_map_id is None + + +def test_summary_distributed_map_id_none_for_unparseable_arn(): + assert _summary_with_arn("not-an-arn").distributed_map_id is None + + +def test_summary_carries_source_exhausted_and_run_error(): + """The terminal details' SourceExhausted and Error reach the summary.""" + details = DistributedMapDetails( + distributed_map_run_arn=_RUN_ARN, + source_exhausted=False, + error=ErrorObject( + message="tolerance exceeded", + type="DistributedMapFailure", + data="d", + stack_trace=["line"], + ), + success_count=1, + failure_count=2, + read_count=6, + ) + summary = DistributedMapSummary.from_operation( + _terminal_operation(OperationStatus.FAILED, details) + ) + assert summary.source_exhausted is False + assert summary.error is not None + assert summary.error.message == "tolerance exceeded" + assert summary.error.data == "d" + assert summary.error.stack_trace == ["line"] + + +def test_summary_throw_if_error_carries_the_run_error(): + """A thrown run-level error carries every member of the summary's error object.""" + details = DistributedMapDetails( + distributed_map_run_arn=_RUN_ARN, + source_exhausted=True, + error=ErrorObject( + message="boom", type="SourceFailure", data="d", stack_trace=["line"] + ), + success_count=0, + failure_count=1, + read_count=1, + ) + summary = DistributedMapSummary.from_operation( + _terminal_operation(OperationStatus.FAILED, details) + ) + with pytest.raises(DistributedMapError, match="Map run ended FAILED: boom") as exc: + summary.throw_if_error() + assert exc.value.message == "Map run ended FAILED: boom" + assert exc.value.error_type == "SourceFailure" + assert exc.value.data == "d" + assert exc.value.stack_trace == ["line"] + cause = exc.value.__cause__ + assert isinstance(cause, DurableOperationError) + assert cause.message == "boom" + assert cause.error_type == "SourceFailure" + assert cause.data == "d" + assert cause.stack_trace == ["line"] + + +def test_summary_throw_if_error_rebuilds_a_typed_cause(): + """The run error's cause is rebuilt as the registered class its type names.""" + summary = DistributedMapSummary( + status=DistributedMapStatus.FAILED, + success_count=0, + failure_count=0, + read_count=0, + error=ErrorObject( + message="boom", + type=f"{StepError.__module__}.{StepError.__qualname__}", + data=None, + stack_trace=None, + ), + ) + with pytest.raises(DistributedMapError) as exc: + summary.throw_if_error() + assert type(exc.value.__cause__) is StepError + + +def test_summary_throw_if_error_with_an_empty_run_error_has_no_cause(): + """A wholly empty run error carries nothing to rebuild, so it gets no cause.""" + summary = DistributedMapSummary( + status=DistributedMapStatus.FAILED, + success_count=0, + failure_count=0, + read_count=0, + error=ErrorObject(message=None, type=None, data=None, stack_trace=None), + ) + with pytest.raises(DistributedMapError) as exc: + summary.throw_if_error() + assert exc.value.message == "Map run ended FAILED" + assert exc.value.__cause__ is None + + +def test_summary_missing_details_names_the_operation_status(): + """The missing-details error reports the status the operation actually ended in.""" + op = _terminal_operation(OperationStatus.FAILED, None) + with pytest.raises( + ExecutionError, match="ended FAILED but carried no DistributedMapDetails" + ): + DistributedMapSummary.from_operation(op) + + +def test_summary_missing_source_exhausted_raises_once_a_run_exists(): + """SourceExhausted is required at terminal once a run was created.""" + details = DistributedMapDetails( + distributed_map_run_arn=_RUN_ARN, + success_count=1, + failure_count=0, + read_count=1, + ) + op = _terminal_operation(OperationStatus.SUCCEEDED, details) + with pytest.raises(ExecutionError, match="carried no SourceExhausted"): + DistributedMapSummary.from_operation(op) + + +@pytest.mark.parametrize( + ("omitted", "field_name"), + [ + ("success_count", "SuccessCount"), + ("failure_count", "FailureCount"), + ("read_count", "ReadCount"), + ], +) +def test_summary_requires_every_count_at_terminal(omitted, field_name): + """An omitted count raises and names the count, rather than reading as zero.""" + counts = {"success_count": 2, "failure_count": 1, "read_count": 3} + del counts[omitted] + details = DistributedMapDetails( + distributed_map_run_arn=_RUN_ARN, source_exhausted=True, **counts + ) + op = _terminal_operation(OperationStatus.FAILED, details) + with pytest.raises( + ExecutionError, match=f"missing distributed map {field_name} from backend" + ): + DistributedMapSummary.from_operation(op) + + +def test_summary_requires_total_count_when_the_run_succeeded(): + """A SUCCEEDED run counted its whole source, so TotalCount is required.""" + details = DistributedMapDetails( + distributed_map_run_arn=_RUN_ARN, + source_exhausted=True, + success_count=2, + failure_count=0, + read_count=2, + ) + op = _terminal_operation(OperationStatus.SUCCEEDED, details) + with pytest.raises( + ExecutionError, match="missing distributed map TotalCount from backend" + ): + DistributedMapSummary.from_operation(op) + + +def test_summary_allows_missing_total_count_when_the_run_did_not_succeed(): + """A run that was stopped may never have counted its source.""" + details = DistributedMapDetails( + distributed_map_run_arn=_RUN_ARN, + source_exhausted=False, + success_count=1, + failure_count=0, + read_count=2, + ) + summary = DistributedMapSummary.from_operation( + _terminal_operation(OperationStatus.STOPPED, details) + ) + assert summary.total_count is None + assert summary.success_count == 1 + assert summary.read_count == 2 + + +def test_summary_accepts_a_count_of_zero(): + """Zero is a value the service sends, so it must not be read as absent.""" + details = DistributedMapDetails( + distributed_map_run_arn=_RUN_ARN, + source_exhausted=True, + success_count=0, + failure_count=0, + read_count=0, + total_count=0, + ) + summary = DistributedMapSummary.from_operation( + _terminal_operation(OperationStatus.SUCCEEDED, details) + ) + assert summary.success_count == 0 + assert summary.total_count == 0 + + +def test_summary_allows_missing_source_exhausted_before_run_creation(): + """An operation that failed before run creation carries neither ARN nor SourceExhausted.""" + details = DistributedMapDetails( + error=ErrorObject( + message="admission denied", type="E", data=None, stack_trace=None + ), + success_count=0, + failure_count=0, + read_count=0, + ) + summary = DistributedMapSummary.from_operation( + _terminal_operation(OperationStatus.FAILED, details) + ) + assert summary.distributed_map_run_arn is None + assert summary.source_exhausted is None + assert summary.success_count == 0 + assert summary.failure_count == 0 + assert summary.read_count == 0 + + +def test_result_throw_if_error_raises_first_item_error(): + result = _result( + DistributedMapStatus.SUCCEEDED, + 1, + [ + DistributedMapResultItem( + item_id="0", status=DistributedMapItemStatus.SUCCEEDED, output=1 + ), + DistributedMapResultItem( + item_id="1", + status=DistributedMapItemStatus.FAILED, + error=ErrorObject( + message="boom", type="E", data=None, stack_trace=None + ), + ), + ], + ) + with pytest.raises(DistributedMapError, match="boom") as exc_info: + result.throw_if_error() + assert exc_info.value.error_type == "E" + assert isinstance(exc_info.value.__cause__, DurableOperationError) + + +def test_result_throw_if_error_names_item_without_detail(): + result = _result( + DistributedMapStatus.SUCCEEDED, + 1, + [ + DistributedMapResultItem( + item_id="7", status=DistributedMapItemStatus.FAILED, error=None + ) + ], + ) + with pytest.raises(DistributedMapError, match="item 7 failed"): + result.throw_if_error() + + +def test_result_throw_if_error_names_item_with_an_empty_error(): + """A wholly empty item error carries no detail, so the item is named instead.""" + result = _result( + DistributedMapStatus.SUCCEEDED, + 1, + [ + DistributedMapResultItem( + item_id="7", + status=DistributedMapItemStatus.FAILED, + error=ErrorObject(message=None, type=None, data=None, stack_trace=None), + ) + ], + ) + with pytest.raises(DistributedMapError, match="item 7 failed") as exc: + result.throw_if_error() + assert exc.value.__cause__ is None + + +def test_result_throw_if_error_falls_back_to_summary_when_no_items(): + result = DistributedMapResult( + status=DistributedMapStatus.SUCCEEDED, + success_count=0, + failure_count=2, + read_count=2, + all=[], + ) + with pytest.raises(DistributedMapError, match="2 item"): + result.throw_if_error() + + +def test_result_throw_if_error_run_level_failure(): + result = DistributedMapResult( + status=DistributedMapStatus.FAILED, + success_count=0, + failure_count=1, + read_count=1, + all=[], + ) + with pytest.raises(DistributedMapError, match="Map run ended FAILED") as exc: + result.throw_if_error() + assert exc.value.__cause__ is None + + +def test_result_throw_if_error_clean_success_does_not_raise(): + result = DistributedMapResult( + status=DistributedMapStatus.SUCCEEDED, + success_count=1, + failure_count=0, + read_count=1, + all=[ + DistributedMapResultItem( + item_id="0", status=DistributedMapItemStatus.SUCCEEDED, output=1 + ) + ], + ) + result.throw_if_error() + + +def test_result_from_the_inherited_factory_rejects_retained_results(): + """The inherited factory refuses an operation that retained results. + + It cannot deserialize them, so answering would return counts that + contradict an empty ``all``. Callers with retained results must use + ``from_operation_and_items``. + """ + details = DistributedMapDetails( + distributed_map_run_arn=_RUN_ARN, + source_exhausted=True, + success_count=1, + failure_count=0, + read_count=1, + total_count=1, + results=[ + DistributedMapResultItemApi( + item_id="item-0", + status=DistributedMapItemStatus.SUCCEEDED, + output='"out"', + ) + ], + ) + with pytest.raises(ValidationError, match="from_operation_and_items"): + DistributedMapResult.from_operation( + _terminal_operation(OperationStatus.SUCCEEDED, details) + ) + + +def test_result_from_the_inherited_factory_has_no_items(): + """The inherited summary factory builds a result whose all is empty.""" + details = DistributedMapDetails( + distributed_map_run_arn=_RUN_ARN, + source_exhausted=True, + success_count=0, + failure_count=0, + read_count=0, + total_count=0, + ) + result = DistributedMapResult.from_operation( + _terminal_operation(OperationStatus.SUCCEEDED, details) + ) + assert isinstance(result, DistributedMapResult) + assert result.all == [] + assert result.status is DistributedMapStatus.SUCCEEDED + + +def test_status_derived_from_operation_when_details_omit_status(): + """Status comes from the operation, not from details.""" + details = DistributedMapDetails( + success_count=3, + total_count=3, + ) + op = _terminal_operation(OperationStatus.SUCCEEDED, details) + assert _to_distributed_map_status(op) is DistributedMapStatus.SUCCEEDED + + +def test_to_distributed_map_status_rejects_non_terminal(): + """A non-terminal operation status cannot map to a DistributedMapStatus.""" + op = _terminal_operation( + OperationStatus.STARTED, + DistributedMapDetails(success_count=0), + ) + with pytest.raises(ExecutionError, match="Cannot derive distributed map status"): + _to_distributed_map_status(op) diff --git a/packages/aws-durable-execution-sdk-python/tests/dmap/typing_test.py b/packages/aws-durable-execution-sdk-python/tests/dmap/typing_test.py new file mode 100644 index 000000000..5fe49175e --- /dev/null +++ b/packages/aws-durable-execution-sdk-python/tests/dmap/typing_test.py @@ -0,0 +1,159 @@ +"""Static type checks for the distributed map authoring surface. + +``assert_type`` is checked by mypy and returns its value unchanged at runtime, +so every test below asserts nothing beyond building the value it checks. Each +test is annotated, because mypy skips the body of an unannotated function. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, assert_type + +from aws_durable_execution_sdk_python.config import ( + DistributedMapProcessor, + DistributedMapResultConfig, + NestingType, +) +from aws_durable_execution_sdk_python.context import DurableContext +from aws_durable_execution_sdk_python.dmap.helpers import ( + ReaderPage, + process_distributed_map_batch, + process_distributed_map_items, + read_distributed_map_page, +) +from aws_durable_execution_sdk_python.dmap.models import DistributedMapResult +from aws_durable_execution_sdk_python.serdes import SerDes, SerDesContext +from aws_durable_execution_sdk_python.logger import Logger +from aws_durable_execution_sdk_python.types import ( + DistributedMapBatchContext, + DistributedMapItemContext, + DistributedMapReaderContext, + LoggerInterface, +) + + +@dataclass(frozen=True) +class _Order: + """A result type the default serdes cannot write.""" + + order_id: str + + +class _OrderSerDes(SerDes[_Order]): + """A serdes that fixes the result type of a map run that uses it.""" + + def serialize(self, value: _Order, _serdes_context: SerDesContext) -> str: + return value.order_id + + def deserialize(self, data: str, _serdes_context: SerDesContext) -> _Order: + return _Order(order_id=data) + + +def _check_result_config_carries_its_output_type(ctx: DurableContext) -> None: + """Checked by mypy only. A map run needs a live execution, so nothing calls this.""" + result = ctx.distributed_map( + ["a"], + DistributedMapProcessor.report_item_outcomes("proc"), + max_concurrency=1, + config=DistributedMapResultConfig(result_serdes=_OrderSerDes()), + ) + assert_type(result, DistributedMapResult[_Order]) + assert_type(result.get_results(), list[_Order | None]) + + +_RUN_ARN = ( + "arn:aws:lambda:us-east-1:123456789012:function:fn:$LATEST" + "/durable-execution/exec1/invoke1/distributed-map-run/abc" +) +_EVENT: dict[str, Any] = { + "distributedMapRunArn": _RUN_ARN, + "records": [{"itemId": "0", "body": "1"}], + "maxItemsPerPage": 10, +} + + +def test_process_items_non_durable_form_returns_the_response() -> None: + def item_func(item: Any, ctx: DistributedMapItemContext) -> Any: + assert_type(item, Any) + assert_type(ctx, DistributedMapItemContext) + assert_type(ctx.logger, LoggerInterface) + return item + + response = process_distributed_map_items(_EVENT, item_func) + assert_type(response, dict[str, Any]) + configured = process_distributed_map_items( + _EVENT, item_func, item_serdes=None, result_serdes=None, concurrency=2 + ) + assert_type(configured, dict[str, Any]) + + +def test_process_items_durable_form_passes_the_durable_context_to_func() -> None: + def item_func( + context: DurableContext, item: Any, ctx: DistributedMapItemContext + ) -> Any: + assert_type(item, Any) + assert_type(ctx, DistributedMapItemContext) + return context.step(lambda _step_ctx: item, name="read") + + def run(context: DurableContext) -> None: + durable = process_distributed_map_items( + context, _EVENT, item_func, concurrency=2, nesting_type=NestingType.NESTED + ) + assert_type(durable, dict[str, Any]) + + assert callable(run) + + +def test_process_items_durable_func_receives_the_durable_logger_type() -> None: + """The item function sees the durable context's Logger and the item context's LoggerInterface. + + The Python DurableContext has one logger type, Logger, so there is no + customer logger type parameter to flow. A customer logger installed with + set_logger is wrapped by that Logger, and the item context's logger is typed + LoggerInterface. + """ + + def item_func( + context: DurableContext, _item: Any, ctx: DistributedMapItemContext + ) -> Any: + assert_type(context.logger, Logger) + assert_type(ctx.logger, LoggerInterface) + + def run(context: DurableContext) -> None: + assert_type( + process_distributed_map_items(context, _EVENT, item_func), + dict[str, Any], + ) + + assert callable(run) + + +def test_process_batch_returns_none() -> None: + def batch_func(items: list[Any], ctx: DistributedMapBatchContext) -> None: + assert_type(items, list[Any]) + assert_type(ctx, DistributedMapBatchContext) + assert_type(ctx.item_ids, tuple[str, ...]) + + assert_type(process_distributed_map_batch(_EVENT, batch_func), None) + assert_type( + process_distributed_map_batch(_EVENT, batch_func, item_serdes=None), None + ) + + +def test_read_page_returns_the_response() -> None: + def read_func( + state: Any, max_items_per_page: int, ctx: DistributedMapReaderContext + ) -> ReaderPage: + assert_type(state, Any) + assert_type(max_items_per_page, int) + assert_type(ctx, DistributedMapReaderContext) + return ReaderPage() + + assert_type(read_distributed_map_page(_EVENT, read_func), dict[str, Any]) + assert_type( + read_distributed_map_page( + _EVENT, read_func, item_serdes=None, state_serdes=None + ), + dict[str, Any], + ) diff --git a/packages/aws-durable-execution-sdk-python/tests/e2e/dmap_durable_item_replay_test.py b/packages/aws-durable-execution-sdk-python/tests/e2e/dmap_durable_item_replay_test.py new file mode 100644 index 000000000..4b73ad4a5 --- /dev/null +++ b/packages/aws-durable-execution-sdk-python/tests/e2e/dmap_durable_item_replay_test.py @@ -0,0 +1,274 @@ +"""process_distributed_map_items in a durable handler resumes after a wait. + +Also covers the helpers composed with other durable operations in the same +handler, run through DurableFunctionTestRunner. +""" + +from __future__ import annotations + +import json +import threading +from collections import Counter +from typing import Any + +from aws_durable_execution_sdk_python.config import Duration, NestingType +from aws_durable_execution_sdk_python.context import DurableContext +from aws_durable_execution_sdk_python.dmap.helpers import ( + process_distributed_map_batch, + process_distributed_map_items, +) +from aws_durable_execution_sdk_python.exceptions import DurableOperationError +from aws_durable_execution_sdk_python.execution import ( + InvocationStatus, + durable_execution, +) +from aws_durable_execution_sdk_python.lambda_service import OperationType +from aws_durable_execution_sdk_python.serdes import SerDes, SerDesContext +from aws_durable_execution_sdk_python.types import ( + DistributedMapBatchContext, + DistributedMapItemContext, +) +from aws_durable_execution_sdk_python_testing.runner import ( + DurableFunctionTestResult, + DurableFunctionTestRunner, +) + +_RUN_ARN = ( + "arn:aws:lambda:us-east-1:123456789012:function:fn:$LATEST" + "/durable-execution/exec1/invoke1/distributed-map-run/abc" +) + +_LOCK = threading.Lock() +_CALLS: dict[str, Counter[str]] = { + "func": Counter(), + "step": Counter(), + "serialize": Counter(), +} + + +def _count(kind: str, item: str) -> None: + with _LOCK: + _CALLS[kind][item] += 1 + + +class _TaggingSerDes(SerDes[str]): + """Prefixes each output so a double encoding would be visible.""" + + def serialize(self, value: str, serdes_context: SerDesContext) -> str: # noqa: ARG002 + _count("serialize", value) + return f"tag:{value}" + + def deserialize(self, data: str, serdes_context: SerDesContext) -> str: # noqa: ARG002 + return data.removeprefix("tag:") + + +def _process(ctx: DurableContext, item: str, _ctx: DistributedMapItemContext) -> str: + _count("func", item) + ctx.step(lambda _: _count("step", item), name="item-step") + if item == "b": + ctx.wait(Duration.from_seconds(1), name="item-b-wait") + return item + + +def _event(items: list[str]) -> str: + return json.dumps( + { + "distributedMapRunArn": _RUN_ARN, + "records": [ + {"itemId": f"id-{item}", "body": json.dumps(item)} for item in items + ], + } + ) + + +def _items_handler(nesting_type: NestingType) -> Any: + @durable_execution + def handler(event: dict[str, Any], context: DurableContext) -> dict[str, Any]: + return process_distributed_map_items( + context, + event, + _process, + result_serdes=_TaggingSerDes(), + concurrency=2, + nesting_type=nesting_type, + ) + + return handler + + +def _run_and_check_response(nesting_type: NestingType) -> DurableFunctionTestResult: + for counter in _CALLS.values(): + counter.clear() + + with DurableFunctionTestRunner(handler=_items_handler(nesting_type)) as runner: + result: DurableFunctionTestResult = runner.run( + input=_event(["a", "b"]), execution_timeout=15 + ) + + assert result.status is InvocationStatus.SUCCEEDED + assert result.result is not None + response: dict[str, Any] = json.loads(result.result) + assert response["batchItemFailures"] == [] + assert sorted(response["batchItemResults"], key=lambda r: r["itemIdentifier"]) == [ + {"itemIdentifier": "id-a", "output": "tag:a"}, + {"itemIdentifier": "id-b", "output": "tag:b"}, + ] + return result + + +def test_flat_item_helper_reruns_a_completed_items_function_but_not_its_steps() -> None: + """Under FLAT, the resume after item b's wait replays item a's function. + + The function body and the result serializer of item a each run again. The + step inside item a does not, because its result is checkpointed. + """ + _run_and_check_response(NestingType.FLAT) + + assert _CALLS["func"]["a"] == 2 + assert _CALLS["serialize"]["a"] == 2 + assert _CALLS["step"]["a"] == 1 + assert _CALLS["func"]["b"] == 2 + assert _CALLS["step"]["b"] == 1 + + +def test_nested_item_helper_resumes_without_rerunning_a_completed_item() -> None: + """Under NESTED, item a's function and result serializer each run once.""" + _run_and_check_response(NestingType.NESTED) + + assert _CALLS["func"]["a"] == 1 + assert _CALLS["serialize"]["a"] == 1 + assert _CALLS["step"]["a"] == 1 + assert _CALLS["func"]["b"] == 2 + assert _CALLS["step"]["b"] == 1 + + +def _walk(operations: list[Any]) -> list[Any]: + found: list[Any] = [] + for operation in operations: + found.append(operation) + found.extend(_walk(getattr(operation, "child_operations", []))) + return found + + +def test_flat_item_helper_records_no_per_item_context_operation() -> None: + """Under FLAT the item steps sit directly under the Map operation.""" + result = _run_and_check_response(NestingType.FLAT) + + contexts = [ + op + for op in _walk(result.operations) + if op.operation_type is OperationType.CONTEXT + ] + assert [op.sub_type for op in contexts] == ["Map"] + + +def test_nested_item_helper_records_one_context_operation_per_item() -> None: + """Under NESTED each item gets its own MapIteration context operation.""" + result = _run_and_check_response(NestingType.NESTED) + + contexts = [ + op + for op in _walk(result.operations) + if op.operation_type is OperationType.CONTEXT + ] + assert [op.sub_type for op in contexts] == ["Map", "MapIteration", "MapIteration"] + + +def test_item_helper_runs_after_a_step_in_the_same_handler() -> None: + step_runs: list[str] = [] + + @durable_execution + def handler(event: dict[str, Any], context: DurableContext) -> dict[str, Any]: + def before_items(_: Any) -> str: + step_runs.append("before") + return "pre" + + prefix = context.step(before_items, name="before-items") + response = process_distributed_map_items( + context, event, lambda _ctx, item, _item_ctx: f"{prefix}-{item}" + ) + return response + + with DurableFunctionTestRunner(handler=handler) as runner: + result = runner.run(input=_event(["a", "b"]), execution_timeout=15) + + assert result.status is InvocationStatus.SUCCEEDED + assert result.result is not None + response = json.loads(result.result) + assert response["batchItemFailures"] == [] + assert response["batchItemResults"] == [ + {"itemIdentifier": "id-a", "output": '"pre-a"'}, + {"itemIdentifier": "id-b", "output": '"pre-b"'}, + ] + assert step_runs == ["before"] + + +def test_batch_helper_in_a_durable_handler_uses_the_handlers_own_context() -> None: + seen: list[Any] = [] + + @durable_execution + def handler(event: dict[str, Any], context: DurableContext) -> None: + def process(items: list[Any], batch_ctx: DistributedMapBatchContext) -> None: + seen.append((items, batch_ctx.item_ids)) + context.step(lambda _: len(items), name="count-batch") + + return process_distributed_map_batch(event, process) + + with DurableFunctionTestRunner(handler=handler) as runner: + result = runner.run(input=_event(["a", "b"]), execution_timeout=15) + + assert result.status is InvocationStatus.SUCCEEDED + assert result.result is not None + assert json.loads(result.result) is None + assert seen == [(["a", "b"], ("id-a", "id-b"))] + steps = [op for op in result.operations if op.operation_type is OperationType.STEP] + assert [op.name for op in steps] == ["count-batch"] + + +def test_flat_item_helper_forwards_error_data_to_the_response() -> None: + """Each failed item's errorData and stackTrace reach the response under FLAT.""" + + def process( + _ctx: DurableContext, _item: str, _item_ctx: DistributedMapItemContext + ) -> str: + raise DurableOperationError( + message="boom", + error_type="Inner", + data="payload", + stack_trace=["frame one", "frame two"], + ) + + @durable_execution + def handler(event: dict[str, Any], context: DurableContext) -> dict[str, Any]: + return process_distributed_map_items( + context, event, process, nesting_type=NestingType.FLAT + ) + + with DurableFunctionTestRunner(handler=handler) as runner: + result = runner.run(input=_event(["a"]), execution_timeout=15) + + assert result.status is InvocationStatus.SUCCEEDED + assert result.result is not None + response = json.loads(result.result) + assert response["batchItemResults"] == [] + assert response["batchItemFailures"] == [ + { + "itemIdentifier": "id-a", + "error": { + "errorType": ( + f"{DurableOperationError.__module__}." + f"{DurableOperationError.__qualname__}" + ), + "errorMessage": "boom", + "errorData": "payload", + "stackTrace": ["frame one", "frame two"], + }, + } + ] + + contexts = [ + op + for op in _walk(result.operations) + if op.operation_type is OperationType.CONTEXT + ] + assert "MapIteration" not in [op.sub_type for op in contexts] diff --git a/packages/aws-durable-execution-sdk-python/tests/e2e/dmap_helpers_int_test.py b/packages/aws-durable-execution-sdk-python/tests/e2e/dmap_helpers_int_test.py new file mode 100644 index 000000000..e500ab448 --- /dev/null +++ b/packages/aws-durable-execution-sdk-python/tests/e2e/dmap_helpers_int_test.py @@ -0,0 +1,376 @@ +"""Integration tests for the distributed map helpers inside durable handlers. + +Each test defines a ``@durable_execution`` handler that calls a helper, and runs +it through the full invocation harness with a mocked checkpoint backend. +""" + +from __future__ import annotations + +import json +import threading +import time +from typing import Any +from unittest.mock import Mock, patch + +import pytest + +from aws_durable_execution_sdk_python.dmap.helpers import ( + process_distributed_map_batch, + process_distributed_map_items, +) +from aws_durable_execution_sdk_python.exceptions import DurableOperationError +from aws_durable_execution_sdk_python.filesystem_serdes import FileSystemSerDes +from aws_durable_execution_sdk_python.execution import ( + InvocationStatus, + durable_execution, +) +from aws_durable_execution_sdk_python.lambda_service import ( + CheckpointOutput, + CheckpointUpdatedExecutionState, + Operation, + OperationStatus, + OperationType, +) +from aws_durable_execution_sdk_python.serdes import SerDes, SerDesContext + +_RUN_ARN = ( + "arn:aws:lambda:us-east-1:123456789012:function:fn:$LATEST" + "/durable-execution/exec1/invoke1/distributed-map-run/abc" +) + +_ARN = "arn:aws:lambda:us-east-1:123456789012:function:proc:1/durable-execution/execution-1" + + +def _lambda_context(): + ctx = Mock() + ctx.aws_request_id = "test-request-id" + ctx.client_context = None + ctx.identity = None + ctx._epoch_deadline_time_in_ms = 0 # noqa: SLF001 + ctx.invoked_function_arn = "test-arn" + ctx.tenant_id = None + return ctx + + +def _event(records: list[dict]): + return { + "DurableExecutionArn": _ARN, + "CheckpointToken": "test-token", + "InitialExecutionState": { + "Operations": [ + { + "Id": "execution-1", + "Type": "EXECUTION", + "Status": "STARTED", + "ExecutionDetails": { + "InputPayload": json.dumps( + {"distributedMapRunArn": _RUN_ARN, "records": records} + ) + }, + } + ], + "NextMarker": "", + }, + "LocalRunner": True, + } + + +def _mock_checkpoint(): + """Return a checkpoint stub that accepts every update and echoes the state.""" + operations = [ + Operation( + operation_id="execution-1", + operation_type=OperationType.EXECUTION, + status=OperationStatus.STARTED, + ) + ] + + def mock_checkpoint( + durable_execution_arn, checkpoint_token, updates, client_token="token" + ): # noqa: S107 + for update in updates: + operations.append( + Operation( + operation_id=update.operation_id, + operation_type=update.operation_type, + status=OperationStatus.STARTED, + parent_id=update.parent_id, + ) + ) + return CheckpointOutput( + checkpoint_token="new_token", # noqa: S106 + new_execution_state=CheckpointUpdatedExecutionState( + operations=operations.copy() + ), + ) + + return mock_checkpoint + + +def _run(handler, records: list[dict]): + with patch( + "aws_durable_execution_sdk_python.execution.LambdaClient" + ) as mock_client_class: + mock_client = Mock() + mock_client_class.initialize_client.return_value = mock_client + mock_client.checkpoint = _mock_checkpoint() + return handler(_event(records), _lambda_context()) + + +def _items_handler(func, **options): + """Build a durable handler that returns process_distributed_map_items.""" + + @durable_execution + def handler(event, context): + return process_distributed_map_items(context, event, func, **options) + + return handler + + +def _batch_handler(func, **options): + """Build a durable handler that calls process_distributed_map_batch. + + ``func`` receives the handler's own DurableContext first. + """ + + @durable_execution + def handler(event, context): + return process_distributed_map_batch( + event, lambda items, batch_ctx: func(context, items, batch_ctx), **options + ) + + return handler + + +def test_items_helper_reports_results(): + handler = _items_handler(lambda _context, item, _ctx: item * 2) + result = _run(handler, [{"itemId": "0", "body": "2"}, {"itemId": "1", "body": "3"}]) + assert result["Status"] == InvocationStatus.SUCCEEDED.value + data = json.loads(result["Result"]) + assert data["batchItemResults"] == [ + {"itemIdentifier": "0", "output": "4"}, + {"itemIdentifier": "1", "output": "6"}, + ] + assert data["batchItemFailures"] == [] + + +def test_items_helper_captures_failure(): + def process(_context, item, _ctx): + if item == "bad": + msg = "boom" + raise ValueError(msg) + return item + + handler = _items_handler(process) + result = _run( + handler, [{"itemId": "0", "body": '"ok"'}, {"itemId": "1", "body": '"bad"'}] + ) + assert result["Status"] == InvocationStatus.SUCCEEDED.value + data = json.loads(result["Result"]) + assert data["batchItemResults"] == [{"itemIdentifier": "0", "output": '"ok"'}] + assert data["batchItemFailures"][0]["itemIdentifier"] == "1" + assert data["batchItemFailures"][0]["error"]["errorType"] == "ValueError" + + +def test_items_helper_forwards_every_error_member(): + """The branch error's data and stack trace reach the service, not just type and message.""" + + def process(_context, _item, _ctx): + raise DurableOperationError( + message="boom", + error_type="Inner", + data="payload", + stack_trace=["frame one", "frame two"], + ) + + handler = _items_handler(process) + result = _run(handler, [{"itemId": "0", "body": "1"}]) + assert result["Status"] == InvocationStatus.SUCCEEDED.value + data = json.loads(result["Result"]) + + error = data["batchItemFailures"][0]["error"] + # A branch error is checkpointed and rebuilt, which normalizes errorType to + # the raised class's qualified name. + assert error["errorType"] == ( + f"{DurableOperationError.__module__}.{DurableOperationError.__qualname__}" + ) + assert error["errorMessage"] == "boom" + assert error["errorData"] == "payload" + assert error["stackTrace"] == ["frame one", "frame two"] + + +def test_batch_helper_records_no_output(): + """A batch processor reports no output, so the return value is not forwarded.""" + seen: list = [] + + def process(_context, items, _ctx): + seen.extend(items) + return {"count": len(items)} + + handler = _batch_handler(process) + result = _run(handler, [{"itemId": "0", "body": "1"}, {"itemId": "1", "body": "2"}]) + assert result["Status"] == InvocationStatus.SUCCEEDED.value + assert json.loads(result["Result"]) is None + assert seen == [1, 2] + + +def test_items_helper_fails_only_the_item_whose_output_cannot_be_serialized(): + """A result serdes failure is that item's failure, not the batch's.""" + + class _RejectsBad(SerDes[Any]): + def serialize(self, value: Any, _serdes_context: SerDesContext) -> str: + if value == "bad": + msg = "cannot serialize" + raise TypeError(msg) + return json.dumps(value) + + def deserialize(self, data: str, _serdes_context: SerDesContext) -> Any: + return json.loads(data) + + handler = _items_handler( + lambda _context, item, _ctx: item, result_serdes=_RejectsBad() + ) + result = _run( + handler, [{"itemId": "0", "body": '"ok"'}, {"itemId": "1", "body": '"bad"'}] + ) + assert result["Status"] == InvocationStatus.SUCCEEDED.value + data = json.loads(result["Result"]) + assert data["batchItemResults"] == [{"itemIdentifier": "0", "output": '"ok"'}] + assert data["batchItemFailures"] == [ + { + "itemIdentifier": "1", + "error": {"errorType": "TypeError", "errorMessage": "cannot serialize"}, + } + ] + + +def test_items_helper_serializes_a_custom_result_type(): + """Only the result serdes can write this output, so it must run before the checkpoint.""" + + class _Order: + def __init__(self, order_id: str) -> None: + self.order_id = order_id + + class _OrderSerDes(SerDes[Any]): + def serialize(self, value: Any, _serdes_context: SerDesContext) -> str: + return json.dumps({"orderId": value.order_id}) + + def deserialize(self, data: str, _serdes_context: SerDesContext) -> Any: + return _Order(json.loads(data)["orderId"]) + + handler = _items_handler( + lambda _context, item, _ctx: _Order(item), result_serdes=_OrderSerDes() + ) + result = _run(handler, [{"itemId": "0", "body": '"o-1"'}]) + assert result["Status"] == InvocationStatus.SUCCEEDED.value + data = json.loads(result["Result"]) + assert data["batchItemFailures"] == [] + assert data["batchItemResults"] == [ + {"itemIdentifier": "0", "output": '{"orderId": "o-1"}'} + ] + + +def test_items_helper_omits_the_output_of_a_handler_returning_none(): + handler = _items_handler(lambda _context, _item, _ctx: None) + result = _run(handler, [{"itemId": "0", "body": "1"}]) + assert result["Status"] == InvocationStatus.SUCCEEDED.value + data = json.loads(result["Result"]) + assert data == { + "batchItemFailures": [], + "batchItemResults": [{"itemIdentifier": "0"}], + } + + +def test_items_helper_runs_items_one_at_a_time_by_default(): + lock = threading.Lock() + in_flight = 0 + peak = 0 + + def process(_context, item, _ctx): + nonlocal in_flight, peak + with lock: + in_flight += 1 + peak = max(peak, in_flight) + # Hold the branch so that a wider bound would overlap this item with the + # next one, which is what makes the peak below meaningful. + time.sleep(0.02) + with lock: + in_flight -= 1 + return item + + handler = _items_handler(process) + result = _run(handler, [{"itemId": str(i), "body": "1"} for i in range(4)]) + assert result["Status"] == InvocationStatus.SUCCEEDED.value + assert peak == 1 + + +def test_items_helper_honors_requested_concurrency(): + # Each item blocks until all four have arrived, so the batch only finishes + # if the map really runs four items at once. At a smaller bound the first + # item waits out the timeout and every item fails. + barrier = threading.Barrier(4, timeout=5) + + def process(_context, item, _ctx): + barrier.wait() + return item + + handler = _items_handler(process, concurrency=4) + result = _run(handler, [{"itemId": str(i), "body": str(i)} for i in range(4)]) + assert result["Status"] == InvocationStatus.SUCCEEDED.value + data = json.loads(result["Result"]) + assert data["batchItemFailures"] == [] + assert data["batchItemResults"] == [ + {"itemIdentifier": "0", "output": "0"}, + {"itemIdentifier": "1", "output": "1"}, + {"itemIdentifier": "2", "output": "2"}, + {"itemIdentifier": "3", "output": "3"}, + ] + + +def test_items_helper_stores_each_output_under_its_own_key(tmp_path): + """A serdes that stores values under their context keeps every output.""" + fs = FileSystemSerDes(str(tmp_path)) + handler = _items_handler( + lambda _context, item, _ctx: f"out-{item}", result_serdes=fs + ) + records = [{"itemId": f"item-{i}", "body": json.dumps(i)} for i in range(3)] + result = _run(handler, records) + assert result["Status"] == InvocationStatus.SUCCEEDED.value + outputs = [r["output"] for r in json.loads(result["Result"])["batchItemResults"]] + assert len(set(outputs)) == 3 + assert [fs.deserialize(o, SerDesContext()) for o in outputs] == [ + "out-0", + "out-1", + "out-2", + ] + + +@pytest.mark.parametrize("batch", [False, True], ids=["item", "batch"]) +def test_helper_reads_and_writes_each_value_under_its_own_context(batch): + lock = threading.Lock() + contexts: list[SerDesContext] = [] + + class _Recording(SerDes[Any]): + def serialize(self, value: Any, serdes_context: SerDesContext) -> str: + with lock: + contexts.append(serdes_context) + return json.dumps(value) + + def deserialize(self, data: str, serdes_context: SerDesContext) -> Any: + with lock: + contexts.append(serdes_context) + return json.loads(data) + + serdes = _Recording() + if batch: + handler = _batch_handler( + lambda _context, _items, _ctx: None, item_serdes=serdes + ) + else: + handler = _items_handler( + lambda _context, item, _ctx: item, item_serdes=serdes, result_serdes=serdes + ) + _run(handler, [{"itemId": "0", "body": "1"}, {"itemId": "1", "body": "2"}]) + assert ( + len({c.operation_id for c in contexts}) == len(contexts) == (2 if batch else 4) + ) diff --git a/packages/aws-durable-execution-sdk-python/tests/e2e/dmap_int_test.py b/packages/aws-durable-execution-sdk-python/tests/e2e/dmap_int_test.py new file mode 100644 index 000000000..1fe03db51 --- /dev/null +++ b/packages/aws-durable-execution-sdk-python/tests/e2e/dmap_int_test.py @@ -0,0 +1,593 @@ +"""Integration tests for ctx.distributed_map through a full durable_execution invocation. + +Drives the real suspend/resume flow: the first invocation starts the DISTRIBUTED_MAP +operation and suspends (PENDING); a replay invocation with the operation +completed (carrying DistributedMapDetails) resolves to the summary/result. The backend +is mocked; no emulator or real service is involved. +""" + +from __future__ import annotations + +import json +from typing import Any +from unittest.mock import Mock, patch + +from botocore.exceptions import ClientError + +from aws_durable_execution_sdk_python.dmap.helpers import ( + ItemFailure, + process_distributed_map_items, +) +from aws_durable_execution_sdk_python.dmap.models import DistributedMapResult +from aws_durable_execution_sdk_python.config import ( + DistributedMapResultConfig, + DistributedMapProcessor, + DistributedMapSource, +) +from aws_durable_execution_sdk_python.filesystem_serdes import FileSystemSerDes +from aws_durable_execution_sdk_python.context import ( + DurableContext, + StepContext, + durable_step, +) +from aws_durable_execution_sdk_python.exceptions import ( + CheckpointError, + DurableOperationError, + ValidationError, +) +from aws_durable_execution_sdk_python.execution import ( + InvocationStatus, + durable_execution, +) +from aws_durable_execution_sdk_python.lambda_service import ( + CheckpointOutput, + CheckpointUpdatedExecutionState, + Operation, + OperationStatus, + OperationType, +) +from aws_durable_execution_sdk_python.plugin import ( + DurableInstrumentationPlugin, + InvocationStartInfo, + OperationEndInfo, + OperationStartInfo, + OperationType as PluginOperationType, +) +from tests.test_helpers import operation_id_sequence, plugin_factory + + +def _lambda_context(): + ctx = Mock() + ctx.aws_request_id = "test-request-id" + ctx.client_context = None + ctx.identity = None + ctx._epoch_deadline_time_in_ms = 0 # noqa: SLF001 + ctx.invoked_function_arn = "test-arn" + ctx.tenant_id = None + return ctx + + +_ARN = ( + "arn:aws:lambda:us-east-1:123456789012:function:test-func:1" + "/durable-execution/exec-001/inv-001" +) +_RUN_ARN = f"{_ARN}/distributed-map-run/abc" + + +def _initial_event(): + return { + "DurableExecutionArn": _ARN, + "CheckpointToken": "test-token", + "InitialExecutionState": { + "Operations": [ + { + "Id": "execution-1", + "Type": "EXECUTION", + "Status": "STARTED", + "ExecutionDetails": {"InputPayload": "{}"}, + } + ], + "NextMarker": "", + }, + "LocalRunner": True, + } + + +def _replay_event(distributed_map_details: dict): + distributed_map_id = next(operation_id_sequence()) + return distributed_map_id, { + "DurableExecutionArn": _ARN, + "CheckpointToken": "test-token", + "InitialExecutionState": { + "Operations": [ + { + "Id": "execution-1", + "Type": "EXECUTION", + "Status": "STARTED", + "ExecutionDetails": {"InputPayload": "{}"}, + }, + { + "Id": distributed_map_id, + "Type": "DISTRIBUTED_MAP", + "SubType": "DistributedMap", + "Status": "SUCCEEDED", + "DistributedMapDetails": distributed_map_details, + }, + ], + "NextMarker": "", + }, + "LocalRunner": True, + } + + +def _tracking_checkpoint(): + """Checkpoint mock that records created operations as STARTED.""" + calls: list = [] + operations = [ + Operation( + operation_id="execution-1", + operation_type=OperationType.EXECUTION, + status=OperationStatus.STARTED, + ) + ] + + def mock_checkpoint( + durable_execution_arn, checkpoint_token, updates, client_token="token" + ): # noqa: S107 + calls.append(updates) + for update in updates: + operations.append( + Operation( + operation_id=update.operation_id, + operation_type=update.operation_type, + sub_type=update.sub_type, + name=update.name, + status=OperationStatus.STARTED, + parent_id=update.parent_id, + ) + ) + return CheckpointOutput( + checkpoint_token="new_token", # noqa: S106 + new_execution_state=CheckpointUpdatedExecutionState( + operations=operations.copy() + ), + ) + + return calls, mock_checkpoint + + +def _run(handler, event): + with patch( + "aws_durable_execution_sdk_python.execution.LambdaClient" + ) as mock_client_class: + mock_client = Mock() + mock_client_class.initialize_client.return_value = mock_client + _calls, mock_checkpoint = _tracking_checkpoint() + mock_client.checkpoint = mock_checkpoint + return handler(event, _lambda_context()) + + +def test_map_run_suspends_then_resumes_with_summary(): + @durable_execution + def handler(event, context: DurableContext) -> dict[str, Any]: + summary = context.distributed_map( + ["a", "b"], + DistributedMapProcessor.report_batch_outcome("proc"), + max_concurrency=2, + ) + return { + "status": summary.status.value, + "success": summary.success_count, + "failure": summary.failure_count, + "distributed_map_run_arn": summary.distributed_map_run_arn, + } + + # First invocation suspends. + first = _run(handler, _initial_event()) + assert first["Status"] == InvocationStatus.PENDING.value + + # Replay with the run completed. + _map_run_id, replay_event = _replay_event( + { + "SourceExhausted": True, + "SuccessCount": 2, + "FailureCount": 0, + "ReadCount": 2, + "TotalCount": 2, + "DistributedMapRunArn": "arn:aws:lambda:us-east-1:123456789012:function:fn:$LATEST/durable-execution/exec1/invoke1/distributed-map-run/abc", + } + ) + replay = _run(handler, replay_event) + assert replay["Status"] == InvocationStatus.SUCCEEDED.value + data = json.loads(replay["Result"]) + assert data == { + "status": "SUCCEEDED", + "success": 2, + "failure": 0, + "distributed_map_run_arn": "arn:aws:lambda:us-east-1:123456789012:function:fn:$LATEST/durable-execution/exec1/invoke1/distributed-map-run/abc", + } + + +def test_map_run_subtype_is_a_plain_string_on_first_run_and_replay(): + """The START update and every plugin hook carry the subtype as a plain str.""" + sub_types: list[object] = [] + + class Record(DurableInstrumentationPlugin): + def on_invocation_start(self, info: InvocationStartInfo) -> None: + sub_types.extend( + op.sub_type + for op in info.operations.values() + if op.operation_type is PluginOperationType.DISTRIBUTED_MAP + ) + + def on_operation_start(self, info: OperationStartInfo) -> None: + sub_types.append(info.sub_type) + + def on_operation_end(self, info: OperationEndInfo) -> None: + sub_types.append(info.sub_type) + + def handler(event, context: DurableContext) -> int: + return context.distributed_map( + ["a"], + DistributedMapProcessor.report_batch_outcome("proc"), + max_concurrency=1, + ).success_count + + wrapped = durable_execution(handler, plugins=[plugin_factory(Record())]) + with patch( + "aws_durable_execution_sdk_python.execution.LambdaClient" + ) as mock_client_class: + mock_client = Mock() + mock_client_class.initialize_client.return_value = mock_client + calls, mock_client.checkpoint = _tracking_checkpoint() + first = wrapped(_initial_event(), _lambda_context()) + assert first["Status"] == InvocationStatus.PENDING.value + first_run_hooks = len(sub_types) + _map_run_id, replay_event = _replay_event( + { + "SourceExhausted": True, + "SuccessCount": 1, + "FailureCount": 0, + "ReadCount": 1, + "TotalCount": 1, + } + ) + replay = _run(wrapped, replay_event) + assert replay["Status"] == InvocationStatus.SUCCEEDED.value + + (start,) = [u for batch in calls for u in batch] + assert type(start.sub_type) is str + assert first_run_hooks > 0 + assert len(sub_types) > first_run_hooks + assert sub_types == ["DistributedMap"] * len(sub_types) + assert {type(sub_type) for sub_type in sub_types} == {str} + + +def test_map_run_result_config_returns_items(): + @durable_execution + def handler(event, context: DurableContext) -> dict[str, Any]: + result: DistributedMapResult[Any] = context.distributed_map( + ["a", "b"], + DistributedMapProcessor.report_item_outcomes("proc"), + max_concurrency=2, + config=DistributedMapResultConfig(), + ) + assert isinstance(result, DistributedMapResult) + return { + "results": result.get_results(), + "errors": [ + e.message if e is not None else None for e in result.get_errors() + ], + } + + _map_run_id, replay_event = _replay_event( + { + "SourceExhausted": True, + "SuccessCount": 1, + "FailureCount": 1, + "ReadCount": 2, + "TotalCount": 2, + "DistributedMapRunArn": _RUN_ARN, + "Results": [ + {"ItemId": "0", "Status": "SUCCEEDED", "Output": "5"}, + { + "ItemId": "1", + "Status": "FAILED", + "Error": {"ErrorType": "E", "ErrorMessage": "boom"}, + }, + ], + } + ) + replay = _run(handler, replay_event) + assert replay["Status"] == InvocationStatus.SUCCEEDED.value + data = json.loads(replay["Result"]) + assert data == {"results": [5], "errors": ["boom"]} + + +def test_map_run_throw_if_error_fails_execution(): + @durable_execution + def handler(event, context: DurableContext) -> dict[str, Any]: + summary = context.distributed_map( + ["a"], + DistributedMapProcessor.report_batch_outcome("proc"), + max_concurrency=1, + ) + summary.throw_if_error() + return {"status": summary.status.value} + + _map_run_id, replay_event = _replay_event( + { + "SourceExhausted": False, + "Error": { + "ErrorType": "DistributedMapFailure", + "ErrorMessage": "failure tolerance exceeded", + }, + "SuccessCount": 0, + "FailureCount": 1, + "ReadCount": 1, + "TotalCount": 1, + } + ) + replay = _run(handler, replay_event) + assert replay["Status"] == InvocationStatus.FAILED.value + + +def test_item_error_loses_data_and_stack_trace_before_the_parent(): + """The processor reports all four error members and the parent receives two. + + Verified against the beta cell on 2026-11-05: the processor's response + carried all four, and the run's recorded item Error held ErrorMessage and + ErrorType only. The two are therefore lost in the service, not in the SDK, + which surfaces whichever members arrive (operation/dmap_test.py's + test_item_error_keeps_every_error_member covers that). + + The wire ErrorType is the raised class's qualified name, so the exception's + own error_type is replaced rather than forwarded. + """ + + def process(_item: Any, _ctx: Any) -> Any: + raise DurableOperationError( + message="boom", + error_type="Inner", + data="payload", + stack_trace=["frame one", "frame two"], + ) + + response = process_distributed_map_items( + {"distributedMapRunArn": _RUN_ARN, "records": [{"itemId": "0", "body": "1"}]}, + process, + ) + failure = ItemFailure.from_dict(response["batchItemFailures"][0]) + assert failure.error is not None + assert failure.error.message == "boom" + assert failure.error.type == ( + f"{DurableOperationError.__module__}.{DurableOperationError.__qualname__}" + ) + assert failure.error.data == "payload" + assert failure.error.stack_trace == ["frame one", "frame two"] + + @durable_execution + def handler(event, context: DurableContext) -> dict[str, Any]: + result: DistributedMapResult[Any] = context.distributed_map( + ["a"], + DistributedMapProcessor.report_item_outcomes("proc"), + max_concurrency=1, + config=DistributedMapResultConfig(), + ) + assert isinstance(result, DistributedMapResult) + [err] = result.get_errors() + assert err is not None + return { + "type": err.type, + "message": err.message, + "data": err.data, + "stack_trace": err.stack_trace, + } + + # The replayed item error is what the processor just produced, less the two + # members the service drops on the way to the parent. + _map_run_id, replay_event = _replay_event( + { + "SourceExhausted": True, + "SuccessCount": 0, + "FailureCount": 1, + "ReadCount": 1, + "TotalCount": 1, + "Results": [ + { + "ItemId": failure.item_identifier, + "Status": "FAILED", + "Error": { + "ErrorType": failure.error.type, + "ErrorMessage": failure.error.message, + }, + } + ], + } + ) + replay = _run(handler, replay_event) + assert replay["Status"] == InvocationStatus.SUCCEEDED.value + assert json.loads(replay["Result"]) == { + "type": f"{DurableOperationError.__module__}.{DurableOperationError.__qualname__}", + "message": "boom", + "data": None, + "stack_trace": None, + } + + +def _rejecting_checkpoint(message: str): + """Checkpoint mock that rejects a DISTRIBUTED_MAP start the way the service does. + + It raises the CheckpointError that LambdaClient builds from a 400 + InvalidParameterValueException, so everything after that point is the real + path: the checkpoint thread wraps it in BackgroundThreadError and the + invocation handler decides the outcome. + """ + calls: list = [] + rejection = CheckpointError.from_exception( + ClientError( + { + "Error": { + "Code": "InvalidParameterValueException", + "Message": message, + }, + "ResponseMetadata": { + "RequestId": "req-1", + "HostId": "", + "HTTPStatusCode": 400, + "HTTPHeaders": {}, + "RetryAttempts": 0, + }, + }, + "CheckpointDurableExecution", + ) + ) + + def mock_checkpoint( + durable_execution_arn, checkpoint_token, updates, client_token="token" + ): # noqa: S107 + calls.append(updates) + if any(u.operation_type is OperationType.DISTRIBUTED_MAP for u in updates): + raise rejection + return CheckpointOutput( + checkpoint_token="new_token", # noqa: S106 + new_execution_state=CheckpointUpdatedExecutionState(operations=[]), + ) + + return calls, mock_checkpoint + + +def test_start_rejected_by_the_service_fails_the_execution(): + """A rejected START fails the execution, as a rejected checkpoint does anywhere. + + The SDK does not turn the rejection into a ValidationError. The failure is + raised on the checkpoint thread, so customer code cannot catch it, and the + invocation reports FAILED carrying the service's message. + """ + message = "Source.MaxItemsToRead is out of range" + caught: list = [] + + @durable_execution + def handler(event, context: DurableContext) -> dict[str, Any]: + try: + context.distributed_map( + ["a"], + DistributedMapProcessor.report_batch_outcome("proc"), + max_concurrency=1, + ) + except Exception as exc: # noqa: BLE001 + caught.append(type(exc).__name__) + return {"reached_the_end": True} + + with patch( + "aws_durable_execution_sdk_python.execution.LambdaClient" + ) as mock_client_class: + mock_client = Mock() + mock_client_class.initialize_client.return_value = mock_client + calls, mock_checkpoint = _rejecting_checkpoint(message) + mock_client.checkpoint = mock_checkpoint + result = handler(_initial_event(), _lambda_context()) + + assert result["Status"] == InvocationStatus.FAILED.value + assert message in result["Error"]["ErrorMessage"] + assert caught == [] + # One request was sent, carrying the rejected START. Nothing was recorded. + assert len(calls) == 1 + assert [u.operation_type for u in calls[0]] == [OperationType.DISTRIBUTED_MAP] + + +def test_configuration_the_sdk_rejects_itself_stays_catchable(): + """A configuration error the SDK finds is a catchable ValidationError. + + The SDK validates what it can before checkpointing, so the error is raised + at the call site with nothing sent. Customer code catches it and the + invocation carries on to a later durable operation. + """ + + @durable_step + def finish(_step_context: StepContext) -> str: + return "done" + + @durable_execution + def handler(event, context: DurableContext) -> dict[str, Any]: + caught = None + try: + context.distributed_map( + ["a"], + DistributedMapProcessor.report_batch_outcome("proc"), + max_concurrency=0, + ) + except ValidationError as exc: + caught = str(exc) + return {"caught": caught, "stepped": context.step(finish())} + + result = _run(handler, _initial_event()) + + assert result["Status"] == InvocationStatus.SUCCEEDED.value + data = json.loads(result["Result"]) + assert "max_concurrency must be greater than zero" in data["caught"] + assert data["stepped"] == "done" + + +def test_filesystem_serdes_keeps_every_item_from_parent_to_processor_and_back( + tmp_path, +): + """Every inline item and output survives FileSystemSerDes on its own key. + + The local runner does not run distributed maps, so the test plays the + service: it hands the START items to the processor and its outputs back. + """ + fs = FileSystemSerDes(str(tmp_path)) + + @durable_execution + def handler(event, context: DurableContext) -> list[Any]: + result: DistributedMapResult[Any] = context.distributed_map( + DistributedMapSource.inline(["a", "b", "c"], serdes=fs), + DistributedMapProcessor.report_item_outcomes("proc"), + max_concurrency=1, + config=DistributedMapResultConfig(result_serdes=fs), + ) + return result.get_results() + + with patch( + "aws_durable_execution_sdk_python.execution.LambdaClient" + ) as mock_client_class: + mock_client = Mock() + mock_client_class.initialize_client.return_value = mock_client + calls, mock_client.checkpoint = _tracking_checkpoint() + first = handler(_initial_event(), _lambda_context()) + assert first["Status"] == InvocationStatus.PENDING.value + (start,) = [u for batch in calls for u in batch] + items = start.to_dict()["DistributedMapOptions"]["Source"]["InlineSourceConfig"][ + "Items" + ] + + records = [{"itemId": str(i), "body": body} for i, body in enumerate(items)] + response = process_distributed_map_items( + {"distributedMapRunArn": _RUN_ARN, "records": records}, + lambda item, _ctx: item.upper(), + item_serdes=fs, + result_serdes=fs, + ) + + _map_run_id, replay_event = _replay_event( + { + "DistributedMapRunArn": _RUN_ARN, + "SourceExhausted": True, + "SuccessCount": 3, + "FailureCount": 0, + "ReadCount": 3, + "TotalCount": 3, + "Results": [ + { + "ItemId": r["itemIdentifier"], + "Status": "SUCCEEDED", + "Output": r["output"], + } + for r in response["batchItemResults"] + ], + } + ) + replay = _run(handler, replay_event) + assert replay["Status"] == InvocationStatus.SUCCEEDED.value + assert json.loads(replay["Result"]) == ["A", "B", "C"] diff --git a/packages/aws-durable-execution-sdk-python/tests/exceptions_test.py b/packages/aws-durable-execution-sdk-python/tests/exceptions_test.py index 540f09fa5..ef1a9288e 100644 --- a/packages/aws-durable-execution-sdk-python/tests/exceptions_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/exceptions_test.py @@ -16,6 +16,7 @@ ChildContextError, CheckpointError, CheckpointErrorCategory, + DistributedMapError, DurableApiErrorCategory, DurableExecutionsError, DurableOperationError, @@ -257,6 +258,7 @@ def test_durable_operation_error_with_none_message(): [ StepError, InvokeError, + DistributedMapError, ChildContextError, WaitForConditionError, CallbackError, @@ -279,6 +281,10 @@ def test_operation_error_registry_contains_all_subclasses(): mod: str = "aws_durable_execution_sdk_python.exceptions" assert _DURABLE_OPERATION_ERROR_REGISTRY[f"{mod}.StepError"] is StepError assert _DURABLE_OPERATION_ERROR_REGISTRY[f"{mod}.InvokeError"] is InvokeError + assert ( + _DURABLE_OPERATION_ERROR_REGISTRY[f"{mod}.DistributedMapError"] + is DistributedMapError + ) assert ( _DURABLE_OPERATION_ERROR_REGISTRY[f"{mod}.ChildContextError"] is ChildContextError diff --git a/packages/aws-durable-execution-sdk-python/tests/lambda_service_test.py b/packages/aws-durable-execution-sdk-python/tests/lambda_service_test.py index 975d5302a..8a81d128b 100644 --- a/packages/aws-durable-execution-sdk-python/tests/lambda_service_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/lambda_service_test.py @@ -10,9 +10,12 @@ import pytest from aws_durable_execution_sdk_python.__about__ import __version__ +from aws_durable_execution_sdk_python.config import DistributedMapItemStatus from aws_durable_execution_sdk_python.exceptions import ( CheckpointError, + DistributedMapError, DurableOperationError, + ExecutionError, GetExecutionStateError, SerDesError, StepError, @@ -48,6 +51,10 @@ _is_bundled, _user_agent_version, ) +from aws_durable_execution_sdk_python.lambda_service import ( + DistributedMapDetails, + DistributedMapResultItem, +) # ============================================================================= @@ -291,6 +298,17 @@ def test_error_object_to_durable_operation_error_reconstructs_subclass(): assert operation_error.stack_trace == ["line1"] +def test_distributed_map_error_reconstructs_across_boundary(): + """A DistributedMapError round-trips through error-field reconstruction.""" + original = DistributedMapError("m", data="d", stack_trace=["s"]) + reconstructed = ErrorObject.from_exception(original).to_durable_operation_error() + assert type(reconstructed) is DistributedMapError + assert reconstructed.message == "m" + assert reconstructed.error_type == original.error_type + assert reconstructed.data == "d" + assert reconstructed.stack_trace == ["s"] + + def test_error_object_to_durable_operation_error_unknown_type_falls_back(): """An unknown discriminator falls back to the base DurableOperationError.""" error = ErrorObject( @@ -385,6 +403,8 @@ def test_step_details_minimal(): (StepDetails, {}), (ContextDetails, {}), (ChainedInvokeDetails, {}), + (DistributedMapDetails, {}), + (DistributedMapResultItem, {"ItemId": "0", "Status": "FAILED"}), ], ) @pytest.mark.parametrize( @@ -409,7 +429,12 @@ def test_step_details_minimal(): ) def test_operation_details_preserve_error_presence( details_type: type[ - CallbackDetails | StepDetails | ContextDetails | ChainedInvokeDetails + CallbackDetails + | StepDetails + | ContextDetails + | ChainedInvokeDetails + | DistributedMapDetails + | DistributedMapResultItem ], required_fields: dict[str, Any], error_field: dict[str, Any], @@ -434,13 +459,35 @@ def test_operation_details_preserve_error_presence( "chained_invoke_details", ChainedInvokeDetails(), ), + ( + OperationType.DISTRIBUTED_MAP, + "distributed_map_details", + DistributedMapDetails( + success_count=0, + failure_count=1, + read_count=1, + results=[ + DistributedMapResultItem( + item_id="0", + status=DistributedMapItemStatus.FAILED, + error=ErrorObject( + message=None, type=None, data=None, stack_trace=None + ), + ) + ], + ), + ), ], ) @pytest.mark.parametrize("json_roundtrip", [False, True]) def test_operation_roundtrip_preserves_empty_error( operation_type: OperationType, details_field: str, - details: CallbackDetails | StepDetails | ContextDetails | ChainedInvokeDetails, + details: CallbackDetails + | StepDetails + | ContextDetails + | ChainedInvokeDetails + | DistributedMapDetails, json_roundtrip: bool, ) -> None: error = ErrorObject(message=None, type=None, data=None, stack_trace=None) @@ -1433,6 +1480,67 @@ def test_operation_from_dict_no_options(): assert operation.operation_id == "test-id" +def test_operation_from_dict_in_flight_distributed_map_details_parsed_without_status(): + """In-flight DistributedMapDetails (no SourceExhausted) parses without raising.""" + data = { + "Id": "dmap-id", + "Type": "DISTRIBUTED_MAP", + "Status": "STARTED", + "DistributedMapDetails": { + "TotalCount": 3, + "SuccessCount": 1, + }, + } + operation = Operation.from_dict(data) + assert operation.distributed_map_details is not None + assert operation.distributed_map_details.source_exhausted is None + assert operation.distributed_map_details.error is None + assert operation.distributed_map_details.total_count == 3 + assert operation.distributed_map_details.success_count == 1 + + +def test_operation_from_dict_terminal_distributed_map_details_parsed(): + """Terminal DistributedMapDetails parses into distributed_map_details.""" + data = { + "Id": "dmap-id", + "Type": "DISTRIBUTED_MAP", + "Status": "SUCCEEDED", + "DistributedMapDetails": { + "SourceExhausted": True, + "TotalCount": 3, + "SuccessCount": 3, + }, + } + operation = Operation.from_dict(data) + assert operation.distributed_map_details is not None + assert operation.distributed_map_details.source_exhausted is True + + +def test_operation_round_trip_keeps_empty_distributed_map_details(): + """An empty DistributedMapDetails object survives from_dict and to_dict.""" + data = { + "Id": "dmap-id", + "Type": "DISTRIBUTED_MAP", + "Status": "PENDING", + "DistributedMapDetails": {}, + } + operation = Operation.from_dict(data) + assert operation.distributed_map_details == DistributedMapDetails() + assert operation.to_dict()["DistributedMapDetails"] == {} + + +def test_operation_from_dict_absent_distributed_map_details_stays_none(): + """An absent DistributedMapDetails key leaves the field None.""" + data = { + "Id": "dmap-id", + "Type": "DISTRIBUTED_MAP", + "Status": "PENDING", + } + operation = Operation.from_dict(data) + assert operation.distributed_map_details is None + assert "DistributedMapDetails" not in operation.to_dict() + + def test_operation_from_dict_individual_options(): """Test Operation.from_dict with each option type individually.""" # Test with just ContextOptions @@ -3297,3 +3405,128 @@ def test_create_context_succeed_rejects_the_removed_positional_sub_type(): # endregion subtypes + + +# ========================================================================== +# Distributed map wire round-trips +# ========================================================================== + + +def test_map_run_details_from_dict_parses_results(): + data = { + "Status": "SUCCEEDED", + "SourceExhausted": True, + "SuccessCount": 1, + "FailureCount": 1, + "ReadCount": 2, + "TotalCount": 2, + "DistributedMapRunArn": "arn:aws:lambda:us-east-1:123456789012:map-run:x", + "Results": [ + {"ItemId": "0", "Status": "SUCCEEDED", "Output": 5}, + { + "ItemId": "1", + "Status": "FAILED", + "Error": {"ErrorType": "E", "ErrorMessage": "boom"}, + }, + ], + } + details = DistributedMapDetails.from_dict(data) + assert details.total_count == 2 + assert details.source_exhausted is True + assert details.results is not None + assert details.results[0].item_id == "0" + assert details.results[1].error is not None + assert details.results[1].error.type == "E" + + +def test_details_missing_source_exhausted_parses_with_none(): + # In-flight runs omit SourceExhausted, so parsing must succeed with None. + details = DistributedMapDetails.from_dict({"SuccessCount": 2}) + assert details.source_exhausted is None + assert details.success_count == 2 + + +def test_details_parses_the_run_level_error(): + """The run-level Error parses into the shared ErrorObject with every member.""" + details = DistributedMapDetails.from_dict( + { + "SourceExhausted": False, + "Error": { + "ErrorType": "SourceFailure", + "ErrorMessage": "boom", + "ErrorData": "d", + "StackTrace": ["line"], + }, + } + ) + assert details.error is not None + assert details.error.type == "SourceFailure" + assert details.error.message == "boom" + assert details.error.data == "d" + assert details.error.stack_trace == ["line"] + + +def test_result_item_wire_round_trip(): + item = DistributedMapResultItem.from_dict( + {"ItemId": "0", "Status": "SUCCEEDED", "Output": {"x": 1}} + ) + assert item.output == {"x": 1} + assert item.to_dict() == {"ItemId": "0", "Status": "SUCCEEDED", "Output": {"x": 1}} + + failed = DistributedMapResultItem.from_dict( + { + "ItemId": "1", + "Status": "FAILED", + "Error": {"ErrorType": "E", "ErrorMessage": "boom"}, + } + ) + dumped = failed.to_dict() + assert dumped["Error"]["ErrorType"] == "E" + assert "Output" not in dumped + + +def test_result_item_unknown_status_maps_to_unknown_to_sdk_version(): + """A status added after this SDK version parses, and the other items are kept.""" + details = DistributedMapDetails.from_dict( + { + "SourceExhausted": True, + "Results": [ + {"ItemId": "0", "Status": "SUCCEEDED", "Output": "1"}, + {"ItemId": "1", "Status": "PARTIALLY_SUCCEEDED"}, + { + "ItemId": "2", + "Status": "FAILED", + "Error": {"ErrorType": "E", "ErrorMessage": "boom"}, + }, + ], + } + ) + + assert details.results is not None + assert [item.status for item in details.results] == [ + DistributedMapItemStatus.SUCCEEDED, + DistributedMapItemStatus.UNKNOWN_TO_SDK_VERSION, + DistributedMapItemStatus.FAILED, + ] + + +def test_result_item_missing_status_raises(): + """Status is required, so its absence breaks the contract.""" + with pytest.raises(ExecutionError, match="carried no item status"): + DistributedMapResultItem.from_dict({"ItemId": "0", "Output": "1"}) + + +def test_result_item_missing_item_id_raises(): + """ItemId is required, so a result the customer cannot match to an item fails.""" + with pytest.raises( + ExecutionError, match="missing distributed map item id from backend" + ): + DistributedMapResultItem.from_dict({"Status": "SUCCEEDED", "Output": "1"}) + + +def test_result_item_empty_item_id_raises(): + """An empty item id identifies no item, so it is rejected like an absent one.""" + with pytest.raises( + ExecutionError, match="missing distributed map item id from backend" + ): + DistributedMapResultItem.from_dict({"ItemId": "", "Status": "SUCCEEDED"}) diff --git a/packages/aws-durable-execution-sdk-python/tests/operation/dmap_test.py b/packages/aws-durable-execution-sdk-python/tests/operation/dmap_test.py new file mode 100644 index 000000000..049f56148 --- /dev/null +++ b/packages/aws-durable-execution-sdk-python/tests/operation/dmap_test.py @@ -0,0 +1,1781 @@ +"""Unit tests for map run handler.""" + +from __future__ import annotations + +import json +from unittest.mock import Mock, patch + +import pytest + +from aws_durable_execution_sdk_python.dmap.models import ( + DistributedMapResult, + DistributedMapSummary, +) +from aws_durable_execution_sdk_python.config import ( + Duration, + DistributedMapItemStatus, + DistributedMapStatus, + DistributedMapCompletionConfig, + DistributedMapConfig, + DistributedMapResultConfig, + DistributedMapCsvDelimiter, + DistributedMapDestination, + DistributedMapDestinationConfig, + DistributedMapSource, + DistributedMapProcessor, + DistributedMapProcessorRetryConfig, +) +from aws_durable_execution_sdk_python.exceptions import ( + ExecutionError, + DistributedMapError, + NonDeterministicExecutionError, + SuspendExecution, +) +from aws_durable_execution_sdk_python.identifier import OperationIdentifier +from aws_durable_execution_sdk_python.lambda_service import ( + ErrorObject, + DistributedMapDetails, + DistributedMapFunctionResponseType, + DistributedMapOptions, + DistributedMapResultCollectionMode, + DistributedMapResultItem as DistributedMapResultItemApi, + DistributedMapSourceType, + Operation, + OperationAction, + OperationStatus, + OperationSubType, + OperationType, +) +from aws_durable_execution_sdk_python.operation.dmap import ( + DistributedMapOperationExecutor, +) +from aws_durable_execution_sdk_python.dmap.helpers import process_distributed_map_items +from aws_durable_execution_sdk_python.filesystem_serdes import FileSystemSerDes +from aws_durable_execution_sdk_python.serdes import SerDes, SerDesContext +from aws_durable_execution_sdk_python.state import CheckpointedResult, ExecutionState + +_RUN_ARN = ( + "arn:aws:lambda:us-east-1:123456789012:function:fn:$LATEST" + "/durable-execution/exec1/invoke1/distributed-map-run/abc" +) + + +# Test helper - wraps DistributedMapOperationExecutor with a simple handler signature. +def distributed_map_handler( + source, processor, max_concurrency, state, operation_identifier, config=None +): + """Test helper that wraps DistributedMapOperationExecutor and runs it. + + ``processor`` may be a function-name string (wrapped as a batch-outcome + processor) or an already-built DistributedMapProcessor. + """ + if not config: + config = DistributedMapConfig() + if isinstance(processor, str): + processor = DistributedMapProcessor.report_batch_outcome(processor) + executor = DistributedMapOperationExecutor( + source=source, + processor=processor, + max_concurrency=max_concurrency, + state=state, + operation_identifier=operation_identifier, + config=config, + ) + return executor.process() + + +def _identifier( + operation_id: str, name: str | None = "test_map_run" +) -> OperationIdentifier: + return OperationIdentifier( + operation_id, + OperationSubType.DISTRIBUTED_MAP, + None, + name, + operation_type=OperationType.DISTRIBUTED_MAP, + ) + + +def test_map_run_handler_already_succeeded(): + """Test distributed_map_handler returns a summary when the operation already succeeded.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + + operation = Operation( + operation_id="mr1", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.SUCCEEDED, + distributed_map_details=DistributedMapDetails( + source_exhausted=True, + success_count=5, + failure_count=0, + read_count=5, + total_count=5, + distributed_map_run_arn="arn:aws:lambda:us-east-1:123456789012:function:fn:$LATEST/durable-execution/exec1/invoke1/distributed-map-run/abc", + ), + ) + mock_state.get_checkpoint_result.return_value = ( + CheckpointedResult.create_from_operation(operation) + ) + + result = distributed_map_handler( + source=["a", "b"], + processor="test_processor", + max_concurrency=10, + state=mock_state, + operation_identifier=_identifier("mr1"), + ) + + assert result.status is DistributedMapStatus.SUCCEEDED + assert result.source_exhausted is True + assert result.error is None + assert result.success_count == 5 + assert result.failure_count == 0 + assert result.total_count == 5 + assert result.distributed_map_run_arn.endswith("/distributed-map-run/abc") + mock_state.create_checkpoint.assert_not_called() + + +def test_map_run_handler_resolves_non_success_without_raising(): + """Test a non-SUCCEEDED run resolves with a summary rather than raising. + + The run failed, so distributed_map must still return the summary carrying + the counts and let the caller opt into raising. + """ + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + + operation = Operation( + operation_id="mr2", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.FAILED, + distributed_map_details=DistributedMapDetails( + source_exhausted=False, + error=ErrorObject( + message="failure tolerance exceeded", + type="DistributedMapFailure", + data=None, + stack_trace=None, + ), + success_count=3, + failure_count=2, + read_count=6, + distributed_map_run_arn="arn:aws:lambda:us-east-1:123456789012:function:fn:$LATEST/durable-execution/exec1/invoke1/distributed-map-run/abc", + ), + ) + mock_state.get_checkpoint_result.return_value = ( + CheckpointedResult.create_from_operation(operation) + ) + + result = distributed_map_handler( + source=["a"], + processor="test_processor", + max_concurrency=10, + state=mock_state, + operation_identifier=_identifier("mr2"), + ) + + assert result.status is DistributedMapStatus.FAILED + assert result.source_exhausted is False + assert result.error is not None + assert result.error.message == "failure tolerance exceeded" + assert result.failure_count == 2 + assert result.has_failure is True + + +def test_map_run_handler_succeeded_no_details_raises(): + """Test a succeeded operation carrying no DistributedMapDetails raises ExecutionError.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + + operation = Operation( + operation_id="mr3", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.SUCCEEDED, + distributed_map_details=None, + ) + mock_state.get_checkpoint_result.return_value = ( + CheckpointedResult.create_from_operation(operation) + ) + + with pytest.raises(ExecutionError): + distributed_map_handler( + source=["a"], + processor="test_processor", + max_concurrency=10, + state=mock_state, + operation_identifier=_identifier("mr3"), + ) + + +def test_map_run_handler_already_started(): + """Test distributed_map_handler suspends when the operation is already started.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + + operation = Operation( + operation_id="mr5", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.STARTED, + ) + mock_state.get_checkpoint_result.return_value = ( + CheckpointedResult.create_from_operation(operation) + ) + + with pytest.raises( + SuspendExecution, match="Map run mr5 started, suspending for completion" + ): + distributed_map_handler( + source=["a"], + processor="test_processor", + max_concurrency=10, + state=mock_state, + operation_identifier=_identifier("mr5"), + ) + + +def test_map_run_handler_new_operation(): + """Test distributed_map_handler creates a START checkpoint for a new operation.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + + not_found = CheckpointedResult.create_not_found() + started_op = Operation( + operation_id="mr6", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.STARTED, + ) + started = CheckpointedResult.create_from_operation(started_op) + mock_state.get_checkpoint_result.side_effect = [not_found, started] + + with pytest.raises(SuspendExecution): + distributed_map_handler( + source=["a", "b", "c"], + processor="test_processor", + max_concurrency=42, + state=mock_state, + operation_identifier=_identifier("mr6"), + ) + + mock_state.create_checkpoint.assert_called_once() + operation_update = mock_state.create_checkpoint.call_args[1]["operation_update"] + assert operation_update.operation_id == "mr6" + assert operation_update.operation_type == OperationType.DISTRIBUTED_MAP + assert operation_update.action == OperationAction.START + assert operation_update.name == "test_map_run" + + distributed_map_options = operation_update.to_dict()["DistributedMapOptions"] + assert distributed_map_options["MaxConcurrency"] == 42 + assert distributed_map_options["Processor"]["FunctionName"] == "test_processor" + assert distributed_map_options["Source"]["InlineSourceConfig"]["Items"] == [ + '"a"', + '"b"', + '"c"', + ] + + +def test_map_run_handler_no_config(): + """Test distributed_map_handler uses a default config when none is provided.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + + not_found = CheckpointedResult.create_not_found() + started_op = Operation( + operation_id="mr7", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.STARTED, + ) + started = CheckpointedResult.create_from_operation(started_op) + mock_state.get_checkpoint_result.side_effect = [not_found, started] + + with pytest.raises(SuspendExecution): + distributed_map_handler( + source=["a"], + processor="test_processor", + max_concurrency=10, + state=mock_state, + operation_identifier=_identifier("mr7"), + config=None, + ) + + mock_state.create_checkpoint.assert_called_once() + + +# Immediate Response Handling Tests +# ============================================================================ + + +def test_map_run_immediate_response_get_checkpoint_result_called_twice(): + """Test get_checkpoint_result is called twice when a checkpoint is created.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + + not_found = CheckpointedResult.create_not_found() + started_op = Operation( + operation_id="mr8", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.STARTED, + ) + started = CheckpointedResult.create_from_operation(started_op) + mock_state.get_checkpoint_result.side_effect = [not_found, started] + + with pytest.raises(SuspendExecution): + distributed_map_handler( + source=["a"], + processor="test_processor", + max_concurrency=10, + state=mock_state, + operation_identifier=_identifier("mr8"), + ) + + assert mock_state.get_checkpoint_result.call_count == 2 + + +def test_map_run_immediate_response_create_checkpoint_is_sync_true(): + """Test create_checkpoint is called with is_sync=True.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + + not_found = CheckpointedResult.create_not_found() + started_op = Operation( + operation_id="mr9", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.STARTED, + ) + started = CheckpointedResult.create_from_operation(started_op) + mock_state.get_checkpoint_result.side_effect = [not_found, started] + + with pytest.raises(SuspendExecution): + distributed_map_handler( + source=["a"], + processor="test_processor", + max_concurrency=10, + state=mock_state, + operation_identifier=_identifier("mr9"), + ) + + mock_state.create_checkpoint.assert_called_once() + assert mock_state.create_checkpoint.call_args[1]["is_sync"] is True + + +def test_map_run_immediate_response_immediate_success(): + """Test immediate success: second check returns SUCCEEDED, summary returned.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + + not_found = CheckpointedResult.create_not_found() + succeeded_op = Operation( + operation_id="mr10", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.SUCCEEDED, + distributed_map_details=DistributedMapDetails( + source_exhausted=True, + success_count=1, + failure_count=0, + read_count=1, + total_count=1, + ), + ) + succeeded = CheckpointedResult.create_from_operation(succeeded_op) + mock_state.get_checkpoint_result.side_effect = [not_found, succeeded] + + result = distributed_map_handler( + source=["a"], + processor="test_processor", + max_concurrency=10, + state=mock_state, + operation_identifier=_identifier("mr10"), + ) + + assert result.status is DistributedMapStatus.SUCCEEDED + assert result.success_count == 1 + mock_state.create_checkpoint.assert_called_once() + assert mock_state.get_checkpoint_result.call_count == 2 + + +def test_map_run_immediate_response_no_immediate_response(): + """Test no immediate response: second check returns STARTED, suspends.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + + not_found = CheckpointedResult.create_not_found() + started_op = Operation( + operation_id="mr12", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.STARTED, + ) + started = CheckpointedResult.create_from_operation(started_op) + mock_state.get_checkpoint_result.side_effect = [not_found, started] + + with pytest.raises(SuspendExecution): + distributed_map_handler( + source=["a"], + processor="test_processor", + max_concurrency=10, + state=mock_state, + operation_identifier=_identifier("mr12"), + ) + + mock_state.create_checkpoint.assert_called_once() + assert mock_state.get_checkpoint_result.call_count == 2 + + +def test_map_run_immediate_response_already_completed(): + """Test already completed: first check is SUCCEEDED, no checkpoint created.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + + succeeded_op = Operation( + operation_id="mr13", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.SUCCEEDED, + distributed_map_details=DistributedMapDetails( + source_exhausted=True, + success_count=1, + failure_count=0, + read_count=1, + total_count=1, + ), + ) + mock_state.get_checkpoint_result.return_value = ( + CheckpointedResult.create_from_operation(succeeded_op) + ) + + result = distributed_map_handler( + source=["a"], + processor="test_processor", + max_concurrency=10, + state=mock_state, + operation_identifier=_identifier("mr13"), + ) + + assert result.status is DistributedMapStatus.SUCCEEDED + mock_state.create_checkpoint.assert_not_called() + assert mock_state.get_checkpoint_result.call_count == 1 + + +@patch( + "aws_durable_execution_sdk_python.operation.dmap.suspend_with_optional_resume_delay" +) +def test_map_run_handler_suspend_does_not_raise(mock_suspend): + """Test distributed_map_handler raises ExecutionError if suspend does not raise.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + + not_found = CheckpointedResult.create_not_found() + started_op = Operation( + operation_id="mr14", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.STARTED, + ) + started = CheckpointedResult.create_from_operation(started_op) + mock_state.get_checkpoint_result.side_effect = [not_found, started] + + mock_suspend.return_value = None + + with pytest.raises( + ExecutionError, + match="suspend_with_optional_resume_delay should have raised an exception, but did not.", + ): + distributed_map_handler( + source=["a"], + processor="test_processor", + max_concurrency=10, + state=mock_state, + operation_identifier=_identifier("mr14"), + ) + + mock_suspend.assert_called_once() + + +# Serialization and result-collection tests +# ============================================================================ + + +def _start_options(state_calls, source, processor, max_concurrency, config): + """Run the executor through the new-operation path and return the sent options dict.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + mock_state.get_checkpoint_result.side_effect = state_calls + + executor = DistributedMapOperationExecutor( + source=source, + processor=processor, + max_concurrency=max_concurrency, + state=mock_state, + operation_identifier=_identifier("mrw"), + config=config, + ) + with pytest.raises(SuspendExecution): + executor.process() + update = mock_state.create_checkpoint.call_args[1]["operation_update"] + return update.to_dict()["DistributedMapOptions"] + + +def _new_op_state_calls(): + not_found = CheckpointedResult.create_not_found() + started = CheckpointedResult.create_from_operation( + Operation( + operation_id="mrw", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.STARTED, + ) + ) + return [not_found, started] + + +def test_processor_item_outcomes_sets_response_types(): + """report_item_outcomes serializes FunctionResponseTypes=REPORT_BATCH_ITEM_OUTCOMES.""" + options = _start_options( + _new_op_state_calls(), + source=["a"], + processor=DistributedMapProcessor.report_item_outcomes("proc", batch_size=25), + max_concurrency=4, + config=DistributedMapConfig(), + ) + processor = options["Processor"] + assert processor["FunctionName"] == "proc" + assert processor["FunctionResponseTypes"] == ["REPORT_BATCH_ITEM_OUTCOMES"] + assert processor["BatchSize"] == 25 + + +def test_processor_batch_outcome_sets_no_response_types(): + """report_batch_outcome omits FunctionResponseTypes, selecting default batch mode.""" + options = _start_options( + _new_op_state_calls(), + source=["a"], + processor=DistributedMapProcessor.report_batch_outcome("proc"), + max_concurrency=4, + config=DistributedMapConfig(), + ) + assert "FunctionResponseTypes" not in options["Processor"] + + +def test_processor_unlimited_retries_maps_to_negative_one(): + """DistributedMapProcessorRetryConfig.UNLIMITED serializes to MaxRetryAttempts=-1.""" + options = _start_options( + _new_op_state_calls(), + source=["a"], + processor=DistributedMapProcessor.report_item_outcomes( + "proc", + retry=DistributedMapProcessorRetryConfig( + max_retry_attempts=DistributedMapProcessorRetryConfig.UNLIMITED, + max_retry_duration=Duration.from_hours(1), + ), + ), + max_concurrency=1, + config=DistributedMapConfig(), + ) + processor = options["Processor"] + assert processor["FunctionResponseTypes"] == ["REPORT_BATCH_ITEM_OUTCOMES"] + assert processor["MaxRetryAttempts"] == -1 + assert processor["MaxRetryDurationSeconds"] == 3600 + + +def test_processor_explicit_retry_attempts_pass_through(): + """A plain int retry count passes through unchanged (no sentinel mapping).""" + options = _start_options( + _new_op_state_calls(), + source=["a"], + processor=DistributedMapProcessor.report_batch_outcome( + "proc", retry=DistributedMapProcessorRetryConfig(max_retry_attempts=0) + ), + max_concurrency=1, + config=DistributedMapConfig(), + ) + assert options["Processor"]["MaxRetryAttempts"] == 0 + # batch mode reports no per-item response types + assert "FunctionResponseTypes" not in options["Processor"] + + +def test_s3_source_serializes_config(): + """An S3 json_lines source serializes to an S3SourceConfig block.""" + options = _start_options( + _new_op_state_calls(), + source=DistributedMapSource.s3_json_lines( + "s3://bucket/data.jsonl", max_items=500 + ), + processor=DistributedMapProcessor.report_batch_outcome("proc"), + max_concurrency=2, + config=DistributedMapConfig(), + ) + source = options["Source"] + assert source["Type"] == "S3" + assert source["MaxItemsToRead"] == 500 + s3 = source["S3SourceConfig"] + assert s3["Type"] == "OBJECT" + assert s3["Bucket"] == "bucket" + assert s3["ObjectConfig"]["Key"] == "data.jsonl" + assert s3["ObjectConfig"]["Format"] == "JSON_LINES" + assert "ListedObjectMetadataConfig" not in s3 + assert "ListedObjectsConfig" not in s3 + + +def test_full_config_serializes_all_blocks(): + """Completion, destination, timeout, and result-collection blocks all serialize.""" + config = DistributedMapResultConfig( + completion_config=DistributedMapCompletionConfig.failure_percentage( + 5, minimum_sample_size=200 + ), + destination=DistributedMapDestinationConfig( + on_success=DistributedMapDestination.s3_successes("s3://out/ok"), + on_failure=DistributedMapDestination.s3_failures("s3://out/bad"), + ), + timeout=Duration.from_minutes(30), + ) + options = _start_options( + _new_op_state_calls(), + source=["a"], + processor=DistributedMapProcessor.report_item_outcomes("proc"), + max_concurrency=8, + config=config, + ) + assert options["CompletionConfig"] == { + "ToleratedFailurePercentage": 5, + "MinimumSampleSize": 200, + } + on_success = options["Destination"]["OnSuccess"] + assert on_success["Type"] == "S3" + assert on_success["S3DestinationConfig"]["Bucket"] == "out" + assert on_success["S3DestinationConfig"]["KeyPrefix"] == "ok" + on_failure = options["Destination"]["OnFailure"] + assert on_failure["Include"] == ["INPUT", "ERROR"] + assert on_failure["S3DestinationConfig"]["Bucket"] == "out" + assert options["TimeoutSeconds"] == 1800 + assert options["ResultCollection"] == {"Mode": "INLINE"} + + +def test_result_config_returns_map_run_result_with_items(): + """With a DistributedMapResultConfig, a DistributedMapResult with per-item results is built.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + error = ErrorObject(message="boom", type="ItemError", data=None, stack_trace=None) + operation = Operation( + operation_id="mrr", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.SUCCEEDED, + distributed_map_details=DistributedMapDetails( + distributed_map_run_arn=_RUN_ARN, + source_exhausted=True, + success_count=1, + failure_count=1, + read_count=2, + total_count=2, + results=( + DistributedMapResultItemApi( + item_id="0", status=DistributedMapItemStatus.SUCCEEDED, output="42" + ), + DistributedMapResultItemApi( + item_id="1", status=DistributedMapItemStatus.FAILED, error=error + ), + ), + ), + ) + mock_state.get_checkpoint_result.return_value = ( + CheckpointedResult.create_from_operation(operation) + ) + + result = distributed_map_handler( + source=["a", "b"], + processor=DistributedMapProcessor.report_item_outcomes("proc"), + max_concurrency=2, + state=mock_state, + operation_identifier=_identifier("mrr"), + config=DistributedMapResultConfig(), + ) + + assert isinstance(result, DistributedMapResult) + assert len(result.all) == 2 + assert result.get_results() == [42] + errors = result.get_errors() + assert len(errors) == 1 + assert errors[0].type == "ItemError" + assert errors[0].message == "boom" + + +def test_item_error_keeps_every_error_member(): + """An item's error reaches the caller as the full ErrorObject, data and trace included.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + operation = Operation( + operation_id="mre", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.SUCCEEDED, + distributed_map_details=DistributedMapDetails( + source_exhausted=True, + success_count=0, + failure_count=1, + read_count=1, + total_count=1, + results=( + DistributedMapResultItemApi( + item_id="0", + status=DistributedMapItemStatus.FAILED, + error=ErrorObject( + message="boom", + type="ItemError", + data="payload", + stack_trace=["frame one", "frame two"], + ), + ), + ), + ), + ) + mock_state.get_checkpoint_result.return_value = ( + CheckpointedResult.create_from_operation(operation) + ) + + result = distributed_map_handler( + source=["a"], + processor=DistributedMapProcessor.report_item_outcomes("proc"), + max_concurrency=1, + state=mock_state, + operation_identifier=_identifier("mre"), + config=DistributedMapResultConfig(), + ) + + error = result.get_errors()[0] + assert error is not None + assert error.data == "payload" + assert error.stack_trace == ["frame one", "frame two"] + + # The raised item failure carries the same members. + with pytest.raises(DistributedMapError) as exc: + result.throw_if_error() + assert exc.value.error_type == "ItemError" + assert exc.value.data == "payload" + assert exc.value.stack_trace == ["frame one", "frame two"] + + +def test_item_error_members_absent_from_the_backend_stay_none(): + """An omitted error member stays None rather than becoming an empty string.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + operation = Operation( + operation_id="mren", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.SUCCEEDED, + distributed_map_details=DistributedMapDetails( + source_exhausted=True, + success_count=0, + failure_count=1, + read_count=1, + total_count=1, + results=( + DistributedMapResultItemApi( + item_id="0", + status=DistributedMapItemStatus.FAILED, + error=ErrorObject( + message=None, type=None, data=None, stack_trace=None + ), + ), + ), + ), + ) + mock_state.get_checkpoint_result.return_value = ( + CheckpointedResult.create_from_operation(operation) + ) + + result = distributed_map_handler( + source=["a"], + processor=DistributedMapProcessor.report_item_outcomes("proc"), + max_concurrency=1, + state=mock_state, + operation_identifier=_identifier("mren"), + config=DistributedMapResultConfig(), + ) + + error = result.get_errors()[0] + assert error is not None + assert error.type is None + assert error.message is None + + +def test_plain_config_returns_plain_summary(): + """With a plain DistributedMapConfig, a DistributedMapSummary is returned.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + operation = Operation( + operation_id="mrs", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.SUCCEEDED, + distributed_map_details=DistributedMapDetails( + source_exhausted=True, + success_count=2, + failure_count=0, + read_count=2, + total_count=2, + ), + ) + mock_state.get_checkpoint_result.return_value = ( + CheckpointedResult.create_from_operation(operation) + ) + + result = distributed_map_handler( + source=["a", "b"], + processor=DistributedMapProcessor.report_batch_outcome("proc"), + max_concurrency=2, + state=mock_state, + operation_identifier=_identifier("mrs"), + ) + + assert isinstance(result, DistributedMapSummary) + assert not isinstance(result, DistributedMapResult) + assert result.success_count == 2 + + +def test_csv_source_header_location(): + """Explicit headers map to GIVEN, omitting them maps to FIRST_ROW.""" + # headers -> HeaderLocation GIVEN, headers sent + given = _start_options( + _new_op_state_calls(), + source=DistributedMapSource.s3_csv("s3://b/data.csv", headers=["a", "b"]), + processor=DistributedMapProcessor.report_batch_outcome("proc"), + max_concurrency=1, + config=DistributedMapConfig(), + ) + csv_opts = given["Source"]["S3SourceConfig"]["ObjectConfig"]["CsvFormatOptions"] + assert csv_opts["HeaderLocation"] == "GIVEN" + assert csv_opts["Headers"] == ["a", "b"] + assert csv_opts["Delimiter"] == "COMMA" + + # no headers -> HeaderLocation FIRST_ROW + first_row = _start_options( + _new_op_state_calls(), + source=DistributedMapSource.s3_csv("s3://b/data.csv"), + processor=DistributedMapProcessor.report_batch_outcome("proc"), + max_concurrency=1, + config=DistributedMapConfig(), + ) + object_cfg = first_row["Source"]["S3SourceConfig"]["ObjectConfig"] + assert object_cfg["CsvFormatOptions"]["HeaderLocation"] == "FIRST_ROW" + assert "Headers" not in object_cfg["CsvFormatOptions"] + + +# Call-site validation and serdes tests +# ============================================================================ + + +def test_csv_delimiter_accepts_enum(): + opts = _start_options( + _new_op_state_calls(), + source=DistributedMapSource.s3_csv( + "s3://b/data.csv", delimiter=DistributedMapCsvDelimiter.PIPE + ), + processor=DistributedMapProcessor.report_batch_outcome("proc"), + max_concurrency=1, + config=DistributedMapConfig(), + ) + assert ( + opts["Source"]["S3SourceConfig"]["ObjectConfig"]["CsvFormatOptions"][ + "Delimiter" + ] + == "PIPE" + ) + + +def test_reader_state_serialized(): + # typed initial_state is serialized into the opaque state string + options = _start_options( + _new_op_state_calls(), + source=DistributedMapSource.reader_function( + "reader", initial_state={"page": 0} + ), + processor=DistributedMapProcessor.report_batch_outcome("proc"), + max_concurrency=1, + config=DistributedMapConfig(), + ) + reader_cfg = options["Source"]["ReaderFunctionSourceConfig"] + assert reader_cfg["FunctionName"] == "reader" + assert reader_cfg["InitialState"] == '{"page": 0}' + + +def test_inline_custom_serdes_applied_to_items(): + """A custom inline serdes transforms each item's serialized value.""" + from aws_durable_execution_sdk_python.serdes import SerDes + + class _UpperSerDes(SerDes): + def serialize(self, value, _serdes_context): # noqa: ANN001, ANN201 + return json.dumps(value.upper()) + + def deserialize(self, data, _serdes_context): # noqa: ANN001, ANN201 + return json.loads(data).lower() + + options = _start_options( + _new_op_state_calls(), + source=DistributedMapSource.inline(["a", "b"], serdes=_UpperSerDes()), + processor=DistributedMapProcessor.report_batch_outcome("proc"), + max_concurrency=1, + config=DistributedMapConfig(), + ) + assert options["Source"]["InlineSourceConfig"]["Items"] == ['"A"', '"B"'] + + +# Result helpers, from_dict, destinations, and source variants +# ============================================================================ + + +def test_map_run_options_from_dict_round_trip(): + sent = _start_options( + _new_op_state_calls(), + source=["a", "b"], + processor=DistributedMapProcessor.report_batch_outcome("proc"), + max_concurrency=7, + config=DistributedMapConfig(), + ) + parsed = DistributedMapOptions.from_dict(sent) + assert parsed.max_concurrency == 7 + assert parsed.source.source_type is DistributedMapSourceType.INLINE + assert parsed.processor.function_name == "proc" + + +def test_destination_only_success(): + opts = _start_options( + _new_op_state_calls(), + source=["a"], + processor=DistributedMapProcessor.report_batch_outcome("p"), + max_concurrency=1, + config=DistributedMapConfig( + destination=DistributedMapDestinationConfig( + on_success=DistributedMapDestination.s3_successes("s3://out/ok") + ) + ), + ) + dest = opts["Destination"] + assert "OnSuccess" in dest + assert "OnFailure" not in dest + + +def test_destination_only_failure(): + opts = _start_options( + _new_op_state_calls(), + source=["a"], + processor=DistributedMapProcessor.report_batch_outcome("p"), + max_concurrency=1, + config=DistributedMapConfig( + destination=DistributedMapDestinationConfig( + on_failure=DistributedMapDestination.s3_failures("s3://out/bad") + ) + ), + ) + dest = opts["Destination"] + assert "OnFailure" in dest + assert "OnSuccess" not in dest + + +def test_s3_objects_source_config(): + opts = _start_options( + _new_op_state_calls(), + source=DistributedMapSource.s3_objects("s3://b/prefix/"), + processor=DistributedMapProcessor.report_batch_outcome("p"), + max_concurrency=1, + config=DistributedMapConfig(), + ) + s3 = opts["Source"]["S3SourceConfig"] + assert s3["Type"] == "LISTED_OBJECT_METADATA" + assert s3["ListedObjectMetadataConfig"]["KeyPrefix"] == "prefix/" + assert "ObjectConfig" not in s3 + assert "ListedObjectsConfig" not in s3 + + +def test_s3_flattened_json_lines_source_config(): + opts = _start_options( + _new_op_state_calls(), + source=DistributedMapSource.s3_flattened_json_lines("s3://b/prefix/"), + processor=DistributedMapProcessor.report_batch_outcome("p"), + max_concurrency=1, + config=DistributedMapConfig(), + ) + s3 = opts["Source"]["S3SourceConfig"] + assert s3["Type"] == "LISTED_OBJECTS" + assert s3["ListedObjectsConfig"]["KeyPrefix"] == "prefix/" + assert s3["ListedObjectsConfig"]["Format"] == "JSON_LINES" + + +# Validations, config branches, and round-trips +# ============================================================================ + + +def _start_executor(source, processor, config, max_concurrency=1): + """Build an executor on the new-operation path (for error-path tests).""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + mock_state.get_checkpoint_result.side_effect = _new_op_state_calls() + return DistributedMapOperationExecutor( + source=source, + processor=processor, + max_concurrency=max_concurrency, + state=mock_state, + operation_identifier=_identifier("mrw"), + config=config, + ) + + +# --- Completion config translation --- + + +def test_completion_config_percentage_and_sample_size_sent(): + options = _start_options( + _new_op_state_calls(), + source=["a"], + processor=DistributedMapProcessor.report_batch_outcome("p"), + max_concurrency=1, + config=DistributedMapConfig( + completion_config=DistributedMapCompletionConfig.failure_percentage( + 25, minimum_sample_size=50 + ) + ), + ) + assert options["CompletionConfig"] == { + "ToleratedFailurePercentage": 25, + "MinimumSampleSize": 50, + } + + +# --- Source translation variants --- + + +def test_objects_whole_bucket_prefix_config(): + options = _start_options( + _new_op_state_calls(), + source=DistributedMapSource.s3_objects("s3://bucket"), + processor=DistributedMapProcessor.report_batch_outcome("p"), + max_concurrency=1, + config=DistributedMapConfig(), + ) + s3 = options["Source"]["S3SourceConfig"] + assert s3["Type"] == "LISTED_OBJECT_METADATA" + assert s3["ListedObjectMetadataConfig"]["KeyPrefix"] == "" + assert "ObjectConfig" not in s3 + + +def test_flattened_csv_source_config(): + options = _start_options( + _new_op_state_calls(), + source=DistributedMapSource.s3_flattened_csv( + "s3://b/prefix", headers=["a", "b"] + ), + processor=DistributedMapProcessor.report_batch_outcome("p"), + max_concurrency=1, + config=DistributedMapConfig(), + ) + listed = options["Source"]["S3SourceConfig"]["ListedObjectsConfig"] + assert listed["Format"] == "CSV" + assert listed["CsvFormatOptions"]["HeaderLocation"] == "GIVEN" + assert listed["CsvFormatOptions"]["Headers"] == ["a", "b"] + + +def test_reader_source_without_initial_state_omits_state(): + options = _start_options( + _new_op_state_calls(), + source=DistributedMapSource.reader_function("reader"), + processor=DistributedMapProcessor.report_batch_outcome("p"), + max_concurrency=1, + config=DistributedMapConfig(), + ) + reader = options["Source"]["ReaderFunctionSourceConfig"] + assert reader["FunctionName"] == "reader" + assert "InitialState" not in reader + + +def test_inline_non_json_serdes_supported(): + """Items are opaque strings, so a serdes need not produce JSON.""" + from aws_durable_execution_sdk_python.serdes import SerDes + + class _PlainTextSerDes(SerDes): + def serialize(self, value, _serdes_context): # noqa: ANN001, ANN201 + return f"item-{value}" + + def deserialize(self, data, _serdes_context): # noqa: ANN001, ANN201, ARG002 + return data + + options = _start_options( + _new_op_state_calls(), + source=DistributedMapSource.inline([1, 2], serdes=_PlainTextSerDes()), + processor=DistributedMapProcessor.report_batch_outcome("p"), + max_concurrency=1, + config=DistributedMapConfig(), + ) + assert options["Source"]["InlineSourceConfig"]["Items"] == ["item-1", "item-2"] + + +# --- Destination translation permutations --- + + +def test_success_destination_include_input_and_owner(): + options = _start_options( + _new_op_state_calls(), + source=["a"], + processor=DistributedMapProcessor.report_batch_outcome("p"), + max_concurrency=1, + config=DistributedMapConfig( + destination=DistributedMapDestinationConfig( + on_success=DistributedMapDestination.s3_successes( + "s3://out/ok", + include_input=True, + include_output=True, + expected_bucket_owner="123456789012", + ) + ) + ), + ) + on_success = options["Destination"]["OnSuccess"] + assert on_success["Include"] == ["INPUT", "OUTPUT"] + assert on_success["S3DestinationConfig"]["ExpectedBucketOwner"] == "123456789012" + assert "OnFailure" not in options["Destination"] + + +def test_failure_destination_error_only_and_owner(): + options = _start_options( + _new_op_state_calls(), + source=["a"], + processor=DistributedMapProcessor.report_batch_outcome("p"), + max_concurrency=1, + config=DistributedMapConfig( + destination=DistributedMapDestinationConfig( + on_failure=DistributedMapDestination.s3_failures( + "s3://out/bad", + include_input=False, + include_error=True, + expected_bucket_owner="123456789012", + ) + ) + ), + ) + on_failure = options["Destination"]["OnFailure"] + assert on_failure["Include"] == ["ERROR"] + assert on_failure["S3DestinationConfig"]["ExpectedBucketOwner"] == "123456789012" + + +# --- Operation round-trips through the checkpoint --- + + +def test_operation_to_dict_round_trip_preserves_results(): + op = Operation( + operation_id="opx", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.SUCCEEDED, + distributed_map_details=DistributedMapDetails( + source_exhausted=True, + success_count=1, + failure_count=1, + read_count=2, + total_count=2, + distributed_map_run_arn="arn:aws:lambda:us-east-1:123456789012:function:fn:$LATEST/durable-execution/exec1/invoke1/distributed-map-run/z", + error=ErrorObject( + message="tolerated", + type="DistributedMapFailure", + data=None, + stack_trace=None, + ), + results=( + DistributedMapResultItemApi( + item_id="0", status=DistributedMapItemStatus.SUCCEEDED, output=5 + ), + DistributedMapResultItemApi( + item_id="1", + status=DistributedMapItemStatus.FAILED, + error=ErrorObject( + message="boom", type="E", data=None, stack_trace=None + ), + ), + ), + ), + ) + block = op.to_dict()["DistributedMapDetails"] + assert block["Results"][0] == {"ItemId": "0", "Status": "SUCCEEDED", "Output": 5} + assert block["DistributedMapRunArn"].endswith("/distributed-map-run/z") + assert block["SourceExhausted"] is True + assert block["Error"]["ErrorType"] == "DistributedMapFailure" + assert block["TotalCount"] == 2 + + parsed = Operation.from_dict(op.to_dict()) + assert parsed.distributed_map_details is not None + assert parsed.distributed_map_details.source_exhausted is True + assert parsed.distributed_map_details.error.message == "tolerated" + assert parsed.distributed_map_details.results[0].output == 5 + assert parsed.distributed_map_details.results[1].error.type == "E" + + +def test_options_full_round_trip(): + options_dict = _start_options( + _new_op_state_calls(), + source=DistributedMapSource.s3_csv("s3://b/f.csv", headers=["a"]), + processor=DistributedMapProcessor.report_item_outcomes( + "proc", + batch_size=5, + retry=DistributedMapProcessorRetryConfig( + max_retry_attempts=DistributedMapProcessorRetryConfig.UNLIMITED, + max_retry_duration=Duration.from_minutes(10), + ), + durable_execution_name_prefix="pfx", + ), + max_concurrency=3, + config=DistributedMapResultConfig( + destination=DistributedMapDestinationConfig( + on_success=DistributedMapDestination.s3_successes("s3://o/ok"), + on_failure=DistributedMapDestination.s3_failures("s3://o/bad"), + ), + completion_config=DistributedMapCompletionConfig.failure_count(2), + timeout=Duration.from_minutes(5), + ), + ) + parsed = DistributedMapOptions.from_dict(options_dict) + assert parsed.max_concurrency == 3 + assert parsed.source.source_type is DistributedMapSourceType.S3 + assert parsed.processor.function_response_types == [ + DistributedMapFunctionResponseType.REPORT_BATCH_ITEM_OUTCOMES + ] + assert parsed.processor.max_retry_attempts == -1 + assert parsed.processor.durable_execution_name_prefix == "pfx" + assert parsed.destination is not None + assert parsed.completion_config.tolerated_failure_count == 2 + assert parsed.result_collection.mode is DistributedMapResultCollectionMode.INLINE + assert parsed.timeout_seconds == 300 + assert parsed.to_dict()["MaxConcurrency"] == 3 + + +# Remaining validation and config branches +# ============================================================================ + + +def test_csv_first_row_no_headers(): + options = _start_options( + _new_op_state_calls(), + source=DistributedMapSource.s3_csv("s3://b/f.csv"), + processor=DistributedMapProcessor.report_batch_outcome("p"), + max_concurrency=1, + config=DistributedMapConfig(), + ) + csv_opts = options["Source"]["S3SourceConfig"]["ObjectConfig"]["CsvFormatOptions"] + assert csv_opts["HeaderLocation"] == "FIRST_ROW" + assert "Headers" not in csv_opts + assert csv_opts["Delimiter"] == "COMMA" + + +def test_s3_source_expected_bucket_owner(): + options = _start_options( + _new_op_state_calls(), + source=DistributedMapSource.s3_json_lines( + "s3://b/k.jsonl", expected_bucket_owner="123456789012" + ), + processor=DistributedMapProcessor.report_batch_outcome("p"), + max_concurrency=1, + config=DistributedMapConfig(), + ) + assert options["Source"]["S3SourceConfig"]["ExpectedBucketOwner"] == "123456789012" + + +def test_empty_destination_config_omitted(): + options = _start_options( + _new_op_state_calls(), + source=["a"], + processor=DistributedMapProcessor.report_batch_outcome("p"), + max_concurrency=1, + config=DistributedMapConfig(destination=DistributedMapDestinationConfig()), + ) + assert "Destination" not in options + + +def test_success_destination_input_only(): + options = _start_options( + _new_op_state_calls(), + source=["a"], + processor=DistributedMapProcessor.report_batch_outcome("p"), + max_concurrency=1, + config=DistributedMapConfig( + destination=DistributedMapDestinationConfig( + on_success=DistributedMapDestination.s3_successes( + "s3://out/ok", include_input=True, include_output=False + ) + ) + ), + ) + assert options["Destination"]["OnSuccess"]["Include"] == ["INPUT"] + + +def test_failure_destination_input_only(): + options = _start_options( + _new_op_state_calls(), + source=["a"], + processor=DistributedMapProcessor.report_batch_outcome("p"), + max_concurrency=1, + config=DistributedMapConfig( + destination=DistributedMapDestinationConfig( + on_failure=DistributedMapDestination.s3_failures( + "s3://out/bad", include_input=True, include_error=False + ) + ) + ), + ) + assert options["Destination"]["OnFailure"]["Include"] == ["INPUT"] + + +def test_reader_source_options_round_trip(): + options_dict = _start_options( + _new_op_state_calls(), + source=DistributedMapSource.reader_function( + "reader", initial_state={"page": 0} + ), + processor=DistributedMapProcessor.report_batch_outcome("p"), + max_concurrency=1, + config=DistributedMapConfig(), + ) + parsed = DistributedMapOptions.from_dict(options_dict) + assert parsed.source.source_type is DistributedMapSourceType.READER_FUNCTION + assert parsed.source.reader_config is not None + assert parsed.source.reader_config.function_name == "reader" + + +def test_operation_to_dict_minimal_details_omits_optionals(): + op = Operation( + operation_id="opm", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.SUCCEEDED, + distributed_map_details=DistributedMapDetails( + source_exhausted=True, + success_count=1, + failure_count=0, + read_count=1, + ), + ) + block = op.to_dict()["DistributedMapDetails"] + assert "DistributedMapRunArn" not in block + assert "CompletionDetails" not in block + assert "TotalCount" not in block + assert "Results" not in block + + +@pytest.mark.parametrize( + "status", + [OperationStatus.FAILED, OperationStatus.STOPPED, OperationStatus.TIMED_OUT], +) +def test_operation_level_terminal_failure_without_details_raises(status): + """A terminal failure carrying no details raises, since counts cannot be built.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + operation = Operation( + operation_id="mrf", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=status, + ) + mock_state.get_checkpoint_result.return_value = ( + CheckpointedResult.create_from_operation(operation) + ) + with pytest.raises(ExecutionError): + distributed_map_handler( + source=["a"], + processor="p", + max_concurrency=1, + state=mock_state, + operation_identifier=_identifier("mrf"), + ) + + +@pytest.mark.parametrize( + ("status", "expected"), + [ + (OperationStatus.FAILED, DistributedMapStatus.FAILED), + (OperationStatus.TIMED_OUT, DistributedMapStatus.TIMED_OUT), + (OperationStatus.STOPPED, DistributedMapStatus.STOPPED), + ], +) +def test_terminal_failure_with_details_resolves_with_summary(status, expected): + """A terminal non-success run resolves with its summary rather than raising.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + operation = Operation( + operation_id="mrf", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=status, + distributed_map_details=DistributedMapDetails( + source_exhausted=False, + success_count=1, + failure_count=2, + read_count=3, + ), + ) + mock_state.get_checkpoint_result.return_value = ( + CheckpointedResult.create_from_operation(operation) + ) + summary = distributed_map_handler( + source=["a"], + processor="p", + max_concurrency=1, + state=mock_state, + operation_identifier=_identifier("mrf"), + ) + assert summary.status is expected + assert summary.failure_count == 2 + # The caller opts into raising rather than having it forced on them. + with pytest.raises(DistributedMapError): + summary.throw_if_error() + + +def test_terminal_without_source_exhausted_raises(): + """A terminal operation whose run exists but omits SourceExhausted is surfaced, not papered over.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + operation = Operation( + operation_id="mrf", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.STOPPED, + distributed_map_details=DistributedMapDetails( + distributed_map_run_arn="arn:aws:lambda:us-east-1:123456789012:function:fn:$LATEST/durable-execution/exec1/invoke1/distributed-map-run/abc", + success_count=0, + failure_count=0, + read_count=3, + ), + ) + mock_state.get_checkpoint_result.return_value = ( + CheckpointedResult.create_from_operation(operation) + ) + with pytest.raises(ExecutionError, match="carried no SourceExhausted"): + distributed_map_handler( + source=["a"], + processor="p", + max_concurrency=1, + state=mock_state, + operation_identifier=_identifier("mrf"), + ) + + +# Serdes decode, falsy output, and duration-only retry +# ============================================================================ + + +def test_custom_result_serdes_applied_on_decode(): + """A custom result_serdes transforms each per-item output on decode.""" + from aws_durable_execution_sdk_python.serdes import SerDes + + class _UpperSerDes(SerDes): + def serialize(self, value, _serdes_context): # noqa: ANN001, ANN201 + return json.dumps(value) + + def deserialize(self, data, _serdes_context): # noqa: ANN001, ANN201 + return json.loads(data).upper() + + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + operation = Operation( + operation_id="cs", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.SUCCEEDED, + distributed_map_details=DistributedMapDetails( + distributed_map_run_arn=_RUN_ARN, + source_exhausted=True, + success_count=1, + failure_count=0, + read_count=1, + total_count=1, + results=( + DistributedMapResultItemApi( + item_id="0", + status=DistributedMapItemStatus.SUCCEEDED, + output='"abc"', + ), + ), + ), + ) + mock_state.get_checkpoint_result.return_value = ( + CheckpointedResult.create_from_operation(operation) + ) + result = distributed_map_handler( + source=["a"], + processor=DistributedMapProcessor.report_item_outcomes("proc"), + max_concurrency=1, + state=mock_state, + operation_identifier=_identifier("cs"), + config=DistributedMapResultConfig(result_serdes=_UpperSerDes()), + ) + assert result.get_results() == ["ABC"] + + +@pytest.mark.parametrize("value", [0, False, "", [], {}]) +def test_falsy_output_round_trips(value): + """A falsy-but-present output survives the round-trip and decode (not dropped).""" + entry = DistributedMapResultItemApi( + item_id="0", + status=DistributedMapItemStatus.SUCCEEDED, + output=json.dumps(value), + ) + assert entry.to_dict()["Output"] == json.dumps(value) + + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + operation = Operation( + operation_id="fo", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.SUCCEEDED, + distributed_map_details=DistributedMapDetails( + distributed_map_run_arn=_RUN_ARN, + source_exhausted=True, + success_count=1, + failure_count=0, + read_count=1, + total_count=1, + results=(entry,), + ), + ) + mock_state.get_checkpoint_result.return_value = ( + CheckpointedResult.create_from_operation(operation) + ) + result = distributed_map_handler( + source=["a"], + processor=DistributedMapProcessor.report_item_outcomes("proc"), + max_concurrency=1, + state=mock_state, + operation_identifier=_identifier("fo"), + config=DistributedMapResultConfig(), + ) + assert result.get_results() == [value] + + +def test_processor_retry_duration_only(): + """A retry config with only a duration sends the duration and omits attempts.""" + options = _start_options( + _new_op_state_calls(), + source=["a"], + processor=DistributedMapProcessor.report_batch_outcome( + "proc", + retry=DistributedMapProcessorRetryConfig( + max_retry_duration=Duration.from_minutes(5), + ), + ), + max_concurrency=1, + config=DistributedMapConfig(), + ) + processor = options["Processor"] + assert processor["MaxRetryDurationSeconds"] == 300 + assert "MaxRetryAttempts" not in processor + + +def test_resolved_summary_uses_operation_status_not_details(): + """_resolve_summary carries the derived status when details omit it.""" + operation = Operation( + operation_id="dmap-id", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.SUCCEEDED, + distributed_map_details=DistributedMapDetails( + source_exhausted=True, + success_count=2, + failure_count=0, + read_count=2, + total_count=2, + ), + ) + executor = DistributedMapOperationExecutor( + source=["a", "b"], + processor=DistributedMapProcessor.report_batch_outcome("proc"), + max_concurrency=1, + state=Mock(spec=ExecutionState), + operation_identifier=_identifier("dmap-id"), + config=DistributedMapConfig(), + ) + + summary = executor._resolve_summary(operation) + + assert summary.status is DistributedMapStatus.SUCCEEDED + assert summary.source_exhausted is True + assert summary.success_count == 2 + + +def test_checkpoint_from_a_different_map_is_rejected(): + """A checkpoint whose identity differs from the current call is not consumed.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + operation = Operation( + operation_id="dmap-id", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="a_different_map", + status=OperationStatus.SUCCEEDED, + distributed_map_details=DistributedMapDetails( + source_exhausted=True, + success_count=999, + failure_count=0, + read_count=999, + total_count=999, + ), + ) + mock_state.get_checkpoint_result.return_value = ( + CheckpointedResult.create_from_operation(operation) + ) + + with pytest.raises(NonDeterministicExecutionError, match="name checkpoint="): + distributed_map_handler( + source=["a", "b"], + processor=DistributedMapProcessor.report_batch_outcome("proc"), + max_concurrency=1, + state=mock_state, + operation_identifier=_identifier("dmap-id"), + ) + + +# Each map run value gets its own serdes context, so a serdes that stores values +# under their context, such as FileSystemSerDes, keeps them all. +# ============================================================================ + + +def _sent_inline_items(operation_id: str, source: DistributedMapSource) -> list[str]: + """Serialize a source's inline items as a new map run with this id does.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + executor = DistributedMapOperationExecutor( + source=source, + processor=DistributedMapProcessor.report_batch_outcome("proc"), + max_concurrency=1, + state=mock_state, + operation_identifier=_identifier(operation_id), + config=DistributedMapConfig(), + ) + return executor._build_source_config().to_dict()["InlineSourceConfig"]["Items"] + + +def test_inline_items_are_stored_under_their_own_keys(tmp_path): + fs = FileSystemSerDes(str(tmp_path)) + source = DistributedMapSource.inline(["alpha", "beta", "gamma"], serdes=fs) + items = _sent_inline_items("op-1", source) + assert len(set(items)) == 3 + assert [fs.deserialize(i, SerDesContext()) for i in items] == [ + "alpha", + "beta", + "gamma", + ] + # Another map run in the same execution uses other keys. + assert set(_sent_inline_items("op-2", source)).isdisjoint(items) + + +def test_inline_items_keep_their_keys_when_serialized_again(tmp_path): + """A retried START writes each item to the key it used before.""" + fs = FileSystemSerDes(str(tmp_path)) + source = DistributedMapSource.inline(["alpha", "beta"], serdes=fs) + first = _sent_inline_items("op-1", source) + assert _sent_inline_items("op-1", source) == first + assert [fs.deserialize(i, SerDesContext()) for i in first] == ["alpha", "beta"] + + +class _StoreSerDes(SerDes): + """Stores each value under its context, so a reader must rebuild that context.""" + + def __init__(self) -> None: + self.values: dict[tuple[str, str], object] = {} + + def serialize(self, value, serdes_context): # noqa: ANN001, ANN201 + key = (serdes_context.durable_execution_arn, serdes_context.operation_id) + self.values[key] = value + return "ref" + + def deserialize(self, data, serdes_context): # noqa: ANN001, ANN201 + key = (serdes_context.durable_execution_arn, serdes_context.operation_id) + return self.values[key] + + +def _result_with_outputs(outputs, result_serdes, run_arn=_RUN_ARN): + """Resolve a succeeded map run whose items carry these outputs.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "test_arn" + operation = Operation( + operation_id="mro", + operation_type=OperationType.DISTRIBUTED_MAP, + sub_type=OperationSubType.DISTRIBUTED_MAP, + name="test_map_run", + status=OperationStatus.SUCCEEDED, + distributed_map_details=DistributedMapDetails( + distributed_map_run_arn=run_arn, + source_exhausted=True, + success_count=len(outputs), + failure_count=0, + read_count=len(outputs), + total_count=len(outputs), + results=tuple( + DistributedMapResultItemApi( + item_id=r["itemIdentifier"], + status=DistributedMapItemStatus.SUCCEEDED, + output=r["output"], + ) + for r in outputs + ), + ), + ) + mock_state.get_checkpoint_result.return_value = ( + CheckpointedResult.create_from_operation(operation) + ) + return distributed_map_handler( + source=["a"], + processor=DistributedMapProcessor.report_item_outcomes("proc"), + max_concurrency=1, + state=mock_state, + operation_identifier=_identifier("mro"), + config=DistributedMapResultConfig(result_serdes=result_serdes), + ) + + +def test_parent_reads_each_output_under_the_context_the_processor_wrote_it(): + serdes = _StoreSerDes() + records = [{"itemId": f"item-{i}", "body": json.dumps(i)} for i in range(3)] + resp = process_distributed_map_items( + {"distributedMapRunArn": _RUN_ARN, "records": records}, + lambda i, _ctx: f"out-{i}", + result_serdes=serdes, + ) + result = _result_with_outputs(resp["batchItemResults"], serdes) + assert result.get_results() == ["out-0", "out-1", "out-2"] + + +@pytest.mark.parametrize("run_arn", [None, "not-an-arn"], ids=["absent", "malformed"]) +def test_parent_rejects_an_output_without_a_valid_run_arn(run_arn): + with pytest.raises(ExecutionError, match="no valid DistributedMapRunArn"): + _result_with_outputs( + [{"itemIdentifier": "0", "output": "1"}], None, run_arn=run_arn + ) diff --git a/packages/aws-durable-execution-sdk-python/tests/plugin_test.py b/packages/aws-durable-execution-sdk-python/tests/plugin_test.py index ab3996335..f83536b8f 100644 --- a/packages/aws-durable-execution-sdk-python/tests/plugin_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/plugin_test.py @@ -19,6 +19,7 @@ CallbackDetails, ChainedInvokeDetails, ContextDetails, + DistributedMapDetails, DurableExecutionInvocationOutput, ErrorObject, InvocationStatus as ServiceInvocationStatus, @@ -2669,12 +2670,25 @@ def test_extract_error_from_context_details(self): result = PluginExecutor._extract_error(op) self.assertEqual(result.message, "boom") + def test_extract_error_from_distributed_map_details(self): + op = MagicMock() + op.step_details = None + op.callback_details = None + op.chained_invoke_details = None + op.context_details = None + op.distributed_map_details = MagicMock() + op.distributed_map_details.error = ERROR + + result = PluginExecutor._extract_error(op) + self.assertEqual(result.message, "boom") + def test_extract_error_returns_none_when_no_error(self): op = MagicMock() op.step_details = None op.callback_details = None op.chained_invoke_details = None op.context_details = None + op.distributed_map_details = None result = PluginExecutor._extract_error(op) self.assertIsNone(result) @@ -2700,6 +2714,7 @@ def test_extract_error_step_details_no_error(self): ServiceOperationType.CALLBACK, ServiceOperationType.CHAINED_INVOKE, ServiceOperationType.CONTEXT, + ServiceOperationType.DISTRIBUTED_MAP, ], ) @pytest.mark.parametrize( @@ -2747,6 +2762,11 @@ def test_plugin_error_projection_preserves_checkpoint_state( if operation_type is ServiceOperationType.CONTEXT else None ), + distributed_map_details=( + DistributedMapDetails(error=error) + if operation_type is ServiceOperationType.DISTRIBUTED_MAP + else None + ), ) checkpoint = deepcopy(operation.to_dict()) observed: list[OperationInfo | OperationEndInfo] = []