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
fix(sfn): status change (#1553)
Nahuel Nucerafbac4eaa6be1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6dfbe9fe..8e170109 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,11 @@ 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]++### Fixed+- **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.+## [1.5.2] — 2026-08-26### Addeddiff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.pyindex 838e452d..b55a7be6 100644--- a/ministack/services/stepfunctions.py+++ b/ministack/services/stepfunctions.py@@ -631,6 +631,8 @@ def _start_execution(data):# this snapshot the worker runs under the default scope and silently# fails to find the execution stored under the caller's account and# region. See issue #639.+ _emit_execution_status_event(_executions[exec_arn])+ctx_snapshot = contextvars.copy_context()threading.Thread(target=ctx_snapshot.run,@@ -662,6 +664,7 @@ def _stop_execution(data):"cause": data.get("cause", ""),},})+ _emit_execution_status_event(execution)return json_response({"stopDate": stop_date})@@ -776,6 +779,9 @@ def _start_sync_execution(data):"input": input_str, "roleArn": sm["roleArn"]}},],}+ # StartSyncExecution is the express-flavored path: express workflows emit+ # no EventBridge status events on AWS, so the emitter skips this record.+ _executions[exec_arn]["sync"] = True_run_execution(exec_arn)@@ -1274,6 +1280,84 @@ class _ExecutionError(Exception):super().__init__(f"{error}: {cause}")+def _iso_to_epoch_ms(iso):+ """AWS's ISO record stamp -> the epoch-millisecond integer the status+ event carries (the documented payloads show 13-digit values)."""+ if not iso:+ return None+ try:+ dt = datetime.fromisoformat(iso.replace("Z", "+00:00"))+ except ValueError:+ return None+ return int(dt.timestamp() * 1000)+++# The status event excludes an input/output whose escaped form exceeds 248 KiB+# (an EventBridge quota Step Functions documents for these events); the+# inputDetails/outputDetails "included" flag reports the exclusion.+_STATUS_EVENT_PAYLOAD_CAP = 248 * 1024+++def _emit_execution_status_event(execution) -> None:+ """Publish "Step Functions Execution Status Change" to the default bus.++ Standard-workflow executions emit this automatically on AWS at every+ status change (source aws.states): it is how consumers track a run+ without polling DescribeExecution. Delivery is best-effort there, so a+ publish failure is logged and never fails the execution. Sync-started+ executions (the express-flavored path) emit nothing, as on AWS.+ """+ if execution.get("sync"):+ return+ status = execution["status"]+ failed = status == "FAILED"+ redrivable = failed # TIMED_OUT is never set locally; FAILED is the one+ detail = {+ "executionArn": execution["executionArn"],+ "stateMachineArn": execution["stateMachineArn"],+ "name": execution["name"],+ "status": status,+ "startDate": _iso_to_epoch_ms(execution.get("startDate")),+ "stopDate": _iso_to_epoch_ms(execution.get("stopDate")),+ "input": execution.get("input"),+ "inputDetails": {"included": True},+ # The documented payloads carry the output only on SUCCEEDED; a failed+ # record's local output (the Error/Cause document) stays off the event.+ "output": execution.get("output") if status == "SUCCEEDED" else None,+ "outputDetails": {"included": True} if status == "SUCCEEDED" else None,+ "stateMachineVersionArn": None,+ "stateMachineAliasArn": None,+ "redriveCount": 0,+ "redriveDate": None,+ "redriveStatus": "REDRIVABLE" if redrivable else "NOT_REDRIVABLE",+ "redriveStatusReason": (+ f"Execution is {status} and is redrivable" if redrivable+ else f"Execution is {status} and cannot be redriven"+ ),+ "error": execution.get("error") if failed else None,+ "cause": execution.get("cause") if failed else None,+ }+ if detail["input"] is not None and len(detail["input"]) > _STATUS_EVENT_PAYLOAD_CAP:+ detail["input"] = None+ detail["inputDetails"] = {"included": False}+ if detail["output"] is not None and len(detail["output"]) > _STATUS_EVENT_PAYLOAD_CAP:+ detail["output"] = None+ detail["outputDetails"] = {"included": False}+ try:+ from ministack.services import eventbridge+ eventbridge._put_events({+ "Entries": [{+ "Source": "aws.states",+ "DetailType": "Step Functions Execution Status Change",+ "Detail": json.dumps(detail),+ "Resources": [execution["executionArn"]],+ }]+ })+ except Exception:+ logger.warning("Failed to publish execution status event for %s",+ execution["executionArn"], exc_info=True)++def _run_execution(exec_arn):"""Background thread: walk the ASL definition to completion."""execution = _executions.get(exec_arn)@@ -1397,6 +1481,7 @@ def _run_execution(exec_arn):_add_event(execution, "ExecutionSucceeded", {"executionSucceededEventDetails": {"output": output_json},})+ _emit_execution_status_event(execution)except _ExecutionError as err:_fail_execution(execution, err.error, err.cause)@@ -1414,6 +1499,7 @@ def _fail_execution(execution, error, cause):_add_event(execution, "ExecutionFailed", {"executionFailedEventDetails": {"error": error, "cause": cause},})+ _emit_execution_status_event(execution)# ---------------------------------------------------------------------------diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.pyindex 3eadafb3..ab108940 100644--- a/tests/test_stepfunctions.py+++ b/tests/test_stepfunctions.py@@ -7818,3 +7818,151 @@ def test_concurrent_sync_executions_do_not_block_the_loop(sfn, sfn_sync):probe.assert_responsive("sync execution burst")assert all(s == "SUCCEEDED" for s in statuses), f"sync executions returned {set(statuses)}"+++# ---------------------------------------------------------------------------+# Execution status change events (EventBridge)+# ---------------------------------------------------------------------------++def _drain_queue(sqs, q_url, want, tries=20):+ """Collect up to `want` messages, polling briefly."""+ got = []+ for _ in range(tries):+ resp = sqs.receive_message(+ QueueUrl=q_url, MaxNumberOfMessages=10, WaitTimeSeconds=1+ )+ for m in resp.get("Messages", []):+ got.append(m)+ sqs.delete_message(QueueUrl=q_url, ReceiptHandle=m["ReceiptHandle"])+ if len(got) >= want:+ break+ return got+++def _status_event_rule(eb, sqs, slug):+ q_url = sqs.create_queue(QueueName=f"qa-sfn-evt-{slug}")["QueueUrl"]+ q_arn = sqs.get_queue_attributes(+ QueueUrl=q_url, AttributeNames=["QueueArn"]+ )["Attributes"]["QueueArn"]+ eb.put_rule(+ Name=f"qa-sfn-evt-{slug}",+ EventPattern=json.dumps({+ "source": ["aws.states"],+ "detail-type": ["Step Functions Execution Status Change"],+ }),+ State="ENABLED",+ )+ eb.put_targets(+ Rule=f"qa-sfn-evt-{slug}", Targets=[{"Id": "t1", "Arn": q_arn}]+ )+ return q_url, f"qa-sfn-evt-{slug}"+++def test_sfn_execution_emits_status_change_events(sfn, eb, sqs):+ """A standard execution publishes aws.states / "Step Functions Execution+ Status Change" to the default bus on start (RUNNING) and completion+ (SUCCEEDED), with the documented detail fields and epoch-ms dates."""+ q_url, rule = _status_event_rule(eb, sqs, "ok")+ sm_arn = sfn.create_state_machine(+ name="qa-evt-ok",+ definition=json.dumps(+ {"StartAt": "Done", "States": {"Done": {"Type": "Succeed"}}}+ ),+ roleArn="arn:aws:iam::000000000000:role/R",+ )["stateMachineArn"]+ try:+ exec_arn = sfn.start_execution(+ stateMachineArn=sm_arn, input='{"a": 1}'+ )["executionArn"]+ msgs = _drain_queue(sqs, q_url, want=2)+ details = []+ for m in msgs:+ env = json.loads(m["Body"])+ assert env["source"] == "aws.states"+ assert env["detail-type"] == "Step Functions Execution Status Change"+ assert env["resources"] == [exec_arn]+ details.append(env["detail"])+ statuses = {d["status"] for d in details}+ assert statuses == {"RUNNING", "SUCCEEDED"}+ for d in details:+ assert d["executionArn"] == exec_arn+ assert d["stateMachineArn"] == sm_arn+ assert isinstance(d["startDate"], int) and d["startDate"] > 10**12+ assert d["input"] == '{"a": 1}'+ assert d["inputDetails"] == {"included": True}+ assert d["redriveStatus"] == "NOT_REDRIVABLE"+ running = next(d for d in details if d["status"] == "RUNNING")+ assert running["stopDate"] is None+ assert running["output"] is None and running["outputDetails"] is None+ done = next(d for d in details if d["status"] == "SUCCEEDED")+ assert isinstance(d["stopDate"], int)+ assert json.loads(done["output"]) == {"a": 1}+ assert done["outputDetails"] == {"included": True}+ finally:+ sfn.delete_state_machine(stateMachineArn=sm_arn)+ eb.remove_targets(Rule=rule, Ids=["t1"])+ eb.delete_rule(Name=rule)+ sqs.delete_queue(QueueUrl=q_url)+++def test_sfn_failed_and_aborted_executions_emit_status_events(sfn, eb, sqs):+ """FAILED carries error/cause and reports REDRIVABLE; a StopExecution+ lands ABORTED with error/cause null, per the documented payloads."""+ q_url, rule = _status_event_rule(eb, sqs, "failstop")+ fail_arn = sfn.create_state_machine(+ name="qa-evt-fail",+ definition=json.dumps({"StartAt": "Boom", "States": {+ "Boom": {"Type": "Fail", "Error": "Kaput", "Cause": "went wrong"}+ }}),+ roleArn="arn:aws:iam::000000000000:role/R",+ )["stateMachineArn"]+ wait_arn = sfn.create_state_machine(+ name="qa-evt-wait",+ definition=json.dumps({"StartAt": "W", "States": {+ "W": {"Type": "Wait", "Seconds": 30, "End": True}+ }}),+ roleArn="arn:aws:iam::000000000000:role/R",+ )["stateMachineArn"]+ try:+ sfn.start_execution(stateMachineArn=fail_arn)+ waiting = sfn.start_execution(stateMachineArn=wait_arn)["executionArn"]+ time.sleep(0.5)+ sfn.stop_execution(executionArn=waiting)+ msgs = _drain_queue(sqs, q_url, want=4)+ details = [json.loads(m["Body"])["detail"] for m in msgs]+ failed = next(d for d in details if d["status"] == "FAILED")+ assert failed["error"] == "Kaput" and failed["cause"] == "went wrong"+ assert failed["redriveStatus"] == "REDRIVABLE"+ assert failed["output"] is None and failed["outputDetails"] is None+ aborted = next(d for d in details if d["status"] == "ABORTED")+ assert aborted["executionArn"] == waiting+ assert aborted["error"] is None and aborted["cause"] is None+ assert aborted["redriveStatus"] == "NOT_REDRIVABLE"+ finally:+ sfn.delete_state_machine(stateMachineArn=fail_arn)+ sfn.delete_state_machine(stateMachineArn=wait_arn)+ eb.remove_targets(Rule=rule, Ids=["t1"])+ eb.delete_rule(Name=rule)+ sqs.delete_queue(QueueUrl=q_url)+++def test_sfn_sync_execution_emits_no_status_events(sfn_sync, sfn, eb, sqs):+ """StartSyncExecution is the express-flavored path; express workflows+ emit no status events on AWS, so none are published."""+ q_url, rule = _status_event_rule(eb, sqs, "sync")+ sm_arn = sfn.create_state_machine(+ name="qa-evt-sync",+ definition=json.dumps(+ {"StartAt": "Done", "States": {"Done": {"Type": "Succeed"}}}+ ),+ roleArn="arn:aws:iam::000000000000:role/R",+ )["stateMachineArn"]+ try:+ sfn_sync.start_sync_execution(stateMachineArn=sm_arn, input="{}")+ msgs = _drain_queue(sqs, q_url, want=1, tries=3)+ assert msgs == []+ finally:+ sfn.delete_state_machine(stateMachineArn=sm_arn)+ eb.remove_targets(Rule=rule, Ids=["t1"])+ eb.delete_rule(Name=rule)+ sqs.delete_queue(QueueUrl=q_url)