mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(sfn): support Retry policies in Task, Parallel, and Map states (#2455)
* feat(sfn): honor Retry policies in the ASL executor Task, Parallel, and Map states previously ignored their Retry field, so any failure went straight to Catch or failed the execution. They now retry per the ASL spec. ErrorEquals matching reuses the Catch matcher, including the States.ALL and States.TaskFailed wildcards, and States.Runtime is never retried. AWS defaults apply when fields are omitted (MaxAttempts 3, IntervalSeconds 1, BackoffRate 2.0). MaxDelaySeconds is honored. Each retrier keeps its own attempt counter and an exhausted retrier falls through to Catch. The context object field $$.State.RetryCount increments per attempt. Attempt counts, defaults, backoff timing, retry before catch order, and per attempt RetryCount resolution were verified against real AWS Step Functions in us-east-1 using execution histories. Two deviations are documented. The delay between attempts is capped at 30 seconds, matching the cap Floci applies to Wait states. JitterStrategy is accepted but ignored. Refs #2283 * test(sfn): add end-to-end Retry integration tests Covers the JSON 1.0 wire protocol path. The fail-then-succeed case works without mocks by resolving the DynamoDB table name from $$.State.RetryCount, so attempt 0 targets a missing table and the retry targets one that exists. This also exercises per attempt Parameters re-resolution, which real AWS does the same way. The other cases cover retrier exhaustion falling through to Catch and an unmatched error failing without retry. * fix(sfn): unwrap branch failures so Parallel Retry and Catch apply * fix(sfn): isolate the context object per Parallel branch and per branch state * fix(sfn): fail a missing Lambda function as Lambda.ResourceNotFoundException * test(sfn): cover Retry and Catch for Parallel and Map states * feat(sfn): support JitterStrategy FULL in Retry backoff * fix(sfn): keep branch Error causes wrapped so executions still terminate
This commit is contained in:
1 parent
127e51e71b
commit
56e74d64c6
4 files changed
+783
-6
No files matched your search
@@ -75,6 +75,7 @@ import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.BiConsumer;
|
||||
@@ -311,9 +312,9 @@ public class AslExecutor {
|
||||
// Update per-state context fields
|
||||
updateStateContext(execContext, currentStateName);
|
||||
|
||||
boolean jsonata = isJsonata(stateDef, topLevelQueryLanguage);
|
||||
var jsonata = isJsonata(stateDef, topLevelQueryLanguage);
|
||||
try {
|
||||
StateResult stateResult = executeState(currentStateName, type, stateDef, currentInput,
|
||||
var stateResult = executeStateWithRetry(currentStateName, type, stateDef, currentInput,
|
||||
history, eventId, sm, jsonata, topLevelQueryLanguage, execContext, variables);
|
||||
addEvent(history, eventId, stateExitedEventType(type), eventId.get() - 1,
|
||||
Map.of("name", currentStateName, "output", stateResult.output().toString()));
|
||||
@@ -373,6 +374,84 @@ public class AslExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a state, honoring its {@code Retry} policy: a {@code FailStateException} matched by
|
||||
* a retrier re-runs the state after the retrier's backoff until its {@code MaxAttempts} are
|
||||
* used up. Errors that no retrier matches (or that exhaust their retrier) propagate to the
|
||||
* caller's Catch handling, preserving Retry-before-Catch order.
|
||||
*/
|
||||
private StateResult executeStateWithRetry(String name, String type, JsonNode stateDef, JsonNode input,
|
||||
List<HistoryEvent> history, AtomicLong eventId, StateMachine sm,
|
||||
boolean jsonata, String topLevelQueryLanguage, JsonNode context,
|
||||
ObjectNode variables) throws Exception {
|
||||
var retriers = stateDef.path("Retry");
|
||||
var attemptsPerRetrier = new HashMap<Integer, Integer>();
|
||||
var attempt = 0;
|
||||
while (true) {
|
||||
try {
|
||||
return executeState(name, type, stateDef, input, history, eventId, sm, jsonata,
|
||||
topLevelQueryLanguage, context, variables);
|
||||
} catch (FailStateException e) {
|
||||
var retrierIndex = findMatchingRetrier(retriers, e);
|
||||
if (retrierIndex < 0) {
|
||||
throw e;
|
||||
}
|
||||
var retrier = retriers.get(retrierIndex);
|
||||
var attemptsUsed = attemptsPerRetrier.merge(retrierIndex, 1, Integer::sum);
|
||||
if (attemptsUsed > retrier.path("MaxAttempts").asInt(3)) {
|
||||
throw e;
|
||||
}
|
||||
sleepBeforeRetry(retrier, attemptsUsed);
|
||||
attempt++;
|
||||
updateRetryCount(context, attempt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int findMatchingRetrier(JsonNode retriers, FailStateException failure) {
|
||||
if (!retriers.isArray()) {
|
||||
return -1;
|
||||
}
|
||||
var error = failure.error != null ? failure.error : "States.Runtime";
|
||||
for (var i = 0; i < retriers.size(); i++) {
|
||||
if (catchMatches(retriers.get(i), error)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private void sleepBeforeRetry(JsonNode retrier, int attemptsUsed) throws InterruptedException {
|
||||
var delaySeconds = retryDelaySeconds(retrier, attemptsUsed, ThreadLocalRandom.current().nextDouble());
|
||||
if (delaySeconds > 0) {
|
||||
Thread.sleep((long) (delaySeconds * 1000));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the delay before a retry attempt. {@code random} is a value in [0, 1) used when
|
||||
* the retrier declares {@code JitterStrategy: FULL}, which draws the delay uniformly between
|
||||
* zero and the computed delay. Jitter applies after the caps, matching AWS.
|
||||
*/
|
||||
static double retryDelaySeconds(JsonNode retrier, int attemptsUsed, double random) {
|
||||
var interval = retrier.path("IntervalSeconds").asDouble(1.0);
|
||||
var backoffRate = retrier.path("BackoffRate").asDouble(2.0);
|
||||
var delaySeconds = interval * Math.pow(backoffRate, attemptsUsed - 1.0);
|
||||
var maxDelay = retrier.path("MaxDelaySeconds").asDouble(MAX_WAIT_SECONDS);
|
||||
// Like the Wait state, cap the delay at MAX_WAIT_SECONDS to keep emulated runs fast.
|
||||
delaySeconds = Math.min(delaySeconds, Math.min(maxDelay, MAX_WAIT_SECONDS));
|
||||
if ("FULL".equals(retrier.path("JitterStrategy").asText(null))) {
|
||||
delaySeconds *= random;
|
||||
}
|
||||
return delaySeconds;
|
||||
}
|
||||
|
||||
private void updateRetryCount(JsonNode context, int retryCount) {
|
||||
if (context.get("State") instanceof ObjectNode state) {
|
||||
state.put("RetryCount", retryCount);
|
||||
}
|
||||
}
|
||||
|
||||
private StateResult executeState(String name, String type, JsonNode stateDef, JsonNode input,
|
||||
List<HistoryEvent> history, AtomicLong eventId, StateMachine sm,
|
||||
boolean jsonata, String topLevelQueryLanguage, JsonNode context,
|
||||
@@ -540,7 +619,10 @@ public class AslExecutor {
|
||||
String region = extractRegionFromArn(sm.getStateMachineArn());
|
||||
LambdaFunction fn = functionStore.get(region, functionName).orElse(null);
|
||||
if (fn == null) {
|
||||
throw new RuntimeException("Lambda function not found: " + functionName);
|
||||
// A missing function is a task failure on AWS, so it must stay reachable for
|
||||
// Retry and Catch instead of surfacing as States.Runtime.
|
||||
throw new FailStateException("Lambda.ResourceNotFoundException",
|
||||
"Lambda function not found: " + functionName);
|
||||
}
|
||||
|
||||
String payloadStr = objectMapper.writeValueAsString(lambdaPayload);
|
||||
@@ -1443,13 +1525,16 @@ public class AslExecutor {
|
||||
// Each branch gets an isolated copy of the current variables: assignments inside a
|
||||
// branch are scoped to that branch and do not leak back to the parent after the state.
|
||||
ObjectNode branchVariables = variables.deepCopy();
|
||||
// Each branch also gets its own copy of the context object so State.RetryCount and
|
||||
// Task.Token writes cannot race across concurrent branches.
|
||||
var branchContext = ((ObjectNode) context).deepCopy();
|
||||
|
||||
// Run each branch on its own worker thread under the execution's account: the request
|
||||
// scope is thread-bound, so without this a branch's Task integrations would resolve to
|
||||
// the default account rather than the execution's.
|
||||
futures.add(executor.submit(() -> callUnderExecutionAccount(sm,
|
||||
() -> executeBranch(startAt, branchStates, capturedInput, sm, topLevelQueryLanguage, context,
|
||||
branchVariables))));
|
||||
() -> executeBranch(startAt, branchStates, capturedInput, sm, topLevelQueryLanguage,
|
||||
branchContext, branchVariables))));
|
||||
}
|
||||
|
||||
int timeoutSeconds = stateDef.path("TimeoutSeconds").asInt(0);
|
||||
@@ -1476,6 +1561,16 @@ public class AslExecutor {
|
||||
futures.forEach(future -> future.cancel(true));
|
||||
Thread.currentThread().interrupt();
|
||||
throw e;
|
||||
} catch (ExecutionException e) {
|
||||
futures.forEach(future -> future.cancel(true));
|
||||
// Unwrap so a branch's FailStateException reaches the Parallel state's own
|
||||
// Retry and Catch handling instead of surfacing as States.Runtime. An Error
|
||||
// cause stays wrapped so the execution-level Exception handlers still
|
||||
// publish a terminal FAILED update instead of leaving the execution RUNNING.
|
||||
if (e.getCause() instanceof Exception exception) {
|
||||
throw exception;
|
||||
}
|
||||
throw e;
|
||||
} catch (Exception | Error e) {
|
||||
futures.forEach(future -> future.cancel(true));
|
||||
throw e;
|
||||
@@ -1997,9 +2092,10 @@ public class AslExecutor {
|
||||
}
|
||||
String type = stateDef.path("Type").asText();
|
||||
boolean stateJsonata = isJsonata(stateDef, topLevelQueryLanguage);
|
||||
updateStateContext(context, currentState);
|
||||
StateResult result;
|
||||
try {
|
||||
result = executeState(currentState, type, stateDef, currentInput, ignored, eventId, sm,
|
||||
result = executeStateWithRetry(currentState, type, stateDef, currentInput, ignored, eventId, sm,
|
||||
stateJsonata, topLevelQueryLanguage, context, variables);
|
||||
} catch (FailStateException e) {
|
||||
StateResult caught = handleCatch(stateDef, currentInput, e, stateJsonata, context, variables);
|
||||
|
||||
Reference in new issue
Block a user