diff --git a/docs/services/step-functions.md b/docs/services/step-functions.md index ebe5d0074f..01cbfc8361 100644 --- a/docs/services/step-functions.md +++ b/docs/services/step-functions.md @@ -57,6 +57,15 @@ changes to `StateMachineName` or `StateMachineType` use replacement semantics. `Parameters` or `Arguments` payload, serialized as a JSON string. `timeoutInSeconds` and `heartbeatInSeconds` appear only when the state sets `TimeoutSeconds` or `HeartbeatSeconds` as a literal number. + `resourceType` is the integrated service (`states`, `ecs`, `aws-sdk:sqs`) and `resource` the + API with its suffix (`startExecution.sync:2`, `runTask.sync`), as AWS names them. A `.sync` + Task (`states:startExecution.sync` and `.sync:2`, `ecs:runTask.sync`) also records + `TaskSubmitted` after `TaskStarted`, once the call that started its job has returned and before + it waits on the job. `taskSubmittedEventDetails` carries `resourceType`, `resource`, + `outputDetails`, and that call's response as `output`, in PascalCase: `{"ExecutionArn", + "StartDate"}` with `StartDate` in epoch milliseconds for a nested execution, `{"Failures", + "Tasks"}` for an ECS task. AWS folds the SDK's `SdkHttpMetadata` and `SdkResponseMetadata` + into that response as well; Floci records the response fields alone. - A direct Lambda function ARN emits `LambdaFunctionScheduled`, `LambdaFunctionStarted`, and then `LambdaFunctionSucceeded` or `LambdaFunctionFailed`. `LambdaFunctionScheduled` carries `resource` and `input`. `resource` holds the full function ARN. `LambdaFunctionStarted` @@ -109,15 +118,15 @@ When the request sets `includeExecutionData` to false, the details objects stay `taskScheduledEventDetails.parameters`. This matches AWS. A few gaps remain. `TaskStarted`, `LambdaFunctionStarted`, and `ActivityStarted` fire at -scheduling time, not when a worker actually picks up the task. `TaskSubmitted`, which real -AWS emits for `.sync` and `.waitForTaskToken` integrations, is not emitted yet. When an inline -`Map` iteration fails, AWS records a `MapIterationAborted` for each iteration it cuts and the -`*StateAborted` of the state that iteration was in, all chained to the failing iteration's last -event and recorded before `MapIterationFailed` and `MapStateFailed`; Floci cancels the iterations -without recording them, where a `Parallel` records the state of each branch it cuts, as above. A -Distributed `Map` that declares no tolerance reports a failed item's own error rather than AWS's -`States.ExceedToleratedFailureThreshold`, and emits `MapRunFailed` with that error. A `Map` that -declares one reports `States.ExceedToleratedFailureThreshold`, as AWS does. +scheduling time, not when a worker actually picks up the task. `TaskSubmitted` is recorded for +the three `.sync` integrations above and not yet for a `.waitForTaskToken` one, which AWS also +records it for. When an inline `Map` iteration fails, AWS records a `MapIterationAborted` for each +iteration it cuts and the `*StateAborted` of the state that iteration was in, all chained to the +failing iteration's last event and recorded before `MapIterationFailed` and `MapStateFailed`; Floci +cancels the iterations without recording them, where a `Parallel` records the state of each branch +it cuts, as above. A Distributed `Map` that declares no tolerance reports a failed item's own error +rather than AWS's `States.ExceedToleratedFailureThreshold`, and emits `MapRunFailed` with that +error. A `Map` that declares one reports `States.ExceedToleratedFailureThreshold`, as AWS does. ## Map concurrency diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java index 124f4f23c9..542b55b961 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 @@ -118,6 +118,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiConsumer; +import java.util.function.Consumer; import java.util.stream.Collectors; @ApplicationScoped @@ -825,7 +826,8 @@ public class AslExecutor { : invokeResource(effectiveResource, effectiveInput, sm, taskToken, context.path("Execution").path("Id").asText(null), executionDeadlineNanos, taskDeadlineNanos, - jsonata ? null : stateDef.path("Parameters")); + jsonata ? null : stateDef.path("Parameters"), + jobResponse -> addTaskSubmittedEvent(chain, profile, jobResponse)); if (tokenFuture != null) { taskResult = awaitToken(tokenFuture, stateDef, taskToken, executionDeadlineNanos, taskDeadlineNanos); @@ -1075,9 +1077,13 @@ public class AslExecutor { return new FailStateException("Exception", cause); } + /** + * @param jobSubmitted called with the response of the call that started a {@code .sync} job, + * once it has returned and before the job is waited on + */ private JsonNode invokeResource(String resource, JsonNode input, StateMachine sm, String taskToken, String executionArn, long executionDeadlineNanos, long taskDeadlineNanos, - JsonNode rawParameters) throws Exception { + JsonNode rawParameters, Consumer jobSubmitted) throws Exception { // Support Lambda resources: direct ARN or optimized integration String functionName = null; String functionRef = null; @@ -1226,7 +1232,8 @@ public class AslExecutor { ? ".waitForTaskToken" : integration.suffix(); String region = extractRegionFromArn(sm.getStateMachineArn()); - return invokeEcsRunTask(mode, input, region, executionArn, executionDeadlineNanos, taskDeadlineNanos); + return invokeEcsRunTask(mode, input, region, executionArn, executionDeadlineNanos, taskDeadlineNanos, + jobSubmitted); } // AWS SDK service integrations: Step Functions @@ -1252,7 +1259,7 @@ public class AslExecutor { String mode = integration.suffix(); String region = extractRegionFromArn(sm.getStateMachineArn()); return invokeNestedStateMachine(mode, input, region, executionArn, executionDeadlineNanos, - taskDeadlineNanos, rawParameters); + taskDeadlineNanos, rawParameters, jobSubmitted); } throw new FailStateException("States.TaskFailed", "Unsupported resource: " + resource); @@ -1671,7 +1678,8 @@ public class AslExecutor { private JsonNode invokeNestedStateMachine(String mode, JsonNode input, String region, String executionArn, long executionDeadlineNanos, long taskDeadlineNanos, - JsonNode rawParameters) throws Exception { + JsonNode rawParameters, Consumer jobSubmitted) + throws Exception { String smArn = input.path("StateMachineArn").asText(null); if (smArn == null || smArn.isBlank()) { throw new FailStateException("States.TaskFailed", @@ -1717,6 +1725,20 @@ public class AslExecutor { return result; } + // The job is submitted: AWS records the StartExecution response here, before the wait + // (measured: PascalCase, StartDate in epoch milliseconds). + ObjectNode startResponse = objectMapper.createObjectNode(); + startResponse.put("ExecutionArn", execArn); + startResponse.put("StartDate", Math.round(exec.getStartDate() * 1000)); + try { + jobSubmitted.accept(startResponse); + } catch (RuntimeException e) { + // The event could not be recorded (the history-event limit): the child has started and + // the wait that would abort it is never entered, so it is aborted here. + abortChildExecution(execArn, executionArn); + throw e; + } + // .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 @@ -1825,7 +1847,8 @@ public class AslExecutor { * (both ".sync" and ".waitForTaskToken" fail the state on a placement failure). */ private JsonNode invokeEcsRunTask(String mode, JsonNode input, String region, String executionArn, - long executionDeadlineNanos, long taskDeadlineNanos) throws Exception { + long executionDeadlineNanos, long taskDeadlineNanos, + Consumer jobSubmitted) throws Exception { String taskDefinition = input.path("TaskDefinition").asText(null); if (taskDefinition == null || taskDefinition.isBlank()) { throw new FailStateException("States.TaskFailed", @@ -1901,6 +1924,22 @@ public class AslExecutor { // 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 taskArns = launched.stream().map(EcsTask::getTaskArn).toList(); + // The job is submitted: AWS records the RunTask response here, before the wait (measured: + // Failures then Tasks, PascalCase). + ObjectNode runTaskResponse = objectMapper.createObjectNode(); + runTaskResponse.putArray("Failures"); + ArrayNode submittedTasks = runTaskResponse.putArray("Tasks"); + for (EcsTask t : launched) { + submittedTasks.add(recaseKeys(objectMapper, ecsJsonHandler.taskNode(t), true)); + } + try { + jobSubmitted.accept(runTaskResponse); + } catch (RuntimeException e) { + // Same as the nested case: the tasks are running and the wait that would stop them is + // never entered, so they are stopped here. + stopEcsTasks(cluster, taskArns, executionArn, region); + throw e; + } while (true) { try { sleepOrTimeOutTask(TimeUnit.MILLISECONDS.toNanos(SYNC_POLL_INTERVAL_MS), @@ -5391,6 +5430,14 @@ public class AslExecutor { if (resource.contains(":lambda:") && resource.contains(":function:")) { return new TaskEventProfile("LambdaFunction", null, resource); } + // A well-formed integration id splits at its service: AWS reports states / startExecution.sync:2, + // and a split at the last colon would report startExecution.sync / 2 for it. + StatesIntegration integration = StatesIntegration.parse(resource).orElse(null); + if (integration != null) { + return new TaskEventProfile("Task", + (integration.sdk() ? "aws-sdk:" : "") + integration.service(), + integration.api() + integration.suffix()); + } String tail = StatesIntegration.tail(resource).orElse(null); if (tail != null) { int idx = tail.lastIndexOf(':'); @@ -5434,6 +5481,20 @@ public class AslExecutor { } } + /** + * Recorded for a {@code .sync} Task once the call that started its job has returned, carrying + * that response as {@code output}. AWS also folds the SDK's {@code SdkHttpMetadata} and + * {@code SdkResponseMetadata} into it; Floci records the response fields alone. + */ + private void addTaskSubmittedEvent(HistoryChain chain, TaskEventProfile profile, JsonNode jobResponse) { + LinkedHashMap details = new LinkedHashMap<>(); + details.put("resourceType", profile.resourceType()); + details.put("resource", profile.resource()); + details.put("output", jobResponse.toString()); + details.put("outputDetails", Map.of("truncated", false)); + chain.publish("TaskSubmitted", details); + } + private void addTaskSucceededEvent(HistoryChain chain, TaskEventProfile profile, JsonNode taskResult) { var output = taskResult.toString(); if ("Task".equals(profile.prefix())) { 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.java index 40b30f715b..caa1dc3c0c 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.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; @@ -199,6 +200,84 @@ class AslExecutorEcsRunTaskModeTest { + "] which was managing this resource was aborted"), eq(REGION)); } + /** + * AWS records TaskSubmitted once RunTask has returned and before it waits on the task (measured: + * resourceType ecs, resource runTask.sync, the response as Failures then Tasks in PascalCase, + * chained to TaskStarted). + */ + @Test + void syncRecordsTaskSubmittedWithTheRunTaskResponse() throws Exception { + launchOneTask(); + when(ecsService.describeTasks(any(), any(), any())).thenReturn(List.of(task("STOPPED"))); + + Execution execution = run("arn:aws:states:::ecs:runTask.sync", "{\"TaskDefinition\":\"my-task-def\"}"); + + assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause()); + List types = history.stream().map(HistoryEvent::getType).toList(); + assertEquals(List.of("TaskStateEntered", "TaskScheduled", "TaskStarted", "TaskSubmitted", + "TaskSucceeded", "TaskStateExited", "ExecutionSucceeded"), types); + HistoryEvent submitted = history.get(3); + assertEquals(history.get(2).getId(), submitted.getPreviousEventId().longValue()); + assertEquals(submitted.getId(), history.get(4).getPreviousEventId().longValue()); + assertEquals("ecs", submitted.getDetails().get("resourceType")); + assertEquals("runTask.sync", submitted.getDetails().get("resource")); + JsonNode output = objectMapper.readTree((String) submitted.getDetails().get("output")); + assertEquals(List.of("Failures", "Tasks"), fieldNames(output)); + assertTrue(output.path("Failures").isArray() && output.path("Failures").isEmpty(), output.toString()); + assertEquals(1, output.path("Tasks").size(), output.toString()); + assertEquals(task("PENDING").getTaskArn(), output.path("Tasks").get(0).path("TaskArn").asText()); + assertEquals("PENDING", output.path("Tasks").get(0).path("LastStatus").asText()); + assertEquals(Map.of("truncated", false), submitted.getDetails().get("outputDetails")); + } + + /** + * When TaskSubmitted is the event that hits the 25,000-event limit, the wait that would stop + * the launched task is never entered, so it is stopped on the way out instead of running on. + */ + @Test + void aTaskWhoseTaskSubmittedHitsTheHistoryLimitIsStopped() throws Exception { + launchOneTask(); + when(ecsService.describeTasks(any(), any(), any())).thenReturn(List.of(task("RUNNING"))); + List recorded = new ArrayList<>(); + for (int i = 0; i < 24_996; i++) { + recorded.add(new HistoryEvent()); + } + + Execution execution = runDefinition(""" + { + "StartAt": "RunTask", + "States": { + "RunTask": { "Type": "Task", "Resource": "arn:aws:states:::ecs:runTask.sync", "End": true } + } + } + """, "{\"TaskDefinition\":\"my-task-def\"}", recorded); + + assertEquals("FAILED", execution.getStatus()); + assertEquals("States.Runtime", execution.getError()); + assertEquals("TaskStarted", history.get(24_998).getType()); + assertTrue(history.stream().noneMatch(event -> "TaskSubmitted".equals(event.getType()))); + 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)); + } + + @Test + void requestResponseRecordsNoTaskSubmitted() throws Exception { + launchOneTask(); + + Execution execution = run("arn:aws:states:::ecs:runTask", "{\"TaskDefinition\":\"my-task-def\"}"); + + assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause()); + assertTrue(history.stream().noneMatch(event -> "TaskSubmitted".equals(event.getType())), + history.stream().map(HistoryEvent::getType).toList().toString()); + } + + private static List fieldNames(JsonNode node) { + List names = new ArrayList<>(); + node.fieldNames().forEachRemaining(names::add); + return names; + } + @Test void syncIsNotCappedByAPollCountWhenNoTimeoutSecondsIsDeclared() throws Exception { // The former loop gave up after 600 polls. A task that stops on the 700th read must still @@ -348,6 +427,11 @@ class AslExecutorEcsRunTaskModeTest { } private Execution runDefinition(String definition, String input) { + return runDefinition(definition, input, new ArrayList<>()); + } + + /** {@code recorded} is the history the execution starts with, counted towards the event limit. */ + private Execution runDefinition(String definition, String input, List recorded) { StateMachine stateMachine = new StateMachine(); stateMachine.setName("ecs-runtask-test"); stateMachine.setStateMachineArn("arn:aws:states:%s:%s:stateMachine:ecs-runtask-test".formatted(REGION, ACCOUNT)); @@ -360,7 +444,7 @@ class AslExecutorEcsRunTaskModeTest { execution.setStateMachineArn(stateMachine.getStateMachineArn()); execution.setInput(input); - history = new ArrayList<>(); + history = recorded; executor.executeSync(stateMachine, execution, history, (updated, events) -> { }); return execution; } diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedStartExecutionTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedStartExecutionTest.java index 558b053606..1f14c130a7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedStartExecutionTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedStartExecutionTest.java @@ -25,11 +25,16 @@ import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import java.util.ArrayList; +import java.util.List; +import java.util.Map; 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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -53,6 +58,7 @@ class AslExecutorNestedStartExecutionTest { private final ObjectMapper mapper = new ObjectMapper(); private AslExecutor executor; private StepFunctionsService childSfn; + private List history; @BeforeEach @SuppressWarnings("unchecked") @@ -91,6 +97,11 @@ class AslExecutorNestedStartExecutionTest { } private Execution runParent(String parentDefinition, String input) { + return runParent(parentDefinition, input, new ArrayList<>()); + } + + /** {@code recorded} is the history the execution starts with, counted towards the event limit. */ + private Execution runParent(String parentDefinition, String input, List recorded) { StateMachine sm = new StateMachine(); sm.setName("parent"); sm.setStateMachineArn("arn:aws:states:us-east-1:000000000000:stateMachine:parent"); @@ -101,7 +112,8 @@ class AslExecutorNestedStartExecutionTest { exec.setExecutionArn("arn:aws:states:us-east-1:000000000000:execution:parent:pe"); exec.setStateMachineArn(sm.getStateMachineArn()); exec.setInput(input); - executor.executeSync(sm, exec, new ArrayList(), (u, e) -> { + history = recorded; + executor.executeSync(sm, exec, history, (u, e) -> { }); return exec; } @@ -285,4 +297,82 @@ class AslExecutorNestedStartExecutionTest { assertEquals("{\"ok\":true}", output.path("output").asText(), "envelope output is the child output JSON string"); } } + /** + * AWS records TaskSubmitted once StartExecution has returned and before it waits on the child + * (measured: resourceType states, resource startExecution.sync:2, the response in PascalCase with + * StartDate in epoch milliseconds, chained to TaskStarted). It also names the integration as + * states / startExecution.sync:2 on every event, not startExecution.sync / 2. + */ + @ParameterizedTest + @ValueSource(strings = {".sync", ".sync:2"}) + void syncRecordsTaskSubmittedWithTheStartExecutionResponse(String mode) throws Exception { + childSucceeds(); + + Execution exec = runParent(parentMode(mode), "{}"); + + assertEquals("SUCCEEDED", exec.getStatus(), exec.getCause()); + assertEquals(List.of("TaskStateEntered", "TaskScheduled", "TaskStarted", "TaskSubmitted", + "TaskSucceeded", "TaskStateExited", "ExecutionSucceeded"), types()); + HistoryEvent submitted = history.get(3); + assertEquals(history.get(2).getId(), submitted.getPreviousEventId().longValue()); + assertEquals(submitted.getId(), history.get(4).getPreviousEventId().longValue()); + assertEquals("states", submitted.getDetails().get("resourceType")); + assertEquals("startExecution" + mode, submitted.getDetails().get("resource")); + assertEquals("{\"ExecutionArn\":\"arn:aws:states:us-east-1:000000000000:execution:child:e1\"," + + "\"StartDate\":1000}", submitted.getDetails().get("output")); + assertEquals(Map.of("truncated", false), submitted.getDetails().get("outputDetails")); + for (int i = 1; i <= 4; i++) { + assertEquals("states", history.get(i).getDetails().get("resourceType"), history.get(i).getType()); + assertEquals("startExecution" + mode, history.get(i).getDetails().get("resource"), history.get(i).getType()); + } + } + + /** + * TaskSubmitted is the first event after the child exists. When it is the one that hits the + * 25,000-event limit, the wait that would abort the child is never entered, so the child is + * aborted on the way out instead of running on. + */ + @Test + void aChildWhoseTaskSubmittedHitsTheHistoryLimitIsAborted() { + List recorded = new ArrayList<>(); + for (int i = 0; i < 24_996; i++) { + recorded.add(new HistoryEvent()); + } + + Execution exec = runParent(parentMode(".sync:2"), "{}", recorded); + + assertEquals("FAILED", exec.getStatus()); + assertEquals("States.Runtime", exec.getError()); + assertEquals("The execution reached the maximum number of history events (25000).", exec.getCause()); + assertEquals("TaskStarted", history.get(24_998).getType()); + assertFalse(types().contains("TaskSubmitted"), "the event that hit the limit is not recorded"); + verify(childSfn).stopExecution(eq("arn:aws:states:us-east-1:000000000000:execution:child:e1"), + eq("The Task state in AWS Step Functions execution " + + "[arn:aws:states:us-east-1:000000000000:execution:parent:pe]" + + " which was managing this resource was aborted"), isNull()); + } + + @Test + void requestResponseRecordsNoTaskSubmitted() { + Execution exec = runParent(parentMode(""), "{}"); + + assertEquals("SUCCEEDED", exec.getStatus(), exec.getCause()); + assertFalse(types().contains("TaskSubmitted"), types().toString()); + } + + private void childSucceeds() { + Execution done = new Execution(); + done.setExecutionArn("arn:aws:states:us-east-1:000000000000:execution:child:e1"); + done.setStateMachineArn(CHILD_ARN); + done.setName("e1"); + done.setStatus("SUCCEEDED"); + done.setStartDate(1.0); + done.setStopDate(2.0); + done.setOutput("{\"ok\":true}"); + when(childSfn.describeExecution(any())).thenReturn(done); + } + + private List types() { + return history.stream().map(HistoryEvent::getType).toList(); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsExecutionHistoryIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsExecutionHistoryIntegrationTest.java index fd0fb48b30..b461bfde37 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsExecutionHistoryIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsExecutionHistoryIntegrationTest.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.stepfunctions; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; @@ -459,6 +460,74 @@ class StepFunctionsExecutionHistoryIntegrationTest { }); } + /** + * A {@code .sync} Task records {@code TaskSubmitted} between {@code TaskStarted} and its terminal + * event, carrying the response of the call that started the job, as AWS does (measured in + * ap-northeast-1 on 2026-09-29: PascalCase, {@code StartDate} in epoch milliseconds). + */ + @Test + void syncTaskRecordsTaskSubmittedWithTheStartExecutionResponse() throws Exception { + String childArn = createStateMachine("execution-history-task-submitted-child", """ + {"StartAt": "Done", "States": {"Done": {"Type": "Pass", "End": true}}} + """); + String parentArn = createStateMachine("execution-history-task-submitted-parent", """ + { + "StartAt": "Nest", + "States": { + "Nest": { + "Type": "Task", + "Resource": "arn:aws:states:::states:startExecution.sync:2", + "Parameters": {"StateMachineArn": "%s"}, + "End": true + } + } + } + """.formatted(childArn)); + String executionArn = startExecution(parentArn); + waitForExecution(executionArn); + + Response response = given() + .header("X-Amz-Target", "AWSStepFunctions.GetExecutionHistory") + .contentType(SFN_CONTENT_TYPE) + .body(String.format(""" + {"executionArn": "%s"} + """, executionArn)) + .when() + .post("/"); + response.then().statusCode(200); + + JsonNode events = MAPPER.readTree(response.body().asString()).path("events"); + List types = new ArrayList<>(); + events.forEach(event -> types.add(event.path("type").asText())); + assertEquals(List.of("ExecutionStarted", "TaskStateEntered", "TaskScheduled", "TaskStarted", + "TaskSubmitted", "TaskSucceeded", "TaskStateExited", "ExecutionSucceeded"), types); + List expectedPreviousEventIds = List.of(0L, 0L, 2L, 3L, 4L, 5L, 6L, 7L); + for (int 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()); + } + + JsonNode submitted = events.get(4).path("taskSubmittedEventDetails"); + assertEquals("states", submitted.path("resourceType").asText()); + assertEquals("startExecution.sync:2", submitted.path("resource").asText()); + assertFalse(submitted.path("outputDetails").path("truncated").asBoolean(true)); + JsonNode output = MAPPER.readTree(submitted.path("output").asText()); + assertEquals(List.of("ExecutionArn", "StartDate"), fieldNames(output)); + String childExecutionPrefix = childArn.replace(":stateMachine:", ":execution:") + ":"; + assertTrue(output.path("ExecutionArn").asText().startsWith(childExecutionPrefix), output.toString()); + assertTrue(output.path("StartDate").isIntegralNumber(), output.toString()); + assertTrue(output.path("StartDate").asLong() > 1_000_000_000_000L, "epoch milliseconds: " + output); + // The same integration name on every event of the family, not startExecution.sync / 2. + assertEquals("startExecution.sync:2", events.get(2).path("taskScheduledEventDetails").path("resource").asText()); + assertEquals("startExecution.sync:2", events.get(5).path("taskSucceededEventDetails").path("resource").asText()); + } + + private static List fieldNames(JsonNode node) { + List names = new ArrayList<>(); + node.fieldNames().forEachRemaining(names::add); + return names; + } + private static String quote(String raw) { return "\"" + raw .replace("\\", "\\\\")