Skip to content

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

Support JSONPath workflow variable assignment (#2444)

Jay Janssencf6700d82726
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index 2df3ff5e..3b1161a2 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -1916,10 +1916,11 @@ def _execute_pass(state_def, raw_input, ctx=None):
effective = _apply_input_path(state_def, raw_input, ctx)
effective = _apply_parameters(state_def, effective, ctx)
- result = state_def.get("Result", effective)
- result = _apply_result_selector(state_def, result)
+ assignment_result = state_def.get("Result", effective)
+ result = _apply_result_selector(state_def, assignment_result)
output = _apply_result_path(state_def, raw_input, result)
output = _apply_output_path(state_def, output, ctx)
+ _apply_state_assign(state_def, effective, ctx, result=assignment_result)
return output, _next_or_end(state_def)
@@ -1964,6 +1965,7 @@ def _execute_task(state_def, raw_input, execution, ctx):
result = _apply_result_selector(state_def, mock_result)
output = _apply_result_path(state_def, raw_input, result)
output = _apply_output_path(state_def, output, ctx)
+ _apply_state_assign(state_def, raw_input, ctx, result=mock_result)
return output, _next_or_end(state_def)
if is_callback:
@@ -2025,6 +2027,7 @@ def _execute_task(state_def, raw_input, execution, ctx):
result = _apply_result_selector(state_def, task_result)
output = _apply_result_path(state_def, raw_input, result)
output = _apply_output_path(state_def, output, ctx)
+ _apply_state_assign(state_def, raw_input, ctx, result=task_result)
return output, _next_or_end(state_def)
except _ExecutionError as err:
@@ -2304,11 +2307,15 @@ def _execute_choice(state_def, raw_input, ctx=None):
for choice in state_def.get("Choices", []):
if _evaluate_rule(choice, effective, ctx):
- return _apply_output_path(state_def, effective, ctx), choice["Next"]
+ output = _apply_output_path(state_def, effective, ctx)
+ _apply_state_assign(choice, effective, ctx)
+ return output, choice["Next"]
default = state_def.get("Default")
if default:
- return _apply_output_path(state_def, effective, ctx), default
+ output = _apply_output_path(state_def, effective, ctx)
+ _apply_state_assign(state_def, effective, ctx)
+ return output, default
raise _ExecutionError("States.NoChoiceMatched",
"No choice rule matched and no Default")
@@ -2331,6 +2338,14 @@ def _evaluate_jsonata_choice_rule(rule, raw_input, ctx):
def _resolve_path_or_ctx(path, data, ctx):
if path.startswith("$$."):
return _resolve_ctx_path(path, ctx or {})
+ if path.startswith("$") and len(path) > 1 and path[1] not in ".[":
+ match = re.match(r"^\$([^.[\s]+)(.*)$", path)
+ if match:
+ name, suffix = match.groups()
+ variables = (ctx or {}).get("variables", {})
+ if name not in variables:
+ raise _ExecutionError("States.Runtime", f"Undefined workflow variable: {name}")
+ return _resolve_path("$" + suffix, variables[name])
return _resolve_path(path, data)
@@ -2455,6 +2470,7 @@ def _execute_wait(state_def, raw_input, ctx=None):
_sleep_until(ts_str)
output = _apply_output_path(state_def, effective, ctx)
+ _apply_state_assign(state_def, effective, ctx)
return output, _next_or_end(state_def)
@@ -2574,7 +2590,7 @@ def _run_parallel_branches(state_def, raw_input, execution, ctx):
results[idx] = _run_sub_machine(
branch.get("States", {}),
branch.get("StartAt"),
- effective, execution, ctx)
+ effective, execution, copy.deepcopy(ctx))
except Exception as exc:
errors[idx] = exc
@@ -2604,6 +2620,7 @@ def _run_parallel_branches(state_def, raw_input, execution, ctx):
result = _apply_result_selector(state_def, results)
output = _apply_result_path(state_def, raw_input, result)
output = _apply_output_path(state_def, output, ctx)
+ _apply_state_assign(state_def, raw_input, ctx, result=results)
return output, _next_or_end(state_def)
@@ -2687,6 +2704,7 @@ def _run_map_items(state_def, raw_input, execution, ctx):
result = _apply_result_selector(state_def, results)
output = _apply_result_path(state_def, raw_input, result)
output = _apply_output_path(state_def, output, ctx)
+ _apply_state_assign(state_def, raw_input, ctx, result=results)
return output, _next_or_end(state_def)
@@ -2850,6 +2868,7 @@ def _run_distributed_map(state_def, raw_input, effective, iterator, execution, c
result = _apply_result_selector(state_def, results)
output = _apply_result_path(state_def, raw_input, result)
output = _apply_output_path(state_def, output, ctx)
+ _apply_state_assign(state_def, raw_input, ctx, result=results)
return output, _next_or_end(state_def)
@@ -2980,7 +2999,7 @@ def _apply_jsonata_output(state_def, raw_input, ctx=None, result=None, error_out
def _apply_state_assign(state_def, raw_input, ctx, result=None, error_output=None):
- """Evaluate a state's `Assign` field (JSONata only) and merge results
+ """Evaluate a state's JSONPath or JSONata `Assign` field and merge results
into ``ctx['variables']`` so later JSONata expressions can reference them
as ``$name``. Variables are execution-scoped per AWS.
@@ -2989,17 +3008,23 @@ def _apply_state_assign(state_def, raw_input, ctx, result=None, error_output=Non
"""
if ctx is None:
return
- if _state_query_language(state_def, ctx) != "JSONata":
- return
assign = state_def.get("Assign")
if not isinstance(assign, dict):
return
variables = ctx.setdefault("variables", {})
- for name, template in assign.items():
- variables[name] = _apply_jsonata_template(
- template, raw_input, ctx,
- result=result, error_output=error_output,
- )
+ if _state_query_language(state_def, ctx) == "JSONata":
+ assigned = {
+ name: _apply_jsonata_template(template, raw_input, ctx,
+ result=result, error_output=error_output)
+ for name, template in assign.items()
+ }
+ else:
+ data = result if state_def.get("Type") in ("Task", "Pass", "Map", "Parallel") else raw_input
+ if error_output is not None:
+ data = error_output
+ assigned = _resolve_params_obj(assign, data, ctx)
+ # All expressions see state-entry values, including assignments to peers.
+ variables.update(copy.deepcopy(assigned))
def _apply_jsonata_template(value, raw_input, ctx=None, result=None, error_output=None):
@@ -3462,7 +3487,7 @@ def _eval_intrinsic_arg(arg, data, ctx):
path = arg[1]
if path.startswith("$$."):
return _resolve_ctx_path(path, ctx or {})
- return _resolve_path(path, data)
+ return _resolve_path_or_ctx(path, data, ctx)
elif kind == "call":
return _exec_intrinsic(arg, data, ctx)
return None
@@ -3601,7 +3626,7 @@ def _resolve_params_obj(template, data, ctx=None):
elif value.startswith("$$."):
result[real_key] = _resolve_ctx_path(value, ctx or {})
else:
- result[real_key] = _resolve_path(value, data)
+ result[real_key] = _resolve_path_or_ctx(value, data, ctx)
else:
result[real_key] = value
elif isinstance(value, dict):
diff --git a/tests/test_jsonpath_variables.py b/tests/test_jsonpath_variables.py
new file mode 100644
index 00000000..c7c12325
--- /dev/null
+++ b/tests/test_jsonpath_variables.py
@@ -0,0 +1,63 @@
+"""JSONPath workflow variables survive output projection and nested callbacks."""
+import unittest
+from unittest.mock import patch
+from ministack.services import stepfunctions as sfn
+
+
+class JSONPathVariablesTest(unittest.TestCase):
+ def test_task_assignment_uses_raw_result_and_survives_projection(self):
+ ctx = {"State": {}, "variables": {"target": None}}
+ task = {"Type": "Task", "Resource": "arn:aws:states:::lambda:invoke",
+ "Assign": {"target.$": "$.Payload.address"},
+ "OutputPath": "$.Payload.value", "End": True}
+ with patch.object(sfn, "_invoke_resource", return_value={"Payload": {"address": {"id": "physical"}, "value": {}}}), patch.object(sfn, "_add_event"):
+ output, _ = sfn._execute_task(task, {}, {}, ctx)
+ self.assertEqual(output, {})
+ self.assertEqual(sfn._resolve_params_obj({"target.$": "$target"}, output, ctx), {"target": {"id": "physical"}})
+ self.assertEqual(sfn._resolve_params_obj({"id.$": "States.Format('{}', $target.id)"}, {}, ctx), {"id": "physical"})
+
+ def test_assignments_read_previous_values(self):
+ ctx = {"variables": {"a": 1, "b": 2}}
+ sfn._execute_pass({"Type": "Pass", "Assign": {"a.$": "$b", "b.$": "$a"}, "End": True}, {}, ctx)
+ self.assertEqual(ctx["variables"], {"a": 2, "b": 1})
+
+ def test_choice_assignment_and_default(self):
+ for flag in (True, False):
+ ctx = {"variables": {}}
+ state = {"Type": "Choice", "Choices": [{"Variable": "$.flag", "BooleanEquals": True, "Assign": {"chosen": True}, "Next": "Done"}], "Assign": {"chosen": False}, "Default": "Done"}
+ sfn._execute_choice(state, {"flag": flag}, ctx)
+ self.assertEqual(ctx["variables"]["chosen"], flag)
+
+ def test_nested_parallel_reads_outer_variable_without_leaking_assignment(self):
+ ctx = {"State": {}, "variables": {"target": {"id": "physical"}}}
+ branch = {"StartAt": "Read", "States": {"Read": {
+ "Type": "Pass", "Parameters": {"address.$": "$target.id"},
+ "Assign": {"branchOnly": "value"}, "End": True}}}
+ output, _ = sfn._execute_parallel({"Type": "Parallel", "Branches": [branch, branch], "End": True}, {}, {}, ctx)
+ self.assertEqual(output, [{"address": "physical"}, {"address": "physical"}])
+ self.assertNotIn("branchOnly", ctx["variables"])
+
+ def test_map_assignment_uses_aggregate_result(self):
+ ctx = {"State": {}, "variables": {"target": "outer"}}
+ state = {"Type": "Map", "ItemsPath": "$.items", "Iterator": {
+ "StartAt": "Read", "States": {"Read": {"Type": "Pass",
+ "Parameters": {"target.$": "$target"}, "End": True}}},
+ "Assign": {"results.$": "$"}, "ResultPath": None, "End": True}
+ output, _ = sfn._execute_map(state, {"items": [1, 2]}, {}, ctx)
+ self.assertEqual(output, {"items": [1, 2]})
+ self.assertEqual(ctx["variables"]["results"], [{"target": "outer"}] * 2)
+
+ def test_wait_assignment_uses_filtered_input(self):
+ ctx = {"variables": {}}
+ sfn._execute_wait({"Type": "Wait", "Seconds": 0, "InputPath": "$.value",
+ "Assign": {"saved.$": "$"}, "End": True},
+ {"value": {"id": 3}}, ctx)
+ self.assertEqual(ctx["variables"]["saved"], {"id": 3})
+
+ def test_undefined_variable_fails(self):
+ with self.assertRaises(sfn._ExecutionError):
+ sfn._resolve_params_obj({"value.$": "$missing"}, {}, {"variables": {}})
+
+
+if __name__ == "__main__":
+ unittest.main()