fix(stepfunctions): bound a .sync Task by its TimeoutSeconds, not by a poll count (#4519)

* fix(stepfunctions): bound a .sync Task by its TimeoutSeconds, not by a poll count

A Task waiting on ecs:runTask.sync or states:startExecution.sync gave up
after 600 polls at 100 ms, about 60 seconds, whatever its TimeoutSeconds
said; that clock was read for a task-token wait alone. The deadline is
now computed once at schedule time and shared by awaitToken and both
.sync loops, which poll until it or the execution's budget fires. The
Task's clock ends the state as States.Timeout with a TaskTimedOut event
and no cause, the shape the token wait already used.

Closes #4518

* fix(stepfunctions): stop the job a timed-out .sync Task was waiting on

Measured on AWS: when a Task's TimeoutSeconds fires around an
ecs:runTask.sync or states:startExecution.sync, Step Functions stops
the ECS task (stopCode UserInitiated) or aborts the child execution,
both with the cause "The Task state in AWS Step Functions execution
[<arn>] which was managing this resource was aborted". Floci left the
job running. Best effort, like AWS: a job already gone is logged and
the timeout is still what the state reports.

* fix(stepfunctions): end a .sync wait on StopExecution and start its clock at schedule time

Review follow-ups on #4519. The Task's TimeoutSeconds is read before the
scheduled event is built, so a large input cannot extend it. A late wake
re-reads the execution's clock, so a spent budget ends the execution
TIMED_OUT rather than the Task. Both .sync loops read the execution back
each poll and, once StopExecution has marked it ABORTED, stop the job and
unwind without writing an event, instead of polling until a clock ran
out. Tests cover .sync:2 under a Catch on States.Timeout and the aborted
parent; the nested test imports its types.

* docs(stepfunctions): drop the two em dashes the .sync timeout change added

* chore(stepfunctions): let sleepOrTimeOutExecution delegate to sleepOrTimeOutTask

With no Task deadline (Long.MAX_VALUE) sleepOrTimeOutTask parks on the
execution's budget alone and ends the execution TIMED_OUT, which is
exactly what sleepOrTimeOutExecution did in its own copy.

---------

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-29 07:05:49 -04:00
1 parent 071a170ce9
commit ac41ff339a
4 files changed
+559 -44

No files matched your search

@@ -8,6 +8,8 @@ import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;
import io.github.hectorvent.floci.services.ecs.EcsService;
import io.github.hectorvent.floci.services.ecs.container.HostVolumePolicy;
import io.github.hectorvent.floci.services.ecs.model.Container;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration;
import io.github.hectorvent.floci.services.lambda.LambdaExecutorService;
import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore;
@@ -21,16 +23,22 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.time.Clock;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
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.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.verify;
import static org.mockito.Mockito.when;
@@ -43,7 +51,9 @@ import static org.mockito.Mockito.when;
* <li>{@code .sync} (and {@code .waitForTaskToken}) fail the state on a placement failure,
* using the AWS error name {@code AmazonECS.Unknown};</li>
* <li>an awsvpc {@code NetworkConfiguration} in the parameters is parsed and passed to runTask
* rather than dropped.</li>
* rather than dropped;</li>
* <li>a {@code .sync} wait is bounded by the Task's {@code TimeoutSeconds} and by the execution's
* budget, and by nothing else: no poll count of its own cuts a long-running task short.</li>
* </ul>
*/
class AslExecutorEcsRunTaskModeTest {
@@ -53,16 +63,28 @@ class AslExecutorEcsRunTaskModeTest {
private final ObjectMapper objectMapper = new ObjectMapper();
private EcsService ecsService;
private StepFunctionsService sfnService;
private AslExecutor executor;
private List<HistoryEvent> history;
@BeforeEach
void setUp() {
ecsService = mock(EcsService.class);
// The .sync wait reads the execution back to notice a StopExecution; RUNNING unless a test says otherwise.
sfnService = mock(StepFunctionsService.class);
when(sfnService.describeExecution(any())).thenAnswer(invocation -> parent(invocation.getArgument(0), "RUNNING"));
executor = newExecutor(TimeUnit.NANOSECONDS::sleep);
}
@SuppressWarnings("unchecked")
private AslExecutor newExecutor(AslExecutor.Sleeper sleeper) {
// A real handler so parseNetworkConfiguration / parseContainerOverrides actually run.
EcsJsonHandler ecsJsonHandler = new EcsJsonHandler(ecsService, objectMapper,
new HostVolumePolicy(mock(EmulatorConfig.class, RETURNS_DEEP_STUBS)));
Instance<StepFunctionsService> instance = mock(Instance.class);
when(instance.get()).thenReturn(sfnService);
executor = new AslExecutor(
return new AslExecutor(
mock(LambdaExecutorService.class),
mock(LambdaFunctionStore.class),
mock(DynamoDbFacade.class),
@@ -78,9 +100,12 @@ class AslExecutorEcsRunTaskModeTest {
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
objectMapper,
new JsonataEvaluator(objectMapper),
mock(Instance.class),
instance,
mock(EmulatorConfig.class),
null,
null,
Clock.systemUTC(),
sleeper,
null);
}
@@ -144,16 +169,142 @@ class AslExecutorEcsRunTaskModeTest {
assertEquals("ENABLED", passed.getAwsvpcConfiguration().getAssignPublicIp());
}
@Test
void syncFailsWithStatesTimeoutWhenTheTaskOutlivesTimeoutSeconds() throws Exception {
launchOneTask();
when(ecsService.describeTasks(any(), any(), any())).thenReturn(List.of(task("RUNNING")));
Execution execution = runDefinition("""
{
"StartAt": "RunTask",
"States": {
"RunTask": { "Type": "Task", "Resource": "arn:aws:states:::ecs:runTask.sync",
"TimeoutSeconds": 1, "End": true }
}
}
""", "{\"TaskDefinition\":\"my-task-def\"}");
assertEquals("FAILED", execution.getStatus());
assertEquals("States.Timeout", execution.getError());
assertNull(execution.getCause(), "a timeout carries no cause");
HistoryEvent timedOut = history.stream()
.filter(event -> "TaskTimedOut".equals(event.getType()))
.findFirst().orElseThrow(() -> new AssertionError("no TaskTimedOut event in " + history));
assertEquals("ecs", timedOut.getDetails().get("resourceType"));
assertEquals("States.Timeout", timedOut.getDetails().get("error"));
// AWS stops the task it was waiting on, with this exact stoppedReason (measured).
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 syncIsNotCappedByAPollCountWhenNoTimeoutSecondsIsDeclared() throws Exception {
// The former loop gave up after 600 polls. A task that stops on the 700th read must still
// succeed: without a TimeoutSeconds only the emulator's default bound applies, and the
// no-op sleeper keeps that from being real time.
executor = newExecutor(nanos -> { });
launchOneTask();
AtomicInteger polls = new AtomicInteger();
when(ecsService.describeTasks(any(), any(), any()))
.thenAnswer(invocation -> List.of(task(polls.incrementAndGet() < 700 ? "RUNNING" : "STOPPED")));
Execution execution = run("arn:aws:states:::ecs:runTask.sync",
"{\"TaskDefinition\":\"my-task-def\"}");
assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause());
assertEquals(700, polls.get());
assertEquals("STOPPED", objectMapper.readTree(execution.getOutput()).path("LastStatus").asText());
}
@Test
void executionBudgetCutsASyncWaitBeforeTheTasksOwnTimeout() throws Exception {
launchOneTask();
when(ecsService.describeTasks(any(), any(), any())).thenReturn(List.of(task("RUNNING")));
Execution execution = runDefinition("""
{
"StartAt": "RunTask",
"TimeoutSeconds": 1,
"States": {
"RunTask": { "Type": "Task", "Resource": "arn:aws:states:::ecs:runTask.sync",
"TimeoutSeconds": 60, "End": true }
}
}
""", "{\"TaskDefinition\":\"my-task-def\"}");
assertEquals("TIMED_OUT", execution.getStatus());
assertNull(execution.getError());
verify(ecsService, never()).stopTask(any(), any(), any(), any());
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 stopExecutionEndsTheSyncWaitAndStopsTheTask() throws Exception {
executor = newExecutor(nanos -> { });
launchOneTask();
AtomicInteger parentReads = new AtomicInteger();
when(sfnService.describeExecution(any()))
.thenAnswer(invocation -> parent(invocation.getArgument(0), parentReads.incrementAndGet() < 3 ? "RUNNING" : "ABORTED"));
AtomicInteger polls = new AtomicInteger();
when(ecsService.describeTasks(any(), any(), any())).thenAnswer(invocation -> {
polls.incrementAndGet();
return List.of(task("RUNNING"));
});
Execution execution = run("arn:aws:states:::ecs:runTask.sync",
"{\"TaskDefinition\":\"my-task-def\"}");
assertEquals(2, polls.get(), "polling stops as soon as the execution reads ABORTED");
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));
List<String> types = history.stream().map(HistoryEvent::getType).toList();
assertTrue(types.stream().noneMatch(type -> type.equals("TaskTimedOut") || type.equals("TaskFailed")
|| type.equals("ExecutionFailed") || type.equals("ExecutionSucceeded")),
"an aborted execution gets no terminal event from the worker: " + types);
}
private static Execution parent(String executionArn, String status) {
Execution parent = new Execution();
parent.setExecutionArn(executionArn);
parent.setStatus(status);
return parent;
}
private void launchOneTask() {
when(ecsService.runTask(any(), any(), anyInt(), any(), any(), any(), any(), any(), any()))
.thenReturn(List.of(task("PENDING")));
}
private static EcsTask task(String lastStatus) {
EcsTask task = new EcsTask();
task.setTaskArn("arn:aws:ecs:%s:%s:task/default/0123456789abcdef".formatted(REGION, ACCOUNT));
task.setClusterArn("arn:aws:ecs:%s:%s:cluster/default".formatted(REGION, ACCOUNT));
task.setLastStatus(lastStatus);
Container container = new Container();
container.setName("runner");
if ("STOPPED".equals(lastStatus)) {
container.setExitCode(0);
}
task.setContainers(List.of(container));
return task;
}
private Execution run(String resource, String input) {
String definition = """
return runDefinition("""
{
"StartAt": "RunTask",
"States": {
"RunTask": { "Type": "Task", "Resource": "%s", "End": true }
}
}
""".formatted(resource);
""".formatted(resource), input);
}
private Execution runDefinition(String definition, String input) {
StateMachine stateMachine = new StateMachine();
stateMachine.setName("ecs-runtask-test");
stateMachine.setStateMachineArn("arn:aws:states:%s:%s:stateMachine:ecs-runtask-test".formatted(REGION, ACCOUNT));
@@ -166,7 +317,7 @@ class AslExecutorEcsRunTaskModeTest {
execution.setStateMachineArn(stateMachine.getStateMachineArn());
execution.setInput(input);
List<HistoryEvent> history = new ArrayList<>();
history = new ArrayList<>();
executor.executeSync(stateMachine, execution, history, (updated, events) -> { });
return execution;
}
@@ -0,0 +1,230 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
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.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
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.never;
import static org.mockito.Mockito.verify;
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.
*/
class AslExecutorNestedSyncTimeoutTest {
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 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("RUNNING"));
when(sfnService.describeExecution(PARENT_ARN)).thenReturn(parent("RUNNING"));
}
@Test
void syncFailsWithStatesTimeoutWhenTheChildOutlivesTimeoutSeconds() {
when(sfnService.describeExecution(CHILD_ARN)).thenReturn(child("RUNNING"));
Execution execution = run(newExecutor(TimeUnit.NANOSECONDS::sleep), ".sync", 1, false);
assertEquals("FAILED", execution.getStatus());
assertEquals("States.Timeout", execution.getError());
assertNull(execution.getCause());
HistoryEvent timedOut = history.stream()
.filter(event -> "TaskTimedOut".equals(event.getType()))
.findFirst().orElseThrow(() -> new AssertionError("no TaskTimedOut event in " + history));
assertEquals("states", timedOut.getDetails().get("resourceType"));
// AWS aborts the child it was waiting on: no error, this exact cause (measured).
verify(sfnService).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());
}
@Test
void sync2TimeoutIsCaughtUnderStatesTimeout() throws Exception {
when(sfnService.describeExecution(CHILD_ARN)).thenReturn(child("RUNNING"));
Execution execution = run(newExecutor(TimeUnit.NANOSECONDS::sleep), ".sync:2", 1, true);
assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause());
JsonNode output = objectMapper.readTree(execution.getOutput());
assertEquals("States.Timeout", output.path("Error").asText());
assertTrue(history.stream().anyMatch(event -> "TaskTimedOut".equals(event.getType())));
verify(sfnService).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());
}
@Test
void syncIsNotCappedByAPollCountWhenNoTimeoutSecondsIsDeclared() throws Exception {
AtomicInteger polls = new AtomicInteger();
when(sfnService.describeExecution(CHILD_ARN)).thenAnswer(invocation -> {
if (polls.incrementAndGet() < 700) {
return child("RUNNING");
}
Execution done = child("SUCCEEDED");
done.setOutput("{\"answer\":42}");
return done;
});
Execution execution = run(newExecutor(nanos -> { }), ".sync", 0, false);
assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause());
assertEquals(700, polls.get());
assertTrue(objectMapper.readTree(execution.getOutput()).path("output").asText().contains("42"));
verify(sfnService, never()).stopExecution(any(), any(), any());
}
@Test
void stopExecutionOnTheParentEndsTheWaitAndAbortsTheChild() {
AtomicInteger parentReads = new AtomicInteger();
when(sfnService.describeExecution(PARENT_ARN))
.thenAnswer(invocation -> parent(parentReads.incrementAndGet() < 3 ? "RUNNING" : "ABORTED"));
AtomicInteger childPolls = new AtomicInteger();
when(sfnService.describeExecution(CHILD_ARN)).thenAnswer(invocation -> {
childPolls.incrementAndGet();
return child("RUNNING");
});
run(newExecutor(nanos -> { }), ".sync", 0, false);
assertEquals(2, childPolls.get(), "polling stops as soon as the parent reads ABORTED");
verify(sfnService).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());
List<String> types = history.stream().map(HistoryEvent::getType).toList();
assertTrue(types.stream().noneMatch(type -> type.equals("TaskTimedOut")
|| type.equals("TaskFailed") || type.startsWith("Execution")
&& !type.equals("ExecutionStarted")), "an aborted execution gets no terminal event from the worker: " + types);
}
private static Execution child(String status) {
Execution current = new Execution();
current.setExecutionArn(CHILD_ARN);
current.setStateMachineArn(CHILD_SM_ARN);
current.setName("run-1");
current.setStatus(status);
current.setStartDate(1.0);
return current;
}
private static Execution parent(String status) {
Execution current = new Execution();
current.setExecutionArn(PARENT_ARN);
current.setStatus(status);
return current;
}
@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,
null);
}
private Execution run(AslExecutor executor, String mode, int timeoutSeconds, boolean catchTimeout) {
String timeout = timeoutSeconds > 0 ? "\"TimeoutSeconds\": %d,".formatted(timeoutSeconds) : "";
String catcher = catchTimeout
? "\"Catch\": [{\"ErrorEquals\": [\"States.Timeout\"], \"Next\": \"Recover\"}],"
: "";
String definition = """
{
"StartAt": "Child",
"States": {
"Child": {
"Type": "Task",
"Resource": "arn:aws:states:::states:startExecution%s",
%s
%s
"Parameters": { "StateMachineArn": "%s" },
"End": true
},
"Recover": { "Type": "Pass", "End": true }
}
}
""".formatted(mode, timeout, catcher, CHILD_SM_ARN);
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<>();
executor.executeSync(stateMachine, execution, history, (updated, events) -> { });
return execution;
}
}