fix(stepfunctions): bound a running execution the four ways AWS does (#2782)

* fix(stepfunctions): enforce both TimeoutSeconds clocks

The state machine's top-level TimeoutSeconds was read back by
DescribeStateMachine and copied into activityScheduledEventDetails but
never used as a deadline, so an execution ran to completion however long
it took. Compute the budget once in doExecute, check it before every
state and inside the Wait sleep, and end the execution TIMED_OUT with
stopDate set, no error, no cause, and one ExecutionTimedOut event
carrying States.Timeout and previousEventId 0.

A Task's two bounds were swapped: HeartbeatSeconds acted as the total
wait and TimeoutSeconds was decorative, so "TimeoutSeconds": 5,
"HeartbeatSeconds": 60 failed at 60 seconds instead of 5. awaitToken now
bounds the whole wait with TimeoutSeconds and the gap between heartbeats
with HeartbeatSeconds. SendTaskHeartbeat only logged, so the gap bound
needed a per-token timestamp: the service now records one when the token
is registered and again on every heartbeat, and forgets it when the
waiting task stops listening.

Either clock ends the state as a TaskTimedOutException, which is what
us-east-1 answers for a heartbeat expiry: an ActivityTimedOut event
carrying error States.Timeout and no cause, then an execution reading
FAILED with error States.Timeout and no cause key, over the six-event
history ExecutionStarted, TaskStateEntered, ActivityScheduled,
ActivityStarted, ActivityTimedOut, ExecutionFailed. A Catch still
matches a heartbeat expiry under States.HeartbeatTimeout, so ErrorEquals
matching now asks the failure which names it answers to rather than
comparing one string.

The Wait sleep stops at the execution deadline instead of sleeping its
full duration first, which would have reported the timeout as many
seconds late as the Wait outlasts the budget and left a WaitStateExited
behind for a state AWS never finished. awaitToken discards its token on
the way out; without that the token would stay pending for the life of
the process and a later SendTaskSuccess would be answered as if someone
were still waiting.

Neither timeout carries a cause, so failExecution now reads a null cause
as the failure having none and leaves the key out of both
DescribeExecution and the ExecutionFailed event. The two other failures
that reach it without a cause -- a Fail state with no Cause, and
SendTaskFailure with no cause -- keep reporting an empty one, since
AWS's shape for those is unmeasured.

Refs #2733

* fix(stepfunctions): bound an execution's history and make StopExecution stop it

AWS puts two bounds on a running execution that floci did not: it ends one that
reaches 25,000 history events with States.Runtime, event 25,000 being the
ExecutionFailed event itself, and StopExecution stops the worker rather than
relabelling an execution that goes on to overwrite the status it wrote.

Counting an event against that limit and numbering it in the published history
are two meanings that one AtomicLong was carrying. They are separated here.
producedEventCount counts every event the execution produces, the top-level
flow's and those of its Parallel branches and inline Map iterations alike, and
is what the limit judges. The published history numbers its own events: an
event's id is its position in the list, which makes the list the only authority
for the next id, where the counter and the seal in StepFunctionsService used to
be a second one that agreed with it only at rest. A branch's events are counted
and never built, so executeBranch no longer assembles HistoryEvent objects with
full input and output JSON into a list it throws away.

A Distributed Map runs each item as a child execution on AWS, and a child
execution has a history of its own, so its items are counted against their own
limit rather than the parent's: a Distributed Map over 13,000 items no longer
fails the parent partway through with States.Runtime.

The count is taken before it is judged. Reading it and then taking it let 40
concurrent inline Map iterations through the same check and spent more events
than the execution had.

StopExecution records its abort against a history that need not be in memory.
Executions are stored and histories are not, so a restart in persistent mode
brings a RUNNING execution back with nothing behind it, and the same window
opens between a reset emptying the cache and emptying the store; the abort was
written to the store and then thrown away as a 500.

* fix(stepfunctions): end an execution that spends its budget waiting

A state machine's TimeoutSeconds budget was read only between states and
around the two pauses a definition asks for, a Wait and a Retry backoff. Every
other way a state blocks outlasted it: a Task waiting for its token, a
states:startExecution.sync or ecs:runTask.sync poll, and a Parallel or Map
waiting for its branches. Those executions ended past their budget, and ended
FAILED or SUCCEEDED rather than TIMED_OUT.

Each of those waits now stops at the budget, and the Task path publishes no
failure event for the state it cuts. Measured against us-east-1: a state
machine with TimeoutSeconds 5 over an activity Task whose own TimeoutSeconds
is 60 stops at exactly 5.000 s with status TIMED_OUT, and its history is
ExecutionStarted, TaskStateEntered, ActivityScheduled, ExecutionTimedOut, with
no ActivityTimedOut and no ExecutionFailed.

---------

Co-authored-by: Facundo Paredes <naranjax@MAC-69786.local>
This commit is contained in:
Facundo ParedesandFacundo Paredes authored and GitHub committed 2026-08-30 18:40:07 -04:00
1 parent 2480daaa09
commit 9288769607
11 files changed
+1985 -173

No files matched your search

@@ -0,0 +1,377 @@
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.dynamodb.DynamoDbJsonHandler;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
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.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 io.quarkus.test.junit.QuarkusTest;
import io.vertx.mutiny.core.Vertx;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
/**
* Guards the bound AWS puts on a running execution: a state machine that never reaches a terminal
* state is ended at 25,000 history events with {@code States.Runtime}. The cut is an event count,
* not a wall clock, and the counter is neither reset nor offset: the {@code ExecutionFailed} event
* is event 25,000 itself, so the last event the machine produced is 24,999.
*
* <p>A {@code Choice} that loops back through a {@code Pass} reaches it in a few hundred
* milliseconds, which is why nothing here waits on the clock.
*/
@QuarkusTest
class AslExecutorHistoryEventLimitTest {
private static final String REGION = "us-east-2";
private static final String ACCOUNT = "000000000000";
/** A Choice that spins forever, four history events per lap and no terminal state. */
private static final String RUNAWAY_LOOP = """
{
"StartAt": "Loop",
"States": {
"Loop": {
"Type": "Choice",
"Choices": [{"Variable": "$.spin", "BooleanEquals": true, "Next": "Tick"}],
"Default": "Done"
},
"Tick": {"Type": "Pass", "Next": "Loop"},
"Done": {"Type": "Succeed"}
}
}
""";
/**
* A Parallel branch that laps 10,000 times, four history events per lap. The lap count is high
* enough that the branch alone produces far more than 25,000 events, and finite so the run ends
* either way: bounded, at event 25,000; unbounded, by finishing every lap.
*/
private static final String RUNAWAY_PARALLEL_BRANCH = """
{
"QueryLanguage": "JSONata",
"StartAt": "Seed",
"States": {
"Seed": {"Type": "Pass", "Assign": {"laps": 0}, "Next": "Fan"},
"Fan": {
"Type": "Parallel",
"Branches": [{
"StartAt": "Spin",
"States": {
"Spin": {
"Type": "Choice",
"Choices": [{"Condition": "{% $laps < 10000 %}", "Next": "Tick"}],
"Default": "Stop"
},
"Tick": {"Type": "Pass", "Assign": {"laps": "{% $laps + 1 %}"}, "Next": "Spin"},
"Stop": {"Type": "Succeed"}
}
}],
"End": true
}
}
}
""";
/**
* The same runaway branch under a Parallel that declares a Retry and a Catch for States.ALL,
* the two clauses AWS allows on a Parallel. Reaching the limit is States.Runtime, which
* catchMatches refuses before it reads ErrorEquals, so neither clause runs.
*/
private static final String RUNAWAY_PARALLEL_BRANCH_UNDER_RETRY_AND_CATCH = """
{
"QueryLanguage": "JSONata",
"StartAt": "Seed",
"States": {
"Seed": {"Type": "Pass", "Assign": {"laps": 0}, "Next": "Fan"},
"Fan": {
"Type": "Parallel",
"Retry": [{"ErrorEquals": ["States.ALL"], "IntervalSeconds": 30, "MaxAttempts": 3}],
"Catch": [{"ErrorEquals": ["States.ALL"], "Next": "Recovered"}],
"Branches": [{
"StartAt": "Spin",
"States": {
"Spin": {
"Type": "Choice",
"Choices": [{"Condition": "{% $laps < 10000 %}", "Next": "Tick"}],
"Default": "Stop"
},
"Tick": {"Type": "Pass", "Assign": {"laps": "{% $laps + 1 %}"}, "Next": "Spin"},
"Stop": {"Type": "Succeed"}
}
}],
"Next": "Recovered"
},
"Recovered": {"Type": "Succeed"}
}
}
""";
/**
* More items than the 25,000-event limit has room for: each one enters and exits a single Pass,
* so 13,000 items are 26,000 events if the parent is charged for them.
*/
private static final int DISTRIBUTED_MAP_ITEMS = 13_000;
/** One item per iteration, run one at a time so the run is the same on every machine. */
private static final String DISTRIBUTED_MAP_OVER_MANY_ITEMS = """
{
"StartAt": "Fan",
"States": {
"Fan": {
"Type": "Map",
"ItemsPath": "$.items",
"MaxConcurrency": 1,
"ItemProcessor": {
"ProcessorConfig": {"Mode": "DISTRIBUTED", "ExecutionType": "STANDARD"},
"StartAt": "Handle",
"States": {"Handle": {"Type": "Pass", "End": true}}
},
"End": true
}
}
}
""";
/**
* The same items run inline, 40 at a time. An inline Map's iterations are part of this
* execution, so together they run it out of history events while 40 of them are in flight.
*/
private static final String INLINE_MAP_OVER_MANY_ITEMS = """
{
"StartAt": "Fan",
"States": {
"Fan": {
"Type": "Map",
"ItemsPath": "$.items",
"MaxConcurrency": 40,
"ItemProcessor": {
"StartAt": "Handle",
"States": {"Handle": {"Type": "Pass", "End": true}}
},
"End": true
}
}
}
""";
private final ObjectMapper objectMapper = new ObjectMapper();
private final List<HistoryEvent> history = new ArrayList<>();
private AslExecutor executor;
@Inject
Vertx vertx;
@BeforeEach
void setUp() {
executor = new AslExecutor(
mock(LambdaExecutorService.class),
mock(LambdaFunctionStore.class),
mock(DynamoDbService.class),
mock(DynamoDbJsonHandler.class),
mock(SqsJsonHandler.class),
mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class),
mock(io.github.hectorvent.floci.services.ec2.Ec2Service.class),
mock(S3Service.class),
mock(io.github.hectorvent.floci.services.ecs.EcsService.class),
mock(io.github.hectorvent.floci.services.ecs.EcsJsonHandler.class),
mock(io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerService.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
objectMapper,
new JsonataEvaluator(objectMapper),
mock(Instance.class), mock(EmulatorConfig.class), vertx, null);
}
@Test
void runawayLoopFailsWithTheHistoryEventLimitError() {
Execution execution = run(RUNAWAY_LOOP);
assertEquals("FAILED", execution.getStatus());
assertEquals("States.Runtime", execution.getError());
assertEquals("The execution reached the maximum number of history events (25000).",
execution.getCause());
assertNotNull(execution.getStopDate());
}
@Test
void executionFailedIsTheTwentyFiveThousandthEvent() {
run(RUNAWAY_LOOP);
assertEquals(25000, history.size());
HistoryEvent last = history.get(history.size() - 1);
assertEquals("ExecutionFailed", last.getType());
assertEquals(25000L, last.getId());
// Not reset and not offset: 24,999 is the last event the machine itself produced.
HistoryEvent lastFromTheMachine = history.get(history.size() - 2);
assertEquals(24999L, lastFromTheMachine.getId());
assertNotEquals("ExecutionFailed", lastFromTheMachine.getType());
}
@Test
void eventsProducedInsideAParallelBranchCountTowardsTheLimit() {
Execution execution = run(RUNAWAY_PARALLEL_BRANCH);
assertEquals("FAILED", execution.getStatus());
assertEquals("States.Runtime", execution.getError());
assertEquals("The execution reached the maximum number of history events (25000).",
execution.getCause());
}
/**
* The branch produced the events that ran the execution out of them, and floci publishes none
* of them. What the caller reads back is the four events the top-level flow did produce, ending
* in the failure: an unbroken chain, not four events numbered as if 25,000 had happened.
*/
@Test
void aParallelBranchLeavesThePublishedHistoryUnbroken() {
run(RUNAWAY_PARALLEL_BRANCH);
assertEquals(List.of("PassStateEntered", "PassStateExited", "ParallelStateEntered",
"ExecutionFailed"),
history.stream().map(HistoryEvent::getType).toList());
for (int index = 0; index < history.size(); index++) {
assertEquals(index + 1L, history.get(index).getId(), "unexpected id at index " + index);
assertEquals((long) index, history.get(index).getPreviousEventId(),
"unexpected previousEventId at index " + index);
}
}
/**
* A Distributed Map runs each item as a child execution, and a child execution has a history of
* its own. The parent is charged for the Map run, not for what the items do inside it, so a
* Distributed Map over more items than the limit has room for still succeeds.
*/
@Test
void aDistributedMapItemDoesNotSpendTheParentsHistoryEvents() {
Execution execution = run(DISTRIBUTED_MAP_OVER_MANY_ITEMS, manyItemsInput());
assertEquals("SUCCEEDED", execution.getStatus(),
"error=" + execution.getError() + " cause=" + execution.getCause());
}
/**
* The same items run inline are the execution's own, whatever the concurrency: 40 iterations
* counting against one limit run it out of history events, where a Distributed Map's items do
* not.
*/
@Test
void concurrentInlineMapIterationsSpendTheExecutionsHistoryEvents() {
Execution execution = run(INLINE_MAP_OVER_MANY_ITEMS, manyItemsInput());
assertEquals("FAILED", execution.getStatus());
assertEquals("States.Runtime", execution.getError());
assertEquals("The execution reached the maximum number of history events (25000).",
execution.getCause());
}
/**
* The event that reaches the limit is what ends the execution, so exactly one of the iterations
* racing for the last countable event may take it. Reading the count and then taking it lets
* every racer through the check and spends more events than the execution has.
*/
@Test
void onlyOneOfTheThreadsRacingForTheLastCountableEventTakesIt() throws Exception {
int racers = 40;
// 24,998 events produced: one is left before the limit, and event 25,000 is the failure.
AtomicLong producedEventCount = new AtomicLong(24_998);
CountDownLatch ready = new CountDownLatch(racers);
CountDownLatch go = new CountDownLatch(1);
AtomicInteger counted = new AtomicInteger();
List<Thread> racerThreads = new ArrayList<>();
for (int racer = 0; racer < racers; racer++) {
Thread thread = new Thread(() -> {
ready.countDown();
try {
go.await();
AslExecutor.countTowardsHistoryEventLimit(producedEventCount);
counted.incrementAndGet();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (AslExecutor.FailStateException expected) {
// The limit was already reached by another racer.
}
});
racerThreads.add(thread);
thread.start();
}
ready.await();
go.countDown();
for (Thread thread : racerThreads) {
thread.join();
}
assertEquals(1, counted.get(), "more than one racer took the last countable event");
}
/** {@code {"items": [0, 1, ... ]}}, one item per iteration of the Distributed Map. */
private static String manyItemsInput() {
StringBuilder input = new StringBuilder("{\"items\": [0");
for (int item = 1; item < DISTRIBUTED_MAP_ITEMS; item++) {
input.append(',').append(item);
}
return input.append("]}").toString();
}
@Test
void neitherRetryNorCatchInterceptsTheHistoryEventLimit() {
long startedAt = System.currentTimeMillis();
Execution execution = run(RUNAWAY_PARALLEL_BRANCH_UNDER_RETRY_AND_CATCH);
assertEquals("FAILED", execution.getStatus());
assertEquals("States.Runtime", execution.getError());
assertEquals("The execution reached the maximum number of history events (25000).",
execution.getCause());
assertEquals("ExecutionFailed", history.get(history.size() - 1).getType());
assertNotEquals("SucceedStateEntered", history.get(history.size() - 2).getType());
// Three attempts at IntervalSeconds 30 would put this past 90 seconds if the Retry ran.
assertTrue(System.currentTimeMillis() - startedAt < 30_000,
"the Retry's backoff ran");
}
private Execution run(String definition) {
return run(definition, "{\"spin\": true}");
}
private Execution run(String definition, String input) {
StateMachine stateMachine = new StateMachine();
stateMachine.setName("history-event-limit-test");
stateMachine.setStateMachineArn(
"arn:aws:states:%s:%s:stateMachine:history-event-limit-test".formatted(REGION, ACCOUNT));
stateMachine.setRoleArn("arn:aws:iam::%s:role/test-role".formatted(ACCOUNT));
stateMachine.setDefinition(definition);
Execution execution = new Execution();
execution.setName("history-event-limit-execution");
execution.setExecutionArn(
"arn:aws:states:%s:%s:execution:history-event-limit-test:history-event-limit-execution"
.formatted(REGION, ACCOUNT));
execution.setStateMachineArn(stateMachine.getStateMachineArn());
execution.setInput(input);
executor.executeSync(stateMachine, execution, history, (updated, events) -> {
});
return execution;
}
}
@@ -257,6 +257,48 @@ class AslExecutorTaskHistoryEventsTest {
assertNull(started.getDetails());
}
/**
* A Parallel branch and a Map iteration run states of their own whose events floci does not
* publish. The published history is still one unbroken chain: the ids of the events around them
* do not skip the numbers those states used.
*/
@Test
void parallelAndMapPublishAnUnbrokenEventChain() throws Exception {
var history = new ArrayList<HistoryEvent>();
var execution = run("""
{
"StartAt": "Fan",
"States": {
"Fan": {
"Type": "Parallel",
"Branches": [{
"StartAt": "BranchStep",
"States": {"BranchStep": {"Type": "Pass", "Next": "BranchTail"},
"BranchTail": {"Type": "Pass", "End": true}}
}],
"Next": "Iterate"
},
"Iterate": {
"Type": "Map",
"ItemsPath": "$[0].items",
"ItemProcessor": {
"StartAt": "ItemStep",
"States": {"ItemStep": {"Type": "Pass", "End": true}}
},
"End": true
}
}
}
""", "{\"items\": [1, 2]}", null, history);
assertEquals("SUCCEEDED", execution.getStatus(), "history: " + typesOf(history));
assertEquals(
List.of("ParallelStateEntered", "ParallelStateExited",
"MapStateEntered", "MapStateExited", "ExecutionSucceeded"),
typesOf(history));
assertChain(history);
}
private static List<String> typesOf(List<HistoryEvent> history) {
return history.stream().map(HistoryEvent::getType).toList();
}
@@ -10,6 +10,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -35,7 +36,7 @@ class MapIterationSchedulerTest {
List<Integer> results = MapIterationScheduler.execute(5, 1, index -> () -> {
starts.add(index);
return index;
});
}, Long.MAX_VALUE);
assertEquals(List.of(0, 1, 2, 3, 4), starts);
assertEquals(starts, results);
@@ -64,7 +65,7 @@ class MapIterationSchedulerTest {
} finally {
active.decrementAndGet();
}
}));
}, Long.MAX_VALUE));
assertTrue(firstWaveStarted.await(2, TimeUnit.SECONDS), "initial worker window did not start");
assertEquals(maxConcurrency, started.get(), "queued items must not be submitted early");
@@ -99,7 +100,7 @@ class MapIterationSchedulerTest {
fail("slow iteration did not start");
}
throw new IllegalStateException("later iteration failed");
}));
}, Long.MAX_VALUE));
ExecutionException failure = assertThrows(ExecutionException.class,
() -> execution.get(2, TimeUnit.SECONDS));
@@ -123,8 +124,105 @@ class MapIterationSchedulerTest {
laterItemsCompleted.countDown();
}
return index;
}));
}, Long.MAX_VALUE));
assertEquals(List.of(0, 1, 2), results);
}
@Test
void stopsStartingSerialIterationsOncePastTheDeadline() {
AtomicInteger started = new AtomicInteger();
assertThrows(TimeoutException.class, () -> MapIterationScheduler.execute(3, 1, index -> () -> {
started.incrementAndGet();
return index;
}, System.nanoTime() - 1));
assertEquals(0, started.get());
}
@Test
void endsTheSerialWaitForASingleItemOncePastTheDeadline() throws Exception {
CountDownLatch neverRelease = new CountDownLatch(1);
CountDownLatch blockedInterrupted = new CountDownLatch(1);
// Not try-with-resources: against the still-buggy serial path the iteration below never
// returns and is never interrupted, so ExecutorService#close() would block on
// awaitTermination forever. shutdownNow() in the finally block does not wait.
ExecutorService driver = Executors.newSingleThreadExecutor();
try {
Future<List<Integer>> execution = driver.submit(() -> MapIterationScheduler.execute(
1, 3, index -> () -> {
try {
neverRelease.await();
return index;
} catch (InterruptedException e) {
blockedInterrupted.countDown();
throw e;
}
}, System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(200)));
ExecutionException failure = assertThrows(ExecutionException.class,
() -> execution.get(2, TimeUnit.SECONDS));
assertEquals(TimeoutException.class, failure.getCause().getClass());
assertTrue(blockedInterrupted.await(2, TimeUnit.SECONDS),
"the single iteration should be interrupted once the deadline passes");
} finally {
driver.shutdownNow();
}
}
@Test
void endsTheSerialWaitForMaxConcurrencyOneOncePastTheDeadline() throws Exception {
CountDownLatch neverRelease = new CountDownLatch(1);
CountDownLatch blockedInterrupted = new CountDownLatch(1);
// Not try-with-resources: see endsTheSerialWaitForASingleItemOncePastTheDeadline above.
ExecutorService driver = Executors.newSingleThreadExecutor();
try {
Future<List<Integer>> execution = driver.submit(() -> MapIterationScheduler.execute(
2, 1, index -> () -> {
try {
neverRelease.await();
return index;
} catch (InterruptedException e) {
blockedInterrupted.countDown();
throw e;
}
}, System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(200)));
ExecutionException failure = assertThrows(ExecutionException.class,
() -> execution.get(2, TimeUnit.SECONDS));
assertEquals(TimeoutException.class, failure.getCause().getClass());
assertTrue(blockedInterrupted.await(2, TimeUnit.SECONDS),
"the blocked iteration should be interrupted once the deadline passes");
} finally {
driver.shutdownNow();
}
}
@Test
void endsTheConcurrentWaitOncePastTheDeadline() throws Exception {
CountDownLatch neverRelease = new CountDownLatch(1);
CountDownLatch blockedInterrupted = new CountDownLatch(2);
try (ExecutorService driver = Executors.newSingleThreadExecutor()) {
Future<List<Integer>> execution = driver.submit(() -> MapIterationScheduler.execute(
2, 2, index -> () -> {
try {
neverRelease.await();
return index;
} catch (InterruptedException e) {
blockedInterrupted.countDown();
throw e;
}
}, System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(200)));
ExecutionException failure = assertThrows(ExecutionException.class,
() -> execution.get(5, TimeUnit.SECONDS));
assertEquals(TimeoutException.class, failure.getCause().getClass());
assertTrue(blockedInterrupted.await(2, TimeUnit.SECONDS),
"the iterations still running should be interrupted once the deadline passes");
}
}
}
@@ -284,10 +284,59 @@ class StepFunctionsAwsSdkTaskIntegrationTest {
assertEquals("Sfn.InvalidTokenException", describe.jsonPath().getString("error"));
}
@Test
@Order(9)
void sendTaskSuccessOnATokenWhoseResourceInvocationThrewFailsAsInvalid() throws Exception {
// "Leak" registers a task token, then fails invoking its own (unsupported) resource before it
// ever waits on that token. The registration must not outlive the failure: the token is
// recovered from the TaskScheduled event it wrote on its way to failing, and a second
// execution's SendTaskSuccess on that same token must find nothing pending for it.
var leakArn = createStateMachine("aws-sdk-task-leaked-token", """
{
"QueryLanguage": "JSONata",
"StartAt": "Leak",
"States": {
"Leak": {
"Type": "Task",
"Resource": "arn:aws:states:::unsupported:doSomething.waitForTaskToken",
"Arguments": {"token": "{% $states.context.Task.Token %}"},
"End": true
}
}
}
""");
var leaked = waitForTerminalState(startExecution(leakArn, "{}"));
assertEquals("FAILED", leaked.jsonPath().getString("status"));
assertEquals("States.TaskFailed", leaked.jsonPath().getString("error"));
var taskToken = scheduledTaskToken(leaked.jsonPath().getString("executionArn"));
var senderArn = createStateMachine("aws-sdk-send-success-leaked-token", """
{
"QueryLanguage": "JSONata",
"StartAt": "Resume",
"States": {
"Resume": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:sfn:sendTaskSuccess",
"Arguments": {"TaskToken": "{% $states.input.token %}", "Output": {}},
"End": true
}
}
}
""");
var describe = waitForTerminalState(startExecution(senderArn, tokenInput(taskToken)));
assertEquals("FAILED", describe.jsonPath().getString("status"),
"Leak's token must be discarded once its resource invocation throws, not left pending");
assertEquals("Sfn.InvalidTokenException", describe.jsonPath().getString("error"));
}
// ──────────────────────────── scheduler:createSchedule / updateSchedule ────────────────────────────
@Test
@Order(9)
@Order(10)
void createScheduleReturnsTheScheduleArnAndTheScheduleIsReadable() throws Exception {
var result = mapper.readTree(succeedingOutputOf(
createStateMachine("aws-sdk-create-schedule", scheduleTask("createSchedule",
@@ -303,7 +352,7 @@ class StepFunctionsAwsSdkTaskIntegrationTest {
}
@Test
@Order(10)
@Order(11)
void updateScheduleKeepsTheArnAndChangesTheExpression() throws Exception {
var result = mapper.readTree(succeedingOutputOf(
createStateMachine("aws-sdk-update-schedule", scheduleTask("updateSchedule",
@@ -317,7 +366,7 @@ class StepFunctionsAwsSdkTaskIntegrationTest {
}
@Test
@Order(11)
@Order(12)
void createScheduleOnANameAlreadyTakenFailsWithConflict() {
var describe = waitForTerminalState(startExecution(
createStateMachine("aws-sdk-create-schedule-twice", scheduleTask("createSchedule",
@@ -328,7 +377,7 @@ class StepFunctionsAwsSdkTaskIntegrationTest {
}
@Test
@Order(12)
@Order(13)
void updateScheduleOnAScheduleThatDoesNotExistFailsWithResourceNotFound() {
var describe = waitForTerminalState(startExecution(
createStateMachine("aws-sdk-update-missing-schedule", scheduleTask("updateSchedule",
@@ -339,7 +388,7 @@ class StepFunctionsAwsSdkTaskIntegrationTest {
}
@Test
@Order(13)
@Order(14)
void createScheduleWithIncompleteEventBridgeParametersIsCatchableAsAValidationException() throws Exception {
var smArn = createStateMachine("aws-sdk-create-schedule-invalid-target", """
{
@@ -379,7 +428,7 @@ class StepFunctionsAwsSdkTaskIntegrationTest {
}
@Test
@Order(14)
@Order(15)
void createScheduleWithAMalformedListIsCatchableAsASerializationException() throws Exception {
// A malformed EcsParameters list is refused before the conversion runs, so it reaches Catch
// as the SDK exception AWS sends rather than as States.Runtime.
@@ -569,6 +618,29 @@ class StepFunctionsAwsSdkTaskIntegrationTest {
.when().post("/");
}
private static Response getExecutionHistory(String execArn) {
return given()
.header("X-Amz-Target", "AWSStepFunctions.GetExecutionHistory")
.contentType(SFN_CONTENT_TYPE)
.body("""
{"executionArn": "%s"}
""".formatted(execArn))
.when().post("/");
}
/** The token a Task registered for itself, recovered from its own TaskScheduled event. */
private static String scheduledTaskToken(String execArn) throws Exception {
var events = mapper.readTree(getExecutionHistory(execArn).body().asString()).path("events");
for (var event : events) {
if ("TaskScheduled".equals(event.path("type").asText())) {
var parameters = event.path("taskScheduledEventDetails").path("parameters").asText();
return mapper.readTree(parameters).path("token").asText();
}
}
fail("no TaskScheduled event found in history: " + events);
return null;
}
private static Response waitForTerminalState(String execArn) {
for (var i = 0; i < 150; i++) {
var resp = describeExecution(execArn);
@@ -0,0 +1,194 @@
package io.github.hectorvent.floci.services.stepfunctions;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Guards that {@code StopExecution} stops the execution instead of relabelling it: the status,
* error and cause it writes are what {@code DescribeExecution} returns, and the worker thread that
* is still inside the {@code Wait} does not overwrite them when it gets there.
*/
@QuarkusTest
class StepFunctionsStopExecutionIntegrationTest {
private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role";
/** Long enough that the stop lands mid-flight, short enough that the re-read is cheap. */
private static final int WAIT_SECONDS = 3;
private static final String WAITING_MACHINE = """
{"StartAt": "W", "States": {"W": {"Type": "Wait", "Seconds": %d, "End": true}}}
""".formatted(WAIT_SECONDS);
@Inject
StepFunctionsService stepFunctionsService;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
/**
* The executions survive a restart in persistent storage mode; their histories do not, because
* the history lives in memory. An execution that reloads as RUNNING with no history behind it is
* still stoppable, and StopExecution reports the abort it performed rather than an error. The
* same pairing happens during a reset, between the moment the in-memory state is dropped and
* the moment the stored executions are.
*/
@Test
void executionWithNoHistoryInMemoryIsStillStoppable() throws Exception {
String executionArn = startWaitingExecution("stop-without-history");
Thread.sleep(300);
stepFunctionsService.clear();
stopExecution(executionArn, "Manual", "probe");
Response described = describeExecution(executionArn);
assertEquals("ABORTED", described.jsonPath().getString("status"));
assertEquals("Manual", described.jsonPath().getString("error"));
assertEquals("probe", described.jsonPath().getString("cause"));
}
@Test
void stoppedExecutionReportsTheCallersErrorAndCause() throws Exception {
String executionArn = startWaitingExecution("stop-reports-error");
Thread.sleep(300);
stopExecution(executionArn, "Manual", "probe");
Response described = describeExecution(executionArn);
assertEquals("ABORTED", described.jsonPath().getString("status"));
assertEquals("Manual", described.jsonPath().getString("error"));
assertEquals("probe", described.jsonPath().getString("cause"));
}
@Test
void stoppedExecutionStaysAbortedAfterTheWaitElapses() throws Exception {
String executionArn = startWaitingExecution("stop-survives-wait");
Thread.sleep(300);
stopExecution(executionArn, "Manual", "probe");
double stopDate = describeExecution(executionArn).jsonPath().getDouble("stopDate");
Thread.sleep((WAIT_SECONDS + 2) * 1000L);
Response described = describeExecution(executionArn);
assertEquals("ABORTED", described.jsonPath().getString("status"));
assertEquals("Manual", described.jsonPath().getString("error"));
assertEquals("probe", described.jsonPath().getString("cause"));
assertEquals(stopDate, described.jsonPath().getDouble("stopDate"));
}
@Test
void abortedExecutionEndsItsHistoryAtExecutionAborted() throws Exception {
String executionArn = startWaitingExecution("stop-ends-history");
Thread.sleep(300);
stopExecution(executionArn, "Manual", "probe");
// The worker is still inside the Wait. Let it come out and try to record the state it left.
Thread.sleep((WAIT_SECONDS + 2) * 1000L);
List<Map<String, Object>> events = getExecutionHistory(executionArn).jsonPath().getList("events");
List<String> types = events.stream().map(event -> (String) event.get("type")).toList();
List<Object> ids = events.stream().map(event -> event.get("id")).toList();
assertAll(
() -> assertEquals("ExecutionAborted", types.get(types.size() - 1),
"history continued past the terminal event: " + types),
() -> assertEquals(ids.size(), new HashSet<>(ids).size(),
"history repeats an event id: " + ids + " for " + types));
}
private String startWaitingExecution(String namePrefix) {
String name = namePrefix + "-" + UUID.randomUUID();
String stateMachineArn = createStateMachine(name, WAITING_MACHINE);
Response response = given()
.header("X-Amz-Target", "AWSStepFunctions.StartExecution")
.contentType(SFN_CONTENT_TYPE)
.body("""
{"stateMachineArn": "%s", "input": "{}"}
""".formatted(stateMachineArn))
.when()
.post("/");
response.then().statusCode(200);
return response.jsonPath().getString("executionArn");
}
private String createStateMachine(String name, String definition) {
Response response = given()
.header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
.contentType(SFN_CONTENT_TYPE)
.body("""
{"name": "%s", "definition": %s, "roleArn": "%s"}
""".formatted(name, quote(definition), ROLE_ARN))
.when()
.post("/");
response.then().statusCode(200);
return response.jsonPath().getString("stateMachineArn");
}
private void stopExecution(String executionArn, String error, String cause) {
given()
.header("X-Amz-Target", "AWSStepFunctions.StopExecution")
.contentType(SFN_CONTENT_TYPE)
.body("""
{"executionArn": "%s", "error": "%s", "cause": "%s"}
""".formatted(executionArn, error, cause))
.when()
.post("/")
.then()
.statusCode(200);
}
private Response describeExecution(String executionArn) {
Response response = given()
.header("X-Amz-Target", "AWSStepFunctions.DescribeExecution")
.contentType(SFN_CONTENT_TYPE)
.body("""
{"executionArn": "%s"}
""".formatted(executionArn))
.when()
.post("/");
response.then().statusCode(200);
return response;
}
private Response getExecutionHistory(String executionArn) {
Response response = given()
.header("X-Amz-Target", "AWSStepFunctions.GetExecutionHistory")
.contentType(SFN_CONTENT_TYPE)
.body("""
{"executionArn": "%s", "includeExecutionData": true}
""".formatted(executionArn))
.when()
.post("/");
response.then().statusCode(200);
return response;
}
private static String quote(String raw) {
return "\"" + raw
.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t")
+ "\"";
}
}
@@ -0,0 +1,553 @@
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;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* The two {@code TimeoutSeconds} fields of ASL, each enforced on its own clock: the state
* machine's total budget and a {@code Task}'s wait for its task token, the second one bounded a
* second time by {@code HeartbeatSeconds}.
*
* <p>The bounds here are one to ten seconds where the report that measured them against us-east-1
* used three and five; the shape of the terminal execution is what the assertions pin, not the
* duration.
*/
@QuarkusTest
class StepFunctionsTimeoutSecondsIntegrationTest {
private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role";
private static final ObjectMapper mapper = new ObjectMapper();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void stateMachineTimeoutSecondsCutsAWaitLongerThanTheRemainingBudget() throws Exception {
String smArn = createStateMachine("top-level-timeout-wait", """
{
"StartAt": "Linger",
"TimeoutSeconds": 1,
"States": {
"Linger": {"Type": "Wait", "Seconds": 3, "End": true}
}
}
""");
Response timedOut = waitForTerminalExecution(startExecution(smArn, "{}"));
assertEquals("TIMED_OUT", timedOut.jsonPath().getString("status"));
JsonNode body = mapper.readTree(timedOut.body().asString());
assertTrue(body.has("stopDate"), "stopDate must be set on a timed out execution");
assertFalse(body.has("error"), "TIMED_OUT carries no error key: " + body);
assertFalse(body.has("cause"), "TIMED_OUT carries no cause key: " + body);
}
@Test
void timedOutExecutionEmitsExecutionTimedOutAndNoStateExitedForTheCutState() throws Exception {
String smArn = createStateMachine("top-level-timeout-history", """
{
"StartAt": "Linger",
"TimeoutSeconds": 1,
"States": {
"Linger": {"Type": "Wait", "Seconds": 3, "End": true}
}
}
""");
String execArn = startExecution(smArn, "{}");
waitForTerminalExecution(execArn);
JsonNode events = mapper.readTree(getExecutionHistory(execArn).body().asString()).path("events");
assertEquals(List.of("ExecutionStarted", "WaitStateEntered", "ExecutionTimedOut"),
eventTypes(events), "history was " + events);
JsonNode timedOut = events.get(events.size() - 1);
assertEquals(0, timedOut.path("previousEventId").asLong());
assertEquals("States.Timeout",
timedOut.path("executionTimedOutEventDetails").path("error").asText());
assertFalse(timedOut.path("executionTimedOutEventDetails").has("cause"),
"ExecutionTimedOut carries only the error: " + timedOut);
}
@Test
void stateMachineTimeoutSecondsCutsTheWaitForAParallelBranch() throws Exception {
// A branch is never cut mid-state, so its Wait sleeps out in full on its own thread. What
// the budget cuts is the join: the execution ends while the branch is still running, and
// the Parallel state gets no Exited event and no state after it is entered.
String smArn = createStateMachine("top-level-timeout-loop", """
{
"StartAt": "Fork",
"TimeoutSeconds": 1,
"States": {
"Fork": {
"Type": "Parallel",
"Branches": [{
"StartAt": "Linger",
"States": {"Linger": {"Type": "Wait", "Seconds": 3, "End": true}}
}],
"Next": "Unreached"
},
"Unreached": {"Type": "Pass", "End": true}
}
}
""");
String execArn = startExecution(smArn, "{}");
long startedAt = System.currentTimeMillis();
Response timedOut = waitForTerminalExecution(execArn);
long elapsedMillis = System.currentTimeMillis() - startedAt;
assertEquals("TIMED_OUT", timedOut.jsonPath().getString("status"));
assertTrue(elapsedMillis < 3_000,
"the branch's 3-second Wait outlasted the 1-second budget: " + elapsedMillis + " ms");
JsonNode events = mapper.readTree(getExecutionHistory(execArn).body().asString()).path("events");
assertEquals(List.of("ExecutionStarted", "ParallelStateEntered", "ExecutionTimedOut"),
eventTypes(events), "history was " + events);
}
@Test
void stateMachineTimeoutSecondsCutsTheWaitForATaskToken() throws Exception {
// Measured against us-east-1: a state machine whose budget is shorter than the Task's own
// TimeoutSeconds ends TIMED_OUT the instant the budget runs out, and writes nothing about
// the task it cut. No ActivityTimedOut, no TaskFailed, no ExecutionFailed.
String activityArn = createActivity("top-level-timeout-token");
String smArn = createStateMachine("top-level-timeout-token", """
{
"StartAt": "Await",
"TimeoutSeconds": 1,
"States": {
"Await": {
"Type": "Task",
"Resource": "%s",
"TimeoutSeconds": 60,
"End": true
}
}
}
""".formatted(activityArn));
String execArn = startExecution(smArn, "{}");
long startedAt = System.currentTimeMillis();
Response timedOut = waitForTerminalExecution(execArn);
long elapsedMillis = System.currentTimeMillis() - startedAt;
assertEquals("TIMED_OUT", timedOut.jsonPath().getString("status"), timedOut.body().asString());
assertTrue(elapsedMillis < 5_000,
"the task's 60-second wait outlasted the 1-second budget: " + elapsedMillis + " ms");
JsonNode events = mapper.readTree(getExecutionHistory(execArn).body().asString()).path("events");
assertEquals(List.of("ExecutionStarted", "TaskStateEntered", "ActivityScheduled",
"ActivityStarted", "ExecutionTimedOut"), eventTypes(events), "history was " + events);
}
@Test
void 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.
String childArn = createStateMachine("nested-child", """
{
"StartAt": "Linger",
"States": {"Linger": {"Type": "Wait", "Seconds": 10, "End": true}}
}
""");
String parentArn = createStateMachine("nested-parent", """
{
"StartAt": "RunChild",
"TimeoutSeconds": 1,
"States": {
"RunChild": {
"Type": "Task",
"Resource": "arn:aws:states:::states:startExecution.sync",
"Parameters": {"StateMachineArn": "%s", "Input": {}},
"End": true
}
}
}
""".formatted(childArn));
String execArn = startExecution(parentArn, "{}");
long startedAt = System.currentTimeMillis();
Response timedOut = waitForTerminalExecution(execArn);
long elapsedMillis = System.currentTimeMillis() - startedAt;
assertEquals("TIMED_OUT", timedOut.jsonPath().getString("status"), timedOut.body().asString());
assertTrue(elapsedMillis < 5_000,
"the child's 10-second Wait outlasted the 1-second budget: " + elapsedMillis + " ms");
JsonNode events = mapper.readTree(getExecutionHistory(execArn).body().asString()).path("events");
assertEquals("ExecutionTimedOut", events.get(events.size() - 1).path("type").asText(),
"history was " + events);
}
@Test
void stateMachineTimeoutSecondsCutsTheWaitForMapIterations() throws Exception {
// Two iterations run concurrently and each sleeps past the budget, so what the budget cuts
// is the Map state's wait for them rather than any single iteration.
String smArn = createStateMachine("top-level-timeout-map", """
{
"StartAt": "OverItems",
"TimeoutSeconds": 1,
"States": {
"OverItems": {
"Type": "Map",
"ItemsPath": "$.items",
"ItemProcessor": {
"StartAt": "Linger",
"States": {"Linger": {"Type": "Wait", "Seconds": 10, "End": true}}
},
"End": true
}
}
}
""");
String execArn = startExecution(smArn, "{\"items\": [1, 2]}");
long startedAt = System.currentTimeMillis();
Response timedOut = waitForTerminalExecution(execArn);
long elapsedMillis = System.currentTimeMillis() - startedAt;
assertEquals("TIMED_OUT", timedOut.jsonPath().getString("status"), timedOut.body().asString());
assertTrue(elapsedMillis < 5_000,
"the iterations' 10-second Wait outlasted the 1-second budget: " + elapsedMillis + " ms");
JsonNode events = mapper.readTree(getExecutionHistory(execArn).body().asString()).path("events");
assertEquals(List.of("ExecutionStarted", "MapStateEntered", "ExecutionTimedOut"),
eventTypes(events), "history was " + events);
}
@Test
void stateMachineTimeoutSecondsCutsTheWaitForASingleMapIteration() throws Exception {
// A single item runs the Map state's serial path rather than the concurrent one; the
// budget must cut it the same way it cuts a concurrent iteration above.
String smArn = createStateMachine("top-level-timeout-map-single-item", """
{
"StartAt": "OverItems",
"TimeoutSeconds": 1,
"States": {
"OverItems": {
"Type": "Map",
"ItemsPath": "$.items",
"ItemProcessor": {
"StartAt": "Linger",
"States": {"Linger": {"Type": "Wait", "Seconds": 10, "End": true}}
},
"End": true
}
}
}
""");
String execArn = startExecution(smArn, "{\"items\": [1]}");
long startedAt = System.currentTimeMillis();
Response timedOut = waitForTerminalExecution(execArn);
long elapsedMillis = System.currentTimeMillis() - startedAt;
assertEquals("TIMED_OUT", timedOut.jsonPath().getString("status"), timedOut.body().asString());
assertTrue(elapsedMillis < 5_000,
"the single iteration's 10-second Wait outlasted the 1-second budget: " + elapsedMillis + " ms");
JsonNode events = mapper.readTree(getExecutionHistory(execArn).body().asString()).path("events");
assertEquals(List.of("ExecutionStarted", "MapStateEntered", "ExecutionTimedOut"),
eventTypes(events), "history was " + events);
}
@Test
void stateMachineTimeoutSecondsCutsARetryBackoffLongerThanTheRemainingBudget() throws Exception {
// The Lambda does not exist, so every attempt fails immediately and the only thing this
// state spends time on is the backoff between attempts. AWS ends the execution when the
// budget runs out, mid-backoff; before this the backoff ran in full and the state failed
// on its own error afterwards, so the execution ended FAILED past its budget.
String smArn = createStateMachine("top-level-timeout-retry", """
{
"StartAt": "Flaky",
"TimeoutSeconds": 1,
"States": {
"Flaky": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {"FunctionName": "absent-function"},
"Retry": [{"ErrorEquals": ["States.ALL"], "IntervalSeconds": 10, "MaxAttempts": 1}],
"End": true
}
}
}
""");
String execArn = startExecution(smArn, "{}");
long startedAt = System.currentTimeMillis();
Response timedOut = waitForTerminalExecution(execArn);
long elapsedMillis = System.currentTimeMillis() - startedAt;
assertEquals("TIMED_OUT", timedOut.jsonPath().getString("status"), timedOut.body().asString());
assertTrue(elapsedMillis < 5_000,
"the 10-second backoff outlasted the 1-second budget: " + elapsedMillis + " ms");
JsonNode events = mapper.readTree(getExecutionHistory(execArn).body().asString()).path("events");
assertEquals("ExecutionTimedOut", events.get(events.size() - 1).path("type").asText(),
"history was " + events);
}
@Test
void taskTimeoutSecondsBoundsTheWholeWaitForTheTaskToken() throws Exception {
String activityArn = createActivity("timeout-seconds-total");
String smArn = createStateMachine("task-timeout-seconds", activityTask(activityArn, 1, 0));
Response failed = waitForTerminalExecution(startExecution(smArn, "{}"));
assertEquals("FAILED", failed.jsonPath().getString("status"));
assertEquals("States.Timeout", failed.jsonPath().getString("error"));
JsonNode body = mapper.readTree(failed.body().asString());
assertFalse(body.has("cause"),
"a task that ran out of time carries no cause key: " + body);
}
@Test
void taskHeartbeatSecondsBoundsTheGapBetweenHeartbeats() throws Exception {
String activityArn = createActivity("heartbeat-seconds-gap");
String smArn = createStateMachine("task-heartbeat-gap", activityTask(activityArn, 10, 1));
String execArn = startExecution(smArn, "{}");
// A worker picks the task up and then goes silent, so the gap HeartbeatSeconds allows runs
// out long before the state's TimeoutSeconds does.
getActivityTask(activityArn);
Response failed = waitForTerminalExecution(execArn);
assertEquals("FAILED", failed.jsonPath().getString("status"));
assertEquals("States.Timeout", failed.jsonPath().getString("error"));
JsonNode body = mapper.readTree(failed.body().asString());
assertFalse(body.has("cause"),
"a task that missed its heartbeats carries no cause key: " + body);
JsonNode events = mapper.readTree(getExecutionHistory(execArn).body().asString()).path("events");
assertEquals(List.of("ExecutionStarted", "TaskStateEntered", "ActivityScheduled",
"ActivityStarted", "ActivityTimedOut", "ExecutionFailed"),
eventTypes(events), "history was " + events);
JsonNode timedOut = events.get(events.size() - 2);
assertEquals("States.Timeout",
timedOut.path("activityTimedOutEventDetails").path("error").asText());
assertFalse(timedOut.path("activityTimedOutEventDetails").has("cause"),
"ActivityTimedOut carries only the error: " + timedOut);
}
@Test
void aCatchMatchesAHeartbeatExpiryUnderEitherErrorName() throws Exception {
for (String errorEquals : List.of("States.HeartbeatTimeout", "States.Timeout")) {
String activityArn = createActivity("heartbeat-seconds-catch");
String smArn = createStateMachine("task-heartbeat-catch",
caughtActivityTask(activityArn, errorEquals));
String execArn = startExecution(smArn, "{}");
getActivityTask(activityArn);
Response caught = waitForTerminalExecution(execArn);
assertEquals("SUCCEEDED", caught.jsonPath().getString("status"),
"Catch on " + errorEquals + " left the execution " + caught.body().asString());
assertEquals("States.Timeout",
mapper.readTree(caught.jsonPath().getString("output")).path("Error").asText(),
"Catch on " + errorEquals + " reported the wrong error");
}
}
@Test
void heartbeatsKeepATaskAliveUntilItsTimeoutSecondsRunOut() throws Exception {
String activityArn = createActivity("heartbeat-seconds-reset");
String smArn = createStateMachine("task-heartbeat-reset", activityTask(activityArn, 12, 3));
String execArn = startExecution(smArn, "{}");
String taskToken = getActivityTask(activityArn);
// Five seconds of work reported every 500 ms: nearly twice the heartbeat gap, so the task
// survives only if each heartbeat pushes that gap's deadline forward.
for (int beat = 0; beat < 10; beat++) {
Thread.sleep(500);
sendTaskHeartbeat(taskToken);
}
sendTaskSuccess(taskToken, "{\"answered\":true}");
Response succeeded = waitForTerminalExecution(execArn);
assertEquals("SUCCEEDED", succeeded.jsonPath().getString("status"),
"execution was " + succeeded.body().asString());
assertTrue(mapper.readTree(succeeded.jsonPath().getString("output")).path("answered").asBoolean());
}
private static String activityTask(String activityArn, int timeoutSeconds, int heartbeatSeconds) {
String heartbeat = heartbeatSeconds > 0 ? ",\"HeartbeatSeconds\": " + heartbeatSeconds : "";
return """
{
"StartAt": "Await",
"States": {
"Await": {
"Type": "Task",
"Resource": "%s",
"TimeoutSeconds": %d%s,
"End": true
}
}
}
""".formatted(activityArn, timeoutSeconds, heartbeat);
}
private static String caughtActivityTask(String activityArn, String errorEquals) {
return """
{
"StartAt": "Await",
"States": {
"Await": {
"Type": "Task",
"Resource": "%s",
"TimeoutSeconds": 10,
"HeartbeatSeconds": 1,
"Catch": [{"ErrorEquals": ["%s"], "Next": "Recovered"}],
"End": true
},
"Recovered": {"Type": "Pass", "End": true}
}
}
""".formatted(activityArn, errorEquals);
}
private static List<String> eventTypes(JsonNode events) {
List<String> types = new ArrayList<>();
events.forEach(event -> types.add(event.path("type").asText()));
return types;
}
private static String createActivity(String name) {
Response resp = given()
.header("X-Amz-Target", "AWSStepFunctions.CreateActivity")
.contentType(SFN_CONTENT_TYPE)
.body("""
{"name": "%s-%d"}
""".formatted(name, System.currentTimeMillis()))
.when()
.post("/");
resp.then().statusCode(200);
return resp.jsonPath().getString("activityArn");
}
private static String getActivityTask(String activityArn) {
Response resp = given()
.header("X-Amz-Target", "AWSStepFunctions.GetActivityTask")
.contentType(SFN_CONTENT_TYPE)
.body("""
{"activityArn": "%s", "workerName": "timeout-seconds-worker"}
""".formatted(activityArn))
.when()
.post("/");
resp.then().statusCode(200);
String taskToken = resp.jsonPath().getString("taskToken");
assertFalse(taskToken == null || taskToken.isBlank(), "no activity task was queued");
return taskToken;
}
private static void sendTaskHeartbeat(String taskToken) {
given()
.header("X-Amz-Target", "AWSStepFunctions.SendTaskHeartbeat")
.contentType(SFN_CONTENT_TYPE)
.body("""
{"taskToken": %s}
""".formatted(quote(taskToken)))
.when()
.post("/")
.then()
.statusCode(200);
}
private static void sendTaskSuccess(String taskToken, String output) {
given()
.header("X-Amz-Target", "AWSStepFunctions.SendTaskSuccess")
.contentType(SFN_CONTENT_TYPE)
.body("""
{"taskToken": %s, "output": %s}
""".formatted(quote(taskToken), quote(output)))
.when()
.post("/")
.then()
.statusCode(200);
}
private static String createStateMachine(String name, String definition) {
Response resp = given()
.header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
.contentType(SFN_CONTENT_TYPE)
.body("""
{"name": "%s-%d", "definition": %s, "roleArn": "%s"}
""".formatted(name, System.currentTimeMillis(), quote(definition), ROLE_ARN))
.when()
.post("/");
resp.then().statusCode(200);
return resp.jsonPath().getString("stateMachineArn");
}
private static String startExecution(String smArn, String input) {
Response resp = given()
.header("X-Amz-Target", "AWSStepFunctions.StartExecution")
.contentType(SFN_CONTENT_TYPE)
.body("""
{"stateMachineArn": "%s", "input": %s}
""".formatted(smArn, quote(input)))
.when()
.post("/");
resp.then().statusCode(200);
return resp.jsonPath().getString("executionArn");
}
private static Response describeExecution(String execArn) {
return given()
.header("X-Amz-Target", "AWSStepFunctions.DescribeExecution")
.contentType(SFN_CONTENT_TYPE)
.body("""
{"executionArn": "%s"}
""".formatted(execArn))
.when()
.post("/");
}
private static Response getExecutionHistory(String execArn) {
return given()
.header("X-Amz-Target", "AWSStepFunctions.GetExecutionHistory")
.contentType(SFN_CONTENT_TYPE)
.body("""
{"executionArn": "%s"}
""".formatted(execArn))
.when()
.post("/");
}
/**
* Polls for 20 seconds: twice the longest bound any definition here declares, and far short of
* the 300-second default a task that ignores TimeoutSeconds falls back on.
*/
private static Response waitForTerminalExecution(String execArn) throws InterruptedException {
for (int poll = 0; poll < 200; poll++) {
Response resp = describeExecution(execArn);
String status = resp.jsonPath().getString("status");
if (!"RUNNING".equals(status)) {
return resp;
}
Thread.sleep(100);
}
fail("Execution " + execArn + " was still RUNNING after 20 seconds");
return null;
}
private static String quote(String raw) {
return "\"" + raw
.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t")
+ "\"";
}
}