Skip to content

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

fix(stepfunctions): propagate request contextvars into background execution threads (#640)

Michael Denyer0297f0c05eb6
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index e71b4054..035b7fb3 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -25,6 +25,7 @@ SUCCEEDED / FAILED / TIMED_OUT / ABORTED.
import ast
import asyncio
+import contextvars
import copy
import json
import logging
@@ -532,8 +533,18 @@ def _start_execution(data):
],
}
+ # Propagate the request's contextvars (notably the account ID set by
+ # set_request_account_id) into the background execution thread. Python's
+ # threading.Thread does NOT automatically copy contextvars, so without
+ # this snapshot the worker runs under the default account and silently
+ # fails to find the execution stored in AccountScopedDict under the
+ # caller's account. See issue #639.
+ ctx_snapshot = contextvars.copy_context()
threading.Thread(
- target=_run_execution, args=(exec_arn,), daemon=True).start()
+ target=ctx_snapshot.run,
+ args=(_run_execution, exec_arn),
+ daemon=True,
+ ).start()
logger.info("Step Functions execution started: %s", exec_arn)
return json_response({"executionArn": exec_arn, "startDate": start_date})
@@ -1736,8 +1747,19 @@ def _execute_parallel(state_def, raw_input, execution, ctx):
except Exception as exc:
errors[idx] = exc
- threads = [threading.Thread(target=run_branch, args=(i, b), daemon=True)
- for i, b in enumerate(branches)]
+ # Each branch runs in its own thread; propagate the parent's contextvars
+ # so AccountScopedDict lookups (account ID, region) keep resolving to the
+ # current execution's tenant. Take a fresh copy_context() per branch —
+ # a single Context cannot be entered by two threads concurrently. See
+ # issue #639.
+ threads = [
+ threading.Thread(
+ target=contextvars.copy_context().run,
+ args=(run_branch, i, b),
+ daemon=True,
+ )
+ for i, b in enumerate(branches)
+ ]
for t in threads:
t.start()
for t in threads:
@@ -1790,8 +1812,16 @@ def _execute_map(state_def, raw_input, execution, ctx):
errors[idx] = exc
workers = max_conc if max_conc > 0 else (len(items) or 1)
+ # ThreadPoolExecutor workers do not inherit the submitting thread's
+ # contextvars, so wrap each submitted callable with copy_context().run
+ # to keep AccountScopedDict lookups bound to the current tenant. Take
+ # a fresh copy_context() per item — a single Context cannot be entered
+ # by two threads concurrently. See issue #639.
with ThreadPoolExecutor(max_workers=workers) as pool:
- futs = [pool.submit(run_item, i, item) for i, item in enumerate(items)]
+ futs = [
+ pool.submit(contextvars.copy_context().run, run_item, i, item)
+ for i, item in enumerate(items)
+ ]
futures_wait(futs)
for err in errors:
diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.py
index 7f85cf26..255288f9 100644
--- a/tests/test_stepfunctions.py
+++ b/tests/test_stepfunctions.py
@@ -3963,3 +3963,81 @@ def test_sfn_create_alias_rejects_malformed_routing_config(sfn):
assert exc_info.value.response["Error"]["Code"] == "ValidationException"
finally:
sfn.delete_state_machine(stateMachineArn=sm_arn)
+
+
+# ---------------------------------------------------------------------------
+# Regression: contextvars propagation to background execution thread (#639)
+# ---------------------------------------------------------------------------
+
+
+def test_sfn_execution_proceeds_under_non_default_account_id():
+ """Execution background thread must inherit the request's account context.
+
+ When a caller uses a 12-digit access-key as their account ID (the
+ documented per-account-isolation pattern), the execution record is stored
+ in AccountScopedDict under that account. Without contextvars propagation
+ into the threading.Thread that runs _run_execution, the worker thread
+ looks up the execution under the default account and silently returns,
+ leaving the execution stuck at ExecutionStarted forever.
+
+ Regression for #639. The fix wraps the background thread target with
+ contextvars.copy_context().run so the request's account/region context
+ survives the thread hop.
+ """
+ import boto3
+ from botocore.config import Config
+
+ # Borrow ENDPOINT + REGION from conftest's _default_kwargs without
+ # importing private names; rebuild a client with a 12-digit access key.
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+ region = os.environ.get("MINISTACK_REGION", "us-east-1")
+
+ alt_account_id = "123456789012" # AWS docs placeholder account
+ alt_kwargs = dict(
+ endpoint_url=endpoint,
+ aws_access_key_id=alt_account_id,
+ aws_secret_access_key="test",
+ region_name=region,
+ config=Config(region_name=region, retries={"max_attempts": 0}),
+ )
+ sfn = boto3.client("stepfunctions", **alt_kwargs)
+
+ uid = _uuid_mod.uuid4().hex[:8]
+ sm_name = f"ctxvars-{uid}"
+ sm = sfn.create_state_machine(
+ name=sm_name,
+ definition=json.dumps(
+ {
+ "StartAt": "P",
+ "States": {"P": {"Type": "Pass", "End": True}},
+ }
+ ),
+ roleArn=f"arn:aws:iam::{alt_account_id}:role/r",
+ type="STANDARD",
+ )
+ sm_arn = sm["stateMachineArn"]
+ try:
+ # ARN must be scoped to the alt account, not 000000000000.
+ assert f":states:{region}:{alt_account_id}:stateMachine:" in sm_arn
+
+ exec_resp = sfn.start_execution(
+ stateMachineArn=sm_arn,
+ name=f"e-{uid}",
+ input="{}",
+ )
+ desc = _wait_sfn(sfn, exec_resp["executionArn"], timeout=10)
+ assert desc["status"] == "SUCCEEDED", (
+ f"Execution under account {alt_account_id} stalled at "
+ f"{desc['status']!r}. Background thread lost the account "
+ f"contextvars — see issue #639."
+ )
+
+ # History must have progressed past ExecutionStarted.
+ hist = sfn.get_execution_history(executionArn=exec_resp["executionArn"])
+ event_types = [e["type"] for e in hist["events"]]
+ assert "ExecutionStarted" in event_types
+ assert "ExecutionSucceeded" in event_types, (
+ f"Execution never reached terminal Succeed; events: {event_types}"
+ )
+ finally:
+ sfn.delete_state_machine(stateMachineArn=sm_arn)