feat(stepfunctions): support workflow variables in JSONPath states (#7106)

This commit is contained in:
syedali032-creator authored and GitHub committed 2026-11-03 08:32:00 -04:00
1 parent d7797bf56d
commit 25780c051e
3 files changed
+425 -8

No files matched your search

@@ -134,6 +134,7 @@ import java.util.function.Consumer;
import java.util.function.IntFunction;
import java.util.function.LongSupplier;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
@ApplicationScoped
@@ -728,6 +729,27 @@ public class AslExecutor {
JsonNode stateDef, JsonNode input, StateMachine sm,
String topLevelQueryLanguage, JsonNode context, ObjectNode variables,
long executionDeadlineNanos) throws Exception {
// JSONPath states read and Assign workflow variables through JSONPATH_SCOPE (see there).
JsonPathScope previousScope = JSONPATH_SCOPE.get();
JsonPathScope scope = isJsonata(stateDef, topLevelQueryLanguage) ? null
: new JsonPathScope(variables, context, objectMapper.createObjectNode());
JSONPATH_SCOPE.set(scope);
try {
StateResult result = runEnteredStateBody(chain, name, enteredEventId, type, stateDef, input, sm,
topLevelQueryLanguage, context, variables, executionDeadlineNanos);
if (scope != null) {
variables.setAll(scope.pendingAssignments());
}
return result;
} finally {
restoreJsonPathScope(previousScope);
}
}
private StateResult runEnteredStateBody(HistoryChain chain, String name, long enteredEventId, String type,
JsonNode stateDef, JsonNode input, StateMachine sm,
String topLevelQueryLanguage, JsonNode context, ObjectNode variables,
long executionDeadlineNanos) throws Exception {
updateStateContext(context, name);
boolean jsonata = isJsonata(stateDef, topLevelQueryLanguage);
StateResult result;
@@ -810,6 +832,10 @@ public class AslExecutor {
return executeState(name, type, stateDef, input, chain, sm, jsonata,
topLevelQueryLanguage, context, variables, executionDeadlineNanos);
} catch (FailStateException raised) {
JsonPathScope scope = JSONPATH_SCOPE.get();
if (scope != null) {
scope.pendingAssignments().removeAll();
}
FailStateException e = raised.attributedTo(name, enteredEventId);
if (!raised.hasFinalCause()) {
publishEvaluationFailedEvent(chain, name, e);
@@ -920,6 +946,7 @@ public class AslExecutor {
result = stateDef.get("Result");
}
applyJsonPathAssign(stateDef, result);
JsonNode output = mergeResult(stateDef, input, result);
output = applyOutputPath(stateDef, output, context);
return new StateResult(output, stateDef.path("Next").asText(null));
@@ -1051,7 +1078,8 @@ public class AslExecutor {
JsonNode output = applyJsonataOutput(stateDef, input, taskResult, context, variables);
return new StateResult(output, stateDef.path("Next").asText(null));
} else {
// ResultSelector transforms the raw result before ResultPath merges it into the state input.
// Assign reads the raw task result; ResultSelector transforms it before ResultPath merges it.
applyJsonPathAssign(stateDef, taskResult);
if (stateDef.has("ResultSelector")) {
taskResult = resolveParameters(stateDef.get("ResultSelector"), taskResult, context);
}
@@ -2875,6 +2903,8 @@ public class AslExecutor {
JsonNode choices = stateDef.path("Choices");
for (JsonNode choice : choices) {
if (evaluateCondition(choice, effectiveInput, context)) {
// A matched rule carries its own Assign; the state-level one applies on the Default path.
applyJsonPathAssign(choice, effectiveInput);
JsonNode output = applyOutputPath(stateDef, effectiveInput, context);
return new StateResult(output, choice.path("Next").asText());
}
@@ -2882,6 +2912,7 @@ public class AslExecutor {
// Default branch
String defaultState = stateDef.path("Default").asText(null);
if (defaultState != null) {
applyJsonPathAssign(stateDef, effectiveInput);
JsonNode output = applyOutputPath(stateDef, effectiveInput, context);
return new StateResult(output, defaultState);
}
@@ -2902,7 +2933,7 @@ public class AslExecutor {
private StateResult executeWaitState(JsonNode stateDef, JsonNode input, boolean jsonata, JsonNode context,
ObjectNode variables, long executionDeadlineNanos)
throws InterruptedException {
throws Exception {
long waitNanos = 0;
JsonNode effectiveInput = input;
if (jsonata) {
@@ -2948,6 +2979,7 @@ public class AslExecutor {
JsonNode output = applyJsonataOutput(stateDef, input, null, context, variables);
return new StateResult(output, stateDef.path("Next").asText(null));
}
applyJsonPathAssign(stateDef, effectiveInput);
JsonNode output = applyOutputPath(stateDef, effectiveInput, context);
return new StateResult(output, stateDef.path("Next").asText(null));
}
@@ -3176,7 +3208,8 @@ public class AslExecutor {
return new StateResult(output, stateDef.path("Next").asText(null));
}
// ResultSelector transforms the raw branch results before ResultPath merges them in.
// Assign reads the raw branch results; ResultSelector transforms them before ResultPath merges them in.
applyJsonPathAssign(stateDef, results);
JsonNode selected = stateDef.has("ResultSelector")
? resolveParameters(stateDef.get("ResultSelector"), results, context)
: results;
@@ -3324,7 +3357,7 @@ public class AslExecutor {
iterInput = jsonata
? jsonataEvaluator.resolveTemplate(itemTransform, "ItemSelector",
buildStatesVar(mapInput, null, iterContext), variables)
: resolveParameters(itemTransform, mapInput, iterContext);
: resolveMapItemParameters(itemTransform, mapInput, iterContext, variables);
}
if (!distributed) {
iterationChain.publishIterationStart("MapIterationStarted", Map.of("name", name, "index", i));
@@ -3468,7 +3501,8 @@ public class AslExecutor {
return new StateResult(output, stateDef.path("Next").asText(null));
}
// ResultSelector transforms the raw iteration results before ResultPath merges them in.
// Assign reads the raw iteration results; ResultSelector transforms them before ResultPath merges them in.
applyJsonPathAssign(stateDef, mapResult);
JsonNode selected = stateDef.has("ResultSelector")
? resolveParameters(stateDef.get("ResultSelector"), mapResult, context)
: mapResult;
@@ -4457,6 +4491,79 @@ public class AslExecutor {
return resolvePath(path, input, context);
}
/**
* Workflow variables of the JSONPath state running on this thread. AWS lets JSONPath states read
* variables through {@code $name} / {@code $name.path} references and write them with
* {@code Assign}; the JSONPath resolvers have no {@code variables} parameter, so
* {@link #runEnteredState} exposes the state's scope here for the duration of the state
* (Map iterations and Parallel branches run their own states, so each sees its own scope).
* Not set for JSONata states, which use {@code variables} directly.
*/
private static final ThreadLocal<JsonPathScope> JSONPATH_SCOPE = new ThreadLocal<>();
private record JsonPathScope(ObjectNode variables, JsonNode context, ObjectNode pendingAssignments) {
}
private static void restoreJsonPathScope(JsonPathScope previousScope) {
if (previousScope == null) {
JSONPATH_SCOPE.remove();
} else {
JSONPATH_SCOPE.set(previousScope);
}
}
private JsonNode resolveMapItemParameters(JsonNode template, JsonNode input, JsonNode context,
ObjectNode variables) throws Exception {
JsonPathScope previousScope = JSONPATH_SCOPE.get();
JSONPATH_SCOPE.set(new JsonPathScope(variables, context, objectMapper.createObjectNode()));
try {
return resolveParameters(template, input, context);
} finally {
restoreJsonPathScope(previousScope);
}
}
/**
* Resolves a JSONPath workflow-variable reference ({@code $name}, {@code $name.field},
* {@code $name[0]}), or returns {@code null} when {@code path} is not one ({@code $}, {@code $.},
* {@code $[}, {@code $$}). An unknown variable fails the state with States.Runtime, as on AWS.
*/
private JsonNode resolveVariableReference(String path) {
if (path == null || path.startsWith("$$") || path.startsWith("$.") || path.startsWith("$[")) {
return null;
}
Matcher m = ChoiceOperators.variableReferenceMatcher(path);
if (!m.matches()) {
return null;
}
JsonPathScope scope = JSONPATH_SCOPE.get();
JsonNode value = scope == null ? null : scope.variables().get(m.group(1));
if (value == null) {
throw new FailStateException("States.Runtime",
"The JSONPath variable reference '" + path + "' refers to an undefined variable '" + m.group(1) + "'");
}
String rest = m.group(2);
return rest.isEmpty() ? value : resolvePathNode("$" + rest, value, null);
}
/**
* JSONPath {@code Assign}: evaluated against the state result (Pass: after Parameters/Result; Task,
* Map, Parallel: the raw result, before ResultSelector; Choice: the effective input; Catch: the error
* output; Wait: the effective input) with the variables as they were on state entry. Values stay
* pending until the state finishes successfully, so output processing cannot see its assignments.
*/
private void applyJsonPathAssign(JsonNode holder, JsonNode result) throws Exception {
JsonPathScope scope = JSONPATH_SCOPE.get();
if (scope == null || holder == null || !holder.has("Assign")) {
return;
}
JsonNode assigned = resolveParameters(holder.get("Assign"), result, scope.context());
if (assigned == null || !assigned.isObject()) {
throw new FailStateException("States.Runtime", "Assign must evaluate to an object");
}
scope.pendingAssignments().setAll((ObjectNode) assigned);
}
private JsonNode mergeResult(JsonNode stateDef, JsonNode input, JsonNode result) throws Exception {
if (!stateDef.has("ResultPath")) {
return result;
@@ -4564,6 +4671,10 @@ public class AslExecutor {
if (path.startsWith("States.")) {
return evaluateIntrinsic(path, root, context);
}
JsonNode variable = resolveVariableReference(path);
if (variable != null) {
return variable;
}
if ("$$".equals(path)) {
return context == null ? MissingNode.getInstance() : context;
}
@@ -4611,6 +4722,15 @@ public class AslExecutor {
if (path.startsWith("States.")) {
return evaluateIntrinsic(path, searchRoot, context);
}
String referencePath = path;
Matcher variable = ChoiceOperators.variableReferenceMatcher(path);
if (variable.matches()) {
searchRoot = resolveVariableReference("$" + variable.group(1));
path = "$" + variable.group(2);
if ("$".equals(path)) {
return searchRoot;
}
}
if (!path.startsWith("$.") && !path.startsWith("$[")) {
return NullNode.getInstance();
}
@@ -4619,7 +4739,7 @@ public class AslExecutor {
if (!value.isMissingNode()) {
return value;
}
throw unresolvedPayloadTemplateReference(path, fieldKey, reportedInput);
throw unresolvedPayloadTemplateReference(referencePath, fieldKey, reportedInput);
}
String[] parts = splitPathSegments(path);
if (containsWildcard(parts)) {
@@ -4633,7 +4753,7 @@ public class AslExecutor {
if (lookup.outOfRangeArrayIndex) {
return NullNode.getInstance();
}
throw unresolvedPayloadTemplateReference(path, fieldKey, reportedInput);
throw unresolvedPayloadTemplateReference(referencePath, fieldKey, reportedInput);
}
private static boolean isAdvancedJsonPath(String path) {
@@ -5824,7 +5944,8 @@ public class AslExecutor {
if (context != null && "$$".equals(arg)) {
return context;
}
if (arg.startsWith("$.") || arg.startsWith("$[") || "$".equals(arg)) {
if (ChoiceOperators.variableReferenceMatcher(arg).matches()
|| arg.startsWith("$.") || arg.startsWith("$[") || "$".equals(arg)) {
return resolveIntrinsicReference(arg, root, context, root);
}
if (arg.startsWith("States.")) {
@@ -6206,6 +6327,7 @@ public class AslExecutor {
catcher, "Catch[" + i + "]/", statesVar, errorOutput, variables);
return new StateResult(output, next);
}
applyJsonPathAssign(catcher, errorOutput);
return new StateResult(mergeResult(catcher, input, errorOutput), next);
}
return null;
@@ -10,6 +10,7 @@ import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
@@ -35,6 +36,9 @@ import java.util.regex.Pattern;
*/
public final class ChoiceOperators {
private static final Pattern VARIABLE_REFERENCE =
Pattern.compile("^\\$([_\\p{javaUnicodeIdentifierStart}][\\p{javaUnicodeIdentifierPart}]*)((?:[.\\[].*)?)$");
private ChoiceOperators() {
}
@@ -457,6 +461,10 @@ public final class ChoiceOperators {
}
}
static Matcher variableReferenceMatcher(String path) {
return VARIABLE_REFERENCE.matcher(path);
}
/**
* Pragmatic ASL reference-path syntax check: must start with {@code $} or {@code $$}; either root
* alone is valid; a longer path must be a sequence of non-empty {@code .segment} steps and balanced
@@ -467,6 +475,11 @@ public final class ChoiceOperators {
if (p == null || p.isEmpty() || p.charAt(0) != '$') {
return false;
}
// A JSONPath workflow variable ($name, $name.field, $name[0]) is a valid reference on AWS.
Matcher variable = variableReferenceMatcher(p);
if (variable.matches()) {
return variable.group(2).isEmpty() || isReferencePath("$" + variable.group(2));
}
if (p.startsWith("$$")) {
p = "$" + p.substring(2);
}