Light, fluffy, and always free - The AWS Local Emulator alternative
fix(stepfunctions): stop a .sync job whenever its Task is cut, and record the cut state (#4660)
mitsukado-shinagawadc3beadf6a55
diff --git a/docs/services/step-functions.md b/docs/services/step-functions.mdindex 6466972280..186ca06eb4 100644--- a/docs/services/step-functions.md+++ b/docs/services/step-functions.md@@ -80,7 +80,10 @@ the parent execution's history, as on AWS. A `Parallel` records `ParallelStateSt`MapIterationStarted`, `MapIterationSucceeded`, `MapIterationFailed`, `MapStateSucceeded` and`MapStateFailed`. A Distributed `Map` records `MapRunStarted`, `MapRunSucceeded` and`MapRunFailed` instead. Its items are child executions and publish nothing into the parent-history. A `Task` whose failure ends its branch also records `TaskStateAborted`.+history. A `Task` whose failure ends its branch also records `TaskStateAborted`. When a failure+ends a `Parallel`, each other branch that is still inside a `Task` or a `Wait` records+`TaskStateAborted` or `WaitStateAborted`, chained to the failing branch's last event and recorded+before `ParallelStateFailed`.Branches and iterations run concurrently, so the order in which their events interleave differsfrom run to run. Each branch chains its own events through `previousEventId`, and that chain is@@ -263,7 +266,8 @@ When the `Task`'s own clock fires, the job it was waiting on is stopped the wayECS task reads `stopCode: UserInitiated`, the child execution reads `ABORTED` with no error, andboth carry the cause `The Task state in AWS Step Functions execution [<arn>] which was managingthis resource was aborted`. A `StopExecution` that lands while the state waits ends the wait and-stops the job with the same cause. When the execution's budget fires instead, the job is left running.+stops the job with the same cause, and so does the execution's budget, and a failure in another+`Parallel` branch that cuts the branch the `Task` is in.One deviation. AWS starts the `TimeoutSeconds` clock when a worker picks the task up, the instantit emits `ActivityStarted`. Floci emits `ActivityStarted` at schedule time, so both clocks startdiff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.javaindex 0107db00d2..7c4133eb95 100644--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java@@ -561,8 +561,21 @@ public class AslExecutor {StateMachine sm, String topLevelQueryLanguage, JsonNode context,ObjectNode variables, long executionDeadlineNanos) throws Exception {var type = stateDef.path("Type").asText();- var enteredEventId = chain.publish(stateEnteredEventType(type),+ long enteredEventId = chain.publishStateEntered(type, stateEnteredEventType(type),Map.of("name", name, "input", input.toString(), "inputDetails", Map.of("truncated", false)));+ try {+ return runEnteredState(chain, name, enteredEventId, type, stateDef, input, sm, topLevelQueryLanguage,+ context, variables, executionDeadlineNanos);+ } finally {+ // A state that ends by throwing publishes no Exited event, so the chain leaves it here.+ chain.leaveState();+ }+ }++ private StateResult runEnteredState(HistoryChain chain, String name, long enteredEventId, String type,+ JsonNode stateDef, JsonNode input, StateMachine sm,+ String topLevelQueryLanguage, JsonNode context, ObjectNode variables,+ long executionDeadlineNanos) throws Exception {updateStateContext(context, name);var jsonata = isJsonata(stateDef, topLevelQueryLanguage);StateResult result;@@ -589,12 +602,12 @@ public class AslExecutor {if (result == null) {if (chain.isBranch() && "Task".equals(type) && !failure.isRuntimeError()) {// AWS records this after TaskFailed when the failure ends the branch.- chain.publishAside("TaskStateAborted", null);+ chain.leaveStateAside("TaskStateAborted", null);}throw failure;}}- chain.publish(stateExitedEventType(type),+ chain.publishStateExited(stateExitedEventType(type),Map.of("name", name, "output", result.output().toString(),"outputDetails", Map.of("truncated", false)));return result;@@ -831,7 +844,8 @@ public class AslExecutor {// was sealed by the abort; nothing more is written about the state.throw e;} catch (InterruptedException e) {- // The task of a branch that was cut. AWS records nothing for it.+ // The task of a branch that was cut. The branch records nothing more; the Parallel+ // that cut it records its TaskStateAborted.throw e;} catch (Exception e) {var failure = e instanceof FailStateException f ? f : null;@@ -1703,16 +1717,16 @@ public class AslExecutor {return result;}- // .sync or .sync:2 polls until terminal, or until one of the two clocks runs out: the parent- // execution's TimeoutSeconds budget ends the parent as TIMED_OUT and leaves the child running;- // the Task's own TimeoutSeconds fails the state with States.Timeout and aborts the child, the- // way AWS does (measured: child ABORTED, no error, the cause below). A StopExecution on the- // parent ends the wait the same way, so a stopped execution does not keep a polling worker.+ // .sync or .sync:2 polls until terminal. Whatever else ends the wait aborts the child, the way+ // AWS does (measured: child ABORTED, no error, the cause below): the Task's own TimeoutSeconds,+ // which fails the state with States.Timeout; the parent execution's budget, which ends it+ // TIMED_OUT; a failure in a sibling Parallel branch, which interrupts this one; and a+ // StopExecution on the parent, so a stopped execution does not keep a polling worker.while (true) {try {sleepOrTimeOutTask(TimeUnit.MILLISECONDS.toNanos(SYNC_POLL_INTERVAL_MS),executionDeadlineNanos, taskDeadlineNanos);- } catch (TaskTimedOutException e) {+ } catch (TaskTimedOutException | ExecutionTimedOutException | InterruptedException e) {abortChildExecution(execArn, executionArn);throw e;}@@ -1839,15 +1853,16 @@ public class AslExecutor {// All tasks must be polled (not just the first): with Count > 1, a failure in any task must// fail the state, otherwise tasks beyond the first would run unmonitored. The wait is bounded// by the Task's TimeoutSeconds and by the execution's budget, never by a poll count of its own.- // The Task's clock also stops the tasks it launched, the way AWS does (measured: the ECS task- // reads stopCode UserInitiated with the cause below), and so does a StopExecution on the- // execution, which otherwise would leave this worker polling until a clock ran out.+ // Whatever ends the wait before the tasks stop also stops the tasks it launched, the way AWS+ // does (measured: the ECS task reads stopCode UserInitiated with the cause below): either+ // clock, a failure in a sibling Parallel branch, which interrupts this one, and a+ // StopExecution on the execution, which otherwise would leave this worker polling.List<String> taskArns = launched.stream().map(EcsTask::getTaskArn).toList();while (true) {try {sleepOrTimeOutTask(TimeUnit.MILLISECONDS.toNanos(SYNC_POLL_INTERVAL_MS),executionDeadlineNanos, taskDeadlineNanos);- } catch (TaskTimedOutException e) {+ } catch (TaskTimedOutException | ExecutionTimedOutException | InterruptedException e) {stopEcsTasks(cluster, taskArns, executionArn, region);throw e;}@@ -1882,8 +1897,8 @@ public class AslExecutor {}/**- * The reason AWS writes on a job it stops because the {@code .sync} Task waiting on it ran out- * of its {@code TimeoutSeconds}: verbatim, as the ECS task's {@code stoppedReason} and the child+ * The reason AWS writes on a job it stops because the {@code .sync} Task waiting on it ended+ * first, whichever way it ended: verbatim, as the ECS task's {@code stoppedReason} and the child* execution's {@code cause}.*/private static String syncAbortCause(String executionArn) {@@ -1891,24 +1906,24 @@ public class AslExecutor {+ "] which was managing this resource was aborted";}- /** Best effort, like AWS: a task that is already gone does not change the timeout being reported. */+ /** Best effort, like AWS: a task that is already gone does not change how the state ends. */private void stopEcsTasks(String cluster, List<String> taskArns, String executionArn, String region) {for (String taskArn : taskArns) {try {ecsService.stopTask(cluster, taskArn, syncAbortCause(executionArn), region);} catch (RuntimeException e) {- LOG.warnv("ecs:runTask.sync timed out but the task {0} could not be stopped: {1}",+ LOG.warnv("ecs:runTask.sync ended before its task {0} did, and the task could not be stopped: {1}",taskArn, e.getMessage());}}}- /** Best effort, like AWS: a child that already ended does not change the timeout being reported. */+ /** Best effort, like AWS: a child that already ended does not change how the state ends. */private void abortChildExecution(String childExecutionArn, String executionArn) {try {sfnService.get().stopExecution(childExecutionArn, syncAbortCause(executionArn), null);} catch (RuntimeException e) {- LOG.warnv("states:startExecution.sync timed out but the child {0} could not be stopped: {1}",+ LOG.warnv("states:startExecution.sync ended before its child {0} did, and the child could not be stopped: {1}",childExecutionArn, e.getMessage());}}@@ -2580,8 +2595,13 @@ public class AslExecutor {Thread.currentThread().interrupt();throw e;} catch (ExecutionException e) {- abandon(branchChains, futures);+ List<String> abortedEventTypes = cutAfterFailure(branchChains, futures);chain.continueFrom(branchChains.get(joined).lastEventId());+ if (e.getCause() instanceof FailStateException failure && !failure.isRuntimeError()) {+ for (String abortedEventType : abortedEventTypes) {+ chain.publishBeside(abortedEventType, null);+ }+ }// Unwrap so a branch's FailStateException reaches the Parallel state's own Retry and// Catch handling instead of surfacing as States.Runtime, and so an Error reaches the// execution-level handler as itself rather than as an ExecutionException wrapper. The@@ -2617,6 +2637,28 @@ public class AslExecutor {return new StateResult(output, stateDef.path("Next").asText(null));}+ /**+ * Cuts every branch after one of them failed, like {@link #abandon}, and returns one+ * {@code *StateAborted} event type per branch it cut inside a Task or a Wait: the two state+ * types AWS was measured recording it for (a {@code .sync} Task waiting on its job, and a Wait).+ * A branch between states, or inside any other state, gets no event. Each branch is read and cut+ * in one step, so a state that exits before its cut is not reported, and one that is reported+ * records no Exited event afterwards. The state alone decides: a branch that has finished, the+ * failed one included, has left every state it entered, and reading its future as well would+ * reopen the gap between the cut and that read.+ */+ private static List<String> cutAfterFailure(List<HistoryChain> chains, List<? extends Future<?>> futures) {+ List<String> abortedEventTypes = new ArrayList<>();+ for (HistoryChain branch : chains) {+ String stateType = branch.abandonInState();+ if ("Task".equals(stateType) || "Wait".equals(stateType)) {+ abortedEventTypes.add(stateType + "StateAborted");+ }+ }+ futures.forEach(future -> future.cancel(true));+ return abortedEventTypes;+ }+private static void abandon(List<HistoryChain> chains, List<? extends Future<?>> futures) {chains.forEach(HistoryChain::abandon);futures.forEach(future -> future.cancel(true));diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/HistoryChain.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/HistoryChain.javaindex 8849960c65..bf3f6416c3 100644--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/HistoryChain.java+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/HistoryChain.java@@ -20,6 +20,7 @@ final class HistoryChain {private final AtomicBoolean ended;private final HistoryChain parent;private volatile boolean abandoned;+ private String activeStateType;private long lastEventId;private long tailEventId;@@ -68,11 +69,57 @@ final class HistoryChain {continueFrom(last);}- /** AWS records nothing of a branch it cut. */+ /**+ * Nothing more is recorded on a branch once it is cut. The state it was cut in is recorded by+ * the Parallel that cut it, through {@link #publishBeside}.+ */void abandon() {abandoned = true;}+ /*+ * The state this chain is in is published together with the event that enters or exits it,+ * and read together with the cut, all under this chain's lock. A cut therefore reports a state+ * only when its Entered event is recorded and its Exited event never will be.+ */++ /** Publishes a state's Entered event and marks the chain as inside that state. */+ synchronized long publishStateEntered(String stateType, String eventType, Map<String, Object> details) {+ long id = publish(eventType, details);+ activeStateType = stateType;+ return id;+ }++ /** Marks the chain as between states and publishes the state's Exited event. */+ synchronized void publishStateExited(String eventType, Map<String, Object> details) {+ activeStateType = null;+ publish(eventType, details);+ }++ /** Marks the chain as between states when a state ends without an Exited event. */+ synchronized void leaveState() {+ activeStateType = null;+ }++ /**+ * Marks the chain as between states and publishes an aside event, as a Task whose own failure+ * ends its branch records {@code TaskStateAborted}. A cut that lands first reports the state+ * instead, and this event is then not recorded, so the state is reported aborted exactly once.+ */+ synchronized void leaveStateAside(String eventType, Map<String, Object> details) {+ activeStateType = null;+ publishAside(eventType, details);+ }++ /**+ * Cuts the chain like {@link #abandon} and returns the type of the state it was in, or null+ * when it was between states.+ */+ synchronized String abandonInState() {+ abandoned = true;+ return activeStateType;+ }+private boolean isAbandoned() {for (var chain = this; chain != null; chain = chain.parent) {if (chain.abandoned) {@@ -109,6 +156,22 @@ final class HistoryChain {}}+ /**+ * Chained to the last event rather than to the tail, and the last event stays where it is, so+ * several events published this way all point at the same one. AWS records the+ * {@code *StateAborted} event of each branch a failure cuts this way, before the Parallel's+ * {@code ParallelStateFailed}, which points at that same event.+ */+ void publishBeside(String type, Map<String, Object> details) {+ if (isAbandoned()) {+ return;+ }+ long id = append(type, lastEventId, details, true);+ if (id > 0) {+ tailEventId = id;+ }+ }+/** The terminal event does not count towards the limit, and nothing is recorded after it. */void end(String type, Map<String, Object> details) {end(type, tailEventId, details);diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorEcsRunTaskModeTest.javaindex e34445d10a..40b30f715b 100644--- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java@@ -26,6 +26,7 @@ import org.mockito.ArgumentCaptor;import java.time.Clock;import java.util.ArrayList;import java.util.List;+import java.util.concurrent.CountDownLatch;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;@@ -38,7 +39,7 @@ import static org.mockito.ArgumentMatchers.anyInt;import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.RETURNS_DEEP_STUBS;import static org.mockito.Mockito.mock;-import static org.mockito.Mockito.never;+import static org.mockito.Mockito.timeout;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;@@ -106,7 +107,7 @@ class AslExecutorEcsRunTaskModeTest {null,Clock.systemUTC(),sleeper,- null);+ 30);}@Test@@ -218,7 +219,7 @@ class AslExecutorEcsRunTaskModeTest {}@Test- void executionBudgetCutsASyncWaitBeforeTheTasksOwnTimeout() throws Exception {+ void executionBudgetCutsASyncWaitBeforeTheTasksOwnTimeoutAndStopsTheTask() throws Exception {launchOneTask();when(ecsService.describeTasks(any(), any(), any())).thenReturn(List.of(task("RUNNING")));@@ -235,12 +236,54 @@ class AslExecutorEcsRunTaskModeTest {assertEquals("TIMED_OUT", execution.getStatus());assertNull(execution.getError());- verify(ecsService, never()).stopTask(any(), any(), any(), any());+ // AWS stops the task on the execution's budget too (measured: UserInitiated, same reason).+ verify(ecsService).stopTask(any(), eq(task("RUNNING").getTaskArn()),+ eq("The Task state in AWS Step Functions execution [" + execution.getExecutionArn()+ + "] which was managing this resource was aborted"), eq(REGION));assertTrue(history.stream().noneMatch(event -> "TaskTimedOut".equals(event.getType())),"the execution's budget writes nothing about the state it cut");assertTrue(history.stream().anyMatch(event -> "ExecutionTimedOut".equals(event.getType())));}+ @Test+ void failureInASiblingParallelBranchStopsTheTask() throws Exception {+ // The sibling's Pause is held until this branch is polling, so the cut lands mid-wait.+ CountDownLatch polling = new CountDownLatch(1);+ executor = newExecutor(nanos -> {+ if (nanos == TimeUnit.SECONDS.toNanos(1)) {+ polling.await();+ return;+ }+ polling.countDown();+ TimeUnit.NANOSECONDS.sleep(nanos);+ });+ launchOneTask();+ when(ecsService.describeTasks(any(), any(), any())).thenReturn(List.of(task("RUNNING")));++ Execution execution = runDefinition("""+ {+ "StartAt": "P",+ "States": {+ "P": { "Type": "Parallel", "End": true, "Branches": [+ { "StartAt": "Pause", "States": {+ "Pause": { "Type": "Wait", "Seconds": 1, "Next": "Boom" },+ "Boom": { "Type": "Fail", "Error": "Boom" } } },+ { "StartAt": "RunTask", "States": {+ "RunTask": { "Type": "Task", "Resource": "arn:aws:states:::ecs:runTask.sync",+ "Parameters": { "TaskDefinition": "my-task-def" }, "End": true } } }+ ] }+ }+ }+ """, "{}");++ assertEquals("FAILED", execution.getStatus());+ assertEquals("Boom", execution.getError());+ // The cut branch stops its task on its own thread, after the Parallel has already failed.+ verify(ecsService, timeout(5_000)).stopTask(any(), eq(task("RUNNING").getTaskArn()),+ eq("The Task state in AWS Step Functions execution [" + execution.getExecutionArn()+ + "] which was managing this resource was aborted"), eq(REGION));+ }+@Testvoid stopExecutionEndsTheSyncWaitAndStopsTheTask() throws Exception {executor = newExecutor(nanos -> { });diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedSyncTimeoutTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedSyncTimeoutTest.javaindex ca840a9738..1dfffb9c5e 100644--- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedSyncTimeoutTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedSyncTimeoutTest.java@@ -44,8 +44,8 @@ import static org.mockito.Mockito.when;/*** A {@code states:startExecution.sync} wait is bounded by the Task's {@code TimeoutSeconds}, the* way AWS bounds it, and no longer by a fixed poll count of its own. The timeout aborts the child,- * a {@code Catch} on {@code States.Timeout} takes it, and a StopExecution on the parent ends the- * wait and the child alike.+ * a {@code Catch} on {@code States.Timeout} takes it, and the parent's own budget and a+ * StopExecution on the parent each end the wait and abort the child alike.*/class AslExecutorNestedSyncTimeoutTest {@@ -122,6 +122,18 @@ class AslExecutorNestedSyncTimeoutTest {verify(sfnService, never()).stopExecution(any(), any(), any());}+ @Test+ void executionBudgetEndsTheParentTimedOutAndAbortsTheChild() {+ when(sfnService.describeExecution(CHILD_ARN)).thenReturn(child("RUNNING"));++ Execution execution = run(newExecutor(TimeUnit.NANOSECONDS::sleep), ".sync:2", 60, false, 1);++ assertEquals("TIMED_OUT", execution.getStatus());+ assertTrue(history.stream().noneMatch(event -> "TaskTimedOut".equals(event.getType())));+ // Measured on AWS: the child is aborted on the parent's budget too, with the same cause.+ verify(sfnService).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());+ }+@Testvoid stopExecutionOnTheParentEndsTheWaitAndAbortsTheChild() {AtomicInteger parentReads = new AtomicInteger();@@ -190,12 +202,21 @@ class AslExecutorNestedSyncTimeoutTest {}private Execution run(AslExecutor executor, String mode, int timeoutSeconds, boolean catchTimeout) {+ return run(executor, mode, timeoutSeconds, catchTimeout, 0);+ }++ private Execution run(AslExecutor executor, String mode, int timeoutSeconds, boolean catchTimeout,+ int executionTimeoutSeconds) {String timeout = timeoutSeconds > 0 ? "\"TimeoutSeconds\": %d,".formatted(timeoutSeconds) : "";String catcher = catchTimeout? "\"Catch\": [{\"ErrorEquals\": [\"States.Timeout\"], \"Next\": \"Recover\"}],": "";+ String budget = executionTimeoutSeconds > 0+ ? "\"TimeoutSeconds\": %d,".formatted(executionTimeoutSeconds)+ : "";String definition = """{+ %s"StartAt": "Child","States": {"Child": {@@ -209,7 +230,7 @@ class AslExecutorNestedSyncTimeoutTest {"Recover": { "Type": "Pass", "End": true }}}- """.formatted(mode, timeout, catcher, CHILD_SM_ARN);+ """.formatted(budget, mode, timeout, catcher, CHILD_SM_ARN);StateMachine stateMachine = new StateMachine();stateMachine.setName("parent");diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorParallelCutTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorParallelCutTest.javanew file mode 100644index 0000000000..fca99aee93--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorParallelCutTest.java@@ -0,0 +1,265 @@+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.cloudformation.CloudFormationQueryHandler;+import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade;+import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;+import io.github.hectorvent.floci.services.ec2.Ec2Service;+import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;+import io.github.hectorvent.floci.services.ecs.EcsService;+import io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler;+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.scheduler.SchedulerController;+import io.github.hectorvent.floci.services.scheduler.SchedulerService;+import io.github.hectorvent.floci.services.sns.SnsJsonHandler;+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.StateMachine;+import jakarta.enterprise.inject.Instance;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.time.Clock;+import java.util.ArrayList;+import java.util.List;+import java.util.Set;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.TimeUnit;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.ArgumentMatchers.isNull;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.timeout;+import static org.mockito.Mockito.times;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++/**+ * A Parallel branch that is cut while its {@code .sync} Task waits on a child execution aborts that+ * child, the way AWS does, and the history records the state each cut branch was in. Measured on+ * AWS: a failure in one branch aborts the child of every other branch within about 0.1 s with the+ * cause below, and records one {@code TaskStateAborted} (or {@code WaitStateAborted}) per cut+ * branch, each chained to the failing branch's last event and recorded before+ * {@code ParallelStateFailed}, which is chained to that same event. When the execution's budget+ * cuts the Parallel instead, the child is aborted as well and no such event is recorded.+ *+ * <p>The failing branch pauses in a Wait that the sleeper holds until every other branch is+ * parked on its own wait, so the cut always lands while the others are mid-state.+ */+class AslExecutorParallelCutTest {++ private static final String REGION = "us-east-2";+ private static final String ACCOUNT = "000000000000";+ private static final String CHILD_SM_ARN =+ "arn:aws:states:%s:%s:stateMachine:child".formatted(REGION, ACCOUNT);+ private static final String CHILD_ARN =+ "arn:aws:states:%s:%s:execution:child:run-1".formatted(REGION, ACCOUNT);+ private static final String PARENT_ARN =+ "arn:aws:states:%s:%s:execution:parent:parent-run".formatted(REGION, ACCOUNT);+ private static final String ABORT_CAUSE =+ "The Task state in AWS Step Functions execution [" + PARENT_ARN+ + "] which was managing this resource was aborted";+ private static final long PAUSE_NANOS = TimeUnit.SECONDS.toNanos(1);+ private static final String FAILING_BRANCH = """+ {"StartAt":"Pause","States":{+ "Pause":{"Type":"Wait","Seconds":1,"Next":"Boom"},+ "Boom":{"Type":"Fail","Error":"Boom","Cause":"sibling failed"}}}""";+ private static final String NESTED_SYNC_BRANCH = """+ {"StartAt":"Nest","States":{"Nest":{"Type":"Task",+ "Resource":"arn:aws:states:::states:startExecution.sync:2",+ "Parameters":{"StateMachineArn":"%s"},"End":true}}}""".formatted(CHILD_SM_ARN);+ private static final String PASS_BRANCH = """+ {"StartAt":"Done","States":{"Done":{"Type":"Pass","End":true}}}""";+ private static final String LONG_WAIT_BRANCH = """+ {"StartAt":"Long","States":{"Long":{"Type":"Wait","Seconds":20,"End":true}}}""";++ private final ObjectMapper objectMapper = new ObjectMapper();+ private StepFunctionsService sfnService;+ private List<HistoryEvent> history;++ @BeforeEach+ void setUp() {+ sfnService = mock(StepFunctionsService.class);+ when(sfnService.startExecution(any(), any(), any(), any())).thenReturn(child());+ when(sfnService.describeExecution(CHILD_ARN)).thenReturn(child());+ Execution parent = new Execution();+ parent.setExecutionArn(PARENT_ARN);+ parent.setStatus("RUNNING");+ when(sfnService.describeExecution(PARENT_ARN)).thenReturn(parent);+ }++ @Test+ void siblingFailureAbortsTheChildAndRecordsTaskStateAbortedBesideTheFailure() {+ Execution execution = run(parallel(FAILING_BRANCH, NESTED_SYNC_BRANCH), 1, 0);++ assertEquals("FAILED", execution.getStatus());+ assertEquals("Boom", execution.getError());+ assertEquals("sibling failed", execution.getCause());+ long failure = eventOfType("FailStateEntered").getId();+ List<HistoryEvent> aborted = eventsOfType("TaskStateAborted");+ assertEquals(1, aborted.size(), "one TaskStateAborted for the one cut branch: " + types());+ assertEquals(failure, aborted.get(0).getPreviousEventId().longValue());+ assertNull(aborted.get(0).getDetails());+ HistoryEvent parallelFailed = eventOfType("ParallelStateFailed");+ assertEquals(failure, parallelFailed.getPreviousEventId().longValue());+ assertTrue(aborted.get(0).getId() < parallelFailed.getId());+ verify(sfnService, timeout(5_000)).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());+ }++ @Test+ void everyCutBranchRecordsItsOwnTaskStateAbortedAgainstTheSameEvent() {+ Execution execution = run(parallel(FAILING_BRANCH, NESTED_SYNC_BRANCH, NESTED_SYNC_BRANCH), 2, 0);++ assertEquals("FAILED", execution.getStatus());+ long failure = eventOfType("FailStateEntered").getId();+ List<HistoryEvent> aborted = eventsOfType("TaskStateAborted");+ assertEquals(2, aborted.size(), types().toString());+ assertTrue(aborted.stream().allMatch(event -> event.getPreviousEventId() == failure), types().toString());+ assertEquals(failure, eventOfType("ParallelStateFailed").getPreviousEventId().longValue());+ verify(sfnService, timeout(5_000).times(2)).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());+ }++ @Test+ void aWaitCutByASiblingFailureIsRecordedAsWaitStateAborted() {+ Execution execution = run(parallel(FAILING_BRANCH, LONG_WAIT_BRANCH), 1, 0);++ assertEquals("FAILED", execution.getStatus());+ long failure = eventOfType("FailStateEntered").getId();+ HistoryEvent aborted = eventOfType("WaitStateAborted");+ assertEquals(failure, aborted.getPreviousEventId().longValue());+ assertTrue(eventsOfType("TaskStateAborted").isEmpty(), types().toString());+ assertTrue(aborted.getId() < eventOfType("ParallelStateFailed").getId());+ }++ @Test+ void aBranchThatFinishedBeforeTheFailureRecordsNoAbortedState() {+ // The failing branch's Pause really sleeps, so the Pass branch has long finished by then.+ AslExecutor.Sleeper sleeper = nanos -> TimeUnit.MILLISECONDS.sleep(200);+ Execution execution = run(parallel(FAILING_BRANCH, PASS_BRANCH), sleeper, 0);++ assertEquals("FAILED", execution.getStatus());+ assertTrue(types().contains("PassStateExited"), types().toString());+ assertTrue(types().stream().noneMatch(type -> type.endsWith("StateAborted")), types().toString());+ }++ @Test+ void executionBudgetCuttingTheParallelAbortsTheChildAndRecordsNoAbortedState() {+ Execution execution = run(parallel(NESTED_SYNC_BRANCH), 0, 1);++ assertEquals("TIMED_OUT", execution.getStatus());+ assertTrue(types().stream().noneMatch(type -> type.endsWith("StateAborted")), types().toString());+ verify(sfnService, timeout(5_000)).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());+ }++ private static Execution child() {+ Execution current = new Execution();+ current.setExecutionArn(CHILD_ARN);+ current.setStateMachineArn(CHILD_SM_ARN);+ current.setName("run-1");+ current.setStatus("RUNNING");+ current.setStartDate(1.0);+ return current;+ }++ private static String parallel(String... branches) {+ return "{\"Type\":\"Parallel\",\"End\":true,\"Branches\":[" + String.join(",", branches) + "]}";+ }++ /**+ * The failing branch's one-second Pause is held until {@code waitingBranches} other branch+ * threads have started a sleep of their own (a {@code .sync} poll, or a longer Wait); every+ * other sleep is real, so the cut interrupts it.+ */+ private static AslExecutor.Sleeper sleeper(int waitingBranches) {+ CountDownLatch othersWaiting = new CountDownLatch(waitingBranches);+ Set<Thread> seen = ConcurrentHashMap.newKeySet();+ return nanos -> {+ if (nanos == PAUSE_NANOS) {+ othersWaiting.await();+ return;+ }+ if (seen.add(Thread.currentThread())) {+ othersWaiting.countDown();+ }+ TimeUnit.NANOSECONDS.sleep(nanos);+ };+ }++ @SuppressWarnings("unchecked")+ private AslExecutor newExecutor(AslExecutor.Sleeper sleeper) {+ Instance<StepFunctionsService> instance = mock(Instance.class);+ when(instance.get()).thenReturn(sfnService);+ return new AslExecutor(+ mock(LambdaExecutorService.class),+ mock(LambdaFunctionStore.class),+ mock(DynamoDbFacade.class),+ mock(DynamoDbJsonHandler.class),+ mock(SqsJsonHandler.class), mock(SnsJsonHandler.class),+ mock(CloudFormationQueryHandler.class),+ mock(Ec2Service.class),+ mock(S3Service.class),+ mock(EcsService.class),+ mock(EcsJsonHandler.class),+ mock(EventBridgeHandler.class),+ mock(SchedulerService.class),+ mock(SchedulerController.class),+ objectMapper,+ new JsonataEvaluator(objectMapper),+ instance,+ mock(EmulatorConfig.class),+ null,+ null,+ Clock.systemUTC(),+ sleeper,+ 30);+ }++ private Execution run(String parallelState, int waitingBranches, int executionTimeoutSeconds) {+ return run(parallelState, sleeper(waitingBranches), executionTimeoutSeconds);+ }++ private Execution run(String parallelState, AslExecutor.Sleeper sleeper, int executionTimeoutSeconds) {+ String budget = executionTimeoutSeconds > 0+ ? "\"TimeoutSeconds\":%d,".formatted(executionTimeoutSeconds)+ : "";+ String definition = "{" + budget + "\"StartAt\":\"P\",\"States\":{\"P\":" + parallelState + "}}";++ StateMachine stateMachine = new StateMachine();+ stateMachine.setName("parent");+ stateMachine.setStateMachineArn("arn:aws:states:%s:%s:stateMachine:parent".formatted(REGION, ACCOUNT));+ stateMachine.setRoleArn("arn:aws:iam::%s:role/test-role".formatted(ACCOUNT));+ stateMachine.setDefinition(definition);++ Execution execution = new Execution();+ execution.setName("parent-run");+ execution.setExecutionArn(PARENT_ARN);+ execution.setStateMachineArn(stateMachine.getStateMachineArn());+ execution.setInput("{}");++ history = new ArrayList<>();+ newExecutor(sleeper).executeSync(stateMachine, execution, history, (updated, events) -> { });+ return execution;+ }++ private List<String> types() {+ return history.stream().map(HistoryEvent::getType).toList();+ }++ private List<HistoryEvent> eventsOfType(String type) {+ return history.stream().filter(event -> type.equals(event.getType())).toList();+ }++ private HistoryEvent eventOfType(String type) {+ return history.stream().filter(event -> type.equals(event.getType())).findFirst()+ .orElseThrow(() -> new AssertionError("no " + type + " in " + types()));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/HistoryChainTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/HistoryChainTest.javaindex 523216d4cb..6503d77cf0 100644--- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/HistoryChainTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/HistoryChainTest.java@@ -4,11 +4,14 @@ import io.github.hectorvent.floci.services.stepfunctions.model.HistoryEvent;import org.junit.jupiter.api.Test;import java.util.ArrayList;+import java.util.Collections;import java.util.List;import java.util.Map;+import java.util.concurrent.CountDownLatch;import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;class HistoryChainTest {@@ -45,4 +48,83 @@ class HistoryChainTest {});assertEquals(1, history.size());}++ @Test+ void aStateCutAfterItsEnteredEventIsReportedAndRecordsNoExitedEvent() {+ List<HistoryEvent> history = new ArrayList<>();+ HistoryChain branch = HistoryChain.of(history).fork();+ branch.publishStateEntered("Task", "TaskStateEntered", null);++ assertEquals("Task", branch.abandonInState());+ branch.publishStateExited("TaskStateExited", null);++ assertEquals(List.of("TaskStateEntered"), typesOf(history));+ }++ @Test+ void aStateThatExitedBeforeTheCutIsNotReported() {+ List<HistoryEvent> history = new ArrayList<>();+ HistoryChain branch = HistoryChain.of(history).fork();+ branch.publishStateEntered("Task", "TaskStateEntered", null);+ branch.publishStateExited("TaskStateExited", null);++ assertNull(branch.abandonInState());+ assertEquals(List.of("TaskStateEntered", "TaskStateExited"), typesOf(history));+ }++ @Test+ void aTaskThatEndsItsBranchBeforeTheCutIsNotReportedTwice() {+ List<HistoryEvent> history = new ArrayList<>();+ HistoryChain branch = HistoryChain.of(history).fork();+ branch.publishStateEntered("Task", "TaskStateEntered", null);+ branch.leaveStateAside("TaskStateAborted", null);++ assertNull(branch.abandonInState());+ assertEquals(List.of("TaskStateEntered", "TaskStateAborted"), typesOf(history));+ }++ @Test+ void aTaskCutBeforeItEndsItsBranchIsReportedByTheCutOnly() {+ List<HistoryEvent> history = new ArrayList<>();+ HistoryChain branch = HistoryChain.of(history).fork();+ branch.publishStateEntered("Task", "TaskStateEntered", null);++ assertEquals("Task", branch.abandonInState());+ branch.leaveStateAside("TaskStateAborted", null);++ assertEquals(List.of("TaskStateEntered"), typesOf(history));+ }++ @Test+ void aCutRacingAStateNeverDisagreesWithTheRecordedEvents() throws Exception {+ for (int round = 0; round < 2_000; round++) {+ List<HistoryEvent> history = Collections.synchronizedList(new ArrayList<>());+ HistoryChain branch = HistoryChain.of(history).fork();+ CountDownLatch start = new CountDownLatch(1);+ Thread worker = new Thread(() -> {+ try {+ start.await();+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ return;+ }+ branch.publishStateEntered("Task", "TaskStateEntered", null);+ branch.publishStateExited("TaskStateExited", null);+ });+ worker.start();+ start.countDown();+ String reported = branch.abandonInState();+ worker.join();++ List<String> types = typesOf(history);+ boolean cutMidState = types.contains("TaskStateEntered") && !types.contains("TaskStateExited");+ assertEquals(cutMidState, "Task".equals(reported), "round " + round + ": " + reported + " with " + types);+ }+ }++ private static List<String> typesOf(List<HistoryEvent> history) {+ synchronized (history) {+ return history.stream().map(HistoryEvent::getType).toList();+ }+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsTimeoutSecondsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsTimeoutSecondsIntegrationTest.javaindex bf6ce1c12e..e9d581dc1a 100644--- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsTimeoutSecondsIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsTimeoutSecondsIntegrationTest.java@@ -160,7 +160,7 @@ class StepFunctionsTimeoutSecondsIntegrationTest {@Testvoid stateMachineTimeoutSecondsCutsTheWaitForANestedExecution() throws Exception {// The child sleeps far past the parent's budget. The parent ends TIMED_OUT where its budget- // runs out; the child keeps running, since nothing in ASL propagates the parent's timeout.+ // runs out, and the child is aborted with it, as AWS does (measured: ABORTED, no error).String childArn = createStateMachine("nested-child", """{"StartAt": "Linger",@@ -193,6 +193,16 @@ class StepFunctionsTimeoutSecondsIntegrationTest {JsonNode events = mapper.readTree(getExecutionHistory(execArn).body().asString()).path("events");assertEquals("ExecutionTimedOut", events.get(events.size() - 1).path("type").asText(),"history was " + events);+ Response children = given()+ .header("X-Amz-Target", "AWSStepFunctions.ListExecutions")+ .contentType(SFN_CONTENT_TYPE)+ .body("""+ {"stateMachineArn": "%s"}+ """.formatted(childArn))+ .when()+ .post("/");+ assertEquals(List.of("ABORTED"), children.jsonPath().getList("executions.status"),+ children.body().asString());}@Test