feat(stepfunctions): run Map iterations concurrently honoring MaxConcurrency (#1810)

* feat(stepfunctions): run Map iterations concurrently honoring MaxConcurrency

A Map state ran its iterations one after another. AWS runs them
concurrently up to MaxConcurrency (default 0 = unlimited), which is a
correctness requirement, not just a speed-up: a Map whose iterations
coordinate — e.g. a dependency-ordered fan-out where one child blocks
until a sibling completes — deadlocks when the iterations are serialised.

Run each iteration on the shared executor under the execution's account,
gated by a Semaphore sized to MaxConcurrency (unlimited when 0). Results
are written into per-index slots so the output array preserves input order
regardless of completion order, MaxConcurrency=1 stays strictly sequential,
and a failed iteration cancels the rest and fails the Map (fail-fast,
matching the default ToleratedFailureCount of 0).

* fix(stepfunctions): cap Map worker threads with a bounded pool + handle interruption

Address review: submitting every iteration to the shared cached pool behind
a Semaphore spawned one thread per item (a 1000-item Map with
MaxConcurrency=5 created ~1000 threads, ~995 parked). Run iterations on a
fixed-size per-Map ThreadPoolExecutor sized to MaxConcurrency so live
threads are capped and the rest queue. shutdownNow() in finally stops the
iterations on any exit, and an InterruptedException from the driver now
preserves the interrupt status.

* fix(stepfunctions): make Map concurrency bounded and fail-fast

* docs(stepfunctions): document map concurrency

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after OpenTofu registry flake

* test(stepfunctions): pin Map item selection order
This commit is contained in:
Alex Banna authored and GitHub committed 2026-08-13 16:22:54 -04:00
1 parent 9e7cdad29a
commit a7da1b9856
8 files changed
+888 -108

No files matched your search

@@ -94,6 +94,14 @@ class AslExecutorPathIntrinsicsTest {
assertEquals("b", executor.resolvePath("$.items[1]", root).asText());
}
@Test
void bracketQuotedMembersSupportNamesOutsideDotShorthand() throws Exception {
JsonNode root = mapper.readTree("{\"config\":{\"max-limit\":2},\"a.b\":3}");
assertEquals(2, executor.resolvePath("$['config']['max-limit']", root).asInt());
assertEquals(3, executor.resolvePath("$['a.b']", root).asInt());
}
@Test
void resolvePathNodeDistinguishesExplicitNullFromMissing() throws Exception {
JsonNode root = mapper.readTree("{\"x\":null}");
@@ -0,0 +1,130 @@
package io.github.hectorvent.floci.services.stepfunctions;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
class MapIterationSchedulerTest {
@Test
void appliesAwsConcurrencyCeilingsForInlineAndDistributedMaps() {
assertEquals(40, AslExecutor.effectiveMapConcurrency(50_000, 0, false));
assertEquals(40, AslExecutor.effectiveMapConcurrency(50_000, 500, false));
assertEquals(7, AslExecutor.effectiveMapConcurrency(7, 0, false));
assertEquals(10_000, AslExecutor.effectiveMapConcurrency(50_000, 0, true));
assertEquals(250, AslExecutor.effectiveMapConcurrency(50_000, 250, true));
}
@Test
void maxConcurrencyOneStartsEachItemStrictlyInInputOrder() throws Exception {
List<Integer> starts = new java.util.concurrent.CopyOnWriteArrayList<>();
List<Integer> results = MapIterationScheduler.execute(5, 1, index -> () -> {
starts.add(index);
return index;
});
assertEquals(List.of(0, 1, 2, 3, 4), starts);
assertEquals(starts, results);
}
@Test
void keepsOnlyMaxConcurrencyIterationsInFlight() throws Exception {
int itemCount = 50;
int maxConcurrency = 3;
AtomicInteger active = new AtomicInteger();
AtomicInteger maxObserved = new AtomicInteger();
AtomicInteger started = new AtomicInteger();
CountDownLatch firstWaveStarted = new CountDownLatch(maxConcurrency);
CountDownLatch release = new CountDownLatch(1);
try (ExecutorService driver = Executors.newSingleThreadExecutor()) {
Future<List<Integer>> execution = driver.submit(() -> MapIterationScheduler.execute(
itemCount, maxConcurrency, index -> () -> {
int nowActive = active.incrementAndGet();
maxObserved.accumulateAndGet(nowActive, Math::max);
started.incrementAndGet();
firstWaveStarted.countDown();
try {
release.await();
return index;
} finally {
active.decrementAndGet();
}
}));
assertTrue(firstWaveStarted.await(2, TimeUnit.SECONDS), "initial worker window did not start");
assertEquals(maxConcurrency, started.get(), "queued items must not be submitted early");
release.countDown();
assertEquals(java.util.stream.IntStream.range(0, itemCount).boxed().toList(),
execution.get(5, TimeUnit.SECONDS));
assertEquals(maxConcurrency, maxObserved.get());
}
}
@Test
void reportsLaterFailureWithoutWaitingForAnEarlierBlockedItem() throws Exception {
CountDownLatch slowStarted = new CountDownLatch(1);
CountDownLatch slowInterrupted = new CountDownLatch(1);
CountDownLatch neverRelease = new CountDownLatch(1);
try (ExecutorService driver = Executors.newSingleThreadExecutor()) {
Future<List<Integer>> execution = driver.submit(() -> MapIterationScheduler.execute(
2, 2, index -> () -> {
if (index == 0) {
slowStarted.countDown();
try {
neverRelease.await();
return index;
} catch (InterruptedException e) {
slowInterrupted.countDown();
throw e;
}
}
if (!slowStarted.await(2, TimeUnit.SECONDS)) {
fail("slow iteration did not start");
}
throw new IllegalStateException("later iteration failed");
}));
ExecutionException failure = assertThrows(ExecutionException.class,
() -> execution.get(2, TimeUnit.SECONDS));
assertEquals(IllegalStateException.class, failure.getCause().getClass());
assertEquals("later iteration failed", failure.getCause().getMessage());
assertTrue(slowInterrupted.await(2, TimeUnit.SECONDS),
"the blocked sibling should be interrupted after failure");
}
}
@Test
void preservesInputOrderWhenItemsCompleteOutOfOrder() throws Exception {
CountDownLatch laterItemsCompleted = new CountDownLatch(2);
List<Integer> results = org.junit.jupiter.api.Assertions.assertTimeoutPreemptively(
Duration.ofSeconds(2),
() -> MapIterationScheduler.execute(3, 3, index -> () -> {
if (index == 0) {
laterItemsCompleted.await();
} else {
laterItemsCompleted.countDown();
}
return index;
}));
assertEquals(List.of(0, 1, 2), results);
}
}
@@ -0,0 +1,212 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Wire-level coverage for Map concurrency configuration and ordered results. The scheduler's
* concurrency, bounded-window, cancellation, and fail-fast behavior is covered deterministically
* by {@link MapIterationSchedulerTest} rather than with wall-clock assertions.
*/
@QuarkusTest
class StepFunctionsMapConcurrencyIntegrationTest {
private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role";
private final ObjectMapper mapper = new ObjectMapper();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static String mapDef(Integer maxConcurrency) {
String mc = maxConcurrency == null ? "" : "\"MaxConcurrency\":" + maxConcurrency + ",";
return mapDefWithConcurrencyField(mc);
}
private static String mapDefWithConcurrencyField(String concurrencyField) {
return "{\"StartAt\":\"M\",\"States\":{"
+ "\"M\":{\"Type\":\"Map\",\"ItemsPath\":\"$.items\"," + concurrencyField
+ "\"ItemProcessor\":{\"StartAt\":\"P\",\"States\":{"
+ "\"P\":{\"Type\":\"Pass\",\"End\":true}}},"
+ "\"End\":true}}}";
}
private static String items(int n) {
StringBuilder sb = new StringBuilder("{\"items\":[");
for (int i = 0; i < n; i++) {
if (i > 0) sb.append(',');
sb.append("{\"i\":").append(i).append('}');
}
return sb.append("]}").toString();
}
private void assertOrderedItems(String output, int n) throws Exception {
JsonNode arr = mapper.readTree(output);
assertEquals(n, arr.size());
for (int i = 0; i < n; i++) {
assertEquals(i, arr.get(i).path("i").asInt(), "results must be in input order");
}
}
@Test
void mapPreservesInputOrderWithDefaultConcurrency() throws Exception {
assertOrderedItems(run(mapDef(null), items(50)), 50);
}
@Test
void mapAcceptsStaticMaxConcurrency() throws Exception {
assertOrderedItems(run(mapDef(1), items(5)), 5);
}
@Test
void mapResolvesMaxConcurrencyPathFromItsInput() throws Exception {
String input = "{\"ignored\":true,\"payload\":{"
+ "\"config\":{\"max-limit\":2},\"items\":["
+ "{\"i\":0},{\"i\":1},{\"i\":2},{\"i\":3}]}}";
assertOrderedItems(run(mapDefWithConcurrencyField(
"\"InputPath\":\"$.payload\","
+ "\"MaxConcurrencyPath\":\"$.config.['max-limit']\","), input), 4);
}
@Test
void mapResolvesItemsPathFromEffectiveInputWithoutResultWriter() throws Exception {
String definition = """
{
"StartAt": "M",
"States": {
"M": {
"Type": "Map",
"InputPath": "$.payload",
"ItemsPath": "$.items",
"ItemProcessor": {
"StartAt": "P",
"States": {"P": {"Type": "Pass", "End": true}}
},
"End": true
}
}
}
""";
String input = "{\"items\":[{\"i\":99}],\"payload\":{\"items\":[{\"i\":0},{\"i\":1}]}}";
assertOrderedItems(run(definition, input), 2);
}
@Test
void jsonataMapEvaluatesMaxConcurrencyExpression() throws Exception {
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "M",
"States": {
"M": {
"Type": "Map",
"Items": "{% $states.input.items %}",
"MaxConcurrency": "{% $states.input.limit %}",
"ItemProcessor": {
"StartAt": "P",
"States": {"P": {"Type": "Pass", "End": true}}
},
"End": true
}
}
}
""";
assertOrderedItems(run(definition,
"{\"limit\":3,\"items\":[{\"i\":0},{\"i\":1},{\"i\":2},{\"i\":3}]}"), 4);
}
@ParameterizedTest
@ValueSource(strings = {"true", "-1", "1.5", "$states.input.missing"})
void invalidJsonataMaxConcurrencyIsCatchableAsQueryEvaluationError(String expression) throws Exception {
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "M",
"States": {
"M": {
"Type": "Map",
"Items": "{% $states.input.items %}",
"MaxConcurrency": "{% __EXPRESSION__ %}",
"ItemProcessor": {
"StartAt": "P",
"States": {"P": {"Type": "Pass", "End": true}}
},
"Catch": [{
"ErrorEquals": ["States.QueryEvaluationError"],
"Next": "Caught"
}],
"Next": "Unexpected"
},
"Caught": {
"Type": "Pass",
"Output": {"caught": true},
"End": true
},
"Unexpected": {"Type": "Fail", "Error": "UnexpectedSuccess"}
}
}
""".replace("__EXPRESSION__", expression);
JsonNode output = mapper.readTree(run(definition, "{\"items\":[1,2]}"));
assertTrue(output.path("caught").asBoolean());
}
private String run(String definition, String input) throws InterruptedException {
String name = "map-concurrency-" + System.nanoTime();
Response create = given()
.header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
.contentType(SFN_CONTENT_TYPE)
.body("{\"name\":\"" + name + "\",\"definition\":" + quote(definition) + ",\"roleArn\":\"" + ROLE_ARN + "\"}")
.when().post("/");
create.then().statusCode(200);
String smArn = create.jsonPath().getString("stateMachineArn");
Response start = given()
.header("X-Amz-Target", "AWSStepFunctions.StartExecution")
.contentType(SFN_CONTENT_TYPE)
.body("{\"stateMachineArn\":\"" + smArn + "\",\"input\":" + quote(input) + "}")
.when().post("/");
start.then().statusCode(200);
String execArn = start.jsonPath().getString("executionArn");
for (int i = 0; i < 100; i++) {
Response d = given()
.header("X-Amz-Target", "AWSStepFunctions.DescribeExecution")
.contentType(SFN_CONTENT_TYPE)
.body("{\"executionArn\":\"" + execArn + "\"}")
.when().post("/");
String status = d.jsonPath().getString("status");
if ("SUCCEEDED".equals(status)) {
return d.jsonPath().getString("output");
}
if ("FAILED".equals(status)) {
fail("Execution failed: " + d.body().asString());
}
Thread.sleep(100);
}
fail("Execution did not complete");
return null;
}
private static String quote(String raw) {
return "\"" + raw.replace("\\", "\\\\").replace("\"", "\\\"")
.replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t") + "\"";
}
}
@@ -184,6 +184,104 @@ class StepFunctionsValidateStateMachineDefinitionIntegrationTest {
.body("diagnostics[0].location", equalTo("/States/X/InputPath"));
}
@Test
void mapCannotSpecifyBothMaxConcurrencyFields() {
String def = mapDefinition("", "\"MaxConcurrency\":2,"
+ "\"MaxConcurrencyPath\":\"$.limit\",");
given().contentType(CT).header("X-Amz-Target", TARGET)
.body(definitionRequest(def))
.when().post("/")
.then().statusCode(200)
.body("result", equalTo("FAIL"))
.body("diagnostics", hasSize(1))
.body("diagnostics[0].location", equalTo("/States/M/MaxConcurrency"));
}
@Test
void mapMaxConcurrencyMustBeANonNegativeInteger() {
String def = mapDefinition("", "\"MaxConcurrency\":-1,");
given().contentType(CT).header("X-Amz-Target", TARGET)
.body(definitionRequest(def))
.when().post("/")
.then().statusCode(200)
.body("result", equalTo("FAIL"))
.body("diagnostics", hasSize(1))
.body("diagnostics[0].location", equalTo("/States/M/MaxConcurrency"));
}
@Test
void jsonataMapRejectsMaxConcurrencyPath() {
String def = mapDefinition("\"QueryLanguage\":\"JSONata\",",
"\"MaxConcurrencyPath\":\"$.limit\",");
given().contentType(CT).header("X-Amz-Target", TARGET)
.body(definitionRequest(def))
.when().post("/")
.then().statusCode(200)
.body("result", equalTo("FAIL"))
.body("diagnostics", hasSize(1))
.body("diagnostics[0].location", equalTo("/States/M/MaxConcurrencyPath"));
}
@Test
void jsonataMapAcceptsMaxConcurrencyExpression() {
String def = mapDefinition("\"QueryLanguage\":\"JSONata\",",
"\"MaxConcurrency\":\"{% $states.input.limit %}\",");
given().contentType(CT).header("X-Amz-Target", TARGET)
.body(definitionRequest(def))
.when().post("/")
.then().statusCode(200)
.body("result", equalTo("OK"))
.body("diagnostics", hasSize(0));
}
@Test
void nestedMapMaxConcurrencyIsValidatedAtItsStructuredPath() {
String def = "{\"StartAt\":\"Outer\",\"States\":{\"Outer\":{\"Type\":\"Map\","
+ "\"ItemProcessor\":{\"StartAt\":\"Inner\",\"States\":{"
+ "\"Inner\":{\"Type\":\"Map\",\"MaxConcurrency\":-1,"
+ "\"ItemProcessor\":{\"StartAt\":\"P\",\"States\":{"
+ "\"P\":{\"Type\":\"Pass\",\"End\":true}}},\"End\":true}}},"
+ "\"End\":true}}}";
given().contentType(CT).header("X-Amz-Target", TARGET)
.body(definitionRequest(def))
.when().post("/")
.then().statusCode(200)
.body("result", equalTo("FAIL"))
.body("diagnostics", hasSize(1))
.body("diagnostics[0].location", equalTo(
"/States/Outer/ItemProcessor/States/Inner/MaxConcurrency"));
}
@Test
void maxConcurrencyPathMustSelectASingleNode() {
String def = mapDefinition("", "\"MaxConcurrencyPath\":\"$.limits[*]\",");
given().contentType(CT).header("X-Amz-Target", TARGET)
.body(definitionRequest(def))
.when().post("/")
.then().statusCode(200)
.body("result", equalTo("FAIL"))
.body("diagnostics", hasSize(1))
.body("diagnostics[0].location", equalTo("/States/M/MaxConcurrencyPath"));
}
@Test
void maxConcurrencyLargerThanIntegerRangeIsAcceptedAndRuntimeCapped() {
String def = mapDefinition("", "\"MaxConcurrency\":9223372036854775807,");
given().contentType(CT).header("X-Amz-Target", TARGET)
.body(definitionRequest(def))
.when().post("/")
.then().statusCode(200)
.body("result", equalTo("OK"))
.body("diagnostics", hasSize(0));
}
@Test
void unsupportedItemReaderResource_returnsFailWithSchemaError() {
given().contentType(CT).header("X-Amz-Target", TARGET)
@@ -519,4 +617,21 @@ class StepFunctionsValidateStateMachineDefinitionIntegrationTest {
.then().statusCode(400)
.body("__type", containsString("ValidationException"));
}
private static String mapDefinition(String topLevelFields, String concurrencyFields) {
return "{" + topLevelFields
+ "\"StartAt\":\"M\",\"States\":{\"M\":{\"Type\":\"Map\","
+ concurrencyFields
+ "\"ItemProcessor\":{\"StartAt\":\"P\",\"States\":{"
+ "\"P\":{\"Type\":\"Pass\",\"End\":true}}},\"End\":true}}}";
}
private static String definitionRequest(String definition) {
String escaped = definition.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t");
return "{\"definition\":\"" + escaped + "\"}";
}
}