fix(stepfunctions): fail the state when a JSONata expression returns nothing (#2689)

* fix(stepfunctions): fail the state when a JSONata expression returns nothing

An expression that returned nothing lost its key and the execution carried on
down the happy path. Real AWS fails the state with States.QueryEvaluationError,
names the field the expression was written in and a Catch on that error fires.
Three of the positions changed control flow rather than data: a Choice took
Default, a Wait did not wait, and a Task sent its request with the argument
omitted.

evaluateField evaluates one expression and fails the state on a missing node.
resolveTemplate calls it at every leaf, carrying the field it is inside and
extending it with /key per object key and [i] per array index, so the cause
names Output/a/b[0][1] the way AWS does. Choices[n]/Condition, Seconds, Error,
Cause, MaxConcurrency and Items call it directly.

Three pieces go with it, all of them things a missing node used to need. An
undefined array element was a States.Runtime special case with its own wording;
AWS answers States.QueryEvaluationError and Output/values[0], the same shape as
every other position. resolveTemplateNode existed to let resolveTemplate turn a
whole field that returned nothing into a null, so the output would still
serialize; there is no output to serialize once the state fails. And the two
ResultWriter guards fired only on a key resolveTemplate had dropped, which can
no longer happen.

An explicit JSON null is a value and still succeeds, everywhere.

Closes #2665

* fix(stepfunctions): name a Choice rule's and a Catch clause's own fields under their index

A matched Choices[i] rule and a matching Catch[i] clause carry their own Assign and
Output, and applyJsonataAssignAndOutput named them 'Output' and 'Assign' as if they
were the state's. AWS names them under the rule or the clause: Choices[1]/Output/v,
Choices[0]/Assign/x and Catch[1]/Output/v, each measured on the account. The index is
the position in Choices or Catch, not the position among the entries that matched.

The Catch label was unobservable until now. doExecute calls handleCatch from inside
its own catch (FailStateException), so an expression failure raised while resolving
the clause's own Output escaped both that clause and its sibling catch (Exception),
reaching the method-level handler that answers States.Runtime with the raw message.
The execution now fails with the clause's own error, which is what AWS reports and
what the clause was catching no longer is.

* test(stepfunctions): follow the field path through the crashing evaluator stub

* test(stepfunctions): put the Catch clause under test on a Task, as AWS requires

aCatchClauseNamesItsOwnOutputUnderTheClauseIndex carried Catch on a Pass state,
which AWS refuses: validate-state-machine-definition answers SCHEMA_VALIDATION_FAILED,
"Field 'Catch' is not supported" at /States/Boom. The label the test pins is right,
Catch[1]/Output/v, and the state now fails on its own Arguments the way the measured
execution did, so the definition is one AWS accepts.

* docs(stepfunctions): drop the deviation this change removes

The key dropped by an expression that returned nothing is no longer Floci's
own behaviour: the state fails, as the section below records.

---------

Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
This commit is contained in:
Facundo ParedesandFacundo Paredes authored and GitHub committed 2026-08-28 23:34:46 -04:00
1 parent 5534460492
commit ea11e67719
8 files changed
+585 -131

No files matched your search

@@ -64,7 +64,7 @@ class AslExecutorErrorTerminationTest {
}
@Override
JsonNode resolveTemplate(JsonNode template, JsonNode statesVar, JsonNode variables) {
JsonNode resolveTemplate(JsonNode template, String field, JsonNode statesVar, JsonNode variables) {
throw new LinkageError(ERROR_MESSAGE);
}
}
@@ -288,7 +288,7 @@ class AslExecutorHttpInvokeTest {
}
@Test
void jsonataArgumentsSendAnExplicitNullAndOmitOnlyWhatReturnedNothing() throws Exception {
void jsonataArgumentsSendAnExplicitNull() throws Exception {
// AWS keeps the null in the arguments a Task is invoked with: TestState TRACE reports
// afterArguments {"FunctionName":"nope","Payload":{"v":null}} for Payload {"v":"{% null %}"}.
Execution execution = run("""
@@ -307,7 +307,6 @@ class AslExecutorHttpInvokeTest {
},
"RequestBody": {
"fromInput": "{%% $lookup($states.input, 'customerId') %%}",
"returnedNothing": "{%% $states.input.absent %%}",
"active": true
}
},
@@ -324,7 +323,6 @@ class AslExecutorHttpInvokeTest {
assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause());
JsonNode body = objectMapper.readTree(onlyRequest().body());
assertTrue(body.path("fromInput").isNull(), body.toString());
assertTrue(body.path("returnedNothing").isMissingNode(), body.toString());
assertTrue(body.path("active").asBoolean());
}
@@ -402,19 +402,27 @@ class AslExecutorResultWriterTest {
assertEquals("States.QueryEvaluationError", nestedBucketFailure.error);
assertTrue(nestedBucketFailure.getMessage().contains("Bucket must resolve to a string"));
JsonNode nestedPrefixStateDef = mapper.readTree("""
verify(s3Service, org.mockito.Mockito.never())
.putObject(anyString(), anyString(), any(byte[].class), anyString(), any());
}
@Test
void aDestinationExpressionReturningNothingFailsBeforeWriting() throws Exception {
JsonNode stateDef = mapper.readTree("""
{"Type":"Map",
"ResultWriter":{"Resource":"arn:aws:states:::s3:putObject",
"Arguments":{"Bucket":"b","Prefix":"{% $states.input.missing %}"}}}
""");
AslExecutor.FailStateException nestedPrefixFailure = assertThrows(
AslExecutor.FailStateException failure = assertThrows(
AslExecutor.FailStateException.class,
() -> executor.applyResultWriter("Process", nestedPrefixStateDef, mapper.createObjectNode(),
() -> executor.applyResultWriter("Process", stateDef, mapper.createObjectNode(),
arr("{\"ok\":true}"), mapper.createArrayNode(), List.of(),
sm, context, true));
assertEquals("States.QueryEvaluationError", nestedPrefixFailure.error);
assertTrue(nestedPrefixFailure.getMessage().contains("Prefix must resolve to a string"));
assertEquals("States.QueryEvaluationError", failure.error);
assertEquals("The JSONata expression '$states.input.missing' specified for the field "
+ "'ResultWriter/Arguments/Prefix' returned nothing (undefined).", failure.cause);
verify(s3Service, org.mockito.Mockito.never())
.putObject(anyString(), anyString(), any(byte[].class), anyString(), any());
}
@@ -6,6 +6,11 @@ import com.fasterxml.jackson.databind.node.NullNode;
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.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
@@ -97,7 +102,7 @@ class JsonataEvaluatorTest {
void resolveTemplate_nonExpressionStringPassesThrough() throws Exception {
JsonNode template = objectMapper.readTree("\"plain text\"");
JsonNode statesVar = objectMapper.createObjectNode();
JsonNode result = evaluator.resolveTemplate(template, statesVar);
JsonNode result = evaluator.resolveTemplate(template, "Output", statesVar);
assertEquals("plain text", result.asText());
}
@@ -105,7 +110,7 @@ class JsonataEvaluatorTest {
void resolveTemplate_evaluatesExpressionInString() throws Exception {
JsonNode template = objectMapper.readTree("\"{% 1 + 1 %}\"");
JsonNode statesVar = objectMapper.createObjectNode();
JsonNode result = evaluator.resolveTemplate(template, statesVar);
JsonNode result = evaluator.resolveTemplate(template, "Output", statesVar);
assertEquals(2, result.asInt());
}
@@ -121,7 +126,7 @@ class JsonataEvaluatorTest {
JsonNode statesVar = objectMapper.readTree("""
{"input": {"name": "Bob"}}
""");
JsonNode result = evaluator.resolveTemplate(template, statesVar);
JsonNode result = evaluator.resolveTemplate(template, "Output", statesVar);
assertTrue(result.isObject());
assertEquals("Hello Bob", result.get("greeting").asText());
assertEquals("unchanged", result.get("static").asText());
@@ -136,7 +141,7 @@ class JsonataEvaluatorTest {
JsonNode statesVar = objectMapper.readTree("""
{"input": {"a": 1, "b": 2}}
""");
JsonNode result = evaluator.resolveTemplate(template, statesVar);
JsonNode result = evaluator.resolveTemplate(template, "Output", statesVar);
assertTrue(result.isArray());
assertEquals(1, result.get(0).asInt());
assertEquals("static", result.get(1).asText());
@@ -150,7 +155,7 @@ class JsonataEvaluatorTest {
JsonNode statesVar = objectMapper.readTree("""
{"input": {"name": "Alice", "age": 30}}
""");
JsonNode result = evaluator.resolveTemplate(template, statesVar);
JsonNode result = evaluator.resolveTemplate(template, "Output", statesVar);
assertTrue(result.isTextual());
assertEquals("Hello {% $states.input.name %}, you are {% $states.input.age %} years old", result.asText());
}
@@ -161,7 +166,7 @@ class JsonataEvaluatorTest {
JsonNode statesVar = objectMapper.readTree("""
{"input": {"name": "Alice", "age": 30}}
""");
JsonNode result = evaluator.resolveTemplate(template, statesVar);
JsonNode result = evaluator.resolveTemplate(template, "Output", statesVar);
assertTrue(result.isObject());
assertEquals("Alice", result.get("name").asText());
}
@@ -170,9 +175,9 @@ class JsonataEvaluatorTest {
void resolveTemplate_primitivesPassThrough() throws Exception {
JsonNode statesVar = objectMapper.createObjectNode();
assertEquals(42, evaluator.resolveTemplate(objectMapper.readTree("42"), statesVar).asInt());
assertTrue(evaluator.resolveTemplate(objectMapper.readTree("true"), statesVar).asBoolean());
assertTrue(evaluator.resolveTemplate(NullNode.getInstance(), statesVar).isNull());
assertEquals(42, evaluator.resolveTemplate(objectMapper.readTree("42"), "Output", statesVar).asInt());
assertTrue(evaluator.resolveTemplate(objectMapper.readTree("true"), "Output", statesVar).asBoolean());
assertTrue(evaluator.resolveTemplate(NullNode.getInstance(), "Output", statesVar).isNull());
}
@Test
@@ -804,18 +809,17 @@ class JsonataEvaluatorTest {
}
@Test
void anExplicitNullKeepsItsKeyAndOnlyWhatReturnedNothingIsDropped() throws Exception {
void anExplicitNullKeepsItsKey() throws Exception {
JsonNode statesVar = objectMapper.readTree("""
{"input": {"bar": null}}
""");
JsonNode template = objectMapper.readTree("""
{"fromInput": "{% $lookup($states.input, 'bar') %}",
"returnedNothing": "{% $states.input.absent %}",
"kept": 1}
""");
assertEquals("{\"fromInput\":null,\"kept\":1}",
evaluator.resolveTemplate(template, statesVar).toString());
evaluator.resolveTemplate(template, "Output", statesVar).toString());
}
@Test
@@ -826,34 +830,23 @@ class JsonataEvaluatorTest {
""");
assertEquals("{\"outer\":{\"fromExpression\":null,\"kept\":1}}",
evaluator.resolveTemplate(template, statesVar).toString());
evaluator.resolveTemplate(template, "Output", statesVar).toString());
}
@Test
void aWholeTemplateIsANullWhetherItEvaluatedToNullOrReturnedNothing() throws Exception {
void aWholeTemplateEvaluatingToNullIsANull() throws Exception {
JsonNode statesVar = objectMapper.createObjectNode();
assertTrue(evaluator.resolveTemplate(objectMapper.readTree("\"{% null %}\""), statesVar).isNull());
// AWS fails the second one with States.QueryEvaluationError, which #2665 covers. Until then
// it is a null and not a missing node: an Output or Arguments is serialized as it stands,
// and a missing node writes itself as the empty string rather than as JSON.
assertTrue(evaluator.resolveTemplate(objectMapper.readTree("\"{% $states.input.absent %}\""), statesVar)
.isNull());
assertTrue(evaluator.resolveTemplate(objectMapper.readTree("\"{% null %}\""), "Output", statesVar).isNull());
}
@Test
void anExplicitNullIsAnArrayElementWhileNothingStillFailsTheState() throws Exception {
void anExplicitNullIsAnArrayElement() throws Exception {
JsonNode statesVar = objectMapper.createObjectNode();
assertEquals("{\"values\":[null,1]}", evaluator.resolveTemplate(objectMapper.readTree("""
{"values": ["{% null %}", 1]}
"""), statesVar).toString());
AslExecutor.FailStateException failure = assertThrows(AslExecutor.FailStateException.class,
() -> evaluator.resolveTemplate(objectMapper.readTree("""
{"values": ["{% $states.input.absent %}"]}
"""), statesVar));
assertTrue(failure.cause.contains("returned nothing (undefined)"), failure.cause);
"""), "Output", statesVar).toString());
}
@Test
@@ -862,7 +855,7 @@ class JsonataEvaluatorTest {
assertEquals("{\"literal\":null,\"kept\":1}", evaluator.resolveTemplate(objectMapper.readTree("""
{"literal": null, "kept": 1}
"""), statesVar).toString());
"""), "Output", statesVar).toString());
}
@Test
@@ -885,4 +878,54 @@ class JsonataEvaluatorTest {
assertTrue(evaluator.evaluate("{% $nullVariable %}", statesVar, variables).isNull());
assertTrue(evaluator.evaluate("{% $exists($nullVariable) %}", statesVar, variables).asBoolean());
}
/**
* The field path AWS names in the cause: the ASL field the template came from, a {@code /}
* before every object key below it and {@code [i]} appended for every array index. Measured on
* TestState, one Pass or one Assign per row.
*/
static Stream<Arguments> templatesWhoseExpressionReturnsNothing() {
return Stream.of(
Arguments.of("{\"v\": \"{% $states.input.missing %}\"}", "Output", "Output/v"),
Arguments.of("{\"a\": {\"b\": \"{% $states.input.missing %}\"}}", "Output", "Output/a/b"),
Arguments.of("\"{% $states.input.missing %}\"", "Output", "Output"),
Arguments.of("{\"values\": [\"{% $states.input.missing %}\", 1]}", "Output", "Output/values[0]"),
Arguments.of("{\"a\": {\"b\": [[1, \"{% $states.input.missing %}\"]]}}", "Output", "Output/a/b[0][1]"),
Arguments.of("{\"x\": {\"y\": \"{% $states.input.missing %}\"}}", "Assign", "Assign/x/y"));
}
@ParameterizedTest
@MethodSource("templatesWhoseExpressionReturnsNothing")
void anExpressionReturningNothingFailsTheStateNamingTheFieldPath(String template, String field,
String expectedFieldPath) throws Exception {
JsonNode statesVar = objectMapper.readTree("{\"input\": {}}");
AslExecutor.FailStateException failure = assertThrows(AslExecutor.FailStateException.class,
() -> evaluator.resolveTemplate(objectMapper.readTree(template), field, statesVar));
assertEquals("States.QueryEvaluationError", failure.error);
assertEquals("The JSONata expression '$states.input.missing' specified for the field '"
+ expectedFieldPath + "' returned nothing (undefined).", failure.cause);
}
@Test
void evaluateFieldNamesTheFieldOfAPositionThatHoldsASingleExpression() throws Exception {
JsonNode statesVar = objectMapper.readTree("{\"input\": {}}");
AslExecutor.FailStateException failure = assertThrows(AslExecutor.FailStateException.class,
() -> evaluator.evaluateField("{% $states.input.missing %}", "Seconds", statesVar, null));
assertEquals("States.QueryEvaluationError", failure.error);
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Seconds' "
+ "returned nothing (undefined).", failure.cause);
}
@Test
void anExplicitNullIsAValueAndKeepsEveryPositionEvaluating() throws Exception {
JsonNode statesVar = objectMapper.readTree("{\"input\": {\"bar\": null}}");
assertTrue(evaluator.evaluateField("{% null %}", "Seconds", statesVar, null).isNull());
assertEquals("{\"v\":null}", evaluator.resolveTemplate(
objectMapper.readTree("{\"v\": \"{% $states.input.bar %}\"}"), "Output", statesVar).toString());
}
}
@@ -1226,10 +1226,9 @@ class StepFunctionsJsonataIntegrationTest {
}
@Test
void outputKeepsAnExplicitNullInEveryPositionAndDropsOnlyWhatReturnedNothing() throws Exception {
void outputKeepsAnExplicitNullInEveryPosition() throws Exception {
// AWS returns {"v":null} for an expression that evaluates to JSON null, in an object field,
// nested, as an array element and as a literal. Only an expression that returned nothing
// loses its key.
// nested, as an array element and as a literal.
String definition = """
{
"QueryLanguage": "JSONata",
@@ -1242,8 +1241,7 @@ class StepFunctionsJsonataIntegrationTest {
"fromLiteralExpression": "{% null %}",
"literal": null,
"nested": {"inner": "{% null %}", "kept": 1},
"values": ["{% null %}", 1],
"returnedNothing": "{% $states.input.absent %}"
"values": ["{% null %}", 1]
},
"End": true
}
@@ -1260,7 +1258,381 @@ class StepFunctionsJsonataIntegrationTest {
assertTrue(output.path("literal").isNull(), output.toString());
assertTrue(output.path("nested").path("inner").isNull(), output.toString());
assertEquals("[null,1]", output.path("values").toString());
assertTrue(output.path("returnedNothing").isMissingNode(), output.toString());
}
@Test
void outputExpressionReturningNothingFailsTheStateAndIsCatchable() throws Exception {
// Real AWS on the same definition: States.QueryEvaluationError, "An error occurred while
// executing the state 'Transform' (entered at the event id #2). The JSONata expression
// '$states.input.missing' specified for the field 'Output/v' returned nothing (undefined)."
// Floci does not yet render the "An error occurred while executing the state" prefix (#2668).
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Transform",
"States": {
"Transform": {
"Type": "Pass",
"Output": {"v": "{% $states.input.missing %}"},
"End": true
}
}
}
""";
String smArn = createStateMachine("jsonata-output-returned-nothing-test", definition);
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Output/v' "
+ "returned nothing (undefined).", failure.jsonPath().getString("cause"));
String catching = definition.replace("\"End\": true",
"""
"Catch": [{"ErrorEquals": ["States.QueryEvaluationError"], "Next": "Caught"}],
"Next": "Unreached"
},
"Unreached": {"Type": "Fail", "Error": "UnexpectedSuccess"},
"Caught": {"Type": "Pass", "Output": {"caught": true}, "End": true""");
String catchingArn = createStateMachine("jsonata-output-returned-nothing-catch-test", catching);
JsonNode caught = objectMapper.readTree(waitForExecution(startExecution(catchingArn, "{}")));
assertTrue(caught.path("caught").asBoolean(), caught.toString());
}
@Test
void assignExpressionReturningNothingFailsTheState() throws Exception {
// Real AWS names 'Assign/x' for this definition; before this guard the variable was never
// bound and the next state read it as missing.
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Bind",
"States": {
"Bind": {
"Type": "Pass",
"Assign": {"x": "{% $states.input.missing %}"},
"Next": "Read"
},
"Read": {"Type": "Pass", "Output": {"got": "{% $x %}"}, "End": true}
}
}
""";
String smArn = createStateMachine("jsonata-assign-returned-nothing-test", definition);
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Assign/x' "
+ "returned nothing (undefined).", failure.jsonPath().getString("cause"));
}
@Test
void taskArgumentReturningNothingFailsTheStateBeforeTheRequestIsSent() throws Exception {
// Real AWS names 'Arguments/MessageGroupId' and fails before reaching SQS, which is why the
// queue url below never has to exist. Before this guard Floci sent the message without it.
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Send",
"States": {
"Send": {
"Type": "Task",
"Resource": "arn:aws:states:::sqs:sendMessage",
"Arguments": {
"QueueUrl": "http://localhost:4566/000000000000/absent-queue",
"MessageBody": "m",
"MessageGroupId": "{% $states.input.missing %}"
},
"End": true
}
}
}
""";
String smArn = createStateMachine("jsonata-arguments-returned-nothing-test", definition);
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field "
+ "'Arguments/MessageGroupId' returned nothing (undefined).",
failure.jsonPath().getString("cause"));
}
@Test
void choiceConditionReturningNothingFailsTheStateInsteadOfTakingDefault() throws Exception {
// Real AWS names the rule by its index, 'Choices[1]/Condition', and evaluates the rules in
// order, so the first rule being false is what makes the second one run.
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Pick",
"States": {
"Pick": {
"Type": "Choice",
"Choices": [
{"Condition": "{% false %}", "Next": "First"},
{"Condition": "{% $states.input.missing %}", "Next": "Second"}
],
"Default": "Fallback"
},
"First": {"Type": "Pass", "Output": {"went": "First"}, "End": true},
"Second": {"Type": "Pass", "Output": {"went": "Second"}, "End": true},
"Fallback": {"Type": "Pass", "Output": {"went": "Fallback"}, "End": true}
}
}
""";
String smArn = createStateMachine("jsonata-condition-returned-nothing-test", definition);
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field "
+ "'Choices[1]/Condition' returned nothing (undefined).", failure.jsonPath().getString("cause"));
}
@Test
void aChoiceRuleAfterTheMatchingOneIsNeverEvaluated() throws Exception {
// AWS succeeds on this definition: the first rule matches, so the undefined condition in the
// second one is never reached. The guard must not turn rule order into a failure.
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Pick",
"States": {
"Pick": {
"Type": "Choice",
"Choices": [
{"Condition": "{% true %}", "Next": "First"},
{"Condition": "{% $states.input.missing %}", "Next": "Second"}
],
"Default": "Fallback"
},
"First": {"Type": "Pass", "Output": {"went": "First"}, "End": true},
"Second": {"Type": "Pass", "Output": {"went": "Second"}, "End": true},
"Fallback": {"Type": "Pass", "Output": {"went": "Fallback"}, "End": true}
}
}
""";
String smArn = createStateMachine("jsonata-condition-short-circuit-test", definition);
JsonNode output = objectMapper.readTree(waitForExecution(startExecution(smArn, "{}")));
assertEquals("First", output.path("went").asText(), output.toString());
}
@Test
void aMatchedChoiceRuleNamesItsOwnOutputUnderTheRuleIndex() throws Exception {
// Real AWS names 'Choices[1]/Output/v': a rule's own Output is a field of the rule, not the
// state-level Output, and the index is the rule's position in Choices.
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Pick",
"States": {
"Pick": {
"Type": "Choice",
"Choices": [
{"Condition": "{% false %}", "Next": "First"},
{"Condition": "{% true %}",
"Output": {"v": "{% $states.input.missing %}"}, "Next": "First"}
],
"Default": "Fallback"
},
"First": {"Type": "Pass", "End": true},
"Fallback": {"Type": "Pass", "End": true}
}
}
""";
String smArn = createStateMachine("jsonata-choice-rule-output-nothing-test", definition);
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field "
+ "'Choices[1]/Output/v' returned nothing (undefined).", failure.jsonPath().getString("cause"));
}
@Test
void aMatchedChoiceRuleNamesItsOwnAssignUnderTheRuleIndex() throws Exception {
// Real AWS names 'Choices[0]/Assign/x' for a rule's own Assign.
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Pick",
"States": {
"Pick": {
"Type": "Choice",
"Choices": [
{"Condition": "{% true %}",
"Assign": {"x": "{% $states.input.missing %}"}, "Next": "First"}
],
"Default": "Fallback"
},
"First": {"Type": "Pass", "End": true},
"Fallback": {"Type": "Pass", "End": true}
}
}
""";
String smArn = createStateMachine("jsonata-choice-rule-assign-nothing-test", definition);
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field "
+ "'Choices[0]/Assign/x' returned nothing (undefined).", failure.jsonPath().getString("cause"));
}
@Test
void aCatchClauseNamesItsOwnOutputUnderTheClauseIndex() throws Exception {
// Real AWS names 'Catch[1]/Output/v': a clause's own Output is a field of the clause, and the
// index is its position in Catch, not its position among the clauses that matched. Measured
// with a real execution: TestState answers CAUGHT_ERROR and omits the output rather than
// failing. Catch belongs to a Task, which AWS rejects on a Pass, so the state below fails on
// its own Arguments and the clause catches that.
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Boom",
"States": {
"Boom": {
"Type": "Task",
"Resource": "arn:aws:states:::sqs:sendMessage",
"Arguments": {
"QueueUrl": "http://localhost:4566/000000000000/absent-queue",
"MessageBody": "m",
"MessageGroupId": "{% $states.input.missing %}"
},
"Catch": [
{"ErrorEquals": ["States.Timeout"], "Next": "Caught"},
{"ErrorEquals": ["States.QueryEvaluationError"],
"Output": {"v": "{% $states.input.missing %}"}, "Next": "Caught"}
],
"End": true
},
"Caught": {"Type": "Pass", "End": true}
}
}
""";
String smArn = createStateMachine("jsonata-catch-output-nothing-test", definition);
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field "
+ "'Catch[1]/Output/v' returned nothing (undefined).", failure.jsonPath().getString("cause"));
}
@Test
void waitSecondsReturningNothingFailsTheStateInsteadOfNotWaiting() throws Exception {
// Real AWS names 'Seconds'. Before this guard the expression resolved to zero and the state
// did not wait at all.
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Pause",
"States": {
"Pause": {"Type": "Wait", "Seconds": "{% $states.input.missing %}", "End": true}
}
}
""";
String smArn = createStateMachine("jsonata-wait-returned-nothing-test", definition);
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Seconds' "
+ "returned nothing (undefined).", failure.jsonPath().getString("cause"));
}
@Test
void failErrorAndCauseReturningNothingFailTheStateWithTheQueryEvaluationError() throws Exception {
// Real AWS names 'Error' and 'Cause'. The Fail state's own error is replaced by the
// evaluation failure, so a Catch on States.QueryEvaluationError fires instead of one on the
// error the definition meant to raise.
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Stop",
"States": {
"Stop": {"Type": "Fail", "Error": "%s", "Cause": "%s"}
}
}
""";
Response errorFailure = waitForExecutionFailure(startExecution(
createStateMachine("jsonata-fail-error-returned-nothing-test",
definition.formatted("{% $states.input.missing %}", "boom")), "{}"));
assertEquals("States.QueryEvaluationError", errorFailure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Error' "
+ "returned nothing (undefined).", errorFailure.jsonPath().getString("cause"));
Response causeFailure = waitForExecutionFailure(startExecution(
createStateMachine("jsonata-fail-cause-returned-nothing-test",
definition.formatted("Boom", "{% $states.input.missing %}")), "{}"));
assertEquals("States.QueryEvaluationError", causeFailure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Cause' "
+ "returned nothing (undefined).", causeFailure.jsonPath().getString("cause"));
}
@Test
void mapItemsReturningNothingFailsTheStateInsteadOfIteratingNothing() throws Exception {
// Real AWS names 'Items'.
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Fan",
"States": {
"Fan": {
"Type": "Map",
"Items": "{% $states.input.missing %}",
"ItemProcessor": {
"StartAt": "P",
"States": {"P": {"Type": "Pass", "End": true}}
},
"End": true
}
}
}
""";
String smArn = createStateMachine("jsonata-map-items-returned-nothing-test", definition);
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Items' "
+ "returned nothing (undefined).", failure.jsonPath().getString("cause"));
}
@Test
void mapMaxConcurrencyReturningNothingFailsTheStateNamingTheField() throws Exception {
// Real AWS names 'MaxConcurrency'. Before this guard the undefined value reached the
// non-negative-integer check and failed with Floci's own wording instead of AWS's.
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Fan",
"States": {
"Fan": {
"Type": "Map",
"Items": [1, 2],
"MaxConcurrency": "{% $states.input.missing %}",
"ItemProcessor": {
"StartAt": "P",
"States": {"P": {"Type": "Pass", "End": true}}
},
"End": true
}
}
}
""";
String smArn = createStateMachine("jsonata-map-maxconcurrency-returned-nothing-test", definition);
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field "
+ "'MaxConcurrency' returned nothing (undefined).", failure.jsonPath().getString("cause"));
}
@Test
@@ -1298,10 +1670,9 @@ class StepFunctionsJsonataIntegrationTest {
}
@Test
void aWholeOutputThatReturnedNothingStaysReadableJson() throws Exception {
// AWS fails this state with States.QueryEvaluationError, which #2665 covers. Until then the
// execution succeeds, and what DescribeExecution hands back has to parse: an output field
// holding the empty string is not JSON any client can read.
void aWholeOutputThatReturnedNothingFailsTheState() throws Exception {
// Real AWS names the whole field, 'Output', with no path below it. There is no output to
// serialize once the state fails, which is what the null this used to resolve to stood in for.
String definition = """
{
"QueryLanguage": "JSONata",
@@ -1309,7 +1680,7 @@ class StepFunctionsJsonataIntegrationTest {
"States": {
"Transform": {
"Type": "Pass",
"Output": "{% $states.input.absent %}",
"Output": "{% $states.input.missing %}",
"End": true
}
}
@@ -1317,10 +1688,11 @@ class StepFunctionsJsonataIntegrationTest {
""";
String smArn = createStateMachine("jsonata-whole-output-nothing-test", definition);
String execArn = startExecution(smArn, "{}");
String output = waitForExecution(execArn);
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
assertTrue(objectMapper.readTree(output).isNull(), output);
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Output' "
+ "returned nothing (undefined).", failure.jsonPath().getString("cause"));
}
@Test