diff --git a/src/test/java/io/floci/aws/services/lambda/LambdaExecutorServiceTest.java b/src/test/java/io/floci/aws/services/lambda/LambdaExecutorServiceTest.java index eb8387053c..ef69a4c4e5 100644 --- a/src/test/java/io/floci/aws/services/lambda/LambdaExecutorServiceTest.java +++ b/src/test/java/io/floci/aws/services/lambda/LambdaExecutorServiceTest.java @@ -164,11 +164,18 @@ class LambdaExecutorServiceTest { RuntimeApiServer rtas = mock(RuntimeApiServer.class); ContainerHandle handle = new ContainerHandle("cid-bound", "test-fn", rtas, ContainerState.WARM); when(warmPool.acquire(any())).thenReturn(handle); - when(rtas.enqueue(any())).thenReturn(new CompletableFuture<>()); + doAnswer(inv -> { + PendingInvocation invocation = inv.getArgument(0); + invocation.getResultFuture().complete( + new InvokeResult(200, null, "{}".getBytes(), null, invocation.getRequestId())); + return invocation.getResultFuture(); + }).when(rtas).enqueue(any(PendingInvocation.class)); - executor.invoke(fn, "{}".getBytes(), InvocationType.RequestResponse, LambdaInvocationChain.MAX_DEPTH); + InvokeResult result = executor.invoke(fn, "{}".getBytes(), InvocationType.RequestResponse, + LambdaInvocationChain.MAX_DEPTH); verify(warmPool).acquire(fn); + assertNull(result.getFunctionError()); } @Test @@ -186,8 +193,9 @@ class LambdaExecutorServiceTest { assertEquals(200, result.getStatusCode()); assertEquals("Unhandled", result.getFunctionError()); String payload = new String(result.getPayload()); - assertTrue(payload.contains("Function.TimedOut"), "payload should contain error type"); - assertTrue(payload.contains("1 seconds"), "payload should contain timeout value"); + assertTrue(payload.contains("\"errorType\":\"Function.TimedOut\""), payload); + assertTrue(payload.contains("Task timed out after 1 seconds"), payload); + assertNotNull(result.getRequestId()); } @Test @@ -348,24 +356,6 @@ class LambdaExecutorServiceTest { assertTrue(new String(result.getPayload()).contains("Function.TimedOut")); } - @Test - void timeoutResponse_containsCorrectErrorPayload() { - fn.setTimeout(2); - RuntimeApiServer rtas = mock(RuntimeApiServer.class); - ContainerHandle handle = new ContainerHandle("cid-3", "test-fn", rtas, ContainerState.WARM); - - when(warmPool.acquire(any())).thenReturn(handle); - when(rtas.enqueue(any())).thenReturn(new CompletableFuture<>()); - - InvokeResult result = executor.invoke(fn, "{}".getBytes(), InvocationType.RequestResponse); - - assertNotNull(result.getPayload()); - String payload = new String(result.getPayload()); - assertTrue(payload.contains("\"errorType\":\"Function.TimedOut\"")); - assertTrue(payload.contains("Task timed out after 2 seconds")); - assertNotNull(result.getRequestId()); - } - @Test void dryRunInvocation_doesNotAcquireContainer() { InvokeResult result = executor.invoke(fn, "{}".getBytes(), InvocationType.DryRun); diff --git a/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorExecutionBudgetTest.java b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorExecutionBudgetTest.java new file mode 100644 index 0000000000..6f5f00f721 --- /dev/null +++ b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorExecutionBudgetTest.java @@ -0,0 +1,249 @@ +package io.floci.aws.services.stepfunctions; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.lambda.LambdaExecutorService; +import io.floci.aws.services.lambda.LambdaFunctionStore; +import io.floci.aws.services.lambda.model.InvocationType; +import io.floci.aws.services.lambda.model.InvokeResult; +import io.floci.aws.services.lambda.model.LambdaFunction; +import io.floci.aws.services.stepfunctions.model.Execution; +import io.floci.aws.services.stepfunctions.model.HistoryEvent; +import jakarta.enterprise.inject.Instance; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; + +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.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +/** + * The state machine's {@code TimeoutSeconds} budget cutting each kind of wait, and a heartbeat + * expiry caught under either of its names, on a clock the test moves forward so no case waits the + * budget out. One end-to-end case per clock stays in {@code StepFunctionsTimeoutSecondsIntegrationTest}. + * + *

The executor reads {@code System.nanoTime()} plus an offset the test controls, which keeps it + * on the time base the task-token store stamps heartbeats with. A Wait or a Retry backoff moves the + * offset through the sleeper instead of sleeping. A Parallel branch's Wait moves it the same way + * and then stays parked, since a branch is never cut mid-state; the thread joining the branches + * reads the clock only once the branch is parked, so the join finds the budget already spent. + */ +@Timeout(10) +class AslExecutorExecutionBudgetTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + private static final String ACTIVITY_ARN = "arn:aws:states:%s:%s:activity:worker".formatted(REGION, ACCOUNT); + private static final String FUNCTION_NAME = "flaky"; + private static final String FUNCTION_ARN = + "arn:aws:lambda:%s:%s:function:%s".formatted(REGION, ACCOUNT, FUNCTION_NAME); + private static final long PAST_ONE_SECOND = TimeUnit.SECONDS.toNanos(2); + + private final ObjectMapper mapper = new ObjectMapper(); + private final AtomicLong offset = new AtomicLong(); + private final List sleeps = new CopyOnWriteArrayList<>(); + private final CountDownLatch branchParked = new CountDownLatch(1); + private final CountDownLatch releaseBranches = new CountDownLatch(1); + private final RecordingHistory history = new RecordingHistory(); + private final LambdaExecutorService lambdaExecutor = mock(LambdaExecutorService.class); + private final LambdaFunctionStore functionStore = mock(LambdaFunctionStore.class); + private StepFunctionsService tokens; + private AslExecutor executor; + + @BeforeEach + @SuppressWarnings("unchecked") + void setUp() { + RegionResolver resolver = mock(RegionResolver.class); + when(resolver.getRegion()).thenReturn(REGION); + when(resolver.getAccountId()).thenReturn(ACCOUNT); + tokens = spy(new StepFunctionsService(mock(StorageFactory.class), resolver, mock(AslExecutor.class), + mapper, mock(SfnMockLoader.class), mock(StepFunctionsEventPublisher.class))); + Instance instance = mock(Instance.class); + when(instance.get()).thenReturn(tokens); + executor = AslExecutorFixture.builder() + .objectMapper(mapper) + .lambdaExecutor(lambdaExecutor) + .functionStore(functionStore) + .sfnService(instance) + .customResourceLiveness(null) + .maxWaitSeconds(30) + .nanoTime(this::now) + .sleeper(this::sleep) + .build(); + } + + @AfterEach + void releaseParkedBranches() { + releaseBranches.countDown(); + executor.stop(); + } + + @Test + void stateMachineTimeoutSecondsCutsTheWaitForATaskToken() { + // Measured against us-east-1: the execution ends TIMED_OUT the instant its budget runs out, + // and writes nothing about the task it cut. No ActivityTimedOut, no TaskFailed. + advanceOnceTheTokenIsRegistered(); + + Execution execution = run(""" + {"StartAt":"Await","TimeoutSeconds":1,"States":{ + "Await":{"Type":"Task","Resource":"%s","TimeoutSeconds":60,"End":true}}} + """.formatted(ACTIVITY_ARN)); + + assertTimedOut(execution); + assertEquals(List.of("TaskStateEntered", "ActivityScheduled", "ActivityStarted", "ExecutionTimedOut"), types()); + } + + @Test + void stateMachineTimeoutSecondsCutsTheWaitForAParallelBranch() { + // The branch's Wait is entered and never exited: the budget cuts the join, so the Parallel + // gets no Exited event and the state after it is never entered. + Execution execution = run(""" + {"StartAt":"Fork","TimeoutSeconds":1,"States":{ + "Fork":{"Type":"Parallel","Next":"Unreached","Branches":[{"StartAt":"Linger", + "States":{"Linger":{"Type":"Wait","Seconds":3,"End":true}}}]}, + "Unreached":{"Type":"Pass","End":true}}} + """); + + assertTimedOut(execution); + assertEquals(List.of("ParallelStateEntered", "ParallelStateStarted", "WaitStateEntered", + "ExecutionTimedOut"), types()); + } + + @Test + void stateMachineTimeoutSecondsCutsARetryBackoffLongerThanTheRemainingBudget() { + // Every attempt fails at once, so the only time the state spends is the 10-second backoff. + // AWS ends the execution where the budget runs out, mid-backoff, rather than failing the + // state on its own error once the backoff is over. + LambdaFunction function = new LambdaFunction(); + function.setFunctionName(FUNCTION_NAME); + function.setFunctionArn(FUNCTION_ARN); + when(functionStore.get(REGION, FUNCTION_NAME)).thenReturn(Optional.of(function)); + when(lambdaExecutor.invoke(eq(function), any(byte[].class), eq(InvocationType.RequestResponse))) + .thenReturn(new InvokeResult(200, "Handled", + "{\"errorType\":\"Boom\"}".getBytes(StandardCharsets.UTF_8), null, "req-1")); + + Execution execution = run(""" + {"StartAt":"Flaky","TimeoutSeconds":1,"States":{ + "Flaky":{"Type":"Task","Resource":"%s","End":true, + "Retry":[{"ErrorEquals":["States.ALL"],"IntervalSeconds":10,"MaxAttempts":1}]}}} + """.formatted(FUNCTION_ARN)); + + assertTimedOut(execution); + assertEquals("ExecutionTimedOut", history.getLast().getType()); + assertEquals(1, types().stream().filter("LambdaFunctionFailed"::equals).count(), types().toString()); + // The test clock takes any sleep, so the sleeps themselves show the backoff stopped at the budget. + long budget = TimeUnit.SECONDS.toNanos(1); + assertTrue(!sleeps.isEmpty() && sleeps.stream().allMatch(nanos -> nanos <= budget), + "the backoff must sleep no longer than the one-second budget: " + sleeps); + } + + @ParameterizedTest + @ValueSource(strings = {"States.HeartbeatTimeout", "States.Timeout"}) + void aCatchMatchesAHeartbeatExpiryUnderEitherErrorName(String errorEquals) throws Exception { + advanceOnceTheTokenIsRegistered(); + + Execution execution = run(""" + {"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(ACTIVITY_ARN, errorEquals)); + + assertEquals("SUCCEEDED", execution.getStatus(), "Catch on " + errorEquals + " left " + types()); + assertEquals("States.Timeout", mapper.readTree(execution.getOutput()).path("Error").asText(), + "Catch on " + errorEquals + " reported the wrong error"); + assertTrue(types().contains("ActivityTimedOut"), types().toString()); + } + + /** + * Moves the clock past a one-second bound as soon as the task's token is registered, which is + * when both of its clocks start, the same instant a worker that never answers would leave it. + */ + private void advanceOnceTheTokenIsRegistered() { + doAnswer(invocation -> { + Object future = invocation.callRealMethod(); + offset.addAndGet(PAST_ONE_SECOND); + return future; + }).when(tokens).registerPendingToken(anyString(), anyString(), anyString()); + } + + private Execution run(String definition) { + return AslExecutorFixture.runSync(executor, REGION, "budget", definition, "{}", history); + } + + private long now() { + if (Thread.currentThread() == history.joiningThread) { + awaitUninterruptibly(branchParked); + } + return System.nanoTime() + offset.get(); + } + + private void sleep(long nanos) throws InterruptedException { + sleeps.add(nanos); + offset.addAndGet(nanos); + if (Thread.currentThread() != history.runningThread) { + branchParked.countDown(); + releaseBranches.await(); + } + } + + private static void awaitUninterruptibly(CountDownLatch latch) { + try { + assertTrue(latch.await(5, TimeUnit.SECONDS), "the branch never reached its Wait"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + private void assertTimedOut(Execution execution) { + assertEquals("TIMED_OUT", execution.getStatus(), types().toString()); + assertNull(execution.getError(), "TIMED_OUT carries no error"); + assertNull(execution.getCause(), "TIMED_OUT carries no cause"); + } + + private List types() { + return history.stream().map(HistoryEvent::getType).toList(); + } + + /** + * The history, which also names the thread that runs the execution (the one that records its + * first event; ExecutionStarted is the service's to record) and, once a Parallel starts, the + * thread that joins its branches. + */ + private static final class RecordingHistory extends CopyOnWriteArrayList { + + private volatile Thread runningThread; + private volatile Thread joiningThread; + + @Override + public boolean add(HistoryEvent event) { + if (runningThread == null) { + runningThread = Thread.currentThread(); + } + if ("ParallelStateStarted".equals(event.getType())) { + joiningThread = Thread.currentThread(); + } + return super.add(event); + } + } +} diff --git a/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorNestedSyncTimeoutTest.java b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorNestedSyncTimeoutTest.java index 8b9b2f77ea..80bc1f6d43 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorNestedSyncTimeoutTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorNestedSyncTimeoutTest.java @@ -323,6 +323,7 @@ class AslExecutorNestedSyncTimeoutTest { assertEquals(1, waits.get()); assertEquals("TIMED_OUT", execution.getStatus()); + assertEquals("ExecutionTimedOut", history.getLast().getType()); assertTrue(history.stream().noneMatch(event -> "TaskTimedOut".equals(event.getType()))); verify(sfnService).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull()); } diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsControlTaskIamIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsControlTaskIamIntegrationTest.java index d6e9c01d68..09c94ea0cd 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsControlTaskIamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsControlTaskIamIntegrationTest.java @@ -243,13 +243,21 @@ class StepFunctionsControlTaskIamIntegrationTest { target.notReached().check(); } + /** + * A refusal is caught under its own error name for every integration. The Retry path in front of + * the Catch is the same for all of them and costs a real one-second interval, so one integration + * proves it. + */ @ParameterizedTest @MethodSource("eachIntegration") void aRefusalCanBeRetriedAndCaught(String integration) throws Exception { Target target = target(integration); Map task = jsonPathTask(target, null); - task.put("Retry", List.of(Map.of("ErrorEquals", List.of(target.error()), "IntervalSeconds", 1, - "BackoffRate", 1.0, "MaxAttempts", 1))); + boolean retried = eachIntegration().findFirst().orElseThrow().equals(integration); + if (retried) { + task.put("Retry", List.of(Map.of("ErrorEquals", List.of(target.error()), "IntervalSeconds", 1, + "BackoffRate", 1.0, "MaxAttempts", 1))); + } task.put("Catch", List.of(Map.of("ErrorEquals", List.of(target.error()), "Next", "Recovered"))); task.remove("End"); task.put("Next", "Done"); @@ -258,7 +266,7 @@ class StepFunctionsControlTaskIamIntegrationTest { String execution = start(machineWithDefinition(target.machineName(), definition, role(STATES_TRUST, READ_ONLY)), "{}"); assertEquals("SUCCEEDED", terminal(execution).jsonPath().getString("status")); - assertEquals(2, eventsOfType(execution, "TaskFailed").size()); + assertEquals(retried ? 2 : 1, eventsOfType(execution, "TaskFailed").size()); assertEquals(target.error(), eventsOfType(execution, "TaskFailed").getLast() .path("taskFailedEventDetails").path("error").asText()); } diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsDataTaskIamIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsDataTaskIamIntegrationTest.java index 8430e9736f..4664b94f46 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsDataTaskIamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsDataTaskIamIntegrationTest.java @@ -240,13 +240,21 @@ class StepFunctionsDataTaskIamIntegrationTest { assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); } + /** + * A refusal is caught under its own error name for every integration. The Retry path in front of + * the Catch is the same for all of them and costs a real one-second interval, so one integration + * proves it. + */ @ParameterizedTest @MethodSource("integrations") void aRefusalCanBeRetriedAndCaught(String integration) throws Exception { Target target = target(integration); Map task = new LinkedHashMap<>(jsonPathTask(target, null)); - task.put("Retry", List.of(Map.of("ErrorEquals", List.of(target.error()), "IntervalSeconds", 1, - "BackoffRate", 1.0, "MaxAttempts", 1))); + boolean retried = integrations().findFirst().orElseThrow().equals(integration); + if (retried) { + task.put("Retry", List.of(Map.of("ErrorEquals", List.of(target.error()), "IntervalSeconds", 1, + "BackoffRate", 1.0, "MaxAttempts", 1))); + } task.put("Catch", List.of(Map.of("ErrorEquals", List.of(target.error()), "Next", "Recovered"))); String definition = MAPPER.writeValueAsString(Map.of("StartAt", "Send", "States", Map.of("Send", task, "Recovered", Map.of("Type", "Pass", "End", true)))); @@ -255,7 +263,7 @@ class StepFunctionsDataTaskIamIntegrationTest { Response completed = terminal(execution); assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); - assertEquals(2, eventsOfType(execution, "TaskFailed").size()); + assertEquals(retried ? 2 : 1, eventsOfType(execution, "TaskFailed").size()); assertEquals(target.error(), eventsOfType(execution, "TaskFailed").getLast() .path("taskFailedEventDetails").path("error").asText()); } diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsJobTaskIamIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsJobTaskIamIntegrationTest.java index 09215d78de..d16aba42be 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsJobTaskIamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsJobTaskIamIntegrationTest.java @@ -272,13 +272,21 @@ class StepFunctionsJobTaskIamIntegrationTest { target.notReached().check(); } + /** + * A refusal is caught under its own error name for every integration. The Retry path in front of + * the Catch is the same for all of them and costs a real one-second interval, so one integration + * proves it. + */ @ParameterizedTest @MethodSource("eachIntegration") void aRefusalCanBeRetriedAndCaught(String integration) throws Exception { Target target = target(integration); Map task = new LinkedHashMap<>(jsonPathTask(target, null)); - task.put("Retry", List.of(Map.of("ErrorEquals", List.of(target.error()), "IntervalSeconds", 1, - "BackoffRate", 1.0, "MaxAttempts", 1))); + boolean retried = eachIntegration().findFirst().orElseThrow().equals(integration); + if (retried) { + task.put("Retry", List.of(Map.of("ErrorEquals", List.of(target.error()), "IntervalSeconds", 1, + "BackoffRate", 1.0, "MaxAttempts", 1))); + } task.put("Catch", List.of(Map.of("ErrorEquals", List.of(target.error()), "Next", "Recovered"))); String definition = MAPPER.writeValueAsString(Map.of("StartAt", "Send", "States", Map.of("Send", task, "Recovered", Map.of("Type", "Pass", "End", true)))); @@ -287,7 +295,7 @@ class StepFunctionsJobTaskIamIntegrationTest { Response completed = terminal(execution); assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); - assertEquals(2, eventsOfType(execution, "TaskFailed").size()); + assertEquals(retried ? 2 : 1, eventsOfType(execution, "TaskFailed").size()); assertEquals(target.error(), eventsOfType(execution, "TaskFailed").getLast() .path("taskFailedEventDetails").path("error").asText()); } diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsMessagingTaskIamIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsMessagingTaskIamIntegrationTest.java index 2b1dee3f6d..af078f3bd2 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsMessagingTaskIamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsMessagingTaskIamIntegrationTest.java @@ -231,13 +231,21 @@ class StepFunctionsMessagingTaskIamIntegrationTest { assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); } + /** + * A refusal is caught under its own error name for every integration. The Retry path in front of + * the Catch is the same for all of them and costs a real one-second interval, so one integration + * proves it. + */ @ParameterizedTest @ValueSource(strings = {"sns:publish", "aws-sdk:sns:publish", "events:putEvents"}) void aRefusalCanBeRetriedAndCaught(String integration) throws Exception { Target target = target(integration); Map task = new LinkedHashMap<>(jsonPathTask(target, null)); - task.put("Retry", List.of(Map.of("ErrorEquals", List.of(target.error()), "IntervalSeconds", 1, - "BackoffRate", 1.0, "MaxAttempts", 1))); + boolean retried = "sns:publish".equals(integration); + if (retried) { + task.put("Retry", List.of(Map.of("ErrorEquals", List.of(target.error()), "IntervalSeconds", 1, + "BackoffRate", 1.0, "MaxAttempts", 1))); + } task.put("Catch", List.of(Map.of("ErrorEquals", List.of(target.error()), "Next", "Recovered"))); String definition = MAPPER.writeValueAsString(Map.of("StartAt", "Send", "States", Map.of("Send", task, "Recovered", Map.of("Type", "Pass", "End", true)))); @@ -246,14 +254,14 @@ class StepFunctionsMessagingTaskIamIntegrationTest { Response completed = terminal(execution); assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); - assertEquals(2, eventsOfType(execution, "TaskFailed").size()); + assertEquals(retried ? 2 : 1, eventsOfType(execution, "TaskFailed").size()); assertEquals(target.error(), eventsOfType(execution, "TaskFailed").getLast() .path("taskFailedEventDetails").path("error").asText()); } /** The retry decides again, so a role granted the action between attempts then delivers. */ @ParameterizedTest - @ValueSource(strings = {"sns:publish", "events:putEvents"}) + @ValueSource(strings = {"sns:publish"}) void aRetryDecidesAgain(String integration) throws Exception { Target target = target(integration); String roleName = "sfn-msg-" + UUID.randomUUID(); diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsSqsTaskIamIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsSqsTaskIamIntegrationTest.java index 11da39a70e..78f135168d 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsSqsTaskIamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsSqsTaskIamIntegrationTest.java @@ -299,13 +299,21 @@ class StepFunctionsSqsTaskIamIntegrationTest { assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); } + /** + * A refusal is caught under its own error name for every integration. The Retry path in front of + * the Catch is the same for all of them and costs a real one-second interval, so one integration + * proves it. + */ @ParameterizedTest @CsvSource({"sqs:sendMessage,SQS.AccessDeniedException", "aws-sdk:sqs:sendMessage,Sqs.AccessDeniedException"}) void aRefusalCanBeRetriedAndCaught(String integration, String error) throws Exception { SqsTestQueue queue = queue(); Map task = new LinkedHashMap<>(jsonPathTask(integration, queue, null)); - task.put("Retry", List.of(Map.of("ErrorEquals", List.of(error), "IntervalSeconds", 1, - "BackoffRate", 1.0, "MaxAttempts", 1))); + boolean retried = "sqs:sendMessage".equals(integration); + if (retried) { + task.put("Retry", List.of(Map.of("ErrorEquals", List.of(error), "IntervalSeconds", 1, + "BackoffRate", 1.0, "MaxAttempts", 1))); + } task.put("Catch", List.of(Map.of("ErrorEquals", List.of(error), "Next", "Recovered"))); String definition = MAPPER.writeValueAsString(Map.of("StartAt", "Send", "States", Map.of("Send", task, "Recovered", Map.of("Type", "Pass", "End", true)))); @@ -314,7 +322,7 @@ class StepFunctionsSqsTaskIamIntegrationTest { Response completed = terminal(execution); assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); - assertEquals(2, eventsOfType(execution, "TaskFailed").size()); + assertEquals(retried ? 2 : 1, eventsOfType(execution, "TaskFailed").size()); assertEquals(error, eventsOfType(execution, "TaskFailed").getLast() .path("taskFailedEventDetails").path("error").asText()); } diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsStopExecutionIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsStopExecutionIntegrationTest.java index 036a42f0c7..0a85ce9e14 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsStopExecutionIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsStopExecutionIntegrationTest.java @@ -78,6 +78,11 @@ class StepFunctionsStopExecutionIntegrationTest { assertEquals("probe", described.jsonPath().getString("cause")); } + /** + * The worker is still inside the Wait when the stop lands. Once it comes out, it neither + * rewrites the outcome nor records the state it left: the history still ends at + * ExecutionAborted, with no event id repeated. + */ @Test void stoppedExecutionStaysAbortedAfterTheWaitElapses() throws Exception { String executionArn = startWaitingExecution("stop-survives-wait"); @@ -89,10 +94,19 @@ class StepFunctionsStopExecutionIntegrationTest { 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")); + List> events = getExecutionHistory(executionArn).jsonPath().getList("events"); + List types = events.stream().map(event -> (String) event.get("type")).toList(); + List ids = events.stream().map(event -> event.get("id")).toList(); + + assertAll( + () -> assertEquals("ABORTED", described.jsonPath().getString("status")), + () -> assertEquals("Manual", described.jsonPath().getString("error")), + () -> assertEquals("probe", described.jsonPath().getString("cause")), + () -> assertEquals(stopDate, described.jsonPath().getDouble("stopDate")), + () -> 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)); } /** @@ -129,27 +143,6 @@ class StepFunctionsStopExecutionIntegrationTest { assertEquals(Map.of(), aborted.get("executionAbortedEventDetails")); } - @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> events = getExecutionHistory(executionArn).jsonPath().getList("events"); - List types = events.stream().map(event -> (String) event.get("type")).toList(); - List 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); diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsTimeoutSecondsIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsTimeoutSecondsIntegrationTest.java index 3b0d8ff4eb..84bf727b48 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsTimeoutSecondsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsTimeoutSecondsIntegrationTest.java @@ -25,6 +25,12 @@ import static org.junit.jupiter.api.Assertions.fail; *

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. + * + *

Each clock keeps one case here that runs it end to end, in real time. The budget cutting a + * task token, a Parallel branch and a Retry backoff, and a Catch on either heartbeat error name, + * run on a test clock in {@code AslExecutorExecutionBudgetTest}; the budget cutting a nested + * execution does in {@code AslExecutorNestedSyncTimeoutTest}. The Map cases stay here because + * {@code MapIterationScheduler} measures the budget on {@code System.nanoTime()} directly. */ @QuarkusTest class StepFunctionsTimeoutSecondsIntegrationTest { @@ -50,159 +56,24 @@ class StepFunctionsTimeoutSecondsIntegrationTest { } """); - Response timedOut = waitForTerminalExecution(startExecution(smArn, "{}")); + String execArn = startExecution(smArn, "{}"); + Response timedOut = waitForTerminalExecution(execArn); 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); + // The cut state gets no Exited event, and the terminal event carries only the error. 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()); + JsonNode timedOutEvent = events.get(events.size() - 1); + assertEquals(0, timedOutEvent.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"); - // The branch's Wait was entered and never exited: the budget cut it. - assertEquals(List.of("ExecutionStarted", "ParallelStateEntered", "ParallelStateStarted", - "WaitStateEntered", "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, and the child is aborted with it, as AWS does (measured: ABORTED, no error). - 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); - Response children = given() - .header("X-Amz-Target", "AWSStepFunctions.ListExecutions") - .contentType(SFN_CONTENT_TYPE) - .body(""" - {"stateMachineArn": "%s"} - """.formatted(childArn)) - .when() - .post("/"); - assertEquals(List.of("ABORTED"), children.jsonPath().getList("executions.status"), - children.body().asString()); + timedOutEvent.path("executionTimedOutEventDetails").path("error").asText()); + assertFalse(timedOutEvent.path("executionTimedOutEventDetails").has("cause"), + "ExecutionTimedOut carries only the error: " + timedOutEvent); } @Test @@ -282,41 +153,6 @@ class StepFunctionsTimeoutSecondsIntegrationTest { 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"); @@ -359,25 +195,6 @@ class StepFunctionsTimeoutSecondsIntegrationTest { "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"); @@ -416,25 +233,6 @@ class StepFunctionsTimeoutSecondsIntegrationTest { """.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 eventTypes(JsonNode events) { List types = new ArrayList<>(); events.forEach(event -> types.add(event.path("type").asText()));