feat(sfn): publish history events for Parallel branches and Map iterations (#3167)

* feat(sfn): publish Parallel branch and Map iteration history events

The states inside a Parallel branch or an inline Map iteration now publish
their events into the execution history.

The cause of a failure the interpreter raises now carries the AWS prefix
"An error occurred while executing the state '<name>' (entered at the event
id #<n>). ". It is written once, at the innermost state.

Every shape was verified against real Step Functions in us-east-1.

* feat(sfn): record EvaluationFailed for JSONata failures

A JSONata expression that fails now leaves the EvaluationFailed event AWS
records, with error, the attributed cause, location and state. The location
names the field the way the cause does. The event is recorded once per
attempt when the state retries, and before the Failed event and the Catch.
A Catch clause whose own expression fails records it from where the state
stood before its first Failed event, then fails the state again.

Verified against real Step Functions in us-east-1

* fix(sfn): record every Distributed Map run so DescribeMapRun resolves its ARN

* fix(sfn): stop counting history events once the execution has ended
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-09-07 23:18:05 -04:00
1 parent 5eacd01636
commit fd21ac9a6d
19 files changed
+1726 -333

No files matched your search

@@ -0,0 +1,614 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
import io.github.hectorvent.floci.services.lambda.LambdaExecutorService;
import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore;
import io.github.hectorvent.floci.services.s3.S3Service;
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.MockedResponseStep;
import io.github.hectorvent.floci.services.stepfunctions.model.MockedTestCase;
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
import io.quarkus.test.junit.QuarkusTest;
import io.vertx.mutiny.core.Vertx;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* The history events of the states inside a Parallel branch or a Map iteration, and the cause a
* failure inside one reports. Every shape here was read off real Step Functions in us-east-1 for
* issue #2868: the event families a Parallel and a Map publish around their branches, how
* {@code previousEventId} chains a branch's events to each other and to the state that started
* them, which failures leave a {@code *StateFailed} event, and the
* {@code An error occurred while executing the state ...} prefix a cause carries.
*
* <p>Branches run concurrently, so the order in which their events interleave is not asserted.
* What is asserted is what a reader needs to follow each branch: the chain.
*/
@QuarkusTest
class AslExecutorBranchHistoryEventsTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private final ObjectMapper objectMapper = new ObjectMapper();
private AslExecutor executor;
@Inject
Vertx vertx;
@BeforeEach
void setUp() {
Instance<StepFunctionsService> sfnService = mock(Instance.class);
when(sfnService.get()).thenReturn(mock(StepFunctionsService.class));
executor = new AslExecutor(
mock(LambdaExecutorService.class),
mock(LambdaFunctionStore.class),
mock(DynamoDbService.class),
mock(DynamoDbJsonHandler.class),
mock(SqsJsonHandler.class),
mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class),
mock(io.github.hectorvent.floci.services.ec2.Ec2Service.class),
mock(S3Service.class),
mock(io.github.hectorvent.floci.services.ecs.EcsService.class),
mock(io.github.hectorvent.floci.services.ecs.EcsJsonHandler.class),
mock(io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerService.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
objectMapper,
new JsonataEvaluator(objectMapper),
sfnService, mock(EmulatorConfig.class), vertx,
mock(io.github.hectorvent.floci.core.common.CustomResourceLiveness.class));
}
@Test
void parallelBranchesPublishTheirStatesOnChainsOfTheirOwn() {
var history = run("""
{"StartAt":"P","States":{
"P":{"Type":"Parallel","Branches":[
{"StartAt":"A1","States":{"A1":{"Type":"Pass","Next":"A2"},"A2":{"Type":"Pass","End":true}}},
{"StartAt":"B1","States":{"B1":{"Type":"Pass","Next":"B2"},"B2":{"Type":"Pass","End":true}}}
],"Next":"After"},
"After":{"Type":"Pass","End":true}}}
""", "{\"x\":\"a\"}");
assertEquals("SUCCEEDED", status(history), typesOf(history).toString());
assertEquals(16, history.size(), typesOf(history).toString());
assertIdsAreConsecutive(history);
assertEquals(List.of("ExecutionStarted", "ParallelStateEntered", "ParallelStateStarted"),
typesOf(history.subList(0, 3)));
assertEquals(List.of("ParallelStateSucceeded", "ParallelStateExited", "PassStateEntered",
"PassStateExited", "ExecutionSucceeded"),
typesOf(history.subList(11, 16)));
var started = eventOfType(history, "ParallelStateStarted");
assertEquals(2L, started.getPreviousEventId());
assertNull(started.getDetails());
// Each branch's first state starts from ParallelStateStarted, and the branch chains on from
// there: A1 exited points at A1 entered, A2 entered at A1 exited.
for (String branch : List.of("A", "B")) {
var firstEntered = stateEvent(history, "PassStateEntered", branch + "1");
var firstExited = stateEvent(history, "PassStateExited", branch + "1");
var secondEntered = stateEvent(history, "PassStateEntered", branch + "2");
var secondExited = stateEvent(history, "PassStateExited", branch + "2");
assertEquals(started.getId(), firstEntered.getPreviousEventId());
assertEquals(firstEntered.getId(), firstExited.getPreviousEventId());
assertEquals(firstExited.getId(), secondEntered.getPreviousEventId());
assertEquals(secondEntered.getId(), secondExited.getPreviousEventId());
}
// The Parallel continues from the last event a branch published. ParallelStateSucceeded
// points at it and is passed by: ParallelStateExited points at it too.
long lastBranchEvent = history.get(10).getId();
var succeeded = eventOfType(history, "ParallelStateSucceeded");
var exited = eventOfType(history, "ParallelStateExited");
assertEquals(lastBranchEvent, succeeded.getPreviousEventId());
assertNull(succeeded.getDetails());
assertEquals(lastBranchEvent, exited.getPreviousEventId());
assertEquals("[{\"x\":\"a\"},{\"x\":\"a\"}]", exited.getDetails().get("output"));
assertEquals(exited.getId(), stateEvent(history, "PassStateEntered", "After").getPreviousEventId());
}
/** The shape reported in issue #2868, with the branch that never fails left out. */
@Test
void runtimeErrorInABranchNamesTheBranchStateAndItsEnteredEvent() {
var history = run("""
{"StartAt":"P","States":{
"P":{"Type":"Parallel","Branches":[
{"StartAt":"Fast","States":{"Fast":{"Type":"Pass","Parameters":{"m.$":"$.nope"},"End":true}}}
],"End":true}}}
""", "{\"x\":\"a\"}");
assertEquals(List.of("ExecutionStarted", "ParallelStateEntered", "ParallelStateStarted",
"PassStateEntered", "ExecutionFailed"), typesOf(history));
assertEquals(List.of(0L, 0L, 2L, 3L, 4L), previousEventIdsOf(history));
var failed = history.get(4);
assertEquals("States.Runtime", failed.getDetails().get("error"));
assertEquals("An error occurred while executing the state 'Fast' (entered at the event id #4). "
+ "The JSONPath '$.nope' specified for the field 'm.$' could not be found in the input '{\"x\":\"a\"}'",
failed.getDetails().get("cause"));
}
@Test
void failStateInABranchPassesItsCauseThroughAndLeavesAParallelStateFailedEvent() {
var history = run("""
{"StartAt":"P","States":{
"P":{"Type":"Parallel","Branches":[
{"StartAt":"Boom","States":{"Boom":{"Type":"Fail","Error":"MyError","Cause":"my cause"}}}
],"End":true}}}
""", "{\"x\":\"a\"}");
assertEquals(List.of("ExecutionStarted", "ParallelStateEntered", "ParallelStateStarted",
"FailStateEntered", "ParallelStateFailed", "ExecutionFailed"), typesOf(history));
assertEquals(List.of(0L, 0L, 2L, 3L, 4L, 5L), previousEventIdsOf(history));
assertNull(history.get(4).getDetails());
assertEquals(Map.of("error", "MyError", "cause", "my cause"), history.get(5).getDetails());
}
@Test
void caughtBranchFailureExitsTheParallelWithTheErrorOutput() {
var history = run("""
{"QueryLanguage":"JSONata","StartAt":"P","States":{
"P":{"Type":"Parallel","Branches":[
{"StartAt":"Undef","States":{"Undef":{"Type":"Pass","Output":{"v":"{% $states.input.missing %}"},"End":true}}}
],"Catch":[{"ErrorEquals":["States.ALL"],"Next":"Handled"}],"End":true},
"Handled":{"Type":"Pass","End":true}}}
""", "{\"x\":\"a\"}");
assertEquals(List.of("ExecutionStarted", "ParallelStateEntered", "ParallelStateStarted",
"PassStateEntered", "EvaluationFailed", "ParallelStateFailed", "ParallelStateExited",
"PassStateEntered", "PassStateExited", "ExecutionSucceeded"), typesOf(history));
assertEquals(List.of(0L, 0L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L), previousEventIdsOf(history));
var cause = "An error occurred while executing the state 'Undef' (entered at the event id #4). "
+ "The JSONata expression '$states.input.missing' specified for the field 'Output/v' "
+ "returned nothing (undefined).";
assertEquals(Map.of("error", "States.QueryEvaluationError", "cause", cause, "location", "Output/v",
"state", "Undef"), history.get(4).getDetails());
var errorOutput = "{\"Error\":\"States.QueryEvaluationError\",\"Cause\":\"" + cause.replace("\"", "\\\"") + "\"}";
assertEquals(errorOutput, history.get(6).getDetails().get("output"));
assertEquals(errorOutput, history.get(9).getDetails().get("output"));
}
@Test
void retriedParallelStartsAgainAndFailsOnceItsRetryIsUsedUp() {
var history = run("""
{"StartAt":"P","States":{
"P":{"Type":"Parallel","Branches":[
{"StartAt":"Boom","States":{"Boom":{"Type":"Fail","Error":"MyError","Cause":"my cause"}}}
],"Retry":[{"ErrorEquals":["States.ALL"],"MaxAttempts":1,"IntervalSeconds":0}],"End":true}}}
""", "{\"x\":\"a\"}");
assertEquals(List.of("ExecutionStarted", "ParallelStateEntered", "ParallelStateStarted",
"FailStateEntered", "ParallelStateStarted", "FailStateEntered", "ParallelStateFailed",
"ExecutionFailed"), typesOf(history));
assertEquals(List.of(0L, 0L, 2L, 3L, 4L, 5L, 6L, 7L), previousEventIdsOf(history));
}
@Test
void parallelOwnFailureIsAttributedToTheParallelAfterItsBranchesSucceeded() {
var history = run("""
{"StartAt":"P","States":{
"P":{"Type":"Parallel","Branches":[
{"StartAt":"Ok","States":{"Ok":{"Type":"Pass","End":true}}}
],"ResultSelector":{"m.$":"$.nope"},"End":true}}}
""", "{\"x\":\"a\"}");
assertEquals(List.of("ExecutionStarted", "ParallelStateEntered", "ParallelStateStarted",
"PassStateEntered", "PassStateExited", "ParallelStateSucceeded", "ExecutionFailed"),
typesOf(history));
assertEquals(List.of(0L, 0L, 2L, 3L, 4L, 5L, 6L), previousEventIdsOf(history));
assertEquals("An error occurred while executing the state 'P' (entered at the event id #2). "
+ "The JSONPath '$.nope' specified for the field 'm.$' could not be found in the input '[{\"x\":\"a\"}]'",
history.get(6).getDetails().get("cause"));
}
@Test
void taskFailureEndingABranchIsRecordedAsAbortedAndPassesItsCauseThrough() {
var mocks = new MockedTestCase("branch-history-test", "Case", Map.of("Send", List.of(
new MockedResponseStep(0, 0, null, "SQS.QueueDoesNotExistException", "The specified queue does not exist."))));
var history = run("""
{"StartAt":"P","States":{
"P":{"Type":"Parallel","Branches":[
{"StartAt":"Send","States":{"Send":{"Type":"Task","Resource":"arn:aws:states:::sqs:sendMessage",
"Parameters":{"QueueUrl":"https://sqs.us-east-1.amazonaws.com/000000000000/missing","MessageBody":"hi"},"End":true}}}
],"Catch":[{"ErrorEquals":["States.ALL"],"Next":"Handled"}],"End":true},
"Handled":{"Type":"Pass","End":true}}}
""", "{\"x\":\"a\"}", mocks);
assertEquals(List.of("ExecutionStarted", "ParallelStateEntered", "ParallelStateStarted",
"TaskStateEntered", "TaskScheduled", "TaskStarted", "TaskFailed", "TaskStateAborted",
"ParallelStateFailed", "ParallelStateExited", "PassStateEntered", "PassStateExited",
"ExecutionSucceeded"), typesOf(history));
assertEquals(List.of(0L, 0L, 2L, 3L, 4L, 5L, 6L, 7L, 7L, 9L, 10L, 11L, 12L), previousEventIdsOf(history));
assertNull(history.get(7).getDetails());
assertEquals("{\"Error\":\"SQS.QueueDoesNotExistException\",\"Cause\":\"The specified queue does not exist.\"}",
history.get(9).getDetails().get("output"));
}
@Test
void mapIterationsPublishTheirStatesUnderIterationEvents() {
var history = run("""
{"StartAt":"M","States":{
"M":{"Type":"Map","ItemsPath":"$.items","ItemProcessor":{"ProcessorConfig":{"Mode":"INLINE"},
"StartAt":"I1","States":{"I1":{"Type":"Pass","Next":"I2"},"I2":{"Type":"Pass","End":true}}},
"Next":"After"},
"After":{"Type":"Pass","End":true}}}
""", "{\"items\":[1,2]}");
assertEquals("SUCCEEDED", status(history), typesOf(history).toString());
assertEquals(20, history.size(), typesOf(history).toString());
assertIdsAreConsecutive(history);
assertEquals(List.of("ExecutionStarted", "MapStateEntered", "MapStateStarted"), typesOf(history.subList(0, 3)));
var started = history.get(2);
assertEquals(2L, started.getPreviousEventId());
assertEquals(Map.of("length", 2), started.getDetails());
for (int index = 0; index < 2; index++) {
var iterationStarted = iterationEvent(history, "MapIterationStarted", index);
var iterationSucceeded = iterationEvent(history, "MapIterationSucceeded", index);
var input = String.valueOf(index + 1);
var firstEntered = stateEventWithInput(history, "PassStateEntered", "I1", input);
var firstExited = stateEventWithOutput(history, "PassStateExited", "I1", input);
var secondEntered = stateEventWithInput(history, "PassStateEntered", "I2", input);
var secondExited = stateEventWithOutput(history, "PassStateExited", "I2", input);
assertEquals(Map.of("name", "M", "index", index), iterationStarted.getDetails());
assertEquals(started.getId(), iterationStarted.getPreviousEventId());
assertEquals(iterationStarted.getId(), firstEntered.getPreviousEventId());
assertEquals(firstEntered.getId(), firstExited.getPreviousEventId());
assertEquals(firstExited.getId(), secondEntered.getPreviousEventId());
assertEquals(secondEntered.getId(), secondExited.getPreviousEventId());
assertEquals(secondExited.getId(), iterationSucceeded.getPreviousEventId());
assertEquals(Map.of("name", "M", "index", index), iterationSucceeded.getDetails());
}
assertEquals(List.of("MapStateSucceeded", "MapStateExited", "PassStateEntered", "PassStateExited",
"ExecutionSucceeded"), typesOf(history.subList(15, 20)));
long lastIterationEvent = history.get(14).getId();
assertEquals("MapIterationSucceeded", history.get(14).getType());
assertEquals(lastIterationEvent, history.get(15).getPreviousEventId());
assertNull(history.get(15).getDetails());
assertEquals(lastIterationEvent, history.get(16).getPreviousEventId());
assertEquals("[1,2]", history.get(16).getDetails().get("output"));
}
@Test
void mapOverNoItemsExitsFromItsStartedEvent() {
var history = run("""
{"StartAt":"M","States":{
"M":{"Type":"Map","ItemsPath":"$.items",
"ItemProcessor":{"StartAt":"I","States":{"I":{"Type":"Pass","End":true}}},"End":true}}}
""", "{\"items\":[]}");
assertEquals(List.of("ExecutionStarted", "MapStateEntered", "MapStateStarted", "MapStateSucceeded",
"MapStateExited", "ExecutionSucceeded"), typesOf(history));
assertEquals(List.of(0L, 0L, 2L, 3L, 3L, 5L), previousEventIdsOf(history));
}
@Test
void runtimeErrorInABranchTaskLeavesNoAbortedEvent() {
var history = run("""
{"StartAt":"P","States":{
"P":{"Type":"Parallel","Branches":[
{"StartAt":"Send","States":{"Send":{"Type":"Task","Resource":"arn:aws:states:::sqs:sendMessage",
"Parameters":{"QueueUrl.$":"$.nope","MessageBody":"hi"},"End":true}}}
],"End":true}}}
""", "{\"x\":\"a\"}");
assertEquals(List.of("ExecutionStarted", "ParallelStateEntered", "ParallelStateStarted",
"TaskStateEntered", "ExecutionFailed"), typesOf(history));
assertEquals(List.of(0L, 0L, 2L, 3L, 4L), previousEventIdsOf(history));
}
@Test
void mapIterationFailureLeavesIterationAndStateFailedEventsBehind() {
var history = run("""
{"QueryLanguage":"JSONata","StartAt":"M","States":{
"M":{"Type":"Map","Items":"{% $states.input.items %}","MaxConcurrency":1,
"ItemProcessor":{"ProcessorConfig":{"Mode":"INLINE"},"StartAt":"Undef",
"States":{"Undef":{"Type":"Pass","Output":{"v":"{% $states.input.missing %}"},"End":true}}},
"End":true}}}
""", "{\"items\":[1,2]}");
assertEquals(List.of("ExecutionStarted", "MapStateEntered", "MapStateStarted", "MapIterationStarted",
"PassStateEntered", "EvaluationFailed", "MapIterationFailed", "MapStateFailed", "ExecutionFailed"),
typesOf(history));
// MapIterationFailed points at the iteration's last event and is passed by: MapStateFailed
// points at that same event.
assertEquals(List.of(0L, 0L, 2L, 3L, 4L, 5L, 6L, 6L, 8L), previousEventIdsOf(history));
var cause = "An error occurred while executing the state 'Undef' (entered at the event id #5). "
+ "The JSONata expression '$states.input.missing' specified for the field 'Output/v' "
+ "returned nothing (undefined).";
assertEquals("Undef", history.get(5).getDetails().get("state"));
assertEquals(Map.of("name", "M", "index", 0), history.get(6).getDetails());
assertNull(history.get(7).getDetails());
assertEquals(cause, history.get(8).getDetails().get("cause"));
}
@Test
void runtimeErrorInAMapIterationLeavesNoFailedEvents() {
var history = run("""
{"StartAt":"M","States":{
"M":{"Type":"Map","ItemsPath":"$.items","MaxConcurrency":1,
"ItemProcessor":{"ProcessorConfig":{"Mode":"INLINE"},"StartAt":"Fast",
"States":{"Fast":{"Type":"Pass","Parameters":{"m.$":"$.nope"},"End":true}}},
"End":true}}}
""", "{\"items\":[1,2]}");
assertEquals(List.of("ExecutionStarted", "MapStateEntered", "MapStateStarted", "MapIterationStarted",
"PassStateEntered", "ExecutionFailed"), typesOf(history));
assertEquals(List.of(0L, 0L, 2L, 3L, 4L, 5L), previousEventIdsOf(history));
assertEquals("An error occurred while executing the state 'Fast' (entered at the event id #5). "
+ "The JSONPath '$.nope' specified for the field 'm.$' could not be found in the input '1'",
history.get(5).getDetails().get("cause"));
}
@Test
void distributedMapNamesItsRunAndPublishesNoItemEvents() {
var history = run("""
{"StartAt":"D","States":{
"D":{"Type":"Map","ItemsPath":"$.items","ItemProcessor":{
"ProcessorConfig":{"Mode":"DISTRIBUTED","ExecutionType":"STANDARD"},
"StartAt":"I1","States":{"I1":{"Type":"Pass","End":true}}},
"End":true}}}
""", "{\"items\":[1,2]}");
assertEquals(List.of("ExecutionStarted", "MapStateEntered", "MapStateStarted", "MapRunStarted",
"MapRunSucceeded", "MapStateSucceeded", "MapStateExited", "ExecutionSucceeded"), typesOf(history));
// The parent chain stays at MapRunStarted: MapStateExited points at it, past both Succeeded events.
assertEquals(List.of(0L, 0L, 2L, 3L, 4L, 5L, 4L, 7L), previousEventIdsOf(history));
var mapRunArn = (String) history.get(3).getDetails().get("mapRunArn");
assertTrue(mapRunArn.startsWith("arn:aws:states:us-east-1:000000000000:mapRun:branch-history-test/"), mapRunArn);
assertEquals("[1,2]", history.get(6).getDetails().get("output"));
}
@Test
void nestedMapInsideAParallelBranchChainsToTheBranch() {
var history = run("""
{"StartAt":"P","States":{
"P":{"Type":"Parallel","Branches":[
{"StartAt":"M","States":{"M":{"Type":"Map","ItemsPath":"$.items","ItemProcessor":{
"ProcessorConfig":{"Mode":"INLINE"},"StartAt":"I1","States":{"I1":{"Type":"Pass","End":true}}},
"End":true}}},
{"StartAt":"B1","States":{"B1":{"Type":"Pass","End":true}}}
],"End":true}}}
""", "{\"items\":[1,2]}");
assertEquals("SUCCEEDED", status(history), typesOf(history).toString());
assertEquals(20, history.size(), typesOf(history).toString());
assertIdsAreConsecutive(history);
var parallelStarted = eventOfType(history, "ParallelStateStarted");
var mapEntered = eventOfType(history, "MapStateEntered");
var mapStarted = eventOfType(history, "MapStateStarted");
var mapSucceeded = eventOfType(history, "MapStateSucceeded");
var mapExited = eventOfType(history, "MapStateExited");
assertEquals(parallelStarted.getId(), mapEntered.getPreviousEventId());
assertEquals(parallelStarted.getId(), stateEvent(history, "PassStateEntered", "B1").getPreviousEventId());
assertEquals(mapEntered.getId(), mapStarted.getPreviousEventId());
for (int index = 0; index < 2; index++) {
assertEquals(mapStarted.getId(), iterationEvent(history, "MapIterationStarted", index).getPreviousEventId());
}
long lastIterationEvent = Math.max(iterationEvent(history, "MapIterationSucceeded", 0).getId(),
iterationEvent(history, "MapIterationSucceeded", 1).getId());
assertEquals(lastIterationEvent, mapSucceeded.getPreviousEventId());
assertEquals(lastIterationEvent, mapExited.getPreviousEventId());
var parallelExited = eventOfType(history, "ParallelStateExited");
long lastBranchEvent = Math.max(mapExited.getId(), stateEvent(history, "PassStateExited", "B1").getId());
assertEquals(lastBranchEvent, eventOfType(history, "ParallelStateSucceeded").getPreviousEventId());
assertEquals(lastBranchEvent, parallelExited.getPreviousEventId());
assertEquals("ExecutionSucceeded", history.get(19).getType());
}
@Test
void jsonataFailureRecordsAnEvaluationFailedEventPerAttempt() {
var history = run("""
{"QueryLanguage":"JSONata","StartAt":"Send","States":{
"Send":{"Type":"Task","Resource":"arn:aws:states:::sqs:sendMessage",
"Arguments":{"QueueUrl":"https://sqs.us-east-1.amazonaws.com/000000000000/q","MessageBody":"{% $states.input.missing %}"},
"Retry":[{"ErrorEquals":["States.ALL"],"MaxAttempts":1,"IntervalSeconds":0}],"End":true}}}
""", "{\"x\":\"a\"}");
assertEquals(List.of("ExecutionStarted", "TaskStateEntered", "EvaluationFailed", "EvaluationFailed",
"ExecutionFailed"), typesOf(history));
assertEquals(List.of(0L, 0L, 2L, 3L, 4L), previousEventIdsOf(history));
var cause = "An error occurred while executing the state 'Send' (entered at the event id #2). "
+ "The JSONata expression '$states.input.missing' specified for the field 'Arguments/MessageBody' "
+ "returned nothing (undefined).";
var expected = Map.of("error", "States.QueryEvaluationError", "cause", cause,
"location", "Arguments/MessageBody", "state", "Send");
assertEquals(expected, history.get(2).getDetails());
assertEquals(expected, history.get(3).getDetails());
assertEquals(Map.of("error", "States.QueryEvaluationError", "cause", cause), history.get(4).getDetails());
}
@Test
void mapItemsExpressionFailureIsRecordedBeforeTheMapStarts() {
var history = run("""
{"QueryLanguage":"JSONata","StartAt":"Fan","States":{
"Fan":{"Type":"Map","Items":"{% $states.input.missing %}",
"ItemProcessor":{"ProcessorConfig":{"Mode":"INLINE"},"StartAt":"I","States":{"I":{"Type":"Pass","End":true}}},
"End":true}}}
""", "{\"x\":\"a\"}");
assertEquals(List.of("ExecutionStarted", "MapStateEntered", "EvaluationFailed", "MapStateFailed",
"ExecutionFailed"), typesOf(history));
assertEquals(List.of(0L, 0L, 2L, 3L, 4L), previousEventIdsOf(history));
assertEquals("Items", history.get(2).getDetails().get("location"));
}
/**
* A Catch clause whose own Output fails. AWS records the clause's EvaluationFailed from where the
* state stood before its first Failed event, then fails the state a second time.
*/
@Test
void catchClauseOutputFailureIsRecordedFromBeforeTheStateFailedEvent() {
var history = run("""
{"QueryLanguage":"JSONata","StartAt":"P","States":{
"P":{"Type":"Parallel","Branches":[
{"StartAt":"Boom","States":{"Boom":{"Type":"Fail","Error":"MyError","Cause":"my cause"}}}
],"Catch":[{"ErrorEquals":["Other"],"Next":"Done"},
{"ErrorEquals":["States.ALL"],"Output":{"v":"{% $states.input.missing %}"},"Next":"Done"}],
"End":true},
"Done":{"Type":"Pass","End":true}}}
""", "{\"x\":\"a\"}");
assertEquals(List.of("ExecutionStarted", "ParallelStateEntered", "ParallelStateStarted", "FailStateEntered",
"ParallelStateFailed", "EvaluationFailed", "ParallelStateFailed", "ExecutionFailed"), typesOf(history));
assertEquals(List.of(0L, 0L, 2L, 3L, 4L, 4L, 6L, 7L), previousEventIdsOf(history));
var cause = "An error occurred while executing the state 'P' (entered at the event id #2). "
+ "The JSONata expression '$states.input.missing' specified for the field 'Catch[1]/Output/v' "
+ "returned nothing (undefined).";
assertEquals(Map.of("error", "States.QueryEvaluationError", "cause", cause,
"location", "Catch[1]/Output/v", "state", "P"), history.get(5).getDetails());
assertEquals(Map.of("error", "States.QueryEvaluationError", "cause", cause), history.get(7).getDetails());
}
@Test
void choiceWithNoMatchingRuleAndNoDefaultFailsAsAwsDoes() {
var history = run("""
{"StartAt":"C","States":{
"C":{"Type":"Choice","Choices":[{"Variable":"$.x","StringEquals":"never","Next":"Done"}]},
"Done":{"Type":"Pass","End":true}}}
""", "{\"x\":\"a\"}");
assertEquals(List.of("ExecutionStarted", "ChoiceStateEntered", "ExecutionFailed"), typesOf(history));
assertEquals(Map.of("error", "States.Runtime",
"cause", "An error occurred while executing the state 'C' (entered at the event id #2). "
+ "Failed to transition out of the state. The state does not point to a next state."),
history.get(2).getDetails());
}
@Test
void catchInsideABranchTakesItsNextEvenOnAnEndState() {
var mocks = new MockedTestCase("branch-history-test", "Case", Map.of("Send", List.of(
new MockedResponseStep(0, 0, null, "MyError", "boom"))));
var history = run("""
{"StartAt":"P","States":{
"P":{"Type":"Parallel","Branches":[
{"StartAt":"Send","States":{
"Send":{"Type":"Task","Resource":"arn:aws:states:::sqs:sendMessage",
"Parameters":{"QueueUrl":"https://sqs.us-east-1.amazonaws.com/000000000000/q","MessageBody":"hi"},
"Catch":[{"ErrorEquals":["States.ALL"],"Next":"Recover"}],"End":true},
"Recover":{"Type":"Pass","Result":{"recovered":true},"End":true}}}
],"End":true}}}
""", "{}", mocks);
assertEquals("SUCCEEDED", status(history), typesOf(history).toString());
assertEquals("[{\"recovered\":true}]", eventOfType(history, "ExecutionSucceeded").getDetails().get("output"));
assertFalse(typesOf(history).contains("TaskStateAborted"));
}
private static String status(List<HistoryEvent> history) {
var last = history.get(history.size() - 1).getType();
return switch (last) {
case "ExecutionSucceeded" -> "SUCCEEDED";
case "ExecutionFailed" -> "FAILED";
default -> last;
};
}
private static List<String> typesOf(List<HistoryEvent> history) {
return history.stream().map(HistoryEvent::getType).toList();
}
private static List<Long> previousEventIdsOf(List<HistoryEvent> history) {
return history.stream().map(HistoryEvent::getPreviousEventId).toList();
}
private static void assertIdsAreConsecutive(List<HistoryEvent> history) {
for (var i = 0; i < history.size(); i++) {
assertEquals(i + 1L, history.get(i).getId(), "unexpected id at index " + i);
}
var referenced = history.stream().map(HistoryEvent::getPreviousEventId).collect(Collectors.toSet());
referenced.remove(0L);
assertTrue(referenced.stream().allMatch(id -> id < history.size()),
"previousEventId points past the history: " + Set.copyOf(referenced));
}
private static HistoryEvent eventOfType(List<HistoryEvent> history, String type) {
return history.stream()
.filter(event -> type.equals(event.getType()))
.findFirst()
.orElseThrow(() -> new AssertionError("history has no " + type + " event: " + typesOf(history)));
}
private static HistoryEvent stateEvent(List<HistoryEvent> history, String type, String name) {
return history.stream()
.filter(event -> type.equals(event.getType()) && name.equals(event.getDetails().get("name")))
.findFirst()
.orElseThrow(() -> new AssertionError("history has no " + type + " for " + name + ": " + typesOf(history)));
}
private static HistoryEvent stateEventWithInput(List<HistoryEvent> history, String type, String name, String input) {
return history.stream()
.filter(event -> type.equals(event.getType()) && name.equals(event.getDetails().get("name"))
&& input.equals(event.getDetails().get("input")))
.findFirst()
.orElseThrow(() -> new AssertionError("history has no " + type + " for " + name + " with input "
+ input + ": " + typesOf(history)));
}
private static HistoryEvent stateEventWithOutput(List<HistoryEvent> history, String type, String name, String output) {
return history.stream()
.filter(event -> type.equals(event.getType()) && name.equals(event.getDetails().get("name"))
&& output.equals(event.getDetails().get("output")))
.findFirst()
.orElseThrow(() -> new AssertionError("history has no " + type + " for " + name + " with output "
+ output + ": " + typesOf(history)));
}
private static HistoryEvent iterationEvent(List<HistoryEvent> history, String type, int index) {
return history.stream()
.filter(event -> type.equals(event.getType()) && Integer.valueOf(index).equals(event.getDetails().get("index")))
.findFirst()
.orElseThrow(() -> new AssertionError("history has no " + type + " for index " + index + ": " + typesOf(history)));
}
private List<HistoryEvent> run(String definition, String input) {
return run(definition, input, null);
}
/** Runs the definition the way StartExecution does: the history already holds ExecutionStarted as event 1. */
private List<HistoryEvent> run(String definition, String input, MockedTestCase mocks) {
var stateMachine = new StateMachine();
stateMachine.setName("branch-history-test");
stateMachine.setStateMachineArn("arn:aws:states:%s:%s:stateMachine:branch-history-test".formatted(REGION, ACCOUNT));
stateMachine.setRoleArn("arn:aws:iam::%s:role/test-role".formatted(ACCOUNT));
stateMachine.setDefinition(definition);
var execution = new Execution();
execution.setName("branch-history-execution");
execution.setExecutionArn(
"arn:aws:states:%s:%s:execution:branch-history-test:branch-history-execution".formatted(REGION, ACCOUNT));
execution.setStateMachineArn(stateMachine.getStateMachineArn());
execution.setInput(input);
var history = new ArrayList<HistoryEvent>();
var started = new HistoryEvent();
started.setId(1L);
started.setPreviousEventId(0L);
started.setType("ExecutionStarted");
started.setDetails(Map.of("input", input, "inputDetails", Map.of("truncated", false)));
history.add(started);
executor.executeSync(stateMachine, execution, history, mocks, (updated, events) -> {
});
return history;
}
}
@@ -29,6 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Guards the bound AWS puts on a running execution: a state machine that never reaches a terminal
@@ -183,6 +184,8 @@ class AslExecutorHistoryEventLimitTest {
@BeforeEach
void setUp() {
Instance<StepFunctionsService> sfnService = mock(Instance.class);
when(sfnService.get()).thenReturn(mock(StepFunctionsService.class));
executor = new AslExecutor(
mock(LambdaExecutorService.class),
mock(LambdaFunctionStore.class),
@@ -199,7 +202,7 @@ class AslExecutorHistoryEventLimitTest {
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
objectMapper,
new JsonataEvaluator(objectMapper),
mock(Instance.class), mock(EmulatorConfig.class), vertx, null);
sfnService, mock(EmulatorConfig.class), vertx, null);
}
@Test
@@ -238,17 +241,20 @@ class AslExecutorHistoryEventLimitTest {
}
/**
* The branch produced the events that ran the execution out of them, and floci publishes none
* of them. What the caller reads back is the four events the top-level flow did produce, ending
* in the failure: an unbroken chain, not four events numbered as if 25,000 had happened.
* The branch produced the events that ran the execution out of them, and they are published
* into the execution's history like any other: what the caller reads back is one history,
* numbered without a gap and ending in the failure.
*/
@Test
void aParallelBranchLeavesThePublishedHistoryUnbroken() {
run(RUNAWAY_PARALLEL_BRANCH);
assertEquals(List.of("PassStateEntered", "PassStateExited", "ParallelStateEntered",
"ExecutionFailed"),
history.stream().map(HistoryEvent::getType).toList());
"ParallelStateStarted", "ChoiceStateEntered"),
history.subList(0, 5).stream().map(HistoryEvent::getType).toList());
HistoryEvent last = history.get(history.size() - 1);
assertEquals("ExecutionFailed", last.getType());
assertEquals(25_000, history.size());
for (int index = 0; index < history.size(); index++) {
assertEquals(index + 1L, history.get(index).getId(), "unexpected id at index " + index);
assertEquals((long) index, history.get(index).getPreviousEventId(),
@@ -14,6 +14,7 @@ import org.junit.jupiter.api.Test;
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.mockito.Mockito.mock;
/**
@@ -164,6 +165,14 @@ class AslExecutorIntrinsicMissingArgumentTest {
+ "input '{\"items\":[1,2]}'", failure.cause);
}
/** The plain form of the same path is not a miss. AWS resolves it to null and the execution succeeds. */
@Test
void plainReferencePastTheEndOfAnArrayResolvesToNull() throws Exception {
var resolved = resolve("{\"v.$\":\"$.items[5]\"}", "{\"items\":[1,2]}");
assertTrue(resolved.path("v").isNull());
}
/** Reading a field off the absent element fails alike. */
@Test
void navigatingPastAnOutOfRangeIndexFails() throws Exception {
@@ -281,6 +281,7 @@ class AslExecutorTaskHistoryEventsTest {
"Iterate": {
"Type": "Map",
"ItemsPath": "$[0].items",
"MaxConcurrency": 1,
"ItemProcessor": {
"StartAt": "ItemStep",
"States": {"ItemStep": {"Type": "Pass", "End": true}}
@@ -293,10 +294,23 @@ class AslExecutorTaskHistoryEventsTest {
assertEquals("SUCCEEDED", execution.getStatus(), "history: " + typesOf(history));
assertEquals(
List.of("ParallelStateEntered", "ParallelStateExited",
"MapStateEntered", "MapStateExited", "ExecutionSucceeded"),
List.of("ParallelStateEntered", "ParallelStateStarted",
"PassStateEntered", "PassStateExited", "PassStateEntered", "PassStateExited",
"ParallelStateSucceeded", "ParallelStateExited",
"MapStateEntered", "MapStateStarted",
"MapIterationStarted", "PassStateEntered", "PassStateExited", "MapIterationSucceeded",
"MapIterationStarted", "PassStateEntered", "PassStateExited", "MapIterationSucceeded",
"MapStateSucceeded", "MapStateExited", "ExecutionSucceeded"),
typesOf(history));
assertChain(history);
// The branch and the iterations chain to the Started event that opened them, and a
// Succeeded event is passed by: the Exited event after it points where it pointed.
assertEquals(
List.of(0L, 1L, 2L, 3L, 4L, 5L, 6L, 6L,
8L, 9L, 10L, 11L, 12L, 13L, 10L, 15L, 16L, 17L, 18L, 18L, 20L),
history.stream().map(HistoryEvent::getPreviousEventId).toList());
for (var i = 0; i < history.size(); i++) {
assertEquals(i + 1L, history.get(i).getId(), "unexpected id at index " + i);
}
}
private static List<String> typesOf(List<HistoryEvent> history) {
@@ -0,0 +1,48 @@
package io.github.hectorvent.floci.services.stepfunctions;
import io.github.hectorvent.floci.services.stepfunctions.model.HistoryEvent;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
class HistoryChainTest {
/** The history-event limit of AslExecutor. A counted event past it fails the execution. */
private static final int MAX_HISTORY_EVENTS = 25_000;
@Test
void publishingAfterTheExecutionEndedRecordsNothingAndDoesNotCountTowardsTheLimit() {
List<HistoryEvent> history = new ArrayList<>();
var chain = HistoryChain.of(history);
chain.end("ExecutionSucceeded", Map.of());
assertDoesNotThrow(() -> {
for (var i = 0; i < MAX_HISTORY_EVENTS; i++) {
assertEquals(0L, chain.publish("PassStateEntered", null));
chain.publishAside("PassStateSucceeded", null);
}
});
assertEquals(1, history.size());
}
@Test
void publishingIntoAHistorySealedByStopExecutionStopsCountingAsWell() {
var history = new StepFunctionsService.ExecutionHistory();
var chain = HistoryChain.of(history);
var branch = chain.fork();
history.sealWith("ExecutionAborted", Map.of());
assertDoesNotThrow(() -> {
for (var i = 0; i < MAX_HISTORY_EVENTS; i++) {
assertEquals(0L, chain.publish("PassStateEntered", null));
assertEquals(0L, branch.publish("PassStateEntered", null));
}
});
assertEquals(1, history.size());
}
}
@@ -22,8 +22,8 @@ import static org.junit.jupiter.api.Assertions.fail;
* the {@code arn:aws:states:::aws-sdk:sfn:describeMapRun} Task integration.
*
* <p>Every asserted value was measured against us-east-1 with a distributed Map run of the same
* shape. A Map run only becomes describable once its {@code ResultWriter} has minted the Map run
* ARN and returned it in the Map result, which is also the only way an ASL author obtains it.
* shape. Every run is describable through the {@code mapRunArn} of its {@code MapRunStarted}
* event. A run with a {@code ResultWriter} also returns that ARN in the Map result.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@@ -240,6 +240,44 @@ class StepFunctionsDescribeMapRunIntegrationTest {
assertEquals(0, response.jsonPath().getInt(set + ".pendingRedrive"));
}
@Test
@Order(10)
void describeMapRunResolvesTheArnOfAMapWithoutResultWriter() throws Exception {
var smArn = createStateMachine("describe-map-run-no-writer", distributedMapWithoutWriter(
"[1, 2]", "Keep", "{\"Keep\": {\"Type\": \"Pass\", \"End\": true}}"));
var execArn = startExecution(smArn, "{}");
var describe = waitForTerminalState(execArn);
assertEquals("SUCCEEDED", describe.jsonPath().getString("status"),
"cause: " + describe.jsonPath().getString("cause"));
var mapRunArn = mapRunArnFromHistory(execArn);
var response = describeMapRun(mapRunArn);
response.then().statusCode(200);
assertEquals(mapRunArn, response.jsonPath().getString("mapRunArn"));
assertEquals(execArn, response.jsonPath().getString("executionArn"));
assertEquals("SUCCEEDED", response.jsonPath().getString("status"));
assertCounters(response, "itemCounts", 2);
assertCounters(response, "executionCounts", 2);
}
@Test
@Order(11)
void describeMapRunReportsARunWhoseItemFailed() throws Exception {
var smArn = createStateMachine("describe-map-run-failed", distributedMapWithoutWriter(
"[1]", "Boom", "{\"Boom\": {\"Type\": \"Fail\", \"Error\": \"Boom\", \"Cause\": \"item failed\"}}"));
var execArn = startExecution(smArn, "{}");
assertEquals("FAILED", waitForTerminalState(execArn).jsonPath().getString("status"));
var response = describeMapRun(mapRunArnFromHistory(execArn));
response.then().statusCode(200);
assertEquals("FAILED", response.jsonPath().getString("status"));
assertEquals(0, response.jsonPath().getInt("itemCounts.succeeded"));
assertEquals(1, response.jsonPath().getInt("itemCounts.failed"));
assertEquals(0, response.jsonPath().getInt("itemCounts.aborted"));
assertEquals(1, response.jsonPath().getInt("itemCounts.total"));
assertEquals(1, response.jsonPath().getInt("itemCounts.resultsWritten"));
}
private static void assertTaskCounters(JsonNode counts, int items) {
assertEquals(0, counts.path("Pending").asInt());
assertEquals(0, counts.path("Running").asInt());
@@ -284,6 +322,44 @@ class StepFunctionsDescribeMapRunIntegrationTest {
.replace("BUCKET", bucket);
}
private static String distributedMapWithoutWriter(String items, String startAt, String states) {
return """
{
"QueryLanguage": "JSONata",
"StartAt": "Fan",
"States": {
"Fan": {
"Type": "Map",
"End": true,
"Items": ITEMS,
"ItemProcessor": {
"ProcessorConfig": {"Mode": "DISTRIBUTED", "ExecutionType": "STANDARD"},
"StartAt": "START_AT",
"States": STATES
}
}
}
}
""".replace("ITEMS", items).replace("START_AT", startAt).replace("STATES", states);
}
private static String mapRunArnFromHistory(String execArn) throws Exception {
var history = given()
.header("X-Amz-Target", "AWSStepFunctions.GetExecutionHistory")
.contentType(SFN_CONTENT_TYPE)
.body("""
{"executionArn": "%s"}
""".formatted(execArn))
.when().post("/");
history.then().statusCode(200);
for (JsonNode event : mapper.readTree(history.asString()).path("events")) {
if ("MapRunStarted".equals(event.path("type").asText())) {
return event.path("mapRunStartedEventDetails").path("mapRunArn").asText();
}
}
return fail("no MapRunStarted event in the history of " + execArn);
}
private static Response describeMapRun(String mapRunArn) {
return given()
.header("X-Amz-Target", "AWSStepFunctions.DescribeMapRun")
@@ -220,6 +220,136 @@ class StepFunctionsExecutionHistoryIntegrationTest {
}
}
/**
* The events of the states inside a Parallel branch and a Map iteration reach the caller through
* GetExecutionHistory under the details field the SDK names for each event type. Shapes read
* off real Step Functions in us-east-1 for issue #2868.
*/
@Test
void getExecutionHistory_publishesParallelBranchAndMapIterationEvents() throws Exception {
String definition = """
{
"StartAt": "P",
"States": {
"P": {
"Type": "Parallel",
"Branches": [
{"StartAt": "A1", "States": {"A1": {"Type": "Pass", "End": true}}}
],
"Next": "M"
},
"M": {
"Type": "Map",
"ItemsPath": "$[0].items",
"MaxConcurrency": 1,
"ItemProcessor": {
"ProcessorConfig": {"Mode": "INLINE"},
"StartAt": "I1",
"States": {"I1": {"Type": "Pass", "End": true}}
},
"End": true
}
}
}
""";
String stateMachineArn = createStateMachine("execution-history-branches-test", definition);
String executionArn = startExecution(stateMachineArn, "{\"items\": [1, 2]}");
waitForExecution(executionArn);
var events = MAPPER.readTree(getExecutionHistory(executionArn).body().asString()).path("events");
var types = new ArrayList<String>();
events.forEach(event -> types.add(event.path("type").asText()));
assertEquals(List.of("ExecutionStarted", "ParallelStateEntered", "ParallelStateStarted",
"PassStateEntered", "PassStateExited", "ParallelStateSucceeded", "ParallelStateExited",
"MapStateEntered", "MapStateStarted",
"MapIterationStarted", "PassStateEntered", "PassStateExited", "MapIterationSucceeded",
"MapIterationStarted", "PassStateEntered", "PassStateExited", "MapIterationSucceeded",
"MapStateSucceeded", "MapStateExited", "ExecutionSucceeded"), types);
var expectedPreviousEventIds = List.of(0L, 0L, 2L, 3L, 4L, 5L, 5L, 7L, 8L, 9L, 10L, 11L, 12L,
9L, 14L, 15L, 16L, 17L, 17L, 19L);
for (var i = 0; i < events.size(); i++) {
assertEquals(i + 1L, events.get(i).path("id").asLong());
assertEquals(expectedPreviousEventIds.get(i), events.get(i).path("previousEventId").asLong(),
"previousEventId of event " + (i + 1) + " in " + events);
}
assertFalse(events.get(2).has("parallelStateStartedEventDetails"));
assertEquals(2, events.get(8).path("mapStateStartedEventDetails").path("length").asInt());
assertEquals("M", events.get(9).path("mapIterationStartedEventDetails").path("name").asText());
assertEquals(0, events.get(9).path("mapIterationStartedEventDetails").path("index").asInt());
assertEquals("M", events.get(16).path("mapIterationSucceededEventDetails").path("name").asText());
assertEquals(1, events.get(16).path("mapIterationSucceededEventDetails").path("index").asInt());
assertEquals("[1,2]", events.get(18).path("stateExitedEventDetails").path("output").asText());
}
/** The shape reported in issue #2868, verified against us-east-1. */
@Test
void getExecutionHistory_namesTheBranchStateAFailureBelongsTo() throws Exception {
String definition = """
{
"StartAt": "P",
"States": {
"P": {
"Type": "Parallel",
"Branches": [
{"StartAt": "Fast", "States": {"Fast": {"Type": "Pass", "Parameters": {"m.$": "$.nope"}, "End": true}}}
],
"End": true
}
}
}
""";
String stateMachineArn = createStateMachine("execution-history-branch-failure-test", definition);
String executionArn = startExecution(stateMachineArn, "{\"x\": \"a\"}");
var cause = "An error occurred while executing the state 'Fast' (entered at the event id #4). "
+ "The JSONPath '$.nope' specified for the field 'm.$' could not be found in the input '{\"x\":\"a\"}'";
await().atMost(Duration.ofSeconds(5)).pollInterval(Duration.ofMillis(100)).untilAsserted(() -> {
var described = describeExecution(executionArn);
assertEquals("FAILED", described.jsonPath().getString("status"), described.body().asString());
assertEquals("States.Runtime", described.jsonPath().getString("error"));
assertEquals(cause, described.jsonPath().getString("cause"));
});
var events = MAPPER.readTree(getExecutionHistory(executionArn).body().asString()).path("events");
var types = new ArrayList<String>();
events.forEach(event -> types.add(event.path("type").asText()));
assertEquals(List.of("ExecutionStarted", "ParallelStateEntered", "ParallelStateStarted",
"PassStateEntered", "ExecutionFailed"), types);
assertEquals("Fast", events.get(3).path("stateEnteredEventDetails").path("name").asText());
assertEquals(cause, events.get(4).path("executionFailedEventDetails").path("cause").asText());
assertEquals(4L, events.get(4).path("previousEventId").asLong());
}
private Response getExecutionHistory(String executionArn) {
Response response = given()
.header("X-Amz-Target", "AWSStepFunctions.GetExecutionHistory")
.contentType(SFN_CONTENT_TYPE)
.body(String.format("""
{
"executionArn": "%s",
"includeExecutionData": true
}
""", executionArn))
.when()
.post("/");
response.then().statusCode(200);
return response;
}
private Response describeExecution(String executionArn) {
Response response = given()
.header("X-Amz-Target", "AWSStepFunctions.DescribeExecution")
.contentType(SFN_CONTENT_TYPE)
.body(String.format("""
{ "executionArn": "%s" }
""", executionArn))
.when()
.post("/");
response.then().statusCode(200);
return response;
}
private static String createQueue(String queueName) {
var response = given()
.header("X-Amz-Target", "AmazonSQS.CreateQueue")
@@ -278,6 +408,22 @@ class StepFunctionsExecutionHistoryIntegrationTest {
return response.jsonPath().getString("executionArn");
}
private String startExecution(String stateMachineArn, String input) {
Response response = given()
.header("X-Amz-Target", "AWSStepFunctions.StartExecution")
.contentType(SFN_CONTENT_TYPE)
.body(String.format("""
{
"stateMachineArn": "%s",
"input": %s
}
""", stateMachineArn, quote(input)))
.when()
.post("/");
response.then().statusCode(200);
return response.jsonPath().getString("executionArn");
}
private void waitForExecution(String executionArn) {
await()
.atMost(Duration.ofSeconds(5))
@@ -39,7 +39,8 @@ class StepFunctionsIntrinsicMissingArgumentIntegrationTest {
assertEquals("FAILED", describe.jsonPath().getString("status"), describe.body().asString());
assertEquals("States.Runtime", describe.jsonPath().getString("error"));
assertEquals("The function 'States.Format('{}', $.nope)' had the following error: "
assertEquals("An error occurred while executing the state 'Pick' (entered at the event id #2). "
+ "The function 'States.Format('{}', $.nope)' had the following error: "
+ "The JsonPath argument for the field '$.nope' could not be found in the input "
+ "'{\"other\":1}'",
describe.jsonPath().getString("cause"));
@@ -58,7 +59,8 @@ class StepFunctionsIntrinsicMissingArgumentIntegrationTest {
var describe = run("nested-intrinsic", definition, "{\"other\":1}");
assertEquals("FAILED", describe.jsonPath().getString("status"), describe.body().asString());
assertEquals("The function 'States.Format('{}', States.Format('{}', $.nope))' had the "
assertEquals("An error occurred while executing the state 'Pick' (entered at the event id #2). "
+ "The function 'States.Format('{}', States.Format('{}', $.nope))' had the "
+ "following error: The JsonPath argument for the field '$.nope' could not be "
+ "found in the input '{\"other\":1}'",
describe.jsonPath().getString("cause"));
@@ -79,7 +81,8 @@ class StepFunctionsIntrinsicMissingArgumentIntegrationTest {
var describe = run("intrinsic-index-out-of-range", definition, "{\"items\":[1,2]}");
assertEquals("FAILED", describe.jsonPath().getString("status"), describe.body().asString());
assertEquals("The function 'States.Format('{}', $.items[5])' had the following error: "
assertEquals("An error occurred while executing the state 'Pick' (entered at the event id #2). "
+ "The function 'States.Format('{}', $.items[5])' had the following error: "
+ "The JsonPath argument for the field '$.items[5]' could not be found in the "
+ "input '{\"items\":[1,2]}'",
describe.jsonPath().getString("cause"));
@@ -101,7 +104,8 @@ class StepFunctionsIntrinsicMissingArgumentIntegrationTest {
assertEquals("FAILED", describe.jsonPath().getString("status"), describe.body().asString());
assertEquals("States.Runtime", describe.jsonPath().getString("error"));
assertEquals("The function 'States.Format('{}', $.nope)' had the following error: "
assertEquals("An error occurred while executing the state 'M' (entered at the event id #2). "
+ "The function 'States.Format('{}', $.nope)' had the following error: "
+ "The JsonPath argument for the field '$.nope' could not be found in the input "
+ "'{\"items\":[1,2]}'",
describe.jsonPath().getString("cause"));
@@ -247,7 +247,8 @@ class StepFunctionsJsonataFunctionsIntegrationTest {
Response resp = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", resp.jsonPath().getString("error"));
assertEquals("The JSONata expression '$sum(['a'])' specified for the field 'Output/v' threw an error "
assertEquals("An error occurred while executing the state 'Sum' (entered at the event id #2). "
+ "The JSONata expression '$sum(['a'])' specified for the field 'Output/v' threw an error "
+ "during evaluation. T0412: Argument [\"a\"] must be an array of \"numbers\"",
resp.jsonPath().getString("cause"));
}
@@ -277,7 +278,8 @@ class StepFunctionsJsonataFunctionsIntegrationTest {
Response resp = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", resp.jsonPath().getString("error"));
assertEquals("The JSONata expression '$abs(\"x\")' specified for the field 'Output/v' threw an error "
assertEquals("An error occurred while executing the state 'Abs' (entered at the event id #2). "
+ "The JSONata expression '$abs(\"x\")' specified for the field 'Output/v' threw an error "
+ "during evaluation. T0410: Argument 1 of function \"abs\" does not match function signature",
resp.jsonPath().getString("cause"));
}
@@ -619,7 +619,8 @@ class StepFunctionsJsonataIntegrationTest {
assertEquals("FAILED", failure.jsonPath().getString("status"));
assertEquals("States.ItemReaderFailed", failure.jsonPath().getString("error"));
assertEquals("The provided ReaderConfig.ItemsPointer does not match any valid path in the JSON structure.",
assertEquals("An error occurred while executing the state 'ProcessWorkers' (entered at the event id #2). "
+ "The provided ReaderConfig.ItemsPointer does not match any valid path in the JSON structure.",
failure.jsonPath().getString("cause"));
}
@@ -672,7 +673,8 @@ class StepFunctionsJsonataIntegrationTest {
assertEquals("FAILED", failure.jsonPath().getString("status"));
assertEquals("States.ItemReaderFailed", failure.jsonPath().getString("error"));
assertEquals("Attempting to map over non-iterable node.", failure.jsonPath().getString("cause"));
assertEquals("An error occurred while executing the state 'ProcessWorkers' (entered at the event id #2). "
+ "Attempting to map over non-iterable node.", failure.jsonPath().getString("cause"));
}
@Test
@@ -770,7 +772,8 @@ class StepFunctionsJsonataIntegrationTest {
assertEquals("FAILED", failure.jsonPath().getString("status"));
assertEquals("States.Runtime", failure.jsonPath().getString("error"));
assertEquals("The ItemReader, ItemBatcher and ResultWriter fields are not supported for INLINE maps",
assertEquals("An error occurred while executing the state 'ProcessWorkers' (entered at the event id #2). "
+ "The ItemReader, ItemBatcher and ResultWriter fields are not supported for INLINE maps",
failure.jsonPath().getString("cause"));
}
@@ -1295,7 +1298,8 @@ class StepFunctionsJsonataIntegrationTest {
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Output/v' "
assertEquals("An error occurred while executing the state 'Transform' (entered at the event id #2). "
+ "The JSONata expression '$states.input.missing' specified for the field 'Output/v' "
+ "returned nothing (undefined).", failure.jsonPath().getString("cause"));
String catching = definition.replace("\"End\": true",
@@ -1390,7 +1394,8 @@ class StepFunctionsJsonataIntegrationTest {
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Assign/x' "
assertEquals("An error occurred while executing the state 'Bind' (entered at the event id #2). "
+ "The JSONata expression '$states.input.missing' specified for the field 'Assign/x' "
+ "returned nothing (undefined).", failure.jsonPath().getString("cause"));
}
@@ -1421,7 +1426,8 @@ class StepFunctionsJsonataIntegrationTest {
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field "
assertEquals("An error occurred while executing the state 'Send' (entered at the event id #2). "
+ "The JSONata expression '$states.input.missing' specified for the field "
+ "'Arguments/MessageGroupId' returned nothing (undefined).",
failure.jsonPath().getString("cause"));
}
@@ -1454,7 +1460,8 @@ class StepFunctionsJsonataIntegrationTest {
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field "
assertEquals("An error occurred while executing the state 'Pick' (entered at the event id #2). "
+ "The JSONata expression '$states.input.missing' specified for the field "
+ "'Choices[1]/Condition' returned nothing (undefined).", failure.jsonPath().getString("cause"));
}
@@ -1516,7 +1523,8 @@ class StepFunctionsJsonataIntegrationTest {
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field "
assertEquals("An error occurred while executing the state 'Pick' (entered at the event id #2). "
+ "The JSONata expression '$states.input.missing' specified for the field "
+ "'Choices[1]/Output/v' returned nothing (undefined).", failure.jsonPath().getString("cause"));
}
@@ -1546,7 +1554,8 @@ class StepFunctionsJsonataIntegrationTest {
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field "
assertEquals("An error occurred while executing the state 'Pick' (entered at the event id #2). "
+ "The JSONata expression '$states.input.missing' specified for the field "
+ "'Choices[0]/Assign/x' returned nothing (undefined).", failure.jsonPath().getString("cause"));
}
@@ -1586,7 +1595,8 @@ class StepFunctionsJsonataIntegrationTest {
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field "
assertEquals("An error occurred while executing the state 'Boom' (entered at the event id #2). "
+ "The JSONata expression '$states.input.missing' specified for the field "
+ "'Catch[1]/Output/v' returned nothing (undefined).", failure.jsonPath().getString("cause"));
}
@@ -1608,7 +1618,8 @@ class StepFunctionsJsonataIntegrationTest {
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Seconds' "
assertEquals("An error occurred while executing the state 'Pause' (entered at the event id #2). "
+ "The JSONata expression '$states.input.missing' specified for the field 'Seconds' "
+ "returned nothing (undefined).", failure.jsonPath().getString("cause"));
}
@@ -1631,14 +1642,16 @@ class StepFunctionsJsonataIntegrationTest {
createStateMachine("jsonata-fail-error-returned-nothing-test",
definition.formatted("{% $states.input.missing %}", "boom")), "{}"));
assertEquals("States.QueryEvaluationError", errorFailure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Error' "
assertEquals("An error occurred while executing the state 'Stop' (entered at the event id #2). "
+ "The JSONata expression '$states.input.missing' specified for the field 'Error' "
+ "returned nothing (undefined).", errorFailure.jsonPath().getString("cause"));
Response causeFailure = waitForExecutionFailure(startExecution(
createStateMachine("jsonata-fail-cause-returned-nothing-test",
definition.formatted("Boom", "{% $states.input.missing %}")), "{}"));
assertEquals("States.QueryEvaluationError", causeFailure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Cause' "
assertEquals("An error occurred while executing the state 'Stop' (entered at the event id #2). "
+ "The JSONata expression '$states.input.missing' specified for the field 'Cause' "
+ "returned nothing (undefined).", causeFailure.jsonPath().getString("cause"));
}
@@ -1667,7 +1680,8 @@ class StepFunctionsJsonataIntegrationTest {
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Items' "
assertEquals("An error occurred while executing the state 'Fan' (entered at the event id #2). "
+ "The JSONata expression '$states.input.missing' specified for the field 'Items' "
+ "returned nothing (undefined).", failure.jsonPath().getString("cause"));
}
@@ -1698,7 +1712,8 @@ class StepFunctionsJsonataIntegrationTest {
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field "
assertEquals("An error occurred while executing the state 'Fan' (entered at the event id #2). "
+ "The JSONata expression '$states.input.missing' specified for the field "
+ "'MaxConcurrency' returned nothing (undefined).", failure.jsonPath().getString("cause"));
}
@@ -1758,7 +1773,8 @@ class StepFunctionsJsonataIntegrationTest {
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Output' "
assertEquals("An error occurred while executing the state 'Transform' (entered at the event id #2). "
+ "The JSONata expression '$states.input.missing' specified for the field 'Output' "
+ "returned nothing (undefined).", failure.jsonPath().getString("cause"));
}
@@ -117,7 +117,9 @@ class StepFunctionsTimeoutSecondsIntegrationTest {
assertTrue(elapsedMillis < 3_000,
"the branch's 3-second Wait outlasted the 1-second budget: " + elapsedMillis + " ms");
JsonNode events = mapper.readTree(getExecutionHistory(execArn).body().asString()).path("events");
assertEquals(List.of("ExecutionStarted", "ParallelStateEntered", "ExecutionTimedOut"),
// The branch's Wait was entered and never exited: the budget cut it.
assertEquals(List.of("ExecutionStarted", "ParallelStateEntered", "ParallelStateStarted",
"WaitStateEntered", "ExecutionTimedOut"),
eventTypes(events), "history was " + events);
}
@@ -224,8 +226,14 @@ class StepFunctionsTimeoutSecondsIntegrationTest {
assertTrue(elapsedMillis < 5_000,
"the iterations' 10-second Wait outlasted the 1-second budget: " + elapsedMillis + " ms");
JsonNode events = mapper.readTree(getExecutionHistory(execArn).body().asString()).path("events");
assertEquals(List.of("ExecutionStarted", "MapStateEntered", "ExecutionTimedOut"),
eventTypes(events), "history was " + events);
// Both iterations entered their Wait and neither exited it. They run concurrently, so
// the order their events interleave in is theirs to choose.
List<String> types = eventTypes(events);
assertEquals(List.of("ExecutionStarted", "MapStateEntered", "MapStateStarted"), types.subList(0, 3),
"history was " + events);
assertEquals(List.of("MapIterationStarted", "MapIterationStarted", "WaitStateEntered", "WaitStateEntered"),
types.subList(3, 7).stream().sorted().toList(), "history was " + events);
assertEquals(List.of("ExecutionTimedOut"), types.subList(7, types.size()), "history was " + events);
}
@Test
@@ -259,7 +267,8 @@ class StepFunctionsTimeoutSecondsIntegrationTest {
assertTrue(elapsedMillis < 5_000,
"the single iteration's 10-second Wait outlasted the 1-second budget: " + elapsedMillis + " ms");
JsonNode events = mapper.readTree(getExecutionHistory(execArn).body().asString()).path("events");
assertEquals(List.of("ExecutionStarted", "MapStateEntered", "ExecutionTimedOut"),
assertEquals(List.of("ExecutionStarted", "MapStateEntered", "MapStateStarted", "MapIterationStarted",
"WaitStateEntered", "ExecutionTimedOut"),
eventTypes(events), "history was " + events);
}
@@ -38,7 +38,8 @@ class StepFunctionsUnresolvableJsonPathIntegrationTest {
assertEquals("FAILED", describe.jsonPath().getString("status"), describe.body().asString());
assertEquals("States.Runtime", describe.jsonPath().getString("error"));
assertEquals("The JSONPath '$.nope.deep' specified for the field 'missing.$' could not "
assertEquals("An error occurred while executing the state 'Pick' (entered at the event id #2). "
+ "The JSONPath '$.nope.deep' specified for the field 'missing.$' could not "
+ "be found in the input '{\"other\":1}'",
describe.jsonPath().getString("cause"));
}
@@ -92,7 +93,8 @@ class StepFunctionsUnresolvableJsonPathIntegrationTest {
assertEquals("FAILED", describe.jsonPath().getString("status"), describe.body().asString());
assertEquals("States.Runtime", describe.jsonPath().getString("error"));
assertEquals("The JSONPath '$.nope' specified for the field 'missing.$' could not be "
assertEquals("An error occurred while executing the state 'M' (entered at the event id #2). "
+ "The JSONPath '$.nope' specified for the field 'missing.$' could not be "
+ "found in the input '[1,2]'",
describe.jsonPath().getString("cause"));
}