Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(stepfunctions): evaluate the JSONata fields of an inline Map state (#2425)

mishukdutta-cz7f8a18756f00
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 85ed3a93..7b781381 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **Step Functions — JSONata fields on an inline `Map`** — `Items`, `ItemSelector`, `MaxConcurrency`, `Output` and `Assign` were ignored or read as JSONPath, so the Map iterated over the whole input, iterations got literal `{% ... %}` text, a `MaxConcurrency` expression failed with `States.Runtime`, and `Assign` variables were never set; all five are now evaluated, as on AWS. `Items` that is not an array fails with `States.QueryEvaluationError`.
- **Step Functions — JSONata `Catch` on `Map` and `Parallel` states** — a catcher's `Output` and `Assign` were ignored, so the caught error passed on unchanged and the catcher's variables were never set; both now apply, as on a `Task` state.
- **Step Functions — JSONata variables with the value `null`** — a variable assigned `null` read back as undefined, so `{% $var %}` failed with `States.QueryEvaluationError`; it now reads back as `null`, as on AWS. An unset variable still fails.
- **Lambda — Kinesis event source mapping filters** — a `FilterCriteria` pattern on a Kinesis record's `data` or on its metadata (`partitionKey`, `sequenceNumber`, ...) never matched, so a mapping with filters dropped every record. Patterns are now matched as AWS documents them: metadata fields next to the event fields, and `data` decoded from base64 as JSON. Data that isn't JSON can't match a `data` pattern but still matches metadata patterns.
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index 9b784713..2df3ff5e 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -2621,9 +2621,12 @@ def _run_map_items(state_def, raw_input, execution, ctx):
# No _apply_parameters here: on a Map, Parameters is the deprecated ItemSelector spelling and
# is applied per item below -- and ItemsPath must resolve against the untransformed input
effective = _apply_input_path(state_def, raw_input, ctx)
+ is_jsonata = _state_query_language(state_def, ctx) == "JSONata"
- items_path = state_def.get("ItemsPath", "$")
- items = _resolve_path_or_ctx(items_path, effective, ctx)
+ if is_jsonata and "Items" in state_def:
+ items = _jsonata_state_field(state_def, "Items", "array", raw_input, ctx)
+ else:
+ items = _resolve_path_or_ctx(state_def.get("ItemsPath", "$"), effective, ctx)
if not isinstance(items, list):
items = [items]
@@ -2633,6 +2636,8 @@ def _run_map_items(state_def, raw_input, execution, ctx):
iter_states = iterator.get("States", {})
iter_start = iterator.get("StartAt")
max_conc = state_def.get("MaxConcurrency", 0)
+ if is_jsonata and "MaxConcurrency" in state_def:
+ max_conc = _jsonata_state_field(state_def, "MaxConcurrency", "number", raw_input, ctx)
results = [None] * len(items)
errors = [None] * len(items)
@@ -2642,10 +2647,15 @@ def _run_map_items(state_def, raw_input, execution, ctx):
item_ctx = copy.deepcopy(ctx)
item_ctx["Map"] = {"Item": {"Index": idx, "Value": item}}
item_params = state_def.get("ItemSelector") or state_def.get("Parameters")
- # ItemSelector $ paths resolve against the Map state's effective input,
- # not the individual item. $$.Map.Item.Value provides the item.
- item_input = (_resolve_params_obj(item_params, effective, item_ctx)
- if item_params else item)
+ if not item_params:
+ item_input = item
+ elif is_jsonata:
+ # $states.context.Map.Item.Value provides the item.
+ item_input = _apply_jsonata_template(item_params, raw_input, item_ctx)
+ else:
+ # ItemSelector $ paths resolve against the Map state's effective input,
+ # not the individual item. $$.Map.Item.Value provides the item.
+ item_input = _resolve_params_obj(item_params, effective, item_ctx)
results[idx] = _run_sub_machine(
iter_states, iter_start, item_input, execution, item_ctx)
except Exception as exc:
@@ -2669,6 +2679,11 @@ def _run_map_items(state_def, raw_input, execution, ctx):
raise err if isinstance(err, _ExecutionError) else _ExecutionError(
"States.MapFailed", str(err))
+ if is_jsonata:
+ output = _apply_jsonata_output(state_def, raw_input, ctx, result=results, default=results)
+ _apply_state_assign(state_def, raw_input, ctx, result=results)
+ return output, _next_or_end(state_def)
+
result = _apply_result_selector(state_def, results)
output = _apply_result_path(state_def, raw_input, result)
output = _apply_output_path(state_def, output, ctx)
diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.py
index 452c248a..1cb370f6 100644
--- a/tests/test_stepfunctions.py
+++ b/tests/test_stepfunctions.py
@@ -8035,6 +8035,15 @@ def test_sfn_jsonata_undefined_variable_raises_query_eval_error(sfn_sync):
sfn_sync.delete_state_machine(stateMachineArn=sm_arn)
+_SFN_ECHO_PROCESSOR = {"ProcessorConfig": {"Mode": "INLINE"}, "StartAt": "Echo",
+ "States": {"Echo": {"Type": "Pass", "End": True}}}
+
+
+def test_sfn_jsonata_inline_map_evaluates_its_fields(sfn_sync):
+ """A JSONata inline Map evaluates Items, ItemSelector, MaxConcurrency, Output and Assign. ItemSelector
+ reads the current item and variables from the outer scope."""
+ import uuid as _uuid_local
+ sm_name = f"jsonata-map-fields-{_uuid_local.uuid4().hex[:8]}"
def test_sfn_jsonata_assign_null_variable_reads_back_as_null(sfn_sync):
"""A variable with the value `null` reads back as `null`, not as undefined.
AWS keeps the two apart: only an unset variable fails."""
@@ -8045,6 +8054,46 @@ def test_sfn_jsonata_assign_null_variable_reads_back_as_null(sfn_sync):
roleArn="arn:aws:iam::000000000000:role/test-role",
definition=json.dumps({
"QueryLanguage": "JSONata",
+ "StartAt": "Init",
+ "States": {
+ "Init": {"Type": "Pass", "Assign": {"prefix": "item"}, "Next": "M"},
+ "M": {
+ "Type": "Map",
+ "Items": "{% $states.input.xs %}",
+ "ItemSelector": {"v": "{% $states.context.Map.Item.Value %}", "p": "{% $prefix %}"},
+ "MaxConcurrency": "{% 1 %}",
+ "ItemProcessor": _SFN_ECHO_PROCESSOR,
+ "Output": {"items": "{% $states.result %}"},
+ "Assign": {"n": "{% $count($states.result) %}"},
+ "Next": "After",
+ },
+ "After": {"Type": "Pass", "Output": {"map": "{% $states.input %}", "n": "{% $n %}"}, "End": True},
+ },
+ }),
+ )["stateMachineArn"]
+ try:
+ resp = sfn_sync.start_sync_execution(stateMachineArn=sm_arn, input=json.dumps({"xs": [10, 20]}))
+ assert resp["status"] == "SUCCEEDED", resp.get("cause")
+ assert json.loads(resp["output"]) == {
+ "map": {"items": [{"v": 10, "p": "item"}, {"v": 20, "p": "item"}]},
+ "n": 2,
+ }
+ finally:
+ sfn_sync.delete_state_machine(stateMachineArn=sm_arn)
+
+
+def test_sfn_jsonata_inline_map_items_not_an_array_fails(sfn_sync):
+ """A JSONata Map whose Items does not evaluate to an array fails with `States.QueryEvaluationError`."""
+ import uuid as _uuid_local
+ sm_name = f"jsonata-map-items-type-{_uuid_local.uuid4().hex[:8]}"
+ sm_arn = sfn_sync.create_state_machine(
+ name=sm_name,
+ roleArn="arn:aws:iam::000000000000:role/test-role",
+ definition=json.dumps({
+ "QueryLanguage": "JSONata",
+ "StartAt": "M",
+ "States": {
+ "M": {"Type": "Map", "Items": "{% 'x' %}", "ItemProcessor": _SFN_ECHO_PROCESSOR, "End": True},
"StartAt": "SetNull",
"States": {
"SetNull": {
@@ -8062,8 +8111,8 @@ def test_sfn_jsonata_assign_null_variable_reads_back_as_null(sfn_sync):
)["stateMachineArn"]
try:
resp = sfn_sync.start_sync_execution(stateMachineArn=sm_arn, input="{}")
- assert resp["status"] == "SUCCEEDED"
- assert json.loads(resp["output"]) == {"v": None}
+ assert resp["status"] == "FAILED"
+ assert resp.get("error") == "States.QueryEvaluationError"
finally:
sfn_sync.delete_state_machine(stateMachineArn=sm_arn)