From b31b76e4aace7b99027b752e5fd49bf465a2abb7 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:00:35 -0400 Subject: [PATCH] fix(stepfunctions): let a .sync cleanup pass over only a job that is gone (#8540) When a .sync Task's wait ends early, Step Functions "will make a best-effort attempt to cancel the task". Floci's EMR Serverless undo already passes over only the answers that say the application or run is gone or past undoing, and fails the Task with any other. Its three siblings passed over every failure: the EMR step's cancel, the ECS tasks' stop and the child execution's abort. Each now passes over only its service's answer for a job that is gone or past undoing, logged as before: EMR's InvalidRequestException for a cluster that is gone or a release that cannot cancel steps (a step it will not cancel comes back FAILED in an answer that succeeds), ECS's InvalidParameterException for a task it does not know, and Step Functions' ExecutionDoesNotExist; a task already stopped and a child already ended are answered without an error. Any other refusal fails the state with the integration's error (EMR., ECS., StepFunctions.) and the service's message, the ECS one once every task has been asked to stop, and any other failure is raised. --- docs/services/step-functions.md | 9 +++- .../services/stepfunctions/AslExecutor.java | 28 +++++++++-- .../stepfunctions/EmrTaskInvoker.java | 12 ++++- .../AslExecutorEcsRunTaskModeTest.java | 43 +++++++++++++++++ .../stepfunctions/AslExecutorEmrSyncTest.java | 48 +++++++++++++++++++ .../AslExecutorNestedSyncTimeoutTest.java | 26 ++++++++++ 6 files changed, 160 insertions(+), 6 deletions(-) diff --git a/docs/services/step-functions.md b/docs/services/step-functions.md index e35c142084..5229095ff5 100644 --- a/docs/services/step-functions.md +++ b/docs/services/step-functions.md @@ -356,6 +356,10 @@ both carry the cause `The Task state in AWS Step Functions execution [] whi this resource was aborted`. A `StopExecution` that lands while the state waits ends the wait and stops the job with the same cause, and so does the execution's budget, and so does a failure in another branch of the `Parallel`, or in another iteration of the `Map`, that the `Task` is in. +Stopping is best effort: an ECS task that is gone (`InvalidParameterException`) or already stopped, +or a child execution that is gone (`ExecutionDoesNotExist`) or already ended, leaves the state +ending as it would have; any other refusal fails it, with `ECS.` or `StepFunctions.` +and the service's message, and any other failure with `States.Runtime`. An `addStep.sync` step is cancelled with `CancelSteps` instead, and the cluster of a `createCluster.sync` is left running (see [Amazon EMR tasks](#amazon-emr-tasks)). An EMR Serverless job run is cancelled, a started application stopped and a created one deleted (see @@ -1299,7 +1303,10 @@ the same two clocks as the other `.sync` integrations (see [Timeouts](#timeouts) fail the Task with `States.TaskFailed`, the describe response as the cause: a JSON string, which a `Catch` reads with `States.StringToJson` (for example its `Step.Status.State`). When the wait ends early, `addStep.sync` cancels its step with `CancelSteps`, as Step Functions "will make -a best-effort attempt to cancel the task". A cluster is never terminated: "Step Functions does not +a best-effort attempt to cancel the task": if EMR answers that the cluster is gone or that its release +cannot cancel steps (`InvalidRequestException`), or reports the step past cancelling (a `FAILED` entry in +`CancelStepsInfoList`), the Task ends as it would have; any other failure fails it. A +cluster is never terminated: "Step Functions does not terminate an Amazon EMR cluster automatically if execution is stopped." EMR in Floci reaches each state at once, so every wait ends at its first poll. diff --git a/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java b/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java index 55028f4949..104a212422 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java @@ -2477,23 +2477,43 @@ public class AslExecutor { + "] which was managing this resource was aborted"; } - /** Best effort, like AWS: a task that is already gone does not change how the state ends. */ + /** + * Best effort, like AWS: a task that is already gone, which ECS answers with InvalidParameterException, does not + * change how the state ends, nor does one already stopped, which StopTask answers as it is. Any other refusal is a + * fault, raised as the integration's ECS error once every task has been asked to stop, as the emr-serverless undo + * raises its own; any other failure is raised at once. + */ private void stopEcsTasks(String cluster, List taskArns, String executionArn, String region) { + FailStateException fault = null; for (String taskArn : taskArns) { try { ecsService.stopTask(cluster, taskArn, syncAbortCause(executionArn), region); - } catch (RuntimeException e) { + } catch (AwsException e) { + if (!"InvalidParameterException".equals(e.getErrorCode())) { + fault = fault != null ? fault : new FailStateException("ECS." + e.getErrorCode(), e.getMessage()); + continue; + } LOG.warnv("ecs:runTask.sync ended before its task {0} did, and the task could not be stopped: {1}", taskArn, e.getMessage()); } } + if (fault != null) { + throw fault; + } } - /** Best effort, like AWS: a child that already ended does not change how the state ends. */ + /** + * Best effort, like AWS: a child that is gone, which Step Functions answers with ExecutionDoesNotExist, does not + * change how the state ends, nor does one that already ended, which StopExecution leaves as it is. Any other + * refusal is a fault, raised as the integration names a refused StartExecution, and any other failure is raised. + */ private void abortChildExecution(String childExecutionArn, String executionArn) { try { sfnService.get().stopExecution(childExecutionArn, syncAbortCause(executionArn), null); - } catch (RuntimeException e) { + } catch (AwsException e) { + if (!"ExecutionDoesNotExist".equals(e.getErrorCode())) { + throw new FailStateException(optimizedSfnErrorName(e.getErrorCode()), e.getMessage()); + } LOG.warnv("states:startExecution.sync ended before its child {0} did, and the child could not be stopped: {1}", childExecutionArn, e.getMessage()); } diff --git a/src/main/java/io/floci/aws/services/stepfunctions/EmrTaskInvoker.java b/src/main/java/io/floci/aws/services/stepfunctions/EmrTaskInvoker.java index d34293adbc..c5d6a78325 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/EmrTaskInvoker.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/EmrTaskInvoker.java @@ -37,6 +37,9 @@ public class EmrTaskInvoker { // a ValidationException fails addStep.sync as EMR.AmazonElasticMapReduceException. private static final Set MODELED_ERRORS = Set.of("InvalidRequestException", "InternalServerException"); private static final String BASE_ERROR = "AmazonElasticMapReduceException"; + // What EMR answers a step's cancel when its cluster is gone, or the step past cancelling where a cluster's release + // takes no cancel. + private static final String NOTHING_TO_UNDO = "EMR.InvalidRequestException"; private static final Set APIS = Set.of("createCluster", "setClusterTerminationProtection", "terminateCluster", "addStep", "cancelStep", "modifyInstanceFleetByName", "modifyInstanceGroupByName"); private static final Set SYNC_APIS = Set.of("createCluster", "terminateCluster", "addStep"); @@ -130,7 +133,14 @@ public class EmrTaskInvoker { request.putArray("StepIds").add(job.stepId()); try { call("CancelSteps", request, region); - } catch (RuntimeException e) { + } catch (AslExecutor.FailStateException e) { + // EMR's InvalidRequestException says the cluster is gone or its release cannot cancel steps (a step it + // will not cancel comes back FAILED in an answer that succeeds). Being best effort, either leaves the Task + // ending as it was. Any other answer, like any other failure, is a fault and is raised, as the + // emr-serverless undo raises its own. + if (!NOTHING_TO_UNDO.equals(e.error)) { + throw e; + } LOG.warnv("elasticmapreduce:addStep.sync ended before its step {0} did, and the step could not be " + "cancelled: {1}", job.stepId(), e.getMessage()); } diff --git a/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java index 9483321d42..bf5e756394 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java @@ -3,6 +3,7 @@ package io.floci.aws.services.stepfunctions; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.AwsException; import io.floci.aws.services.ecs.EcsJsonHandler; import io.floci.aws.services.ecs.EcsService; import io.floci.aws.services.ecs.container.HostVolumePolicy; @@ -179,6 +180,48 @@ class AslExecutorEcsRunTaskModeTest { + "] which was managing this resource was aborted"), eq(REGION)); } + @Test + void syncStillTimesOutWhenTheTaskItStopsIsAlreadyGone() throws Exception { + launchOneTask(); + when(ecsService.describeTasks(any(), any(), any())).thenReturn(List.of(task("RUNNING"))); + when(ecsService.stopTask(any(), any(), any(), any())) + .thenThrow(new AwsException("InvalidParameterException", "Task not found: task", 400)); + + Execution execution = runDefinition(""" + { + "StartAt": "RunTask", + "States": { + "RunTask": { "Type": "Task", "Resource": "arn:aws:states:::ecs:runTask.sync", + "TimeoutSeconds": 1, "End": true } + } + } + """, "{\"TaskDefinition\":\"my-task-def\"}"); + + // Best effort: a task that is gone leaves the state ending as it was. + assertEquals("States.Timeout", execution.getError()); + } + + @Test + void anotherRefusalStoppingTheTaskFailsTheStateWithIt() throws Exception { + launchOneTask(); + when(ecsService.describeTasks(any(), any(), any())).thenReturn(List.of(task("RUNNING"))); + when(ecsService.stopTask(any(), any(), any(), any())) + .thenThrow(new AwsException("ServerException", "The ECS service failed", 500)); + + Execution execution = runDefinition(""" + { + "StartAt": "RunTask", + "States": { + "RunTask": { "Type": "Task", "Resource": "arn:aws:states:::ecs:runTask.sync", + "TimeoutSeconds": 1, "End": true } + } + } + """, "{\"TaskDefinition\":\"my-task-def\"}"); + + assertEquals("ECS.ServerException", execution.getError()); + assertEquals("The ECS service failed", execution.getCause()); + } + /** * AWS records TaskSubmitted once RunTask has returned and before it waits on the task (measured: * resourceType ecs, resource runTask.sync, the response as Failures then Tasks in PascalCase, diff --git a/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEmrSyncTest.java b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEmrSyncTest.java index dfb5999c48..09c8f97edb 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEmrSyncTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEmrSyncTest.java @@ -2,6 +2,7 @@ package io.floci.aws.services.stepfunctions; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.AwsException; import io.floci.aws.services.emr.EmrHandler; import io.floci.aws.services.emr.EmrService; import io.floci.aws.services.emr.model.EmrCluster; @@ -90,6 +91,53 @@ class AslExecutorEmrSyncTest { verify(emrService).cancelSteps(CLUSTER_ID, List.of(STEP_ID)); } + @Test + void addStepSyncStillTimesOutWhenEmrNoLongerHasTheCluster() { + when(emrService.describeStep(CLUSTER_ID, STEP_ID)).thenReturn(step("RUNNING")); + when(emrService.cancelSteps(CLUSTER_ID, List.of(STEP_ID))).thenThrow(new AwsException( + "InvalidRequestException", "Cluster id 'j-SYNCTEST00001' is not valid.", 400)); + + Execution execution = run(""" + {"StartAt": "Add", "States": {"Add": {"Type": "Task", + "Resource": "arn:aws:states:::elasticmapreduce:addStep.sync", "TimeoutSeconds": 1, "End": true}}} + """, ADD_STEP); + + // Best effort: nothing left to cancel leaves the Task ending as it was. + assertEquals("States.Timeout", execution.getError()); + verify(emrService).cancelSteps(CLUSTER_ID, List.of(STEP_ID)); + } + + @Test + void addStepSyncStillTimesOutWhenEmrWillNotCancelTheStep() { + when(emrService.describeStep(CLUSTER_ID, STEP_ID)).thenReturn(step("RUNNING")); + when(emrService.cancelSteps(CLUSTER_ID, List.of(STEP_ID))).thenReturn(List.of( + new EmrService.CancelStepInfo(STEP_ID, "FAILED", "Step is not in a cancellable state: RUNNING"))); + + Execution execution = run(""" + {"StartAt": "Add", "States": {"Add": {"Type": "Task", + "Resource": "arn:aws:states:::elasticmapreduce:addStep.sync", "TimeoutSeconds": 1, "End": true}}} + """, ADD_STEP); + + // A step EMR will not cancel comes back FAILED in an answer that succeeds, which the cleanup passes over. + assertEquals("States.Timeout", execution.getError()); + verify(emrService).cancelSteps(CLUSTER_ID, List.of(STEP_ID)); + } + + @Test + void anInternalErrorCancellingTheStepFailsTheTaskWithIt() { + when(emrService.describeStep(CLUSTER_ID, STEP_ID)).thenReturn(step("RUNNING")); + when(emrService.cancelSteps(CLUSTER_ID, List.of(STEP_ID))) + .thenThrow(new AwsException("InternalServerException", "Request processing failed", 500)); + + Execution execution = run(""" + {"StartAt": "Add", "States": {"Add": {"Type": "Task", + "Resource": "arn:aws:states:::elasticmapreduce:addStep.sync", "TimeoutSeconds": 1, "End": true}}} + """, ADD_STEP); + + assertEquals("EMR.InternalServerException", execution.getError()); + assertEquals("Request processing failed", execution.getCause()); + } + @Test void addStepSyncFailsWithTheStepWhenTheStepFails() throws Exception { EmrStep failed = step("FAILED"); 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 e132962157..8b9b2f77ea 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorNestedSyncTimeoutTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorNestedSyncTimeoutTest.java @@ -2,6 +2,7 @@ package io.floci.aws.services.stepfunctions; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.AwsException; import io.floci.aws.services.stepfunctions.model.Execution; import io.floci.aws.services.stepfunctions.model.ExecutionStatusSubscription; import io.floci.aws.services.stepfunctions.model.HistoryEvent; @@ -32,6 +33,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; @@ -88,6 +90,30 @@ class AslExecutorNestedSyncTimeoutTest { verify(sfnService).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull()); } + @Test + void syncStillTimesOutWhenTheChildItAbortsIsGone() { + when(sfnService.describeExecution(CHILD_ARN)).thenReturn(child("RUNNING")); + doThrow(new AwsException("ExecutionDoesNotExist", "Execution does not exist", 400)) + .when(sfnService).stopExecution(eq(CHILD_ARN), any(), any()); + + Execution execution = run(newExecutor(TimeUnit.NANOSECONDS::sleep), ".sync", 1, false); + + // Best effort: a child that is gone leaves the state ending as it was. + assertEquals("States.Timeout", execution.getError()); + } + + @Test + void anotherRefusalAbortingTheChildFailsTheStateWithIt() { + when(sfnService.describeExecution(CHILD_ARN)).thenReturn(child("RUNNING")); + doThrow(new AwsException("ValidationException", "The execution could not be stopped", 400)) + .when(sfnService).stopExecution(eq(CHILD_ARN), any(), any()); + + Execution execution = run(newExecutor(TimeUnit.NANOSECONDS::sleep), ".sync", 1, false); + + assertEquals("StepFunctions.ValidationException", execution.getError()); + assertEquals("The execution could not be stopped", execution.getCause()); + } + @Test void sync2TimeoutIsCaughtUnderStatesTimeout() throws Exception { when(sfnService.describeExecution(CHILD_ARN)).thenReturn(child("RUNNING"));