Skip to content

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

release v1.5.3 (#1556)

Nahuel Nucera8383224b4c15
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e1e43647..a99f3b9a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,13 +5,24 @@ All notable changes to MiniStack will be documented here.
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
Versioning follows [Semantic Versioning](https://semver.org/).
-## [Unreleased]
+## [1.5.3] — 2026-08-28
### Added
+- **Step Functions — the JSONata query language** — a state machine declaring `QueryLanguage: JSONata` now evaluates its `{% ... %}` expressions through a full JSONata engine: `$states` and workflow variables bind as documented, the six Step Functions functions (`$partition`, `$range`, `$hash`, `$random`, `$uuid`, `$parse`) are registered, failures surface as `States.QueryEvaluationError` with the JSONata error code leading the cause (`T2010: ...`), a malformed expression is refused at `CreateStateMachine`/`UpdateStateMachine` with `InvalidDefinition` (`INVALID_JSONATA_EXPRESSION` naming the field's path) as AWS refuses it, a non-ISO `$toMillis` argument and a zero-length-matching `$replace` regex draw AWS's `D3110`/`D1004`, and evaluation carries AWS's 1-second timeout. `$eval` is absent, as on AWS. Reported by @facuparedes.
+- **IoT Core — jobs delivered over MQTT** — the reserved `$aws/things/<t>/jobs/#` request topics (`get`, `start-next`, `<jobId>/get` including `$next`, `<jobId>/update`) answer on their `accepted`/`rejected` topics from the same store the HTTP plane uses, with `jobDocument` as a JSON object over MQTT (a string over HTTP, as on AWS) and rejections carrying the string `ErrorCode` values plus the execution's state on version and state-transition conflicts; `notify` fires when the pending set changes and `notify-next` only when the queue front changes. `stepTimeoutInMinutes` and `executionNumber` are accepted but ignored. Contributed by @iot-rocket.
+- **IoT Core — provisioning templates, and `AWS::IoT::ProvisioningTemplate`** — `CreateProvisioningTemplate` and the four other template operations answered `Unsupported IoT path` and the CloudFormation type rolled back as unsupported; both now work with the wire shapes of the real service (`ResourceAlreadyExistsException` on duplicates, absent-not-empty `description`, 1-36 char names, a `templateBody` without an `AWS::IoT::Certificate` resource refused). Storage + CRUD only: the fleet-provisioning MQTT workflow is not implemented and versions are not modeled. Contributed by @iot-rocket.
+- **API Gateway — registered custom domains route the data plane** — a request addressed by a registered domain fell through host-pattern service guessing (typically into S3, or into IoT when the name contained `iot.`); it now resolves through the domain's base-path mappings before any guessing — longest base path wins, `"(none)"` is the root mapping, a mapping's stage is authoritative — matching the `BASE_PATH_MAPPING_ONLY` routing mode the records default to. Unregistered hosts are unchanged. Contributed by @iot-rocket.
+- **CloudFormation — in-place update handlers** — a stack update fell through to a destructive re-create for 106 of 132 registered types, wiping published Lambda versions, DynamoDB items, SQS messages and IAM attachments; `AWS::Lambda::Function`, `AWS::DynamoDB::Table`, the four API Gateway types, `AWS::IoT::TopicRule`, `AWS::SNS::Topic`, `AWS::SQS::Queue`, `AWS::Logs::LogGroup`, `AWS::S3::BucketPolicy`, `AWS::IAM::Role` and `AWS::IAM::ManagedPolicy` now update in place through their service's own APIs, replacing only for genuinely create-only properties, as CloudFormation documents per property. Contributed by @iot-rocket.
- **S3 — replication delivers, with `x-amz-replication-status`** — a bucket's replication configuration was stored and echoed but never acted on: no object ever reached the destination and `HeadObject` showed no replication metadata. A write (put, POST upload, copy, or multipart complete) matching an Enabled rule's prefix now lands a copy in the destination bucket with its own version, the source's metadata, storage class override, and tags; the source object answers `ReplicationStatus: COMPLETED` (or `FAILED` when the destination is gone or no longer versioned) and the replica answers `REPLICA`, on current and version-addressed reads alike. The copy is synchronous so tests see a deterministic status. Delete-marker replication and replica re-replication are not modeled. Reported by @cringdahl.
### Fixed
+- **CloudFormation — a resource that cannot be deleted fails the operation** — a missing delete handler was a log warning and `DeleteStack` reported `DELETE_COMPLETE` while resources lived on; the stack now lands `DELETE_FAILED` (failed resources retained for a retry, exports kept, deleted siblings gone) and a failed rollback lands `ROLLBACK_FAILED`/`UPDATE_ROLLBACK_FAILED`, per the documented lifecycle. `AWS::Lambda::Version` gained a real delete handler (its `Ref` now returns the qualified version ARN, as on AWS) and `AWS::AppSync::GraphQLSchema` one that removes the stored schema. Contributed by @iot-rocket.
+- **IoT Core — an HTTP shadow write publishes the reserved-topic notifications** — `UpdateThingShadow` over the REST data plane stored state and emitted nothing, so a topic rule on `.../shadow/update/accepted` fired for MQTT updates only; an accepted HTTP update now publishes `update/accepted`/`delta`/`documents` (and a delete its `delete/accepted`) through the same emission code as the MQTT bridge, which also fixed the `documents` envelope on both transports: it now echoes the request's `clientToken` and carries `state` + `metadata` + `version` only. Contributed by @iot-rocket.
+- **IoT Core — device-plane job timestamps were milliseconds, 1000x off** — `iot-jobs-data` responses served epoch milliseconds where the API reference words every stamp "in seconds since the epoch"; every device-plane stamp, HTTP and MQTT alike, is now whole epoch seconds. Contributed by @iot-rocket.
- **Step Functions — execution status changes are published to EventBridge** — real Step Functions automatically emits `source: aws.states` / `detail-type: "Step Functions Execution Status Change"` to the default bus whenever a standard execution changes status; MiniStack ran the execution and published nothing, so a rule matching those events never fired and applications waiting on them hung with no error anywhere. Every `StartExecution` now emits `RUNNING` and its completion `SUCCEEDED`, `FAILED` (with `error`/`cause` and `REDRIVABLE`) or `ABORTED` on `StopExecution`, carrying the documented detail fields with epoch-millisecond dates; payloads over 248 KiB are excluded and flagged via `inputDetails`/`outputDetails`, and `StartSyncExecution` (the express-flavored path) emits nothing, as on AWS. Reported by @moonyseven.
+- **ECS — a service's tasks register in its target groups** — a `loadBalancers` block was stored and never acted on, so `DescribeTargetHealth` stayed empty and every request through the load balancer fell to the listener's default action; a service now reconciles its target groups from its running tasks' addresses (awsvpc tasks carry their address as `attachments[].details[privateIPv4Address]`, where real ECS reports it), withdrawing only its own registrations so manually registered targets and a second service sharing the group survive, as on AWS. Contributed by @jbschooley.
+- **ECS — an `awsvpc` task no longer publishes host ports** — each `awsvpc` task has its own network namespace on AWS, so container ports never bind on the host; publishing them made two tasks sharing a container port collide with a Docker bind error that cannot happen on Fargate. Only `bridge` and `host` modes publish. Contributed by @jbschooley.
+- **ELBv2 — a rule condition sent as a typed config is read** — only the flat legacy `Values` list was parsed, so a rule created by Terraform (which sends `PathPatternConfig`/`HostHeaderConfig`/`HttpRequestMethodConfig`/`SourceIpConfig`) stored an empty condition and never fired; both shapes now parse, `DescribeRules` echoes the typed config alongside `Values` as AWS does, and the data-plane matcher recognizes AWS's `http-request-method` field name. Contributed by @jbschooley.
## [1.5.2] — 2026-08-26
diff --git a/README.md b/README.md
index 4d5f095f..592f61f4 100644
--- a/README.md
+++ b/README.md
@@ -215,7 +215,7 @@ use1.list_tables()["TableNames"] # → ["users"]
euw1.list_tables()["TableNames"] # → [] — eu-west-1 is independent
```
-**Region-isolated services:** as of 1.5.2, every regional service is region-isolated except S3 and Aurora DSQL (the isolation migrations rolled out service by service from 1.4.0 to 1.4.12 — see the CHANGELOG for the per-release history; services introduced later, like AWS Config and the Cloud Control API in 1.4.14, were born region-scoped).
+**Region-isolated services:** as of 1.5.3, every regional service is region-isolated except S3 and Aurora DSQL (the isolation migrations rolled out service by service from 1.4.0 to 1.4.12 — see the CHANGELOG for the per-release history; services introduced later, like AWS Config and the Cloud Control API in 1.4.14, were born region-scoped).
Cross-resource references resolve in the referenced ARN's own account and region (SNS→SQS fanout, EventBridge targets, event source mappings), and cross-region references that real AWS rejects return the same errors AWS returns — e.g. invoking a `eu-west-1` Lambda from a `us-east-1` Step Functions task fails with `Functions from 'eu-west-1' are not reachable in this region`, exactly as on AWS.
diff --git a/ministack/services/alb.py b/ministack/services/alb.py
index 4be07f1a..8d58d784 100644
--- a/ministack/services/alb.py
+++ b/ministack/services/alb.py
@@ -904,16 +904,26 @@ def _set_rule_priorities(params):
# Target registration handlers
# ---------------------------------------------------------------------------
-def set_targets_for_group(tg_arn, targets):
- """Replace a target group's registrations. Used by ECS, whose services own the
- membership of their target group and reconcile it as tasks come and go.
-
- ``targets`` is an iterable of ``(id, port)``. Unknown target groups are ignored
- rather than raising: a service can outlive the group it referenced.
+def set_targets_for_group(tg_arn, targets, previous_ids=()):
+ """Replace the caller's own registrations in a target group.
+
+ Used by ECS, whose services reconcile their tasks' addresses as they come
+ and go. Real ECS deregisters only its own tasks, so registrations made by
+ anyone else — RegisterTargets calls, or a second service sharing the
+ group — survive: only ``previous_ids`` (the caller's last publication) are
+ withdrawn before ``targets`` (as ``(id, port)`` pairs) are added.
+ Unknown target groups are ignored rather than raising: a service can
+ outlive the group it referenced.
"""
if tg_arn not in _tgs:
return False
- _targets[tg_arn] = [{"Id": tid, "Port": port} for tid, port in targets]
+ withdrawn = set(previous_ids)
+ fresh = [{"Id": tid, "Port": port} for tid, port in targets]
+ fresh_ids = {t["Id"] for t in fresh}
+ _targets[tg_arn] = [
+ t for t in _targets.get(tg_arn, [])
+ if t["Id"] not in withdrawn and t["Id"] not in fresh_ids
+ ] + fresh
return True
@@ -1159,7 +1169,9 @@ def _match_condition(cond, method, path, headers, query_params):
hostname = headers.get("host", "").split(":")[0]
return any(fnmatch.fnmatch(hostname, v) for v in values)
- if field == "http-method":
+ if field in ("http-request-method", "http-method"):
+ # AWS's field name is http-request-method; the old local-only spelling
+ # keeps matching for rules stored before the rename.
return method.upper() in [v.upper() for v in values]
if field == "query-string":
diff --git a/ministack/services/ecs.py b/ministack/services/ecs.py
index 47da1b03..86106254 100644
--- a/ministack/services/ecs.py
+++ b/ministack/services/ecs.py
@@ -733,7 +733,14 @@ def _sync_service_targets(cluster_name, svc):
ip = _task_ip(task)
if ip:
targets.append((ip, port))
- published = alb.set_targets_for_group(tg_arn, targets)
+ # Only this service's previous publication is withdrawn: a second
+ # service sharing the group, or targets registered by hand, stay —
+ # real ECS deregisters only its own tasks.
+ ledger = svc.setdefault("_published_targets", {})
+ published = alb.set_targets_for_group(
+ tg_arn, targets, ledger.get(tg_arn, ())
+ )
+ ledger[tg_arn] = [ip for ip, _ in targets]
if published:
logger.debug("ECS: %s -> %d target(s) in %s", svc_name, len(targets), tg_arn)
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index b55a7be6..d857f1b7 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -38,7 +38,10 @@ from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import wait as futures_wait
from datetime import datetime, timezone
-import jsonata
+try:
+ import jsonata
+except ImportError: # the wheel is optional at runtime: JSONata states refuse
+ jsonata = None # cleanly instead of the whole service failing to load
from ministack.core.arn import ArnParseError, parse_arn
from ministack.core.concurrency import run_reentrant
@@ -311,10 +314,49 @@ async def handle_request(method, path, headers, body, query_params):
# State machine CRUD
# ---------------------------------------------------------------------------
+def _validate_definition_jsonata(definition_str) -> str | None:
+ """The first malformed ``{% ... %}`` expression's refusal, or None.
+
+ AWS rejects a definition carrying an unparsable JSONata expression at
+ CreateStateMachine/UpdateStateMachine time with InvalidDefinition and an
+ INVALID_JSONATA_EXPRESSION message naming the field's path — a typo never
+ reaches an execution. Parse only: evaluation errors stay runtime."""
+ if jsonata is None or not isinstance(definition_str, str):
+ return None
+ try:
+ definition = json.loads(definition_str)
+ except (TypeError, ValueError):
+ return None # JSON validity is judged by the existing checks
+
+ def walk(node, path):
+ if isinstance(node, dict):
+ for k, v in node.items():
+ found = walk(v, f"{path}/{k}")
+ if found:
+ return found
+ elif isinstance(node, list):
+ for i, v in enumerate(node):
+ found = walk(v, f"{path}/{i}")
+ if found:
+ return found
+ elif (isinstance(node, str) and node.startswith("{%")
+ and node.endswith("%}")):
+ try:
+ jsonata.Jsonata.jsonata(node[2:-2].strip())
+ except Exception as exc:
+ return f"INVALID_JSONATA_EXPRESSION: {exc}\n at {path or '/'}"
+ return None
+
+ return walk(definition, "")
+
+
def _create_state_machine(data):
name = data.get("name")
if not name:
return error_response_json("ValidationException", "name is required", 400)
+ invalid = _validate_definition_jsonata(data.get("definition"))
+ if invalid:
+ return error_response_json("InvalidDefinition", invalid, 400)
arn = f"arn:aws:states:{get_region()}:{get_account_id()}:stateMachine:{name}"
if arn in _state_machines:
@@ -482,6 +524,9 @@ def _update_state_machine(data):
"StateMachineDoesNotExist",
f"State machine {arn} not found", 400)
if "definition" in data:
+ invalid = _validate_definition_jsonata(data["definition"])
+ if invalid:
+ return error_response_json("InvalidDefinition", invalid, 400)
sm["definition"] = data["definition"]
if "roleArn" in data:
sm["roleArn"] = data["roleArn"]
@@ -2353,6 +2398,11 @@ def _evaluate_jsonata(expression, raw_input, ctx=None, result=None, error_output
# `$states.input`.
bindings = dict(ctx.get("variables", {}))
bindings["states"] = states
+ if jsonata is None:
+ raise _ExecutionError(
+ "States.QueryEvaluationError",
+ "JSONata support requires the jsonata-python package, which is "
+ "not installed in this build")
try:
expr = jsonata.Jsonata.jsonata(expression, timeout=1000)
_register_sfn_jsonata_functions(expr)
@@ -2360,7 +2410,12 @@ def _evaluate_jsonata(expression, raw_input, ctx=None, result=None, error_output
except _ExecutionError:
raise
except Exception as exc:
- raise _ExecutionError("States.QueryEvaluationError", str(exc))
+ # AWS's cause leads with the JSONata error code (T2010, D3030, ...).
+ # The engine keeps it in JException.error and leaves it out of the
+ # message, so it is prefixed here; a plain Python exception has none.
+ code = getattr(exc, "error", None)
+ message = f"{code}: {exc}" if isinstance(code, str) and code else str(exc)
+ raise _ExecutionError("States.QueryEvaluationError", message)
if value is None and not _jsonata_result_defined(expression, bindings):
# AWS raises on an expression that yields JSONata `undefined` (a missing
# field or unbound variable): "JSON cannot represent an undefined value
@@ -2391,6 +2446,11 @@ def _jsonata_result_defined(expression, bindings):
# States.* intrinsics available to JSONPath states. Per AWS, functions that
# take integer parameters round any non-integer argument down.
def _register_sfn_jsonata_functions(expr):
+ # Two base-engine functions are shadowed because jsonata-python returns a
+ # value where AWS (and jsonata-js) fail the evaluation; the shadows refuse
+ # exactly there and delegate everywhere else.
+ expr.register_lambda("toMillis", _sfn_jsonata_to_millis)
+ expr.register_lambda("replace", _sfn_jsonata_replace)
expr.register_lambda("partition", _sfn_jsonata_partition)
expr.register_lambda("range", _sfn_jsonata_range)
expr.register_lambda("hash", _sfn_jsonata_hash)
@@ -2399,6 +2459,34 @@ def _register_sfn_jsonata_functions(expr):
expr.register_lambda("parse", _sfn_jsonata_parse)
+def _sfn_jsonata_to_millis(timestamp=None, picture=None):
+ """`$toMillis` requiring a real ISO 8601 timestamp, as AWS does (D3110).
+
+ jsonata-python's parser also accepts a space-separated form; AWS refuses
+ it, so the space form and anything else the parser cannot read answer the
+ documented D3110 message."""
+ from jsonata import functions as _jsonata_functions
+ refusal = ValueError(
+ "D3110: The argument of the toMillis function must be an ISO 8601 "
+ f'formatted timestamp. Given "{timestamp}"')
+ if picture is None and isinstance(timestamp, str) and "T" not in timestamp:
+ raise refusal
+ try:
+ return _jsonata_functions.Functions.datetime_to_millis(timestamp, picture)
+ except ValueError:
+ raise refusal
+
+
+def _sfn_jsonata_replace(string=None, pattern=None, replacement=None, limit=None):
+ """`$replace` refusing a regex that can match nothing, as AWS does (D1004)."""
+ from jsonata import functions as _jsonata_functions
+ if hasattr(pattern, "search"):
+ m = pattern.search("")
+ if m is not None and m.group() == "":
+ raise ValueError("D1004: Regular expression matches zero length string")
+ return _jsonata_functions.Functions.replace(string, pattern, replacement, limit)
+
+
def _sfn_jsonata_partition(array, size):
"""`$partition(array, size)` -> array chunked into sub-arrays of `size`."""
size = math.floor(size)
diff --git a/pyproject.toml b/pyproject.toml
index 58113e59..b8230ca9 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.5.2"
+version = "1.5.3"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/test_ecs.py b/tests/test_ecs.py
index 22f53d9d..a2713c03 100644
--- a/tests/test_ecs.py
+++ b/tests/test_ecs.py
@@ -1690,3 +1690,62 @@ def test_ecs_sync_service_targets_does_not_publish_a_stale_view(monkeypatch):
final = sorted(t["Id"] for t in _alb._targets[tg_arn])
assert final == ["10.3.0.1"], f"a stale view was published: {final}"
+
+
+def test_ecs_service_reconcile_spares_foreign_targets(monkeypatch):
+ """A service withdraws only its own registrations: targets registered by
+ hand (or by another service sharing the group) survive its reconcile and
+ its deletion — real ECS deregisters only its own tasks."""
+ from ministack.services import alb as _alb
+ from ministack.services import ecs as _ecs
+
+ task_ip = "172.30.0.21"
+
+ class FakeContainer:
+ def __init__(self, cid):
+ self.id = cid
+ self.attrs = {"NetworkSettings": {"Networks": {"ministack_default": {"IPAddress": task_ip}}}}
+
+ def reload(self):
+ pass
+
+ class FakeContainers:
+ def __init__(self):
+ self.n = 0
+
+ def get(self, _name):
+ raise Exception("not found")
+
+ def list(self, *a, **k):
+ return []
+
+ def run(self, image, **kwargs):
+ self.n += 1
+ return FakeContainer(f"container-{self.n:012d}")
+
+ monkeypatch.setattr(_ecs, "_get_docker", lambda: SimpleNamespace(containers=FakeContainers()))
+
+ tg_arn = "arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/tg-shared/def456"
+ _alb._tgs[tg_arn] = {"TargetGroupArn": tg_arn, "Port": 80, "TargetType": "ip"}
+ # A registration the service does not own.
+ _alb._targets[tg_arn] = [{"Id": "10.9.9.9", "Port": 80}]
+
+ _ecs._register_task_definition({
+ "family": "lb-shared-td",
+ "networkMode": "awsvpc",
+ "containerDefinitions": [{"name": "web", "image": "busybox"}],
+ })
+ _ecs._create_service({
+ "cluster": "lb-shared-c",
+ "serviceName": "lb-shared-svc",
+ "taskDefinition": "lb-shared-td",
+ "desiredCount": 1,
+ "loadBalancers": [
+ {"targetGroupArn": tg_arn, "containerName": "web", "containerPort": 80},
+ ],
+ })
+ registered = sorted(t["Id"] for t in _alb._targets.get(tg_arn, []))
+ assert registered == ["10.9.9.9", task_ip], registered
+
+ _ecs._delete_service({"cluster": "lb-shared-c", "service": "lb-shared-svc", "force": True})
+ assert _alb._targets.get(tg_arn) == [{"Id": "10.9.9.9", "Port": 80}]
diff --git a/tests/test_iot_jobs.py b/tests/test_iot_jobs.py
index 5d05deea..5b627197 100644
--- a/tests/test_iot_jobs.py
+++ b/tests/test_iot_jobs.py
@@ -1233,3 +1233,450 @@ def test_iot_jobs_lists_do_not_paginate_and_return_no_token(iot_client):
assert "nextToken" not in executions
finally:
_cleanup(iot_client, jobs=[job_a, job_b], things=[thing])
+
+
+# ---------------------------------------------------------------------------
+# Jobs over MQTT: the reserved $aws/things/<t>/jobs/# bridge
+# ---------------------------------------------------------------------------
+from test_iot_data import _collect_shadow_frames # noqa: E402
+
+_DOCUMENT_OBJECT = json.loads(_DOCUMENT)
+
+
+def _frames_by_topic(received):
+ return {topic: json.loads(payload) for topic, payload in received}
+
+
+def _assert_epoch_seconds(value):
+ """Stamps must be whole epoch seconds — milliseconds are off by 1000x."""
+ assert isinstance(value, int)
+ assert abs(value - time.time()) < 5 * 60
+
+
+def test_jobs_mqtt_create_job_notifies_and_get_lists(iot_client, iot_data_client):
+ """CreateJob publishes notify (per-status aggregate) + notify-next (full
+ execution incl. the jobDocument as an object) to each target thing; a
+ publish on jobs/get answers get/accepted with the queued summary."""
+ thing = _unique("jobs-mqtt")
+ job_id = _unique("job")
+ thing_arn = _create_thing(iot_client, thing)
+ base = f"$aws/things/{thing}/jobs"
+
+ received = _collect_shadow_frames(
+ f"{base}/#",
+ lambda: iot_client.create_job(
+ jobId=job_id, targets=[thing_arn], document=_DOCUMENT
+ ),
+ want=2,
+ )
+ frames = _frames_by_topic(received)
+
+ notify = frames[f"{base}/notify"]
+ # Empty status lists are omitted: only QUEUED appears.
+ assert set(notify["jobs"]) == {"QUEUED"}
+ summary = notify["jobs"]["QUEUED"][0]
+ assert summary["jobId"] == job_id
+ _assert_epoch_seconds(notify["timestamp"])
+ _assert_epoch_seconds(summary["queuedAt"])
+ _assert_epoch_seconds(summary["lastUpdatedAt"])
+
+ nn = frames[f"{base}/notify-next"]
+ execution = nn["execution"]
+ assert execution["jobId"] == job_id
+ assert execution["status"] == "QUEUED"
+ # Over MQTT the job document is a JSON object (a string over HTTP).
+ assert execution["jobDocument"] == _DOCUMENT_OBJECT
+ _assert_epoch_seconds(nn["timestamp"])
+ _assert_epoch_seconds(execution["queuedAt"])
+
+ received = _collect_shadow_frames(
+ f"{base}/get/accepted",
+ lambda: iot_data_client.publish(
+ topic=f"{base}/get",
+ payload=json.dumps({"clientToken": "tok-get"}).encode(),
+ ),
+ want=1,
+ )
+ doc = _frames_by_topic(received)[f"{base}/get/accepted"]
+ assert doc["clientToken"] == "tok-get"
+ assert [q["jobId"] for q in doc["queuedJobs"]] == [job_id]
+ assert doc["inProgressJobs"] == []
+ _assert_epoch_seconds(doc["timestamp"])
+ _assert_epoch_seconds(doc["queuedJobs"][0]["queuedAt"])
+
+
+def test_jobs_mqtt_create_behind_existing_job_no_notify_next(
+ iot_client, iot_data_client
+):
+ """A job created behind an existing pending job changes the pending set
+ (notify) but not its front — no notify-next."""
+ thing = _unique("jobs-mqtt-2nd")
+ first_job = _unique("job")
+ second_job = _unique("job")
+ thing_arn = _create_thing(iot_client, thing)
+ base = f"$aws/things/{thing}/jobs"
+
+ # Drain the first job's own notify + notify-next before subscribing again.
+ _collect_shadow_frames(
+ f"{base}/#",
+ lambda: iot_client.create_job(
+ jobId=first_job, targets=[thing_arn], document=_DOCUMENT
+ ),
+ want=2,
+ )
+
+ received = _collect_shadow_frames(
+ f"{base}/#",
+ lambda: iot_client.create_job(
+ jobId=second_job, targets=[thing_arn], document=_DOCUMENT
+ ),
+ want=2,
+ timeout=3.0,
+ )
+ topics = [topic for topic, _ in received]
+ assert f"{base}/notify-next" not in topics
+ notify = _frames_by_topic(received)[f"{base}/notify"]
+ assert [s["jobId"] for s in notify["jobs"]["QUEUED"]] == [first_job, second_job]
+
+
+def test_jobs_mqtt_start_next_of_first_job_is_silent(iot_client, iot_data_client):
+ """start-next hands out the execution on start-next/accepted, but fires
+ NEITHER notify nor notify-next: QUEUED -> IN_PROGRESS keeps the execution
+ both pending and at the front of the queue (live-captured silence)."""
+ thing = _unique("jobs-mqtt-sn")
+ job_id = _unique("job")
+ thing_arn = _create_thing(iot_client, thing)
+ base = f"$aws/things/{thing}/jobs"
+ _collect_shadow_frames(
+ f"{base}/#",
+ lambda: iot_client.create_job(
+ jobId=job_id, targets=[thing_arn], document=_DOCUMENT
+ ),
+ want=2,
+ )
+
+ received = _collect_shadow_frames(
+ f"{base}/#",
+ lambda: iot_data_client.publish(
+ topic=f"{base}/start-next",
+ payload=json.dumps({"clientToken": "tok-sn"}).encode(),
+ ),
+ want=3, # request echo + accepted; a 3rd frame would be a bug
+ timeout=3.0,
+ )
+ topics = [topic for topic, _ in received]
+ assert f"{base}/notify" not in topics
+ assert f"{base}/notify-next" not in topics
+
+ doc = _frames_by_topic(received)[f"{base}/start-next/accepted"]
+ execution = doc["execution"]
+ assert execution["jobId"] == job_id
+ assert execution["status"] == "IN_PROGRESS"
+ assert execution["jobDocument"] == _DOCUMENT_OBJECT
+ assert execution["versionNumber"] == 2
+ _assert_epoch_seconds(doc["timestamp"])
+ _assert_epoch_seconds(execution["startedAt"])
+
+
+def test_jobs_mqtt_update_include_flags_and_terminal_notify(
+ iot_client, iot_data_client
+):
+ """update/accepted is minimal unless the include flags ask for more; a
+ terminal report then publishes accepted first, notify with the emptied
+ aggregate, and a bare notify-next (captured order)."""
+ thing = _unique("jobs-mqtt-rt")
+ job_id = _unique("job")
+ thing_arn = _create_thing(iot_client, thing)
+ base = f"$aws/things/{thing}/jobs"
+ _collect_shadow_frames(
+ f"{base}/#",
+ lambda: iot_client.create_job(
+ jobId=job_id, targets=[thing_arn], document=_DOCUMENT
+ ),
+ want=2,
+ )
+ _collect_shadow_frames(
+ f"{base}/start-next/accepted",
+ lambda: iot_data_client.publish(topic=f"{base}/start-next", payload=b"{}"),
+ want=1,
+ )
+
+ received = _collect_shadow_frames(
+ f"{base}/{job_id}/update/accepted",
+ lambda: iot_data_client.publish(
+ topic=f"{base}/{job_id}/update",
+ payload=json.dumps(
+ {
+ "status": "IN_PROGRESS",
+ "expectedVersion": 2,
+ "includeJobExecutionState": True,
+ "includeJobDocument": True,
+ "clientToken": "tok-up",
+ }
+ ).encode(),
+ ),
+ want=1,
+ )
+ doc = _frames_by_topic(received)[f"{base}/{job_id}/update/accepted"]
+ assert doc["executionState"]["status"] == "IN_PROGRESS"
+ assert doc["executionState"]["versionNumber"] == 3
+ assert doc["jobDocument"] == _DOCUMENT_OBJECT
+ assert doc["clientToken"] == "tok-up"
+
+ received = _collect_shadow_frames(
+ f"{base}/#",
+ lambda: iot_data_client.publish(
+ topic=f"{base}/{job_id}/update",
+ payload=json.dumps(
+ {
+ "status": "SUCCEEDED",
+ "expectedVersion": 3,
+ "clientToken": "tok-done",
+ }
+ ).encode(),
+ ),
+ want=4, # request echo + accepted + notify + notify-next
+ )
+ topics = [topic for topic, _ in received]
+ frames = _frames_by_topic(received)
+
+ # Without the include flags the terminal accepted carries nothing else
+ # (live capture: clientToken + timestamp only).
+ accepted = frames[f"{base}/{job_id}/update/accepted"]
+ assert set(accepted) == {"clientToken", "timestamp"}
+ assert accepted["clientToken"] == "tok-done"
+ _assert_epoch_seconds(accepted["timestamp"])
+
+ # The last pending job left the set: {} aggregate, bare notify-next.
+ notify = frames[f"{base}/notify"]
+ assert notify["jobs"] == {}
+ assert set(notify) == {"jobs", "timestamp"}
+ nn = frames[f"{base}/notify-next"]
+ assert set(nn) == {"timestamp"}
+
+ # accepted first, then notify, then notify-next — the captured order.
+ assert topics.index(f"{base}/{job_id}/update/accepted") < topics.index(
+ f"{base}/notify"
+ ) < topics.index(f"{base}/notify-next")
+
+
+def test_jobs_mqtt_version_mismatch_rejected(iot_client, iot_data_client):
+ """A stale expectedVersion answers update/rejected with the string
+ VersionMismatch code, the captured message wording, and the execution's
+ current state."""
+ thing = _unique("jobs-mqtt-ver")
+ job_id = _unique("job")
+ thing_arn = _create_thing(iot_client, thing)
+ iot_client.create_job(jobId=job_id, targets=[thing_arn], document=_DOCUMENT)
+ base = f"$aws/things/{thing}/jobs"
+
+ received = _collect_shadow_frames(
+ f"{base}/{job_id}/update/rejected",
+ lambda: iot_data_client.publish(
+ topic=f"{base}/{job_id}/update",
+ payload=json.dumps(
+ {
+ "status": "SUCCEEDED",
+ "expectedVersion": 99,
+ "clientToken": "tok-ver",
+ }
+ ).encode(),
+ ),
+ want=1,
+ )
+ doc = _frames_by_topic(received)[f"{base}/{job_id}/update/rejected"]
+ assert doc["code"] == "VersionMismatch"
+ assert doc["message"] == "Expected version 99 but found version 1"
+ assert doc["executionState"] == {"status": "QUEUED", "versionNumber": 1}
+ assert doc["clientToken"] == "tok-ver"
+ _assert_epoch_seconds(doc["timestamp"])
+
+
+def test_jobs_mqtt_update_unknown_job_rejected(iot_client, iot_data_client):
+ """An update for a job that does not exist answers update/rejected with
+ the string ResourceNotFound code — never a silent drop."""
+ thing = _unique("jobs-mqtt-rej")
+ _create_thing(iot_client, thing)
+ base = f"$aws/things/{thing}/jobs"
+
+ received = _collect_shadow_frames(
+ f"{base}/no-such-job/update/rejected",
+ lambda: iot_data_client.publish(
+ topic=f"{base}/no-such-job/update",
+ payload=json.dumps({"status": "SUCCEEDED", "clientToken": "tok-x"}).encode(),
+ ),
+ want=1,
+ )
+ doc = _frames_by_topic(received)[f"{base}/no-such-job/update/rejected"]
+ assert doc["code"] == "ResourceNotFound"
+ assert doc["clientToken"] == "tok-x"
+
+
+def test_jobs_mqtt_next_sentinel_get(iot_client, iot_data_client):
+ """``$next`` as the jobId on the get topic resolves the front of the
+ pending queue WITHOUT starting it — the documented MQTT counterpart of
+ the HTTP plane's DescribeJobExecution sentinel."""
+ thing = _unique("jobs-mqtt-next")
+ job_id = _unique("job")
+ thing_arn = _create_thing(iot_client, thing)
+ iot_client.create_job(jobId=job_id, targets=[thing_arn], document=_DOCUMENT)
+ base = f"$aws/things/{thing}/jobs"
+
+ received = _collect_shadow_frames(
+ f"{base}/$next/get/accepted",
+ lambda: iot_data_client.publish(
+ topic=f"{base}/$next/get",
+ payload=json.dumps({"clientToken": "tok-next"}).encode(),
+ ),
+ want=1,
+ )
+ doc = _frames_by_topic(received)[f"{base}/$next/get/accepted"]
+ execution = doc["execution"]
+ assert execution["jobId"] == job_id
+ assert execution["status"] == "QUEUED" # peeked, not started
+ assert execution["versionNumber"] == 1
+ assert execution["jobDocument"] == _DOCUMENT_OBJECT
+ assert doc["clientToken"] == "tok-next"
+
+ received = _collect_shadow_frames(
+ f"{base}/get/accepted",
+ lambda: iot_data_client.publish(topic=f"{base}/get", payload=b"{}"),
+ want=1,
+ )
+ doc = _frames_by_topic(received)[f"{base}/get/accepted"]
+ assert [q["jobId"] for q in doc["queuedJobs"]] == [job_id]
+ assert doc["inProgressJobs"] == []
+
+
+def test_jobs_mqtt_non_object_payload_rejected(iot_client, iot_data_client):
+ """A payload that parses as JSON but is not an object (an array, say) is
+ rejected with the InvalidJson code instead of being coerced to {}."""
+ thing = _unique("jobs-mqtt-json")
+ _create_thing(iot_client, thing)
+ base = f"$aws/things/{thing}/jobs"
+
+ received = _collect_shadow_frames(
+ f"{base}/get/rejected",
+ lambda: iot_data_client.publish(topic=f"{base}/get", payload=b"[1, 2]"),
+ want=1,
+ )
+ doc = _frames_by_topic(received)[f"{base}/get/rejected"]
+ assert doc["code"] == "InvalidJson"
+ _assert_epoch_seconds(doc["timestamp"])
+
+
+def _qa_publish(iot_data_client, topic, payload):
+ iot_data_client.publish(topic=topic, qos=1, payload=payload)
+
+
+def test_jobs_mqtt_malformed_json_is_rejected_invalidjson(iot_client, iot_data_client):
+ thing = _unique("qa-bad-json")
+ _create_thing(iot_client, thing)
+ base = f"$aws/things/{thing}/jobs"
+ received = _collect_shadow_frames(
+ f"{base}/get/rejected",
+ lambda: _qa_publish(iot_data_client, f"{base}/get", b"{not json"),
+ want=1,
+ )
+ doc = json.loads(received[0][1])
+ assert doc["code"] == "InvalidJson"
+ assert isinstance(doc["timestamp"], int)
+
+
+def test_jobs_mqtt_terminal_update_rejected_terminalstatereached(iot_client, iot_data_client):
+ thing = _unique("qa-terminal")
+ job_id = _unique("job")
+ arn = _create_thing(iot_client, thing)
+ iot_client.create_job(jobId=job_id, targets=[arn], document=_DOCUMENT)
+ base = f"$aws/things/{thing}/jobs"
+ _collect_shadow_frames(
+ f"{base}/{job_id}/update/accepted",
+ lambda: _qa_publish(iot_data_client, f"{base}/{job_id}/update",
+ json.dumps({"status": "SUCCEEDED"}).encode()),
+ want=1,
+ )
+ received = _collect_shadow_frames(
+ f"{base}/{job_id}/update/rejected",
+ lambda: _qa_publish(iot_data_client, f"{base}/{job_id}/update",
+ json.dumps({"status": "FAILED"}).encode()),
+ want=1,
+ )
+ assert json.loads(received[0][1])["code"] == "TerminalStateReached"
+
+
+def test_jobs_mqtt_wrong_version_carries_execution_state(iot_client, iot_data_client):
+ thing = _unique("qa-version")
+ job_id = _unique("job")
+ arn = _create_thing(iot_client, thing)
+ iot_client.create_job(jobId=job_id, targets=[arn], document=_DOCUMENT)
+ base = f"$aws/things/{thing}/jobs"
+ received = _collect_shadow_frames(
+ f"{base}/{job_id}/update/rejected",
+ lambda: _qa_publish(iot_data_client, f"{base}/{job_id}/update",
+ json.dumps({"status": "IN_PROGRESS",
+ "expectedVersion": 99,
+ "clientToken": "qa-1"}).encode()),
+ want=1,
+ )
+ doc = json.loads(received[0][1])
+ assert doc["code"] == "VersionMismatch"
+ assert doc["clientToken"] == "qa-1"
+ assert set(doc["executionState"]) == {"status", "versionNumber"}
+
+
+def test_jobs_mqtt_job_named_get_does_not_break_thing_level_get(iot_client, iot_data_client):
+ thing = _unique("qa-collide")
+ arn = _create_thing(iot_client, thing)
+ iot_client.create_job(jobId="get", targets=[arn], document=_DOCUMENT)
+ try:
+ base = f"$aws/things/{thing}/jobs"
+ received = _collect_shadow_frames(
+ f"{base}/get/accepted",
+ lambda: _qa_publish(iot_data_client, f"{base}/get", b"{}"),
+ want=1,
+ )
+ doc = json.loads(received[0][1])
+ assert [s["jobId"] for s in doc["queuedJobs"]] == ["get"]
+ finally:
+ iot_client.delete_job(jobId="get", force=True)
+
+
+def test_jobs_mqtt_next_get_on_idle_thing_answers_bare_timestamp(iot_client, iot_data_client):
+ thing = _unique("qa-idle")
+ _create_thing(iot_client, thing)
+ base = f"$aws/things/{thing}/jobs"
+ received = _collect_shadow_frames(
+ f"{base}/$next/get/accepted",
+ lambda: _qa_publish(iot_data_client, f"{base}/$next/get",
+ json.dumps({"clientToken": "t0"}).encode()),
+ want=1,
+ )
+ doc = json.loads(received[0][1])
+ assert "execution" not in doc
+ assert doc["clientToken"] == "t0"
+
+
+def test_jobs_mqtt_start_next_twice_rehands_in_progress_silently(iot_client, iot_data_client):
+ thing = _unique("qa-rehand")
+ job_id = _unique("job")
+ arn = _create_thing(iot_client, thing)
+ iot_client.create_job(jobId=job_id, targets=[arn], document=_DOCUMENT)
+ base = f"$aws/things/{thing}/jobs"
+ first = _collect_shadow_frames(
+ f"{base}/start-next/accepted",
+ lambda: _qa_publish(iot_data_client, f"{base}/start-next",
+ json.dumps({"statusDetails": {"step": "a"}}).encode()),
+ want=1,
+ )
+ d1 = json.loads(first[0][1])["execution"]
+ assert d1["status"] == "IN_PROGRESS" and d1["statusDetails"] == {"step": "a"}
+ second = _collect_shadow_frames(
+ f"{base}/start-next/accepted",
+ lambda: _qa_publish(iot_data_client, f"{base}/start-next",
+ json.dumps({"statusDetails": {"step": "b"}}).encode()),
+ want=1,
+ )
+ d2 = json.loads(second[0][1])["execution"]
+ assert d2["status"] == "IN_PROGRESS"
+ assert d2["statusDetails"] == {"step": "a"}
+ assert d2["versionNumber"] == d1["versionNumber"]
diff --git a/tests/test_iot_jobs_mqtt.py b/tests/test_iot_jobs_mqtt.py
deleted file mode 100644
index d0f53757..00000000
--- a/tests/test_iot_jobs_mqtt.py
+++ /dev/null
@@ -1,341 +0,0 @@
-"""IoT Jobs over MQTT: the reserved ``$aws/things/<t>/jobs/#`` bridge.
-
-Request/response round-trips ride the same WS collector the shadow-bridge
-tests use; the notify/notify-next state-change publishes are asserted around
-control-plane CreateJob and data-plane terminal updates. The contract under
-test is the one captured against live AWS: every timestamp — envelope and
-execution fields alike — is whole epoch seconds, ``jobDocument`` is a JSON
-object over MQTT, rejections carry the string ErrorCode enum, ``notify``
-fires only when the pending set's membership changes, and ``notify-next``
-only when the job at the front of the queue changes.
-"""
-
-import json
-import time
-
-from test_iot_data import _collect_shadow_frames
-from test_iot_jobs import _DOCUMENT, _create_thing, _unique
-
-_DOCUMENT_OBJECT = json.loads(_DOCUMENT)
-
-
-def _frames_by_topic(received):
- return {topic: json.loads(payload) for topic, payload in received}
-
-
-def _assert_epoch_seconds(value):
- """Stamps must be whole epoch seconds — milliseconds are off by 1000x."""
- assert isinstance(value, int)
- assert abs(value - time.time()) < 5 * 60
-
-
-def test_jobs_mqtt_create_job_notifies_and_get_lists(iot_client, iot_data_client):
- """CreateJob publishes notify (per-status aggregate) + notify-next (full
- execution incl. the jobDocument as an object) to each target thing; a
- publish on jobs/get answers get/accepted with the queued summary."""
- thing = _unique("jobs-mqtt")
- job_id = _unique("job")
- thing_arn = _create_thing(iot_client, thing)
- base = f"$aws/things/{thing}/jobs"
-
- received = _collect_shadow_frames(
- f"{base}/#",
- lambda: iot_client.create_job(
- jobId=job_id, targets=[thing_arn], document=_DOCUMENT
- ),
- want=2,
- )
- frames = _frames_by_topic(received)
-
- notify = frames[f"{base}/notify"]
- # Empty status lists are omitted: only QUEUED appears.
- assert set(notify["jobs"]) == {"QUEUED"}
- summary = notify["jobs"]["QUEUED"][0]
- assert summary["jobId"] == job_id
- _assert_epoch_seconds(notify["timestamp"])
- _assert_epoch_seconds(summary["queuedAt"])
- _assert_epoch_seconds(summary["lastUpdatedAt"])
-
- nn = frames[f"{base}/notify-next"]
- execution = nn["execution"]
- assert execution["jobId"] == job_id
- assert execution["status"] == "QUEUED"
- # Over MQTT the job document is a JSON object (a string over HTTP).
- assert execution["jobDocument"] == _DOCUMENT_OBJECT
- _assert_epoch_seconds(nn["timestamp"])
- _assert_epoch_seconds(execution["queuedAt"])
-
- received = _collect_shadow_frames(
- f"{base}/get/accepted",
- lambda: iot_data_client.publish(
- topic=f"{base}/get",
- payload=json.dumps({"clientToken": "tok-get"}).encode(),
- ),
- want=1,
- )
- doc = _frames_by_topic(received)[f"{base}/get/accepted"]
- assert doc["clientToken"] == "tok-get"
- assert [q["jobId"] for q in doc["queuedJobs"]] == [job_id]
- assert doc["inProgressJobs"] == []
- _assert_epoch_seconds(doc["timestamp"])
- _assert_epoch_seconds(doc["queuedJobs"][0]["queuedAt"])
-
-
-def test_jobs_mqtt_create_behind_existing_job_no_notify_next(
- iot_client, iot_data_client
-):
- """A job created behind an existing pending job changes the pending set
- (notify) but not its front — no notify-next."""
- thing = _unique("jobs-mqtt-2nd")
- first_job = _unique("job")
- second_job = _unique("job")
- thing_arn = _create_thing(iot_client, thing)
- base = f"$aws/things/{thing}/jobs"
-
- # Drain the first job's own notify + notify-next before subscribing again.
- _collect_shadow_frames(
- f"{base}/#",
- lambda: iot_client.create_job(
- jobId=first_job, targets=[thing_arn], document=_DOCUMENT
- ),
- want=2,
- )
-
- received = _collect_shadow_frames(
- f"{base}/#",
- lambda: iot_client.create_job(
- jobId=second_job, targets=[thing_arn], document=_DOCUMENT
- ),
- want=2,
- timeout=3.0,
- )
- topics = [topic for topic, _ in received]
- assert f"{base}/notify-next" not in topics
- notify = _frames_by_topic(received)[f"{base}/notify"]
- assert [s["jobId"] for s in notify["jobs"]["QUEUED"]] == [first_job, second_job]
-
-
-def test_jobs_mqtt_start_next_of_first_job_is_silent(iot_client, iot_data_client):
- """start-next hands out the execution on start-next/accepted, but fires
- NEITHER notify nor notify-next: QUEUED -> IN_PROGRESS keeps the execution
- both pending and at the front of the queue (live-captured silence)."""
- thing = _unique("jobs-mqtt-sn")
- job_id = _unique("job")
- thing_arn = _create_thing(iot_client, thing)
- base = f"$aws/things/{thing}/jobs"
- _collect_shadow_frames(
- f"{base}/#",
- lambda: iot_client.create_job(
- jobId=job_id, targets=[thing_arn], document=_DOCUMENT
- ),
- want=2,
- )
-
- received = _collect_shadow_frames(
- f"{base}/#",
- lambda: iot_data_client.publish(
- topic=f"{base}/start-next",
- payload=json.dumps({"clientToken": "tok-sn"}).encode(),
- ),
- want=3, # request echo + accepted; a 3rd frame would be a bug
- timeout=3.0,
- )
- topics = [topic for topic, _ in received]
- assert f"{base}/notify" not in topics
- assert f"{base}/notify-next" not in topics
-
- doc = _frames_by_topic(received)[f"{base}/start-next/accepted"]
- execution = doc["execution"]
- assert execution["jobId"] == job_id
- assert execution["status"] == "IN_PROGRESS"
- assert execution["jobDocument"] == _DOCUMENT_OBJECT
- assert execution["versionNumber"] == 2
- _assert_epoch_seconds(doc["timestamp"])
- _assert_epoch_seconds(execution["startedAt"])
-
-
-def test_jobs_mqtt_update_include_flags_and_terminal_notify(
- iot_client, iot_data_client
-):
- """update/accepted is minimal unless the include flags ask for more; a
- terminal report then publishes accepted first, notify with the emptied
- aggregate, and a bare notify-next (captured order)."""
- thing = _unique("jobs-mqtt-rt")
- job_id = _unique("job")
- thing_arn = _create_thing(iot_client, thing)
- base = f"$aws/things/{thing}/jobs"
- _collect_shadow_frames(
- f"{base}/#",
- lambda: iot_client.create_job(
- jobId=job_id, targets=[thing_arn], document=_DOCUMENT
- ),
- want=2,
- )
- _collect_shadow_frames(
- f"{base}/start-next/accepted",
- lambda: iot_data_client.publish(topic=f"{base}/start-next", payload=b"{}"),
- want=1,
- )
-
- received = _collect_shadow_frames(
- f"{base}/{job_id}/update/accepted",
- lambda: iot_data_client.publish(
- topic=f"{base}/{job_id}/update",
- payload=json.dumps(
- {
- "status": "IN_PROGRESS",
- "expectedVersion": 2,
- "includeJobExecutionState": True,
- "includeJobDocument": True,
- "clientToken": "tok-up",
- }
- ).encode(),
- ),
- want=1,
- )
- doc = _frames_by_topic(received)[f"{base}/{job_id}/update/accepted"]
- assert doc["executionState"]["status"] == "IN_PROGRESS"
- assert doc["executionState"]["versionNumber"] == 3
- assert doc["jobDocument"] == _DOCUMENT_OBJECT
- assert doc["clientToken"] == "tok-up"
-
- received = _collect_shadow_frames(
- f"{base}/#",
- lambda: iot_data_client.publish(
- topic=f"{base}/{job_id}/update",
- payload=json.dumps(
- {
- "status": "SUCCEEDED",
- "expectedVersion": 3,
- "clientToken": "tok-done",
- }
- ).encode(),
- ),
- want=4, # request echo + accepted + notify + notify-next
- )
- topics = [topic for topic, _ in received]
- frames = _frames_by_topic(received)
-
- # Without the include flags the terminal accepted carries nothing else
- # (live capture: clientToken + timestamp only).
- accepted = frames[f"{base}/{job_id}/update/accepted"]
- assert set(accepted) == {"clientToken", "timestamp"}
- assert accepted["clientToken"] == "tok-done"
- _assert_epoch_seconds(accepted["timestamp"])
-
- # The last pending job left the set: {} aggregate, bare notify-next.
- notify = frames[f"{base}/notify"]
- assert notify["jobs"] == {}
- assert set(notify) == {"jobs", "timestamp"}
- nn = frames[f"{base}/notify-next"]
- assert set(nn) == {"timestamp"}
-
- # accepted first, then notify, then notify-next — the captured order.
- assert topics.index(f"{base}/{job_id}/update/accepted") < topics.index(
- f"{base}/notify"
- ) < topics.index(f"{base}/notify-next")
-
-
-def test_jobs_mqtt_version_mismatch_rejected(iot_client, iot_data_client):
- """A stale expectedVersion answers update/rejected with the string
- VersionMismatch code, the captured message wording, and the execution's
- current state."""
- thing = _unique("jobs-mqtt-ver")
- job_id = _unique("job")
- thing_arn = _create_thing(iot_client, thing)
- iot_client.create_job(jobId=job_id, targets=[thing_arn], document=_DOCUMENT)
- base = f"$aws/things/{thing}/jobs"
-
- received = _collect_shadow_frames(
- f"{base}/{job_id}/update/rejected",
- lambda: iot_data_client.publish(
- topic=f"{base}/{job_id}/update",
- payload=json.dumps(
- {
- "status": "SUCCEEDED",
- "expectedVersion": 99,
- "clientToken": "tok-ver",
- }
- ).encode(),
- ),
- want=1,
- )
- doc = _frames_by_topic(received)[f"{base}/{job_id}/update/rejected"]
- assert doc["code"] == "VersionMismatch"
- assert doc["message"] == "Expected version 99 but found version 1"
- assert doc["executionState"] == {"status": "QUEUED", "versionNumber": 1}
- assert doc["clientToken"] == "tok-ver"
- _assert_epoch_seconds(doc["timestamp"])
-
-
-def test_jobs_mqtt_update_unknown_job_rejected(iot_client, iot_data_client):
- """An update for a job that does not exist answers update/rejected with
- the string ResourceNotFound code — never a silent drop."""
- thing = _unique("jobs-mqtt-rej")
- _create_thing(iot_client, thing)
- base = f"$aws/things/{thing}/jobs"
-
- received = _collect_shadow_frames(
- f"{base}/no-such-job/update/rejected",
- lambda: iot_data_client.publish(
- topic=f"{base}/no-such-job/update",
- payload=json.dumps({"status": "SUCCEEDED", "clientToken": "tok-x"}).encode(),
- ),
- want=1,
- )
- doc = _frames_by_topic(received)[f"{base}/no-such-job/update/rejected"]
- assert doc["code"] == "ResourceNotFound"
- assert doc["clientToken"] == "tok-x"
-
-
-def test_jobs_mqtt_next_sentinel_get(iot_client, iot_data_client):
- """``$next`` as the jobId on the get topic resolves the front of the
- pending queue WITHOUT starting it — the documented MQTT counterpart of
- the HTTP plane's DescribeJobExecution sentinel."""
- thing = _unique("jobs-mqtt-next")
- job_id = _unique("job")
- thing_arn = _create_thing(iot_client, thing)
- iot_client.create_job(jobId=job_id, targets=[thing_arn], document=_DOCUMENT)
- base = f"$aws/things/{thing}/jobs"
-
- received = _collect_shadow_frames(
- f"{base}/$next/get/accepted",
- lambda: iot_data_client.publish(
- topic=f"{base}/$next/get",
- payload=json.dumps({"clientToken": "tok-next"}).encode(),
- ),
- want=1,
- )
- doc = _frames_by_topic(received)[f"{base}/$next/get/accepted"]
- execution = doc["execution"]
- assert execution["jobId"] == job_id
- assert execution["status"] == "QUEUED" # peeked, not started
- assert execution["versionNumber"] == 1
- assert execution["jobDocument"] == _DOCUMENT_OBJECT
- assert doc["clientToken"] == "tok-next"
-
- received = _collect_shadow_frames(
- f"{base}/get/accepted",
- lambda: iot_data_client.publish(topic=f"{base}/get", payload=b"{}"),
- want=1,
- )
- doc = _frames_by_topic(received)[f"{base}/get/accepted"]
- assert [q["jobId"] for q in doc["queuedJobs"]] == [job_id]
- assert doc["inProgressJobs"] == []
-
-
-def test_jobs_mqtt_non_object_payload_rejected(iot_client, iot_data_client):
- """A payload that parses as JSON but is not an object (an array, say) is
- rejected with the InvalidJson code instead of being coerced to {}."""
- thing = _unique("jobs-mqtt-json")
- _create_thing(iot_client, thing)
- base = f"$aws/things/{thing}/jobs"
-
- received = _collect_shadow_frames(
- f"{base}/get/rejected",
- lambda: iot_data_client.publish(topic=f"{base}/get", payload=b"[1, 2]"),
- want=1,
- )
- doc = _frames_by_topic(received)[f"{base}/get/rejected"]
- assert doc["code"] == "InvalidJson"
- _assert_epoch_seconds(doc["timestamp"])
diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.py
index ab108940..9a52c8bb 100644
--- a/tests/test_stepfunctions.py
+++ b/tests/test_stepfunctions.py
@@ -7966,3 +7966,100 @@ def test_sfn_sync_execution_emits_no_status_events(sfn_sync, sfn, eb, sqs):
eb.remove_targets(Rule=rule, Ids=["t1"])
eb.delete_rule(Name=rule)
sqs.delete_queue(QueueUrl=q_url)
+
+
+# ---------------------------------------------------------------------------
+# JSONata: definition-time validation and AWS-parity failures
+# ---------------------------------------------------------------------------
+
+def _jsonata_pass_machine(expr):
+ return json.dumps({
+ "QueryLanguage": "JSONata",
+ "StartAt": "Eval",
+ "States": {"Eval": {"Type": "Pass", "Output": {"v": "{% " + expr + " %}"},
+ "End": True}},
+ })
+
+
+def _jsonata_eval(sfn, name, expr, wait=5.0):
+ """Run one JSONata expression through a Pass state; (status, cause)."""
+ sm_arn = sfn.create_state_machine(
+ name=name, definition=_jsonata_pass_machine(expr),
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )["stateMachineArn"]
+ try:
+ exec_arn = sfn.start_execution(stateMachineArn=sm_arn)["executionArn"]
+ deadline = time.time() + wait
+ while time.time() < deadline:
+ desc = sfn.describe_execution(executionArn=exec_arn)
+ if desc["status"] != "RUNNING":
+ break
+ time.sleep(0.1)
+ events = sfn.get_execution_history(executionArn=exec_arn)["events"]
+ cause = ""
+ for e in events:
+ details = e.get("executionFailedEventDetails")
+ if details:
+ cause = details.get("cause", "")
+ return desc["status"], cause
+ finally:
+ sfn.delete_state_machine(stateMachineArn=sm_arn)
+
+
+def test_sfn_jsonata_syntax_error_rejected_at_definition_time(sfn):
+ """AWS refuses a malformed JSONata expression at CreateStateMachine, not
+ at run time, with INVALID_JSONATA_EXPRESSION naming the field's path."""
+ from botocore.exceptions import ClientError
+ with pytest.raises(ClientError) as exc:
+ sfn.create_state_machine(
+ name="qa-jsonata-invalid", definition=_jsonata_pass_machine("[1,2)"),
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ err = exc.value.response["Error"]
+ assert err["Code"] == "InvalidDefinition"
+ assert "INVALID_JSONATA_EXPRESSION" in err["Message"]
+ assert "/States/Eval/Output/v" in err["Message"]
+
+
+def test_sfn_jsonata_cause_carries_the_error_code(sfn):
+ """The evaluation cause leads with the JSONata error code, as AWS's does."""
+ status, cause = _jsonata_eval(sfn, "qa-jsonata-t2010", "null <= \"world\"")
+ assert status == "FAILED"
+ assert "T2010:" in cause, cause
+
+
+def test_sfn_jsonata_tomillis_requires_iso8601(sfn):
+ """A space-separated timestamp draws D3110, as on AWS, instead of a value."""
+ status, cause = _jsonata_eval(
+ sfn, "qa-jsonata-d3110", "$toMillis(\"2018-02-03 11:15:33\")")
+ assert status == "FAILED"
+ assert "D3110" in cause, cause
+
+
+def test_sfn_jsonata_replace_refuses_zero_length_regex(sfn):
+ """A regex that can match nothing draws D1004, as on AWS."""
+ status, cause = _jsonata_eval(
+ sfn, "qa-jsonata-d1004", "$replace(\"abracadabra\", /.*?/, \"x\")")
+ assert status == "FAILED"
+ assert "D1004" in cause, cause
+
+
+def test_sfn_jsonata_tomillis_still_parses_iso(sfn):
+ """The strictness must not break a well-formed timestamp."""
+ sm = sfn.create_state_machine(
+ name="qa-jsonata-iso-ok",
+ definition=_jsonata_pass_machine("$toMillis(\"2020-01-01T00:00:00Z\")"),
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )["stateMachineArn"]
+ try:
+ exec_arn = sfn.start_execution(stateMachineArn=sm)["executionArn"]
+ deadline = time.time() + 5
+ while time.time() < deadline:
+ desc = sfn.describe_execution(executionArn=exec_arn)
+ if desc["status"] != "RUNNING":
+ break
+ time.sleep(0.1)
+ assert desc["status"] == "SUCCEEDED"
+ assert json.loads(desc["output"]) == {"v": 1577836800000}
+ finally:
+ sfn.delete_state_machine(stateMachineArn=sm)