fix(stepfunctions): record TaskSubmitted for a .sync Task, named as AWS names it (#4719)

* fix(stepfunctions): record TaskSubmitted for a .sync Task, named as AWS names it

AWS records TaskSubmitted for every .sync Task once the call that starts
the job has returned and before it waits on the job, chained to
TaskStarted and carrying that call's response as output in PascalCase:
{ExecutionArn, StartDate} in epoch milliseconds for states:startExecution
.sync and .sync:2, {Failures, Tasks} for ecs:runTask.sync. Floci recorded
nothing between TaskStarted and the terminal event, so a client reading
the job's id from the history found nothing until the Task ended.

The two poll loops do not have the HistoryChain; invokeResource hands
them a callback that publishes the event. The SDK's SdkHttpMetadata and
SdkResponseMetadata, which AWS folds into the response, are left out,
as everywhere else in Floci.

The task event profile also split a well-formed integration id at its
last colon, so every event of a .sync:2 Task read resourceType
states:startExecution.sync, resource 2. AWS reports states /
startExecution.sync:2, so a parsed id now splits at its service.

Closes #4648

* test(stepfunctions): name the types in the TaskSubmitted history test

* fix(stepfunctions): stop the job when TaskSubmitted cannot be recorded

TaskSubmitted is the first event after the job exists. When it is the
event that hits the 25,000-event history limit, the publish throws
before the poll loop whose catch stops the job is entered, so the parent
failed with States.Runtime while the child execution or ECS task ran on.
Both loops now abort the job on that path, the way the wait would have.

---------

Co-authored-by: mitsukado-shinagawa <mitsukado-shinagawa@users.noreply.github.com>
This commit is contained in:
mitsukado-shinagawaandmitsukado-shinagawa authored and GitHub committed 2026-09-30 06:35:09 -04:00
1 parent 560de5c13f
commit 2eadc106c5
5 files changed
+330 -17

No files matched your search

@@ -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<String> 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<HistoryEvent> 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<String> fieldNames(JsonNode node) {
List<String> 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<HistoryEvent> 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;
}
@@ -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<HistoryEvent> 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<HistoryEvent> 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<HistoryEvent>(), (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<HistoryEvent> 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<String> types() {
return history.stream().map(HistoryEvent::getType).toList();
}
}
@@ -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<String> 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<Long> 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<String> fieldNames(JsonNode node) {
List<String> names = new ArrayList<>();
node.fieldNames().forEachRemaining(names::add);
return names;
}
private static String quote(String raw) {
return "\"" + raw
.replace("\\", "\\\\")