Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
release/v1.3.44 (#672)
Nahuel Nucera92deb11b6591
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 266216e0..4e36feb7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,19 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [1.3.44] — 2026-05-19++### Added+- **Standard AWS ECS Docker labels on `RunTask` containers** — every container MiniStack spawns for an ECS task now carries the five canonical `com.amazonaws.ecs.*` labels real ECS sets (cluster ARN, container-name, task-arn, task-definition-family, task-definition-version), matching the keys and values documented in the AWS ECS container metadata file spec. Lets host-side log shippers, monitoring agents, and `docker ps --filter "label=…"` queries identify containers the same way they would against real ECS. Contributed by @YakirOren.+- **Step Functions JSONata standard library expanded** — the JSONata evaluator now ships every built-in function called out in the ticket, plus the parity-edge cases AWS/JSONata require: string (`$uppercase`, `$lowercase`, `$substring`, `$trim`, `$contains`, `$split`, `$join`, `$replace`, `$pad`), numeric (`$sum`, `$average`, `$max`, `$min`, `$abs`, `$floor`, `$ceil`, `$round`, `$power`, `$sqrt`, `$formatNumber`), array (`$sort` — including the `function($l, $r){...}` comparator form — `$reverse`, `$distinct`, `$append`), object (`$keys`, `$values`, `$lookup` over both objects and arrays-of-objects, `$exists` distinguishing missing paths from explicit `null` per JSONata spec), type (`$type`, `$boolean` — falsy for arrays of only-falsy values), date/time (`$now()` / `$now(picture)` / `$now(picture, timezone)` with the XPath-3.1 picture-string subset, `$millis`), and utility (`$uuid`, `$base64encode`, `$base64decode`). `$contains`, `$split`, and `$replace` accept JSONata regex literals (`/pattern/flags`), with `$1`/`$&` substitution refs supported in `$replace`. The headline ticket example `"Condition": "{% $exists($states.input.userId) %}"` now routes correctly whether the field is present, explicitly `null`, or missing. Implemented natively in Python with no new runtime dependency. Reported by @youngkwangk.++### Fixed+- **RDS Data API no longer acknowledges writes through the SQL stub for real containers that are still booting** — when a Docker-backed RDS instance is configured but its container is still bootstrapping, `ExecuteStatement` / `BatchExecuteStatement` previously fell back to the in-memory SQL stub on any connection error and returned a 200 acknowledging `CREATE USER` / `GRANT` statements that never reached MySQL. The fallback now only applies to control-plane-only clusters (no real container). Container-backed clusters whose endpoint can't be reached surface `DatabaseUnavailableException` (HTTP 504, the canonical AWS error code), so callers see the same transient-error shape they'd see against real RDS. Real SQL errors (lock-wait timeout, etc.) still surface as `BadRequestException`, not transient-unavailable. Contributed by @jayjanssen.+- **`CreateDBInstance` returns immediately with `DBInstanceStatus="creating"` for Docker-backed instances**, matching real AWS — readiness finalisation runs on a daemon thread and transitions the instance to `available` or `failed` based on container liveness. Previously the call blocked inline for up to 60s. Image-side password mismatches (auth-denied during the readiness probe) log at WARNING with a remediation hint.+- **RDS Aurora MySQL local endpoint and master-user parity** — Aurora cluster endpoints now track the reachable backing DB instance endpoint after cluster members are created, so Lambda containers using `DescribeDBClusters.Endpoint` can connect to MiniStack-backed databases. MySQL and Aurora MySQL containers also grant the configured master username AWS/RDS-like global privileges after the server is reachable, with version-specific dynamic privileges treated as best-effort. Contributed by @jayjanssen.++---+## [1.3.43] — 2026-05-18### Added@@ -33,10 +46,6 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Changed- **Test harness — xdist session-startup reset coordination** — the per-worker `autouse` `reset_server` fixture previously had every xdist worker hit `/_ministack/reset` on session start, so a slower worker's reset could fire after a faster worker had already begun creating fixtures, wiping that state mid-test (most visibly as occasional `list_functions()` empty results in `test_lambda_create_invoke`). The first worker now wins an `O_EXCL` file lock and runs the reset; the others wait briefly for a marker file and skip. Single-process pytest (no xdist) keeps the original behaviour. Removes a class of CI flakes that only reproduced under parallel load.-### Fixed-- **RDS Data API no longer acknowledges writes through the SQL stub for real containers that are still booting** — Docker-backed RDS instances now wait for an authenticated database connection before reporting `available`, and their parent clusters remain `creating` while member instances are not ready. If an endpoint-backed container still cannot be reached, RDS Data API returns `DatabaseUnavailableException` instead of silently tracking `CREATE USER` / `GRANT` statements in memory. Stub SQL mode remains available for control-plane-only clusters without a real backing container. Contributed by @jayjanssen.-- **RDS Aurora MySQL local endpoint and master-user parity** — Aurora cluster endpoints now track the reachable backing DB instance endpoint after cluster members are created, so Lambda containers using `DescribeDBClusters.Endpoint` can connect to MiniStack-backed databases. MySQL and Aurora MySQL containers also grant the configured master username AWS/RDS-like global privileges after the server is reachable, with version-specific dynamic privileges treated as best-effort. Contributed by @jayjanssen.----## [1.3.41] — 2026-05-16diff --git a/ministack/services/rds.py b/ministack/services/rds.pyindex 41561bd9..17c3ae30 100644--- a/ministack/services/rds.py+++ b/ministack/services/rds.py@@ -32,6 +32,7 @@ parameters.import copyimport datetime+import contextvarsimport jsonimport loggingimport os@@ -221,47 +222,80 @@ def _grant_mysql_master_user_privileges(host, port, master_user, master_pass, dbdb_id, e)-def _wait_for_database_ready(host, port, engine, user, password, db_name, timeout=60):- """Block until the database accepts an authenticated connection.+def _try_database_connect(host, port, engine, user, password, db_name):+ """Single auth-probe attempt. Returns True on success, False on a+ transient failure. TCP readiness alone is not enough for MySQL/Postgres+ images — they accept sockets before bootstrap creates users/databases —+ so we open and close an authenticated connection. When the DB driver+ isn't installed (lightweight image) we fall back to a one-shot TCP check.+ """+ try:+ if _is_mysql_engine(engine):+ try:+ import pymysql+ except ImportError:+ return _wait_for_port(host, port, timeout=1)+ conn = pymysql.connect(+ host=host, port=int(port), user="root",+ password=password, database=db_name or None,+ connect_timeout=2, read_timeout=2, write_timeout=2,+ autocommit=True)+ elif _is_postgres_engine(engine):+ try:+ import psycopg2+ except ImportError:+ return _wait_for_port(host, port, timeout=1)+ conn = psycopg2.connect(+ host=host, port=int(port), user=user,+ password=password, dbname=db_name or "postgres",+ connect_timeout=2)+ else:+ return _wait_for_port(host, port, timeout=1)+ conn.close()+ return True+ except Exception as e:+ # Distinguish *permanent* auth failures from transient boot-time errors.+ # A transient failure (server still starting, socket refused, etc.) is+ # expected during the readiness loop. A permanent auth failure means+ # the container's image is configured with a different password than+ # the one ministack handed it — the loop would spin forever and the+ # user would see nothing. Surface that case at WARNING level with a+ # concrete hint so it shows up in ministack logs.+ msg = str(e)+ is_auth_denied = (+ # pymysql: OperationalError with MySQL error code 1045+ (getattr(e, "args", None) and isinstance(e.args[0], int) and e.args[0] == 1045)+ # psycopg2 and generic driver messages+ or "password authentication failed" in msg.lower()+ or "access denied for user" in msg.lower()+ )+ if is_auth_denied:+ logger.warning(+ "RDS: authentication denied probing %s:%s — the container's "+ "image is configured with a different password than ministack "+ "passed at start-up. The instance will stay in `creating` until "+ "the container exits. Driver error: %s",+ host, port, msg,+ )+ else:+ logger.debug("RDS: readiness probe transient failure: %s", e)+ return False+- TCP readiness is not enough for MySQL/Postgres images: they can accept a- socket before bootstrap has created users and databases. When a DB driver is- unavailable in the lightweight install, fall back to TCP readiness so RDS- control-plane behavior remains usable without optional dependencies.+def _wait_for_database_ready(host, port, engine, user, password, db_name,+ is_container_alive):+ """Poll until the database accepts an authenticated connection. No wall+ clock — real AWS `CreateDBInstance` has no caller-visible timeout, so+ neither do we. The loop terminates on success or when the backing+ container stops being alive (mirrors how real RDS flips an instance to+ `failed` based on hardware state, not a fixed deadline)."""- deadline = time.time() + timeout- last_error = None- while time.time() < deadline:- try:- if _is_mysql_engine(engine):- try:- import pymysql- except ImportError:- return _wait_for_port(host, port, timeout=max(1, deadline - time.time()))- conn = pymysql.connect(- host=host, port=int(port), user="root",- password=password, database=db_name or None,- connect_timeout=2, read_timeout=2, write_timeout=2,- autocommit=True)- elif _is_postgres_engine(engine):- try:- import psycopg2- except ImportError:- return _wait_for_port(host, port, timeout=max(1, deadline - time.time()))- conn = psycopg2.connect(- host=host, port=int(port), user=user,- password=password, dbname=db_name or "postgres",- connect_timeout=2)- else:- return _wait_for_port(host, port, timeout=max(1, deadline - time.time()))- conn.close()+ while True:+ if not is_container_alive():+ return False+ if _try_database_connect(host, port, engine, user, password, db_name):return True- except Exception as e:- last_error = e- time.sleep(0.5)- if last_error:- logger.debug("RDS: database readiness check failed: %s", last_error)- return False+ time.sleep(0.5)def _refresh_cluster_status(cluster_id):@@ -654,14 +688,63 @@ def _create_db_instance(p):_register_instance_in_cluster(instance)if real_container_started:+ # Real AWS CreateDBInstance returns immediately with status="creating"+ # and the caller polls (or uses get_waiter('db_instance_available'))+ # until the database becomes reachable. Do the same: run the readiness+ # wait + grant on a daemon thread so the request handler returns now.+ #+ # contextvars.copy_context() carries the request's account_id into+ # the daemon — _instances is account-scoped, so without the snapshot+ # the worker would look the instance up under the default account+ # and silently fail to flip status to "available".ready_host = readiness_host or endpoint_hostready_port = readiness_port or endpoint_port- if _wait_for_database_ready(- ready_host, ready_port, engine, master_user, master_pass, db_name):+ ctx = contextvars.copy_context()++ def _bg_finalize_ready(+ db_id=db_id, cluster_id=cluster_id, engine=engine,+ master_user=master_user, master_pass=master_pass,+ db_name=db_name, ready_host=ready_host, ready_port=ready_port,+ ms_network=ms_network, internal_host=internal_host,+ internal_port=internal_port, endpoint_port=endpoint_port,+ container_id=docker_container_id,+ ):+ # Tie readiness to backing-container liveness rather than a wall+ # clock: real RDS `CreateDBInstance` has no caller-visible timeout+ # and flips status to `failed` based on hardware state. We do the+ # same — instance stays `creating` while the container is up and+ # booting, transitions to `failed` if the container dies before+ # accepting an authenticated connection.+ def _container_alive():+ client = _get_docker()+ if not client or not container_id:+ return True # control-plane-only — nothing to monitor+ try:+ c = client.containers.get(container_id)+ c.reload()+ return c.status not in ("exited", "dead", "removing")+ except Exception:+ return False+ if not _wait_for_database_ready(+ ready_host, ready_port, engine, master_user,+ master_pass, db_name, _container_alive,+ ):+ logger.warning(+ "RDS: %s container for %s at %s:%s exited before becoming reachable",+ engine, db_id, ready_host, ready_port,+ )+ inst = _instances.get(db_id)+ if inst is not None:+ inst["DBInstanceStatus"] = "failed"+ _refresh_cluster_status(cluster_id)+ returnif _is_mysql_engine(engine):_grant_mysql_master_user_privileges(- ready_host, ready_port, master_user, master_pass, db_id)- instance["DBInstanceStatus"] = "available"+ ready_host, ready_port, master_user, master_pass, db_id,+ )+ inst = _instances.get(db_id)+ if inst is not None:+ inst["DBInstanceStatus"] = "available"if cluster_id:cluster = _clusters.get(cluster_id)if cluster:@@ -670,15 +753,17 @@ def _create_db_instance(p):if ms_network and internal_host:logger.info("RDS: %s container for %s ready at %s:%s (network %s)",- engine, db_id, internal_host, internal_port, ms_network)+ engine, db_id, internal_host, internal_port, ms_network,+ )else:logger.info("RDS: %s container for %s ready on port %s",- engine, db_id, endpoint_port)- else:- logger.warning(- "RDS: %s container for %s at %s:%s not ready after timeout",- engine, db_id, ready_host, ready_port)+ engine, db_id, endpoint_port,+ )++ threading.Thread(+ target=ctx.run, args=(_bg_finalize_ready,), daemon=True,+ ).start()req_tags = _parse_tags(p)if req_tags:diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.pyindex c220f073..a9a65fe0 100644--- a/ministack/services/stepfunctions.py+++ b/ministack/services/stepfunctions.py@@ -2094,6 +2094,20 @@ def _eval_jsonata_expr(expr, states):if not expr:raise ValueError("Empty JSONata expression")+ # 0a. Regex literal `/pattern/flags` — short-circuit before the+ # multiplicative-`/`-split would mis-tokenize it.+ if expr.startswith("/"):+ rx = _try_parse_regex_literal(expr)+ if rx is not None:+ return rx++ # 0b. Function literal `function(...) {...}` — short-circuit so the body+ # isn't sliced by operator splitters.+ if expr.startswith("function"):+ fn = _try_parse_function_literal(expr, states)+ if fn is not None:+ return fn+# 1. Ternary (right-associative — peel outermost `?`)q_pos = _find_top_level_token(expr, "?")if q_pos >= 0:@@ -2169,21 +2183,25 @@ def _eval_jsonata_primary(expr, states):if expr.startswith("(") and expr.endswith(")") and _is_balanced_outer(expr, "(", ")"):return _eval_jsonata_expr(expr[1:-1], states)- # Built-in functions (AWS-supported JSONata subset)- for name, fn in (- ("$merge", _jsonata_merge),- ("$count", _jsonata_count),- ("$length", _jsonata_length),- ("$not", _jsonata_not),- ("$string", _jsonata_string),- ("$number", _jsonata_number),- ):- prefix = name + "("- if expr.startswith(prefix) and expr.endswith(")") \- and _is_balanced_outer(expr[len(name):], "(", ")"):- arg_expr = expr[len(prefix):-1].strip()- arg = _eval_jsonata_expr(arg_expr, states) if arg_expr else None- return fn(arg)+ # Built-in JSONata function call: ``$name(arg1, arg2, ...)``. Dispatch by+ # name to the registry; ``$exists`` is special-cased because it must catch+ # resolution errors raised by evaluating its argument.+ fn_match = re.match(r"^\$([A-Za-z_][A-Za-z0-9_]*)\(", expr)+ if fn_match and expr.endswith(")") and _is_balanced_outer(+ expr[len(fn_match.group(0)) - 1:], "(", ")"):+ name = "$" + fn_match.group(1)+ args_body = expr[len(fn_match.group(0)):-1].strip()+ if name == "$exists":+ # `$exists(expr)` distinguishes "missing path" (false) from+ # "explicit null value" (true) per JSONata spec — see+ # `_exists_jsonata_expr` for the walk.+ if not args_body:+ return False+ return _exists_jsonata_expr(args_body, states)+ if name in _JSONATA_FUNCS:+ arg_exprs = _split_top_level(args_body, ",") if args_body else []+ args = [_eval_jsonata_expr(a, states) for a in arg_exprs]+ return _JSONATA_FUNCS[name](*args)# Array literalif expr.startswith("[") and expr.endswith("]") and _is_balanced_outer(expr, "[", "]"):@@ -2240,18 +2258,130 @@ def _eval_jsonata_primary(expr, states):def _truthy(value):- """JSONata truthiness: null/false/0/empty string/empty array/empty object are falsy."""+ """JSONata truthiness: null/false/0/empty string/empty array/empty object are falsy.+ For arrays, an array containing only falsy values is itself falsy (JSONata spec)."""if value is None or value is False:return Falseif isinstance(value, bool):return valueif isinstance(value, (int, float)) and value == 0:return False- if isinstance(value, (str, list, dict)) and len(value) == 0:+ if isinstance(value, str) and len(value) == 0:+ return False+ if isinstance(value, dict) and len(value) == 0:return False+ if isinstance(value, list):+ if len(value) == 0:+ return False+ return any(_truthy(v) for v in value)return True+# Sentinel returned by `_resolve_jsonata_path_with_missing` to mark a path that+# did not match. Distinguished from an explicit JSON `null`, which $exists+# treats as "exists" per JSONata spec.+class _Missing:+ _singleton = None++ def __repr__(self):+ return "<missing>"+++_MISSING = _Missing()+_Missing._singleton = _MISSING+++class _JsonataFunctionLiteral:+ """A `function($a, $b){<body>}` literal compiled into a callable that can+ be passed to higher-order functions like `$sort`."""++ def __init__(self, params, body, states):+ self.params = params # list of str, each like "$a"+ self.body = body+ self.outer_states = states++ def __call__(self, *args):+ if len(args) != len(self.params):+ raise ValueError(+ f"function expected {len(self.params)} args, got {len(args)}")+ # Build a child states with the params bound as variables. `$name`+ # variable lookups go through `states["_variables"]`.+ child = dict(self.outer_states)+ variables = dict(child.get("_variables", {}))+ for pname, pvalue in zip(self.params, args):+ # Strip leading `$` to match the variable-store convention.+ variables[pname[1:]] = pvalue+ child["_variables"] = variables+ return _eval_jsonata_expr(self.body, child)+++def _try_parse_regex_literal(expr):+ """Recognize a JSONata regex literal `/pattern/flags`. Returns a compiled+ `re.Pattern` or `None` if `expr` is not a regex literal."""+ if not expr.startswith("/") or len(expr) < 2:+ return None+ # Walk to find the closing `/`, skipping `\/` escapes.+ i = 1+ while i < len(expr):+ ch = expr[i]+ if ch == "\\" and i + 1 < len(expr):+ i += 2+ continue+ if ch == "/":+ break+ i += 1+ if i >= len(expr) or expr[i] != "/":+ return None+ pattern = expr[1:i]+ flags_str = expr[i + 1:]+ if flags_str and not re.fullmatch(r"[imsxu]*", flags_str):+ return None+ flags = 0+ for f in flags_str:+ flags |= {"i": re.IGNORECASE, "m": re.MULTILINE, "s": re.DOTALL,+ "x": re.VERBOSE, "u": re.UNICODE}[f]+ try:+ return re.compile(pattern, flags)+ except re.error:+ return None+++def _try_parse_function_literal(expr, states):+ """Recognize `function($a, $b, ...) { <body> }` and return a+ `_JsonataFunctionLiteral`, or `None`."""+ m = re.match(r"^function\s*\(", expr)+ if not m:+ return None+ # Find matching close paren for params.+ depth = 0+ paren_close = -1+ for idx, ch in enumerate(expr[m.end() - 1:], start=m.end() - 1):+ if ch == "(":+ depth += 1+ elif ch == ")":+ depth -= 1+ if depth == 0:+ paren_close = idx+ break+ if paren_close < 0:+ return None+ params_body = expr[m.end():paren_close].strip()+ rest = expr[paren_close + 1:].lstrip()+ if not rest.startswith("{") or not rest.endswith("}"):+ return None+ body = rest[1:-1].strip()+ if not _is_balanced_outer(rest, "{", "}"):+ return None+ if not params_body:+ params = []+ else:+ params = [p.strip() for p in _split_top_level(params_body, ",")]+ for p in params:+ if not re.fullmatch(r"\$[A-Za-z_][A-Za-z0-9_]*", p):+ return None+ return _JsonataFunctionLiteral(params, body, states)++def _apply_binary_op(op, left, right):try:if op == "=":@@ -2287,17 +2417,34 @@ def _apply_binary_op(op, left, right):raise ValueError(f"Unknown operator: {op}")-def _jsonata_merge(args):- if not isinstance(args, list):- raise ValueError("$merge expects an array")+# ---------------------------------------------------------------------------+# JSONata built-in functions+# ---------------------------------------------------------------------------+#+# AWS Step Functions exposes a subset of the JSONata standard library. The+# dispatcher in `_eval_jsonata_primary` resolves `$name(args)` against the+# `_JSONATA_FUNCS` registry below. Each handler takes the already-evaluated+# positional arguments. Type validation raises `ValueError`, which the+# caller wraps into `States.QueryEvaluationError`.+#+# `$exists` is special-cased in the dispatcher because it must intercept+# resolution errors on its argument; the rest go through this table.+++def _jsonata_merge(*args):+ if len(args) != 1 or not isinstance(args[0], list):+ raise ValueError("$merge expects a single array argument")merged = {}- for item in args:+ for item in args[0]:if isinstance(item, dict):merged.update(item)return merged-def _jsonata_count(arg):+def _jsonata_count(*args):+ if len(args) != 1:+ raise ValueError("$count expects 1 argument")+ arg = args[0]if arg is None:return 0if isinstance(arg, list):@@ -2305,17 +2452,22 @@ def _jsonata_count(arg):return 1-def _jsonata_length(arg):- if not isinstance(arg, str):+def _jsonata_length(*args):+ if len(args) != 1 or not isinstance(args[0], str):raise ValueError("$length expects a string")- return len(arg)+ return len(args[0])-def _jsonata_not(arg):- return not _truthy(arg)+def _jsonata_not(*args):+ if len(args) != 1:+ raise ValueError("$not expects 1 argument")+ return not _truthy(args[0])-def _jsonata_string(arg):+def _jsonata_string(*args):+ if len(args) != 1:+ raise ValueError("$string expects 1 argument")+ arg = args[0]if arg is None:return ""if isinstance(arg, bool):@@ -2325,7 +2477,10 @@ def _jsonata_string(arg):return str(arg)-def _jsonata_number(arg):+def _jsonata_number(*args):+ if len(args) != 1:+ raise ValueError("$number expects 1 argument")+ arg = args[0]if isinstance(arg, bool):raise ValueError("$number cannot coerce boolean")if isinstance(arg, (int, float)):@@ -2338,6 +2493,661 @@ def _jsonata_number(arg):raise ValueError(f"$number cannot coerce {type(arg).__name__}")+# --- String functions ------------------------------------------------------+++def _require_str(name, value):+ if not isinstance(value, str):+ raise ValueError(f"{name} expects a string")+ return value+++def _jsonata_uppercase(*args):+ if len(args) != 1:+ raise ValueError("$uppercase expects 1 argument")+ return _require_str("$uppercase", args[0]).upper()+++def _jsonata_lowercase(*args):+ if len(args) != 1:+ raise ValueError("$lowercase expects 1 argument")+ return _require_str("$lowercase", args[0]).lower()+++def _jsonata_substring(*args):+ # $substring(str, start) or $substring(str, start, length)+ if len(args) not in (2, 3):+ raise ValueError("$substring expects 2 or 3 arguments")+ s = _require_str("$substring", args[0])+ start = int(args[1])+ # JSONata: negative start counts from end+ if start < 0:+ start = max(len(s) + start, 0)+ if len(args) == 2:+ return s[start:]+ length = int(args[2])+ if length < 0:+ length = 0+ return s[start:start + length]+++def _jsonata_trim(*args):+ # JSONata $trim: strip and collapse internal whitespace runs to a single space.+ if len(args) != 1:+ raise ValueError("$trim expects 1 argument")+ return re.sub(r"\s+", " ", _require_str("$trim", args[0])).strip()+++def _jsonata_contains(*args):+ # JSONata $contains(str, pattern) — pattern may be a string OR a regex.+ if len(args) != 2:+ raise ValueError("$contains expects 2 arguments")+ s = _require_str("$contains", args[0])+ pat = args[1]+ if isinstance(pat, re.Pattern):+ return pat.search(s) is not None+ return _require_str("$contains", pat) in s+++def _jsonata_split(*args):+ # JSONata $split(str, separator, limit) — separator may be a string OR a regex.+ if len(args) not in (2, 3):+ raise ValueError("$split expects 2 or 3 arguments")+ s = _require_str("$split", args[0])+ sep = args[1]+ limit = None+ if len(args) == 3:+ limit = int(args[2])+ if limit < 0:+ raise ValueError("$split limit must be non-negative")+ if isinstance(sep, re.Pattern):+ parts = sep.split(s)+ else:+ sep_str = _require_str("$split", sep)+ parts = s.split(sep_str) if sep_str else list(s)+ return parts[:limit] if limit is not None else parts+++def _jsonata_join(*args):+ # JSONata $join(array_of_strings, separator). Per spec, array values must+ # all be strings — otherwise raise. Single string is treated as a 1-element+ # array (consistent with JSONata's "singleton sequence" semantics).+ if len(args) not in (1, 2):+ raise ValueError("$join expects 1 or 2 arguments")+ arr = args[0]+ if isinstance(arr, str):+ arr = [arr]+ if not isinstance(arr, list):+ raise ValueError("$join expects an array of strings")+ for v in arr:+ if not isinstance(v, str):+ raise ValueError("$join: array elements must all be strings")+ sep = _require_str("$join", args[1]) if len(args) == 2 else ""+ return sep.join(arr)+++def _jsonata_replace(*args):+ # JSONata $replace(str, pattern, replacement, limit) — pattern may be a+ # string OR a regex. With regex, `replacement` honours `$1`/`$&` etc. per+ # the spec; we map those to Python's `\1`/`\g<0>` equivalents.+ if len(args) not in (3, 4):+ raise ValueError("$replace expects 3 or 4 arguments")+ s = _require_str("$replace", args[0])+ pattern = args[1]+ replacement = _require_str("$replace", args[2])+ limit = None+ if len(args) == 4:+ limit = int(args[3])+ if limit < 0:+ raise ValueError("$replace limit must be non-negative")+ if isinstance(pattern, re.Pattern):+ # Translate JSONata/JS substitution refs into Python's: `$&` → \g<0>,+ # `$1`..`$9` → \1..\9, literal `$` written as `$$` → `$`.+ def _translate(repl):+ return re.sub(+ r"\$(\$|&|[1-9])",+ lambda m: {"$": "$", "&": r"\g<0>"}.get(+ m.group(1), r"\%s" % m.group(1)),+ repl,+ )+ py_repl = _translate(replacement)+ return pattern.sub(py_repl, s, count=limit if limit is not None else 0)+ pattern_str = _require_str("$replace", pattern)+ if limit is not None:+ return s.replace(pattern_str, replacement, limit)+ return s.replace(pattern_str, replacement)+++def _jsonata_pad(*args):+ # $pad(str, width) — negative width left-pads, positive right-pads.+ # $pad(str, width, char) — single-char fill.+ if len(args) not in (2, 3):+ raise ValueError("$pad expects 2 or 3 arguments")+ s = _require_str("$pad", args[0])+ width = int(args[1])+ fill = _require_str("$pad", args[2]) if len(args) == 3 else " "+ if not fill:+ return s+ fill_char = fill[0]+ if width >= 0:+ return s.ljust(width, fill_char)+ return s.rjust(-width, fill_char)+++# --- Numeric functions ----------------------------------------------------+++def _coerce_number_list(name, arr):+ if not isinstance(arr, list):+ raise ValueError(f"{name} expects an array of numbers")+ out = []+ for v in arr:+ if isinstance(v, bool) or not isinstance(v, (int, float)):+ raise ValueError(f"{name} expects an array of numbers")+ out.append(v)+ return out+++def _jsonata_sum(*args):+ if len(args) != 1:+ raise ValueError("$sum expects 1 argument")+ return sum(_coerce_number_list("$sum", args[0]))+++def _jsonata_average(*args):+ if len(args) != 1:+ raise ValueError("$average expects 1 argument")+ nums = _coerce_number_list("$average", args[0])+ if not nums:+ raise ValueError("$average of empty array is undefined")+ return sum(nums) / len(nums)+++def _jsonata_max(*args):+ if len(args) != 1:+ raise ValueError("$max expects 1 argument")+ nums = _coerce_number_list("$max", args[0])+ if not nums:+ raise ValueError("$max of empty array is undefined")+ return max(nums)+++def _jsonata_min(*args):+ if len(args) != 1:+ raise ValueError("$min expects 1 argument")+ nums = _coerce_number_list("$min", args[0])+ if not nums:+ raise ValueError("$min of empty array is undefined")+ return min(nums)+++def _require_num(name, value):+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ raise ValueError(f"{name} expects a number")+ return value+++def _jsonata_abs(*args):+ if len(args) != 1:+ raise ValueError("$abs expects 1 argument")+ return abs(_require_num("$abs", args[0]))+++def _jsonata_floor(*args):+ import math+ if len(args) != 1:+ raise ValueError("$floor expects 1 argument")+ return math.floor(_require_num("$floor", args[0]))+++def _jsonata_ceil(*args):+ import math+ if len(args) != 1:+ raise ValueError("$ceil expects 1 argument")+ return math.ceil(_require_num("$ceil", args[0]))+++def _jsonata_round(*args):+ # JSONata uses banker's rounding (round-half-to-even). Python's built-in+ # `round` does the same — defer to it. Optional precision argument.+ if len(args) not in (1, 2):+ raise ValueError("$round expects 1 or 2 arguments")+ n = _require_num("$round", args[0])+ if len(args) == 2:+ precision = int(args[1])+ return round(n, precision)+ return round(n)+++def _jsonata_power(*args):+ if len(args) != 2:+ raise ValueError("$power expects 2 arguments")+ base = _require_num("$power", args[0])+ exp = _require_num("$power", args[1])+ return base ** exp+++def _jsonata_sqrt(*args):+ import math+ if len(args) != 1:+ raise ValueError("$sqrt expects 1 argument")+ n = _require_num("$sqrt", args[0])+ if n < 0:+ raise ValueError("$sqrt of negative number is undefined")+ return math.sqrt(n)+++# --- Array functions ------------------------------------------------------+++def _jsonata_sort(*args):+ # $sort(array) — natural ascending.+ # $sort(array, function($l, $r){...}) — JSONata: comparator returns true+ # if $l should sort *after* $r (i.e. positive).+ if len(args) not in (1, 2):+ raise ValueError("$sort expects 1 or 2 arguments")+ if not isinstance(args[0], list):+ raise ValueError("$sort expects an array")+ if len(args) == 1:+ try:+ return sorted(args[0])+ except TypeError as e:+ raise ValueError(f"$sort: items not mutually comparable ({e})")+ comparator = args[1]+ if not callable(comparator):+ raise ValueError("$sort: second argument must be a function")+ import functools++ def _cmp(a, b):+ # JSONata comparator returns truthy if `a > b`, falsy otherwise.+ if _truthy(comparator(a, b)):+ return 1+ if _truthy(comparator(b, a)):+ return -1+ return 0+ return sorted(args[0], key=functools.cmp_to_key(_cmp))+++def _jsonata_reverse(*args):+ if len(args) != 1:+ raise ValueError("$reverse expects 1 argument")+ if not isinstance(args[0], list):+ raise ValueError("$reverse expects an array")+ return list(reversed(args[0]))+++def _jsonata_distinct(*args):+ # JSONata $distinct preserves first-occurrence order.+ if len(args) != 1:+ raise ValueError("$distinct expects 1 argument")+ if not isinstance(args[0], list):+ raise ValueError("$distinct expects an array")+ seen = []+ seen_keys = set()+ for item in args[0]:+ # JSON-comparable representation as the dedup key — unhashable items+ # (dicts, lists) fall back to a stable repr.+ try:+ key = item if isinstance(item, (str, int, float, bool)) or item is None else json.dumps(item, sort_keys=True)+ except TypeError:+ key = repr(item)+ if key not in seen_keys:+ seen_keys.add(key)+ seen.append(item)+ return seen+++def _jsonata_append(*args):+ if len(args) != 2:+ raise ValueError("$append expects 2 arguments")+ left = args[0] if isinstance(args[0], list) else [args[0]]+ right = args[1] if isinstance(args[1], list) else [args[1]]+ return left + right+++# --- Object functions -----------------------------------------------------+++def _jsonata_keys(*args):+ if len(args) != 1:+ raise ValueError("$keys expects 1 argument")+ if not isinstance(args[0], dict):+ raise ValueError("$keys expects an object")+ return list(args[0].keys())+++def _jsonata_values(*args):+ if len(args) != 1:+ raise ValueError("$values expects 1 argument")+ if not isinstance(args[0], dict):+ raise ValueError("$values expects an object")+ return list(args[0].values())+++def _jsonata_lookup(*args):+ # JSONata $lookup(object, key). If `object` is an array of objects, all+ # matching values are returned as an array; a single match returns the+ # value scalar (per JSONata's "singleton sequence" semantics).+ if len(args) != 2:+ raise ValueError("$lookup expects 2 arguments")+ obj, key = args+ key = _require_str("$lookup", key)+ if isinstance(obj, dict):+ return obj.get(key)+ if isinstance(obj, list):+ hits = [o[key] for o in obj if isinstance(o, dict) and key in o]+ if not hits:+ return None+ return hits[0] if len(hits) == 1 else hits+ raise ValueError("$lookup expects an object or array of objects")+++# --- Type / coercion ------------------------------------------------------+++def _jsonata_type(*args):+ # JSONata returns: "string" | "number" | "boolean" | "array" | "object" |+ # "null". Functions are out of scope — we don't expose first-class fns.+ if len(args) != 1:+ raise ValueError("$type expects 1 argument")+ v = args[0]+ if v is None:+ return "null"+ if isinstance(v, bool):+ return "boolean"+ if isinstance(v, (int, float)):+ return "number"+ if isinstance(v, str):+ return "string"+ if isinstance(v, list):+ return "array"+ if isinstance(v, dict):+ return "object"+ raise ValueError(f"$type: unsupported value type {type(v).__name__}")+++def _jsonata_boolean(*args):+ # JSONata truthy rules: boolean unchanged; "" / 0 / [] / {} / null → false.+ if len(args) != 1:+ raise ValueError("$boolean expects 1 argument")+ return _truthy(args[0])+++# --- Date / Time ----------------------------------------------------------+++def _jsonata_now(*args):+ # JSONata $now() / $now(picture) / $now(picture, timezone).+ # Without args: ISO-8601 UTC, millisecond precision, e.g. "2024-...Z".+ # With picture: XPath-3.1 date/time picture (subset — see+ # `_format_datetime_picture`). With timezone: "+HH:MM" / "-HH:MM" offset+ # applied before formatting.+ from datetime import datetime, timezone, timedelta+ if len(args) > 2:+ raise ValueError("$now expects 0, 1, or 2 arguments")+ now = datetime.now(timezone.utc)+ if len(args) == 2:+ tz = _require_str("$now", args[1])+ m = re.fullmatch(r"([+-])(\d{2}):?(\d{2})", tz)+ if not m:+ raise ValueError(f"$now: invalid timezone offset {tz!r}")+ sign = 1 if m.group(1) == "+" else -1+ offset = timedelta(hours=int(m.group(2)), minutes=int(m.group(3))) * sign+ now = now.astimezone(timezone(offset))+ if args:+ picture = _require_str("$now", args[0])+ return _format_datetime_picture(now, picture)+ return now.strftime("%Y-%m-%dT%H:%M:%S.") + f"{now.microsecond // 1000:03d}Z"+++def _format_datetime_picture(dt, picture):+ """Subset of the XPath 3.1 format-dateTime picture used by JSONata.+ Supports the variable markers documented in the JSONata docs:+ [Y0001] / [Y] year, [M01] / [M] month, [D01] / [D] day,+ [H01] / [H] hour-24, [m01] / [m] minute, [s01] / [s] second,+ [f001] millisecond, [Z] / [z] tz offset.+ Other markers raise so callers get a clear error rather than wrong data."""+ out = []+ i = 0+ while i < len(picture):+ ch = picture[i]+ if ch != "[":+ if ch == "]" and i + 1 < len(picture) and picture[i + 1] == "]":+ out.append("]")+ i += 2+ continue+ out.append(ch)+ i += 1+ continue+ end = picture.find("]", i)+ if end < 0:+ raise ValueError(f"$now: unterminated marker in picture {picture!r}")+ marker = picture[i + 1:end].strip()+ i = end + 1+ if not marker:+ raise ValueError(f"$now: empty marker in picture {picture!r}")+ comp = marker[0]+ width_spec = marker[1:].strip()+ # Width spec like "01" / "0001" / "1" — leading-zero pad to that width.+ pad = 0+ if width_spec:+ m = re.fullmatch(r"(\d+)", width_spec)+ if not m:+ raise ValueError(+ f"$now: unsupported picture width {width_spec!r}")+ pad = len(width_spec)+ if comp == "Y":+ out.append(str(dt.year).zfill(pad or 4))+ elif comp == "M":+ out.append(str(dt.month).zfill(pad or 1))+ elif comp == "D":+ out.append(str(dt.day).zfill(pad or 1))+ elif comp == "H":+ out.append(str(dt.hour).zfill(pad or 1))+ elif comp == "m":+ out.append(str(dt.minute).zfill(pad or 1))+ elif comp == "s":+ out.append(str(dt.second).zfill(pad or 1))+ elif comp == "f":+ out.append(str(dt.microsecond // 1000).zfill(pad or 3))+ elif comp in ("Z", "z"):+ off = dt.utcoffset()+ if off is None or off.total_seconds() == 0:+ out.append("Z" if comp == "Z" else "+00:00")+ else:+ total = int(off.total_seconds())+ sign = "+" if total >= 0 else "-"+ total = abs(total)+ hh, mm = divmod(total // 60, 60)+ out.append(f"{sign}{hh:02d}:{mm:02d}")+ else:+ raise ValueError(+ f"$now: unsupported picture component {comp!r} in {picture!r}")+ return "".join(out)+++def _jsonata_millis(*args):+ if args:+ raise ValueError("$millis takes no arguments")+ return int(time.time() * 1000)+++# --- Utility --------------------------------------------------------------+++def _jsonata_uuid(*args):+ import uuid as _uuid+ if args:+ raise ValueError("$uuid takes no arguments")+ return str(_uuid.uuid4())+++def _jsonata_format_number(*args):+ # JSONata $formatNumber(number, picture[, options]). Implements the+ # XPath-3.1 "decimal-format" subset most workflows use:+ # `0` mandatory digit, `#` optional digit, `,` grouping separator,+ # `.` decimal separator, `;` positive;negative subpictures, `%` percent+ # (×100), and an optional `-` sign in the negative subpicture.+ # Locale-specific overrides via the `options` arg are not supported and+ # raise — callers see a clear error rather than wrong data.+ if len(args) not in (2, 3):+ raise ValueError("$formatNumber expects 2 or 3 arguments")+ if len(args) == 3:+ raise ValueError("$formatNumber: options argument is not supported")+ n = _require_num("$formatNumber", args[0])+ picture = _require_str("$formatNumber", args[1])++ # Split positive;negative subpictures.+ if ";" in picture:+ pos_pic, neg_pic = picture.split(";", 1)+ else:+ pos_pic, neg_pic = picture, None++ def _apply(pic, value):+ # Percent / per-mille suffixes scale the value before formatting.+ scale = 1+ suffix = ""+ prefix = ""+ body = pic+ if body.endswith("%"):+ scale = 100+ suffix = "%"+ body = body[:-1]+ elif body.endswith("‰"):+ scale = 1000+ suffix = "‰"+ body = body[:-1]+ # Leading literal `-` etc. — strip non-format chars from the front into+ # `prefix`, and trailing into `suffix`. Format chars: 0 # , .+ while body and body[0] not in "0#":+ prefix += body[0]+ body = body[1:]+ trailing = ""+ while body and body[-1] not in "0#":+ if body[-1] in ",.":+ break+ trailing = body[-1] + trailing+ body = body[:-1]+ suffix = trailing + suffix++ scaled = value * scale+ if "." in body:+ int_pic, frac_pic = body.split(".", 1)+ else:+ int_pic, frac_pic = body, ""++ # Decimals: count digits in frac picture; pad zeros for `0`s, trim+ # trailing zeros only where `#`s sit.+ frac_digits = sum(1 for c in frac_pic if c in "0#")+ frac_min = sum(1 for c in frac_pic if c == "0")+ rounded = round(scaled, frac_digits) if frac_digits else round(scaled)+ # Use absolute value — sign handled by subpicture selection.+ rounded = abs(rounded)+ if frac_digits == 0:+ int_part = str(int(round(rounded)))+ frac_part = ""+ else:+ s = f"{rounded:.{frac_digits}f}"+ int_part, frac_part = s.split(".")+ # Trim trailing zeros down to the minimum required by `0`s.+ while len(frac_part) > frac_min and frac_part.endswith("0"):+ frac_part = frac_part[:-1]++ # Int picture: pad to required leading zeros (count of `0`s).+ int_min = sum(1 for c in int_pic if c == "0")+ if len(int_part) < int_min:+ int_part = int_part.rjust(int_min, "0")++ # Grouping: if int_pic has `,`, group from the right by the distance+ # between the rightmost `,` and the decimal point (typical 3).+ if "," in int_pic:+ # Distance from rightmost `,` to end of int_pic gives group size.+ last_comma = int_pic.rfind(",")+ group_size = len(int_pic) - last_comma - 1+ if group_size > 0:+ # Insert separators every `group_size` from the right.+ rev = int_part[::-1]+ chunks = [rev[i:i + group_size] for i in range(0, len(rev), group_size)]+ int_part = ",".join(chunks)[::-1]++ result = int_part + (("." + frac_part) if frac_part else "")+ return prefix + result + suffix++ if n < 0:+ if neg_pic is not None:+ return _apply(neg_pic, n)+ return "-" + _apply(pos_pic, n)+ return _apply(pos_pic, n)+++def _jsonata_base64encode(*args):+ import base64+ if len(args) != 1:+ raise ValueError("$base64encode expects 1 argument")+ return base64.b64encode(_require_str("$base64encode", args[0]).encode("utf-8")).decode("ascii")+++def _jsonata_base64decode(*args):+ import base64+ if len(args) != 1:+ raise ValueError("$base64decode expects 1 argument")+ return base64.b64decode(_require_str("$base64decode", args[0])).decode("utf-8")+++# Registry consumed by `_eval_jsonata_primary`. `$exists` is handled inline+# because it must intercept evaluation errors on its argument.+_JSONATA_FUNCS = {+ # core (pre-existing)+ "$merge": _jsonata_merge,+ "$count": _jsonata_count,+ "$length": _jsonata_length,+ "$not": _jsonata_not,+ "$string": _jsonata_string,+ "$number": _jsonata_number,+ # string+ "$uppercase": _jsonata_uppercase,+ "$lowercase": _jsonata_lowercase,+ "$substring": _jsonata_substring,+ "$trim": _jsonata_trim,+ "$contains": _jsonata_contains,+ "$split": _jsonata_split,+ "$join": _jsonata_join,+ "$replace": _jsonata_replace,+ "$pad": _jsonata_pad,+ # numeric+ "$sum": _jsonata_sum,+ "$average": _jsonata_average,+ "$max": _jsonata_max,+ "$min": _jsonata_min,+ "$abs": _jsonata_abs,+ "$floor": _jsonata_floor,+ "$ceil": _jsonata_ceil,+ "$round": _jsonata_round,+ "$power": _jsonata_power,+ "$sqrt": _jsonata_sqrt,+ # array+ "$sort": _jsonata_sort,+ "$reverse": _jsonata_reverse,+ "$distinct": _jsonata_distinct,+ "$append": _jsonata_append,+ # object+ "$keys": _jsonata_keys,+ "$values": _jsonata_values,+ "$lookup": _jsonata_lookup,+ # type+ "$type": _jsonata_type,+ "$boolean": _jsonata_boolean,+ # date/time+ "$now": _jsonata_now,+ "$millis": _jsonata_millis,+ # utility+ "$uuid": _jsonata_uuid,+ "$base64encode": _jsonata_base64encode,+ "$base64decode": _jsonata_base64decode,+ "$formatNumber": _jsonata_format_number,+}++def _find_top_level_any_op(text, ops, keyword=False):"""Return (position, op) of the rightmost top-level occurrence of any op in ops.@@ -2450,6 +3260,68 @@ def _resolve_jsonata_states_path(expr, states):return _resolve_dotted_path(rest, current)+def _exists_jsonata_expr(expr, states):+ """JSONata `$exists`: true iff the expression resolves to a *value* —+ including explicit `null`. Returns false when a `$states.…` path or+ `$variable.…` path has a missing segment, or when evaluation raises.++ For non-path expressions we fall back to "evaluates without raising and+ is not the missing sentinel".+ """+ expr = expr.strip()++ # `$states.<root>.<a>.<b>.…` — walk segments with missing-vs-null distinction.+ if expr.startswith("$states."):+ suffix = expr[len("$states."):]+ root, _, rest = suffix.partition(".")+ if root not in states:+ return False+ current = states[root]+ if not rest:+ return True # the root itself exists (even if null)+ return _path_exists(rest, current)++ # `$varname.<a>.<b>.…` — variable lookup.+ m = re.fullmatch(+ r"\$([A-Za-z_][A-Za-z0-9_]*)(?:\.(.+))?", expr)+ if m:+ head, rest = m.group(1), m.group(2)+ variables = states.get("_variables", {})+ if head not in variables:+ return False+ if not rest:+ return True+ return _path_exists(rest, variables[head])++ # General expression: exists iff it evaluates without raising.+ try:+ _eval_jsonata_expr(expr, states)+ return True+ except Exception:+ return False+++def _path_exists(path, data):+ """Walk a dotted JSONata path and return True iff every segment matches.+ Distinguishes `{"x": null}` (path "x" → True) from `{}` (path "x" → False)."""+ current = data+ for raw_part in path.split("."):+ part = raw_part+ while part:+ match = re.match(r"([A-Za-z_][A-Za-z0-9_]*)(?:\[(\d+)])?(.*)", part)+ if not match:+ return False+ field, idx, part = match.groups()+ if not isinstance(current, dict) or field not in current:+ return False+ current = current[field]+ if idx is not None:+ if not isinstance(current, list) or int(idx) >= len(current):+ return False+ current = current[int(idx)]+ return True++def _resolve_dotted_path(path, data):current = datafor raw_part in path.split("."):diff --git a/pyproject.toml b/pyproject.tomlindex 0c14e28d..b2515fc3 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"[project]name = "ministack"-version = "1.3.43"+version = "1.3.44"description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"readme = "README.md"license = { file = "LICENSE" }diff --git a/tests/test_rds.py b/tests/test_rds.pyindex cb55c54f..913f30e6 100644--- a/tests/test_rds.py+++ b/tests/test_rds.py@@ -983,6 +983,46 @@ def test_rds_mysql_master_user_privilege_grants(monkeypatch):assert ("FLUSH PRIVILEGES", None) in calls+def test_rds_create_db_instance_returns_before_container_is_ready(rds):+ """CreateDBInstance must return immediately matching real AWS:+ status=creating now, status=available after the background readiness+ finalisation flips it.++ Real AWS docs: CreateDBInstance "creates a new DB instance" — the+ response is the freshly-created record with `DBInstanceStatus=creating`,+ not a blocking wait until provisioning completes.+ """+ iid = f"intg-rds-nonblock-{_uuid_mod.uuid4().hex[:8]}"+ t0 = time.time()+ resp = rds.create_db_instance(+ DBInstanceIdentifier=iid,+ DBInstanceClass="db.t3.micro",+ Engine="postgres",+ MasterUsername="admin",+ MasterUserPassword="secret",+ AllocatedStorage=20,+ )+ elapsed = time.time() - t0+ # Real AWS `CreateDBInstance` returns within milliseconds — readiness is+ # observed asynchronously via `DescribeDBInstances`. We allow a couple of+ # seconds for docker-client setup but must not block on the boot itself.+ assert elapsed < 10, (+ f"CreateDBInstance blocked {elapsed:.1f}s — should return immediately "+ "with status=creating and let a background thread finalise readiness"+ )++ status = resp["DBInstance"]["DBInstanceStatus"]+ # Either "creating" (real container still booting) or "available"+ # (the unit-test path with no Docker — endpoint_host is stub, no real+ # readiness check fires). Both are valid AWS shapes for the early return.+ assert status in ("creating", "available"), f"unexpected status: {status}"++ try:+ rds.delete_db_instance(DBInstanceIdentifier=iid, SkipFinalSnapshot=True)+ except Exception:+ pass++def test_rds_modify_cluster_password(rds):"""ModifyDBCluster with MasterUserPassword succeeds."""rds.create_db_cluster(diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.pyindex bc631632..ffdec461 100644--- a/tests/test_stepfunctions.py+++ b/tests/test_stepfunctions.py@@ -4463,3 +4463,296 @@ def test_sfn_jsonata_assign_reuses_input(sfn_sync):assert json.loads(resp["output"]) == "hello world"finally:sfn_sync.delete_state_machine(stateMachineArn=sm_arn)+++# ---------------------------------------------------------------------------+# JSONata standard library — issue #669+# ---------------------------------------------------------------------------++def _sfn_run_pass_output(sfn_sync, output_expr, input_obj=None):+ """Round-trip helper: build a single Pass state whose Output is `output_expr`,+ run it sync, return the parsed JSON output."""+ sm_name = f"jsonata-fn-{_uuid_mod.uuid4().hex[:8]}"+ sm_arn = sfn_sync.create_state_machine(+ name=sm_name,+ roleArn="arn:aws:iam::000000000000:role/sfn-role",+ definition=json.dumps({+ "QueryLanguage": "JSONata",+ "StartAt": "Run",+ "States": {+ "Run": {+ "Type": "Pass",+ "Output": output_expr,+ "End": True,+ },+ },+ }),+ )["stateMachineArn"]+ try:+ resp = sfn_sync.start_sync_execution(+ stateMachineArn=sm_arn,+ input=json.dumps(input_obj or {}),+ )+ assert resp["status"] == "SUCCEEDED", \+ f"Execution failed: {resp.get('error')} - {resp.get('cause')}"+ return json.loads(resp["output"])+ finally:+ sfn_sync.delete_state_machine(stateMachineArn=sm_arn)+++def test_sfn_jsonata_exists_in_choice_condition_issue_669(sfn_sync):+ """The exact example from issue #669: `$exists($states.input.userId)` used+ as a Choice `Condition` must route correctly whether the field is present+ or missing (returning false on missing rather than failing the execution)."""+ sm_name = f"jsonata-exists-{_uuid_mod.uuid4().hex[:8]}"+ sm_arn = sfn_sync.create_state_machine(+ name=sm_name,+ roleArn="arn:aws:iam::000000000000:role/sfn-role",+ definition=json.dumps({+ "QueryLanguage": "JSONata",+ "StartAt": "Route",+ "States": {+ "Route": {+ "Type": "Choice",+ "Choices": [+ {+ "Condition": "{% $exists($states.input.userId) %}",+ "Next": "HasUser",+ },+ ],+ "Default": "NoUser",+ },+ "HasUser": {"Type": "Pass", "Output": {"branch": "has"}, "End": True},+ "NoUser": {"Type": "Pass", "Output": {"branch": "missing"}, "End": True},+ },+ }),+ )["stateMachineArn"]+ try:+ has = sfn_sync.start_sync_execution(+ stateMachineArn=sm_arn, input=json.dumps({"userId": "u-42"}))+ assert has["status"] == "SUCCEEDED"+ assert json.loads(has["output"]) == {"branch": "has"}++ miss = sfn_sync.start_sync_execution(+ stateMachineArn=sm_arn, input=json.dumps({}))+ assert miss["status"] == "SUCCEEDED"+ assert json.loads(miss["output"]) == {"branch": "missing"}+ finally:+ sfn_sync.delete_state_machine(stateMachineArn=sm_arn)+++def test_sfn_jsonata_string_functions(sfn_sync):+ out = _sfn_run_pass_output(sfn_sync, {+ "upper": "{% $uppercase('hello') %}",+ "lower": "{% $lowercase('HELLO') %}",+ "sub2": "{% $substring('abcdef', 2) %}",+ "sub3": "{% $substring('abcdef', 1, 3) %}",+ "trim": "{% $trim(' a b ') %}",+ "contains": "{% $contains('hello world', 'world') %}",+ "split": "{% $split('a,b,c', ',') %}",+ "join": "{% $join(['a', 'b', 'c'], '-') %}",+ "replace": "{% $replace('aXbXc', 'X', '_') %}",+ "pad_right": "{% $pad('x', 4, '.') %}",+ "pad_left": "{% $pad('x', -4, '.') %}",+ })+ assert out == {+ "upper": "HELLO", "lower": "hello",+ "sub2": "cdef", "sub3": "bcd",+ "trim": "a b", "contains": True,+ "split": ["a", "b", "c"], "join": "a-b-c",+ "replace": "a_b_c", "pad_right": "x...", "pad_left": "...x",+ }+++def test_sfn_jsonata_numeric_functions(sfn_sync):+ out = _sfn_run_pass_output(sfn_sync, {+ "sum": "{% $sum([1, 2, 3, 4]) %}",+ "avg": "{% $average([2, 4, 6]) %}",+ "max": "{% $max([3, 1, 2]) %}",+ "min": "{% $min([3, 1, 2]) %}",+ "abs": "{% $abs(-7) %}",+ "floor": "{% $floor(2.9) %}",+ "ceil": "{% $ceil(2.1) %}",+ "round": "{% $round(2.5) %}",+ "roundp": "{% $round(2.345, 2) %}",+ "power": "{% $power(2, 8) %}",+ "sqrt": "{% $sqrt(16) %}",+ })+ # $round uses banker's rounding: 2.5 -> 2 (round-half-to-even)+ assert out == {+ "sum": 10, "avg": 4, "max": 3, "min": 1,+ "abs": 7, "floor": 2, "ceil": 3,+ "round": 2, "roundp": 2.35,+ "power": 256, "sqrt": 4,+ }+++def test_sfn_jsonata_array_functions(sfn_sync):+ out = _sfn_run_pass_output(sfn_sync, {+ "sort": "{% $sort([3, 1, 2]) %}",+ "reverse": "{% $reverse([1, 2, 3]) %}",+ "distinct": "{% $distinct([1, 2, 2, 3, 1]) %}",+ "append": "{% $append([1, 2], [3, 4]) %}",+ })+ assert out == {+ "sort": [1, 2, 3],+ "reverse": [3, 2, 1],+ "distinct": [1, 2, 3],+ "append": [1, 2, 3, 4],+ }+++def test_sfn_jsonata_object_functions(sfn_sync):+ out = _sfn_run_pass_output(+ sfn_sync,+ {+ "keys": "{% $keys($states.input.obj) %}",+ "values": "{% $values($states.input.obj) %}",+ "look": "{% $lookup($states.input.obj, 'a') %}",+ },+ input_obj={"obj": {"a": 1, "b": 2}},+ )+ assert out == {"keys": ["a", "b"], "values": [1, 2], "look": 1}+++def test_sfn_jsonata_type_and_boolean(sfn_sync):+ out = _sfn_run_pass_output(sfn_sync, {+ "t_str": "{% $type('s') %}",+ "t_num": "{% $type(1) %}",+ "t_arr": "{% $type([1]) %}",+ "t_obj": "{% $type({'k': 1}) %}",+ "b_empty": "{% $boolean('') %}",+ "b_str": "{% $boolean('x') %}",+ "b_zero": "{% $boolean(0) %}",+ })+ assert out == {+ "t_str": "string", "t_num": "number",+ "t_arr": "array", "t_obj": "object",+ "b_empty": False, "b_str": True, "b_zero": False,+ }+++def test_sfn_jsonata_datetime_and_util(sfn_sync):+ out = _sfn_run_pass_output(sfn_sync, {+ "now": "{% $now() %}",+ "millis": "{% $millis() %}",+ "uuid": "{% $uuid() %}",+ "b64_encode": "{% $base64encode('hello') %}",+ "b64_decode": "{% $base64decode('aGVsbG8=') %}",+ })+ # $now: ISO-8601 UTC with millisecond precision ending in 'Z'+ assert isinstance(out["now"], str) and out["now"].endswith("Z")+ assert "T" in out["now"]+ assert isinstance(out["millis"], int) and out["millis"] > 0+ assert isinstance(out["uuid"], str) and len(out["uuid"]) == 36+ assert out["b64_encode"] == "aGVsbG8="+ assert out["b64_decode"] == "hello"+++def test_sfn_jsonata_exists_distinguishes_null_from_missing(sfn_sync):+ """JSONata spec: `$exists` returns true for an explicit null value (the path+ matches a value), and false only for a missing path. The previous fix+ collapsed both to false — this regression-locks the spec distinction."""+ out = _sfn_run_pass_output(+ sfn_sync,+ {+ "present_value": "{% $exists($states.input.a) %}",+ "explicit_null": "{% $exists($states.input.b) %}",+ "missing_key": "{% $exists($states.input.c) %}",+ "nested_null": "{% $exists($states.input.d.x) %}",+ "nested_miss": "{% $exists($states.input.d.y) %}",+ },+ input_obj={"a": 1, "b": None, "d": {"x": None}},+ )+ assert out == {+ "present_value": True,+ "explicit_null": True,+ "missing_key": False,+ "nested_null": True,+ "nested_miss": False,+ }+++def test_sfn_jsonata_regex_literal_in_string_fns(sfn_sync):+ """$contains/$split/$replace accept `/pattern/flags` regex literals."""+ out = _sfn_run_pass_output(sfn_sync, {+ "ci_match": "{% $contains('Hello World', /hello/i) %}",+ "no_match": "{% $contains('Hello World', /xyz/) %}",+ "split_ws": "{% $split('a b c', /\\s+/) %}",+ "replace": "{% $replace('foo123bar456', /[0-9]+/, '#') %}",+ "backref": "{% $replace('John Smith', /(\\w+) (\\w+)/, '$2 $1') %}",+ })+ assert out == {+ "ci_match": True,+ "no_match": False,+ "split_ws": ["a", "b", "c"],+ "replace": "foo#bar#",+ "backref": "Smith John",+ }+++def test_sfn_jsonata_sort_with_comparator_function(sfn_sync):+ """$sort accepts a `function($l, $r){...}` comparator. Sorting descending+ via a custom comparator is the canonical JSONata example."""+ out = _sfn_run_pass_output(sfn_sync, {+ "desc": "{% $sort([3, 1, 4, 1, 5, 9, 2, 6], function($l, $r){$l < $r}) %}",+ })+ assert out == {"desc": [9, 6, 5, 4, 3, 2, 1, 1]}+++def test_sfn_jsonata_join_strict_and_lookup_array(sfn_sync):+ """$join requires all-string arrays; $lookup over an array of objects+ returns the matching values."""+ out = _sfn_run_pass_output(+ sfn_sync,+ {+ "join": "{% $join($states.input.names, '|') %}",+ "look1": "{% $lookup($states.input.users, 'id') %}",+ },+ input_obj={+ "names": ["a", "b", "c"],+ "users": [{"id": 1}, {"id": 2}, {"id": 3}],+ },+ )+ assert out == {"join": "a|b|c", "look1": [1, 2, 3]}+++def test_sfn_jsonata_boolean_array_of_falsy_is_false(sfn_sync):+ """JSONata: array of only-false values is itself false; an array with at+ least one truthy value is true."""+ out = _sfn_run_pass_output(sfn_sync, {+ "all_false": "{% $boolean([false, false, 0, '']) %}",+ "any_true": "{% $boolean([false, 'x']) %}",+ })+ assert out == {"all_false": False, "any_true": True}+++def test_sfn_jsonata_now_picture_and_timezone(sfn_sync):+ """$now(picture) and $now(picture, timezone) format per XPath picture."""+ out = _sfn_run_pass_output(sfn_sync, {+ "date_only": "{% $now('[Y0001]-[M01]-[D01]') %}",+ "with_tz": "{% $now('[H01]:[m01][Z]', '+05:30') %}",+ "default": "{% $now() %}",+ })+ import re as _re+ assert _re.fullmatch(r"\d{4}-\d{2}-\d{2}", out["date_only"])+ assert _re.fullmatch(r"\d{2}:\d{2}\+05:30", out["with_tz"])+ assert out["default"].endswith("Z")+++def test_sfn_jsonata_format_number(sfn_sync):+ """$formatNumber supports grouping, decimals, percent, and pos;neg subpictures."""+ out = _sfn_run_pass_output(sfn_sync, {+ "grouped": "{% $formatNumber(12345.6, '#,###.00') %}",+ "percent": "{% $formatNumber(0.5, '00.0%') %}",+ "pad": "{% $formatNumber(7, '000') %}",+ "neg_sub": "{% $formatNumber(-1234.5, '#,##0.00;(#,##0.00)') %}",+ "plain": "{% $formatNumber(1234, '0,000') %}",+ })+ assert out == {+ "grouped": "12,345.60",+ "percent": "50.0%",+ "pad": "007",+ "neg_sub": "(1,234.50)",+ "plain": "1,234",+ }