feat(sfn): apply ItemBatcher to distributed Map children (#3604)

* feat(sfn): apply ItemBatcher to distributed Map children

ItemBatcher was parsed and then ignored: every child execution received one
item regardless of MaxItemsPerBatch, so a state machine that batches ran with a
different payload shape locally than on AWS, silently.

Items are now grouped into batches and each child execution receives
{"BatchInput": ..., "Items": [...]}. A batch closes on MaxItemsPerBatch or
MaxInputBytesPerBatch, in their literal, Path and JSONata expression forms, and
with neither set every item lands in one batch. ItemSelector still runs per item
before grouping, so the transform sees $$.Map.Item as it did before.

MaxConcurrency now bounds concurrent batches, and DescribeMapRun separates the
two counters it used to share: itemCounts counts items, executionCounts counts
child executions.

* fix(sfn): cap a batch at the 256 KiB child-input ceiling

MaxInputBytesPerBatch being optional let MaxItemsPerBatch alone build a child
input larger than Step Functions would ever start, and the byte count measured
the items alone, so a declared cap could still be exceeded by the envelope,
BatchInput and separators.

Batching now measures the serialized child payload and closes a batch at the
declared limit or at 256 KiB, whichever is smaller.

* fix(sfn): fail an item too large to start a child execution

An item whose serialized batch input already exceeded 256 KiB was added anyway,
because the split branch is skipped while the batch is empty, producing a child
input AWS would refuse to start.

Such an item now fails the state with States.DataLimitExceeded, naming its size
and pointing at ItemSelector as the way to reduce it.

* refactor(sfn): resolve every integer Map field through one helper

MaxConcurrency and the ItemBatcher limits read the same three forms, literal,
Path and JSONata expression, through two near-identical methods. The batcher one
already parameterized the field name, so the pair collapses into a single
resolver with a minimum: 0 for MaxConcurrency, where it means the service
ceiling, and 1 for a batch limit, where it is meaningless.

The shared resolver also clamps an oversized value to Integer.MAX_VALUE, which
only the MaxConcurrency copy did before.
This commit is contained in:
Ovidiu (Ovi) authored and GitHub committed 2026-09-15 07:43:59 -04:00
1 parent 38d1d0a8e4
commit 917e94914f
6 files changed
+524 -51

No files matched your search

@@ -292,6 +292,48 @@ class StepFunctionsDescribeMapRunIntegrationTest {
assertEquals(10, counts.size(), "a counter set carries exactly ten fields");
}
/**
* itemCounts counts items and executionCounts counts child executions, which an ItemBatcher run
* is the only shape to tell apart. The split follows the documented ItemBatcher semantics rather
* than a measured run.
*/
@Test
@Order(12)
void describeMapRunCountsBatchedItemsAndExecutionsSeparately() throws Exception {
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Fan",
"States": {
"Fan": {
"Type": "Map",
"End": true,
"Items": [{"n": 1}, {"n": 2}, {"n": 3}, {"n": 4}, {"n": 5}],
"ItemBatcher": {"MaxItemsPerBatch": 2},
"ItemProcessor": {
"ProcessorConfig": {"Mode": "DISTRIBUTED", "ExecutionType": "STANDARD"},
"StartAt": "Keep",
"States": {"Keep": {"Type": "Pass", "End": true}}
}
}
}
}
""";
String smArn = createStateMachine("describe-map-run-batched", definition);
String execArn = startExecution(smArn, "{}");
Response describe = waitForTerminalState(execArn);
assertEquals("SUCCEEDED", describe.jsonPath().getString("status"),
"cause: " + describe.jsonPath().getString("cause"));
Response response = describeMapRun(mapRunArnFromHistory(execArn));
response.then().statusCode(200);
assertEquals(5, response.jsonPath().getInt("itemCounts.total"));
assertEquals(5, response.jsonPath().getInt("itemCounts.succeeded"));
assertEquals(3, response.jsonPath().getInt("executionCounts.total"));
assertEquals(3, response.jsonPath().getInt("executionCounts.succeeded"));
}
private static String distributedMap(String items, String bucket, Integer maxConcurrency) {
return """
{
@@ -942,6 +942,291 @@ class StepFunctionsJsonataIntegrationTest {
assertEquals("States.ItemReaderFailed", failure.jsonPath().getString("error"));
}
@Test
void distributedMapWithItemBatcher_groupsItemsIntoBatchesOfMaxItemsPerBatch() throws Exception {
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Fan",
"States": {
"Fan": {
"Type": "Map",
"Items": [{"n": 1}, {"n": 2}, {"n": 3}, {"n": 4}, {"n": 5}],
"ItemBatcher": {"MaxItemsPerBatch": 2},
"ItemProcessor": {
"ProcessorConfig": {
"Mode": "DISTRIBUTED",
"ExecutionType": "STANDARD"
},
"StartAt": "Keep",
"States": {
"Keep": {
"Type": "Pass",
"End": true
}
}
},
"End": true
}
}
}
""";
String smArn = createStateMachine("map-item-batcher-max-items", definition);
String execArn = startExecution(smArn, "{}");
String output = waitForExecution(execArn);
JsonNode batches = new ObjectMapper().readTree(output);
assertEquals(3, batches.size());
assertEquals(2, batches.get(0).path("Items").size());
assertEquals(2, batches.get(1).path("Items").size());
assertEquals(1, batches.get(2).path("Items").size());
assertEquals(1, batches.get(0).path("Items").get(0).path("n").asInt());
}
@Test
void distributedMapWithItemBatcher_mergesBatchInputIntoEveryBatch() throws Exception {
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Fan",
"States": {
"Fan": {
"Type": "Map",
"Items": [{"n": 1}, {"n": 2}, {"n": 3}, {"n": 4}, {"n": 5}],
"ItemBatcher": {"MaxItemsPerBatch": 2, "BatchInput": {"runType": "nightly"}},
"ItemProcessor": {
"ProcessorConfig": {
"Mode": "DISTRIBUTED",
"ExecutionType": "STANDARD"
},
"StartAt": "Keep",
"States": {
"Keep": {
"Type": "Pass",
"End": true
}
}
},
"End": true
}
}
}
""";
String smArn = createStateMachine("map-item-batcher-batch-input", definition);
String execArn = startExecution(smArn, "{}");
String output = waitForExecution(execArn);
JsonNode batches = new ObjectMapper().readTree(output);
assertEquals(3, batches.size());
for (JsonNode batch : batches) {
assertEquals("nightly", batch.path("BatchInput").path("runType").asText());
}
}
@Test
void distributedMapWithItemBatcher_startsANewBatchOnMaxInputBytesPerBatch() throws Exception {
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Fan",
"States": {
"Fan": {
"Type": "Map",
"Items": [{"n": 1}, {"n": 2}, {"n": 3}, {"n": 4}, {"n": 5}],
"ItemBatcher": {"MaxInputBytesPerBatch": 20},
"ItemProcessor": {
"ProcessorConfig": {
"Mode": "DISTRIBUTED",
"ExecutionType": "STANDARD"
},
"StartAt": "Keep",
"States": {
"Keep": {
"Type": "Pass",
"End": true
}
}
},
"End": true
}
}
}
""";
String smArn = createStateMachine("map-item-batcher-max-bytes", definition);
String execArn = startExecution(smArn, "{}");
String output = waitForExecution(execArn);
JsonNode batches = new ObjectMapper().readTree(output);
assertTrue(batches.size() > 1, "expected the byte limit to split the items: " + output);
for (JsonNode batch : batches) {
assertTrue(batch.path("Items").size() >= 1);
}
}
@Test
void distributedMapWithoutItemBatcher_stillGivesEachChildOneItem() throws Exception {
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Fan",
"States": {
"Fan": {
"Type": "Map",
"Items": [{"n": 1}, {"n": 2}],
"ItemProcessor": {
"ProcessorConfig": {
"Mode": "DISTRIBUTED",
"ExecutionType": "STANDARD"
},
"StartAt": "Keep",
"States": {
"Keep": {
"Type": "Pass",
"End": true
}
}
},
"End": true
}
}
}
""";
String smArn = createStateMachine("map-item-batcher-absent", definition);
String execArn = startExecution(smArn, "{}");
String output = waitForExecution(execArn);
JsonNode children = new ObjectMapper().readTree(output);
assertEquals(2, children.size());
assertEquals(1, children.get(0).path("n").asInt());
assertTrue(children.get(0).path("Items").isMissingNode());
}
@Test
void distributedMapWithItemBatcher_capsABatchAtTheChildInputCeiling() throws Exception {
createBucket("map-inputs-large");
StringBuilder dataset = new StringBuilder("[");
for (int i = 0; i < 40; i++) {
if (i > 0) {
dataset.append(",");
}
dataset.append("{\"pad\":\"").append("x".repeat(10_000)).append("\"}");
}
dataset.append("]");
putObject("map-inputs-large", "large.json", dataset.toString());
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Fan",
"States": {
"Fan": {
"Type": "Map",
"ItemReader": {
"Resource": "arn:aws:states:::s3:getObject",
"ReaderConfig": {
"InputType": "JSON"
},
"Arguments": {
"Bucket": "map-inputs-large",
"Key": "large.json"
}
},
"ItemBatcher": {
"MaxItemsPerBatch": 100
},
"ItemProcessor": {
"ProcessorConfig": {
"Mode": "DISTRIBUTED",
"ExecutionType": "STANDARD"
},
"StartAt": "Count",
"States": {
"Count": {
"Type": "Pass",
"Output": "{% { 'n': $count($states.input.Items) } %}",
"End": true
}
}
},
"End": true
}
}
}
""";
String smArn = createStateMachine("map-item-batcher-ceiling", definition);
String execArn = startExecution(smArn, "{}");
String output = waitForExecution(execArn);
JsonNode batches = new ObjectMapper().readTree(output);
// 40 items of about 10 KB each exceed 256 KiB, so MaxItemsPerBatch 100 cannot be the only limit.
assertTrue(batches.size() > 1, "the ceiling must split the run: " + batches.size() + " batches");
int counted = 0;
for (JsonNode batch : batches) {
int size = batch.path("n").asInt();
assertTrue(size * 10_000 < 256 * 1024, "batch of " + size + " items exceeds the ceiling");
counted += size;
}
assertEquals(40, counted);
}
@Test
void distributedMapWithItemBatcher_failsWhenASingleItemExceedsTheCeiling() throws Exception {
createBucket("map-inputs-oversized");
putObject("map-inputs-oversized", "oversized.json",
"[{\"pad\":\"" + "x".repeat(300_000) + "\"}]");
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Fan",
"States": {
"Fan": {
"Type": "Map",
"ItemReader": {
"Resource": "arn:aws:states:::s3:getObject",
"ReaderConfig": {
"InputType": "JSON"
},
"Arguments": {
"Bucket": "map-inputs-oversized",
"Key": "oversized.json"
}
},
"ItemBatcher": {
"MaxItemsPerBatch": 10
},
"ItemProcessor": {
"ProcessorConfig": {
"Mode": "DISTRIBUTED",
"ExecutionType": "STANDARD"
},
"StartAt": "Keep",
"States": {
"Keep": {
"Type": "Pass",
"End": true
}
}
},
"End": true
}
}
}
""";
String smArn = createStateMachine("map-item-batcher-oversized", definition);
String execArn = startExecution(smArn, "{}");
Response failure = waitForExecutionFailure(execArn);
assertEquals("FAILED", failure.jsonPath().getString("status"));
assertEquals("States.DataLimitExceeded", failure.jsonPath().getString("error"));
}
@Test
void distributedMapWithS3JsonItemReader_objectIteratesKeyValuePairs() throws Exception {
createBucket("map-inputs-object");