feat(stepfunctions): emulate distributed Map ResultWriter (S3 export + manifest) (#1823)

* feat(stepfunctions): export distributed map results to S3

* chore: re-run CI

The Build and Test failure on the previous head was RuntimeApiServerTest's
extension/stop race, a pre-existing flake unrelated to this change — it also failed
on #1820, #1823 and on #2131's own branch (the PR that tried to de-flake it).
Reproduced locally under `--cpus=1` and fixed separately.

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
This commit is contained in:
Alex BannaandAlexander Banna authored and GitHub committed 2026-08-12 00:22:17 -04:00
1 parent cd3588b517
commit 59cb643d6e
4 files changed
+1173 -12

No files matched your search

@@ -1463,14 +1463,24 @@ public class AslExecutor {
private StateResult executeMapState(String name, JsonNode stateDef, JsonNode input, StateMachine sm,
boolean jsonata, String topLevelQueryLanguage, JsonNode context,
ObjectNode variables) throws Exception {
if (stateDef.has("ItemReader")) {
// ItemReader, ItemBatcher and ResultWriter are distributed-map-only fields; AWS rejects them on
// an INLINE map. Guard on all three (not just ItemReader) so a ResultWriter on an inline map is
// rejected rather than silently exporting to S3.
if (stateDef.has("ItemReader") || stateDef.has("ItemBatcher") || stateDef.has("ResultWriter")) {
String mode = stateDef.path("ItemProcessor").path("ProcessorConfig").path("Mode").asText("INLINE");
if (!"DISTRIBUTED".equals(mode)) {
throw new FailStateException("States.Runtime",
"The ItemReader, ItemBatcher and ResultWriter fields are not supported for INLINE maps");
}
}
ResolvedMapItems resolvedItems = resolveMapItems(stateDef, input, jsonata, context, variables);
boolean hasResultWriter = stateDef.has("ResultWriter");
// ResultWriter Parameters and its distributed Map item selection see the effective input
// after InputPath. Keep the pre-existing item-selection behavior unchanged for Maps that do
// not use ResultWriter so this feature does not absorb a separate compatibility correction.
JsonNode mapInput = jsonata ? input : applyInputPath(stateDef, input);
JsonNode itemSelectionInput = hasResultWriter ? mapInput : input;
ResolvedMapItems resolvedItems = resolveMapItems(
stateDef, itemSelectionInput, jsonata, context, variables);
JsonNode items = resolvedItems.items();
if (!items.isArray()) {
@@ -1486,10 +1496,11 @@ public class AslExecutor {
JsonNode itemTransform = stateDef.has("ItemSelector") ? stateDef.get("ItemSelector")
: stateDef.has("Parameters") ? stateDef.get("Parameters") : null;
// Resolve InputPath before iterating so $. in ItemSelector sees the Map state's effective input
JsonNode mapInput = applyInputPath(stateDef, input);
ArrayNode results = objectMapper.createArrayNode();
// When a ResultWriter exports results, AWS records each child execution's input and timing
// (Transformation NONE); capture them alongside the outputs so the export is faithful.
ArrayNode childInputs = hasResultWriter ? objectMapper.createArrayNode() : null;
List<long[]> childTimings = hasResultWriter ? new ArrayList<>() : null;
int index = 0;
for (JsonNode item : items) {
ObjectNode iterContext = ((ObjectNode) context).deepCopy();
@@ -1512,25 +1523,279 @@ public class AslExecutor {
}
// Each iteration gets an isolated copy of the current variables; assignments inside an
// iteration are scoped to that iteration and do not leak back to the parent scope.
results.add(executeBranch(startAt, iteratorStates, iterInput, sm, topLevelQueryLanguage, iterContext,
variables.deepCopy()));
long startMs = hasResultWriter ? System.currentTimeMillis() : 0L;
JsonNode branchOutput =
executeBranch(startAt, iteratorStates, iterInput, sm, topLevelQueryLanguage, iterContext,
variables.deepCopy());
if (hasResultWriter) {
childInputs.add(iterInput);
childTimings.add(new long[]{startMs, System.currentTimeMillis()});
}
results.add(branchOutput);
index++;
}
// A distributed Map's ResultWriter formats the per-child results and, when an S3 Resource is
// given, exports them and yields a reference to the manifest instead of the inline array.
JsonNode mapResult = results;
if (hasResultWriter) {
mapResult = applyResultWriter(name, stateDef, mapInput, results, childInputs, childTimings,
sm, context, jsonata, variables);
}
if (jsonata) {
JsonNode output = applyJsonataOutput(stateDef, input, results, context, variables);
JsonNode output = applyJsonataOutput(stateDef, input, mapResult, context, variables);
return new StateResult(output, stateDef.path("Next").asText(null));
}
// ResultSelector transforms the raw iteration results before ResultPath merges them in.
JsonNode selected = stateDef.has("ResultSelector")
? resolveParameters(stateDef.get("ResultSelector"), results, context)
: results;
? resolveParameters(stateDef.get("ResultSelector"), mapResult, context)
: mapResult;
JsonNode output = mergeResult(stateDef, input, selected);
output = applyOutputPath(stateDef, input, output);
return new StateResult(output, stateDef.path("Next").asText(null));
}
/**
* Emulates a Distributed Map state's {@code ResultWriter}
* (<a href="https://docs.aws.amazon.com/step-functions/latest/dg/input-output-resultwriter.html">AWS docs</a>).
* The child results are formatted per {@code WriterConfig.Transformation} ({@code NONE} /
* {@code COMPACT} / {@code FLATTEN}); then:
* <ul>
* <li>if a {@code Resource} + {@code Parameters}/{@code Arguments} (an S3 bucket/prefix) are
* given, the formatted results are exported to S3 as {@code SUCCEEDED_n.json} plus a
* {@code manifest.json}, and the Map state returns
* {@code {MapRunArn, ResultWriterDetails:{Bucket, Key}}};</li>
* <li>if only a {@code WriterConfig} is given (no S3 {@code Resource}), the formatted results
* are returned directly to the next state (preview) with no S3 write.</li>
* </ul>
*
* <p>By construction every child branch here has already succeeded (a failed branch throws and
* fails the Map before this point, since inline Maps here do not implement tolerated-failure),
* so {@code ResultFiles.FAILED} / {@code PENDING} are empty and all results go to a single
* {@code SUCCEEDED_0.json}.
*/
// Package-private for unit testing of the ResultWriter export/format behaviour.
JsonNode applyResultWriter(String mapStateName, JsonNode stateDef, JsonNode input,
ArrayNode results, ArrayNode childInputs, List<long[]> childTimings,
StateMachine sm, JsonNode context, boolean jsonata) throws Exception {
return applyResultWriter(mapStateName, stateDef, input, results, childInputs, childTimings,
sm, context, jsonata, objectMapper.createObjectNode());
}
private JsonNode applyResultWriter(String mapStateName, JsonNode stateDef, JsonNode input,
ArrayNode results, ArrayNode childInputs, List<long[]> childTimings,
StateMachine sm, JsonNode context, boolean jsonata,
ObjectNode variables) throws Exception {
JsonNode writer = stateDef.get("ResultWriter");
JsonNode writerConfig = writer.path("WriterConfig");
boolean export = writer.hasNonNull("Resource");
// When exporting without an explicit WriterConfig, AWS defaults the transformation to NONE
// (child results plus execution metadata); COMPACT is the default only when no ResultWriter
// is present at all, which is handled by returning the inline array elsewhere.
String transformation = writerConfig.path("Transformation").asText("NONE");
String outputType = writerConfig.path("OutputType").asText("JSON");
String region = extractRegionFromArn(sm.getStateMachineArn());
String account = AwsArnUtils.accountOrDefault(sm.getStateMachineArn(), null);
String smName = context.path("StateMachine").path("Name").asText(sm.getName());
String mapRunLabel = stateDef.path("Label").asText(null);
if (mapRunLabel == null || mapRunLabel.isBlank()) {
mapRunLabel = UUID.randomUUID().toString();
}
JsonNode formatted = formatMapResults(transformation, results, childInputs, childTimings,
region, account, smName, mapRunLabel);
if (!export) {
// WriterConfig only: return the formatted results to the next state (no S3 write).
return formatted;
}
try {
// Resolve the destination bucket/prefix: JSONata states carry them under Arguments,
// JSONPath states under Parameters. Reference paths see the Map's effective input after
// InputPath, which is supplied by executeMapState.
JsonNode loc;
if (jsonata && writer.has("Arguments")) {
JsonNode arguments = writer.get("Arguments");
loc = jsonataEvaluator.resolveTemplate(
arguments, buildStatesVar(input, null, context), variables);
if (arguments.isObject()) {
if (arguments.has("Bucket") && !loc.has("Bucket")) {
throw new FailStateException("States.QueryEvaluationError",
"ResultWriter Bucket must resolve to a string");
}
if (arguments.has("Prefix") && !loc.has("Prefix")) {
throw new FailStateException("States.QueryEvaluationError",
"ResultWriter Prefix must resolve to a string");
}
}
} else if (writer.has("Parameters")) {
loc = resolveParameters(writer.get("Parameters"), input, context);
} else {
loc = objectMapper.createObjectNode();
}
if (!loc.isObject()) {
throw new FailStateException(
jsonata ? "States.QueryEvaluationError" : "States.ResultWriterFailed",
"ResultWriter " + (jsonata ? "Arguments" : "Parameters")
+ " must resolve to an object");
}
JsonNode bucketNode = loc.get("Bucket");
if (bucketNode == null) {
throw new FailStateException("States.ResultWriterFailed",
"ResultWriter destination bucket is required");
}
if (!bucketNode.isTextual()) {
throw new FailStateException(
jsonata ? "States.QueryEvaluationError" : "States.ResultWriterFailed",
"ResultWriter Bucket must resolve to a string");
}
String bucket = bucketNode.asText();
if (bucket.isBlank()) {
throw new FailStateException("States.ResultWriterFailed",
"ResultWriter destination bucket is required");
}
JsonNode prefixNode = loc.get("Prefix");
if (prefixNode != null && !prefixNode.isTextual()) {
throw new FailStateException(
jsonata ? "States.QueryEvaluationError" : "States.ResultWriterFailed",
"ResultWriter Prefix must resolve to a string");
}
String prefix = prefixNode == null ? "" : prefixNode.asText();
// S3 buckets are owned by Floci's single synthetic account. AWS additionally requires
// ResultWriter destinations to be in the state machine's Region.
String bucketRegion = normalizeS3Region(s3Service.getBucketRegion(bucket));
if (!bucketRegion.equalsIgnoreCase(region)) {
throw new FailStateException("States.ResultWriterFailed",
"ResultWriter destination bucket must be in the same AWS Region "
+ "as the state machine");
}
// AWS includes the Map label (or an automatically generated label) before the run id.
// The run id alone keys the exported result set under the user-supplied S3 prefix.
String mapRunId = UUID.randomUUID().toString();
String mapRunArn = "arn:aws:states:" + region + ":" + account + ":mapRun:"
+ smName + "/" + mapRunLabel + ":" + mapRunId;
String base = prefix.isEmpty()
? mapRunId + "/"
: prefix + (prefix.endsWith("/") ? "" : "/") + mapRunId + "/";
String succeededKey = base + "SUCCEEDED_0.json";
String manifestKey = base + "manifest.json";
byte[] succeededBytes = serializeResultFile(formatted, outputType);
s3Service.putObject(bucket, succeededKey, succeededBytes, "application/json", new HashMap<>());
ObjectNode manifest = objectMapper.createObjectNode();
manifest.put("DestinationBucket", bucket);
manifest.put("MapRunArn", mapRunArn);
ObjectNode resultFiles = manifest.putObject("ResultFiles");
resultFiles.putArray("FAILED");
resultFiles.putArray("PENDING");
ObjectNode succeededEntry = resultFiles.putArray("SUCCEEDED").addObject();
succeededEntry.put("Key", succeededKey);
succeededEntry.put("Size", succeededBytes.length);
s3Service.putObject(bucket, manifestKey, objectMapper.writeValueAsBytes(manifest),
"application/json", new HashMap<>());
ObjectNode mapResult = objectMapper.createObjectNode();
mapResult.put("MapRunArn", mapRunArn);
ObjectNode details = mapResult.putObject("ResultWriterDetails");
details.put("Bucket", bucket);
details.put("Key", manifestKey);
return mapResult;
} catch (FailStateException e) {
throw e;
} catch (Exception e) {
String detail = e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName();
throw new FailStateException("States.ResultWriterFailed",
"Unable to export Map Run results: " + detail);
}
}
/**
* Formats a Distributed Map's child results per {@code WriterConfig.Transformation}:
* <ul>
* <li>{@code NONE} — an array of per-child execution records (output plus execution metadata),
* as AWS writes when exporting without a WriterConfig;</li>
* <li>{@code COMPACT} — the child outputs in their original array structure;</li>
* <li>{@code FLATTEN} — the child outputs with any array outputs flattened into one array.</li>
* </ul>
*/
private ArrayNode formatMapResults(String transformation, ArrayNode results, ArrayNode childInputs,
List<long[]> childTimings, String region, String account,
String smName, String mapRunLabel) {
ArrayNode out = objectMapper.createArrayNode();
if ("FLATTEN".equalsIgnoreCase(transformation)) {
for (JsonNode r : results) {
if (r.isArray()) {
r.forEach(out::add);
} else {
out.add(r);
}
}
return out;
}
if ("COMPACT".equalsIgnoreCase(transformation)) {
out.addAll(results);
return out;
}
// NONE: emit an execution record per child, mirroring the AWS export format. The child
// executions run under a derived state machine "<parentName>/<mapRunLabel>".
String childSmArn = "arn:aws:states:" + region + ":" + account + ":stateMachine:"
+ smName + "/" + mapRunLabel;
for (int i = 0; i < results.size(); i++) {
String childId = java.util.UUID.randomUUID().toString();
long start = childTimings != null && i < childTimings.size() ? childTimings.get(i)[0] : 0L;
long stop = childTimings != null && i < childTimings.size() ? childTimings.get(i)[1] : 0L;
ObjectNode rec = out.addObject();
rec.put("ExecutionArn", "arn:aws:states:" + region + ":" + account + ":execution:"
+ smName + "/" + mapRunLabel + ":" + childId);
rec.put("Input", stringifyResult(childInputs != null && i < childInputs.size()
? childInputs.get(i) : NullNode.getInstance()));
rec.putObject("InputDetails").put("Included", true);
rec.put("Name", childId);
rec.put("Output", stringifyResult(results.get(i)));
rec.putObject("OutputDetails").put("Included", true);
rec.put("RedriveCount", 0);
rec.put("RedriveStatus", "NOT_REDRIVABLE");
rec.put("RedriveStatusReason", "Execution is SUCCEEDED and cannot be redriven");
rec.put("StartDate", java.time.Instant.ofEpochMilli(start).toString());
rec.put("StateMachineArn", childSmArn);
rec.put("Status", "SUCCEEDED");
rec.put("StopDate", java.time.Instant.ofEpochMilli(stop).toString());
}
return out;
}
/**
* AWS records a child execution's Input/Output as a JSON-encoded string. Using {@code toString()}
* (not {@code asText()}) keeps scalar strings quoted — the string {@code hello} is exported as
* {@code "hello"} — so the field is always valid JSON regardless of the value's type.
*/
private String stringifyResult(JsonNode node) {
if (node == null || node.isNull() || node.isMissingNode()) {
return "null";
}
return node.toString();
}
/** Serializes a formatted result array as a JSON array or as JSON Lines per {@code OutputType}. */
private byte[] serializeResultFile(JsonNode formatted, String outputType) throws Exception {
if ("JSONL".equalsIgnoreCase(outputType) && formatted.isArray()) {
StringBuilder sb = new StringBuilder();
for (JsonNode element : formatted) {
sb.append(objectMapper.writeValueAsString(element)).append('\n');
}
return sb.toString().getBytes(StandardCharsets.UTF_8);
}
return objectMapper.writeValueAsBytes(formatted);
}
private ResolvedMapItems resolveMapItems(JsonNode stateDef, JsonNode input,
boolean jsonata, JsonNode context, ObjectNode variables) throws Exception {
if (jsonata && stateDef.has("Items")) {
@@ -2652,6 +2917,10 @@ public class AslExecutor {
return AwsArnUtils.regionOrDefault(arn, "us-east-1");
}
private static String normalizeS3Region(String region) {
return region == null || region.isBlank() ? "us-east-1" : region;
}
record StateResult(JsonNode output, String nextState) {}
static class FailStateException extends RuntimeException {
@@ -54,6 +54,9 @@ public class StepFunctionsService implements Resettable {
"arn:aws:states:::s3:listObjectsV2");
private static final Set<String> ITEM_READER_INPUT_TYPES = Set.of(
"MANIFEST", "JSON", "CSV", "JSONL", "PARQUET");
private static final String RESULT_WRITER_RESOURCE = "arn:aws:states:::s3:putObject";
private static final Set<String> RESULT_WRITER_TRANSFORMATIONS = Set.of("NONE", "COMPACT", "FLATTEN");
private static final Set<String> RESULT_WRITER_OUTPUT_TYPES = Set.of("JSON", "JSONL");
@Inject
public StepFunctionsService(StorageFactory storageFactory, RegionResolver regionResolver,
@@ -562,8 +565,13 @@ public class StepFunctionsService implements Resettable {
}
}
if ("Map".equals(stateDef.path("Type").asText()) && stateDef.has("ItemReader")) {
validateItemReader(stateName, stateDef, errors);
if ("Map".equals(stateDef.path("Type").asText())) {
if (stateDef.has("ItemReader")) {
validateItemReader(stateName, stateDef, errors);
}
if (stateDef.has("ResultWriter")) {
validateResultWriter(stateName, stateDef.get("ResultWriter"), stateIsJsonata, errors);
}
}
}
@@ -583,4 +591,95 @@ public class StepFunctionsService implements Resettable {
+ " at /States/" + stateName + "/ItemReader/ReaderConfig/InputType");
}
}
private void validateResultWriter(String stateName, JsonNode writer,
boolean jsonata, List<String> errors) {
String statePath = "/States/" + stateName;
String writerPath = statePath + "/ResultWriter";
if (!writer.isObject() || writer.isEmpty()) {
errors.add("The field 'ResultWriter' must specify WriterConfig or Resource with "
+ (jsonata ? "Arguments" : "Parameters") + " at " + statePath);
return;
}
String destinationField = jsonata ? "Arguments" : "Parameters";
String unsupportedDestinationField = jsonata ? "Parameters" : "Arguments";
if (writer.has(unsupportedDestinationField)) {
errors.add("The field '" + unsupportedDestinationField + "' is not supported for the '"
+ (jsonata ? "JSONata" : "JSONPath") + "' QueryLanguage at "
+ writerPath + "/" + unsupportedDestinationField);
}
boolean hasConfig = writer.has("WriterConfig") && writer.get("WriterConfig").isObject();
boolean hasResource = writer.has("Resource");
boolean destinationIsExpression = jsonata
&& writer.path(destinationField).isTextual()
&& JsonataEvaluator.isExpression(writer.path(destinationField).asText());
boolean hasDestination = writer.has(destinationField)
&& (writer.get(destinationField).isObject() || destinationIsExpression);
if (writer.has("WriterConfig") && !hasConfig) {
errors.add("The field 'WriterConfig' must be an object at " + writerPath);
}
if (writer.has(destinationField) && !hasDestination) {
errors.add("The field '" + destinationField + "' must be an object"
+ (jsonata ? " or a JSONata expression" : "") + " at " + writerPath);
}
if ((!hasConfig && !hasResource && !hasDestination) || hasResource != hasDestination) {
errors.add("The field 'ResultWriter' must specify WriterConfig alone, Resource with "
+ destinationField + ", or all three fields at " + statePath);
}
if (hasResource && (!writer.get("Resource").isTextual()
|| !RESULT_WRITER_RESOURCE.equals(writer.get("Resource").asText()))) {
errors.add("The field 'Resource' does not match the allowed value "
+ RESULT_WRITER_RESOURCE + " at " + writerPath);
}
if (hasDestination && !destinationIsExpression) {
JsonNode destination = writer.get(destinationField);
boolean hasBucket = destination.hasNonNull("Bucket")
|| (!jsonata && destination.hasNonNull("Bucket.$"));
if (!hasBucket) {
errors.add("The field 'Bucket' is required at " + writerPath + "/" + destinationField);
} else if (destination.has("Bucket") && !destination.get("Bucket").isTextual()) {
errors.add("The field 'Bucket' must be a string at "
+ writerPath + "/" + destinationField + "/Bucket");
} else if (!jsonata && destination.has("Bucket.$")
&& !destination.get("Bucket.$").isTextual()) {
errors.add("The field 'Bucket.$' must be a string at "
+ writerPath + "/" + destinationField + "/Bucket.$");
}
if (destination.has("Prefix") && !destination.get("Prefix").isTextual()) {
errors.add("The field 'Prefix' must be a string at "
+ writerPath + "/" + destinationField + "/Prefix");
}
if (!jsonata && destination.has("Prefix.$")
&& !destination.get("Prefix.$").isTextual()) {
errors.add("The field 'Prefix.$' must be a string at "
+ writerPath + "/" + destinationField + "/Prefix.$");
}
}
if (hasConfig) {
JsonNode config = writer.get("WriterConfig");
JsonNode transformationNode = config.get("Transformation");
JsonNode outputTypeNode = config.get("OutputType");
if (transformationNode == null || !transformationNode.isTextual()
|| outputTypeNode == null || !outputTypeNode.isTextual()) {
errors.add("The field 'WriterConfig' must specify string Transformation and OutputType at "
+ writerPath + "/WriterConfig");
} else {
String transformation = transformationNode.asText();
if (!RESULT_WRITER_TRANSFORMATIONS.contains(transformation)) {
errors.add("The field 'Transformation' should have one of these values: "
+ RESULT_WRITER_TRANSFORMATIONS + " at " + writerPath + "/WriterConfig");
}
String outputType = outputTypeNode.asText();
if (!RESULT_WRITER_OUTPUT_TYPES.contains(outputType)) {
errors.add("The field 'OutputType' should have one of these values: "
+ RESULT_WRITER_OUTPUT_TYPES + " at " + writerPath + "/WriterConfig");
}
}
}
}
}