Skip to content

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

fix(lambda): CloudFormation-created ESMs never poll DynamoDB streams (#919)

maximooseminee95492317926
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a116f608..edc4aa11 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **CloudFormation — `GetTemplateSummary` now returns `Capabilities` and `CapabilitiesReason`** — the handler already accepted `TemplateBody` and returned `Parameters` / `ResourceTypes` correctly, but omitted the `Capabilities` and `CapabilitiesReason` fields. These are now computed from the template: `CAPABILITY_NAMED_IAM` for IAM resources with explicit name properties (`RoleName`, `UserName`, etc.), `CAPABILITY_IAM` for unnamed IAM resources, and `CAPABILITY_AUTO_EXPAND` for templates with a `Transform`. `CapabilitiesReason` uses the format confirmed against the AWS API: `"The following resource(s) require capabilities: [<type>]"`. Contributed by @maximoosemine.
- **Lambda - CreateEventSourceMapping persists FilterCriteria** — CreateEventSourceMapping was silently dropping the FilterCriteria parameter, so any filter specified at creation time was never applied.
- **ECS — `RunTask` now applies `containerOverrides.command` to the launched Docker container** — Overridden commands (including an explicit empty command) were ignored at runtime because the Docker `containers.run(...)` call still used the task-definition command. The effective container definition now carries the matched override command into Docker, while non-overridden containers keep their defaults.
+- **Lambda - CloudFormation-created ESMs now poll DynamoDB Streams** — Before, these streams were not getting polled.
---
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 2107c80b..cfa17732 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -1877,9 +1877,9 @@ def _apigw_account_delete(physical_id, props):
# --- Lambda EventSourceMapping ---
def _lambda_esm_create(logical_id, props, stack_name):
- func_name = props.get("FunctionName", "")
- if func_name.startswith("arn:"):
- func_name = func_name.rsplit(":", 1)[-1]
+ func_name, qualifier = _lambda_svc._resolve_name_and_qualifier(
+ props.get("FunctionName", "")
+ )
esm_id = new_uuid()
func = _lambda_svc._functions.get(func_name)
func_arn = func["config"]["FunctionArn"] if func else f"arn:aws:lambda:{get_region()}:{get_account_id()}:function:{func_name}"
@@ -1887,8 +1887,9 @@ def _lambda_esm_create(logical_id, props, stack_name):
esm = {
"UUID": esm_id,
"EventSourceArn": props.get("EventSourceArn", ""),
- "FunctionArn": func_arn,
+ "FunctionArn": func_arn + (f":{qualifier}" if qualifier else ""),
"FunctionName": func_name,
+ "Qualifier": qualifier,
"State": "Enabled",
"StateTransitionReason": "USER_INITIATED",
"BatchSize": int(props.get("BatchSize", 10)),
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 52fbceac..f662daba 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -4813,7 +4813,7 @@ def _poll_dynamodb_streams():
from ministack.services import dynamodb as _ddb
stream_records = getattr(_ddb, "_stream_records", None)
- if not stream_records:
+ if stream_records is None:
return
for (acct_id, _esm_key), esm in list(_esms._data.items()):
@@ -4833,8 +4833,6 @@ def _poll_dynamodb_streams():
table_arn = source_arn.split("/stream/")[0]
table_name = table_arn.split("/")[-1]
table_records = stream_records.get(table_name, [])
- if not table_records:
- continue
esm_id = esm["UUID"]
with _dynamodb_stream_positions_lock:
@@ -4846,6 +4844,9 @@ def _poll_dynamodb_streams():
_dynamodb_stream_positions[esm_id] = len(table_records)
pos = _dynamodb_stream_positions[esm_id]
+ if not table_records:
+ continue
+
batch_size = esm.get("BatchSize", 100)
batch = table_records[pos:pos + batch_size]
if not batch:
diff --git a/tests/conftest.py b/tests/conftest.py
index e816e56f..aa7ad973 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -58,6 +58,7 @@ _SERIAL_TESTS = {
"tests/test_eks.py::test_eks_cfn_cluster",
"tests/test_eks.py::test_eks_create_describe_delete_cluster",
"tests/test_lambda.py::test_lambda_reset_terminates_workers",
+ "tests/test_lambda.py::test_lambda_dynamodb_stream_esm_latest_processes_first_record",
"tests/test_ministack.py::test_ministack_config_invalid_key_ignored",
"tests/test_ses.py::test_ses_messages_endpoint_reset",
"tests/test_ses.py::test_ses_messages_endpoint_account_filter",
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 99e1d437..cecdbfbb 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -1051,6 +1051,56 @@ def test_lambda_dynamodb_stream_esm(lam, ddb):
assert "k2" in pks
assert "k1" not in pks
+
+def test_lambda_dynamodb_stream_esm_latest_processes_first_record(lam, ddb):
+ table_name = "ddb-latest-race-test"
+ fn_name = "ddb-latest-race-fn"
+
+ ddb.create_table(
+ TableName=table_name,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ StreamSpecification={"StreamEnabled": True, "StreamViewType": "NEW_AND_OLD_IMAGES"},
+ )
+ stream_arn = ddb.describe_table(TableName=table_name)["Table"]["LatestStreamArn"]
+
+ code = "def handler(event, context):\n return {'count': len(event['Records'])}\n"
+ lam.create_function(
+ FunctionName=fn_name,
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(code)},
+ )
+
+ esm = lam.create_event_source_mapping(
+ FunctionName=fn_name,
+ EventSourceArn=stream_arn,
+ StartingPosition="LATEST",
+ BatchSize=10,
+ )
+ esm_uuid = esm["UUID"]
+
+ # Let the poller tick at least once with an empty stream so position is
+ # eagerly initialised to 0.
+ time.sleep(2)
+ ddb.put_item(TableName=table_name, Item={"pk": {"S": "first"}, "val": {"S": "x"}})
+
+ for _ in range(10):
+ time.sleep(0.5)
+ resp = lam.get_event_source_mapping(UUID=esm_uuid)
+ if resp.get("LastProcessingResult") != "No records processed":
+ break
+
+ result = lam.get_event_source_mapping(UUID=esm_uuid)
+ assert result.get("LastProcessingResult") != "No records processed", (
+ "LATEST ESM skipped the first record on an initially-empty table"
+ )
+
+ lam.delete_event_source_mapping(UUID=esm_uuid)
+
+
def test_lambda_function_url_config(lam):
"""CreateFunctionUrlConfig / Get / Update / Delete / List lifecycle."""
import uuid as _uuid_mod