Skip to content

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

fix(stepfunctions): time out a Lambda or service task after TimeoutSeconds (#1994)

mishukdutta-cz169e3201468c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 08a72f2a..9469d783 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,13 +7,13 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
-### Fixed
-
-- **Step Functions — `States.TaskFailed` no longer matches `States.Timeout`** — a `Retry` or `Catch` on `States.TaskFailed` also matched a timeout, so a state machine retried or caught a timeout where AWS does not. `States.TaskFailed` now matches every error except `States.Timeout`, as the Step Functions error handling guide describes.
### Added
- **OpenSearch Serverless — collections, security and access policies, and a proxied data plane** — `CreateCollection`, `BatchGetCollection`, `ListCollections`, `UpdateCollection`, `DeleteCollection`, `Create`/`Get`/`Update`/`Delete`/`ListSecurityPolicy` (`encryption`, `network`), `Create`/`Get`/`Update`/`Delete`/`ListAccessPolicy` (`data`), `GetPoliciesStats` and `TagResource` / `UntagResource` / `ListTagsForResource`, enough for Terraform's `aws_opensearchserverless_collection`, `_security_policy` and `_access_policy` to apply, plan clean and destroy. A collection needs a matching encryption policy (exact name or `prefix*`, most specific wins) unless `encryptionConfig` is given, and answers `kmsKeyArn: auto` for an AWS-owned key; policy documents are validated, a resource pattern may sit in only one encryption policy, a data policy refuses empty or wildcard principals, and an update must name the current `policyVersion` (`base64("<lastModifiedDate>_<n>")`). Its `collectionEndpoint`, `http://<id>.<region>.aoss.<host>:<port>`, is served through the gateway and requests must be SigV4-signed for `aoss` and carry `x-amz-content-sha256` (403 otherwise); with `OPENSEARCH_DATAPLANE=1` it is backed by its own `opensearchproject/opensearch` container, persisted on a named Docker volume across a restart under `PERSIST_STATE` and removed on `DeleteCollection`, otherwise it answers 503. APIs AOSS does not support answer 404, as `_refresh`, `_cluster/*` and scroll do on AWS, and `TIMESERIES` collections refuse custom document ids and updates. Data access and network policies are stored, not enforced. Checked against the botocore model and the OpenSearch Serverless developer guide and API reference.
+
### Fixed
+- **Step Functions — `TimeoutSeconds` applies to Lambda and service integration tasks** — only `.waitForTaskToken` tasks used `TimeoutSeconds`; a Lambda or service integration task ran to the end, so a `Retry` or `Catch` on `States.Timeout` never ran. Such a task now fails with `States.Timeout` when it runs longer than `TimeoutSeconds`, as the Step Functions Task state reference describes. Activity tasks and `TimeoutSecondsPath` do not change.
+- **Step Functions — `States.TaskFailed` no longer matches `States.Timeout`** — a `Retry` or `Catch` on `States.TaskFailed` also matched a timeout, so a state machine retried or caught a timeout where AWS does not. `States.TaskFailed` now matches every error except `States.Timeout`, as the Step Functions error handling guide describes.
- **ElastiCache — serverless caches run in cluster mode** — AWS serves a serverless cache as a cluster-mode cache, so a multi-key command whose keys hash to different slots fails with `CROSSSLOT`; MiniStack's container ran without cluster mode and accepted it, so such code passed locally and failed on AWS. The container now runs as one cluster-mode shard holding every slot, and `CLUSTER SLOTS` reports the cache's endpoint, as AWS's single virtual shard does. Contributed by @skialpine.
- **CloudTrail — `PutEventSelectors` stores `AdvancedEventSelectors` and sets `HasCustomEventSelectors`** — advanced selectors are now stored and returned in place of `EventSelectors` instead of being dropped, a request with both kinds, neither, or an empty or oversized list fails with `InvalidEventSelectorsException`, basic selectors read back with their omitted members filled in, and `GetTrail` and `DescribeTrails` report `HasCustomEventSelectors: true` while a trail has selectors other than the default one. Contributed by @iot-rocket.
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index 3250998f..10e2acdb 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -38,6 +38,7 @@ import re
import threading
import time
from concurrent.futures import ThreadPoolExecutor
+from concurrent.futures import TimeoutError as FutureTimeoutError
from concurrent.futures import wait as futures_wait
from datetime import datetime, timezone
@@ -1704,6 +1705,10 @@ def _execute_task(state_def, raw_input, execution, ctx):
if is_callback:
task_result = _invoke_with_callback(
resource, effective, ctx["Task"]["Token"], state_def)
+ # Skip activities: their timeout starts when a worker gets the task, not here
+ elif "TimeoutSeconds" in state_def and ":activity:" not in resource:
+ task_result = _invoke_resource_with_timeout(
+ resource, effective, state_def["TimeoutSeconds"])
else:
task_result = _invoke_resource(resource, effective)
@@ -1826,6 +1831,21 @@ def _invoke_resource(resource, input_data):
return input_data
+def _invoke_resource_with_timeout(resource, input_data, timeout):
+ """Run the task, and raise States.Timeout when it runs longer than TimeoutSeconds.
+
+ This function does not stop the task thread. The task continues to run, but the state ignores its result.
+ """
+ pool = ThreadPoolExecutor(max_workers=1)
+ # Workers do not inherit contextvars, so copy them to keep the account and region scope (#639).
+ future = pool.submit(contextvars.copy_context().run, _invoke_resource, resource, input_data)
+ pool.shutdown(wait=False)
+ try:
+ return future.result(timeout=timeout)
+ except FutureTimeoutError:
+ raise _ExecutionError("States.Timeout", f"Task timed out after {timeout} seconds") from None
+
+
def _invoke_activity(resource, input_data):
"""Enqueue a task for the activity worker and block until SendTaskSuccess/Failure."""
arn = resource
diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.py
index 76c3d4b5..4de7133a 100644
--- a/tests/test_stepfunctions.py
+++ b/tests/test_stepfunctions.py
@@ -3426,38 +3426,36 @@ def test_sfn_integration_sqs_send_message_wait_for_task_token(sfn, sqs):
assert desc["status"] == "SUCCEEDED"
-def test_sfn_task_failed_does_not_match_states_timeout(sfn, sqs):
- """States.TaskFailed matches every error except States.Timeout, in Retry and in Catch."""
- queue_url = sqs.create_queue(QueueName="sfn-taskfailed-timeout")["QueueUrl"]
+def test_sfn_task_timeout_seconds_applies_to_lambda_invoke(sfn, lam):
+ """A Lambda task that runs longer than TimeoutSeconds fails with States.Timeout."""
+ fn = f"sfn-task-timeout-{_uuid_mod.uuid4().hex[:8]}"
+ code = "import time\ndef handler(event, context):\n time.sleep(3)\n return 'done'\n"
+ lam.create_function(
+ FunctionName=fn, Runtime="python3.12", Role=_LAMBDA_ROLE, Handler="index.handler",
+ Code={"ZipFile": _make_zip(code)}, Timeout=10,
+ )
definition = json.dumps({
- "StartAt": "Wait",
+ "StartAt": "Call",
"States": {
- "Wait": {
+ "Call": {
"Type": "Task",
- "Resource": "arn:aws:states:::sqs:sendMessage.waitForTaskToken",
- "Parameters": {"QueueUrl": queue_url, "MessageBody": {"token.$": "$$.Task.Token"}},
+ "Resource": "arn:aws:states:::lambda:invoke",
+ "Parameters": {"FunctionName": fn, "Payload": {}},
"TimeoutSeconds": 1,
- "Retry": [{"ErrorEquals": ["States.TaskFailed"], "IntervalSeconds": 1, "MaxAttempts": 1}],
- "Catch": [
- {"ErrorEquals": ["States.TaskFailed"], "Next": "CaughtAsTaskFailed"},
- {"ErrorEquals": ["States.Timeout"], "Next": "CaughtAsTimeout"},
- ],
+ "Catch": [{"ErrorEquals": ["States.Timeout"], "Next": "TimedOut"}],
"End": True,
},
- "CaughtAsTaskFailed": {"Type": "Pass", "Result": "task-failed", "End": True},
- "CaughtAsTimeout": {"Type": "Pass", "Result": "timeout", "End": True},
+ "TimedOut": {"Type": "Pass", "Result": "timed-out", "End": True},
},
})
sm = sfn.create_state_machine(
- name="sfn-taskfailed-timeout", definition=definition, roleArn="arn:aws:iam::000000000000:role/R",
+ name=fn, definition=definition, roleArn="arn:aws:iam::000000000000:role/R",
)
ex = sfn.start_execution(stateMachineArn=sm["stateMachineArn"], input="{}")
desc = _wait_sfn(sfn, ex["executionArn"])
assert desc["status"] == "SUCCEEDED"
- assert json.loads(desc["output"]) == "timeout"
- events = sfn.get_execution_history(executionArn=ex["executionArn"])["events"]
- assert [e["type"] for e in events].count("TaskScheduled") == 1
+ assert json.loads(desc["output"]) == "timed-out"
def test_sfn_integration_lambda_invoke_wait_for_task_token(sfn, lam):