Skip to content

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

Paginate Step Functions execution history (#1820)

Jay Janssen9535d07b2460
diff --git a/CHANGELOG.md b/CHANGELOG.md
index af246efe..69b6bbc0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **Lambda — `ReservedConcurrentExecutions=0` disables the function** — a zero reservation was treated as unset, so the function ran unbounded instead of throttling every invoke with `TooManyRequestsException`. Zero now throttles across all executors, the Docker pool, and SQS event source mappings.
### Added
+- **Step Functions — execution history pagination** — `GetExecutionHistory` accepts `nextToken` and returns successive pages in forward or reverse order, with a token only while more events remain. `includeExecutionData=false` omits input and output payloads from returned history events.
- **CloudFront — public keys and key groups** — `CreatePublicKey`, `GetPublicKey`, `GetPublicKeyConfig`, `UpdatePublicKey`, `DeletePublicKey`, `ListPublicKeys`, `CreateKeyGroup`, `GetKeyGroup`, `GetKeyGroupConfig`, `UpdateKeyGroup`, `DeleteKeyGroup`, `ListKeyGroups`, so `aws_cloudfront_public_key` / `aws_cloudfront_key_group` (and Upbound's Terraform-based `provider-aws-cloudfront`) apply instead of hitting `NoSuchResource` on every create. Key groups validate their `Items` against real public keys, `DeletePublicKey` refuses a key still referenced by a key group, and `DeleteKeyGroup` refuses a group still referenced by a distribution's trusted key groups — both ETag/`If-Match` optimistic concurrency like the other CloudFront policy families.
- **CloudFormation — AppConfig applications, environments, configuration profiles and deployment strategies update in place** — none of the four had an update handler, so any property change re-ran the create and the resource came back under a new id. The environments, configuration profiles and hosted configuration versions keyed by the old id were orphaned. Each type now updates in place what its resource reference lists as No interruption and replaces on the rest. Contributed by @iot-rocket.
- **CloudFormation — AppSync GraphQL APIs and API keys update in place** — every property of `AWS::AppSync::GraphQLApi` is No interruption, but a change re-ran the create, which minted a new api id with empty key, data source, resolver and type stores, so a renamed API came back empty. The API now keeps its id and applies the change in place. It stores `AdditionalAuthenticationProviders`, `XrayEnabled`, `QueryDepthLimit`, `ResolverCountLimit`, `IntrospectionConfig`, `EnvironmentVariables`, `OwnerContact`, `LogConfig`, `UserPoolConfig`, `OpenIDConnectConfig`, `LambdaAuthorizerConfig`, `EnhancedMetricsConfig` and `MergedApiExecutionRoleArn` in AppSync's camelCase, and a removed member goes back to AppSync's default. A `Visibility` change fails with AWS's message. The API carries the stack-level tags, its id has `CreateGraphqlApi`'s 26 characters (eight made an ARN botocore refuses) and it answers the `REALTIME` endpoint. `AWS::AppSync::ApiKey` keeps its key on a `Description` or `Expires` change, and its record carries `description` and `createdAt`, as `CreateApiKey` writes them. Contributed by @iot-rocket.
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index 126b9fea..4cb69d4b 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -131,6 +131,11 @@ def _get_mock_response(sm_name: str, test_case: str, state_name: str, attempt: i
_state_machines = AccountRegionScopedDict()
_executions = AccountRegionScopedDict()
+# Continuation tokens are ephemeral, like AWS's 24-hour history tokens. Each
+# token fixes the history length so new events cannot shift reverse-order pages.
+_HISTORY_TOKEN_TTL_SECONDS = 24 * 60 * 60
+_history_page_tokens = {}
+_history_page_tokens_lock = threading.Lock()
_task_tokens = AccountRegionScopedDict()
_tags = AccountRegionScopedDict()
_activities = AccountRegionScopedDict()
@@ -775,11 +780,67 @@ def _get_execution_history(data):
return error_response_json(
"ExecutionDoesNotExist",
f"Execution {exec_arn} not found", 400)
+ max_results = data.get("maxResults", 100)
+ if max_results == 0 and not isinstance(max_results, bool):
+ max_results = 100
+ if not isinstance(max_results, int) or isinstance(max_results, bool) or not 0 < max_results <= 1000:
+ return error_response_json("ValidationException", "maxResults must be between 0 and 1000", 400)
+
+ reverse_order = data.get("reverseOrder", False)
+ include_data = data.get("includeExecutionData", True)
events = list(execution["events"])
- if data.get("reverseOrder", False):
- events = list(reversed(events))
- max_results = data.get("maxResults", 1000)
- return json_response({"events": events[:max_results]})
+ token = data.get("nextToken")
+ if token is None:
+ start, snapshot_size = 0, len(events)
+ else:
+ with _history_page_tokens_lock:
+ page_state = _history_page_tokens.get(token) if isinstance(token, str) else None
+ if (page_state is None or page_state["expires"] <= time.time()
+ or page_state["executionArn"] != exec_arn
+ or page_state["maxResults"] != max_results
+ or page_state["reverseOrder"] != reverse_order
+ or page_state["includeExecutionData"] != include_data
+ or page_state["snapshotSize"] > len(events)):
+ return error_response_json("InvalidToken", "Invalid pagination token", 400)
+ start, snapshot_size = page_state["start"], page_state["snapshotSize"]
+
+ events = events[:snapshot_size]
+ if reverse_order:
+ events.reverse()
+
+ page = events[start:start + max_results]
+ if include_data is False:
+ page = [copy.deepcopy(event) for event in page]
+ for event in page:
+ for key, details in event.items():
+ if key.endswith("EventDetails") and isinstance(details, dict):
+ for payload in ("input", "output"):
+ if payload in details:
+ del details[payload]
+
+ response = {"events": page}
+ if start + max_results < snapshot_size:
+ now = time.time()
+ with _history_page_tokens_lock:
+ # Dict insertion order is creation order, so expired tokens are
+ # removed from the front without scanning live continuations.
+ while _history_page_tokens:
+ oldest = next(iter(_history_page_tokens))
+ if _history_page_tokens[oldest]["expires"] > now:
+ break
+ del _history_page_tokens[oldest]
+ next_token = new_uuid()
+ _history_page_tokens[next_token] = {
+ "executionArn": exec_arn,
+ "maxResults": max_results,
+ "reverseOrder": reverse_order,
+ "includeExecutionData": include_data,
+ "start": start + max_results,
+ "snapshotSize": snapshot_size,
+ "expires": now + _HISTORY_TOKEN_TTL_SECONDS,
+ }
+ response["nextToken"] = next_token
+ return json_response(response)
def _start_sync_execution(data):
@@ -4785,6 +4846,8 @@ _SERVICE_DISPATCH = {
def reset():
_state_machines.clear()
_executions.clear()
+ with _history_page_tokens_lock:
+ _history_page_tokens.clear()
_task_tokens.clear()
_tags.clear()
_activities.clear()
diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.py
index 3d2f3a72..c6e6d14c 100644
--- a/tests/test_stepfunctions.py
+++ b/tests/test_stepfunctions.py
@@ -382,6 +382,125 @@ def test_sfn_get_execution_history_v2(sfn):
assert "ExecutionSucceeded" in types
assert any("Pass" in t for t in types)
+
+def test_sfn_get_execution_history_pagination(sfn):
+ states = {
+ f"P{i}": {"Type": "Pass", **({"End": True} if i == 14 else {"Next": f"P{i + 1}"})}
+ for i in range(15)
+ }
+ sm = sfn.create_state_machine(
+ name=f"sfn-history-pages-{_uuid_mod.uuid4().hex}",
+ definition=json.dumps({"StartAt": "P0", "States": states}),
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ ex = sfn.start_execution(stateMachineArn=sm["stateMachineArn"], input='{"secret":"value"}')
+ assert _wait_sfn(sfn, ex["executionArn"])["status"] == "SUCCEEDED"
+
+ arn = ex["executionArn"]
+ full = sfn.get_execution_history(executionArn=arn)["events"]
+ assert len(full) > 25
+ assert full[-1]["type"] == "ExecutionSucceeded"
+
+ pages = []
+ token = None
+ while True:
+ request = {"executionArn": arn, "maxResults": 7}
+ if token is not None:
+ request["nextToken"] = token
+ page = sfn.get_execution_history(**request)
+ pages.append(page)
+ token = page.get("nextToken")
+ if token is None:
+ break
+ assert len(pages) > 2
+ assert all(len(page["events"]) == 7 for page in pages[:-1])
+ assert [event["id"] for page in pages for event in page["events"]] == [event["id"] for event in full]
+ assert "nextToken" not in pages[-1]
+
+ first_25 = sfn.get_execution_history(executionArn=arn, maxResults=25)
+ assert all(event["type"] != "ExecutionSucceeded" for event in first_25["events"])
+ assert "nextToken" in first_25
+ last = sfn.get_execution_history(executionArn=arn, maxResults=25, nextToken=first_25["nextToken"])
+ assert last["events"][-1]["type"] == "ExecutionSucceeded"
+ assert "nextToken" not in last
+
+ reverse = []
+ token = None
+ while True:
+ request = {"executionArn": arn, "maxResults": 7, "reverseOrder": True}
+ if token is not None:
+ request["nextToken"] = token
+ page = sfn.get_execution_history(**request)
+ reverse.extend(page["events"])
+ token = page.get("nextToken")
+ if token is None:
+ break
+ assert [event["id"] for event in reverse] == [event["id"] for event in reversed(full)]
+
+ without_data = sfn.get_execution_history(executionArn=arn, maxResults=7, includeExecutionData=False)
+ assert "nextToken" in without_data
+ without_data_next = sfn.get_execution_history(
+ executionArn=arn, maxResults=7, includeExecutionData=False, nextToken=without_data["nextToken"]
+ )
+ assert [event["id"] for event in without_data_next["events"]] == [event["id"] for event in pages[1]["events"]]
+ assert "input" not in without_data["events"][0]["executionStartedEventDetails"]
+ for event in without_data["events"]:
+ for key, details in event.items():
+ if key.endswith("EventDetails") and isinstance(details, dict):
+ assert "input" not in details
+ assert "output" not in details
+ assert full[0]["executionStartedEventDetails"]["input"] == '{"secret":"value"}'
+ assert sfn.get_execution_history(executionArn=arn, maxResults=0)["events"] == full
+
+
+def test_sfn_get_execution_history_rejects_unrelated_and_forged_tokens(sfn):
+ sm = sfn.create_state_machine(
+ name=f"sfn-history-token-{_uuid_mod.uuid4().hex}",
+ definition=_pass_definition(),
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ first = sfn.start_execution(stateMachineArn=sm["stateMachineArn"])
+ second = sfn.start_execution(stateMachineArn=sm["stateMachineArn"])
+ assert _wait_sfn(sfn, first["executionArn"])["status"] == "SUCCEEDED"
+ assert _wait_sfn(sfn, second["executionArn"])["status"] == "SUCCEEDED"
+ page = sfn.get_execution_history(executionArn=first["executionArn"], maxResults=1)
+ token = page["nextToken"]
+
+ for request in (
+ {"executionArn": second["executionArn"], "maxResults": 1, "nextToken": token},
+ {"executionArn": first["executionArn"], "maxResults": 1, "nextToken": "1"},
+ {"executionArn": first["executionArn"], "maxResults": 2, "nextToken": token},
+ {"executionArn": first["executionArn"], "maxResults": 1, "reverseOrder": True, "nextToken": token},
+ {"executionArn": first["executionArn"], "maxResults": 1, "includeExecutionData": False, "nextToken": token},
+ ):
+ with pytest.raises(ClientError) as exc:
+ sfn.get_execution_history(**request)
+ assert exc.value.response["Error"]["Code"] == "InvalidToken"
+
+
+def test_sfn_get_execution_history_reverse_pages_ignore_new_events(sfn):
+ sm = sfn.create_state_machine(
+ name=f"sfn-history-running-{_uuid_mod.uuid4().hex}",
+ definition=json.dumps({"StartAt": "Wait", "States": {"Wait": {"Type": "Wait", "Seconds": 120, "End": True}}}),
+ roleArn="arn:aws:iam::000000000000:role/R",
+ )
+ arn = sfn.start_execution(stateMachineArn=sm["stateMachineArn"])["executionArn"]
+ for _ in range(50):
+ page = sfn.get_execution_history(executionArn=arn, reverseOrder=True, maxResults=1)
+ if page["events"][0]["type"] == "WaitStateEntered" and "nextToken" in page:
+ break
+ time.sleep(0.1)
+ else:
+ pytest.fail("running execution did not enter Wait state")
+
+ sfn.stop_execution(executionArn=arn)
+ next_page = sfn.get_execution_history(
+ executionArn=arn, reverseOrder=True, maxResults=1, nextToken=page["nextToken"]
+ )
+ assert [event["type"] for event in next_page["events"]] == ["ExecutionStarted"]
+ assert "nextToken" not in next_page
+
+
def test_sfn_tags_v2(sfn):
definition = json.dumps(
{