feat(stepfunctions): describe a distributed Map run after it finishes (#2694)

* feat(stepfunctions): describe a distributed Map run after it finishes

DescribeMapRun was not implemented, and arn:aws:states:::aws-sdk:sfn:describeMapRun
reached the end of the dispatch chain in invokeResource, so a distributed Map could
not be inspected once it was over: the Map run ARN was minted from a fresh UUID,
written into the S3 manifest, returned in the Map result and then dropped.

A run is now retained where the ResultWriter mints that ARN, which is also the only
place an ASL author reads it. The manifest is no shortcut to the counters, since it
writes FAILED and PENDING as empty arrays and puts every item under SUCCEEDED, so
the run carries the item count taken where the iterations complete.

A Map fails on the first item that fails, so a retained run is one whose every item
succeeded. That fixes the status, both tolerances and the redrive counters at the
values us-east-1 reports for such a run, and leaves succeeded, total and
resultsWritten as the item count. An unbounded Map, which ASL spells as MaxConcurrency
0 or by omitting it, is reported as Integer.MAX_VALUE.

The Task integration recases the wire response rather than restating it, so the two
renderings of a run cannot drift, and renders both dates as the SDK's ISO-8601.

Closes #2671

* refactor(stepfunctions): close a Map run's window on the export that mints its ARN

recordMapRun sampled the wall clock and then folded the child timings into both
ends of the run's window, but the clock is read after MapIterationScheduler has
joined every child and after applyResultWriter has exported, so it is at or past
every child's stop. Math.max over the timings could therefore never move stop off
that sample, and the javadoc promised a last-item stop the code never computed.

The sampled value is the faithful one: AWS closes a Map run's window on the export
rather than on the last item, and the sample is taken immediately after it. Only
start is recovered from the timings, which is the one end the Map state records
nowhere else. DescribeMapRun returns the same startDate and stopDate as before.

* test(compatibility): cover DescribeMapRun through the AWS SFN SDK client

StepFunctionsDescribeMapRunIntegrationTest only exercises the endpoint via
RestAssured, leaving the SDK's own request serialization, endpoint routing
and response deserialization untested, contrary to AGENTS.md's rule that
management APIs be validated with AWS SDK clients.

---------

Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
This commit is contained in:
Facundo ParedesandFacundo Paredes authored and GitHub committed 2026-08-29 00:05:50 -04:00
1 parent 9b3aee6a03
commit ff61c2b2a5
8 files changed
+741 -1

No files matched your search

@@ -33,6 +33,7 @@ import io.github.hectorvent.floci.services.s3.model.S3Object;
import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
import io.github.hectorvent.floci.services.stepfunctions.model.Execution;
import io.github.hectorvent.floci.services.stepfunctions.model.HistoryEvent;
import io.github.hectorvent.floci.services.stepfunctions.model.MapRun;
import io.github.hectorvent.floci.services.stepfunctions.model.MockedResponseStep;
import io.github.hectorvent.floci.services.stepfunctions.model.MockedTestCase;
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
@@ -991,6 +992,7 @@ public class AslExecutor {
case "startSyncExecution" -> invokeAwsSdkSfnStartSyncExecution(input, region);
case "sendTaskSuccess" -> invokeAwsSdkSfnSendTaskSuccess(input);
case "sendTaskFailure" -> invokeAwsSdkSfnSendTaskFailure(input);
case "describeMapRun" -> invokeAwsSdkSfnDescribeMapRun(input);
default -> throw new FailStateException("States.TaskFailed",
"Unsupported resource: " + AWS_SDK_SFN_PREFIX + action);
};
@@ -1049,6 +1051,30 @@ public class AslExecutor {
return response;
}
/**
* AWS SDK integration for {@code sfn:describeMapRun}. The SDK names every field in PascalCase
* and renders both dates as ISO-8601, where the wire response of the same run carries epoch
* seconds. Recasing that response is what keeps the two renderings of a Map run in step.
*/
private JsonNode invokeAwsSdkSfnDescribeMapRun(JsonNode input) {
String mapRunArn = input.path("MapRunArn").asText(null);
if (mapRunArn == null || mapRunArn.isBlank()) {
throw new FailStateException("Sfn.InvalidArnException",
"MapRunArn is required for DescribeMapRun");
}
MapRun mapRun;
try {
mapRun = sfnService.get().describeMapRun(mapRunArn);
} catch (AwsException e) {
throw new FailStateException(sdkExceptionName("Sfn", e.getErrorCode()), e.getMessage());
}
ObjectNode response = (ObjectNode) recaseKeys(objectMapper,
StepFunctionsJsonHandler.describeMapRunResponse(objectMapper, mapRun), true);
response.put("StartDate", sdkTimestamp(mapRun.getStartDate()));
response.put("StopDate", sdkTimestamp(mapRun.getStopDate()));
return response;
}
/**
* AWS SDK integration for {@code sfn:sendTaskSuccess}. AWS fails the calling task with
* {@code Sfn.InvalidTokenException} when the token names no waiting task, so a token that
@@ -2018,6 +2044,7 @@ public class AslExecutor {
}
mapResult = applyResultWriter(name, stateDef, mapInput, results, childInputs, childTimings,
sm, context, jsonata, variables);
recordMapRun(mapResult, context, childTimings, requestedConcurrency);
}
if (jsonata) {
@@ -2070,6 +2097,42 @@ public class AslExecutor {
return Math.min(itemCount, Math.min(requestedLimit, serviceLimit));
}
/**
* Retains the Map run that {@link #applyResultWriter} just exported, so {@code DescribeMapRun}
* can report its counters afterwards. Only an exported run is retained: the Map result is the
* one place an ASL author reads the Map run ARN, so a run without a {@code ResultWriter}
* {@code Resource} has no ARN anybody could describe.
*
* <p>The run starts with its first item, taken from the child timings the export record already
* collected, and stops here: the {@code ResultWriter} export has just returned, and AWS closes
* a Map run's window on the export rather than on the last item. A run over no items starts and
* stops at that same instant.
*/
private void recordMapRun(JsonNode mapResult, JsonNode context, List<long[]> childTimings,
int requestedConcurrency) {
String mapRunArn = mapResult.path("MapRunArn").asText(null);
if (mapRunArn == null) {
return;
}
long stop = System.currentTimeMillis();
long start = stop;
for (long[] timing : childTimings) {
start = Math.min(start, timing[0]);
}
MapRun mapRun = new MapRun();
mapRun.setMapRunArn(mapRunArn);
mapRun.setExecutionArn(context.path("Execution").path("Id").asText(null));
mapRun.setStartDate(start / 1000.0);
mapRun.setStopDate(stop / 1000.0);
mapRun.setItemCount(childTimings.size());
// ASL spells an unbounded Map as MaxConcurrency 0, or by omitting it; DescribeMapRun
// reports that same run as Integer.MAX_VALUE.
mapRun.setMaxConcurrency(
requestedConcurrency == 0 ? Integer.MAX_VALUE : requestedConcurrency);
sfnService.get().recordMapRun(mapRun);
}
/**
* 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>).
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.stepfunctions.model.Activity;
import io.github.hectorvent.floci.services.stepfunctions.model.ActivityTask;
import io.github.hectorvent.floci.services.stepfunctions.model.Execution;
import io.github.hectorvent.floci.services.stepfunctions.model.HistoryEvent;
import io.github.hectorvent.floci.services.stepfunctions.model.MapRun;
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -48,6 +49,7 @@ public class StepFunctionsJsonHandler {
case "ListExecutions" -> handleListExecutions(request);
case "StopExecution" -> handleStopExecution(request);
case "GetExecutionHistory" -> handleGetExecutionHistory(request);
case "DescribeMapRun" -> handleDescribeMapRun(request);
case "SendTaskSuccess" -> handleSendTaskSuccess(request);
case "SendTaskFailure" -> handleSendTaskFailure(request);
case "SendTaskHeartbeat" -> handleSendTaskHeartbeat(request);
@@ -287,6 +289,51 @@ public class StepFunctionsJsonHandler {
return Response.ok(response).build();
}
private Response handleDescribeMapRun(JsonNode request) {
MapRun mapRun = service.describeMapRun(requiredText(request, "mapRunArn"));
return Response.ok(describeMapRunResponse(objectMapper, mapRun)).build();
}
/**
* The wire response of {@code DescribeMapRun}, measured against us-east-1. The
* {@code arn:aws:states:::aws-sdk:sfn:describeMapRun} Task integration renders the same node in
* PascalCase, so this is the one place the response is described.
*
* <p>A retained run is one whose every item succeeded, because a Map fails on the first item
* that fails. That fixes {@code status}, both zero tolerances and {@code redriveCount}:
* {@code redriveDate} is absent until a run is redriven, and no run here ever is.
*/
static ObjectNode describeMapRunResponse(ObjectMapper objectMapper, MapRun mapRun) {
ObjectNode response = objectMapper.createObjectNode();
response.put("mapRunArn", mapRun.getMapRunArn());
response.put("executionArn", mapRun.getExecutionArn());
response.put("status", "SUCCEEDED");
response.put("startDate", mapRun.getStartDate());
response.put("stopDate", mapRun.getStopDate());
response.put("maxConcurrency", mapRun.getMaxConcurrency());
response.put("toleratedFailurePercentage", 0.0);
response.put("toleratedFailureCount", 0);
putMapRunCounts(response.putObject("itemCounts"), mapRun.getItemCount());
// One child execution per item: ItemBatcher is not applied, so no execution covers a batch.
putMapRunCounts(response.putObject("executionCounts"), mapRun.getItemCount());
response.put("redriveCount", 0);
return response;
}
/** The ten counters of a run whose every item succeeded and was written to the result set. */
private static void putMapRunCounts(ObjectNode counts, int items) {
counts.put("pending", 0);
counts.put("running", 0);
counts.put("succeeded", items);
counts.put("failed", 0);
counts.put("timedOut", 0);
counts.put("aborted", 0);
counts.put("total", items);
counts.put("resultsWritten", items);
counts.put("failuresNotRedrivable", 0);
counts.put("pendingRedrive", 0);
}
private Response handleListExecutions(JsonNode request) {
List<Execution> list = service.listExecutions(request.path("stateMachineArn").asText());
ObjectNode response = objectMapper.createObjectNode();
@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.stepfunctions.model.Activity;
import io.github.hectorvent.floci.services.stepfunctions.model.ActivityTask;
import io.github.hectorvent.floci.services.stepfunctions.model.Execution;
import io.github.hectorvent.floci.services.stepfunctions.model.HistoryEvent;
import io.github.hectorvent.floci.services.stepfunctions.model.MapRun;
import io.github.hectorvent.floci.services.stepfunctions.model.MockedTestCase;
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachineVersion;
@@ -44,6 +45,7 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
private final StorageBackend<String, StateMachine> stateMachineStore;
private final StorageBackend<String, Execution> executionStore;
private final StorageBackend<String, Activity> activityStore;
private final StorageBackend<String, MapRun> mapRunStore;
private final Map<String, List<HistoryEvent>> historyCache = new ConcurrentHashMap<>();
private final Map<String, BlockingQueue<ActivityTask>> activityQueues = new ConcurrentHashMap<>();
private final Map<String, CompletableFuture<JsonNode>> pendingTaskTokens = new ConcurrentHashMap<>();
@@ -89,6 +91,8 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
new TypeReference<Map<String, Execution>>() {});
this.activityStore = storageFactory.create("stepfunctions", "sfn-activities.json",
new TypeReference<Map<String, Activity>>() {});
this.mapRunStore = storageFactory.create("stepfunctions", "sfn-map-runs.json",
new TypeReference<Map<String, MapRun>>() {});
this.regionResolver = regionResolver;
this.aslExecutor = aslExecutor;
this.objectMapper = objectMapper;
@@ -777,6 +781,23 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
LOG.debugv("Task heartbeat for token {0}", taskToken);
}
// ──────────────────────────── Map runs ────────────────────────────
/**
* Retains a finished Map run so {@code DescribeMapRun} can still report it once the execution
* that opened it is over. Reconciliation state machines read those counters from a later state,
* or from a later execution altogether, so the run has to outlive the Map that produced it.
*/
public void recordMapRun(MapRun mapRun) {
mapRunStore.put(mapRun.getMapRunArn(), mapRun);
}
public MapRun describeMapRun(String mapRunArn) {
return mapRunStore.get(mapRunArn)
.orElseThrow(() -> new AwsException("ResourceNotFound",
"Resource not found: '" + mapRunArn + "'", 400));
}
// ──────────────────────────── Tags ────────────────────────────
public Map<String, String> listTags(String arn) {
@@ -0,0 +1,44 @@
package io.github.hectorvent.floci.services.stepfunctions.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* A distributed Map run that has finished, keyed by its Map run ARN.
*
* <p>A Map fails on the first item that fails, so a run only reaches the {@code ResultWriter} that
* mints its ARN once every item has succeeded. That is why a run carries a single {@code itemCount}
* rather than the ten counters {@code DescribeMapRun} reports: the other nine are zero, and
* {@code succeeded}, {@code total} and {@code resultsWritten} are all this count.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class MapRun {
private String mapRunArn;
/** The execution of the state machine whose Map state opened this run. */
private String executionArn;
private double startDate;
private double stopDate;
/** Items processed by the run, which is also the number of child executions it ran. */
private int itemCount;
/** The Map's declared MaxConcurrency, with an unbounded Map held as Integer.MAX_VALUE. */
private int maxConcurrency;
public String getMapRunArn() { return mapRunArn; }
public void setMapRunArn(String mapRunArn) { this.mapRunArn = mapRunArn; }
public String getExecutionArn() { return executionArn; }
public void setExecutionArn(String executionArn) { this.executionArn = executionArn; }
public double getStartDate() { return startDate; }
public void setStartDate(double startDate) { this.startDate = startDate; }
public double getStopDate() { return stopDate; }
public void setStopDate(double stopDate) { this.stopDate = stopDate; }
public int getItemCount() { return itemCount; }
public void setItemCount(int itemCount) { this.itemCount = itemCount; }
public int getMaxConcurrency() { return maxConcurrency; }
public void setMaxConcurrency(int maxConcurrency) { this.maxConcurrency = maxConcurrency; }
}