diff --git a/docs/services/step-functions.md b/docs/services/step-functions.md index 3c41c5ec6b..4581c653c5 100644 --- a/docs/services/step-functions.md +++ b/docs/services/step-functions.md @@ -94,7 +94,10 @@ ends a `Parallel`, each other branch that is still inside a `Task` or a `Wait` r `TaskStateAborted` or `WaitStateAborted`, chained to the failing branch's last event and recorded before `ParallelStateFailed`. The `Parallel` fails the moment any branch fails, whichever branch is listed first, and cuts the others then; the branch outputs still come back in declaration -order. +order. When a failure ends an inline `Map`, each other iteration that is still running records +`MapIterationAborted`, and one still inside a `Task` or a `Wait` records `TaskStateAborted` or +`WaitStateAborted` right after it, all chained to the failing iteration's last event and recorded +before `MapIterationFailed` and `MapStateFailed`. Branches and iterations run concurrently, so the order in which their events interleave differs from run to run. Each branch chains its own events through `previousEventId`, and that chain is @@ -122,11 +125,7 @@ When the request sets `includeExecutionData` to false, the details objects stay A few gaps remain. `TaskStarted`, `LambdaFunctionStarted`, and `ActivityStarted` fire at scheduling time, not when a worker actually picks up the task. `TaskSubmitted` is recorded for the three `.sync` integrations above and not yet for a `.waitForTaskToken` one, which AWS also -records it for. When an inline `Map` iteration fails, AWS records a `MapIterationAborted` for each -iteration it cuts and the `*StateAborted` of the state that iteration was in, all chained to the -failing iteration's last event and recorded before `MapIterationFailed` and `MapStateFailed`; Floci -cancels the iterations without recording them, where a `Parallel` records the state of each branch -it cuts, as above. A Distributed `Map` that declares no tolerance reports a failed item's own error +records it for. A Distributed `Map` that declares no tolerance reports a failed item's own error rather than AWS's `States.ExceedToleratedFailureThreshold`, and emits `MapRunFailed` with that error. A `Map` that declares one reports `States.ExceedToleratedFailureThreshold`, as AWS does. diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java index 0d5adb38c0..7396549f44 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java @@ -2875,7 +2875,7 @@ public class AslExecutor { : resolveParameters(itemTransform, mapInput, iterContext); } if (!distributed) { - iterationChain.publish("MapIterationStarted", Map.of("name", name, "index", i)); + iterationChain.publishIterationStart("MapIterationStarted", Map.of("name", name, "index", i)); } iterationStarted = true; if (hasResultWriter) { @@ -2891,17 +2891,20 @@ public class AslExecutor { } catch (FailStateException e) { int failedSoFar = failedItems.addAndGet(itemsInChild); failedExecutions.incrementAndGet(); - if (iterationStarted && !distributed && !e.isRuntimeError()) { - iterationChain.publishAside("MapIterationFailed", Map.of("name", name, "index", i)); - } + boolean recordFailed = iterationStarted && !distributed && !e.isRuntimeError(); + // A failure that ends the Map records its MapIterationFailed only once the other + // iterations have been cut, since AWS records what it cut first. if (!tolerated.declared()) { - throw new IterationFailure(i, e); + throw new IterationFailure(i, e, recordFailed); } if (failedSoFar > tolerated.threshold()) { throw new IterationFailure(i, new FailStateException( "States.ExceedToleratedFailureThreshold", "The map run failed because a tolerated failure threshold was exceeded. " - + failedSoFar + " of " + itemCount + " items failed.")); + + failedSoFar + " of " + itemCount + " items failed."), recordFailed); + } + if (recordFailed) { + iterationChain.publishIterationEndAside("MapIterationFailed", Map.of("name", name, "index", i)); } if (hasResultWriter) { failedByIndex[i] = new FailedChild(childInputsByIndex[i], @@ -2912,7 +2915,7 @@ public class AslExecutor { succeededItems.addAndGet(itemsInChild); succeededExecutions.incrementAndGet(); if (!distributed) { - iterationChain.publish("MapIterationSucceeded", Map.of("name", name, "index", i)); + iterationChain.publishIterationEnd("MapIterationSucceeded", Map.of("name", name, "index", i)); } if (hasResultWriter) { childTimingsByIndex[i] = new long[]{startMs, System.currentTimeMillis()}; @@ -2922,11 +2925,17 @@ public class AslExecutor { if (childCount > 0) { List itemOutputs; + // The iterations a failure cuts, each read and cut in one step before it is cancelled, + // as a Parallel does with its branches (cutAfterFailure). Filled on this thread. Only an + // iteration whose start is recorded and whose end is not gets recorded: the scheduler + // names every iteration it has not yet taken off its queue, started or ended or not. + List cutIterations = new ArrayList<>(); try { itemOutputs = MapIterationScheduler.execute( childCount, Math.max(1, effectiveConcurrency), i -> () -> callUnderExecutionAccount(sm, makeTask.apply(i)), - executionDeadlineNanos); + executionDeadlineNanos, + i -> cutIteration(iterationChains.get(i), i, cutIterations)); } catch (java.util.concurrent.TimeoutException e) { // The only deadline the scheduler is given is the state machine's budget, so its // expiry ends the execution rather than failing the Map state. @@ -2935,6 +2944,19 @@ public class AslExecutor { // A Distributed Map's chain stays at MapRunStarted, as on AWS. if (!distributed) { chain.continueFrom(iterationChains.get(e.index).lastEventId()); + // Each event follows the rule of the one it accompanies. The cut iterations are + // recorded right before MapStateFailed and follow its rule: the failure that ends + // the Map is not States.Runtime. MapIterationFailed follows the iteration's own: + // it started, and its own error is not States.Runtime. The two differ for an + // ItemSelector that fails before the iteration starts, which cuts the others but + // has no iteration to report, and for a States.Runtime failure that exceeds a + // declared tolerance, where the Map ends with the tolerance error instead. + if (!e.failure.isRuntimeError()) { + publishCutIterations(chain, name, cutIterations); + } + if (e.recordFailed) { + chain.publishBeside("MapIterationFailed", Map.of("name", name, "index", e.index)); + } } else { publishMapRunFailedEvent(chain, e.failure); recordMapRun(mapRunRecord, "FAILED", succeededItems.get(), failedItems.get(), @@ -5846,11 +5868,40 @@ public class AslExecutor { private static final class IterationFailure extends RuntimeException { final int index; final FailStateException failure; + /** Whether the Map records the iteration's MapIterationFailed once the others are cut. */ + final boolean recordFailed; - IterationFailure(int index, FailStateException failure) { + IterationFailure(int index, FailStateException failure, boolean recordFailed) { super(failure.getMessage(), failure, false, false); this.index = index; this.failure = failure; + this.recordFailed = recordFailed; + } + } + + /** An iteration a failure cut, and the state it was in, or null when it was between states. */ + private record CutIteration(int index, String stateType) {} + + private static void cutIteration(HistoryChain iteration, int index, List cutIterations) { + HistoryChain.IterationCut cut = iteration.abandonIteration(); + if (cut.recorded()) { + cutIterations.add(new CutIteration(index, cut.stateType())); + } + } + + /** + * Records the iterations a failure cut, the way AWS was measured recording them: for each, a + * {@code MapIterationAborted} and then the {@code *StateAborted} of the Task or Wait it was in, + * all chained to the failing iteration's last event, ahead of {@code MapIterationFailed} and + * {@code MapStateFailed}. An iteration between states, or inside any other state type, records + * only the {@code MapIterationAborted}. + */ + private static void publishCutIterations(HistoryChain chain, String name, List cutIterations) { + for (CutIteration cut : cutIterations) { + chain.publishBeside("MapIterationAborted", Map.of("name", name, "index", cut.index())); + if ("Task".equals(cut.stateType()) || "Wait".equals(cut.stateType())) { + chain.publishBeside(cut.stateType() + "StateAborted", null); + } } } diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/HistoryChain.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/HistoryChain.java index bf3f6416c3..b499bd105a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/HistoryChain.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/HistoryChain.java @@ -21,6 +21,8 @@ final class HistoryChain { private final HistoryChain parent; private volatile boolean abandoned; private String activeStateType; + private boolean iterationStarted; + private boolean iterationEnded; private long lastEventId; private long tailEventId; @@ -120,6 +122,52 @@ final class HistoryChain { return activeStateType; } + /** + * Publishes the event that starts a Map iteration and marks it started, under the same lock a + * cut takes, so an iteration is reported cut only when its start is recorded. + */ + synchronized void publishIterationStart(String type, Map details) { + if (publish(type, details) > 0) { + iterationStarted = true; + } + } + + /** + * Publishes the event that ends a Map iteration and marks the iteration ended, under the same + * lock a cut takes, so an iteration is reported either ended or cut, never both. + */ + synchronized void publishIterationEnd(String type, Map details) { + iterationEnded = true; + publish(type, details); + } + + /** {@link #publishIterationEnd} for an event recorded aside, as a tolerated MapIterationFailed is. */ + synchronized void publishIterationEndAside(String type, Map details) { + iterationEnded = true; + publishAside(type, details); + } + + /** + * What a cut found an iteration doing: not yet started, already ended, or else inside + * {@code stateType}, or between states when that is null. + */ + record IterationCut(boolean started, boolean ended, String stateType) { + /** True for an iteration whose start is recorded and whose end never will be. */ + boolean recorded() { + return started && !ended; + } + } + + /** + * Cuts the chain like {@link #abandonInState} and also reports whether the iteration had + * recorded its start and its end. An iteration cut first records neither afterwards; one that + * ended first is not reported as cut, and one that had not started is not reported at all. + */ + synchronized IterationCut abandonIteration() { + abandoned = true; + return new IterationCut(iterationStarted, iterationEnded, activeStateType); + } + private boolean isAbandoned() { for (var chain = this; chain != null; chain = chain.parent) { if (chain.abandoned) { diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/MapIterationScheduler.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/MapIterationScheduler.java index 77b6a8450f..d4ebf1b9a1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/MapIterationScheduler.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/MapIterationScheduler.java @@ -1,10 +1,11 @@ package io.github.hectorvent.floci.services.stepfunctions; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; -import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; -import java.util.Set; +import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; @@ -14,6 +15,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import java.util.function.IntConsumer; import java.util.function.IntFunction; /** Runs Map iterations with a bounded in-flight window while preserving input order. */ @@ -31,6 +33,19 @@ final class MapIterationScheduler { static List execute(int itemCount, int maxConcurrency, IntFunction> taskFactory, long deadlineNanos) throws Exception { + return execute(itemCount, maxConcurrency, taskFactory, deadlineNanos, index -> { }); + } + + /** + * @param cutting called with the index of every iteration still in flight when another one + * fails, in start order and before any of them is cancelled, so the caller can + * read the state each is in while it is still running. Not called when the + * deadline ends the run. + */ + static List execute(int itemCount, int maxConcurrency, + IntFunction> taskFactory, long deadlineNanos, + IntConsumer cutting) + throws Exception { if (itemCount < 0) { throw new IllegalArgumentException("itemCount must not be negative"); } @@ -49,19 +64,20 @@ final class MapIterationScheduler { ExecutorService executor = Executors.newThreadPerTaskExecutor( Thread.ofVirtual().name("sfn-map-", 0).factory()); CompletionService> completions = new ExecutorCompletionService<>(executor); - Set>> inFlight = new HashSet<>(); + Map>, Integer> inFlight = new LinkedHashMap<>(); int nextIndex = 0; int completed = 0; try { while (nextIndex < inFlightLimit) { - inFlight.add(submit(completions, taskFactory, nextIndex++)); + inFlight.put(submit(completions, taskFactory, nextIndex), nextIndex); + nextIndex++; } while (completed < itemCount) { Future> future = completions.poll(deadlineNanos - System.nanoTime(), TimeUnit.NANOSECONDS); if (future == null) { - cancel(inFlight); + cancel(inFlight.keySet()); throw new TimeoutException(); } inFlight.remove(future); @@ -69,12 +85,14 @@ final class MapIterationScheduler { results.set(result.index(), result.value()); completed++; if (nextIndex < itemCount) { - inFlight.add(submit(completions, taskFactory, nextIndex++)); + inFlight.put(submit(completions, taskFactory, nextIndex), nextIndex); + nextIndex++; } } return results; } catch (ExecutionException e) { - cancel(inFlight); + inFlight.values().forEach(cutting::accept); + cancel(inFlight.keySet()); Throwable cause = e.getCause(); if (cause instanceof Exception exception) { throw exception; @@ -84,11 +102,11 @@ final class MapIterationScheduler { } throw new RuntimeException(cause); } catch (InterruptedException e) { - cancel(inFlight); + cancel(inFlight.keySet()); Thread.currentThread().interrupt(); throw e; } finally { - cancel(inFlight); + cancel(inFlight.keySet()); executor.shutdownNow(); } } @@ -99,7 +117,7 @@ final class MapIterationScheduler { return completions.submit(() -> new IndexedResult<>(index, taskFactory.apply(index).call())); } - private static void cancel(Set> futures) { + private static void cancel(Collection> futures) { futures.forEach(future -> future.cancel(true)); } diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorParallelCutTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorParallelCutTest.java index fde877ddac..e0793c136d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorParallelCutTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorParallelCutTest.java @@ -27,6 +27,7 @@ import org.junit.jupiter.api.Timeout; import java.time.Clock; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; @@ -87,14 +88,21 @@ class AslExecutorParallelCutTest { {"StartAt":"Done","States":{"Done":{"Type":"Pass","End":true}}}"""; private static final String LONG_WAIT_BRANCH = """ {"StartAt":"Long","States":{"Long":{"Type":"Wait","Seconds":20,"End":true}}}"""; - /** An inline Map whose "fail" item runs the failing branch and whose other items run the nested one. */ + /** + * An inline Map whose "fail" item runs the failing branch, whose "wait" item runs the long Wait, + * whose "done" item is a Pass, and whose other items run the nested Task. + */ private static final String MAP_WITH_A_FAILING_ITERATION = """ {"Type":"Map","End":true,"ItemProcessor":{"ProcessorConfig":{"Mode":"INLINE"}, "StartAt":"Route","States":{ "Route":{"Type":"Choice","Default":"Nest", - "Choices":[{"Variable":"$.kind","StringEquals":"fail","Next":"Pause"}]}, + "Choices":[{"Variable":"$.kind","StringEquals":"fail","Next":"Pause"}, + {"Variable":"$.kind","StringEquals":"wait","Next":"Long"}, + {"Variable":"$.kind","StringEquals":"done","Next":"Done"}]}, "Pause":{"Type":"Wait","Seconds":1,"Next":"Boom"}, "Boom":{"Type":"Fail","Error":"Boom","Cause":"sibling failed"}, + "Long":{"Type":"Wait","Seconds":20,"End":true}, + "Done":{"Type":"Pass","End":true}, "Nest":{"Type":"Task","Resource":"arn:aws:states:::states:startExecution.sync:2", "Parameters":{"StateMachineArn":"%s"},"End":true}}}}""".formatted(CHILD_SM_ARN); private static final String SLOW_RESULT_BRANCH = """ @@ -225,6 +233,130 @@ class AslExecutorParallelCutTest { verify(sfnService, timeout(5_000)).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull()); } + /** + * Measured on AWS: a failing iteration records, for each iteration it cuts, MapIterationAborted + * and then the *StateAborted of the state it was in, all chained to the failing iteration's last + * event and ahead of MapIterationFailed and MapStateFailed, which point at that same event. + */ + @Test + void aMapIterationCutInsideItsTaskRecordsMapIterationAbortedAndTaskStateAborted() { + Execution execution = run(MAP_WITH_A_FAILING_ITERATION, sleeper(1), 0, + "[{\"kind\":\"nest\"},{\"kind\":\"fail\"}]"); + + assertEquals("FAILED", execution.getStatus()); + HistoryEvent failure = eventOfType("FailStateEntered"); + List tail = history.subList(history.indexOf(failure) + 1, history.size()); + assertEquals(List.of("MapIterationAborted", "TaskStateAborted", "MapIterationFailed", "MapStateFailed", + "ExecutionFailed"), tail.stream().map(HistoryEvent::getType).toList(), types().toString()); + for (HistoryEvent event : tail.subList(0, 4)) { + assertEquals(failure.getId(), event.getPreviousEventId().longValue(), event.getType()); + } + assertEquals(Map.of("name", "P", "index", 0), tail.get(0).getDetails()); + assertNull(tail.get(1).getDetails()); + assertEquals(Map.of("name", "P", "index", 1), tail.get(2).getDetails()); + assertEquals(tail.get(3).getId(), tail.get(4).getPreviousEventId().longValue()); + verify(sfnService, timeout(5_000)).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull()); + } + + @Test + void aMapIterationCutInsideItsWaitRecordsMapIterationAbortedAndWaitStateAborted() { + Execution execution = run(MAP_WITH_A_FAILING_ITERATION, sleeper(1), 0, + "[{\"kind\":\"fail\"},{\"kind\":\"wait\"}]"); + + assertEquals("FAILED", execution.getStatus()); + long failure = eventOfType("FailStateEntered").getId(); + HistoryEvent aborted = eventOfType("MapIterationAborted"); + assertEquals(Map.of("name", "P", "index", 1), aborted.getDetails()); + assertEquals(failure, aborted.getPreviousEventId().longValue()); + HistoryEvent waitAborted = eventOfType("WaitStateAborted"); + assertEquals(failure, waitAborted.getPreviousEventId().longValue()); + assertTrue(aborted.getId() < waitAborted.getId()); + assertTrue(waitAborted.getId() < eventOfType("MapIterationFailed").getId()); + assertEquals(List.of("Pause"), eventsOfType("WaitStateExited").stream() + .map(event -> String.valueOf(event.getDetails().get("name"))).toList(), types().toString()); + } + + /** + * Each event follows the rule of the one it accompanies. A States.Runtime failure in an + * iteration records no MapIterationFailed; when what ends the Map is the tolerance it exceeded, + * MapStateFailed is recorded, and so are the iterations that failure cut, right before it. + */ + @Test + void aRuntimeFailureThatExceedsTheToleranceRecordsTheOnesItCutButNotItself() { + String map = MAP_WITH_A_FAILING_ITERATION.replace("\"Type\":\"Map\",", "\"Type\":\"Map\",\"ToleratedFailureCount\":0,") + .replace("\"Default\":\"Nest\",", ""); + Execution execution = run(map, sleeper(1), 0, "[{\"kind\":\"wait\"},{\"kind\":\"nomatch\"}]"); + + assertEquals("FAILED", execution.getStatus()); + assertEquals("States.ExceedToleratedFailureThreshold", execution.getError()); + assertTrue(types().stream().noneMatch("MapIterationFailed"::equals), types().toString()); + int stateFailed = types().indexOf("MapStateFailed"); + assertEquals(List.of("MapIterationAborted", "WaitStateAborted"), types().subList(stateFailed - 2, stateFailed), + types().toString()); + } + + /** + * A States.Runtime failure that ends the Map records no MapStateFailed, and nothing for the + * iterations it cut either. + */ + @Test + void aRuntimeFailureThatEndsTheMapRecordsNothingForTheOnesItCut() { + String map = MAP_WITH_A_FAILING_ITERATION.replace("\"Default\":\"Nest\",", ""); + Execution execution = run(map, sleeper(1), 0, "[{\"kind\":\"wait\"},{\"kind\":\"nomatch\"}]"); + + assertEquals("FAILED", execution.getStatus()); + assertEquals("States.Runtime", execution.getError()); + assertTrue(types().stream().noneMatch(type -> type.contains("Aborted") || type.endsWith("Failed") + && !type.equals("ExecutionFailed")), types().toString()); + } + + /** + * An ItemSelector that fails does so before its iteration starts, so there is no + * MapIterationFailed to record, but the Map fails with the expression's error and the + * iterations it cut are recorded before MapStateFailed. Which state the other iteration had + * reached by then is a race the test does not fix, so it asserts the invariant over many runs: + * an iteration is recorded cut exactly when its start is recorded and its end is not. + */ + @Test + void anItemSelectorFailureRecordsTheIterationsItCutOnlyOnceTheyStarted() { + String map = """ + {"Type":"Map","End":true,"QueryLanguage":"JSONata","Items":"{% $states.input %}", + "ItemSelector":{"kind":"{% $states.context.Map.Item.Value.kind %}", + "v":"{% $states.context.Map.Item.Value.v %}"}, + "ItemProcessor":{"ProcessorConfig":{"Mode":"INLINE"},"StartAt":"Long","States":{ + "Long":{"Type":"Wait","Seconds":20,"End":true}}}}"""; + for (int round = 0; round < 40; round++) { + Execution execution = run(map, nanos -> TimeUnit.NANOSECONDS.sleep(nanos), 0, + "[{\"kind\":\"wait\",\"v\":1},{\"kind\":\"selector\"}]"); + + assertEquals("FAILED", execution.getStatus(), types().toString()); + assertEquals("States.QueryEvaluationError", execution.getError(), types().toString()); + assertTrue(types().contains("MapStateFailed"), types().toString()); + assertTrue(types().stream().noneMatch("MapIterationFailed"::equals), types().toString()); + boolean started = types().contains("MapIterationStarted"); + boolean ended = types().contains("MapIterationSucceeded"); + assertEquals(started && !ended, types().contains("MapIterationAborted"), "round " + round + ": " + types()); + boolean inWait = types().contains("WaitStateEntered") && !types().contains("WaitStateExited"); + assertEquals(started && !ended && inWait, types().contains("WaitStateAborted"), "round " + round + ": " + types()); + if (types().contains("MapIterationAborted")) { + assertTrue(types().indexOf("MapIterationAborted") < types().indexOf("MapStateFailed"), types().toString()); + } + } + } + + @Test + void aMapIterationThatFinishedBeforeTheFailureRecordsNoAbortedEvent() { + AslExecutor.Sleeper sleeper = nanos -> TimeUnit.MILLISECONDS.sleep(200); + Execution execution = run(MAP_WITH_A_FAILING_ITERATION, sleeper, 0, + "[{\"kind\":\"done\"},{\"kind\":\"fail\"}]"); + + assertEquals("FAILED", execution.getStatus()); + assertEquals(1, eventsOfType("MapIterationSucceeded").size(), types().toString()); + assertTrue(types().stream().noneMatch(type -> type.contains("Aborted")), types().toString()); + assertEquals(eventOfType("FailStateEntered").getId(), + eventOfType("MapIterationFailed").getPreviousEventId().longValue()); + } + @Test void executionBudgetCuttingTheParallelAbortsTheChildAndRecordsNoAbortedState() { Execution execution = run(parallel(NESTED_SYNC_BRANCH), 0, 1); diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/HistoryChainTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/HistoryChainTest.java index 6503d77cf0..58c10741a5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/HistoryChainTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/HistoryChainTest.java @@ -11,7 +11,9 @@ import java.util.concurrent.CountDownLatch; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; class HistoryChainTest { @@ -95,6 +97,87 @@ class HistoryChainTest { assertEquals(List.of("TaskStateEntered"), typesOf(history)); } + @Test + void anIterationThatEndedBeforeTheCutIsReportedEndedAndNotCut() { + List history = new ArrayList<>(); + HistoryChain iteration = HistoryChain.of(history).fork(); + iteration.publishIterationStart("MapIterationStarted", null); + iteration.publishStateEntered("Task", "TaskStateEntered", null); + iteration.publishStateExited("TaskStateExited", null); + iteration.publishIterationEnd("MapIterationSucceeded", null); + + HistoryChain.IterationCut cut = iteration.abandonIteration(); + + assertTrue(cut.started()); + assertTrue(cut.ended()); + assertFalse(cut.recorded()); + assertNull(cut.stateType()); + assertEquals(List.of("MapIterationStarted", "TaskStateEntered", "TaskStateExited", "MapIterationSucceeded"), + typesOf(history)); + } + + @Test + void anIterationCutBeforeItEndsIsReportedInItsStateAndRecordsNoEnd() { + List history = new ArrayList<>(); + HistoryChain iteration = HistoryChain.of(history).fork(); + iteration.publishIterationStart("MapIterationStarted", null); + iteration.publishStateEntered("Task", "TaskStateEntered", null); + + HistoryChain.IterationCut cut = iteration.abandonIteration(); + iteration.publishStateExited("TaskStateExited", null); + iteration.publishIterationEnd("MapIterationSucceeded", null); + + assertTrue(cut.recorded()); + assertFalse(cut.ended()); + assertEquals("Task", cut.stateType()); + assertEquals(List.of("MapIterationStarted", "TaskStateEntered"), typesOf(history)); + } + + @Test + void anIterationCutBeforeItStartsIsNotReportedAndRecordsNoStart() { + List history = new ArrayList<>(); + HistoryChain iteration = HistoryChain.of(history).fork(); + + HistoryChain.IterationCut cut = iteration.abandonIteration(); + iteration.publishIterationStart("MapIterationStarted", null); + iteration.publishStateEntered("Task", "TaskStateEntered", null); + + assertFalse(cut.started()); + assertFalse(cut.recorded()); + assertEquals(List.of(), typesOf(history)); + } + + @Test + void aCutRacingAnIterationNeverDisagreesWithItsRecordedStartAndEnd() throws Exception { + for (int round = 0; round < 2_000; round++) { + List history = Collections.synchronizedList(new ArrayList<>()); + HistoryChain iteration = HistoryChain.of(history).fork(); + CountDownLatch start = new CountDownLatch(1); + Thread worker = new Thread(() -> { + try { + start.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + iteration.publishIterationStart("MapIterationStarted", null); + iteration.publishStateEntered("Task", "TaskStateEntered", null); + iteration.publishStateExited("TaskStateExited", null); + iteration.publishIterationEnd("MapIterationSucceeded", null); + }); + worker.start(); + start.countDown(); + HistoryChain.IterationCut cut = iteration.abandonIteration(); + worker.join(); + + List types = typesOf(history); + assertEquals(types.contains("MapIterationStarted"), cut.started(), "round " + round + ": " + cut + " with " + types); + assertEquals(types.contains("MapIterationSucceeded"), cut.ended(), "round " + round + ": " + cut + " with " + types); + boolean cutMidState = types.contains("TaskStateEntered") && !types.contains("TaskStateExited"); + assertEquals(cutMidState, "Task".equals(cut.stateType()), "round " + round + ": " + cut + " with " + types); + } + } + @Test void aCutRacingAStateNeverDisagreesWithTheRecordedEvents() throws Exception { for (int round = 0; round < 2_000; round++) { diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/MapIterationSchedulerTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/MapIterationSchedulerTest.java index b8e3985453..65571209c7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/MapIterationSchedulerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/MapIterationSchedulerTest.java @@ -5,6 +5,7 @@ import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -226,4 +227,62 @@ class MapIterationSchedulerTest { "the iterations still running should be interrupted once the deadline passes"); } } + @Test + void namesEachInFlightIterationBeforeCancellingItOnFailure() throws Exception { + CountDownLatch othersStarted = new CountDownLatch(2); + CountDownLatch neverRelease = new CountDownLatch(1); + CountDownLatch othersInterrupted = new CountDownLatch(2); + List cut = new CopyOnWriteArrayList<>(); + List namedWhenInterrupted = new CopyOnWriteArrayList<>(); + + try (ExecutorService driver = Executors.newSingleThreadExecutor()) { + Future> execution = driver.submit(() -> MapIterationScheduler.execute( + 3, 3, index -> () -> { + if (index == 1) { + if (!othersStarted.await(2, TimeUnit.SECONDS)) { + fail("the other iterations did not start"); + } + throw new IllegalStateException("middle iteration failed"); + } + othersStarted.countDown(); + try { + neverRelease.await(); + return index; + } catch (InterruptedException e) { + if (cut.contains(index)) { + namedWhenInterrupted.add(index); + } + othersInterrupted.countDown(); + throw e; + } + }, Long.MAX_VALUE, cut::add)); + + assertThrows(ExecutionException.class, () -> execution.get(2, TimeUnit.SECONDS)); + } + + assertEquals(List.of(0, 2), cut, "every in-flight iteration, in start order, never the failed one"); + assertTrue(othersInterrupted.await(2, TimeUnit.SECONDS)); + assertEquals(List.of(0, 2), namedWhenInterrupted.stream().sorted().toList(), + "each was named before it was cancelled"); + } + + @Test + void namesNoIterationWhenTheDeadlineEndsTheRun() throws Exception { + CountDownLatch neverRelease = new CountDownLatch(1); + List cut = new CopyOnWriteArrayList<>(); + + try (ExecutorService driver = Executors.newSingleThreadExecutor()) { + Future> execution = driver.submit(() -> MapIterationScheduler.execute( + 2, 2, index -> () -> { + neverRelease.await(); + return index; + }, System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(100), cut::add)); + + ExecutionException failure = assertThrows(ExecutionException.class, + () -> execution.get(2, TimeUnit.SECONDS)); + assertEquals(TimeoutException.class, failure.getCause().getClass()); + } + + assertEquals(List.of(), cut); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsMapIterationFailureIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsMapIterationFailureIntegrationTest.java new file mode 100644 index 0000000000..e6c17a0fa9 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsMapIterationFailureIntegrationTest.java @@ -0,0 +1,157 @@ +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.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * An inline {@code Map} iteration that fails cuts the other iterations, and the history records what + * it cut the way AWS does (measured in ap-northeast-1 on 2026-09-30): a {@code MapIterationAborted} + * and then the {@code *StateAborted} of the state each cut iteration was in, all chained to the + * failing iteration's last event, ahead of {@code MapIterationFailed} and {@code MapStateFailed}. + */ +@QuarkusTest +class StepFunctionsMapIterationFailureIntegrationTest { + + 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 aFailingIterationRecordsTheIterationItCutAndTheWaitItWasIn() throws Exception { + String smArn = createStateMachine("map-iteration-cut", """ + { + "StartAt": "M", + "States": { + "M": { + "Type": "Map", + "End": true, + "ItemsPath": "$.items", + "ItemProcessor": { + "ProcessorConfig": {"Mode": "INLINE"}, + "StartAt": "Route", + "States": { + "Route": {"Type": "Choice", "Default": "Long", + "Choices": [{"Variable": "$.kind", "StringEquals": "fail", "Next": "Pause"}]}, + "Long": {"Type": "Wait", "Seconds": 15, "End": true}, + "Pause": {"Type": "Wait", "Seconds": 1, "Next": "Boom"}, + "Boom": {"Type": "Fail", "Error": "Boom", "Cause": "sibling failed"} + } + } + } + } + } + """); + String execArn = startExecution(smArn, "{\"items\": [{\"kind\": \"long\"}, {\"kind\": \"fail\"}]}"); + + Response failed = waitForTerminalExecution(execArn, 8_000); + + assertEquals("FAILED", failed.jsonPath().getString("status"), failed.body().asString()); + assertEquals("Boom", failed.jsonPath().getString("error")); + JsonNode events = MAPPER.readTree(getExecutionHistory(execArn).body().asString()).path("events"); + List types = new ArrayList<>(); + events.forEach(event -> types.add(event.path("type").asText())); + int failure = types.indexOf("FailStateEntered"); + assertTrue(failure > 0, types.toString()); + assertEquals(List.of("MapIterationAborted", "WaitStateAborted", "MapIterationFailed", "MapStateFailed", + "ExecutionFailed"), types.subList(failure + 1, types.size()), types.toString()); + long failureId = events.get(failure).path("id").asLong(); + for (int i = failure + 1; i <= failure + 4; i++) { + assertEquals(failureId, events.get(i).path("previousEventId").asLong(), types.get(i)); + } + JsonNode aborted = events.get(failure + 1).path("mapIterationAbortedEventDetails"); + assertEquals("M", aborted.path("name").asText()); + assertEquals(0, aborted.path("index").asInt()); + assertEquals(1, events.get(failure + 3).path("mapIterationFailedEventDetails").path("index").asInt()); + } + + 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) { + Response resp = given() + .header("X-Amz-Target", "AWSStepFunctions.GetExecutionHistory") + .contentType(SFN_CONTENT_TYPE) + .body(""" + {"executionArn": "%s"} + """.formatted(execArn)) + .when() + .post("/"); + resp.then().statusCode(200); + return resp; + } + + private static Response waitForTerminalExecution(String execArn, long limitMillis) throws InterruptedException { + long deadline = System.currentTimeMillis() + limitMillis; + while (System.currentTimeMillis() < deadline) { + Response resp = describeExecution(execArn); + if (!"RUNNING".equals(resp.jsonPath().getString("status"))) { + return resp; + } + Thread.sleep(100); + } + fail("Execution " + execArn + " was still RUNNING after " + limitMillis + " ms"); + return null; + } + + private static String quote(String raw) { + return "\"" + raw + .replace("\\", "\\\\") + .replace("\"", "\\\"") + .replace("\n", "\\n") + .replace("\r", "\\r") + .replace("\t", "\\t") + + "\""; + } +}