diff --git a/sdk/src/main/java/software/amazon/lambda/durable/config/DistributedMapConfig.java b/sdk/src/main/java/software/amazon/lambda/durable/config/DistributedMapConfig.java
new file mode 100644
index 0000000000..08525b976b
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/config/DistributedMapConfig.java
@@ -0,0 +1,148 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.config;
+
+import java.time.Duration;
+import software.amazon.lambda.durable.serde.SerDes;
+
+/** Optional configuration for a distributed map run. */
+public class DistributedMapConfig {
+ private static final long MAX_TIMEOUT_SECONDS = 7776000; // 90 days
+
+ private final DistributedMapDestination destination;
+ private final CompletionConfig completionConfig;
+ private final Duration timeout;
+ private final SerDes resultSerDes;
+
+ private DistributedMapConfig(Builder builder) {
+ if (builder.timeout != null
+ && (builder.timeout.toSeconds() <= 0 || builder.timeout.toSeconds() > MAX_TIMEOUT_SECONDS)) {
+ throw new IllegalArgumentException(
+ "timeout must be positive and at most 90 days, got: " + builder.timeout.toSeconds() + "s");
+ }
+ this.destination = builder.destination;
+ this.completionConfig = builder.completionConfig;
+ this.timeout = builder.timeout;
+ this.resultSerDes = builder.resultSerDes;
+ }
+
+ public DistributedMapDestination destination() {
+ return destination;
+ }
+
+ public CompletionConfig completionConfig() {
+ return completionConfig;
+ }
+
+ public Duration timeout() {
+ return timeout;
+ }
+
+ public SerDes resultSerDes() {
+ return resultSerDes;
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public Builder toBuilder() {
+ var builder = new Builder();
+ builder.destination = destination;
+ builder.completionConfig = completionConfig;
+ builder.timeout = timeout;
+ builder.resultSerDes = resultSerDes;
+ return builder;
+ }
+
+ /** Builder for DistributedMapConfig. */
+ public static class Builder {
+ private DistributedMapDestination destination;
+ private CompletionConfig completionConfig;
+ private Duration timeout;
+ private SerDes resultSerDes;
+
+ private Builder() {}
+
+ public Builder destination(DistributedMapDestination destination) {
+ this.destination = destination;
+ return this;
+ }
+
+ public Builder completionConfig(CompletionConfig completionConfig) {
+ this.completionConfig = completionConfig;
+ return this;
+ }
+
+ public Builder timeout(Duration timeout) {
+ this.timeout = timeout;
+ return this;
+ }
+
+ public Builder resultSerDes(SerDes resultSerDes) {
+ this.resultSerDes = resultSerDes;
+ return this;
+ }
+
+ public DistributedMapConfig build() {
+ return new DistributedMapConfig(this);
+ }
+ }
+
+ /**
+ * Failure-tolerance configuration for a distributed map run. {@code toleratedFailurePercentage} is a number from 0
+ * through 100 and may be fractional.
+ */
+ public record CompletionConfig(
+ Integer toleratedFailureCount, Double toleratedFailurePercentage, Integer minimumSampleSize) {
+
+ public CompletionConfig {
+ if (toleratedFailureCount != null && toleratedFailurePercentage != null) {
+ throw new IllegalArgumentException(
+ "toleratedFailureCount and toleratedFailurePercentage are mutually exclusive");
+ }
+ if (minimumSampleSize != null && toleratedFailurePercentage == null) {
+ throw new IllegalArgumentException("minimumSampleSize is only valid with toleratedFailurePercentage");
+ }
+ // Omitting the config means zero tolerated failures, so an empty one is rejected rather than omitted.
+ if (toleratedFailureCount == null && toleratedFailurePercentage == null) {
+ throw new IllegalArgumentException(
+ "a completion config must set toleratedFailureCount or toleratedFailurePercentage");
+ }
+ if (toleratedFailureCount != null && toleratedFailureCount < 0) {
+ throw new IllegalArgumentException(
+ "toleratedFailureCount must be non-negative, got: " + toleratedFailureCount);
+ }
+ if (toleratedFailurePercentage != null && !Double.isFinite(toleratedFailurePercentage)) {
+ throw new IllegalArgumentException(
+ "toleratedFailurePercentage must be a finite number, got: " + toleratedFailurePercentage);
+ }
+ if (toleratedFailurePercentage != null
+ && (toleratedFailurePercentage < 0 || toleratedFailurePercentage > 100)) {
+ throw new IllegalArgumentException(
+ "toleratedFailurePercentage must be between 0 and 100, got: " + toleratedFailurePercentage);
+ }
+ if (minimumSampleSize != null && minimumSampleSize < 1) {
+ throw new IllegalArgumentException("minimumSampleSize must be at least 1, got: " + minimumSampleSize);
+ }
+ }
+
+ /** Stops the run after more than this many items permanently fail. */
+ public static CompletionConfig failureCount(int count) {
+ return new CompletionConfig(count, null, null);
+ }
+
+ /** Abort once the failure rate exceeds this percentage, a number from 0 through 100 that may be fractional. */
+ public static CompletionConfig failurePercentage(double percentage) {
+ return new CompletionConfig(null, percentage, null);
+ }
+
+ /**
+ * Abort once the failure rate exceeds this percentage, a number from 0 through 100 that may be fractional,
+ * gated by a minimum sample size.
+ */
+ public static CompletionConfig failurePercentage(double percentage, int minimumSampleSize) {
+ return new CompletionConfig(null, percentage, minimumSampleSize);
+ }
+ }
+}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/config/DistributedMapDestination.java b/sdk/src/main/java/software/amazon/lambda/durable/config/DistributedMapDestination.java
new file mode 100644
index 0000000000..8e38a6f39f
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/config/DistributedMapDestination.java
@@ -0,0 +1,109 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.config;
+
+import java.nio.charset.StandardCharsets;
+import software.amazon.lambda.durable.util.DistributedMapValidation;
+
+/** Destination routing for distributed map run results. */
+public record DistributedMapDestination(Success onSuccess, Failure onFailure) {
+ private static final int MAX_DESTINATION_KEY_PREFIX_BYTES = 900;
+
+ /** Routes only succeeded item records. */
+ public static DistributedMapDestination of(Success onSuccess) {
+ return new DistributedMapDestination(onSuccess, null);
+ }
+
+ /** Routes only failed item records. */
+ public static DistributedMapDestination of(Failure onFailure) {
+ return new DistributedMapDestination(null, onFailure);
+ }
+
+ /** Routes both succeeded and failed item records. */
+ public static DistributedMapDestination of(Success onSuccess, Failure onFailure) {
+ return new DistributedMapDestination(onSuccess, onFailure);
+ }
+
+ /** Route succeeded item records to an S3 prefix (defaults to include output only). */
+ public static Success s3Successes(String prefixUri) {
+ return s3Successes(prefixUri, false, true, null);
+ }
+
+ /** Route succeeded item records to an S3 prefix. */
+ public static Success s3Successes(
+ String prefixUri, boolean includeInput, boolean includeOutput, String expectedBucketOwner) {
+ var parsed = DistributedMapValidation.parseS3Uri(prefixUri);
+ return new Success(
+ parsed.bucket(),
+ parsed.path() != null ? parsed.path() : "",
+ includeInput,
+ includeOutput,
+ expectedBucketOwner);
+ }
+
+ /** Route permanently-failed item records to an S3 prefix (defaults to include input and error). */
+ public static Failure s3Failures(String prefixUri) {
+ return s3Failures(prefixUri, true, true, null);
+ }
+
+ /** Route permanently-failed item records to an S3 prefix. */
+ public static Failure s3Failures(
+ String prefixUri, boolean includeInput, boolean includeError, String expectedBucketOwner) {
+ var parsed = DistributedMapValidation.parseS3Uri(prefixUri);
+ return new Failure(
+ parsed.bucket(),
+ parsed.path() != null ? parsed.path() : "",
+ includeInput,
+ includeError,
+ expectedBucketOwner);
+ }
+
+ /**
+ * Rejects a destination key prefix the service would reject. The limit is 900 UTF-8 bytes, including a trailing
+ * slash when the URI has one, and it is measured in bytes rather than characters, so a multi-byte prefix under 900
+ * characters can still exceed it. The service applies the same limit when the start checkpoint is written, so
+ * checking it here fails the call that built the destination instead of the operation.
+ */
+ private static void validateDestinationPrefix(String prefix) {
+ if (prefix == null) {
+ return;
+ }
+ var bytes = prefix.getBytes(StandardCharsets.UTF_8).length;
+ if (bytes > MAX_DESTINATION_KEY_PREFIX_BYTES) {
+ throw new IllegalArgumentException("destination key prefix must be at most "
+ + MAX_DESTINATION_KEY_PREFIX_BYTES + " UTF-8 bytes, got: " + bytes);
+ }
+ }
+
+ /** S3 destination for succeeded distributed map items. */
+ public record Success(
+ String bucket, String prefix, boolean includeInput, boolean includeOutput, String expectedBucketOwner) {
+
+ public Success {
+ if (bucket == null || bucket.isEmpty()) {
+ throw new IllegalArgumentException("success destination bucket cannot be empty");
+ }
+ DistributedMapValidation.validateBucketOwner(expectedBucketOwner);
+ validateDestinationPrefix(prefix);
+ if (!includeInput && !includeOutput) {
+ throw new IllegalArgumentException("success destination must include at least one of input or output");
+ }
+ }
+ }
+
+ /** S3 destination for permanently-failed distributed map items. */
+ public record Failure(
+ String bucket, String prefix, boolean includeInput, boolean includeError, String expectedBucketOwner) {
+
+ public Failure {
+ if (bucket == null || bucket.isEmpty()) {
+ throw new IllegalArgumentException("failure destination bucket cannot be empty");
+ }
+ DistributedMapValidation.validateBucketOwner(expectedBucketOwner);
+ validateDestinationPrefix(prefix);
+ if (!includeInput && !includeError) {
+ throw new IllegalArgumentException("failure destination must include at least one of input or error");
+ }
+ }
+ }
+}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/config/DistributedMapProcessor.java b/sdk/src/main/java/software/amazon/lambda/durable/config/DistributedMapProcessor.java
new file mode 100644
index 0000000000..6c70ee05e1
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/config/DistributedMapProcessor.java
@@ -0,0 +1,116 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.config;
+
+import software.amazon.lambda.durable.util.DistributedMapValidation;
+
+/** Processor configuration for a distributed map run. */
+public class DistributedMapProcessor {
+
+ /** Per-batch response mode reported by the processor. */
+ public enum ResponseMode {
+ BATCH,
+ ITEM_OUTCOMES
+ }
+
+ private static final int MIN_BATCH_SIZE = 1;
+ private static final int MAX_BATCH_SIZE = 10000;
+ private static final int MAX_NAME_PREFIX_LENGTH = 36;
+
+ private final String functionName;
+ private final ResponseMode responseMode;
+ private final Integer batchSize;
+ private final DistributedMapProcessorRetryConfig retry;
+ private final String durableExecutionNamePrefix;
+
+ private DistributedMapProcessor(Builder builder) {
+ DistributedMapValidation.validateFunctionName(builder.functionName);
+ if (builder.batchSize != null && (builder.batchSize < MIN_BATCH_SIZE || builder.batchSize > MAX_BATCH_SIZE)) {
+ throw new IllegalArgumentException("batchSize must be between 1 and 10000, got: " + builder.batchSize);
+ }
+ if (builder.durableExecutionNamePrefix != null
+ && (builder.durableExecutionNamePrefix.isEmpty()
+ || builder.durableExecutionNamePrefix.length() > MAX_NAME_PREFIX_LENGTH)) {
+ throw new IllegalArgumentException("durableExecutionNamePrefix must be between 1 and 36 characters, got: "
+ + builder.durableExecutionNamePrefix.length());
+ }
+ this.functionName = builder.functionName;
+ this.responseMode = builder.responseMode;
+ this.batchSize = builder.batchSize;
+ this.retry = builder.retry;
+ this.durableExecutionNamePrefix = builder.durableExecutionNamePrefix;
+ }
+
+ public String functionName() {
+ return functionName;
+ }
+
+ public ResponseMode responseMode() {
+ return responseMode;
+ }
+
+ public Integer batchSize() {
+ return batchSize;
+ }
+
+ /** Returns the retry settings, or null for the service defaults. */
+ public DistributedMapProcessorRetryConfig retry() {
+ return retry;
+ }
+
+ public String durableExecutionNamePrefix() {
+ return durableExecutionNamePrefix;
+ }
+
+ /** Processor that reports a single pass/fail outcome for the whole batch, with no per-item results. */
+ public static Builder reportBatchOutcome(String functionName) {
+ return new Builder(functionName, ResponseMode.BATCH);
+ }
+
+ /**
+ * Processor that may report a failure or an output for each item. Every item it does not list succeeds with no
+ * output.
+ */
+ public static Builder reportItemOutcomes(String functionName) {
+ return new Builder(functionName, ResponseMode.ITEM_OUTCOMES);
+ }
+
+ /** Builder for DistributedMapProcessor. */
+ public static class Builder {
+ private final String functionName;
+ private final ResponseMode responseMode;
+ private Integer batchSize;
+ private DistributedMapProcessorRetryConfig retry;
+ private String durableExecutionNamePrefix;
+
+ private Builder(String functionName, ResponseMode responseMode) {
+ this.functionName = functionName;
+ this.responseMode = responseMode;
+ }
+
+ public Builder batchSize(int batchSize) {
+ this.batchSize = batchSize;
+ return this;
+ }
+
+ /**
+ * Sets the per-item retry policy. Omit it to take the service defaults of 2 attempts within 6 hours.
+ *
+ * @param retry the retry settings
+ * @return this builder
+ */
+ public Builder retry(DistributedMapProcessorRetryConfig retry) {
+ this.retry = retry;
+ return this;
+ }
+
+ public Builder durableExecutionNamePrefix(String durableExecutionNamePrefix) {
+ this.durableExecutionNamePrefix = durableExecutionNamePrefix;
+ return this;
+ }
+
+ public DistributedMapProcessor build() {
+ return new DistributedMapProcessor(this);
+ }
+ }
+}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/config/DistributedMapProcessorRetryConfig.java b/sdk/src/main/java/software/amazon/lambda/durable/config/DistributedMapProcessorRetryConfig.java
new file mode 100644
index 0000000000..bda75df6a5
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/config/DistributedMapProcessorRetryConfig.java
@@ -0,0 +1,93 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.config;
+
+import java.time.Duration;
+
+/**
+ * Retry settings for a distributed map processor.
+ *
+ * Retry policy belongs to the processor reference rather than the run, because it defines how the service invokes
+ * that function. One Lambda function can back several processor references with different policies.
+ */
+public class DistributedMapProcessorRetryConfig {
+
+ /** Sentinel for unbounded retry attempts (wire value -1). */
+ public static final int UNLIMITED = -1;
+
+ private static final long MIN_RETRY_DURATION_SECONDS = 60;
+ private static final long MAX_RETRY_DURATION_SECONDS = 21600;
+
+ private final Integer maxRetryAttempts;
+ private final Duration maxRetryDuration;
+
+ private DistributedMapProcessorRetryConfig(Builder builder) {
+ this.maxRetryAttempts = builder.maxRetryAttempts;
+ this.maxRetryDuration = builder.maxRetryDuration;
+ }
+
+ /** Returns the max retry attempts, UNLIMITED for unbounded, or null for the service default of 2. */
+ public Integer maxRetryAttempts() {
+ return maxRetryAttempts;
+ }
+
+ /** Returns the cumulative retry duration budget, or null for the service default of 6 hours. */
+ public Duration maxRetryDuration() {
+ return maxRetryDuration;
+ }
+
+ /**
+ * Creates a new builder for {@code DistributedMapProcessorRetryConfig}.
+ *
+ * @return a new builder instance
+ */
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ /** Builder for DistributedMapProcessorRetryConfig. */
+ public static class Builder {
+ private Integer maxRetryAttempts;
+ private Duration maxRetryDuration;
+
+ private Builder() {}
+
+ /**
+ * Sets the number of function-error retries before an item permanently fails. Pass {@link #UNLIMITED} for no
+ * attempt limit within the duration budget, or 0 to disable retries.
+ *
+ * @param maxRetryAttempts a non-negative count, or UNLIMITED
+ * @return this builder
+ */
+ public Builder maxRetryAttempts(int maxRetryAttempts) {
+ if (maxRetryAttempts < 0 && maxRetryAttempts != UNLIMITED) {
+ throw new IllegalArgumentException(
+ "maxRetryAttempts must be non-negative or DistributedMapProcessorRetryConfig.UNLIMITED, got: "
+ + maxRetryAttempts);
+ }
+ this.maxRetryAttempts = maxRetryAttempts;
+ return this;
+ }
+
+ /**
+ * Sets the cumulative backoff budget across all of an item's retries, from 1 minute through 6 hours.
+ *
+ * @param maxRetryDuration the budget
+ * @return this builder
+ */
+ public Builder maxRetryDuration(Duration maxRetryDuration) {
+ if (maxRetryDuration != null
+ && (maxRetryDuration.toSeconds() < MIN_RETRY_DURATION_SECONDS
+ || maxRetryDuration.toSeconds() > MAX_RETRY_DURATION_SECONDS)) {
+ throw new IllegalArgumentException("maxRetryDuration must be between 1 minute and 6 hours, got: "
+ + maxRetryDuration.toSeconds() + "s");
+ }
+ this.maxRetryDuration = maxRetryDuration;
+ return this;
+ }
+
+ public DistributedMapProcessorRetryConfig build() {
+ return new DistributedMapProcessorRetryConfig(this);
+ }
+ }
+}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/config/DistributedMapSource.java b/sdk/src/main/java/software/amazon/lambda/durable/config/DistributedMapSource.java
new file mode 100644
index 0000000000..70510466e6
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/config/DistributedMapSource.java
@@ -0,0 +1,331 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.config;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import software.amazon.lambda.durable.serde.SerDes;
+import software.amazon.lambda.durable.util.DistributedMapValidation;
+import software.amazon.lambda.durable.util.ParameterValidator;
+
+/**
+ * Source of items for a distributed map run.
+ *
+ * @param the item type produced by the source
+ */
+public class DistributedMapSource {
+
+ private static final long MAX_ITEMS_TO_READ = 100_000_000L;
+
+ /** The kind of source backing a distributed map. */
+ public enum SourceType {
+ INLINE,
+ S3,
+ READER_FUNCTION
+ }
+
+ /** How the bytes of an S3 object are split into items. */
+ public enum Format {
+ JSON_LINES,
+ JSON_ARRAY,
+ CSV
+ }
+
+ /** What an S3 source reads. */
+ public enum S3SourceType {
+ OBJECT,
+ LISTED_OBJECT_METADATA,
+ LISTED_OBJECTS
+ }
+
+ private final SourceType sourceType;
+ private final Long maxItems;
+ private final List inlineItems;
+ private final SerDes inlineSerDes;
+ private final S3SourceConfig s3;
+ private final ReaderSourceConfig reader;
+
+ private DistributedMapSource(
+ SourceType sourceType,
+ Long maxItems,
+ List inlineItems,
+ SerDes inlineSerDes,
+ S3SourceConfig s3,
+ ReaderSourceConfig reader) {
+ if (maxItems != null && (maxItems < 1 || maxItems > MAX_ITEMS_TO_READ)) {
+ throw new IllegalArgumentException(
+ "maxItems must be between 1 and " + MAX_ITEMS_TO_READ + ", got: " + maxItems);
+ }
+ this.sourceType = sourceType;
+ this.maxItems = maxItems;
+ // A null item is allowed and is sent as JSON null, so the copy must accept null elements.
+ this.inlineItems = inlineItems != null ? Collections.unmodifiableList(new ArrayList<>(inlineItems)) : null;
+ this.inlineSerDes = inlineSerDes;
+ this.s3 = s3;
+ this.reader = reader;
+ }
+
+ public SourceType sourceType() {
+ return sourceType;
+ }
+
+ public Long maxItems() {
+ return maxItems;
+ }
+
+ public List inlineItems() {
+ return inlineItems;
+ }
+
+ public SerDes inlineSerDes() {
+ return inlineSerDes;
+ }
+
+ public S3SourceConfig s3() {
+ return s3;
+ }
+
+ public ReaderSourceConfig reader() {
+ return reader;
+ }
+
+ /** An in-memory list of items embedded in the start checkpoint. */
+ public static DistributedMapSource inline(Collection items) {
+ return inline(items, null);
+ }
+
+ /** An in-memory list of items embedded in the start checkpoint, serialized with the given SerDes. */
+ public static DistributedMapSource inline(Collection items, SerDes serDes) {
+ ParameterValidator.validateOrderedCollection(items);
+ return new DistributedMapSource<>(SourceType.INLINE, null, new ArrayList<>(items), serDes, null, null);
+ }
+
+ /** Read a single S3 object, treating each line as an item. */
+ public static DistributedMapSource s3JsonLines(String uri) {
+ var parsed = DistributedMapValidation.parseS3Uri(uri);
+ if (parsed.path() == null) {
+ throw new IllegalArgumentException("s3JsonLines requires an S3 object key");
+ }
+ return s3(object(parsed.bucket(), parsed.path(), Format.JSON_LINES, null));
+ }
+
+ /** Read a single S3 object holding a JSON array, treating each element as an item. */
+ public static DistributedMapSource s3JsonArray(String uri) {
+ var parsed = DistributedMapValidation.parseS3Uri(uri);
+ if (parsed.path() == null) {
+ throw new IllegalArgumentException("s3JsonArray requires an S3 object key");
+ }
+ return s3(object(parsed.bucket(), parsed.path(), Format.JSON_ARRAY, null));
+ }
+
+ /** Read a single S3 object, treating each record as an item. */
+ public static DistributedMapSource s3Csv(String uri, CsvFormat format) {
+ var parsed = DistributedMapValidation.parseS3Uri(uri);
+ if (parsed.path() == null) {
+ throw new IllegalArgumentException("s3Csv requires an S3 object key");
+ }
+ return s3(object(parsed.bucket(), parsed.path(), Format.CSV, format));
+ }
+
+ /** Read each object under a prefix as one item (object contents are not read). */
+ public static DistributedMapSource s3Objects(String prefixUri) {
+ var parsed = DistributedMapValidation.parseS3Uri(prefixUri);
+ return s3(new S3SourceConfig(
+ S3SourceType.LISTED_OBJECT_METADATA,
+ parsed.bucket(),
+ null,
+ null,
+ new ListedObjectMetadataConfig(prefixOrEmpty(parsed.path())),
+ null));
+ }
+
+ /** Read a prefix, flattening each object's lines into items. */
+ public static DistributedMapSource s3FlattenedJsonLines(String prefixUri) {
+ var parsed = DistributedMapValidation.parseS3Uri(prefixUri);
+ return s3(listedObjects(parsed.bucket(), prefixOrEmpty(parsed.path()), Format.JSON_LINES, null));
+ }
+
+ /** Read a prefix, flattening each object's JSON array elements into items. */
+ public static DistributedMapSource s3FlattenedJsonArray(String prefixUri) {
+ var parsed = DistributedMapValidation.parseS3Uri(prefixUri);
+ return s3(listedObjects(parsed.bucket(), prefixOrEmpty(parsed.path()), Format.JSON_ARRAY, null));
+ }
+
+ /** Read a prefix, flattening each object's records into items. */
+ public static DistributedMapSource s3FlattenedCsv(String prefixUri, CsvFormat format) {
+ var parsed = DistributedMapValidation.parseS3Uri(prefixUri);
+ return s3(listedObjects(parsed.bucket(), prefixOrEmpty(parsed.path()), Format.CSV, format));
+ }
+
+ private static S3SourceConfig object(String bucket, String key, Format format, CsvFormat csvFormat) {
+ return new S3SourceConfig(
+ S3SourceType.OBJECT, bucket, null, new ObjectConfig(key, format, csvFormat), null, null);
+ }
+
+ private static S3SourceConfig listedObjects(String bucket, String keyPrefix, Format format, CsvFormat csvFormat) {
+ return new S3SourceConfig(
+ S3SourceType.LISTED_OBJECTS,
+ bucket,
+ null,
+ null,
+ null,
+ new ListedObjectsConfig(keyPrefix, format, csvFormat));
+ }
+
+ /** Page items from a customer-supplied reader Lambda function. */
+ public static DistributedMapSource reader(String functionName) {
+ return reader(functionName, null, null);
+ }
+
+ /** Page items from a customer-supplied reader Lambda function with an initial state. */
+ public static DistributedMapSource reader(String functionName, S initialState, SerDes stateSerDes) {
+ return new DistributedMapSource<>(
+ SourceType.READER_FUNCTION,
+ null,
+ null,
+ null,
+ null,
+ new ReaderSourceConfig(functionName, initialState, stateSerDes));
+ }
+
+ /** Returns a copy limiting the total number of items read. */
+ public DistributedMapSource maxItems(long maxItems) {
+ return new DistributedMapSource<>(sourceType, maxItems, inlineItems, inlineSerDes, s3, reader);
+ }
+
+ /** Returns a copy asserting the expected S3 bucket owner (S3 sources only). */
+ public DistributedMapSource expectedBucketOwner(String accountId) {
+ if (s3 == null) {
+ throw new IllegalStateException("expectedBucketOwner only applies to S3 sources");
+ }
+ DistributedMapValidation.validateBucketOwner(accountId);
+ return new DistributedMapSource<>(
+ sourceType, maxItems, inlineItems, inlineSerDes, s3.withExpectedBucketOwner(accountId), reader);
+ }
+
+ private static DistributedMapSource s3(S3SourceConfig s3) {
+ return new DistributedMapSource<>(SourceType.S3, null, null, null, s3, null);
+ }
+
+ private static String prefixOrEmpty(String path) {
+ return path != null ? path : "";
+ }
+
+ /** Resolved S3 source configuration. Exactly one config block matching {@code type} is set. */
+ public record S3SourceConfig(
+ S3SourceType type,
+ String bucket,
+ String expectedBucketOwner,
+ ObjectConfig objectConfig,
+ ListedObjectMetadataConfig listedObjectMetadataConfig,
+ ListedObjectsConfig listedObjectsConfig) {
+
+ S3SourceConfig withExpectedBucketOwner(String owner) {
+ return new S3SourceConfig(
+ type, bucket, owner, objectConfig, listedObjectMetadataConfig, listedObjectsConfig);
+ }
+ }
+
+ /** Reads the single object at {@code key}. */
+ public record ObjectConfig(String key, Format format, CsvFormat csvFormat) {}
+
+ /** Lists the objects under {@code keyPrefix} without reading their contents. */
+ public record ListedObjectMetadataConfig(String keyPrefix) {}
+
+ /** Lists the objects under {@code keyPrefix} and reads every listed object as {@code format}. */
+ public record ListedObjectsConfig(String keyPrefix, Format format, CsvFormat csvFormat) {}
+
+ /** Resolved reader-function source configuration. */
+ public record ReaderSourceConfig(String functionName, Object initialState, SerDes stateSerDes) {
+ public ReaderSourceConfig {
+ DistributedMapValidation.validateFunctionName(functionName);
+ }
+ }
+
+ /** CSV parsing options for a distributed map S3 source. */
+ public record CsvFormat(HeaderLocation headerLocation, List columns, CsvDelimiter delimiter) {
+ private static final int MAX_CSV_COLUMNS = 1000;
+ private static final int MAX_CSV_COLUMN_LENGTH = 256;
+
+ /** Where the column header row comes from. */
+ public enum HeaderLocation {
+ FIRST_ROW,
+ GIVEN
+ }
+
+ public CsvFormat {
+ if (headerLocation == null) {
+ throw new IllegalArgumentException("CsvFormat requires a headerLocation");
+ }
+ if (headerLocation == HeaderLocation.GIVEN) {
+ if (columns == null) {
+ throw new IllegalArgumentException("CsvFormat with headerLocation GIVEN requires headers");
+ }
+ validateColumns("headers", columns);
+ } else {
+ validateColumns("expectedColumns", columns);
+ }
+ columns = columns != null ? List.copyOf(columns) : null;
+ delimiter = delimiter != null ? delimiter : CsvDelimiter.COMMA;
+ }
+
+ /**
+ * File has its own header row. Column names are used only for compile-time typing and are not sent on the wire.
+ */
+ public static CsvFormat expectedColumns(List columns) {
+ return new CsvFormat(HeaderLocation.FIRST_ROW, columns, CsvDelimiter.COMMA);
+ }
+
+ /** File has no header row. The given names are the columns, sent on the wire, and the first row is data. */
+ public static CsvFormat headers(List headers) {
+ return new CsvFormat(HeaderLocation.GIVEN, headers, CsvDelimiter.COMMA);
+ }
+
+ /** File has its own header row and no column names are declared. */
+ public static CsvFormat firstRow() {
+ return new CsvFormat(HeaderLocation.FIRST_ROW, null, CsvDelimiter.COMMA);
+ }
+
+ /** Returns a copy with the given delimiter. */
+ public CsvFormat withDelimiter(CsvDelimiter delimiter) {
+ return new CsvFormat(headerLocation, columns, delimiter);
+ }
+
+ private static void validateColumns(String parameterName, List columns) {
+ if (columns == null) {
+ return;
+ }
+ if (columns.isEmpty()) {
+ throw new IllegalArgumentException(parameterName + " cannot be empty");
+ }
+ if (columns.size() > MAX_CSV_COLUMNS) {
+ throw new IllegalArgumentException(
+ parameterName + " must hold at most " + MAX_CSV_COLUMNS + " names, got: " + columns.size());
+ }
+ for (var column : columns) {
+ if (column == null || column.isEmpty()) {
+ throw new IllegalArgumentException("each " + parameterName + " name cannot be empty");
+ }
+ if (column.length() > MAX_CSV_COLUMN_LENGTH) {
+ throw new IllegalArgumentException("each " + parameterName + " name must be at most "
+ + MAX_CSV_COLUMN_LENGTH + " characters, got: " + column.length());
+ }
+ }
+ if (new HashSet<>(columns).size() != columns.size()) {
+ throw new IllegalArgumentException(parameterName + " must not contain duplicates");
+ }
+ }
+ }
+
+ /** Delimiter for CSV distributed map sources. */
+ public enum CsvDelimiter {
+ COMMA,
+ PIPE,
+ SEMICOLON,
+ SPACE,
+ TAB
+ }
+}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/dmap/BatchContext.java b/sdk/src/main/java/software/amazon/lambda/durable/dmap/BatchContext.java
new file mode 100644
index 0000000000..5e88a63925
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/dmap/BatchContext.java
@@ -0,0 +1,20 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.dmap;
+
+import java.util.List;
+
+/**
+ * The context a batch function receives with its items.
+ *
+ * @param distributedMapRunArn the ARN of the distributed map run the batch belongs to
+ * @param itemIds the items' identifiers, assigned by the service. itemIds.get(i) is the id of items.get(i), so
+ * filtering or reordering the items breaks the pairing
+ */
+public record BatchContext(String distributedMapRunArn, List itemIds) {
+
+ /** Applies a defensive copy. */
+ public BatchContext {
+ itemIds = List.copyOf(itemIds);
+ }
+}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/dmap/DistributedMapHelpers.java b/sdk/src/main/java/software/amazon/lambda/durable/dmap/DistributedMapHelpers.java
new file mode 100644
index 0000000000..d82d6ad4e1
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/dmap/DistributedMapHelpers.java
@@ -0,0 +1,569 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.dmap;
+
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Objects;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Consumer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+import software.amazon.lambda.durable.DurableContext;
+import software.amazon.lambda.durable.TypeToken;
+import software.amazon.lambda.durable.config.CompletionConfig;
+import software.amazon.lambda.durable.config.MapConfig;
+import software.amazon.lambda.durable.config.NestingType;
+import software.amazon.lambda.durable.model.DistributedMapError;
+import software.amazon.lambda.durable.model.MapResult;
+import software.amazon.lambda.durable.serde.JacksonSerDes;
+import software.amazon.lambda.durable.serde.SerDes;
+
+/**
+ * Helpers a distributed map processor or reader Lambda calls inside its own handler.
+ *
+ * Each helper returns the response the distributed map service expects. The handler must return that response.
+ */
+public final class DistributedMapHelpers {
+ private static final Logger LOGGER = LoggerFactory.getLogger(DistributedMapHelpers.class);
+ private static final SerDes JSON = new JacksonSerDes();
+ private static final TypeToken OUTPUT_TYPE = TypeToken.get(String.class);
+ private static final int MIN_CONCURRENCY = 1;
+ private static final int DEFAULT_CONCURRENCY = 1;
+ private static final int READER_STATE_LIMIT = 32 * 1024;
+ private static final String ITEMS_OP_NAME = "distributed-map-items";
+
+ private DistributedMapHelpers() {}
+
+ /** Reader function: returns the page that follows the given state. */
+ @FunctionalInterface
+ public interface ReaderFunction {
+
+ /**
+ * Reads one page.
+ *
+ * @param state the state from the previous page, or null on the first call
+ * @param maxItemsPerPage the most items the page may hold
+ * @param context the reader context for this page request
+ * @return the page of items and the next state, or a null next state when the source is exhausted
+ */
+ ReaderPage apply(S state, Integer maxItemsPerPage, ReaderContext context);
+ }
+
+ /** Durable item function: processes one item under its own DurableContext. */
+ @FunctionalInterface
+ public interface DurableItemFunction {
+
+ /**
+ * Processes one item.
+ *
+ * @param context the durable context for this item's execution
+ * @param item the item to process
+ * @param itemContext the item context for this item
+ * @return the item's output
+ */
+ O apply(DurableContext context, I item, ItemContext itemContext);
+ }
+
+ /**
+ * Calls {@code func} on each item in the batch, and returns each item's result or error in the format the service
+ * expects, running one item at a time.
+ *
+ * Call it in the handler of your non-durable processor Lambda, and pass that Lambda's name to
+ * {@code DistributedMapProcessor.reportItemOutcomes} in the parent's distributed map call.
+ *
+ *
Note: your handler must return this method's result, because the service reads which items failed from the
+ * handler's return value. If the handler returns nothing, the service marks every item as succeeded.
+ *
+ *
It logs one ERROR line per failed item, with the run ARN, the item id and the reported error.
+ *
+ *
{@code
+ * public class OrderProcessor implements RequestHandler {
+ * public ItemHandlerResponse handleRequest(ProcessorEvent event, Context context) {
+ * return DistributedMapHelpers.processDistributedMapItems(
+ * event, (Order order, ItemContext itemContext) -> chargeOrder(order),
+ * TypeToken.get(Order.class), null, null);
+ * }
+ * }
+ * }
+ *
+ * @param event the processor event the service sent
+ * @param func the function to call on each item
+ * @param itemType the item type
+ * @param itemSerDes the serdes that reads each item, or null for the default JSON serdes
+ * @param resultSerDes the serdes that writes each output, or null for the default JSON serdes
+ * @return the response the handler must return
+ */
+ public static ItemHandlerResponse processDistributedMapItems(
+ ProcessorEvent event,
+ BiFunction func,
+ TypeToken itemType,
+ SerDes itemSerDes,
+ SerDes resultSerDes) {
+ return processDistributedMapItems(event, func, itemType, itemSerDes, resultSerDes, DEFAULT_CONCURRENCY);
+ }
+
+ /**
+ * Calls {@code func} on each item in the batch, and returns each item's result or error in the format the service
+ * expects.
+ *
+ * Call it in the handler of your non-durable processor Lambda, and pass that Lambda's name to
+ * {@code DistributedMapProcessor.reportItemOutcomes} in the parent's distributed map call.
+ *
+ *
Note: your handler must return this method's result, because the service reads which items failed from the
+ * handler's return value. If the handler returns nothing, the service marks every item as succeeded.
+ *
+ *
It logs one ERROR line per failed item, with the run ARN, the item id and the reported error.
+ *
+ *
{@code
+ * public class OrderProcessor implements RequestHandler {
+ * public ItemHandlerResponse handleRequest(ProcessorEvent event, Context context) {
+ * return DistributedMapHelpers.processDistributedMapItems(
+ * event, (Order order, ItemContext itemContext) -> chargeOrder(order),
+ * TypeToken.get(Order.class), null, null, 5);
+ * }
+ * }
+ * }
+ *
+ * @param event the processor event the service sent
+ * @param func the function to call on each item
+ * @param itemType the item type
+ * @param itemSerDes the serdes that reads each item, or null for the default JSON serdes
+ * @param resultSerDes the serdes that writes each output, or null for the default JSON serdes
+ * @param concurrency the maximum number of items processed at the same time (default: 1), at least 1. When greater
+ * than 1, {@code func}, {@code itemSerDes} and {@code resultSerDes} are called from several threads at the same
+ * time, so each must be safe for concurrent calls.
+ * @return the response the handler must return
+ */
+ public static ItemHandlerResponse processDistributedMapItems(
+ ProcessorEvent event,
+ BiFunction func,
+ TypeToken itemType,
+ SerDes itemSerDes,
+ SerDes resultSerDes,
+ int concurrency) {
+ validateConcurrency(concurrency);
+ var inSerdes = itemSerDes != null ? itemSerDes : JSON;
+ var outSerdes = resultSerDes != null ? resultSerDes : JSON;
+ var records = event.records();
+ var outputs = new String[records.size()];
+ var errors = new Throwable[records.size()];
+ runItems(event, func, itemType, inSerdes, outSerdes, concurrency, outputs, errors);
+
+ var results = new ArrayList();
+ var failures = new ArrayList();
+ for (var i = 0; i < records.size(); i++) {
+ var itemId = records.get(i).itemId();
+ if (errors[i] != null) {
+ var failure = new ItemFailure(itemId, DistributedMapError.of(errors[i]));
+ logItemFailure(event.distributedMapRunArn(), failure, LOGGER::error);
+ failures.add(failure);
+ } else {
+ results.add(new ItemResult(itemId, outputs[i]));
+ }
+ }
+ return new ItemHandlerResponse(results, failures);
+ }
+
+ // Runs each record on a pool and stores the record's output or error at the record's index.
+ private static void runItems(
+ ProcessorEvent event,
+ BiFunction func,
+ TypeToken itemType,
+ SerDes inSerdes,
+ SerDes outSerdes,
+ int concurrency,
+ String[] outputs,
+ Throwable[] errors) {
+ var records = event.records();
+ var pool = Executors.newFixedThreadPool(concurrency);
+ try {
+ var futures = new ArrayList>();
+ for (var i = 0; i < records.size(); i++) {
+ var index = i;
+ futures.add(pool.submit(() -> {
+ var record = records.get(index);
+ I item = inSerdes.deserialize(record.body(), itemType);
+ O output = func.apply(item, new ItemContext(event.distributedMapRunArn(), record.itemId()));
+ outputs[index] = toOutput(outSerdes, output);
+ return null;
+ }));
+ }
+ for (var i = 0; i < futures.size(); i++) {
+ try {
+ futures.get(i).get();
+ } catch (ExecutionException e) {
+ errors[i] = e.getCause() != null ? e.getCause() : e;
+ }
+ }
+ } catch (InterruptedException e) {
+ pool.shutdownNow();
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException("Distributed map item helper interrupted", e);
+ } finally {
+ pool.shutdown();
+ }
+ }
+
+ /**
+ * Calls {@code func} on each item in the batch under its own durable context, and returns each item's result or
+ * error in the format the service expects, running one item at a time.
+ *
+ * Call it in the handler of your durable processor Lambda, and pass that Lambda's name to
+ * {@code DistributedMapProcessor.reportItemOutcomes} in the parent's distributed map call.
+ *
+ *
Note: your handler must return this method's result, because the service reads which items failed from the
+ * handler's return value. If the handler returns nothing, the service marks every item as succeeded.
+ *
+ *
It logs one ERROR line per failed item, with the run ARN, the item id and the reported error.
+ *
+ *
Pass the handler's {@link DurableContext} first. Each item runs through {@code context.map}, with
+ * {@link NestingType#FLAT} by default.
+ *
+ *
{@code
+ * public class OrderProcessor extends DurableHandler {
+ * public ItemHandlerResponse handleRequest(ProcessorEvent event, DurableContext context) {
+ * return DistributedMapHelpers.processDistributedMapItems(
+ * context, event,
+ * (durableCtx, order, itemContext) -> durableCtx.step("charge", String.class, s -> chargeOrder(order)),
+ * TypeToken.get(Order.class), null, null);
+ * }
+ * }
+ * }
+ *
+ * @param context the handler's durable context
+ * @param event the processor event the service sent
+ * @param func the function to call on each item
+ * @param itemType the item type
+ * @param itemSerDes the serdes that reads each item, or null for the default JSON serdes
+ * @param resultSerDes the serdes that writes each output, or null for the default JSON serdes
+ * @return the response the handler must return
+ */
+ public static ItemHandlerResponse processDistributedMapItems(
+ DurableContext context,
+ ProcessorEvent event,
+ DurableItemFunction func,
+ TypeToken itemType,
+ SerDes itemSerDes,
+ SerDes resultSerDes) {
+ return processDistributedMapItems(
+ context, event, func, itemType, itemSerDes, resultSerDes, DEFAULT_CONCURRENCY, NestingType.FLAT);
+ }
+
+ /**
+ * Calls {@code func} on each item in the batch under its own durable context, and returns each item's result or
+ * error in the format the service expects, with {@link NestingType#FLAT} nesting.
+ *
+ * Call it in the handler of your durable processor Lambda, and pass that Lambda's name to
+ * {@code DistributedMapProcessor.reportItemOutcomes} in the parent's distributed map call.
+ *
+ *
Note: your handler must return this method's result, because the service reads which items failed from the
+ * handler's return value. If the handler returns nothing, the service marks every item as succeeded.
+ *
+ *
It logs one ERROR line per failed item, with the run ARN, the item id and the reported error.
+ *
+ *
{@code
+ * public class OrderProcessor extends DurableHandler {
+ * public ItemHandlerResponse handleRequest(ProcessorEvent event, DurableContext context) {
+ * return DistributedMapHelpers.processDistributedMapItems(
+ * context, event,
+ * (durableCtx, order, itemContext) -> durableCtx.step("charge", String.class, s -> chargeOrder(order)),
+ * TypeToken.get(Order.class), null, null, 5);
+ * }
+ * }
+ * }
+ *
+ * @param context the handler's durable context
+ * @param event the processor event the service sent
+ * @param func the function to call on each item
+ * @param itemType the item type
+ * @param itemSerDes the serdes that reads each item, or null for the default JSON serdes
+ * @param resultSerDes the serdes that writes each output, or null for the default JSON serdes
+ * @param concurrency the maximum number of items processed at the same time (default: 1), at least 1. When greater
+ * than 1, {@code func}, {@code itemSerDes} and {@code resultSerDes} are called from several threads at the same
+ * time, so each must be safe for concurrent calls.
+ * @return the response the handler must return
+ */
+ public static ItemHandlerResponse processDistributedMapItems(
+ DurableContext context,
+ ProcessorEvent event,
+ DurableItemFunction func,
+ TypeToken itemType,
+ SerDes itemSerDes,
+ SerDes resultSerDes,
+ int concurrency) {
+ return processDistributedMapItems(
+ context, event, func, itemType, itemSerDes, resultSerDes, concurrency, NestingType.FLAT);
+ }
+
+ /**
+ * Calls {@code func} on each item in the batch under its own durable context, and returns each item's result or
+ * error in the format the service expects.
+ *
+ * Call it in the handler of your durable processor Lambda, and pass that Lambda's name to
+ * {@code DistributedMapProcessor.reportItemOutcomes} in the parent's distributed map call.
+ *
+ *
Note: your handler must return this method's result, because the service reads which items failed from the
+ * handler's return value. If the handler returns nothing, the service marks every item as succeeded.
+ *
+ *
It logs one ERROR line per failed item, with the run ARN, the item id and the reported error.
+ *
+ *
{@code
+ * public class OrderProcessor extends DurableHandler {
+ * public ItemHandlerResponse handleRequest(ProcessorEvent event, DurableContext context) {
+ * return DistributedMapHelpers.processDistributedMapItems(
+ * context, event,
+ * (durableCtx, order, itemContext) -> durableCtx.step("charge", String.class, s -> chargeOrder(order)),
+ * TypeToken.get(Order.class), null, null, 5, NestingType.NESTED);
+ * }
+ * }
+ * }
+ *
+ * @param context the handler's durable context
+ * @param event the processor event the service sent
+ * @param func the function to call on each item
+ * @param itemType the item type
+ * @param itemSerDes the serdes that reads each item, or null for the default JSON serdes
+ * @param resultSerDes the serdes that writes each output, or null for the default JSON serdes
+ * @param concurrency the maximum number of items processed at the same time (default: 1), at least 1. When greater
+ * than 1, {@code func}, {@code itemSerDes} and {@code resultSerDes} are called from several threads at the same
+ * time, so each must be safe for concurrent calls.
+ * @param nestingType the nesting type for the map iterations (default: {@link NestingType#FLAT})
+ * @return the response the handler must return
+ */
+ public static ItemHandlerResponse processDistributedMapItems(
+ DurableContext context,
+ ProcessorEvent event,
+ DurableItemFunction func,
+ TypeToken itemType,
+ SerDes itemSerDes,
+ SerDes resultSerDes,
+ int concurrency,
+ NestingType nestingType) {
+ validateConcurrency(concurrency);
+ var inSerdes = itemSerDes != null ? itemSerDes : JSON;
+ var outSerdes = resultSerDes != null ? resultSerDes : JSON;
+ var records = event.records();
+ var bodies = new ArrayList(records.size());
+ for (var record : records) {
+ bodies.add(record.body());
+ }
+ // Every item runs to completion, so one failing item never cancels another that would succeed.
+ MapResult batch = context.map(
+ ITEMS_OP_NAME,
+ bodies,
+ OUTPUT_TYPE,
+ (body, index, mapContext) -> {
+ var itemContext = new ItemContext(
+ event.distributedMapRunArn(), records.get(index).itemId());
+ O output = func.apply(mapContext, inSerdes.deserialize(body, itemType), itemContext);
+ return toOutput(outSerdes, output);
+ },
+ MapConfig.builder()
+ .completionConfig(CompletionConfig.allCompleted())
+ .maxConcurrency(concurrency)
+ .nestingType(nestingType)
+ .build());
+ return toItemHandlerResponse(
+ event, batch, message -> context.getLogger().error(message));
+ }
+
+ /**
+ * Calls {@code func} once with all the items in the batch. Returning passes the batch, and throwing fails it.
+ *
+ * Call it in the handler of your processor Lambda, and pass that Lambda's name to
+ * {@code DistributedMapProcessor.reportBatchOutcome} in the parent's distributed map call.
+ *
+ *
Note: your handler must return this method's result and must not catch its exception, because the service
+ * reads a batch failure from the handler's error. If the handler catches the exception, the failure is lost and the
+ * service marks the batch as succeeded.
+ *
+ *
It works the same in a non-durable handler and in a durable handler. In a durable handler, use the handler's
+ * own {@link DurableContext} inside {@code func}. This method does not pass it to {@code func}.
+ *
+ *
{@code
+ * public class RowWriter implements RequestHandler {
+ * public Void handleRequest(ProcessorEvent event, Context context) {
+ * return DistributedMapHelpers.processDistributedMapBatch(
+ * event, (List rows, BatchContext batchContext) -> writeRows(rows),
+ * TypeToken.get(Row.class), null);
+ * }
+ * }
+ * }
+ *
+ * @param event the processor event the service sent
+ * @param func the function to call once with all the items
+ * @param itemType the item type
+ * @param itemSerDes the serdes that reads each item, or null for the default JSON serdes
+ * @return null, which the handler must return
+ */
+ public static Void processDistributedMapBatch(
+ ProcessorEvent event, BiConsumer, BatchContext> func, TypeToken itemType, SerDes itemSerDes) {
+ var serdes = itemSerDes != null ? itemSerDes : JSON;
+ var records = event.records();
+ var items = new ArrayList(records.size());
+ for (var record : records) {
+ items.add(serdes.deserialize(record.body(), itemType));
+ }
+ func.accept(
+ items,
+ new BatchContext(
+ event.distributedMapRunArn(),
+ records.stream().map(ProcessorRecord::itemId).toList()));
+ return null;
+ }
+
+ /**
+ * Calls {@code func} to read one page of items, and returns the page in the format the service expects. A null next
+ * state means the source has no more items.
+ *
+ * Call it in the handler of your reader Lambda, and pass that Lambda's name to
+ * {@code DistributedMapSource.reader} in the parent's distributed map call.
+ *
+ *
Note: your handler must return this method's result, because the service reads the page from the handler's
+ * return value.
+ *
+ *
{@code itemSerDes} must be the serdes the processor is configured with, since the processor deserializes every
+ * item body with its own item serdes. The reader and the processor are separate Lambdas, so nothing checks that
+ * they match.
+ *
+ *
{@code
+ * public class CustomerReader implements RequestHandler {
+ * public ReaderResponse handleRequest(ReaderEvent event, Context context) {
+ * return DistributedMapHelpers.readDistributedMapPage(
+ * event, (String cursor, Integer maxItemsPerPage, ReaderContext readerContext) -> {
+ * var page = listCustomers(cursor, maxItemsPerPage);
+ * return new ReaderPage<>(page.customers(), page.nextCursor());
+ * },
+ * TypeToken.get(String.class), null, null);
+ * }
+ * }
+ * }
+ *
+ * @param event the reader event the service sent
+ * @param func the function that reads one page
+ * @param stateType the state type
+ * @param stateSerDes the serdes for the state, or null for the default JSON serdes
+ * @param itemSerDes the serdes that writes each item, or null for the default JSON serdes
+ * @return the response the handler must return
+ */
+ public static ReaderResponse readDistributedMapPage(
+ ReaderEvent event,
+ ReaderFunction func,
+ TypeToken stateType,
+ SerDes stateSerDes,
+ SerDes itemSerDes) {
+ var serdes = stateSerDes != null ? stateSerDes : JSON;
+ var itemSerdes = itemSerDes != null ? itemSerDes : JSON;
+ S state = event.state() != null ? serdes.deserialize(event.state(), stateType) : null;
+
+ var page = func.apply(state, event.maxItemsPerPage(), new ReaderContext(event.distributedMapRunArn()));
+ if (page.items().size() > event.maxItemsPerPage()) {
+ throw new IllegalStateException("reader returned " + page.items().size()
+ + " items, exceeding maxItemsPerPage " + event.maxItemsPerPage());
+ }
+ var items = new ArrayList(page.items().size());
+ var index = 0;
+ for (I item : page.items()) {
+ var body = itemSerdes.serialize(item);
+ if (body == null) {
+ // The service requires every item to be a string, so a null item is sent as the JSON literal null.
+ if (item != null) {
+ throw new IllegalStateException("serialization of reader item " + index + " produced no string");
+ }
+ body = "null";
+ }
+ items.add(body);
+ index++;
+ }
+ String nextState = null;
+ if (page.nextState() != null) {
+ nextState = serdes.serialize(page.nextState());
+ if (nextState == null) {
+ throw new IllegalStateException("serialization of reader nextState produced no string");
+ }
+ if (nextState.getBytes(StandardCharsets.UTF_8).length > READER_STATE_LIMIT) {
+ throw new IllegalStateException(
+ "reader nextState exceeds the " + (READER_STATE_LIMIT / 1024) + " KB limit");
+ }
+ // The next call would repeat the same position, and the service rejects it as a source failure.
+ if (nextState.equals(event.state())) {
+ throw new IllegalStateException(
+ "reader nextState must differ from the state it was called with, or the next page repeats the same position");
+ }
+ }
+ return new ReaderResponse(items, nextState);
+ }
+
+ private static void validateConcurrency(int concurrency) {
+ if (concurrency < MIN_CONCURRENCY) {
+ throw new IllegalArgumentException(
+ "concurrency must be at least " + MIN_CONCURRENCY + ", got: " + concurrency);
+ }
+ }
+
+ private static ItemHandlerResponse toItemHandlerResponse(
+ ProcessorEvent event, MapResult batch, Consumer logError) {
+ var records = event.records();
+ var results = new ArrayList();
+ var failures = new ArrayList();
+ for (var i = 0; i < records.size(); i++) {
+ var itemId = records.get(i).itemId();
+ var item = batch.getItem(i);
+ if (item.status() == MapResult.MapResultItem.Status.SUCCEEDED) {
+ results.add(new ItemResult(itemId, item.result()));
+ } else {
+ var error = item.error();
+ var failure = new ItemFailure(
+ itemId,
+ error != null
+ ? new DistributedMapError(
+ error.errorType(), error.errorMessage(), null, error.stackTrace())
+ : null);
+ logItemFailure(event.distributedMapRunArn(), failure, logError);
+ failures.add(failure);
+ }
+ }
+ return new ItemHandlerResponse(results, failures);
+ }
+
+ // Puts the failure's fields in the MDC for the one log call, then removes exactly those keys.
+ static void logItemFailure(String runArn, ItemFailure failure, Consumer logError) {
+ var fields = new LinkedHashMap();
+ fields.put("distributedMapRunArn", runArn);
+ fields.put("itemId", failure.itemIdentifier());
+ var error = failure.error();
+ if (error != null) {
+ fields.put("errorType", error.errorType());
+ fields.put("errorMessage", error.errorMessage());
+ fields.put("errorData", error.errorData());
+ fields.put("stackTrace", error.stackTrace() != null ? String.join("\n", error.stackTrace()) : null);
+ }
+ fields.values().removeIf(Objects::isNull);
+ fields.forEach(MDC::put);
+ try {
+ logError.accept("distributed map item failed");
+ } finally {
+ fields.keySet().forEach(MDC::remove);
+ }
+ }
+
+ /** Serializes an item's output, or returns null when the handler returned nothing. */
+ private static String toOutput(SerDes serdes, Object output) {
+ if (output == null) {
+ return null;
+ }
+ var body = serdes.serialize(output);
+ if (body == null) {
+ throw new IllegalStateException("serialization of item output produced no string");
+ }
+ return body;
+ }
+}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/dmap/ItemContext.java b/sdk/src/main/java/software/amazon/lambda/durable/dmap/ItemContext.java
new file mode 100644
index 0000000000..9c885b9d0c
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/dmap/ItemContext.java
@@ -0,0 +1,11 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.dmap;
+
+/**
+ * The context an item function receives with one item.
+ *
+ * @param distributedMapRunArn the ARN of the distributed map run the item belongs to
+ * @param itemId the item's identifier, assigned by the service
+ */
+public record ItemContext(String distributedMapRunArn, String itemId) {}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/dmap/ItemFailure.java b/sdk/src/main/java/software/amazon/lambda/durable/dmap/ItemFailure.java
new file mode 100644
index 0000000000..f989607407
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/dmap/ItemFailure.java
@@ -0,0 +1,13 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.dmap;
+
+import software.amazon.lambda.durable.model.DistributedMapError;
+
+/**
+ * A failed item in a processor response.
+ *
+ * @param itemIdentifier the item's identifier, copied from the input record
+ * @param error why the item failed, or null to report a failure with no detail
+ */
+public record ItemFailure(String itemIdentifier, DistributedMapError error) {}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/dmap/ItemHandlerResponse.java b/sdk/src/main/java/software/amazon/lambda/durable/dmap/ItemHandlerResponse.java
new file mode 100644
index 0000000000..acb9d80a28
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/dmap/ItemHandlerResponse.java
@@ -0,0 +1,17 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.dmap;
+
+import java.util.List;
+
+/**
+ * The reply an item handler returns.
+ *
+ * A null list is omitted from the JSON rather than sent as null, because the Lambda runtime's serializer excludes
+ * null fields. The service treats an absent, null, or empty list identically, so this is a shape choice rather than a
+ * behavioural one.
+ *
+ * @param batchItemResults per-item outputs, or null to leave the key off the wire
+ * @param batchItemFailures the items that failed
+ */
+public record ItemHandlerResponse(List batchItemResults, List batchItemFailures) {}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/dmap/ItemResult.java b/sdk/src/main/java/software/amazon/lambda/durable/dmap/ItemResult.java
new file mode 100644
index 0000000000..82d50f25f0
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/dmap/ItemResult.java
@@ -0,0 +1,12 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.dmap;
+
+/**
+ * A succeeded item in a processor response.
+ *
+ * @param itemIdentifier the item's identifier, copied from the input record
+ * @param output the item's output as the result serdes produced it, or null when the handler returned nothing. A null
+ * output means the item succeeded without an output.
+ */
+public record ItemResult(String itemIdentifier, String output) {}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/dmap/ProcessorEvent.java b/sdk/src/main/java/software/amazon/lambda/durable/dmap/ProcessorEvent.java
new file mode 100644
index 0000000000..53489873d3
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/dmap/ProcessorEvent.java
@@ -0,0 +1,30 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.dmap;
+
+import java.util.List;
+
+/**
+ * The batch the fan-out service sends to a processor function.
+ *
+ * @param distributedMapRunArn the ARN of the distributed map run this batch belongs to
+ * @param records the items in this batch
+ */
+public record ProcessorEvent(String distributedMapRunArn, List records) {
+
+ /**
+ * Rejects an event that is not a processor batch. This runs on instances the Lambda runtime deserializes as well as
+ * on hand-constructed ones, because a record can only be built through its canonical constructor.
+ */
+ public ProcessorEvent {
+ if (records == null) {
+ throw new IllegalStateException("expected a distributed map processor event carrying a 'records' array, "
+ + "the function must be triggered by a distributed map, not invoked directly. An event source "
+ + "such as SQS or S3 sends a capitalised 'Records' array, which is a different contract");
+ }
+ if (distributedMapRunArn == null || distributedMapRunArn.isEmpty()) {
+ throw new IllegalStateException(
+ "expected a distributed map processor event to have a 'distributedMapRunArn'");
+ }
+ }
+}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/dmap/ProcessorRecord.java b/sdk/src/main/java/software/amazon/lambda/durable/dmap/ProcessorRecord.java
new file mode 100644
index 0000000000..259fc2dab2
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/dmap/ProcessorRecord.java
@@ -0,0 +1,22 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.dmap;
+
+/**
+ * One record of a processor event.
+ *
+ * @param itemId the item's identifier, assigned by the service
+ * @param body the serialized item, as the item serdes produced it
+ */
+public record ProcessorRecord(String itemId, String body) {
+
+ /**
+ * Rejects a record with no item id. The helpers report each outcome against this id, so a record without one would
+ * report its outcome against no item. This runs on instances the Lambda runtime deserializes as well.
+ */
+ public ProcessorRecord {
+ if (itemId == null || itemId.isEmpty()) {
+ throw new IllegalStateException("expected each distributed map processor record to have an 'itemId'");
+ }
+ }
+}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/dmap/ReaderContext.java b/sdk/src/main/java/software/amazon/lambda/durable/dmap/ReaderContext.java
new file mode 100644
index 0000000000..e1b0dca219
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/dmap/ReaderContext.java
@@ -0,0 +1,10 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.dmap;
+
+/**
+ * The context a reader function receives with each page request.
+ *
+ * @param distributedMapRunArn the ARN of the distributed map run the page is read for
+ */
+public record ReaderContext(String distributedMapRunArn) {}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/dmap/ReaderEvent.java b/sdk/src/main/java/software/amazon/lambda/durable/dmap/ReaderEvent.java
new file mode 100644
index 0000000000..15de692964
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/dmap/ReaderEvent.java
@@ -0,0 +1,26 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.dmap;
+
+/**
+ * The request the fan-out service sends to a reader function.
+ *
+ * @param distributedMapRunArn the ARN of the distributed map run this page is read for
+ * @param maxItemsPerPage the most items the reader may return in this page. Boxed because the Lambda runtime turns an
+ * absent primitive into zero, which would be indistinguishable from a real value
+ * @param state the opaque state from the previous call, or null on the first call
+ */
+public record ReaderEvent(String distributedMapRunArn, Integer maxItemsPerPage, String state) {
+
+ /** Rejects an event that is not a reader request. Runs on runtime-deserialized instances too. */
+ public ReaderEvent {
+ if (maxItemsPerPage == null) {
+ throw new IllegalStateException(
+ "expected a distributed map reader event carrying a numeric 'maxItemsPerPage', "
+ + "the function must be registered as a distributed map reader");
+ }
+ if (distributedMapRunArn == null || distributedMapRunArn.isEmpty()) {
+ throw new IllegalStateException("expected a distributed map reader event to have a 'distributedMapRunArn'");
+ }
+ }
+}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/dmap/ReaderPage.java b/sdk/src/main/java/software/amazon/lambda/durable/dmap/ReaderPage.java
new file mode 100644
index 0000000000..1c428ffbd2
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/dmap/ReaderPage.java
@@ -0,0 +1,17 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.dmap;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/** A page of items and the next state returned by a distributed map reader function. */
+public record ReaderPage(List items, S nextState) {
+
+ /** Applies a defensive copy and defaults. */
+ public ReaderPage {
+ // A null item is valid and is sent as the JSON literal null. List.copyOf rejects null elements.
+ items = items != null ? Collections.unmodifiableList(new ArrayList<>(items)) : Collections.emptyList();
+ }
+}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/dmap/ReaderResponse.java b/sdk/src/main/java/software/amazon/lambda/durable/dmap/ReaderResponse.java
new file mode 100644
index 0000000000..721434dfe1
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/dmap/ReaderResponse.java
@@ -0,0 +1,16 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.dmap;
+
+import java.util.List;
+
+/**
+ * The page a reader function returns.
+ *
+ * A null nextState is omitted from the JSON rather than sent as null, because the Lambda runtime's serializer
+ * excludes null fields. Omitting the key is how the reader contract signals that the source is exhausted.
+ *
+ * @param items this page's items, each serialized with the reader's item serdes
+ * @param nextState the state to resume from, or null when the source is exhausted
+ */
+public record ReaderResponse(List items, String nextState) {}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/exception/DistributedMapException.java b/sdk/src/main/java/software/amazon/lambda/durable/exception/DistributedMapException.java
new file mode 100644
index 0000000000..3a29a47d61
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/exception/DistributedMapException.java
@@ -0,0 +1,75 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.exception;
+
+import software.amazon.lambda.durable.model.DistributedMapError;
+import software.amazon.lambda.durable.model.DistributedMapStatus;
+
+/**
+ * Thrown by throwIfError when a distributed map run did not fully succeed, or when an item failed on a run that
+ * otherwise succeeded. It reports an aggregate run result and is not a single operation failure, so it stays out of the
+ * DurableOperationException hierarchy.
+ */
+public class DistributedMapException extends DurableExecutionException {
+ private final DistributedMapStatus status;
+ private final DistributedMapError error;
+ private final long failureCount;
+
+ /** Run outcome failure describing the run status, failure count, and the run's error details. */
+ public DistributedMapException(DistributedMapStatus status, long failureCount, DistributedMapError error) {
+ super(runMessage(status, failureCount, error));
+ this.status = status;
+ this.error = error;
+ this.failureCount = failureCount;
+ }
+
+ /** Item failure surfacing the first failed item's error. */
+ public DistributedMapException(
+ DistributedMapStatus status, long failureCount, DistributedMapError error, String itemId) {
+ super(itemMessage(error, itemId));
+ this.status = status;
+ this.error = error;
+ this.failureCount = failureCount;
+ }
+
+ /** Returns the terminal run status. */
+ public DistributedMapStatus status() {
+ return status;
+ }
+
+ /** Returns the error details, or null when none were recorded. */
+ public DistributedMapError error() {
+ return error;
+ }
+
+ /** Returns the count of failed items. */
+ public long failureCount() {
+ return failureCount;
+ }
+
+ private static String runMessage(DistributedMapStatus status, long failureCount, DistributedMapError error) {
+ var message = new StringBuilder("Distributed map run ").append(status);
+ if (failureCount > 0) {
+ message.append(", ").append(failureCount).append(" item(s) failed");
+ }
+ if (error != null && error.errorMessage() != null) {
+ message.append(": ").append(error.errorMessage());
+ }
+ return message.toString();
+ }
+
+ private static String itemMessage(DistributedMapError error, String itemId) {
+ var type = error != null ? error.errorType() : null;
+ var message = error != null ? error.errorMessage() : null;
+ var hasType = type != null && !type.isEmpty();
+ var hasMessage = message != null && !message.isEmpty();
+ var result = new StringBuilder("Distributed map item ").append(itemId).append(" failed");
+ if (hasType) {
+ result.append(": ").append(type);
+ }
+ if (hasMessage) {
+ result.append(": ").append(message);
+ }
+ return result.toString();
+ }
+}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/execution/DurableExecutor.java b/sdk/src/main/java/software/amazon/lambda/durable/execution/DurableExecutor.java
index 64fe95c5a2..4c7a13ff99 100644
--- a/sdk/src/main/java/software/amazon/lambda/durable/execution/DurableExecutor.java
+++ b/sdk/src/main/java/software/amazon/lambda/durable/execution/DurableExecutor.java
@@ -29,6 +29,7 @@
import software.amazon.lambda.durable.DurableContext;
import software.amazon.lambda.durable.TypeToken;
import software.amazon.lambda.durable.context.DurableContextImpl;
+import software.amazon.lambda.durable.dmap.ProcessorEvent;
import software.amazon.lambda.durable.exception.DurableOperationException;
import software.amazon.lambda.durable.exception.IllegalDurableOperationException;
import software.amazon.lambda.durable.exception.UnrecoverableDurableExecutionException;
@@ -41,6 +42,7 @@
import software.amazon.lambda.durable.plugin.InvocationStatus;
import software.amazon.lambda.durable.plugin.PluginInfoConverter;
import software.amazon.lambda.durable.plugin.PluginRunner;
+import software.amazon.lambda.durable.serde.JacksonSerDes;
import software.amazon.lambda.durable.serde.SerDes;
import software.amazon.lambda.durable.util.ExceptionHelper;
@@ -58,6 +60,7 @@ public class DurableExecutor {
// Lambda response size limit is 6MB minus small epsilon for envelope
private static final int LAMBDA_RESPONSE_SIZE_LIMIT = 6 * 1024 * 1024 - 50;
+ private static final SerDes JSON = new JacksonSerDes();
private DurableExecutor() {}
@@ -96,6 +99,7 @@ private static final class Invocation {
private final DurableConfig config;
private final ExecutionManager manager;
private final PluginRunner plugins;
+ private final SerDes invocationSerDes;
private final String requestId;
private final String executionArn;
private final boolean isFirstInvocation;
@@ -117,6 +121,9 @@ private Invocation(
this.config = config;
this.manager = manager;
plugins = manager.getPluginRunner();
+ // A distributed map processor's input and result have a format the service defines, so a customer's SerDes
+ // must not change them. Durable operations inside the processor still use the config's SerDes.
+ invocationSerDes = inputType.getType() == ProcessorEvent.class ? JSON : config.getSerDes();
// Read on the runtime caller before executor dispatch: LMI carriers can be thread-local.
xRayTraceId = plugins.isEmpty() ? null : RuntimeTraceHeader.capture(lambdaContext);
requestId = lambdaContext != null ? lambdaContext.getAwsRequestId() : null;
@@ -167,7 +174,7 @@ private O invokeHandler() {
manager.setCurrentThreadContext(new ThreadContext(ROOT_THREAD_ID, ThreadType.CONTEXT));
Throwable inputFailure = null;
try {
- userInput = extractUserInput(manager.getExecutionOperation(), config.getSerDes(), inputType);
+ userInput = extractUserInput(manager.getExecutionOperation(), invocationSerDes, inputType);
} catch (Throwable failure) {
// Deserialize only once. Even failed input gets paired start/end hooks with a null input value.
inputFailure = failure;
@@ -212,7 +219,7 @@ private DurableExecutionOutput finishInvocation(O value, Throwable failure) {
if (failure != null) return finishFailure(ExceptionHelper.unwrapInvocationFailure(failure));
DurableExecutionOutput output;
try {
- var payload = config.getSerDes().serialize(value);
+ var payload = invocationSerDes.serialize(value);
output = DurableExecutionOutput.success(handleLargePayload(manager, payload));
} catch (Throwable deliveryFailure) {
// Checkpointing a large result fails with SuspendExecutionException when the token is already gone.
@@ -250,7 +257,7 @@ private DurableExecutionOutput finishTerminalFailure(Throwable cause) {
DurableExecutionOutput output;
try {
logger.debug("Execution failed: {}", cause.getMessage());
- output = DurableExecutionOutput.failure(buildErrorObject(cause, config.getSerDes()));
+ output = DurableExecutionOutput.failure(buildErrorObject(cause, invocationSerDes));
} catch (Throwable deliveryFailure) {
return failDelivery(deliveryFailure);
}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/model/DistributedMapError.java b/sdk/src/main/java/software/amazon/lambda/durable/model/DistributedMapError.java
new file mode 100644
index 0000000000..5b14bc2f7f
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/model/DistributedMapError.java
@@ -0,0 +1,22 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.model;
+
+import java.util.List;
+import software.amazon.lambda.durable.util.ExceptionHelper;
+
+/**
+ * Error details on a distributed map run or one of its items.
+ *
+ * Held as a record rather than the client's ErrorObject, so it survives serialization across checkpoint-and-replay
+ * cycles without requiring AWS SDK-specific Jackson modules.
+ */
+public record DistributedMapError(String errorType, String errorMessage, String errorData, List stackTrace) {
+
+ /** Creates an error from a throwable. */
+ public static DistributedMapError of(Throwable e) {
+ // errorData stays null. A throwable carries no machine-readable error data, so there is nothing to put here.
+ return new DistributedMapError(
+ e.getClass().getName(), e.getMessage(), null, ExceptionHelper.serializeStackTrace(e.getStackTrace()));
+ }
+}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/model/DistributedMapResult.java b/sdk/src/main/java/software/amazon/lambda/durable/model/DistributedMapResult.java
new file mode 100644
index 0000000000..917bc12dc8
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/model/DistributedMapResult.java
@@ -0,0 +1,140 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.model;
+
+import java.util.Collections;
+import java.util.List;
+import software.amazon.lambda.durable.exception.DistributedMapException;
+
+/**
+ * Outcome of a distributed map run with collected per-item results.
+ *
+ * An item whose status this SDK version does not recognize is kept in {@code items} with status
+ * {@link Item.Status#UNKNOWN_TO_SDK_VERSION}. It is excluded from {@link #succeeded()}, {@link #failed()},
+ * {@link #results()} and {@link #errors()}.
+ */
+public record DistributedMapResult(DistributedMapSummary summary, List- > items) {
+
+ /** Applies a defensive copy and defaults. */
+ public DistributedMapResult {
+ items = items != null ? List.copyOf(items) : Collections.emptyList();
+ }
+
+ /** Returns items that succeeded. */
+ public List
- > succeeded() {
+ return items.stream()
+ .filter(item -> item.status() == Item.Status.SUCCEEDED)
+ .toList();
+ }
+
+ /** Returns items that failed. */
+ public List
- > failed() {
+ return items.stream()
+ .filter(item -> item.status() == Item.Status.FAILED)
+ .toList();
+ }
+
+ /** Returns the outputs of succeeded items (includes null outputs from successful items). */
+ public List results() {
+ return succeeded().stream().map(Item::output).toList();
+ }
+
+ /** Returns the errors of failed items (includes nulls for items that failed without error details). */
+ public List errors() {
+ return failed().stream().map(Item::error).toList();
+ }
+
+ /** Returns the terminal run status. */
+ public DistributedMapStatus status() {
+ return summary.status();
+ }
+
+ /** Returns true only when the service read the complete source, or null before run creation. */
+ public Boolean sourceExhausted() {
+ return summary.sourceExhausted();
+ }
+
+ /** Returns the count of succeeded items. */
+ public long successCount() {
+ return summary.successCount();
+ }
+
+ /** Returns the count of failed items. */
+ public long failureCount() {
+ return summary.failureCount();
+ }
+
+ /**
+ * Returns the number of items the run read from its source. For an inline source, every admitted item counts as
+ * read when the run starts.
+ */
+ public long readCount() {
+ return summary.readCount();
+ }
+
+ /** Returns the total item count, or null until known. */
+ public Long totalCount() {
+ return summary.totalCount();
+ }
+
+ /** Returns the run ARN, or null when the run never started. */
+ public String distributedMapRunArn() {
+ return summary.distributedMapRunArn();
+ }
+
+ /** Returns why the run did not succeed, or null when the service recorded no error details. */
+ public DistributedMapError error() {
+ return summary.error();
+ }
+
+ /** Returns true when any item failed. */
+ public boolean hasFailure() {
+ return summary.hasFailure();
+ }
+
+ /**
+ * Throws DistributedMapException when the run did not succeed or any item failed. When the run succeeded and the
+ * result contains a failed item, the exception names the first failed item.
+ */
+ public void throwIfError() {
+ if (summary.status() != DistributedMapStatus.SUCCEEDED) {
+ summary.throwIfError();
+ return;
+ }
+ var failedItems = failed();
+ if (!failedItems.isEmpty()) {
+ var first = failedItems.get(0);
+ throw new DistributedMapException(summary.status(), summary.failureCount(), first.error(), first.itemId());
+ }
+ if (summary.hasFailure()) {
+ summary.throwIfError();
+ }
+ }
+
+ /** Outcome of a single distributed map item. */
+ public record Item(String itemId, Status status, O output, DistributedMapError error) {
+
+ /** Status of an individual distributed map item. */
+ public enum Status {
+ SUCCEEDED,
+ FAILED,
+ /** A status the backend returned that this SDK version does not recognize. */
+ UNKNOWN_TO_SDK_VERSION
+ }
+
+ /** Creates a succeeded item. */
+ public static Item succeeded(String itemId, O output) {
+ return new Item<>(itemId, Status.SUCCEEDED, output, null);
+ }
+
+ /** Creates a failed item. */
+ public static Item failed(String itemId, DistributedMapError error) {
+ return new Item<>(itemId, Status.FAILED, null, error);
+ }
+
+ /** Creates an item whose status this SDK version does not recognize. */
+ public static Item unknown(String itemId) {
+ return new Item<>(itemId, Status.UNKNOWN_TO_SDK_VERSION, null, null);
+ }
+ }
+}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/model/DistributedMapStatus.java b/sdk/src/main/java/software/amazon/lambda/durable/model/DistributedMapStatus.java
new file mode 100644
index 0000000000..421f6e836b
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/model/DistributedMapStatus.java
@@ -0,0 +1,11 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.model;
+
+/** Terminal status of a distributed map run. */
+public enum DistributedMapStatus {
+ SUCCEEDED,
+ FAILED,
+ STOPPED,
+ TIMED_OUT
+}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/model/DistributedMapSummary.java b/sdk/src/main/java/software/amazon/lambda/durable/model/DistributedMapSummary.java
new file mode 100644
index 0000000000..98c1ae354c
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/model/DistributedMapSummary.java
@@ -0,0 +1,36 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.model;
+
+import software.amazon.lambda.durable.exception.DistributedMapException;
+
+/**
+ * Outcome of a distributed map run, without per-item results.
+ *
+ * @param sourceExhausted true only when the service read the complete source, null before run creation
+ * @param readCount number of items the run read from its source; for an inline source, every admitted item counts as
+ * read when the run starts
+ * @param error why the run did not succeed, when the service recorded error details
+ */
+public record DistributedMapSummary(
+ DistributedMapStatus status,
+ Boolean sourceExhausted,
+ long successCount,
+ long failureCount,
+ long readCount,
+ String distributedMapRunArn,
+ DistributedMapError error,
+ Long totalCount) {
+
+ /** Returns true when any item failed. */
+ public boolean hasFailure() {
+ return failureCount > 0;
+ }
+
+ /** Throws DistributedMapException when the run did not fully succeed. */
+ public void throwIfError() {
+ if (status != DistributedMapStatus.SUCCEEDED || hasFailure()) {
+ throw new DistributedMapException(status, failureCount, error);
+ }
+ }
+}
diff --git a/sdk/src/main/java/software/amazon/lambda/durable/util/DistributedMapValidation.java b/sdk/src/main/java/software/amazon/lambda/durable/util/DistributedMapValidation.java
new file mode 100644
index 0000000000..b7b1f4fff2
--- /dev/null
+++ b/sdk/src/main/java/software/amazon/lambda/durable/util/DistributedMapValidation.java
@@ -0,0 +1,48 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.util;
+
+import java.util.regex.Pattern;
+
+/** Shared validation and S3 URI parsing for distributed map configuration. */
+public final class DistributedMapValidation {
+ private static final Pattern ACCOUNT_ID = Pattern.compile("\\d{12}");
+ private static final String S3_SCHEME = "s3://";
+ private static final int MAX_FUNCTION_NAME_LENGTH = 170;
+
+ private DistributedMapValidation() {}
+
+ public static void validateFunctionName(String functionName) {
+ if (functionName == null || functionName.isBlank()) {
+ throw new IllegalArgumentException("function name cannot be empty");
+ }
+ if (functionName.length() > MAX_FUNCTION_NAME_LENGTH) {
+ throw new IllegalArgumentException(
+ "function name must be at most 170 characters, got: " + functionName.length());
+ }
+ }
+
+ public static void validateBucketOwner(String expectedBucketOwner) {
+ if (expectedBucketOwner != null
+ && !ACCOUNT_ID.matcher(expectedBucketOwner).matches()) {
+ throw new IllegalArgumentException(
+ "expectedBucketOwner must be a 12-digit account id, got: " + expectedBucketOwner);
+ }
+ }
+
+ public static ParsedS3Uri parseS3Uri(String uri) {
+ if (uri == null || !uri.startsWith(S3_SCHEME)) {
+ throw new IllegalArgumentException("S3 URI must start with s3://, got: " + uri);
+ }
+ var remainder = uri.substring(S3_SCHEME.length());
+ var slash = remainder.indexOf('/');
+ var bucket = slash < 0 ? remainder : remainder.substring(0, slash);
+ var path = slash < 0 ? null : remainder.substring(slash + 1);
+ if (bucket.isEmpty()) {
+ throw new IllegalArgumentException("S3 URI must contain a bucket, got: " + uri);
+ }
+ return new ParsedS3Uri(bucket, path == null || path.isEmpty() ? null : path);
+ }
+
+ public record ParsedS3Uri(String bucket, String path) {}
+}
diff --git a/sdk/src/test/java/software/amazon/lambda/durable/config/DistributedMapConfigTest.java b/sdk/src/test/java/software/amazon/lambda/durable/config/DistributedMapConfigTest.java
new file mode 100644
index 0000000000..40b1e006ae
--- /dev/null
+++ b/sdk/src/test/java/software/amazon/lambda/durable/config/DistributedMapConfigTest.java
@@ -0,0 +1,132 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.config;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+class DistributedMapConfigTest {
+
+ @Test
+ void failureCount_setsCount() {
+ var config = DistributedMapConfig.CompletionConfig.failureCount(3);
+
+ assertEquals(3, config.toleratedFailureCount());
+ assertNull(config.toleratedFailurePercentage());
+ assertNull(config.minimumSampleSize());
+ }
+
+ @Test
+ void failureCount_withZero_shouldPass() {
+ assertEquals(0, DistributedMapConfig.CompletionConfig.failureCount(0).toleratedFailureCount());
+ }
+
+ @Test
+ void failurePercentage_setsPercentage() {
+ var config = DistributedMapConfig.CompletionConfig.failurePercentage(25);
+
+ assertNull(config.toleratedFailureCount());
+ assertEquals(25.0, config.toleratedFailurePercentage());
+ assertNull(config.minimumSampleSize());
+ }
+
+ @Test
+ void failurePercentage_fractional_shouldPass() {
+ assertEquals(
+ 12.5,
+ DistributedMapConfig.CompletionConfig.failurePercentage(12.5).toleratedFailurePercentage());
+ }
+
+ @Test
+ void failurePercentage_withMinimumSampleSize_setsBoth() {
+ var config = DistributedMapConfig.CompletionConfig.failurePercentage(25, 10);
+
+ assertEquals(25.0, config.toleratedFailurePercentage());
+ assertEquals(10, config.minimumSampleSize());
+ }
+
+ @Test
+ void failurePercentage_atBoundaries_shouldPass() {
+ assertEquals(
+ 0.0, DistributedMapConfig.CompletionConfig.failurePercentage(0).toleratedFailurePercentage());
+ assertEquals(
+ 100.0,
+ DistributedMapConfig.CompletionConfig.failurePercentage(100).toleratedFailurePercentage());
+ }
+
+ @Test
+ void countAndPercentage_mutuallyExclusive_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class, () -> new DistributedMapConfig.CompletionConfig(3, 25.0, null));
+ assertEquals(
+ "toleratedFailureCount and toleratedFailurePercentage are mutually exclusive", exception.getMessage());
+ }
+
+ @Test
+ void minimumSampleSize_withoutPercentage_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class, () -> new DistributedMapConfig.CompletionConfig(3, null, 5));
+ assertEquals("minimumSampleSize is only valid with toleratedFailurePercentage", exception.getMessage());
+ }
+
+ @Test
+ void completionConfig_onlyMinimumSampleSize_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class, () -> new DistributedMapConfig.CompletionConfig(null, null, 5));
+ assertEquals("minimumSampleSize is only valid with toleratedFailurePercentage", exception.getMessage());
+ }
+
+ @Test
+ void failureCount_negative_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class, () -> DistributedMapConfig.CompletionConfig.failureCount(-1));
+ assertEquals("toleratedFailureCount must be non-negative, got: -1", exception.getMessage());
+ }
+
+ @Test
+ void failurePercentage_negative_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class, () -> DistributedMapConfig.CompletionConfig.failurePercentage(-0.1));
+ assertEquals("toleratedFailurePercentage must be between 0 and 100, got: -0.1", exception.getMessage());
+ }
+
+ @Test
+ void failurePercentage_aboveHundred_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class, () -> DistributedMapConfig.CompletionConfig.failurePercentage(100.1));
+ assertEquals("toleratedFailurePercentage must be between 0 and 100, got: 100.1", exception.getMessage());
+ }
+
+ @Test
+ void failurePercentage_nan_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapConfig.CompletionConfig.failurePercentage(Double.NaN));
+ assertEquals("toleratedFailurePercentage must be a finite number, got: NaN", exception.getMessage());
+ }
+
+ @Test
+ void failurePercentage_infinite_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapConfig.CompletionConfig.failurePercentage(Double.POSITIVE_INFINITY));
+ assertEquals("toleratedFailurePercentage must be a finite number, got: Infinity", exception.getMessage());
+ }
+
+ @Test
+ void minimumSampleSize_belowOne_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class, () -> DistributedMapConfig.CompletionConfig.failurePercentage(25, 0));
+ assertEquals("minimumSampleSize must be at least 1, got: 0", exception.getMessage());
+ }
+
+ @Test
+ void emptyCompletionConfig_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class, () -> new DistributedMapConfig.CompletionConfig(null, null, null));
+ assertEquals(
+ "a completion config must set toleratedFailureCount or toleratedFailurePercentage",
+ exception.getMessage());
+ }
+}
diff --git a/sdk/src/test/java/software/amazon/lambda/durable/config/DistributedMapDestinationTest.java b/sdk/src/test/java/software/amazon/lambda/durable/config/DistributedMapDestinationTest.java
new file mode 100644
index 0000000000..d2680e7c79
--- /dev/null
+++ b/sdk/src/test/java/software/amazon/lambda/durable/config/DistributedMapDestinationTest.java
@@ -0,0 +1,216 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.config;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.NullAndEmptySource;
+
+class DistributedMapDestinationTest {
+
+ @Test
+ void successes_defaultsIncludeOutputOnly() {
+ var destination = DistributedMapDestination.s3Successes("s3://bucket/results");
+
+ assertEquals("bucket", destination.bucket());
+ assertEquals("results", destination.prefix());
+ assertFalse(destination.includeInput());
+ assertTrue(destination.includeOutput());
+ assertNull(destination.expectedBucketOwner());
+ }
+
+ @Test
+ void successes_withoutPath_prefixIsEmpty() {
+ var destination = DistributedMapDestination.s3Successes("s3://bucket");
+
+ assertEquals("bucket", destination.bucket());
+ assertEquals("", destination.prefix());
+ }
+
+ @Test
+ void successes_withAllArguments() {
+ var destination = DistributedMapDestination.s3Successes("s3://bucket/out", true, true, "123456789012");
+
+ assertEquals("bucket", destination.bucket());
+ assertEquals("out", destination.prefix());
+ assertTrue(destination.includeInput());
+ assertTrue(destination.includeOutput());
+ assertEquals("123456789012", destination.expectedBucketOwner());
+ }
+
+ @Test
+ void successes_allIncludeOff_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapDestination.s3Successes("s3://bucket/out", false, false, null));
+ assertEquals("success destination must include at least one of input or output", exception.getMessage());
+ }
+
+ @Test
+ void successDestination_allIncludeOff_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> new DistributedMapDestination.Success("bucket", "", false, false, null));
+ assertEquals("success destination must include at least one of input or output", exception.getMessage());
+ }
+
+ @ParameterizedTest
+ @NullAndEmptySource
+ void successDestination_nullOrEmptyBucket_shouldThrow(String bucket) {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> new DistributedMapDestination.Success(bucket, "", false, true, null));
+ assertEquals("success destination bucket cannot be empty", exception.getMessage());
+ }
+
+ @Test
+ void failures_defaultsIncludeInputAndError() {
+ var destination = DistributedMapDestination.s3Failures("s3://bucket/errors");
+
+ assertEquals("bucket", destination.bucket());
+ assertEquals("errors", destination.prefix());
+ assertTrue(destination.includeInput());
+ assertTrue(destination.includeError());
+ assertNull(destination.expectedBucketOwner());
+ }
+
+ @Test
+ void failures_withAllArguments() {
+ var destination = DistributedMapDestination.s3Failures("s3://bucket/err", true, false, "123456789012");
+
+ assertEquals("bucket", destination.bucket());
+ assertEquals("err", destination.prefix());
+ assertTrue(destination.includeInput());
+ assertFalse(destination.includeError());
+ assertEquals("123456789012", destination.expectedBucketOwner());
+ }
+
+ @Test
+ void failures_allIncludeOff_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapDestination.s3Failures("s3://bucket/err", false, false, null));
+ assertEquals("failure destination must include at least one of input or error", exception.getMessage());
+ }
+
+ @Test
+ void failureDestination_allIncludeOff_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> new DistributedMapDestination.Failure("bucket", "", false, false, null));
+ assertEquals("failure destination must include at least one of input or error", exception.getMessage());
+ }
+
+ @ParameterizedTest
+ @NullAndEmptySource
+ void failureDestination_nullOrEmptyBucket_shouldThrow(String bucket) {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> new DistributedMapDestination.Failure(bucket, "", true, true, null));
+ assertEquals("failure destination bucket cannot be empty", exception.getMessage());
+ }
+
+ @Test
+ void successes_invalidBucketOwner_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapDestination.s3Successes("s3://bucket/out", false, true, "123"));
+ assertEquals("expectedBucketOwner must be a 12-digit account id, got: 123", exception.getMessage());
+ }
+
+ @Test
+ void successes_invalidUri_shouldThrow() {
+ var exception =
+ assertThrows(IllegalArgumentException.class, () -> DistributedMapDestination.s3Successes("bucket/out"));
+ assertEquals("S3 URI must start with s3://, got: bucket/out", exception.getMessage());
+ }
+
+ @Test
+ void destinationConfig_onSuccess_routesSuccessOnly() {
+ var success = DistributedMapDestination.s3Successes("s3://bucket/ok");
+ var config = DistributedMapDestination.of(success);
+
+ assertSame(success, config.onSuccess());
+ assertNull(config.onFailure());
+ }
+
+ @Test
+ void destinationConfig_onFailure_routesFailureOnly() {
+ var failure = DistributedMapDestination.s3Failures("s3://bucket/bad");
+ var config = DistributedMapDestination.of(failure);
+
+ assertNull(config.onSuccess());
+ assertSame(failure, config.onFailure());
+ }
+
+ @Test
+ void destinationConfig_of_routesBoth() {
+ var success = DistributedMapDestination.s3Successes("s3://bucket/ok");
+ var failure = DistributedMapDestination.s3Failures("s3://bucket/bad");
+ var config = DistributedMapDestination.of(success, failure);
+
+ assertSame(success, config.onSuccess());
+ assertSame(failure, config.onFailure());
+ }
+
+ // ------------------------------------------------------------------
+ // key prefix length
+ // ------------------------------------------------------------------
+
+ private static String repeat(String unit, int times) {
+ return unit.repeat(times);
+ }
+
+ @Test
+ void successes_prefixAtTheByteLimit_isAccepted() {
+ var prefix = repeat("a", 900);
+
+ assertEquals(
+ prefix,
+ DistributedMapDestination.s3Successes("s3://bucket/" + prefix).prefix());
+ }
+
+ @Test
+ void successes_prefixOverTheByteLimit_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapDestination.s3Successes("s3://bucket/" + repeat("a", 901)));
+ assertEquals("destination key prefix must be at most 900 UTF-8 bytes, got: 901", exception.getMessage());
+ }
+
+ @Test
+ void failures_prefixOverTheByteLimit_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapDestination.s3Failures("s3://bucket/" + repeat("a", 901)));
+ assertEquals("destination key prefix must be at most 900 UTF-8 bytes, got: 901", exception.getMessage());
+ }
+
+ @Test
+ void successes_prefixCountsUtf8BytesNotCharacters() {
+ // This character is two UTF-8 bytes, so 450 of them are exactly 900 bytes while being only 450 characters.
+ var atTheLimit = repeat("\u00e9", 450);
+ assertEquals(450, atTheLimit.length());
+ assertEquals(
+ atTheLimit,
+ DistributedMapDestination.s3Successes("s3://bucket/" + atTheLimit)
+ .prefix());
+
+ var overTheLimit = atTheLimit + "\u00e9";
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapDestination.s3Successes("s3://bucket/" + overTheLimit));
+ assertEquals("destination key prefix must be at most 900 UTF-8 bytes, got: 902", exception.getMessage());
+ }
+
+ @Test
+ void successes_prefixLengthCountsTheTrailingSlash() {
+ // 900 characters plus the trailing slash is 901 bytes, so the slash is what pushes it over.
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapDestination.s3Successes("s3://bucket/" + repeat("a", 900) + "/"));
+ assertEquals("destination key prefix must be at most 900 UTF-8 bytes, got: 901", exception.getMessage());
+ }
+}
diff --git a/sdk/src/test/java/software/amazon/lambda/durable/config/DistributedMapProcessorRetryConfigTest.java b/sdk/src/test/java/software/amazon/lambda/durable/config/DistributedMapProcessorRetryConfigTest.java
new file mode 100644
index 0000000000..0f9178a8b8
--- /dev/null
+++ b/sdk/src/test/java/software/amazon/lambda/durable/config/DistributedMapProcessorRetryConfigTest.java
@@ -0,0 +1,80 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.config;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.time.Duration;
+import org.junit.jupiter.api.Test;
+
+class DistributedMapProcessorRetryConfigTest {
+
+ @Test
+ void build_defaultsAreNull() {
+ var retry = DistributedMapProcessorRetryConfig.builder().build();
+
+ assertNull(retry.maxRetryAttempts());
+ assertNull(retry.maxRetryDuration());
+ }
+
+ @Test
+ void maxRetryAttempts_zero_isStored() {
+ var retry =
+ DistributedMapProcessorRetryConfig.builder().maxRetryAttempts(0).build();
+
+ assertEquals(0, retry.maxRetryAttempts());
+ }
+
+ @Test
+ void maxRetryAttempts_unlimited_isStored() {
+ var retry = DistributedMapProcessorRetryConfig.builder()
+ .maxRetryAttempts(DistributedMapProcessorRetryConfig.UNLIMITED)
+ .build();
+
+ assertEquals(-1, retry.maxRetryAttempts());
+ }
+
+ @Test
+ void maxRetryAttempts_otherNegative_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapProcessorRetryConfig.builder().maxRetryAttempts(-2));
+ assertEquals(
+ "maxRetryAttempts must be non-negative or DistributedMapProcessorRetryConfig.UNLIMITED, got: -2",
+ exception.getMessage());
+ }
+
+ @Test
+ void maxRetryDuration_atBoundaries_shouldPass() {
+ assertEquals(
+ Duration.ofMinutes(1),
+ DistributedMapProcessorRetryConfig.builder()
+ .maxRetryDuration(Duration.ofMinutes(1))
+ .build()
+ .maxRetryDuration());
+ assertEquals(
+ Duration.ofHours(6),
+ DistributedMapProcessorRetryConfig.builder()
+ .maxRetryDuration(Duration.ofHours(6))
+ .build()
+ .maxRetryDuration());
+ }
+
+ @Test
+ void maxRetryDuration_belowMinimum_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapProcessorRetryConfig.builder().maxRetryDuration(Duration.ofSeconds(59)));
+ assertEquals("maxRetryDuration must be between 1 minute and 6 hours, got: 59s", exception.getMessage());
+ }
+
+ @Test
+ void maxRetryDuration_aboveMaximum_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapProcessorRetryConfig.builder().maxRetryDuration(Duration.ofHours(7)));
+ assertEquals("maxRetryDuration must be between 1 minute and 6 hours, got: 25200s", exception.getMessage());
+ }
+}
diff --git a/sdk/src/test/java/software/amazon/lambda/durable/config/DistributedMapProcessorTest.java b/sdk/src/test/java/software/amazon/lambda/durable/config/DistributedMapProcessorTest.java
new file mode 100644
index 0000000000..c6adde8f60
--- /dev/null
+++ b/sdk/src/test/java/software/amazon/lambda/durable/config/DistributedMapProcessorTest.java
@@ -0,0 +1,181 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.config;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.time.Duration;
+import org.junit.jupiter.api.Test;
+
+class DistributedMapProcessorTest {
+
+ @Test
+ void batch_setsBatchMode() {
+ var processor = DistributedMapProcessor.reportBatchOutcome("fn").build();
+
+ assertEquals("fn", processor.functionName());
+ assertEquals(DistributedMapProcessor.ResponseMode.BATCH, processor.responseMode());
+ }
+
+ @Test
+ void itemOutcomes_setsItemOutcomesMode() {
+ var processor = DistributedMapProcessor.reportItemOutcomes("fn").build();
+
+ assertEquals(DistributedMapProcessor.ResponseMode.ITEM_OUTCOMES, processor.responseMode());
+ }
+
+ @Test
+ void build_defaultsAreNull() {
+ var processor = DistributedMapProcessor.reportBatchOutcome("fn").build();
+
+ assertNull(processor.batchSize());
+ assertNull(processor.retry());
+ assertNull(processor.durableExecutionNamePrefix());
+ }
+
+ @Test
+ void batchSize_atBoundaries_shouldPass() {
+ assertEquals(
+ 1,
+ DistributedMapProcessor.reportBatchOutcome("fn")
+ .batchSize(1)
+ .build()
+ .batchSize());
+ assertEquals(
+ 10000,
+ DistributedMapProcessor.reportBatchOutcome("fn")
+ .batchSize(10000)
+ .build()
+ .batchSize());
+ }
+
+ @Test
+ void batchSize_belowMinimum_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapProcessor.reportBatchOutcome("fn")
+ .batchSize(0)
+ .build());
+ assertEquals("batchSize must be between 1 and 10000, got: 0", exception.getMessage());
+ }
+
+ @Test
+ void batchSize_aboveMaximum_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapProcessor.reportBatchOutcome("fn")
+ .batchSize(10001)
+ .build());
+ assertEquals("batchSize must be between 1 and 10000, got: 10001", exception.getMessage());
+ }
+
+ @Test
+ void durableExecutionNamePrefix_atBoundaries_shouldPass() {
+ assertEquals(
+ "a",
+ DistributedMapProcessor.reportBatchOutcome("fn")
+ .durableExecutionNamePrefix("a")
+ .build()
+ .durableExecutionNamePrefix());
+ var thirtySix = "a".repeat(36);
+ assertEquals(
+ thirtySix,
+ DistributedMapProcessor.reportBatchOutcome("fn")
+ .durableExecutionNamePrefix(thirtySix)
+ .build()
+ .durableExecutionNamePrefix());
+ }
+
+ @Test
+ void durableExecutionNamePrefix_empty_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapProcessor.reportBatchOutcome("fn")
+ .durableExecutionNamePrefix("")
+ .build());
+ assertEquals("durableExecutionNamePrefix must be between 1 and 36 characters, got: 0", exception.getMessage());
+ }
+
+ @Test
+ void durableExecutionNamePrefix_tooLong_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapProcessor.reportBatchOutcome("fn")
+ .durableExecutionNamePrefix("a".repeat(37))
+ .build());
+ assertEquals("durableExecutionNamePrefix must be between 1 and 36 characters, got: 37", exception.getMessage());
+ }
+
+ @Test
+ void retryFields_areStored() {
+ var processor = DistributedMapProcessor.reportBatchOutcome("fn")
+ .retry(DistributedMapProcessorRetryConfig.builder()
+ .maxRetryAttempts(3)
+ .maxRetryDuration(Duration.ofMinutes(5))
+ .build())
+ .build();
+
+ assertEquals(3, processor.retry().maxRetryAttempts());
+ assertEquals(Duration.ofMinutes(5), processor.retry().maxRetryDuration());
+ }
+
+ @Test
+ void unlimitedRetryAttempts_isStored() {
+ var processor = DistributedMapProcessor.reportBatchOutcome("fn")
+ .retry(DistributedMapProcessorRetryConfig.builder()
+ .maxRetryAttempts(DistributedMapProcessorRetryConfig.UNLIMITED)
+ .build())
+ .build();
+
+ assertEquals(
+ DistributedMapProcessorRetryConfig.UNLIMITED, processor.retry().maxRetryAttempts());
+ }
+
+ @Test
+ void functionName_empty_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapProcessor.reportBatchOutcome("").build());
+ assertEquals("function name cannot be empty", exception.getMessage());
+ }
+
+ @Test
+ void functionName_null_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapProcessor.reportBatchOutcome(null).build());
+ assertEquals("function name cannot be empty", exception.getMessage());
+ }
+
+ @Test
+ void functionName_tooLong_shouldThrow() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapProcessor.reportBatchOutcome("a".repeat(171))
+ .build());
+ assertEquals("function name must be at most 170 characters, got: 171", exception.getMessage());
+ }
+
+ @Test
+ void functionName_atMaxLength_shouldPass() {
+ var name = "a".repeat(170);
+ assertEquals(
+ name, DistributedMapProcessor.reportBatchOutcome(name).build().functionName());
+ }
+
+ @Test
+ void build_allFieldsSet() {
+ var processor = DistributedMapProcessor.reportItemOutcomes("fn")
+ .batchSize(50)
+ .durableExecutionNamePrefix("job")
+ .retry(DistributedMapProcessorRetryConfig.builder()
+ .maxRetryDuration(Duration.ofMinutes(5))
+ .build())
+ .build();
+
+ assertEquals("fn", processor.functionName());
+ assertEquals(50, processor.batchSize());
+ assertEquals("job", processor.durableExecutionNamePrefix());
+ assertEquals(Duration.ofMinutes(5), processor.retry().maxRetryDuration());
+ }
+}
diff --git a/sdk/src/test/java/software/amazon/lambda/durable/config/DistributedMapSourceTest.java b/sdk/src/test/java/software/amazon/lambda/durable/config/DistributedMapSourceTest.java
new file mode 100644
index 0000000000..2224422e87
--- /dev/null
+++ b/sdk/src/test/java/software/amazon/lambda/durable/config/DistributedMapSourceTest.java
@@ -0,0 +1,445 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.config;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.List;
+import org.junit.jupiter.api.Test;
+import software.amazon.lambda.durable.serde.JacksonSerDes;
+
+class DistributedMapSourceTest {
+
+ @Test
+ void inline_storesItems() {
+ var source = DistributedMapSource.inline(List.of("a", "b"));
+
+ assertEquals(DistributedMapSource.SourceType.INLINE, source.sourceType());
+ assertEquals(List.of("a", "b"), source.inlineItems());
+ assertNull(source.inlineSerDes());
+ assertNull(source.s3());
+ assertNull(source.reader());
+ }
+
+ @Test
+ void inline_withSerDes_storesSerDes() {
+ var serDes = new JacksonSerDes();
+
+ var source = DistributedMapSource.inline(List.of("a"), serDes);
+
+ assertEquals(DistributedMapSource.SourceType.INLINE, source.sourceType());
+ assertEquals(List.of("a"), source.inlineItems());
+ assertSame(serDes, source.inlineSerDes());
+ }
+
+ @Test
+ void inline_acceptsNullItem() {
+ var source = DistributedMapSource.inline(java.util.Arrays.asList("a", null));
+ assertEquals(java.util.Arrays.asList("a", null), source.inlineItems());
+ }
+
+ @Test
+ void inline_null_throws() {
+ var exception = assertThrows(IllegalArgumentException.class, () -> DistributedMapSource.inline(null));
+ assertEquals("items cannot be null", exception.getMessage());
+ }
+
+ @Test
+ void inline_rejectsUnorderedSet() {
+ var unordered = new HashSet<>(List.of("a", "b"));
+
+ var exception = assertThrows(IllegalArgumentException.class, () -> DistributedMapSource.inline(unordered));
+ assertEquals("items must have deterministic iteration order", exception.getMessage());
+ }
+
+ @Test
+ void inline_allowsLinkedHashSet() {
+ var ordered = new LinkedHashSet<>(List.of("a", "b"));
+
+ var source = DistributedMapSource.inline(ordered);
+
+ assertEquals(List.of("a", "b"), source.inlineItems());
+ }
+
+ @Test
+ void s3JsonLines_setsBucketKeyFormat() {
+ DistributedMapSource source = DistributedMapSource.s3JsonLines("s3://bucket/data.jsonl");
+
+ assertEquals(DistributedMapSource.SourceType.S3, source.sourceType());
+ var s3 = source.s3();
+ assertEquals(DistributedMapSource.S3SourceType.OBJECT, s3.type());
+ assertEquals("bucket", s3.bucket());
+ assertEquals("data.jsonl", s3.objectConfig().key());
+ assertEquals(DistributedMapSource.Format.JSON_LINES, s3.objectConfig().format());
+ assertNull(s3.listedObjectMetadataConfig());
+ assertNull(s3.listedObjectsConfig());
+ }
+
+ @Test
+ void s3JsonLines_withoutKey_throws() {
+ var exception = assertThrows(
+ IllegalArgumentException.class, () -> DistributedMapSource.s3JsonLines("s3://bucket-only"));
+ assertEquals("s3JsonLines requires an S3 object key", exception.getMessage());
+ }
+
+ @Test
+ void s3JsonArray_setsFormat() {
+ DistributedMapSource source = DistributedMapSource.s3JsonArray("s3://bucket/data.json");
+
+ var s3 = source.s3();
+ assertEquals(DistributedMapSource.S3SourceType.OBJECT, s3.type());
+ assertEquals("bucket", s3.bucket());
+ assertEquals("data.json", s3.objectConfig().key());
+ assertEquals(DistributedMapSource.Format.JSON_ARRAY, s3.objectConfig().format());
+ }
+
+ @Test
+ void s3JsonArray_withoutKey_throws() {
+ var exception = assertThrows(
+ IllegalArgumentException.class, () -> DistributedMapSource.s3JsonArray("s3://bucket-only"));
+ assertEquals("s3JsonArray requires an S3 object key", exception.getMessage());
+ }
+
+ @Test
+ void s3Csv_setsFormatAndCsvFormat() {
+ var format = DistributedMapSource.CsvFormat.headers(List.of("a", "b"));
+
+ DistributedMapSource source = DistributedMapSource.s3Csv("s3://bucket/data.csv", format);
+
+ var s3 = source.s3();
+ assertEquals(DistributedMapSource.S3SourceType.OBJECT, s3.type());
+ assertEquals("bucket", s3.bucket());
+ assertEquals("data.csv", s3.objectConfig().key());
+ assertEquals(DistributedMapSource.Format.CSV, s3.objectConfig().format());
+ assertSame(format, s3.objectConfig().csvFormat());
+ }
+
+ @Test
+ void s3Csv_withoutKey_throws() {
+ var format = DistributedMapSource.CsvFormat.firstRow();
+
+ var exception = assertThrows(
+ IllegalArgumentException.class, () -> DistributedMapSource.s3Csv("s3://bucket-only", format));
+ assertEquals("s3Csv requires an S3 object key", exception.getMessage());
+ }
+
+ @Test
+ void s3Objects_setsListedObjectMetadataWithPrefix() {
+ DistributedMapSource source = DistributedMapSource.s3Objects("s3://bucket/data/");
+
+ var s3 = source.s3();
+ assertEquals(DistributedMapSource.S3SourceType.LISTED_OBJECT_METADATA, s3.type());
+ assertEquals("bucket", s3.bucket());
+ assertEquals("data/", s3.listedObjectMetadataConfig().keyPrefix());
+ assertNull(s3.objectConfig());
+ assertNull(s3.listedObjectsConfig());
+ }
+
+ @Test
+ void s3Objects_wholeBucket_allowsEmptyPrefix() {
+ DistributedMapSource source = DistributedMapSource.s3Objects("s3://bucket");
+
+ var s3 = source.s3();
+ assertEquals("bucket", s3.bucket());
+ assertEquals("", s3.listedObjectMetadataConfig().keyPrefix());
+ assertEquals(DistributedMapSource.S3SourceType.LISTED_OBJECT_METADATA, s3.type());
+ }
+
+ @Test
+ void s3FlattenedJsonLines_setsListedObjects() {
+ DistributedMapSource source = DistributedMapSource.s3FlattenedJsonLines("s3://bucket/prefix/");
+
+ var s3 = source.s3();
+ assertEquals(DistributedMapSource.S3SourceType.LISTED_OBJECTS, s3.type());
+ assertEquals("bucket", s3.bucket());
+ assertEquals("prefix/", s3.listedObjectsConfig().keyPrefix());
+ assertEquals(
+ DistributedMapSource.Format.JSON_LINES, s3.listedObjectsConfig().format());
+ assertNull(s3.objectConfig());
+ }
+
+ @Test
+ void s3FlattenedJsonArray_setsListedObjects() {
+ DistributedMapSource source = DistributedMapSource.s3FlattenedJsonArray("s3://bucket/prefix/");
+
+ var s3 = source.s3();
+ assertEquals(DistributedMapSource.S3SourceType.LISTED_OBJECTS, s3.type());
+ assertEquals(
+ DistributedMapSource.Format.JSON_ARRAY, s3.listedObjectsConfig().format());
+ }
+
+ @Test
+ void s3FlattenedCsv_setsListedObjects() {
+ var format = DistributedMapSource.CsvFormat.firstRow();
+
+ DistributedMapSource source = DistributedMapSource.s3FlattenedCsv("s3://bucket/prefix/", format);
+
+ var s3 = source.s3();
+ assertEquals(DistributedMapSource.S3SourceType.LISTED_OBJECTS, s3.type());
+ assertEquals(DistributedMapSource.Format.CSV, s3.listedObjectsConfig().format());
+ assertSame(format, s3.listedObjectsConfig().csvFormat());
+ }
+
+ @Test
+ void s3FlattenedCsv_wholeBucket_allowsEmptyPrefix() {
+ DistributedMapSource source =
+ DistributedMapSource.s3FlattenedCsv("s3://bucket", DistributedMapSource.CsvFormat.firstRow());
+
+ assertEquals("", source.s3().listedObjectsConfig().keyPrefix());
+ }
+
+ @Test
+ void reader_storesFunctionName() {
+ DistributedMapSource source = DistributedMapSource.reader("my-reader");
+
+ assertEquals(DistributedMapSource.SourceType.READER_FUNCTION, source.sourceType());
+ assertEquals("my-reader", source.reader().functionName());
+ assertNull(source.reader().initialState());
+ assertNull(source.reader().stateSerDes());
+ }
+
+ @Test
+ void reader_withInitialState_storesState() {
+ var serDes = new JacksonSerDes();
+
+ DistributedMapSource source = DistributedMapSource.reader("my-reader", "start-token", serDes);
+
+ assertEquals("my-reader", source.reader().functionName());
+ assertEquals("start-token", source.reader().initialState());
+ assertSame(serDes, source.reader().stateSerDes());
+ }
+
+ @Test
+ void reader_emptyFunctionName_throws() {
+ var exception = assertThrows(IllegalArgumentException.class, () -> DistributedMapSource.reader(""));
+ assertEquals("function name cannot be empty", exception.getMessage());
+ }
+
+ @Test
+ void maxItems_setsMaxItems() {
+ DistributedMapSource source = DistributedMapSource.s3JsonLines("s3://bucket/data.jsonl")
+ .maxItems(500);
+
+ assertEquals(500L, source.maxItems());
+ }
+
+ @Test
+ void maxItems_zero_throws() {
+ DistributedMapSource source = DistributedMapSource.s3JsonLines("s3://bucket/data.jsonl");
+
+ var exception = assertThrows(IllegalArgumentException.class, () -> source.maxItems(0));
+ assertEquals("maxItems must be between 1 and 100000000, got: 0", exception.getMessage());
+ }
+
+ @Test
+ void maxItems_atTheLimit_stores() {
+ DistributedMapSource source = DistributedMapSource.s3JsonLines("s3://bucket/data.jsonl")
+ .maxItems(100_000_000L);
+
+ assertEquals(100_000_000L, source.maxItems());
+ }
+
+ @Test
+ void maxItems_aboveTheLimit_throws() {
+ DistributedMapSource source = DistributedMapSource.s3JsonLines("s3://bucket/data.jsonl");
+
+ var exception = assertThrows(IllegalArgumentException.class, () -> source.maxItems(100_000_001L));
+ assertEquals("maxItems must be between 1 and 100000000, got: 100000001", exception.getMessage());
+ }
+
+ @Test
+ void expectedBucketOwner_twelveDigits_stores() {
+ DistributedMapSource source = DistributedMapSource.s3JsonLines("s3://bucket/data.jsonl")
+ .expectedBucketOwner("123456789012");
+
+ assertEquals("123456789012", source.s3().expectedBucketOwner());
+ }
+
+ @Test
+ void expectedBucketOwner_invalid_throws() {
+ DistributedMapSource source = DistributedMapSource.s3JsonLines("s3://bucket/data.jsonl");
+
+ var exception = assertThrows(IllegalArgumentException.class, () -> source.expectedBucketOwner("123"));
+ assertEquals("expectedBucketOwner must be a 12-digit account id, got: 123", exception.getMessage());
+ }
+
+ @Test
+ void expectedBucketOwner_onNonS3Source_throws() {
+ var source = DistributedMapSource.inline(List.of("a"));
+
+ var exception = assertThrows(IllegalStateException.class, () -> source.expectedBucketOwner("123456789012"));
+ assertEquals("expectedBucketOwner only applies to S3 sources", exception.getMessage());
+ }
+
+ @Test
+ void s3JsonLines_missingScheme_throws() {
+ var exception =
+ assertThrows(IllegalArgumentException.class, () -> DistributedMapSource.s3JsonLines("bucket/key"));
+ assertEquals("S3 URI must start with s3://, got: bucket/key", exception.getMessage());
+ }
+
+ @Test
+ void s3Objects_missingBucket_throws() {
+ var exception = assertThrows(IllegalArgumentException.class, () -> DistributedMapSource.s3Objects("s3:///key"));
+ assertEquals("S3 URI must contain a bucket, got: s3:///key", exception.getMessage());
+ }
+
+ @Test
+ void expectedColumns_setsFirstRowAndColumns() {
+ var format = DistributedMapSource.CsvFormat.expectedColumns(List.of("a", "b"));
+
+ assertEquals(DistributedMapSource.CsvFormat.HeaderLocation.FIRST_ROW, format.headerLocation());
+ assertEquals(List.of("a", "b"), format.columns());
+ assertEquals(DistributedMapSource.CsvDelimiter.COMMA, format.delimiter());
+ }
+
+ @Test
+ void headers_setsGivenAndColumns() {
+ var format = DistributedMapSource.CsvFormat.headers(List.of("a", "b"));
+
+ assertEquals(DistributedMapSource.CsvFormat.HeaderLocation.GIVEN, format.headerLocation());
+ assertEquals(List.of("a", "b"), format.columns());
+ assertEquals(DistributedMapSource.CsvDelimiter.COMMA, format.delimiter());
+ }
+
+ @Test
+ void firstRow_hasNoColumns() {
+ var format = DistributedMapSource.CsvFormat.firstRow();
+
+ assertEquals(DistributedMapSource.CsvFormat.HeaderLocation.FIRST_ROW, format.headerLocation());
+ assertNull(format.columns());
+ assertEquals(DistributedMapSource.CsvDelimiter.COMMA, format.delimiter());
+ }
+
+ @Test
+ void withDelimiter_setsDelimiter() {
+ var format = DistributedMapSource.CsvFormat.headers(List.of("a", "b"))
+ .withDelimiter(DistributedMapSource.CsvDelimiter.PIPE);
+
+ assertEquals(DistributedMapSource.CsvDelimiter.PIPE, format.delimiter());
+ assertEquals(DistributedMapSource.CsvFormat.HeaderLocation.GIVEN, format.headerLocation());
+ assertEquals(List.of("a", "b"), format.columns());
+ }
+
+ @Test
+ void constructor_nullDelimiter_defaultsToComma() {
+ var format = new DistributedMapSource.CsvFormat(
+ DistributedMapSource.CsvFormat.HeaderLocation.GIVEN, List.of("a"), null);
+
+ assertEquals(DistributedMapSource.CsvDelimiter.COMMA, format.delimiter());
+ }
+
+ @Test
+ void expectedColumns_empty_throws() {
+ var exception = assertThrows(
+ IllegalArgumentException.class, () -> DistributedMapSource.CsvFormat.expectedColumns(List.of()));
+ assertEquals("expectedColumns cannot be empty", exception.getMessage());
+ }
+
+ @Test
+ void expectedColumns_aboveTheColumnLimit_throws() {
+ var columns =
+ java.util.stream.IntStream.range(0, 1001).mapToObj(i -> "c" + i).toList();
+
+ var exception = assertThrows(
+ IllegalArgumentException.class, () -> DistributedMapSource.CsvFormat.expectedColumns(columns));
+ assertEquals("expectedColumns must hold at most 1000 names, got: 1001", exception.getMessage());
+ }
+
+ @Test
+ void headers_nameAboveTheLengthLimit_throws() {
+ var columns = List.of("a".repeat(257));
+
+ var exception =
+ assertThrows(IllegalArgumentException.class, () -> DistributedMapSource.CsvFormat.headers(columns));
+ assertEquals("each headers name must be at most 256 characters, got: 257", exception.getMessage());
+ }
+
+ @Test
+ void expectedColumns_duplicates_throws() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapSource.CsvFormat.expectedColumns(List.of("a", "a")));
+ assertEquals("expectedColumns must not contain duplicates", exception.getMessage());
+ }
+
+ @Test
+ void headers_empty_throws() {
+ var exception =
+ assertThrows(IllegalArgumentException.class, () -> DistributedMapSource.CsvFormat.headers(List.of()));
+ assertEquals("headers cannot be empty", exception.getMessage());
+ }
+
+ @Test
+ void headers_emptyName_throws() {
+ var exception =
+ assertThrows(IllegalArgumentException.class, () -> DistributedMapSource.CsvFormat.headers(List.of("")));
+ assertEquals("each headers name cannot be empty", exception.getMessage());
+ }
+
+ @Test
+ void headers_nullName_throws() {
+ var exception = assertThrows(
+ IllegalArgumentException.class, () -> DistributedMapSource.CsvFormat.headers(Arrays.asList("a", null)));
+ assertEquals("each headers name cannot be empty", exception.getMessage());
+ }
+
+ @Test
+ void expectedColumns_emptyName_throws() {
+ var exception = assertThrows(
+ IllegalArgumentException.class, () -> DistributedMapSource.CsvFormat.expectedColumns(List.of("")));
+ assertEquals("each expectedColumns name cannot be empty", exception.getMessage());
+ }
+
+ @Test
+ void expectedColumns_nullName_throws() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> DistributedMapSource.CsvFormat.expectedColumns(Arrays.asList("a", null)));
+ assertEquals("each expectedColumns name cannot be empty", exception.getMessage());
+ }
+
+ @Test
+ void headers_duplicates_throws() {
+ var exception = assertThrows(
+ IllegalArgumentException.class, () -> DistributedMapSource.CsvFormat.headers(List.of("a", "a")));
+ assertEquals("headers must not contain duplicates", exception.getMessage());
+ }
+
+ @Test
+ void constructor_givenWithoutColumns_throws() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> new DistributedMapSource.CsvFormat(
+ DistributedMapSource.CsvFormat.HeaderLocation.GIVEN, null, null));
+ assertEquals("CsvFormat with headerLocation GIVEN requires headers", exception.getMessage());
+ }
+
+ @Test
+ void constructor_givenWithDuplicateColumns_throws() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> new DistributedMapSource.CsvFormat(
+ DistributedMapSource.CsvFormat.HeaderLocation.GIVEN, List.of("a", "a"), null));
+ assertEquals("headers must not contain duplicates", exception.getMessage());
+ }
+
+ @Test
+ void constructor_firstRowWithEmptyColumns_throws() {
+ var exception = assertThrows(
+ IllegalArgumentException.class,
+ () -> new DistributedMapSource.CsvFormat(
+ DistributedMapSource.CsvFormat.HeaderLocation.FIRST_ROW, List.of(), null));
+ assertEquals("expectedColumns cannot be empty", exception.getMessage());
+ }
+
+ @Test
+ void csvFormat_withoutHeaderLocation_throws() {
+ var exception = assertThrows(
+ IllegalArgumentException.class, () -> new DistributedMapSource.CsvFormat(null, null, null));
+ assertEquals("CsvFormat requires a headerLocation", exception.getMessage());
+ }
+}
diff --git a/sdk/src/test/java/software/amazon/lambda/durable/dmap/DistributedMapDurableHelpersTest.java b/sdk/src/test/java/software/amazon/lambda/durable/dmap/DistributedMapDurableHelpersTest.java
new file mode 100644
index 0000000000..7aa0c0779d
--- /dev/null
+++ b/sdk/src/test/java/software/amazon/lambda/durable/dmap/DistributedMapDurableHelpersTest.java
@@ -0,0 +1,434 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.dmap;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.PropertyNamingStrategies;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.services.lambda.model.CheckpointUpdatedExecutionState;
+import software.amazon.awssdk.services.lambda.model.ContextDetails;
+import software.amazon.awssdk.services.lambda.model.ExecutionDetails;
+import software.amazon.awssdk.services.lambda.model.Operation;
+import software.amazon.awssdk.services.lambda.model.OperationAction;
+import software.amazon.awssdk.services.lambda.model.OperationStatus;
+import software.amazon.awssdk.services.lambda.model.OperationType;
+import software.amazon.awssdk.services.lambda.model.OperationUpdate;
+import software.amazon.lambda.durable.DurableConfig;
+import software.amazon.lambda.durable.DurableContext;
+import software.amazon.lambda.durable.DurableHandler;
+import software.amazon.lambda.durable.TestUtils;
+import software.amazon.lambda.durable.TypeToken;
+import software.amazon.lambda.durable.client.DurableExecutionClient;
+import software.amazon.lambda.durable.config.NestingType;
+import software.amazon.lambda.durable.execution.DurableExecutor;
+import software.amazon.lambda.durable.model.DurableExecutionInput;
+import software.amazon.lambda.durable.model.ExecutionStatus;
+import software.amazon.lambda.durable.model.OperationSubType;
+import software.amazon.lambda.durable.serde.DurableInputOutputSerDes;
+import software.amazon.lambda.durable.serde.JacksonSerDes;
+import software.amazon.lambda.durable.serde.SerDes;
+
+/**
+ * Tests the durable distributed map helpers inside durable handlers. The config is how a durable processor registers
+ * plugins or supplies its own client, so the helpers must run under the config the handler's execution uses.
+ */
+class DistributedMapDurableHelpersTest {
+ private static final String EXECUTION_OP_ID = "f3d7b0c0-1234-5678-90ab-cdef12345678";
+ private static final String EXECUTION_ARN =
+ "arn:aws:lambda:us-east-1:123456789012:function:test" + "/durable-execution/exec-name/" + EXECUTION_OP_ID;
+ private static final String RUN_ARN = "arn:aws:lambda:us-east-1:123456789012:distributed-map-run:run-1";
+ private static final TypeToken EVENT_TYPE = TypeToken.get(ProcessorEvent.class);
+
+ /** Counts deserialize calls, so a test can prove the config's own serdes read the event. */
+ private static final class RecordingSerDes implements SerDes {
+ private final SerDes delegate = new JacksonSerDes();
+ private final AtomicInteger deserializeCount = new AtomicInteger();
+
+ @Override
+ public String serialize(Object value) {
+ return delegate.serialize(value);
+ }
+
+ @Override
+ public T deserialize(String data, TypeToken typeToken) {
+ deserializeCount.incrementAndGet();
+ return delegate.deserialize(data, typeToken);
+ }
+ }
+
+ private static DurableConfig configWith(SerDes serDes) {
+ return DurableConfig.builder()
+ .withDurableExecutionClient(TestUtils.createMockClient())
+ .withSerDes(serDes)
+ .build();
+ }
+
+ // TestUtils.createMockClient echoes START and SUCCEED only. This client also echoes a failed child context, and
+ // records every checkpoint update it receives.
+ private static DurableExecutionClient recordingClient(List recorded) {
+ var delegate = TestUtils.createMockClient();
+ var client = mock(DurableExecutionClient.class);
+ when(client.checkpoint(any(), any(), any())).thenAnswer(invocation -> {
+ List updates = invocation.getArgument(2);
+ recorded.addAll(updates);
+ var response = delegate.checkpoint(invocation.getArgument(0), invocation.getArgument(1), updates);
+ var operations = new ArrayList();
+ for (var operation : response.newExecutionState().operations()) {
+ var failure = updates.stream()
+ .filter(u -> u.id().equals(operation.id()))
+ .filter(u -> u.action() == OperationAction.FAIL && u.type() == OperationType.CONTEXT)
+ .findFirst();
+ operations.add(
+ failure.isPresent()
+ ? operation.toBuilder()
+ .status(OperationStatus.FAILED)
+ .contextDetails(ContextDetails.builder()
+ .error(failure.get().error())
+ .build())
+ .build()
+ : operation);
+ }
+ return response.toBuilder()
+ .newExecutionState(CheckpointUpdatedExecutionState.builder()
+ .operations(operations)
+ .build())
+ .build();
+ });
+ return client;
+ }
+
+ private static DurableConfig recordingConfig(List recorded) {
+ return DurableConfig.builder()
+ .withDurableExecutionClient(recordingClient(recorded))
+ .build();
+ }
+
+ // A first invocation of a durable function: one STARTED execution operation carrying the processor batch.
+ private static DurableExecutionInput durableInput(ProcessorEvent event) {
+ var executionOp = Operation.builder()
+ .id(EXECUTION_OP_ID)
+ .type(OperationType.EXECUTION)
+ .status(OperationStatus.STARTED)
+ .startTimestamp(Instant.parse("2026-08-15T00:00:00Z"))
+ .executionDetails(ExecutionDetails.builder()
+ .inputPayload(new JacksonSerDes().serialize(event))
+ .build())
+ .build();
+ return new DurableExecutionInput(
+ EXECUTION_ARN,
+ "token-1",
+ CheckpointUpdatedExecutionState.builder()
+ .operations(List.of(executionOp))
+ .build());
+ }
+
+ private static ProcessorEvent event(String... bodies) {
+ var records = new ArrayList();
+ for (var i = 0; i < bodies.length; i++) {
+ records.add(new ProcessorRecord(String.valueOf(i), bodies[i]));
+ }
+ return new ProcessorEvent(RUN_ARN, records);
+ }
+
+ // Runs the handler body as a durable handler on the processor event's first invocation, under the given config.
+ private static software.amazon.lambda.durable.model.DurableExecutionOutput run(
+ ProcessorEvent event,
+ DurableConfig config,
+ java.util.function.BiFunction body) {
+ return DurableExecutor.wrap(EVENT_TYPE, body, config).handleRequest(durableInput(event), null);
+ }
+
+ private static ItemHandlerResponse response(software.amazon.lambda.durable.model.DurableExecutionOutput output) {
+ assertEquals(ExecutionStatus.SUCCEEDED, output.status());
+ return new JacksonSerDes().deserialize(output.result(), TypeToken.get(ItemHandlerResponse.class));
+ }
+
+ private static List contextUpdates(List recorded, OperationSubType subType) {
+ return recorded.stream()
+ .filter(u ->
+ u.type() == OperationType.CONTEXT && subType.getValue().equals(u.subType()))
+ .toList();
+ }
+
+ @Test
+ void batchHelperRunsInsideADurableHandlerUnderTheSuppliedConfig() {
+ var serDes = new RecordingSerDes();
+ var seen = new ArrayList();
+
+ var output = run(
+ event("1", "2"),
+ configWith(serDes),
+ (event, ctx) -> DistributedMapHelpers.processDistributedMapBatch(
+ event,
+ (items, batchCtx) ->
+ seen.addAll(ctx.step("copy", new TypeToken
>() {}, stepCtx -> items)),
+ TypeToken.get(Integer.class),
+ null));
+
+ assertEquals(ExecutionStatus.SUCCEEDED, output.status());
+ assertEquals(List.of(1, 2), seen);
+ // The processor's event is always read with the default JSON SerDes. The step inside the processor uses the
+ // config's SerDes, so a call here means the supplied config reached the execution.
+ assertTrue(serDes.deserializeCount.get() > 0);
+ }
+
+ @Test
+ void batchHelperPassesIdsAlignedWithItems() {
+ var seenItems = new ArrayList();
+ var seenContext = new ArrayList();
+ var event = new ProcessorEvent(RUN_ARN, List.of(new ProcessorRecord("a", "1"), new ProcessorRecord("b", "2")));
+
+ var output = run(
+ event,
+ configWith(new JacksonSerDes()),
+ (e, ctx) -> DistributedMapHelpers.processDistributedMapBatch(
+ e,
+ (items, batchCtx) -> {
+ seenItems.addAll(items);
+ seenContext.add(batchCtx);
+ },
+ TypeToken.get(Integer.class),
+ null));
+
+ assertEquals(ExecutionStatus.SUCCEEDED, output.status());
+ assertEquals(List.of(1, 2), seenItems);
+ assertEquals(List.of(new BatchContext(RUN_ARN, List.of("a", "b"))), seenContext);
+ }
+
+ @Test
+ void itemHelperRunsUnderTheSuppliedConfig() {
+ var serDes = new RecordingSerDes();
+
+ var output = run(
+ event("1", "2"),
+ configWith(serDes),
+ (event, ctx) -> DistributedMapHelpers.processDistributedMapItems(
+ ctx, event, (itemCtx, item, meta) -> item * 2, TypeToken.get(Integer.class), null, null));
+
+ assertEquals(
+ List.of(new ItemResult("0", "2"), new ItemResult("1", "4")),
+ response(output).batchItemResults());
+ assertTrue(serDes.deserializeCount.get() > 0);
+ }
+
+ @Test
+ void itemHelperPassesEachItemsOwnId() {
+ var seen = new ConcurrentHashMap();
+ var event = new ProcessorEvent(RUN_ARN, List.of(new ProcessorRecord("a", "1"), new ProcessorRecord("b", "2")));
+
+ var output = run(
+ event,
+ configWith(new JacksonSerDes()),
+ (e, ctx) -> DistributedMapHelpers.processDistributedMapItems(
+ ctx,
+ e,
+ (itemCtx, item, meta) -> {
+ seen.put(item, meta);
+ return item;
+ },
+ TypeToken.get(Integer.class),
+ null,
+ null));
+
+ assertEquals(ExecutionStatus.SUCCEEDED, output.status());
+ assertEquals(Map.of(1, new ItemContext(RUN_ARN, "a"), 2, new ItemContext(RUN_ARN, "b")), seen);
+ }
+
+ @Test
+ void durableOverloadRunsItemsThroughContextMapAndNonDurableOverloadDoesNot() {
+ var durableUpdates = new CopyOnWriteArrayList();
+ run(
+ event("1"),
+ recordingConfig(durableUpdates),
+ (event, ctx) -> DistributedMapHelpers.processDistributedMapItems(
+ ctx, event, (itemCtx, item, meta) -> item, TypeToken.get(Integer.class), null, null));
+ assertFalse(contextUpdates(durableUpdates, OperationSubType.MAP).isEmpty());
+
+ var nonDurableUpdates = new CopyOnWriteArrayList();
+ var output = run(
+ event("1"),
+ recordingConfig(nonDurableUpdates),
+ (event, ctx) -> DistributedMapHelpers.processDistributedMapItems(
+ event, (item, meta) -> item, TypeToken.get(Integer.class), null, null));
+ assertEquals(ExecutionStatus.SUCCEEDED, output.status());
+ assertTrue(contextUpdates(nonDurableUpdates, OperationSubType.MAP).isEmpty());
+ }
+
+ @Test
+ void durableItemsAreFlatByDefaultAndNestedWhenAsked() {
+ var flat = new CopyOnWriteArrayList();
+ run(
+ event("1", "2"),
+ recordingConfig(flat),
+ (event, ctx) -> DistributedMapHelpers.processDistributedMapItems(
+ ctx, event, (itemCtx, item, meta) -> item, TypeToken.get(Integer.class), null, null));
+ assertTrue(contextUpdates(flat, OperationSubType.MAP_ITERATION).isEmpty());
+
+ var explicitFlat = new CopyOnWriteArrayList();
+ run(
+ event("1", "2"),
+ recordingConfig(explicitFlat),
+ (event, ctx) -> DistributedMapHelpers.processDistributedMapItems(
+ ctx,
+ event,
+ (itemCtx, item, meta) -> item,
+ TypeToken.get(Integer.class),
+ null,
+ null,
+ 2,
+ NestingType.FLAT));
+ assertTrue(contextUpdates(explicitFlat, OperationSubType.MAP_ITERATION).isEmpty());
+
+ var nested = new CopyOnWriteArrayList();
+ run(
+ event("1", "2"),
+ recordingConfig(nested),
+ (event, ctx) -> DistributedMapHelpers.processDistributedMapItems(
+ ctx,
+ event,
+ (itemCtx, item, meta) -> item,
+ TypeToken.get(Integer.class),
+ null,
+ null,
+ 2,
+ NestingType.NESTED));
+ assertFalse(contextUpdates(nested, OperationSubType.MAP_ITERATION).isEmpty());
+ }
+
+ @Test
+ void failedItemReachesTheResponseIdenticallyInFlatAndNestedMode() {
+ var flat = failingItemResponse(NestingType.FLAT);
+ var nested = failingItemResponse(NestingType.NESTED);
+
+ assertEquals(1, flat.batchItemFailures().size());
+ var error = flat.batchItemFailures().get(0).error();
+ assertEquals("java.lang.IllegalStateException", error.errorType());
+ assertEquals("boom", error.errorMessage());
+ // The map operation's per-item error has no errorData member, so no mode reports one.
+ assertNull(error.errorData());
+ assertNotNull(error.stackTrace());
+ assertEquals(flat.batchItemFailures(), nested.batchItemFailures());
+ }
+
+ private static ItemHandlerResponse failingItemResponse(NestingType nesting) {
+ var recorded = new CopyOnWriteArrayList();
+ var output = run(
+ event("1"),
+ recordingConfig(recorded),
+ (event, ctx) -> DistributedMapHelpers.processDistributedMapItems(
+ ctx,
+ event,
+ (itemCtx, item, meta) -> {
+ throw new IllegalStateException("boom");
+ },
+ TypeToken.get(Integer.class),
+ null,
+ null,
+ 1,
+ nesting));
+ return response(output);
+ }
+
+ @Test
+ void durableHandlerRunsAStepBeforeTheItems() {
+ var recorded = new CopyOnWriteArrayList();
+
+ var output = run(event("1", "2"), recordingConfig(recorded), (event, ctx) -> {
+ var factor = ctx.step("factor", Integer.class, stepCtx -> 3);
+ return DistributedMapHelpers.processDistributedMapItems(
+ ctx, event, (itemCtx, item, meta) -> item * factor, TypeToken.get(Integer.class), null, null);
+ });
+
+ assertEquals(
+ List.of(new ItemResult("0", "3"), new ItemResult("1", "6")),
+ response(output).batchItemResults());
+ assertTrue(recorded.stream().anyMatch(u -> u.type() == OperationType.STEP && "factor".equals(u.name())));
+ }
+
+ @Test
+ void itemHelperFailsItemWhoseOutputSerializesToNull() {
+ SerDes nullSerDes = new SerDes() {
+ @Override
+ public String serialize(Object value) {
+ return null;
+ }
+
+ @Override
+ public T deserialize(String data, TypeToken typeToken) {
+ return null;
+ }
+ };
+
+ var output = run(
+ event("1"),
+ recordingConfig(new CopyOnWriteArrayList<>()),
+ (event, ctx) -> DistributedMapHelpers.processDistributedMapItems(
+ ctx, event, (itemCtx, item, meta) -> item, TypeToken.get(Integer.class), null, nullSerDes));
+
+ var response = response(output);
+ assertEquals(List.of(), response.batchItemResults());
+ var failure = response.batchItemFailures().get(0);
+ assertEquals("0", failure.itemIdentifier());
+ assertEquals(
+ "serialization of item output produced no string",
+ failure.error().errorMessage());
+ }
+
+ // A customer's handler. Its config uses a SerDes that renames fields, which must not change how the service's
+ // processor event is read or how the response is written.
+ private static final class SnakeCaseItemsHandler extends DurableHandler {
+ @Override
+ protected DurableConfig createConfiguration() {
+ var snakeCase = new JacksonSerDes(new ObjectMapper()
+ .setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)
+ .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
+ return configWith(snakeCase);
+ }
+
+ @Override
+ public ItemHandlerResponse handleRequest(ProcessorEvent event, DurableContext context) {
+ return DistributedMapHelpers.processDistributedMapItems(
+ context, event, (itemCtx, item, meta) -> item * 2, TypeToken.get(Integer.class), null, null);
+ }
+ }
+
+ @Test
+ void durableHandlerReadsTheProcessorEventWithDefaultJsonUnderACustomSerDes() throws IOException {
+ // The test's own serializer writes the start timestamp in a form the handler's reader rejects, so it is
+ // dropped.
+ var input = new DurableInputOutputSerDes()
+ .serialize(durableInput(event("1")))
+ .replaceAll("\"StartTimestamp\"\\s*:\\s*(\"[^\"]*\"|[0-9.eE+-]+),?", "");
+ var out = new ByteArrayOutputStream();
+
+ new SnakeCaseItemsHandler()
+ .handleRequest(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)), out, null);
+
+ var result = out.toString(StandardCharsets.UTF_8);
+ assertTrue(result.contains("SUCCEEDED"), result);
+ assertTrue(result.contains("batchItemResults"), result);
+ assertTrue(result.contains("itemIdentifier"), result);
+ assertTrue(result.contains("batchItemFailures"), result);
+ }
+}
diff --git a/sdk/src/test/java/software/amazon/lambda/durable/dmap/DistributedMapHelpersTest.java b/sdk/src/test/java/software/amazon/lambda/durable/dmap/DistributedMapHelpersTest.java
new file mode 100644
index 0000000000..ea70592db6
--- /dev/null
+++ b/sdk/src/test/java/software/amazon/lambda/durable/dmap/DistributedMapHelpersTest.java
@@ -0,0 +1,764 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+package software.amazon.lambda.durable.dmap;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static software.amazon.lambda.durable.dmap.DistributedMapHelpers.*;
+
+import com.amazonaws.services.lambda.runtime.serialization.events.LambdaEventSerializers;
+import com.amazonaws.services.lambda.runtime.serialization.factories.JacksonFactory;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.io.ByteArrayInputStream;
+import java.io.UncheckedIOException;
+import java.lang.reflect.Type;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.NullAndEmptySource;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.slf4j.MDC;
+import org.slf4j.helpers.BasicMDCAdapter;
+import org.slf4j.spi.MDCAdapter;
+import software.amazon.lambda.durable.TypeToken;
+import software.amazon.lambda.durable.model.DistributedMapError;
+import software.amazon.lambda.durable.serde.JacksonSerDes;
+import software.amazon.lambda.durable.serde.SerDes;
+
+/** Unit tests for the distributed map authoring helpers (non-durable variants). */
+class DistributedMapHelpersTest {
+ private static final String RUN_ARN = "arn:aws:lambda:us-east-1:123456789012:distributed-map-run:run-1";
+
+ private final List loggedMessages = new ArrayList<>();
+ private final List