From 70921dea2c8e1399eeb5d6b7bae4b6a703d8a97b Mon Sep 17 00:00:00 2001 From: jwoa95 <88512616+jwoa95@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:08:14 +0000 Subject: [PATCH] fix(sfn): preserve undefined indexed constructed-array paths (#6613) (#8621) --- docs/services/step-functions.md | 11 ++++ .../JsonataConstructedArrayPaths.java | 60 ++++++++++++++++++ .../stepfunctions/JsonataEvaluator.java | 1 + .../stepfunctions/JsonataSymbolReader.java | 50 +++++++++++++++ .../JsonataTopLevelReferences.java | 43 +------------ .../JsonataConstructedArrayFixtures.java | 24 ++++++++ .../JsonataConstructedArrayPathTest.java | 61 +++++++++++++++++++ .../StepFunctionsJsonataIntegrationTest.java | 28 +++++++++ 8 files changed, 238 insertions(+), 40 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/stepfunctions/JsonataConstructedArrayPaths.java create mode 100644 src/main/java/io/floci/aws/services/stepfunctions/JsonataSymbolReader.java create mode 100644 src/test/java/io/floci/aws/services/stepfunctions/JsonataConstructedArrayFixtures.java create mode 100644 src/test/java/io/floci/aws/services/stepfunctions/JsonataConstructedArrayPathTest.java diff --git a/docs/services/step-functions.md b/docs/services/step-functions.md index 5229095ff5..99cad9650c 100644 --- a/docs/services/step-functions.md +++ b/docs/services/step-functions.md @@ -417,6 +417,17 @@ that matches, so an undefined condition in a later rule is never evaluated. The cause of a real execution carries the state prefix described under [The cause of a failure](#the-cause-of-a-failure). +## JSONata constructed-array paths + +An indexed constructed array followed by a property path follows JSONata 2.0.6's +sequence reduction rules. For example, +`$exists([$states.input.Items.{'ok':true}][0].ok)` returns `false`, including when +`Items` has one element. The unwrapped path returns no value, so using it directly +as a state's `Output` fails with `States.QueryEvaluationError`. +Group the array before indexing, `([$states.input.Items.{'ok':true}])[0].ok`, +to read the first object's property. A standalone `[...][0]` still returns the +first object. + ## JSONata functions State machines with `"QueryLanguage": "JSONata"` reach the six functions Step Functions adds on diff --git a/src/main/java/io/floci/aws/services/stepfunctions/JsonataConstructedArrayPaths.java b/src/main/java/io/floci/aws/services/stepfunctions/JsonataConstructedArrayPaths.java new file mode 100644 index 0000000000..bdc13c9e5d --- /dev/null +++ b/src/main/java/io/floci/aws/services/stepfunctions/JsonataConstructedArrayPaths.java @@ -0,0 +1,60 @@ +package io.floci.aws.services.stepfunctions; + +import com.dashjoin.jsonata.Jsonata; +import com.dashjoin.jsonata.Parser; +import com.dashjoin.jsonata.Utils; + +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static io.floci.aws.services.stepfunctions.JsonataSymbolReader.read; + +/** Keeps indexed constructed-array paths consistent with JSONata 2.0.6's missing-value semantics. */ +final class JsonataConstructedArrayPaths { + + private JsonataConstructedArrayPaths() { + } + + static void install(Jsonata.Frame frame) { + Set firstSteps = Collections.newSetFromMap(new IdentityHashMap<>()); + Jsonata.EntryCallback entry = (Jsonata.EntryCallback) frame.lookup("__evaluate_entry"); + Jsonata.ExitCallback exit = (Jsonata.ExitCallback) frame.lookup("__evaluate_exit"); + frame.setEvaluateEntryCallback((expression, input, environment) -> { + entry.callback(expression, input, environment); + Parser.Symbol first = firstConstructedStep(expression); + if (first != null) { + firstSteps.add(first); + } + }); + frame.setEvaluateExitCallback((expression, input, environment, result) -> { + exit.callback(expression, input, environment, result); + if (firstSteps.contains(expression) && result instanceof Utils.JList sequence + && sequence.sequence && !sequence.keepSingleton && sequence.size() == 1 + && hasNoLength(sequence.getFirst())) { + // The reference path iterates the reduced object's absent length and returns + // nothing. Dashjoin instead casts that object to List. Empty only this first + // step's sequence before reduction, preserving grouped and forced-array paths. + sequence.clear(); + } + }); + } + + private static boolean hasNoLength(Object value) { + if (value instanceof Map object) { + return !object.containsKey("length"); + } + return value instanceof Number || value instanceof Boolean; + } + + private static Parser.Symbol firstConstructedStep(Parser.Symbol expression) { + if ("path".equals(read(expression, "type")) && read(expression, "steps") instanceof List steps + && steps.size() > 1 && steps.getFirst() instanceof Parser.Symbol first + && first.consarray && !(boolean) read(first, "keepArray")) { + return first; + } + return null; + } +} diff --git a/src/main/java/io/floci/aws/services/stepfunctions/JsonataEvaluator.java b/src/main/java/io/floci/aws/services/stepfunctions/JsonataEvaluator.java index d9f4c336d2..3a7e80921d 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/JsonataEvaluator.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/JsonataEvaluator.java @@ -218,6 +218,7 @@ public class JsonataEvaluator { frame.setRuntimeBounds(evaluationTimeoutMillis, maxEvaluationDepth); nesting.trackOn(frame); boundHeldMemory(frame); + JsonataConstructedArrayPaths.install(frame); stepFunctionsExtensions.forEach(frame::bind); // AWS disables $eval, and the library ships it. An unbound name called as a function is // the library's own T1006, which is the code AWS answers. $parse is the replacement. diff --git a/src/main/java/io/floci/aws/services/stepfunctions/JsonataSymbolReader.java b/src/main/java/io/floci/aws/services/stepfunctions/JsonataSymbolReader.java new file mode 100644 index 0000000000..97997daea2 --- /dev/null +++ b/src/main/java/io/floci/aws/services/stepfunctions/JsonataSymbolReader.java @@ -0,0 +1,50 @@ +package io.floci.aws.services.stepfunctions; + +import com.dashjoin.jsonata.Parser; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.lang.reflect.Field; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; + +/** + * Reads the nonpublic JSONata parse-tree fields shared by validation and evaluation. + * Quarkus loads application classes and dependency jars with different class loaders, so sharing + * the parser's package would raise IllegalAccessError. Resolve fields once so a dependency upgrade + * that changes the tree fails loudly, and register their native-image reflection in one place. + */ +@RegisterForReflection(targets = Parser.Symbol.class, fields = true) +final class JsonataSymbolReader { + + private static final Map TREE_FIELDS = resolveTreeFields( + "type", "value", "steps", "lhs", "rhs", "expression", "expressions", + "procedure", "arguments", "body", "condition", "then", "_else", "keepArray"); + + private JsonataSymbolReader() { + } + + static Object read(Parser.Symbol node, String field) { + try { + return Objects.requireNonNull(TREE_FIELDS.get(field), field).get(node); + } catch (IllegalAccessException e) { + throw new IllegalStateException( + "com.dashjoin:jsonata no longer allows reading Parser.Symbol." + field, e); + } + } + + private static Map resolveTreeFields(String... names) { + Map fields = new LinkedHashMap<>(); + for (String name : names) { + try { + Field field = Parser.Symbol.class.getDeclaredField(name); + field.setAccessible(true); + fields.put(name, field); + } catch (NoSuchFieldException e) { + throw new IllegalStateException("com.dashjoin:jsonata no longer declares " + + "Parser.Symbol." + name + ", so its parse-tree readers must be updated", e); + } + } + return Map.copyOf(fields); + } +} diff --git a/src/main/java/io/floci/aws/services/stepfunctions/JsonataTopLevelReferences.java b/src/main/java/io/floci/aws/services/stepfunctions/JsonataTopLevelReferences.java index 428f141dad..d28ace06cd 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/JsonataTopLevelReferences.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/JsonataTopLevelReferences.java @@ -1,17 +1,14 @@ package io.floci.aws.services.stepfunctions; import com.dashjoin.jsonata.Parser; -import io.quarkus.runtime.annotations.RegisterForReflection; -import java.lang.reflect.Field; import java.util.ArrayList; -import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; -import java.util.Map; -import java.util.Objects; import java.util.Set; +import static io.floci.aws.services.stepfunctions.JsonataSymbolReader.read; + /** * Parses a Step Functions JSONata expression once and reports either the message the parser refused * it with, or every reference it makes against the top-level context. @@ -29,14 +26,8 @@ import java.util.Set; * {@code $map($states.input.a, function($x){ b })} does name {@code b} at the top level. Both * halves are measured against AWS in {@code JsonataTopLevelReferencesTest}. * - *

{@link Parser#parse(String)} is public and returns a public {@link Parser.Symbol}, but every - * field carrying the tree is package-private, and Quarkus loads application classes and dependency - * jars with different class loaders, so sharing the package raises {@code IllegalAccessError} - * instead. The fields are therefore read reflectively, and the cost is paid up front: all of them - * are resolved once in the static initializer, so a {@code com.dashjoin:jsonata} upgrade that - * renames or removes one fails loudly on the first call instead of quietly naming no reference. + *

Nonpublic parse-tree fields are read through {@link JsonataSymbolReader}. */ -@RegisterForReflection(targets = Parser.Symbol.class, fields = true) final class JsonataTopLevelReferences { /** The name AWS prints for {@code $}, the context item itself. */ @@ -53,10 +44,6 @@ final class JsonataTopLevelReferences { */ static final String STATES_ERROR_OUTPUT = "$states.errorOutput"; - private static final Map TREE_FIELDS = resolveTreeFields( - "type", "value", "steps", "lhs", "rhs", "expression", "expressions", - "procedure", "arguments", "body", "condition", "then", "_else"); - private JsonataTopLevelReferences() { } @@ -207,28 +194,4 @@ final class JsonataTopLevelReferences { return nodes == null || nodes.isEmpty() ? null : nodes.get(0); } - private static Object read(Parser.Symbol node, String field) { - try { - return Objects.requireNonNull(TREE_FIELDS.get(field), field).get(node); - } catch (IllegalAccessException e) { - throw new IllegalStateException( - "com.dashjoin:jsonata no longer allows reading Parser.Symbol." + field, e); - } - } - - private static Map resolveTreeFields(String... names) { - Map fields = new LinkedHashMap<>(); - for (String name : names) { - try { - Field field = Parser.Symbol.class.getDeclaredField(name); - field.setAccessible(true); - fields.put(name, field); - } catch (NoSuchFieldException e) { - throw new IllegalStateException("com.dashjoin:jsonata no longer declares " - + "Parser.Symbol." + name + ", so the top-level reference check has to be " - + "rewritten against the new parse tree", e); - } - } - return Map.copyOf(fields); - } } diff --git a/src/test/java/io/floci/aws/services/stepfunctions/JsonataConstructedArrayFixtures.java b/src/test/java/io/floci/aws/services/stepfunctions/JsonataConstructedArrayFixtures.java new file mode 100644 index 0000000000..fb7edb416c --- /dev/null +++ b/src/test/java/io/floci/aws/services/stepfunctions/JsonataConstructedArrayFixtures.java @@ -0,0 +1,24 @@ +package io.floci.aws.services.stepfunctions; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + +final class JsonataConstructedArrayFixtures { + + private JsonataConstructedArrayFixtures() { + } + + static ObjectNode input(ObjectMapper mapper, int count) { + ObjectNode input = mapper.createObjectNode(); + ArrayNode items = input.putArray("Items"); + for (int i = 0; i < count; i++) { + items.addObject(); + } + return input; + } + + static ObjectNode states(ObjectMapper mapper, int count) { + return mapper.createObjectNode().set("input", input(mapper, count)); + } +} diff --git a/src/test/java/io/floci/aws/services/stepfunctions/JsonataConstructedArrayPathTest.java b/src/test/java/io/floci/aws/services/stepfunctions/JsonataConstructedArrayPathTest.java new file mode 100644 index 0000000000..f1edf0adac --- /dev/null +++ b/src/test/java/io/floci/aws/services/stepfunctions/JsonataConstructedArrayPathTest.java @@ -0,0 +1,61 @@ +package io.floci.aws.services.stepfunctions; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class JsonataConstructedArrayPathTest { + + private final ObjectMapper mapper = new ObjectMapper(); + private final JsonataEvaluator evaluator = new JsonataEvaluator(mapper); + + @ParameterizedTest + @ValueSource(ints = {0, 1, 3}) + void indexedConstructedObjectPathHasNoValueAndExistsIsFalse(int count) throws Exception { + JsonNode states = JsonataConstructedArrayFixtures.states(mapper, count); + assertTrue(evaluator.evaluate("{% [$states.input.Items.{'ok':true}][0].ok %}", states).isMissingNode()); + assertFalse(evaluator.evaluate("{% $exists([$states.input.Items.{'ok':true}][0].ok) %}", states).asBoolean()); + assertEquals(mapper.readTree("{}"), + evaluator.evaluate("{% {'value':[$states.input.Items.{'ok':true}][0].ok} %}", states)); + } + + @ParameterizedTest + @ValueSource(ints = {0, 1, 3}) + void groupingTheConstructedArrayAllowsThePropertyRead(int count) throws Exception { + JsonNode states = JsonataConstructedArrayFixtures.states(mapper, count); + JsonNode grouped = evaluator.evaluate("{% ([$states.input.Items.{'ok':true}])[0].ok %}", states); + if (count == 0) { + assertTrue(grouped.isMissingNode()); + } else { + assertTrue(grouped.asBoolean()); + assertEquals(mapper.readTree("{\"ok\":true}"), + evaluator.evaluate("{% [$states.input.Items.{'ok':true}][0] %}", states)); + } + assertEquals(count, evaluator.evaluate("{% [$states.input.Items.{'ok':true}] %}", states).size()); + } + + @Test + void forcedArraysAndMultipleResultsKeepTheirPathSemantics() throws Exception { + JsonNode states = mapper.readTree("{\"input\":{\"Items\":[{\"a\":1},{\"a\":2}]}}"); + assertEquals("[1]", evaluator.evaluate("{% [$states.input.Items][0][].a %}", states).toString()); + assertEquals("[1,2]", evaluator.evaluate("{% [$states.input.Items][[0,1]].a %}", states).toString()); + assertEquals(mapper.readTree("[\"1\",\"2\"]"), + evaluator.evaluate("{% [[1,2],[3]][0].$string() %}", states)); + assertEquals("[[{\"a\":1},{\"a\":2}]]", + evaluator.evaluate("{% [[$states.input.Items]] %}", states).toString()); + } + + @Test + void numericAndBooleanSingletonPathsAlsoHaveNoValue() throws Exception { + JsonNode states = JsonataConstructedArrayFixtures.states(mapper, 1); + assertTrue(evaluator.evaluate("{% [5][0].$string() %}", states).isMissingNode()); + assertFalse(evaluator.evaluate("{% $exists([true][0].x) %}", states).asBoolean()); + } + +} diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsJsonataIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsJsonataIntegrationTest.java index 58bff95cf3..6c9199f606 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsJsonataIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsJsonataIntegrationTest.java @@ -32,11 +32,39 @@ class StepFunctionsJsonataIntegrationTest { private final ObjectMapper objectMapper = new ObjectMapper(); + @ParameterizedTest + @ValueSource(ints = {0, 1, 3}) + void existsOfAnIndexedConstructedObjectPathReturnsFalse(int count) throws Exception { + String execution = startConstructedArrayExecution("exists", count, + "{% $exists([$states.input.Items.{'ok':true}][0].ok) %}"); + assertFalse(objectMapper.readTree(waitForExecution(execution)).asBoolean()); + } + @BeforeAll static void configureRestAssured() { RestAssuredJsonUtils.configureAwsContentTypes(); } + @ParameterizedTest + @ValueSource(ints = {0, 1, 3}) + void directIndexedConstructedObjectPathStillFailsAsUndefined(int count) throws Exception { + String execution = startConstructedArrayExecution("undefined", count, + "{% [$states.input.Items.{'ok':true}][0].ok %}"); + Response failure = waitForExecutionFailure(execution); + assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error")); + assertTrue(failure.jsonPath().getString("cause").contains("returned nothing (undefined)")); + assertFalse(failure.jsonPath().getString("cause").contains("cannot be cast")); + } + + private String startConstructedArrayExecution(String name, int count, String expression) { + ObjectNode definition = objectMapper.createObjectNode(); + definition.put("QueryLanguage", "JSONata").put("StartAt", "Probe"); + definition.putObject("States").putObject("Probe") + .put("Type", "Pass").put("Output", expression).put("End", true); + String machine = createStateMachine("jsonata-constructed-" + name + "-" + count, definition.toString()); + return startExecution(machine, JsonataConstructedArrayFixtures.input(objectMapper, count).toString()); + } + @Test void passStateWithJsonataOutput() throws Exception { // A Pass state that transforms input using JSONata Output field