Skip to content

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

fix: resolve SQS, DynamoDB, Batch, S3, and StepFunctions issues (#652)

Nahuel Nucera33e9a92949e9
diff --git a/ministack/services/batch.py b/ministack/services/batch.py
index 107c3400..5e9cb813 100644
--- a/ministack/services/batch.py
+++ b/ministack/services/batch.py
@@ -10,6 +10,7 @@ here, not a real container runner.
import copy
import json
import logging
+import os
import time
from ministack.core.responses import (
@@ -184,11 +185,123 @@ def _describe_job_definitions(p):
return _json(200, {"jobDefinitions": revs})
+def _detect_host_limits():
+ """Return the host's installed CPU/memory ceiling MS can compare against.
+
+ Reports *installed* capacity, not currently-available — the gate's purpose
+ is "could this jobdef ever run on this host", which is a stable property,
+ not a fluctuating one. A dimension that can't be confidently measured on
+ this platform returns ``None`` and the corresponding check is skipped, so
+ we don't false-positive on exotic environments.
+ """
+ vcpu = None
+ try:
+ vcpu = os.cpu_count()
+ except Exception:
+ vcpu = None
+
+ memory_mib = None
+ try:
+ page = os.sysconf("SC_PAGE_SIZE")
+ pages = os.sysconf("SC_PHYS_PAGES")
+ if isinstance(page, int) and isinstance(pages, int) and page > 0 and pages > 0:
+ memory_mib = (page * pages) // (1024 * 1024)
+ except (AttributeError, ValueError, OSError):
+ memory_mib = None
+ return {"vcpu": vcpu, "memory_mib": memory_mib}
+
+
+def _parse_resource_requirements(container_props):
+ """Pull VCPU + MEMORY out of a jobdef's ``containerProperties.resourceRequirements``.
+ Returns ``(vcpu_or_None, memory_mib_or_None)``. Malformed entries are
+ treated as absent so we never block on parser quirks.
+ """
+ reqs = (container_props or {}).get("resourceRequirements") or []
+ vcpu = None
+ memory_mib = None
+ for r in reqs:
+ if not isinstance(r, dict):
+ continue
+ kind = (r.get("type") or "").upper()
+ raw = r.get("value")
+ if raw is None:
+ continue
+ try:
+ num = float(raw)
+ except (TypeError, ValueError):
+ continue
+ if kind == "VCPU":
+ vcpu = num
+ elif kind == "MEMORY":
+ try:
+ memory_mib = int(num)
+ except (TypeError, ValueError):
+ continue
+ return vcpu, memory_mib
+
+
+def _resolve_jobdef(ref):
+ """Look up a jobdef record by ``name``, ``name:revision``, or full ARN.
+ Returns the record or ``None`` — never raises so callers can fall through.
+ """
+ if not ref:
+ return None
+ short = ref.split("/")[-1]
+ if ":" in short:
+ name, _, rev = short.rpartition(":")
+ try:
+ target_rev = int(rev)
+ except ValueError:
+ return None
+ for r in _job_definitions.get(name, []):
+ if r.get("revision") == target_rev:
+ return r
+ return None
+ revs = _job_definitions.get(short, [])
+ return revs[-1] if revs else None
+
+
+def _check_host_fit(container_props):
+ """Return an error message if the jobdef can't physically run on this host,
+ else ``None``. Both dimensions must be measurable on both sides for the
+ check to fire — anything ambiguous passes through.
+ """
+ limits = _detect_host_limits()
+ req_vcpu, req_mem = _parse_resource_requirements(container_props)
+
+ over = []
+ if req_vcpu is not None and limits["vcpu"] is not None and req_vcpu > limits["vcpu"]:
+ over.append(f"VCPU={req_vcpu:g} (host has {limits['vcpu']})")
+ if req_mem is not None and limits["memory_mib"] is not None and req_mem > limits["memory_mib"]:
+ over.append(f"MEMORY={req_mem} MiB (host has {limits['memory_mib']} MiB)")
+ if not over:
+ return None
+ return (
+ "SubmitJob refused: jobdef requests "
+ + ", ".join(over)
+ + ". Reduce resourceRequirements for local testing, "
+ "or run this jobdef against real AWS Batch."
+ )
+
+
# ─── jobs ───────────────────────────────────────────────────────
def _submit_job(p):
name = p.get("jobName")
if not name:
return error_response_json("ClientException", "jobName is required", 400)
+
+ # Honest fail-fast for the local-emulator case where the jobdef can't
+ # physically fit on this host. Real AWS Batch has unlimited compute so
+ # this failure mode doesn't exist there; in MS we'd otherwise return
+ # SUCCEEDED for a job that could never actually run, hiding the problem
+ # behind a second describe_jobs call. Issue #650.
+ jobdef = _resolve_jobdef(p.get("jobDefinition"))
+ if jobdef is not None:
+ fit_err = _check_host_fit(jobdef.get("containerProperties"))
+ if fit_err is not None:
+ logger.warning("Batch SubmitJob refused (%s): %s", name, fit_err)
+ return error_response_json("ClientException", fit_err, 400)
+
job_id = new_uuid()
now = _now_ms()
rec = {
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index d14de38e..16ca8cd9 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -2063,6 +2063,20 @@ def _eval_set_value(tokens, item, attr_values, attr_names):
if not tokens:
return None
+ # Strip a single layer of matched outer parens — e.g.
+ # `(if_not_exists(#v, :default) - :amt)`. Without this the binary-operator
+ # scan below never sees the `-` at depth 0 and silently drops the
+ # arithmetic, leaving the attribute at its original value (issue #648).
+ # Only strip when the opening paren's matching close is the LAST token,
+ # so `(a) + (b)` (two separate groups) isn't accidentally flattened.
+ while (len(tokens) >= 2
+ and tokens[0][0] == 'LPAREN'
+ and tokens[-1][0] == 'RPAREN'
+ and _find_matching_paren(tokens, 0) == len(tokens) - 1):
+ tokens = tokens[1:-1]
+ if not tokens:
+ return None
+
paren_depth = 0
for i, tok in enumerate(tokens):
if tok[0] == 'LPAREN':
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 3b9c1212..8562bbbe 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -1348,11 +1348,20 @@ def _parse_notification_config(bucket_name: str) -> list[dict]:
configs: list[dict] = []
+ # Real S3 accepts two ARN-tag forms for Lambda-targeted notifications.
+ # boto3's botocore wire serializes `LambdaFunctionArn` as the legacy
+ # `<CloudFunction>` tag, so MS used to parse only that. Other clients
+ # (AWS SDK for Java v2, Go SDK, hand-crafted XML, Terraform's
+ # `aws_s3_bucket_notification` provider) send the modern
+ # `<LambdaFunctionArn>` tag — MS silently dropped those configs, so
+ # uploads succeeded but the Lambda never fired (issue #649).
_CONFIG_MAP = {
"QueueConfiguration": ("sqs", ("Queue",)),
"TopicConfiguration": ("sns", ("Topic",)),
"CloudFunctionConfiguration": ("lambda", ("CloudFunction", "Function")),
- "LambdaFunctionConfiguration": ("lambda", ("Function", "CloudFunction")),
+ "LambdaFunctionConfiguration": (
+ "lambda", ("LambdaFunctionArn", "CloudFunction", "Function"),
+ ),
}
for tag_suffix, (target_type, arn_tags) in _CONFIG_MAP.items():
diff --git a/ministack/services/sqs.py b/ministack/services/sqs.py
index 283d91d9..db7f178e 100644
--- a/ministack/services/sqs.py
+++ b/ministack/services/sqs.py
@@ -170,6 +170,36 @@ async def _dispatch(action: str, data: dict, qurl: str) -> dict:
# CORE ACTIONS
# ────────────────────────────────────────────────────────────
+def _validate_redrive_policy(rp_str: str) -> None:
+ """Real-AWS-parity validation for the RedrivePolicy queue attribute.
+
+ AWS rejects malformed values at CreateQueue/SetQueueAttributes time with
+ `InvalidAttributeValue` (HTTP 400). Without this gate, MS stores the bad
+ value and `_dlq_sweep` later crashes on receive because `json.loads` of a
+ double-encoded string returns a string, not a dict, and `.get()` blows up.
+ """
+ err_msg = ("Invalid value for the parameter RedrivePolicy. Value must be a "
+ "JSON object containing string fields deadLetterTargetArn and "
+ "maxReceiveCount (an integer between 1 and 1000).")
+ try:
+ parsed = json.loads(rp_str)
+ except (TypeError, ValueError):
+ raise _Err("InvalidAttributeValue", err_msg, 400)
+ if not isinstance(parsed, dict):
+ raise _Err("InvalidAttributeValue", err_msg, 400)
+ dlta = parsed.get("deadLetterTargetArn")
+ mrc = parsed.get("maxReceiveCount")
+ if not isinstance(dlta, str) or not dlta:
+ raise _Err("InvalidAttributeValue", err_msg, 400)
+ # AWS accepts maxReceiveCount as either int or string-encoded int.
+ try:
+ mrc_int = int(mrc)
+ except (TypeError, ValueError):
+ raise _Err("InvalidAttributeValue", err_msg, 400)
+ if mrc_int < 1 or mrc_int > 1000:
+ raise _Err("InvalidAttributeValue", err_msg, 400)
+
+
def _act_create_queue(data: dict, _u: str) -> dict:
name = data.get("QueueName", "")
if not name:
@@ -177,6 +207,8 @@ def _act_create_queue(data: dict, _u: str) -> dict:
"The request must contain the parameter QueueName.")
attrs = data.get("Attributes") or {}
+ if "RedrivePolicy" in attrs:
+ _validate_redrive_policy(str(attrs["RedrivePolicy"]))
is_fifo = name.endswith(".fifo") or attrs.get("FifoQueue") == "true"
if is_fifo and not name.endswith(".fifo"):
@@ -515,7 +547,10 @@ def _act_get_queue_attributes(data: dict, qurl: str) -> dict:
def _act_set_queue_attributes(data: dict, qurl: str) -> dict:
url = data.get("QueueUrl", qurl)
q = _get_q(url)
- for k, v in (data.get("Attributes") or {}).items():
+ incoming = data.get("Attributes") or {}
+ if "RedrivePolicy" in incoming:
+ _validate_redrive_policy(str(incoming["RedrivePolicy"]))
+ for k, v in incoming.items():
q["attributes"][k] = str(v)
q["attributes"]["LastModifiedTimestamp"] = str(int(time.time()))
return {}
@@ -863,7 +898,17 @@ def _dlq_sweep(q: dict) -> None:
rp = json.loads(rp_raw)
except Exception:
return
- max_rc = int(rp.get("maxReceiveCount", 0))
+ # Belt-and-suspenders: persisted state from older MS versions (pre-fix)
+ # may have stored a double-encoded RedrivePolicy that decodes to a string,
+ # not a dict. CreateQueue/SetQueueAttributes now reject this at intake
+ # (InvalidAttributeValue), but skip rather than crash if a legacy value
+ # slips through.
+ if not isinstance(rp, dict):
+ return
+ try:
+ max_rc = int(rp.get("maxReceiveCount", 0))
+ except (TypeError, ValueError):
+ return
arn = rp.get("deadLetterTargetArn", "")
if not max_rc or not arn:
return
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index 035b7fb3..8fbfd1a4 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -962,6 +962,7 @@ def _test_state(data):
# for single-state definitions the state's own QueryLanguage still wins via
# `_state_query_language`.
ctx.setdefault("QueryLanguage", definition.get("QueryLanguage", "JSONPath"))
+ ctx.setdefault("variables", {})
inspection_data = {}
if inspection_level in ("DEBUG", "TRACE"):
@@ -1177,6 +1178,11 @@ def _run_execution(exec_arn):
"Id": execution["stateMachineArn"],
"Name": sm["name"],
},
+ # JSONata workflow variables — bound via state `Assign` fields and
+ # referenced as `$name` in subsequent JSONata expressions. Scope is
+ # the whole execution (per AWS); Map/Parallel sub-branches share
+ # this dict with the parent, matching AWS semantics.
+ "variables": {},
}
try:
@@ -1279,6 +1285,9 @@ def _execute_pass(state_def, raw_input, ctx=None):
# passes input through unchanged (matches AWS behavior — Pass with no
# transformation is the identity state).
output = _apply_jsonata_output(state_def, raw_input, ctx, default=raw_input)
+ # Pass has no API call, so `$states.result` in Assign expressions
+ # refers to the state's computed Output (per AWS docs).
+ _apply_state_assign(state_def, raw_input, ctx, result=output)
return output, _next_or_end(state_def)
effective = _apply_input_path(state_def, raw_input)
@@ -1375,6 +1384,9 @@ def _execute_task(state_def, raw_input, execution, ctx):
result=task_result,
default=task_result,
)
+ # Task `Assign` sees `$states.result` = raw API result (per
+ # AWS), not the post-Output transformed value.
+ _apply_state_assign(state_def, raw_input, ctx, result=task_result)
else:
result = _apply_result_selector(state_def, task_result)
output = _apply_result_path(state_def, raw_input, result)
@@ -1417,6 +1429,10 @@ def _execute_task(state_def, raw_input, execution, ctx):
else:
output = _apply_result_path_raw(
catcher.get("ResultPath", "$"), raw_input, error_output)
+ if query_language == "JSONata":
+ # Catch handlers can also carry `Assign`. `$states.errorOutput`
+ # is available here; `$states.result` is not (per AWS).
+ _apply_state_assign(catcher, raw_input, ctx, error_output=error_output)
return output, catcher["Next"]
raise last_error
@@ -1574,9 +1590,15 @@ def _execute_choice(state_def, raw_input, ctx=None):
# Per-branch Output (if present) takes precedence; otherwise
# input passes through unchanged.
output = _apply_jsonata_output(choice, raw_input, ctx, default=raw_input)
+ # Per-branch Assign — `$states.result` is not applicable on
+ # Choice (no API call); only `$states.input` and existing
+ # variables are usable.
+ _apply_state_assign(choice, raw_input, ctx)
return output, choice["Next"]
default = state_def.get("Default")
if default:
+ # State-level Assign applies when falling through to Default.
+ _apply_state_assign(state_def, raw_input, ctx)
return raw_input, default
raise _ExecutionError("States.NoChoiceMatched",
"No choice rule matched and no Default")
@@ -1963,6 +1985,29 @@ 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
+ into ``ctx['variables']`` so later JSONata expressions can reference them
+ as ``$name``. Variables are execution-scoped per AWS.
+
+ Called after the state's output is computed so that `$states.result` in
+ Assign expressions sees the state's actual result.
+ """
+ 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,
+ )
+
+
def _apply_jsonata_template(value, raw_input, ctx=None, result=None, error_output=None):
if isinstance(value, str):
if value.startswith("{%") and value.endswith("%}"):
@@ -1985,6 +2030,9 @@ def _apply_jsonata_template(value, raw_input, ctx=None, result=None, error_outpu
def _evaluate_jsonata(expression, raw_input, ctx=None, result=None, error_output=None):
states = {
"input": raw_input,
+ # workflow-scoped variables — looked up by bare `$name` references
+ # in expressions. See `_eval_jsonata_primary`.
+ "_variables": (ctx or {}).get("variables", {}),
"result": result,
"errorOutput": error_output,
"context": ctx or {},
@@ -2126,6 +2174,23 @@ def _eval_jsonata_primary(expr, states):
if expr.startswith("$states."):
return _resolve_jsonata_states_path(expr, states)
+ # Bare workflow variable reference: `$name` or `$name.dotted.path`.
+ # `$states.…` is already handled above; `$func(…)` was handled by the
+ # built-in function block above (variable refs have no `(`); so anything
+ # else starting with `$<alpha>` is a variable lookup. Issue #645.
+ if (len(expr) > 1
+ and expr[0] == "$"
+ and "(" not in expr
+ and re.fullmatch(r"\$[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*", expr)):
+ head, _dot, rest = expr[1:].partition(".")
+ variables = states.get("_variables", {})
+ if head not in variables:
+ raise ValueError(f"Undefined variable: ${head}")
+ value = variables[head]
+ if rest:
+ value = _resolve_dotted_path(rest, value)
+ return value
+
if expr in ("true", "false", "null"):
return {"true": True, "false": False, "null": None}[expr]
diff --git a/tests/test_batch.py b/tests/test_batch.py
index efe8392d..fbb3781a 100644
--- a/tests/test_batch.py
+++ b/tests/test_batch.py
@@ -98,3 +98,156 @@ def test_batch_account_isolation():
b_qs = [q["jobQueueName"] for q in b.describe_job_queues()["jobQueues"]]
assert name in a_qs
assert name not in b_qs
+
+
+# ---------------------------------------------------------------------------
+# SubmitJob host-resource gate (issue #650)
+# ---------------------------------------------------------------------------
+
+def _register(batch, name, reqs=None):
+ container = {"image": "alpine:3.20", "command": ["echo", "hi"]}
+ if reqs is not None:
+ container["resourceRequirements"] = reqs
+ return batch.register_job_definition(
+ jobDefinitionName=name, type="container", containerProperties=container,
+ )
+
+
+def test_batch_submit_job_refused_when_jobdef_exceeds_host(batch):
+ """Issue #650: jobdef requesting more resources than MS' host can provide
+ must surface at the SubmitJob call (400 ClientException) — not silently
+ return SUCCEEDED for a job that could never run.
+ """
+ from botocore.exceptions import ClientError
+ name = f"oversize-{_uid()}"
+ _register(batch, name, reqs=[
+ {"type": "VCPU", "value": "256"}, # impossibly high
+ {"type": "MEMORY", "value": "9999999"},
+ ])
+ with pytest.raises(ClientError) as exc:
+ batch.submit_job(jobName=f"r-{_uid()}", jobQueue="q",
+ jobDefinition=f"{name}:1")
+ err = exc.value.response["Error"]
+ assert err["Code"] == "ClientException"
+ msg = err["Message"]
+ assert "SubmitJob refused" in msg
+ assert "VCPU=256" in msg
+ assert "MEMORY=9999999" in msg
+
+
+def test_batch_submit_job_vcpu_only_over_fails(batch):
+ """When only VCPU exceeds, the message reports only VCPU."""
+ from botocore.exceptions import ClientError
+ name = f"vcpu-{_uid()}"
+ _register(batch, name, reqs=[
+ {"type": "VCPU", "value": "256"},
+ {"type": "MEMORY", "value": "64"},
+ ])
+ with pytest.raises(ClientError) as exc:
+ batch.submit_job(jobName=f"r-{_uid()}", jobQueue="q",
+ jobDefinition=f"{name}:1")
+ msg = exc.value.response["Error"]["Message"]
+ assert "VCPU=256" in msg
+ assert "MEMORY" not in msg # only the over-capacity dimension surfaces
+
+
+def test_batch_submit_job_memory_only_over_fails(batch):
+ from botocore.exceptions import ClientError
+ name = f"mem-{_uid()}"
+ _register(batch, name, reqs=[
+ {"type": "VCPU", "value": "1"},
+ {"type": "MEMORY", "value": "9999999"},
+ ])
+ with pytest.raises(ClientError) as exc:
+ batch.submit_job(jobName=f"r-{_uid()}", jobQueue="q",
+ jobDefinition=f"{name}:1")
+ msg = exc.value.response["Error"]["Message"]
+ assert "MEMORY=9999999" in msg
+ assert "VCPU" not in msg
+
+
+def test_batch_submit_job_fitting_resources_succeeds(batch):
+ """Regression: a jobdef well within the host's ceiling must still pass
+ through to the stub-SUCCEEDED behavior MS has always had.
+ """
+ name = f"fit-{_uid()}"
+ _register(batch, name, reqs=[
+ {"type": "VCPU", "value": "1"},
+ {"type": "MEMORY", "value": "128"},
+ ])
+ resp = batch.submit_job(jobName=f"r-{_uid()}", jobQueue="q",
+ jobDefinition=f"{name}:1")
+ assert "jobId" in resp
+ desc = batch.describe_jobs(jobs=[resp["jobId"]])["jobs"][0]
+ assert desc["status"] == "SUCCEEDED"
+
+
+def test_batch_submit_job_no_resource_requirements_succeeds(batch):
+ """A jobdef without `resourceRequirements` has nothing to compare against;
+ pass through unchanged.
+ """
+ name = f"noreqs-{_uid()}"
+ _register(batch, name, reqs=None)
+ resp = batch.submit_job(jobName=f"r-{_uid()}", jobQueue="q",
+ jobDefinition=f"{name}:1")
+ assert "jobId" in resp
+
+
+def test_batch_submit_job_unknown_jobdef_passes_through(batch):
+ """When the `jobDefinition` reference can't be resolved, MS preserves its
+ existing permissive behavior (don't introduce a *new* failure mode while
+ fixing a different one).
+ """
+ resp = batch.submit_job(jobName=f"r-{_uid()}", jobQueue="q",
+ jobDefinition="does-not-exist:99")
+ assert "jobId" in resp
+
+
+def test_batch_submit_job_resolves_by_name_takes_latest_revision(batch):
+ """`jobDefinition='name'` (no `:rev`) resolves to the latest revision."""
+ name = f"byname-{_uid()}"
+ _register(batch, name, reqs=[{"type": "VCPU", "value": "1"},
+ {"type": "MEMORY", "value": "128"}])
+ # Bump revision; the latest one is still small, gate must still pass.
+ _register(batch, name, reqs=[{"type": "VCPU", "value": "1"},
+ {"type": "MEMORY", "value": "64"}])
+ resp = batch.submit_job(jobName=f"r-{_uid()}", jobQueue="q",
+ jobDefinition=name) # no :rev
+ assert "jobId" in resp
+
+
+def test_batch_resource_check_skipped_when_host_unmeasurable(monkeypatch):
+ """If host detection returns None for every dimension (exotic platform),
+ the gate must skip silently — no false-positive refusals.
+ """
+ from ministack.services import batch as batch_mod
+ monkeypatch.setattr(
+ batch_mod, "_detect_host_limits",
+ lambda: {"vcpu": None, "memory_mib": None},
+ )
+ container = {
+ "image": "alpine:3.20",
+ "command": ["echo", "hi"],
+ "resourceRequirements": [
+ {"type": "VCPU", "value": "9999"},
+ {"type": "MEMORY", "value": "9999999"},
+ ],
+ }
+ assert batch_mod._check_host_fit(container) is None
+
+
+def test_batch_resource_check_skipped_when_jobdef_dimension_unmeasurable(monkeypatch):
+ """If the jobdef declares one dimension but not the other, only the
+ declared one is compared — no spurious failures from absent fields.
+ """
+ from ministack.services import batch as batch_mod
+ monkeypatch.setattr(
+ batch_mod, "_detect_host_limits",
+ lambda: {"vcpu": 2, "memory_mib": 1024},
+ )
+ container = {
+ "image": "alpine:3.20",
+ "command": ["echo", "hi"],
+ "resourceRequirements": [{"type": "VCPU", "value": "1"}], # only VCPU
+ }
+ assert batch_mod._check_host_fit(container) is None
diff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.py
index ed74a968..5f3cf023 100644
--- a/tests/test_dynamodb.py
+++ b/tests/test_dynamodb.py
@@ -2652,3 +2652,123 @@ def test_dynamodb_attribute_updates_add_on_string_attribute_raises(ddb):
assert exc_info.value.response["Error"]["Code"] == "ValidationException"
+# ---------------------------------------------------------------------------
+# UpdateExpression arithmetic + if_not_exists (issue #648)
+# ---------------------------------------------------------------------------
+
+def _make_counter_table(ddb, name):
+ ddb.create_table(
+ TableName=name,
+ AttributeDefinitions=[{"AttributeName": "PK", "AttributeType": "S"}],
+ KeySchema=[{"AttributeName": "PK", "KeyType": "HASH"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+
+
+def test_dynamodb_update_if_not_exists_minus_in_outer_parens(ddb):
+ """Regression for #648: `SET v = (if_not_exists(v, :d) - :amt)` lost the
+ arithmetic and assigned the resolved value directly. The outer parens
+ pinned every token to depth>0, so the top-level operator scan skipped
+ the `-` and silently dropped the subtraction.
+ """
+ table = "if-not-exists-minus-parens"
+ _make_counter_table(ddb, table)
+ try:
+ ddb.put_item(TableName=table, Item={"PK": {"S": "x"}, "v": {"N": "10000"}})
+ ddb.update_item(
+ TableName=table,
+ Key={"PK": {"S": "x"}},
+ UpdateExpression="SET #v = (if_not_exists(#v, :d) - :amt)",
+ ExpressionAttributeNames={"#v": "v"},
+ ExpressionAttributeValues={":d": {"N": "0"}, ":amt": {"N": "3000"}},
+ )
+ got = ddb.get_item(TableName=table, Key={"PK": {"S": "x"}})["Item"]["v"]
+ assert got == {"N": "7000"}
+ finally:
+ ddb.delete_table(TableName=table)
+
+
+def test_dynamodb_update_if_not_exists_plus_in_outer_parens(ddb):
+ """Same shape with `+` rather than `-` — both PLUS and MINUS go through
+ the same operator-scan branch, so both need the outer-paren strip.
+ """
+ table = "if-not-exists-plus-parens"
+ _make_counter_table(ddb, table)
+ try:
+ ddb.put_item(TableName=table, Item={"PK": {"S": "x"}, "v": {"N": "100"}})
+ ddb.update_item(
+ TableName=table,
+ Key={"PK": {"S": "x"}},
+ UpdateExpression="SET #v = (if_not_exists(#v, :d) + :amt)",
+ ExpressionAttributeNames={"#v": "v"},
+ ExpressionAttributeValues={":d": {"N": "0"}, ":amt": {"N": "42"}},
+ )
+ got = ddb.get_item(TableName=table, Key={"PK": {"S": "x"}})["Item"]["v"]
+ assert got == {"N": "142"}
+ finally:
+ ddb.delete_table(TableName=table)
+
+
+def test_dynamodb_update_if_not_exists_arithmetic_when_attribute_missing(ddb):
+ """When the attribute doesn't exist yet, `if_not_exists` resolves to the
+ default and the arithmetic still applies: `0 - 3000 = -3000`.
+ """
+ table = "if-not-exists-arith-missing"
+ _make_counter_table(ddb, table)
+ try:
+ ddb.put_item(TableName=table, Item={"PK": {"S": "x"}}) # no `v`
+ ddb.update_item(
+ TableName=table,
+ Key={"PK": {"S": "x"}},
+ UpdateExpression="SET #v = (if_not_exists(#v, :d) - :amt)",
+ ExpressionAttributeNames={"#v": "v"},
+ ExpressionAttributeValues={":d": {"N": "0"}, ":amt": {"N": "3000"}},
+ )
+ got = ddb.get_item(TableName=table, Key={"PK": {"S": "x"}})["Item"]["v"]
+ assert got == {"N": "-3000"}
+ finally:
+ ddb.delete_table(TableName=table)
+
+
+def test_dynamodb_update_arithmetic_without_outer_parens_still_works(ddb):
+ """Sanity: the pre-existing no-outer-parens form must keep working too —
+ `SET v = if_not_exists(v, :d) - :amt`.
+ """
+ table = "if-not-exists-no-parens"
+ _make_counter_table(ddb, table)
+ try:
+ ddb.put_item(TableName=table, Item={"PK": {"S": "x"}, "v": {"N": "10"}})
+ ddb.update_item(
+ TableName=table,
+ Key={"PK": {"S": "x"}},
+ UpdateExpression="SET #v = if_not_exists(#v, :d) - :amt",
+ ExpressionAttributeNames={"#v": "v"},
+ ExpressionAttributeValues={":d": {"N": "0"}, ":amt": {"N": "3"}},
+ )
+ got = ddb.get_item(TableName=table, Key={"PK": {"S": "x"}})["Item"]["v"]
+ assert got == {"N": "7"}
+ finally:
+ ddb.delete_table(TableName=table)
+
+
+def test_dynamodb_update_nested_parens_do_not_flatten_two_groups(ddb):
+ """`(a) + (b)` must NOT be flattened by the outer-paren strip — the
+ opening LPAREN doesn't match the final RPAREN. Numeric value of
+ `(:left) + (:right)` should be 10.
+ """
+ table = "nested-parens-two-groups"
+ _make_counter_table(ddb, table)
+ try:
+ ddb.put_item(TableName=table, Item={"PK": {"S": "x"}})
+ ddb.update_item(
+ TableName=table,
+ Key={"PK": {"S": "x"}},
+ UpdateExpression="SET v = (:left) + (:right)",
+ ExpressionAttributeValues={":left": {"N": "3"}, ":right": {"N": "7"}},
+ )
+ got = ddb.get_item(TableName=table, Key={"PK": {"S": "x"}})["Item"]["v"]
+ assert got == {"N": "10"}
+ finally:
+ ddb.delete_table(TableName=table)
+
+
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 400bb817..9e938cf7 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -3616,6 +3616,67 @@ exports.handler = (event, ctx, cb) => {{
assert result.get("status") == "ok", f"Handler failed: {result}"
assert received.get("path") == "/test-cfn-response", "PUT not received by HTTP server"
assert received.get("body") == "test"
+
+
+def test_nodejs_worker_aws_sdk_v3_stub_wire_roundtrip(lam, ssm):
+ """End-to-end: a Node.js Lambda using @aws-sdk/client-ssm's
+ PutParameterCommand actually creates a parameter on MiniStack's SSM
+ service. Guards against the JSON-RPC stub silently 404'ing or routing
+ to the wrong target prefix (the per-service hardcoded map can drift from
+ router.py undetected by the resolution-only tests).
+ """
+ import shutil
+
+ import uuid as _uuid
+ if not shutil.which("node"):
+ pytest.skip("node not found on PATH")
+
+ fname = f"sdk-roundtrip-{_uuid.uuid4().hex[:8]}"
+ param_name = f"/ministack-test/{_uuid.uuid4().hex[:8]}"
+ param_value = f"value-{_uuid.uuid4().hex[:8]}"
+ code = (
+ "const { SSMClient, PutParameterCommand } = require('@aws-sdk/client-ssm');\n"
+ "exports.handler = async (event) => {\n"
+ " const client = new SSMClient({});\n"
+ " await client.send(new PutParameterCommand({\n"
+ " Name: event.name, Value: event.value, Type: 'String', Overwrite: true,\n"
+ " }));\n"
+ " return { ok: true };\n"
+ "};\n"
+ )
+ try:
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="nodejs20.x",
+ Role="arn:aws:iam::000000000000:role/test-role",
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip_js(code, "index.js")},
+ )
+ resp = lam.invoke(
+ FunctionName=fname,
+ Payload=json.dumps({"name": param_name, "value": param_value}).encode(),
+ )
+ body = resp["Payload"].read().decode()
+ assert resp["StatusCode"] == 200, f"Invoke failed: {body}"
+ assert "FunctionError" not in resp, f"Handler errored: {body}"
+ assert json.loads(body) == {"ok": True}, f"Unexpected body: {body}"
+
+ # The stub must have actually called SSM. Verify via boto3 — if the
+ # X-Amz-Target was wrong or the body didn't reach MS, this raises
+ # ParameterNotFound and the test fails.
+ fetched = ssm.get_parameter(Name=param_name)["Parameter"]
+ assert fetched["Value"] == param_value
+ finally:
+ try:
+ lam.delete_function(FunctionName=fname)
+ except Exception:
+ pass
+ try:
+ ssm.delete_parameter(Name=param_name)
+ except Exception:
+ pass
+
+
def test_lambda_ruby_4_0_runtime_maps_to_official_image():
"""Lambda Ruby 4.0 runtime support (botocore 1.42.94 added the runtime).
Maps to AWS's official Lambda Ruby 4.0 base image."""
diff --git a/tests/test_s3.py b/tests/test_s3.py
index a1178c13..bb9ef73e 100644
--- a/tests/test_s3.py
+++ b/tests/test_s3.py
@@ -1016,6 +1016,144 @@ def test_s3_put_notification_sends_test_event(s3, sqs):
assert "Records" not in body
+def _wait_lambda_invoked(logs_client, function_name, marker, timeout=5.0):
+ """Poll the function's log group for a marker substring. Returns True on
+ first match, False after timeout."""
+ log_group = f"/aws/lambda/{function_name}"
+ end = time.time() + timeout
+ while time.time() < end:
+ try:
+ streams = logs_client.describe_log_streams(logGroupName=log_group)["logStreams"]
+ except Exception:
+ time.sleep(0.2)
+ continue
+ for s in streams:
+ try:
+ events = logs_client.get_log_events(
+ logGroupName=log_group, logStreamName=s["logStreamName"],
+ )["events"]
+ except Exception:
+ continue
+ if any(marker in (e.get("message") or "") for e in events):
+ return True
+ time.sleep(0.2)
+ return False
+
+
+def _create_event_lambda(lam, name):
+ import io as _io
+ import zipfile as _zip
+ code = (
+ "def handler(event, context):\n"
+ " import json\n"
+ " print('S3EVT', json.dumps(event))\n"
+ " return {'ok': True}\n"
+ )
+ buf = _io.BytesIO()
+ with _zip.ZipFile(buf, "w") as z:
+ z.writestr("lambda_function.py", code)
+ lam.create_function(
+ FunctionName=name,
+ Runtime="python3.13",
+ Role="arn:aws:iam::000000000000:role/test",
+ Handler="lambda_function.handler",
+ Code={"ZipFile": buf.getvalue()},
+ )
+ return lam.get_function(FunctionName=name)["Configuration"]["FunctionArn"]
+
+
+def test_s3_event_notification_to_lambda_boto3_default(s3, lam, logs):
+ """Regression: boto3's default put_bucket_notification_configuration
+ (botocore wire serializes LambdaFunctionArn as <CloudFunction>) must keep
+ invoking the Lambda on uploads.
+ """
+ fname = "s3-evt-lam-boto3"
+ arn = _create_event_lambda(lam, fname)
+ s3.create_bucket(Bucket="s3-evt-lam-boto3-bkt")
+ s3.put_bucket_notification_configuration(
+ Bucket="s3-evt-lam-boto3-bkt",
+ NotificationConfiguration={
+ "LambdaFunctionConfigurations": [
+ {"LambdaFunctionArn": arn, "Events": ["s3:ObjectCreated:*"]},
+ ],
+ },
+ )
+ s3.put_object(Bucket="s3-evt-lam-boto3-bkt", Key="boto3.txt", Body=b"hi")
+ assert _wait_lambda_invoked(logs, fname, "boto3.txt"), \
+ "Lambda was not invoked for boto3-shaped notification config"
+
+
+def test_s3_event_notification_to_lambda_modern_xml(s3, lam, logs):
+ """Issue #649: AWS SDK for Java v2, Go SDK, Terraform, and hand-crafted XML
+ all send <LambdaFunctionArn> instead of the legacy <CloudFunction> tag.
+ MS used to drop these configs silently — uploads succeeded but the
+ Lambda never fired. Modern shape is now parsed.
+ """
+ import urllib.request as _urlreq
+ fname = "s3-evt-lam-modern"
+ arn = _create_event_lambda(lam, fname)
+ s3.create_bucket(Bucket="s3-evt-lam-modern-bkt")
+
+ modern_xml = (
+ '<?xml version="1.0" encoding="UTF-8"?>'
+ '<NotificationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">'
+ '<LambdaFunctionConfiguration>'
+ '<Id>modern</Id>'
+ f'<LambdaFunctionArn>{arn}</LambdaFunctionArn>'
+ '<Event>s3:ObjectCreated:*</Event>'
+ '</LambdaFunctionConfiguration>'
+ '</NotificationConfiguration>'
+ )
+ req = _urlreq.Request(
+ "http://localhost:4566/s3-evt-lam-modern-bkt?notification",
+ data=modern_xml.encode(),
+ method="PUT",
+ headers={"Content-Type": "application/xml", "Authorization": "AWS test:test"},
+ )
+ _urlreq.urlopen(req)
+
+ s3.put_object(Bucket="s3-evt-lam-modern-bkt", Key="modern.txt", Body=b"hi")
+ assert _wait_lambda_invoked(logs, fname, "modern.txt"), \
+ "Lambda was not invoked for modern <LambdaFunctionArn> XML — regression for #649"
+
+
+def test_s3_event_notification_to_lambda_with_filter(s3, lam, logs):
+ """Modern XML + prefix filter — only matching keys invoke the Lambda."""
+ import urllib.request as _urlreq
+ fname = "s3-evt-lam-filter"
+ arn = _create_event_lambda(lam, fname)
+ s3.create_bucket(Bucket="s3-evt-lam-filter-bkt")
+
+ modern_xml = (
+ '<?xml version="1.0" encoding="UTF-8"?>'
+ '<NotificationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">'
+ '<LambdaFunctionConfiguration>'
+ '<Id>filtered</Id>'
+ f'<LambdaFunctionArn>{arn}</LambdaFunctionArn>'
+ '<Event>s3:ObjectCreated:*</Event>'
+ '<Filter><S3Key><FilterRule><Name>prefix</Name><Value>data/</Value></FilterRule></S3Key></Filter>'
+ '</LambdaFunctionConfiguration>'
+ '</NotificationConfiguration>'
+ )
+ req = _urlreq.Request(
+ "http://localhost:4566/s3-evt-lam-filter-bkt?notification",
+ data=modern_xml.encode(), method="PUT",
+ headers={"Content-Type": "application/xml", "Authorization": "AWS test:test"},
+ )
+ _urlreq.urlopen(req)
+
+ s3.put_object(Bucket="s3-evt-lam-filter-bkt", Key="other/skipme.txt", Body=b"x")
+ s3.put_object(Bucket="s3-evt-lam-filter-bkt", Key="data/match.txt", Body=b"x")
+
+ assert _wait_lambda_invoked(logs, fname, "data/match.txt"), \
+ "Lambda was not invoked for filter-matched key"
+ # The non-matching key must NOT show up in logs. Short additional wait to
+ # be sure no late delivery sneaks through.
+ time.sleep(0.5)
+ saw_skipme = _wait_lambda_invoked(logs, fname, "skipme", timeout=0.1)
+ assert not saw_skipme, "Lambda was invoked for a filter-mismatched key"
+
+
def test_s3_put_notification_no_test_event_for_missing_bucket(s3, sqs):
queue_url = sqs.create_queue(QueueName="s3-test-evt-missing-q")["QueueUrl"]
queue_arn = sqs.get_queue_attributes(
diff --git a/tests/test_sqs.py b/tests/test_sqs.py
index 77b38af9..9e2ca565 100644
--- a/tests/test_sqs.py
+++ b/tests/test_sqs.py
@@ -686,3 +686,146 @@ def test_sqs_remove_permission_drops_matching_statement(sqs):
sids = [s["Sid"] for s in policy["Statement"]]
assert "keep" in sids
assert "drop" not in sids
+
+
+# ---------------------------------------------------------------------------
+# RedrivePolicy validation (issue #644)
+# ---------------------------------------------------------------------------
+
+def _make_dlq(sqs, name="rp-dlq"):
+ url = sqs.create_queue(QueueName=name)["QueueUrl"]
+ arn = sqs.get_queue_attributes(QueueUrl=url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+ return url, arn
+
+
+def test_sqs_create_queue_rejects_double_encoded_redrive_policy(sqs):
+ """Regression for #644: a double-JSON-encoded RedrivePolicy (jq tostring
+ quirk) used to slip through CreateQueue, get stored as `"\\"{...}\\""`,
+ and then crash ReceiveMessage with `'str' object has no attribute 'get'`
+ when `_dlq_sweep` tried to `.get(...)` on the inner string. CreateQueue
+ now rejects this at intake with InvalidAttributeValue, matching AWS.
+ """
+ _, dlq_arn = _make_dlq(sqs, name="rp-double-dlq")
+ # Inner JSON wrapped in an additional pair of quotes — what `jq tostring`
+ # produces if the caller doesn't realize it already serializes to JSON.
+ bad = '"' + json.dumps({"deadLetterTargetArn": dlq_arn, "maxReceiveCount": "2"}).replace('"', '\\"') + '"'
+ with pytest.raises(ClientError) as exc:
+ sqs.create_queue(
+ QueueName="rp-double-src",
+ Attributes={"RedrivePolicy": bad},
+ )
+ assert exc.value.response["Error"]["Code"] == "InvalidAttributeValue"
+ assert "RedrivePolicy" in exc.value.response["Error"]["Message"]
+
+
[email protected]("bad_value,label", [
+ ("not json at all", "non-json"),
+ ("[1, 2, 3]", "json-array"),
+ ('"just a string"', "json-string"),
+ ("42", "json-number"),
+ ('{"maxReceiveCount":"2"}', "missing-arn"),
+ ('{"deadLetterTargetArn":"arn:x"}', "missing-mrc"),
+ ('{"deadLetterTargetArn":"arn:x","maxReceiveCount":"NaN"}', "non-numeric-mrc"),
+ ('{"deadLetterTargetArn":"arn:x","maxReceiveCount":0}', "mrc-too-low"),
+ ('{"deadLetterTargetArn":"arn:x","maxReceiveCount":1001}', "mrc-too-high"),
+ ('{"deadLetterTargetArn":"","maxReceiveCount":2}', "empty-arn"),
+])
+def test_sqs_create_queue_redrive_policy_invalid_shape(sqs, bad_value, label):
+ """All malformed RedrivePolicy shapes return InvalidAttributeValue (400),
+ not InternalError (500) — covering every branch of the validator.
+ """
+ with pytest.raises(ClientError) as exc:
+ sqs.create_queue(
+ QueueName=f"rp-bad-{label}",
+ Attributes={"RedrivePolicy": bad_value},
+ )
+ assert exc.value.response["Error"]["Code"] == "InvalidAttributeValue", f"label={label}"
+
+
+def test_sqs_create_queue_redrive_policy_accepts_int_max_receive_count(sqs):
+ """maxReceiveCount as a JSON integer (not string) is accepted — AWS allows
+ both, and the existing test in this file already uses the string form.
+ """
+ _, dlq_arn = _make_dlq(sqs, name="rp-int-dlq")
+ sqs.create_queue(
+ QueueName="rp-int-src",
+ Attributes={"RedrivePolicy": json.dumps(
+ {"deadLetterTargetArn": dlq_arn, "maxReceiveCount": 5}
+ )},
+ )
+
+
+def test_sqs_set_queue_attributes_validates_redrive_policy(sqs):
+ """SetQueueAttributes runs the same validator — otherwise CreateQueue
+ rejects the bad value but SetQueueAttributes would let it through and
+ crash later receives, defeating the gate.
+ """
+ _, dlq_arn = _make_dlq(sqs, name="rp-setattr-dlq")
+ src_url = sqs.create_queue(QueueName="rp-setattr-src")["QueueUrl"]
+ bad = '"' + json.dumps({"deadLetterTargetArn": dlq_arn, "maxReceiveCount": "2"}).replace('"', '\\"') + '"'
+ with pytest.raises(ClientError) as exc:
+ sqs.set_queue_attributes(QueueUrl=src_url, Attributes={"RedrivePolicy": bad})
+ assert exc.value.response["Error"]["Code"] == "InvalidAttributeValue"
+
+
+def test_sqs_fifo_receive_with_redrive_policy_does_not_500(sqs):
+ """The original symptom from #644: ReceiveMessage on a FIFO queue with a
+ valid RedrivePolicy attached must not crash with InternalError.
+ """
+ _, dlq_arn = _make_dlq(sqs, name="rp-fifo-recv-dlq.fifo") # name irrelevant
+ # Actually make a FIFO DLQ for parity with the issue's repro.
+ dlq_url = sqs.create_queue(
+ QueueName="rp-fifo-dlq.fifo",
+ Attributes={"FifoQueue": "true", "ContentBasedDeduplication": "false"},
+ )["QueueUrl"]
+ fifo_dlq_arn = sqs.get_queue_attributes(
+ QueueUrl=dlq_url, AttributeNames=["QueueArn"]
+ )["Attributes"]["QueueArn"]
+ src_url = sqs.create_queue(
+ QueueName="rp-fifo-src.fifo",
+ Attributes={
+ "FifoQueue": "true",
+ "ContentBasedDeduplication": "false",
+ "VisibilityTimeout": "5",
+ "RedrivePolicy": json.dumps(
+ {"deadLetterTargetArn": fifo_dlq_arn, "maxReceiveCount": "2"}
+ ),
+ },
+ )["QueueUrl"]
+
+ # Empty-queue receive must not 500.
+ r = sqs.receive_message(QueueUrl=src_url, MaxNumberOfMessages=1, WaitTimeSeconds=1)
+ assert "Messages" not in r or r["Messages"] == []
+
+ # After a SendMessage, the message must come back via ReceiveMessage.
+ sqs.send_message(
+ QueueUrl=src_url,
+ MessageBody="hello",
+ MessageGroupId="g1",
+ MessageDeduplicationId="d-1",
+ )
+ r = sqs.receive_message(QueueUrl=src_url, MaxNumberOfMessages=1, WaitTimeSeconds=2)
+ assert len(r["Messages"]) == 1
+ assert r["Messages"][0]["Body"] == "hello"
+
+
+def test_sqs_dlq_sweep_survives_legacy_double_encoded_policy():
+ """Defence-in-depth unit test: if a legacy queue carried a double-encoded
+ RedrivePolicy from a pre-fix MS version (persistence-load can't be
+ rejected the way an API call is), `_dlq_sweep` must skip rather than
+ crash. Called directly here — boto3 over HTTP would talk to a separately
+ process with its own `_queues` instance, so we can't inject the bad state
+ that way.
+ """
+ from ministack.services.sqs import _dlq_sweep
+
+ bad_rp = '"' + json.dumps(
+ {"deadLetterTargetArn": "arn:x", "maxReceiveCount": "2"}
+ ).replace('"', '\\"') + '"'
+ fake_q = {
+ "messages": [],
+ "attributes": {"RedrivePolicy": bad_rp},
+ }
+ # Pre-fix this raised: AttributeError: 'str' object has no attribute 'get'
+ _dlq_sweep(fake_q)
+ assert fake_q["messages"] == [] # nothing to sweep, no crash
diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.py
index 8e29949a..0f860b44 100644
--- a/tests/test_stepfunctions.py
+++ b/tests/test_stepfunctions.py
@@ -4139,3 +4139,191 @@ def test_sfn_map_iterations_proceed_under_non_default_account_id():
assert out == [1, 2, 3, 4, 5], f"Map items dropped silently: {out}"
finally:
sfn.delete_state_machine(stateMachineArn=sm)
+
+
+# ---------------------------------------------------------------------------
+# JSONata variable assignment (`Assign` field + `$variable` refs) — issue #645
+# ---------------------------------------------------------------------------
+
+def test_sfn_jsonata_assign_pass_then_choice_references_variable(sfn, sfn_sync):
+ """Regression for #645: exact issue repro. A Pass state's `Assign` binds
+ a variable from `$states.result`; a downstream Choice's `Condition`
+ references it via `$myList`. Before the fix the evaluator raised
+ `States.QueryEvaluationError: Unsupported JSONata expression: $myList`.
+ """
+ import uuid as _uuid_local
+ sm_name = f"jsonata-assign-{_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": "SetVars",
+ "States": {
+ "SetVars": {
+ "Type": "Pass",
+ "Output": {"items": ["a", "b"]},
+ "Assign": {"myList": "{% $states.result.items %}"},
+ "Next": "CheckList",
+ },
+ "CheckList": {
+ "Type": "Choice",
+ "Choices": [{
+ "Next": "HasItems",
+ "Condition": "{% $count($myList) > 0 %}",
+ }],
+ "Default": "Empty",
+ },
+ "HasItems": {"Type": "Succeed"},
+ "Empty": {"Type": "Succeed"},
+ },
+ }),
+ )["stateMachineArn"]
+ try:
+ resp = sfn_sync.start_sync_execution(stateMachineArn=sm_arn, input="{}")
+ assert resp["status"] == "SUCCEEDED", f"Status: {resp.get('status')} cause={resp.get('cause')}"
+ # `Empty` is the fallback — if the variable lookup or $count failed,
+ # we'd land there instead of `HasItems`.
+ events = sfn.get_execution_history(executionArn=resp["executionArn"])["events"]
+ entered = [e["stateEnteredEventDetails"]["name"]
+ for e in events if "stateEnteredEventDetails" in e]
+ assert "HasItems" in entered, f"Expected HasItems; entered={entered}"
+ assert "Empty" not in entered
+ finally:
+ sfn_sync.delete_state_machine(stateMachineArn=sm_arn)
+
+
+def test_sfn_jsonata_assign_variable_survives_across_states(sfn_sync):
+ """Variables set on one state must be visible on every subsequent state
+ (execution-scoped, not state-scoped)."""
+ import uuid as _uuid_local
+ sm_name = f"jsonata-assign-chain-{_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": "A",
+ "States": {
+ "A": {
+ "Type": "Pass",
+ "Assign": {"x": 41},
+ "Next": "B",
+ },
+ "B": {
+ "Type": "Pass",
+ "Assign": {"y": "{% $x + 1 %}"},
+ "Next": "C",
+ },
+ "C": {
+ "Type": "Pass",
+ "Output": "{% $y %}",
+ "End": True,
+ },
+ },
+ }),
+ )["stateMachineArn"]
+ try:
+ resp = sfn_sync.start_sync_execution(stateMachineArn=sm_arn, input="{}")
+ assert resp["status"] == "SUCCEEDED"
+ assert json.loads(resp["output"]) == 42
+ finally:
+ sfn_sync.delete_state_machine(stateMachineArn=sm_arn)
+
+
+def test_sfn_jsonata_assign_dotted_variable_path(sfn_sync):
+ """`$user.email` resolves the `email` key inside the assigned `$user` dict."""
+ import uuid as _uuid_local
+ sm_name = f"jsonata-assign-dotted-{_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": "Bind",
+ "States": {
+ "Bind": {
+ "Type": "Pass",
+ "Assign": {"user": {"email": "[email protected]", "id": 7}},
+ "Next": "Use",
+ },
+ "Use": {
+ "Type": "Pass",
+ "Output": "{% $user.email %}",
+ "End": True,
+ },
+ },
+ }),
+ )["stateMachineArn"]
+ try:
+ resp = sfn_sync.start_sync_execution(stateMachineArn=sm_arn, input="{}")
+ assert resp["status"] == "SUCCEEDED"
+ assert json.loads(resp["output"]) == "[email protected]"
+ finally:
+ sfn_sync.delete_state_machine(stateMachineArn=sm_arn)
+
+
+def test_sfn_jsonata_undefined_variable_raises_query_eval_error(sfn_sync):
+ """Referencing an unbound `$var` must surface as `States.QueryEvaluationError`
+ (the documented AWS error code for JSONata evaluation failures), not as a
+ generic Runtime error or silent fallthrough.
+ """
+ import uuid as _uuid_local
+ sm_name = f"jsonata-undef-{_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": "Use",
+ "States": {
+ "Use": {
+ "Type": "Pass",
+ "Output": "{% $never_set %}",
+ "End": True,
+ },
+ },
+ }),
+ )["stateMachineArn"]
+ try:
+ resp = sfn_sync.start_sync_execution(stateMachineArn=sm_arn, input="{}")
+ assert resp["status"] == "FAILED"
+ assert resp.get("error") == "States.QueryEvaluationError"
+ finally:
+ sfn_sync.delete_state_machine(stateMachineArn=sm_arn)
+
+
+def test_sfn_jsonata_assign_reuses_input(sfn_sync):
+ """`Assign` can reference `$states.input` (always available)."""
+ import uuid as _uuid_local
+ sm_name = f"jsonata-input-{_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": "Bind",
+ "States": {
+ "Bind": {
+ "Type": "Pass",
+ "Assign": {"name": "{% $states.input.who %}"},
+ "Next": "Out",
+ },
+ "Out": {
+ "Type": "Pass",
+ "Output": "{% 'hello ' & $name %}",
+ "End": True,
+ },
+ },
+ }),
+ )["stateMachineArn"]
+ try:
+ resp = sfn_sync.start_sync_execution(
+ stateMachineArn=sm_arn,
+ input=json.dumps({"who": "world"}),
+ )
+ assert resp["status"] == "SUCCEEDED"
+ assert json.loads(resp["output"]) == "hello world"
+ finally:
+ sfn_sync.delete_state_machine(stateMachineArn=sm_arn)
+