fix(stepfunctions): end an Express execution at its maximum execution time instead of letting it run on (#5864)

* fix(stepfunctions): end a synchronous execution at its maximum execution time instead of letting it run on

* test(stepfunctions): build AslExecutor in tests through a shared fixture

* fix(stepfunctions): keep the first outcome of a timed-out Express execution and limit asynchronous Express executions too

* fix(stepfunctions): time out an execution a late runtime error reaches, and measure its deadlines on an injectable clock

* test(stepfunctions): test the synchronous caller's timeout step directly instead of on the real clock
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-10-18 09:10:25 -04:00
1 parent 450321a001
commit 1ee87fc4e9
37 files changed
+804 -933

No files matched your search

@@ -124,6 +124,7 @@ 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.function.LongSupplier;
import java.util.stream.Collectors;
@ApplicationScoped
@@ -162,6 +163,9 @@ public class AslExecutor {
// How long a Task waits for its token, or for a .sync job to end, when the state declares no
// TimeoutSeconds. AWS lets it run for a year; the emulator would rather free the worker thread.
private static final int DEFAULT_TASK_TIMEOUT_SECONDS = 300;
// AWS's hard quota on an Express execution, synchronous or not.
private static final Duration EXPRESS_MAX_EXECUTION_TIME = Duration.ofMinutes(5);
private static final Set<String> TERMINAL_STATUSES = Set.of("SUCCEEDED", "FAILED", "TIMED_OUT", "ABORTED");
/**
* AWS ends an execution once its history reaches this many events. The count is neither reset
@@ -268,6 +272,9 @@ public class AslExecutor {
private final Sleeper sleeper;
// Null in production, where the ceiling comes from the Step Functions config. Tests pin it.
private final Integer maxWaitSecondsOverride;
private final Duration expressMaxExecutionTime;
// The monotonic clock every execution and task deadline is measured on. Tests move it forward.
private final LongSupplier nanoTime;
private final Map<String, ActiveMockExecution> activeMocks = new ConcurrentHashMap<>();
private final ExecutorService executor = Executors.newCachedThreadPool(r -> {
Thread t = new Thread(r, "sfn-executor");
@@ -294,7 +301,7 @@ public class AslExecutor {
eventBridgeHandler, schedulerService, schedulerController, rdsDataService,
objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,
Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, redshiftDataHandler, serviceRegistry,
lambdaTaskAuthorizer);
lambdaTaskAuthorizer, null, null);
}
AslExecutor(LambdaExecutorService lambdaExecutor, LambdaTargetResolver targetResolver,
@@ -310,7 +317,8 @@ public class AslExecutor {
CustomResourceLiveness customResourceLiveness,
Clock clock, Sleeper sleeper, Integer maxWaitSecondsOverride,
RedshiftDataJsonHandler redshiftDataHandler, ServiceRegistry serviceRegistry,
LambdaTaskAuthorizer lambdaTaskAuthorizer) {
LambdaTaskAuthorizer lambdaTaskAuthorizer, Duration expressMaxExecutionTimeOverride,
LongSupplier nanoTimeOverride) {
this.serviceRegistry = serviceRegistry;
this.lambdaTaskAuthorizer = lambdaTaskAuthorizer;
this.customResourceLiveness = customResourceLiveness;
@@ -343,6 +351,10 @@ public class AslExecutor {
this.clock = clock;
this.sleeper = sleeper;
this.maxWaitSecondsOverride = maxWaitSecondsOverride;
this.nanoTime = nanoTimeOverride != null ? nanoTimeOverride : System::nanoTime;
this.expressMaxExecutionTime = expressMaxExecutionTimeOverride != null
? expressMaxExecutionTimeOverride
: EXPRESS_MAX_EXECUTION_TIME;
if (vertx != null) {
// This can be optimized further
// TODO Set WebclientOptions useragent to Amazon|StepFunctions|HttpInvoke|{{{{region}}}}
@@ -369,7 +381,7 @@ public class AslExecutor {
ec2Service, s3Service, ecsService, ecsJsonHandler,
eventBridgeHandler, schedulerService, schedulerController, rdsDataService,
objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,
Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, null, null, null);
Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, null, null, null, null, null);
}
// Kept for tests that do not exercise the Redshift Data API integration.
@@ -390,7 +402,7 @@ public class AslExecutor {
ec2Service, s3Service, ecsService, ecsJsonHandler,
eventBridgeHandler, schedulerService, schedulerController, rdsDataService,
objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,
clock, sleeper, maxWaitSecondsOverride, null, null, null);
clock, sleeper, maxWaitSecondsOverride, null, null, null, null, null);
}
AslExecutor(LambdaExecutorService lambdaExecutor, LambdaFunctionStore functionStore,
@@ -458,9 +470,15 @@ public class AslExecutor {
MockedTestCase mockedTestCase,
BiConsumer<Execution, List<HistoryEvent>> onUpdate) {
registerMocks(exec, mockedTestCase);
// An Express execution has the same maximum execution time however it was started; a
// Standard one is allowed a year, which the emulator does not enforce.
long maxExecutionDeadlineNanos = "EXPRESS".equals(sm.getType())
? nanoTime.getAsLong() + expressMaxExecutionTime.toNanos()
: Long.MAX_VALUE;
executor.submit(() -> {
try {
runUnderExecutionAccount(sm, () -> doExecute(sm, exec, history, onUpdate));
runUnderExecutionAccount(sm,
() -> doExecute(sm, exec, history, onUpdate, maxExecutionDeadlineNanos));
} catch (RuntimeException | Error e) {
// submit() parks whatever the task throws in a Future nobody reads, so without this
// the worker dies silently. doExecute has already published the terminal status by
@@ -486,19 +504,37 @@ public class AslExecutor {
MockedTestCase mockedTestCase,
BiConsumer<Execution, List<HistoryEvent>> onUpdate) {
registerMocks(exec, mockedTestCase);
// The execution itself ends at this deadline, as it does at its TimeoutSeconds, so it runs
// no further state once the caller has been answered TIMED_OUT.
long maxExecutionDeadlineNanos = nanoTime.getAsLong() + expressMaxExecutionTime.toNanos();
try {
Future<?> f = executor.submit(() ->
runUnderExecutionAccount(sm, () -> doExecute(sm, exec, history, onUpdate)));
f.get(300, TimeUnit.SECONDS);
Future<?> f = executor.submit(() -> runUnderExecutionAccount(sm,
() -> doExecute(sm, exec, history, onUpdate, maxExecutionDeadlineNanos)));
f.get(maxExecutionDeadlineNanos - nanoTime.getAsLong(), TimeUnit.NANOSECONDS);
} catch (java.util.concurrent.TimeoutException e) {
exec.setStopDate(System.currentTimeMillis() / 1000.0);
exec.setStatus("TIMED_OUT");
onUpdate.accept(exec, history);
answerTimedOutUnlessEnded(exec, history, onUpdate);
} catch (Exception e) {
LOG.warnv("Sync execution wait failed for {0}: {1}", exec.getExecutionArn(), e.getMessage());
}
}
/**
* Answers a synchronous caller whose wait ran out. The worker ends itself at the same deadline;
* this publishes TIMED_OUT when it has not yet, and never replaces an outcome the worker already
* published.
*/
void answerTimedOutUnlessEnded(Execution exec, List<HistoryEvent> history,
BiConsumer<Execution, List<HistoryEvent>> onUpdate) {
synchronized (exec) {
if (hasEnded(exec)) {
return;
}
exec.setStopDate(System.currentTimeMillis() / 1000.0);
exec.setStatus("TIMED_OUT");
}
onUpdate.accept(exec, history);
}
/**
* Runs {@code body} on this worker thread under a CDI request scope whose account is
* the one encoded in the state machine ARN, so service integrations (Lambda, DynamoDB,
@@ -541,8 +577,9 @@ public class AslExecutor {
}
private void doExecute(StateMachine sm, Execution exec, List<HistoryEvent> history,
BiConsumer<Execution, List<HistoryEvent>> onUpdate) {
BiConsumer<Execution, List<HistoryEvent>> onUpdate, long maxExecutionDeadlineNanos) {
HistoryChain chain = HistoryChain.of(history);
long executionDeadlineNanos = maxExecutionDeadlineNanos;
try {
JsonNode definition = objectMapper.readTree(sm.getDefinition());
JsonNode states = definition.path("States");
@@ -550,11 +587,13 @@ public class AslExecutor {
String topLevelQueryLanguage = definition.path("QueryLanguage").asText("JSONPath");
JsonNode currentInput = parseInput(exec.getInput());
// The state machine's total budget, computed once so every state measures against the
// same instant. Long.MAX_VALUE stands for a definition with no TimeoutSeconds.
// same instant: the earlier of its TimeoutSeconds and the maximum execution time its
// workflow type allows. Long.MAX_VALUE stands for neither.
int timeoutSeconds = definition.path("TimeoutSeconds").asInt(0);
long executionDeadlineNanos = timeoutSeconds > 0
? System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds)
: Long.MAX_VALUE;
if (timeoutSeconds > 0) {
executionDeadlineNanos = Math.min(
nanoTime.getAsLong() + TimeUnit.SECONDS.toNanos(timeoutSeconds), maxExecutionDeadlineNanos);
}
JsonNode execContext = buildContext(exec, sm);
// Execution-scoped JSONata variables (the Assign field). Mutated in place as states
// assign, so later states observe earlier assignments.
@@ -562,7 +601,7 @@ public class AslExecutor {
String currentStateName = startAt;
while (currentStateName != null && !abortedByCaller(exec)) {
if (System.nanoTime() >= executionDeadlineNanos) {
if (nanoTime.getAsLong() >= executionDeadlineNanos) {
throw new ExecutionTimedOutException();
}
JsonNode stateDef = states.path(currentStateName);
@@ -575,6 +614,11 @@ public class AslExecutor {
stateResult = runState(chain, currentStateName, stateDef, currentInput, sm,
topLevelQueryLanguage, execContext, variables, executionDeadlineNanos);
} catch (FailStateException e) {
// A failure that came back after the deadline, like a late success, ends the
// execution as timed out.
if (nanoTime.getAsLong() >= executionDeadlineNanos) {
throw new ExecutionTimedOutException();
}
failExecution(exec, chain, e);
onUpdate.accept(exec, history);
return;
@@ -582,6 +626,11 @@ public class AslExecutor {
currentInput = stateResult.output();
currentStateName = stateResult.nextState();
}
// A last state that outran the deadline, such as an integration call that does not
// watch it, ends the execution as timed out rather than succeeded.
if (nanoTime.getAsLong() >= executionDeadlineNanos) {
throw new ExecutionTimedOutException();
}
succeedExecution(exec, chain, currentInput);
onUpdate.accept(exec, history);
@@ -593,6 +642,12 @@ public class AslExecutor {
// StopExecution already wrote ABORTED and sealed the history; the worker only stops.
onUpdate.accept(exec, history);
} catch (Exception e) {
if (nanoTime.getAsLong() >= executionDeadlineNanos) {
// Past the deadline the execution has timed out, whatever broke on the way there.
timeOutExecution(exec, chain);
onUpdate.accept(exec, history);
return;
}
LOG.warnv("ASL execution failed for {0}: {1}", exec.getExecutionArn(), e.getMessage());
// This path previously set only the status, leaving error and cause null forever on an
// execution DescribeExecution reports as FAILED.
@@ -1004,22 +1059,22 @@ public class AslExecutor {
long wakeAtNanos = Math.min(executionDeadlineNanos, Math.min(timeoutDeadlineNanos,
heartbeatDeadlineNanos(taskToken, heartbeatSeconds)));
try {
return future.get(wakeAtNanos - System.nanoTime(), TimeUnit.NANOSECONDS);
return future.get(wakeAtNanos - nanoTime.getAsLong(), TimeUnit.NANOSECONDS);
} catch (java.util.concurrent.TimeoutException e) {
// The execution's budget is read first: when it is the clock that ran out, the
// execution ends as TIMED_OUT and the task's own timeout never applies.
if (System.nanoTime() >= executionDeadlineNanos) {
if (nanoTime.getAsLong() >= executionDeadlineNanos) {
future.cancel(true);
throw new ExecutionTimedOutException();
}
if (System.nanoTime() >= timeoutDeadlineNanos) {
if (nanoTime.getAsLong() >= timeoutDeadlineNanos) {
future.cancel(true);
throw new TaskTimedOutException("States.Timeout");
}
// Read the gap again rather than trusting the one this thread parked on: a
// heartbeat that landed meanwhile has already moved it past now, and the task
// goes back to waiting on the later deadline.
if (System.nanoTime() >= heartbeatDeadlineNanos(taskToken, heartbeatSeconds)) {
if (nanoTime.getAsLong() >= heartbeatDeadlineNanos(taskToken, heartbeatSeconds)) {
future.cancel(true);
throw new TaskTimedOutException("States.HeartbeatTimeout");
}
@@ -1047,7 +1102,7 @@ public class AslExecutor {
if (timeoutSeconds <= 0) {
timeoutSeconds = DEFAULT_TASK_TIMEOUT_SECONDS;
}
return System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds);
return nanoTime.getAsLong() + TimeUnit.SECONDS.toNanos(timeoutSeconds);
}
/**
@@ -2726,7 +2781,7 @@ public class AslExecutor {
*/
private void sleepOrTimeOutTask(long pauseNanos, long executionDeadlineNanos, long taskDeadlineNanos)
throws InterruptedException {
long remainingNanos = Math.min(executionDeadlineNanos, taskDeadlineNanos) - System.nanoTime();
long remainingNanos = Math.min(executionDeadlineNanos, taskDeadlineNanos) - nanoTime.getAsLong();
if (pauseNanos < remainingNanos) {
sleeper.sleep(pauseNanos);
return;
@@ -2734,7 +2789,7 @@ public class AslExecutor {
sleeper.sleep(Math.max(remainingNanos, 0));
// The execution's budget wins when it is the clock that was parked on, and also when a late
// wake finds it spent: the execution ends TIMED_OUT and the Task's own timeout never applies.
if (executionDeadlineNanos <= taskDeadlineNanos || System.nanoTime() >= executionDeadlineNanos) {
if (executionDeadlineNanos <= taskDeadlineNanos || nanoTime.getAsLong() >= executionDeadlineNanos) {
throw new ExecutionTimedOutException();
}
throw new TaskTimedOutException("States.Timeout");
@@ -2833,7 +2888,7 @@ public class AslExecutor {
int timeoutSeconds = stateDef.path("TimeoutSeconds").asInt(0);
long stateDeadlineNanos = timeoutSeconds > 0
? System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds)
? nanoTime.getAsLong() + TimeUnit.SECONDS.toNanos(timeoutSeconds)
: Long.MAX_VALUE;
// Two clocks can end this wait, and the join stops at whichever comes first: the state's
// own TimeoutSeconds, and the state machine's budget for the whole execution.
@@ -2845,7 +2900,7 @@ public class AslExecutor {
int current = -1;
try {
for (int joined = 0; joined < futures.size(); joined++) {
long remainingNanos = joinDeadlineNanos - System.nanoTime();
long remainingNanos = joinDeadlineNanos - nanoTime.getAsLong();
if (remainingNanos <= 0) {
throw parallelJoinExpired(stateDeadlineNanos, timeoutSeconds);
}
@@ -2940,7 +2995,7 @@ public class AslExecutor {
* execution and no Catch sees it.
*/
private RuntimeException parallelJoinExpired(long stateDeadlineNanos, int timeoutSeconds) {
if (System.nanoTime() < stateDeadlineNanos) {
if (nanoTime.getAsLong() < stateDeadlineNanos) {
return new ExecutionTimedOutException();
}
return new FailStateException("States.Timeout",
@@ -5761,7 +5816,7 @@ public class AslExecutor {
*/
private void failExecution(Execution exec, HistoryChain chain, String error, String cause) {
synchronized (exec) {
if (abortedByCaller(exec)) {
if (hasEnded(exec)) {
return;
}
exec.setError(error);
@@ -5800,11 +5855,15 @@ public class AslExecutor {
*/
private void timeOutExecution(Execution exec, HistoryChain chain) {
synchronized (exec) {
if (abortedByCaller(exec)) {
return;
// A synchronous caller may have published the timeout already; the event still ends
// the history. Any other outcome already published stands.
if (!"TIMED_OUT".equals(exec.getStatus())) {
if (hasEnded(exec)) {
return;
}
exec.setStopDate(System.currentTimeMillis() / 1000.0);
exec.setStatus("TIMED_OUT");
}
exec.setStopDate(System.currentTimeMillis() / 1000.0);
exec.setStatus("TIMED_OUT");
}
chain.end("ExecutionTimedOut", 0L, Map.of("error", "States.Timeout"));
}
@@ -5818,7 +5877,7 @@ public class AslExecutor {
*/
private void succeedExecution(Execution exec, HistoryChain chain, JsonNode output) {
synchronized (exec) {
if (abortedByCaller(exec)) {
if (hasEnded(exec)) {
return;
}
exec.setOutput(output.toString());
@@ -5831,9 +5890,7 @@ public class AslExecutor {
/**
* True once StopExecution published ABORTED on this execution. The state loop reads it between
* states and every terminal write here reads it before publishing, so the worker's own status
* loses the race against a stop that arrived while it was still stepping: what a caller has
* already read back from DescribeExecution is what stands.
* states, so the worker stops stepping once a caller has stopped it.
*/
private static boolean abortedByCaller(Execution exec) {
synchronized (exec) {
@@ -5841,6 +5898,18 @@ public class AslExecutor {
}
}
/**
* True once any outcome has been published on this execution: a stop from StopExecution, a
* synchronous caller answered with TIMED_OUT, or the worker's own. Every terminal write reads
* it before publishing, so the first outcome stands: what a caller has already read back from
* DescribeExecution or StartSyncExecution is never replaced.
*/
private static boolean hasEnded(Execution exec) {
synchronized (exec) {
return TERMINAL_STATUSES.contains(exec.getStatus());
}
}
/**
* The same read for a wait that has only the execution's ARN: a {@code .sync} poll loop. An
* execution the store no longer holds is treated as stopped, since nothing is waiting for the