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(lambda): dispatch SQS event source batches concurrently (#1724)
Thailer Lietzaa8ad0bad621
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f86ad850..1c3cd765 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **Lambda — dispatch SQS event source batches concurrently** — one thread polled every mapping and waited for each invoke, so a handler that took 10 seconds held a message on an unrelated queue for about 8.6 seconds, and `ScalingConfig.MaximumConcurrency` was stored but ignored. SQS batches are now invoked off the poll thread, up to `MaximumConcurrency` batches per mapping (default 5), lowered to the function's `ReservedConcurrentExecutions` so a mapping does not throttle its own function. Kinesis and DynamoDB Streams mappings still process one batch at a time. Contributed by @ThailerL.- **ECS — a task's `version` counts its state changes** — the counter was minted at `1` and never moved again, so a consumer holding an older `DescribeTasks` copy could not tell it from the current one, which is the comparison the field exists for. It now increments on each transition the record reports: the move to `ACTIVATING`, the move to `RUNNING`, the move to `STOPPED` whether it came from `StopTask`, an essential container exiting or a failed start, and the restore after a restart that stops a task that was running. A real task counts the same way, measured on a Fargate task polled through `DescribeTasks`: `1` at `PROVISIONING`, `2` at `PENDING`, `3` at `RUNNING`, `4` when `StopTask` set `desiredStatus`, `5` at `DEPROVISIONING`, `6` at `STOPPED`. There are no task state change events here, so the counter is what `DescribeTasks`, `RunTask` and `StopTask` report and nothing else. Contributed by @iot-rocket.- **ECS — only an `awsvpc` task reports an elastic network interface** — every task got an `ElasticNetworkInterface` attachment once its container was up, whatever its network mode, while the Task reference describes `attachments` as the adapter a task has "if the task uses the `awsvpc` network mode": a `bridge` or `host` task on AWS reports none and is reached through its container instance. A task in those modes now reports an empty list, an `awsvpc` task's attachment additionally names the subnet the request placed it in, and the address stays available to the target-group sync in every mode. Contributed by @iot-rocket.- **ECS — a task no longer reports `attachmentsStatus`** — the task record carried an `attachmentsStatus` member next to its attachment, and there is no such member on the `Task` shape: the API model has it on `Cluster` only, and a live task on AWS, awsvpc and bridge alike, sends no such field. A client reading the raw wire saw an invented member, and the emulator was the only place it existed. The cluster's own `attachmentsStatus` is untouched. Contributed by @iot-rocket.diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex d0a8e0be..00d53a7b 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -51,7 +51,7 @@ from urllib.parse import quote, unquotefrom ministack.core import container_reaperfrom ministack.core.arn import ArnParseError, parse_arn-from ministack.core.concurrency import run_reentrant+from ministack.core.concurrency import run_reentrant, spawn_backgroundfrom ministack.core.lambda_runtime import (DURABLE_ENV_VARS,INVOKE_DEPTH_BOOTSTRAP,@@ -4794,6 +4794,15 @@ def _inflight_key(config: dict) -> str:return f"{account}:{region}:{config.get('FunctionName', '?')}:{config.get('Version', '$LATEST')}"+def _reserved_concurrency(func: dict, config: dict) -> int | None:+ reserved = (func or {}).get("concurrency")+ if isinstance(reserved, dict):+ reserved = reserved.get("ReservedConcurrentExecutions")+ if reserved is None:+ reserved = config.get("ReservedConcurrentExecutions")+ return None if reserved is None else int(reserved)++def _acquire_execution_slot(func: dict, config: dict):"""Reserve one unit of concurrency, or None when a cap is reached.@@ -4806,14 +4815,10 @@ def _acquire_execution_slot(func: dict, config: dict):so both are consulted rather than assuming either shape."""global _inflight_total- reserved = (func or {}).get("concurrency")- if isinstance(reserved, dict):- reserved = reserved.get("ReservedConcurrentExecutions")- if reserved is None:- reserved = config.get("ReservedConcurrentExecutions")+ reserved = _reserved_concurrency(func, config)key = _inflight_key(config)with _inflight_lock:- if reserved and _inflight.get(key, 0) >= int(reserved):+ if reserved and _inflight.get(key, 0) >= reserved:return None, "function"if _ACCOUNT_CONCURRENCY_CAP > 0 and _inflight_total >= _ACCOUNT_CONCURRENCY_CAP:return None, "account"@@ -6967,6 +6972,40 @@ _dynamodb_stream_positions_lock = threading.Lock()_esm_backoff_until = AccountRegionScopedDict()_ESM_BACKOFF_SECONDS = 1.0+# SQS batches run off the poll thread so a slow handler can't stall other ESMs.+# Per-ESM limit is ScalingConfig.MaximumConcurrency, else this default.+_ESM_SQS_DEFAULT_CONCURRENCY = 5+# esm_uuid -> dispatched batches not yet finished.+_esm_inflight: dict[str, int] = {}+_esm_inflight_lock = threading.Lock()+# Set when a dispatched batch finishes, so _poll_loop refills the slot at once.+_esm_wake = threading.Event()+++def _sqs_esm_concurrency(esm: dict, func_rec: dict, config: dict) -> int:+ limit = (esm.get("ScalingConfig") or {}).get("MaximumConcurrency") or _ESM_SQS_DEFAULT_CONCURRENCY+ reserved = _reserved_concurrency(func_rec, config)+ return min(limit, reserved) if reserved else limit+++def _dispatch_esm_batch(esm_id: str, fn, *args) -> None:+ with _esm_inflight_lock:+ _esm_inflight[esm_id] = _esm_inflight.get(esm_id, 0) + 1++ def _task():+ try:+ fn(*args)+ finally:+ with _esm_inflight_lock:+ remaining = _esm_inflight.get(esm_id, 0) - 1+ if remaining > 0:+ _esm_inflight[esm_id] = remaining+ else:+ _esm_inflight.pop(esm_id, None)+ _esm_wake.set()++ spawn_background(_task, thread_name="ministack-esm")+def _init_stream_position(esm_id, source_arn, starting):"""Anchor a DynamoDB-stream ESM's read position at subscription time so@@ -7002,6 +7041,7 @@ def _poll_loop():"""Background thread: polls SQS/Kinesis/DynamoDB for active ESMs and invokes Lambda."""while True:processed = False+ _esm_wake.clear()try:processed = _poll_sqs() or processedexcept Exception as e:@@ -7018,7 +7058,7 @@ def _poll_loop():# immediately rather than waiting out the idle cadence below, so# throughput isn't throttled to batch_size-per-tick.if not processed:- time.sleep(1 if _esms.has_any() else 5)+ _esm_wake.wait(1 if _esms.has_any() else 5)def _iter_all_esms():@@ -7045,8 +7085,8 @@ def _sqs_message_attributes_to_camel_case(attrs: dict) -> dict:def _poll_sqs():- """Returns True if any ESM advanced past a batch this pass (successfully- invoked, or filtered out entirely)."""+ """Returns True if any ESM took a batch this pass (dispatched for invoke,+ or filtered out entirely)."""from ministack.services import sqs as _sqsprocessed_any = False@@ -7086,6 +7126,9 @@ def _poll_sqs():esm_id = esm["UUID"]if _esm_backoff_until.get(esm_id, 0) > time.time():continue+ # Only this thread increments, so the count can't rise before dispatch.+ if _esm_inflight.get(esm_id, 0) >= _sqs_esm_concurrency(esm, func_rec, _cfg):+ continuebatch_size = esm.get("BatchSize", 10)now = time.time()@@ -7142,60 +7185,10 @@ def _poll_sqs():processed_any = Truecontinue- event = {"Records": records}- result = _execute_function(func_rec, event)-- if result.get("error"):- err_body = result.get("body") or {}- err_type = err_body.get("errorType") if isinstance(err_body, dict) else None- err_msg = err_body.get("errorMessage") if isinstance(err_body, dict) else None- esm["LastProcessingResult"] = "FAILED"- logger.warning(- "ESM: Lambda %s failed processing SQS batch from %s (errorType=%s errorMessage=%s)\n%s",- func_name, queue_name, err_type, err_msg, result.get("log", ""),- )- # Failed messages stay invisible for their visibility timeout- # rather than advancing, so don't report this as processed.- _esm_backoff_until[esm_id] = time.time() + _ESM_BACKOFF_SECONDS- else:- processed_any = True- _esm_backoff_until.pop(esm_id, None)- # Check for ReportBatchItemFailures — partial batch response- failed_ids = set()- if "ReportBatchItemFailures" in esm.get("FunctionResponseTypes", []):- body = result.get("body")- if isinstance(body, dict):- for failure in body.get("batchItemFailures", []):- fid = failure.get("itemIdentifier", "")- if fid:- failed_ids.add(fid)- elif isinstance(body, str):- try:- parsed = json.loads(body)- for failure in parsed.get("batchItemFailures", []):- fid = failure.get("itemIdentifier", "")- if fid:- failed_ids.add(fid)- except (json.JSONDecodeError, AttributeError):- pass-- # Delete only the messages that succeeded (not in failed_ids)- succeeded = [msg for msg in batch if msg["id"] not in failed_ids]- receipt_handles = {msg["receipt_handle"] for msg in succeeded if msg.get("receipt_handle")}- if receipt_handles:- _sqs._delete_messages_for_esm(queue_url, receipt_handles)-- n_failed = len(batch) - len(succeeded)- if n_failed:- esm["LastProcessingResult"] = f"OK - {len(succeeded)} records, {n_failed} partial failures"- logger.info("ESM: Lambda %s processed %d SQS messages from %s (%d partial failures)",- func_name, len(succeeded), queue_name, n_failed)- else:- esm["LastProcessingResult"] = f"OK - {len(batch)} records"- logger.info("ESM: Lambda %s processed %d SQS messages from %s", func_name, len(batch), queue_name)- log_output = result.get("log", "")- if log_output:- logger.info("ESM: Lambda %s output:\n%s", func_name, log_output)+ _dispatch_esm_batch(+ esm_id, _run_sqs_batch, esm, func_rec, {"Records": records}, batch, queue_url, queue_name+ )+ processed_any = Truefinally:_request_account_id.reset(account_token)_request_region.reset(region_token)@@ -7203,6 +7196,66 @@ def _poll_sqs():return processed_any+def _run_sqs_batch(esm, func_rec, event, batch, queue_url, queue_name):+ from ministack.services import sqs as _sqs++ esm_id = esm["UUID"]+ func_name = esm["FunctionName"]+ result = _execute_function(func_rec, event)++ if result.get("error"):+ err_body = result.get("body") or {}+ err_type = err_body.get("errorType") if isinstance(err_body, dict) else None+ err_msg = err_body.get("errorMessage") if isinstance(err_body, dict) else None+ esm["LastProcessingResult"] = "FAILED"+ logger.warning(+ "ESM: Lambda %s failed processing SQS batch from %s (errorType=%s errorMessage=%s)\n%s",+ func_name, queue_name, err_type, err_msg, result.get("log", ""),+ )+ # Failed messages stay invisible for their visibility timeout; pace+ # retries so the poll loop doesn't spin on a broken ESM.+ _esm_backoff_until[esm_id] = time.time() + _ESM_BACKOFF_SECONDS+ return++ _esm_backoff_until.pop(esm_id, None)+ # Check for ReportBatchItemFailures — partial batch response+ failed_ids = set()+ if "ReportBatchItemFailures" in esm.get("FunctionResponseTypes", []):+ body = result.get("body")+ if isinstance(body, dict):+ for failure in body.get("batchItemFailures", []):+ fid = failure.get("itemIdentifier", "")+ if fid:+ failed_ids.add(fid)+ elif isinstance(body, str):+ try:+ parsed = json.loads(body)+ for failure in parsed.get("batchItemFailures", []):+ fid = failure.get("itemIdentifier", "")+ if fid:+ failed_ids.add(fid)+ except (json.JSONDecodeError, AttributeError):+ pass++ # Delete only the messages that succeeded (not in failed_ids)+ succeeded = [msg for msg in batch if msg["id"] not in failed_ids]+ receipt_handles = {msg["receipt_handle"] for msg in succeeded if msg.get("receipt_handle")}+ if receipt_handles:+ _sqs._delete_messages_for_esm(queue_url, receipt_handles)++ n_failed = len(batch) - len(succeeded)+ if n_failed:+ esm["LastProcessingResult"] = f"OK - {len(succeeded)} records, {n_failed} partial failures"+ logger.info("ESM: Lambda %s processed %d SQS messages from %s (%d partial failures)",+ func_name, len(succeeded), queue_name, n_failed)+ else:+ esm["LastProcessingResult"] = f"OK - {len(batch)} records"+ logger.info("ESM: Lambda %s processed %d SQS messages from %s", func_name, len(batch), queue_name)+ log_output = result.get("log", "")+ if log_output:+ logger.info("ESM: Lambda %s output:\n%s", func_name, log_output)++def _poll_kinesis():"""Returns True if any shard advanced past a batch this pass (successfullyinvoked, or filtered out entirely)."""diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex b8f4a1cb..a28fafa6 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -5155,12 +5155,15 @@ def esm_poll_state(tmp_path, monkeypatch):lsvc._kinesis_positions._data.clear()lsvc._dynamodb_stream_positions._data.clear()lsvc._esm_backoff_until._data.clear()+ lsvc._esm_inflight.clear()_sqs._queues._data.clear()_kin._streams._data.clear()_ddb._tables._data.clear()_ddb._stream_records._data.clear()_ddb._stream_trimmed._data.clear()+ # Run dispatched SQS batches inline so a poll pass finishes its invokes before returning.+ monkeypatch.setattr(lsvc, "spawn_background", lambda task, **_: task())_clear_all()try:yield lsvc, _sqs, _kin, _ddb@@ -5296,10 +5299,10 @@ def test_poll_dynamodb_streams_returns_true_when_batch_processed(esm_poll_state,assert _lsvc._poll_dynamodb_streams() is True-def test_poll_sqs_returns_false_when_invoke_fails(esm_poll_state, monkeypatch):+def test_poll_sqs_backs_off_after_invoke_fails(esm_poll_state, monkeypatch):"""A failed invoke leaves the message undeleted (just invisible for its- visibility timeout) rather than advancing — _poll_loop must not skip its- idle sleep for a pass that made no real progress."""+ visibility timeout) and puts the ESM in backoff, so the next pass finds+ nothing to take and _poll_loop goes back to waiting instead of spinning."""_lsvc, _sqs, _kin, _ddb = esm_poll_statequeue_name = "esm-drain-signal-failure"@@ -5343,8 +5346,9 @@ def test_poll_sqs_returns_false_when_invoke_fails(esm_poll_state, monkeypatch):lambda _func, _event: {"error": True, "body": {"errorType": "Error", "errorMessage": "boom"}},)- assert _lsvc._poll_sqs() is False+ assert _lsvc._poll_sqs() is Trueassert len(_sqs._queues[queue_url]["messages"]) == 1+ assert _lsvc._poll_sqs() is Falsedef test_poll_sqs_backs_off_failing_esm_without_starving_other_esms(esm_poll_state, monkeypatch):@@ -5569,7 +5573,7 @@ def test_poll_sqs_retries_esm_after_backoff_expires(esm_poll_state, monkeypatch)fake_now = [1_000_000.0]monkeypatch.setattr(_lsvc.time, "time", lambda: fake_now[0])- assert _lsvc._poll_sqs() is False+ assert _lsvc._poll_sqs() is Trueassert len(invoke_calls) == 1# Still within the backoff window — skipped before it would even receive.@@ -5579,7 +5583,7 @@ def test_poll_sqs_retries_esm_after_backoff_expires(esm_poll_state, monkeypatch)# Backoff has elapsed — the ESM is retried (and fails again).fake_now[0] += _lsvc._ESM_BACKOFF_SECONDS- assert _lsvc._poll_sqs() is False+ assert _lsvc._poll_sqs() is Trueassert len(invoke_calls) == 2@@ -5708,7 +5712,7 @@ def test_poll_loop_skips_sleep_when_a_poller_processed_work(monkeypatch):monkeypatch.setattr(lsvc, "_poll_sqs", fake_poll_sqs)monkeypatch.setattr(lsvc, "_poll_kinesis", lambda: False)monkeypatch.setattr(lsvc, "_poll_dynamodb_streams", lambda: False)- monkeypatch.setattr(lsvc.time, "sleep", lambda secs: sleep_calls.append(secs))+ monkeypatch.setattr(lsvc._esm_wake, "wait", lambda secs: sleep_calls.append(secs))with pytest.raises(_StopPollLoop):lsvc._poll_loop()@@ -5731,7 +5735,7 @@ def test_poll_loop_sleeps_when_no_poller_processed_work(esm_poll_state, monkeypamonkeypatch.setattr(lsvc, "_poll_sqs", lambda: False)monkeypatch.setattr(lsvc, "_poll_kinesis", lambda: False)monkeypatch.setattr(lsvc, "_poll_dynamodb_streams", lambda: False)- monkeypatch.setattr(lsvc.time, "sleep", fake_sleep)+ monkeypatch.setattr(lsvc._esm_wake, "wait", fake_sleep)with pytest.raises(_StopPollLoop):lsvc._poll_loop()@@ -5739,6 +5743,102 @@ def test_poll_loop_sleeps_when_no_poller_processed_work(esm_poll_state, monkeypaassert sleep_calls == [5]+def test_esm_batch_completion_wakes_poll_loop(esm_poll_state):+ """A finished batch frees a concurrency slot; the poll loop must refill it+ right away rather than waiting out its idle cadence."""+ lsvc._esm_wake.clear()+ lsvc._dispatch_esm_batch("esm-wake", lambda: None)+ assert lsvc._esm_wake.is_set()+ assert "esm-wake" not in lsvc._esm_inflight+++def _sqs_esm_fixture(_lsvc, _sqs, name, *, messages=1, esm_extra=None, func_extra=None):+ queue_url = f"http://localhost:4566/000000000000/{name}"+ _sqs._queues[queue_url] = {+ "name": name,+ "messages": [{+ "id": f"msg-{i}", "body": "payload", "md5_body": "", "receipt_handle": None,+ "sent_at": time.time(), "visible_at": 0, "receive_count": 0,+ "first_receive_at": None, "message_attributes": {},+ } for i in range(messages)],+ "attributes": {"QueueArn": f"arn:aws:sqs:us-east-1:000000000000:{name}"},+ "is_fifo": False,+ "dedup_cache": {},+ "fifo_seq": 0,+ }+ _lsvc._functions[f"{name}-fn"] = {+ "config": {+ "FunctionName": f"{name}-fn",+ "FunctionArn": f"arn:aws:lambda:us-east-1:000000000000:function:{name}-fn",+ },+ "versions": {}, "aliases": {},+ **(func_extra or {}),+ }+ _lsvc._esms[name] = {+ "UUID": name,+ "EventSourceArn": f"arn:aws:sqs:us-east-1:000000000000:{name}",+ "FunctionName": f"{name}-fn",+ "State": "Enabled",+ "Enabled": True,+ "BatchSize": 1,+ **(esm_extra or {}),+ }+ return queue_url+++def esm_threaded_dispatch(esm_poll_state, monkeypatch):+ """Real worker threads instead of the inline dispatch esm_poll_state installs."""+ from ministack.core.concurrency import spawn_background++ threads = []+ monkeypatch.setattr(lsvc, "spawn_background", lambda task, **kw: threads.append(spawn_background(task, **kw)))+ release = threading.Event()+ try:+ yield esm_poll_state, release+ finally:+ release.set()+ for t in threads:+ t.join(10)+++def test_poll_sqs_slow_handler_does_not_block_other_esms(esm_threaded_dispatch, monkeypatch):+ (_lsvc, _sqs, _kin, _ddb), release = esm_threaded_dispatch+ _sqs_esm_fixture(_lsvc, _sqs, "esm-slow")+ _sqs_esm_fixture(_lsvc, _sqs, "esm-fast")+ fast_done = threading.Event()++ def fake_execute(func, _event):+ if func["config"]["FunctionName"] == "esm-slow-fn":+ release.wait(10)+ else:+ fast_done.set()+ return {"body": {}}++ monkeypatch.setattr(_lsvc, "_execute_function", fake_execute)++ assert _lsvc._poll_sqs() is True+ assert fast_done.wait(5), "fast ESM waited on the slow ESM's handler"++[email protected]("esm_extra,func_extra,expected", [+ ({}, {}, 5),+ ({"ScalingConfig": {"MaximumConcurrency": 3}}, {}, 3),+ ({"ScalingConfig": {"MaximumConcurrency": 8}}, {"concurrency": 2}, 2),+])+def test_poll_sqs_caps_in_flight_batches_per_esm(esm_threaded_dispatch, monkeypatch, esm_extra, func_extra, expected):+ """MaximumConcurrency (default 5) bounds one ESM's in-flight batches, and a+ lower ReservedConcurrentExecutions wins so the ESM doesn't throttle itself."""+ (_lsvc, _sqs, _kin, _ddb), release = esm_threaded_dispatch+ _sqs_esm_fixture(_lsvc, _sqs, "esm-capped", messages=20, esm_extra=esm_extra, func_extra=func_extra)+ monkeypatch.setattr(_lsvc, "_execute_function", lambda _func, _event: (release.wait(10), {"body": {}})[1])++ for _ in range(20):+ _lsvc._poll_sqs()++ assert _lsvc._esm_inflight["esm-capped"] == expected++def test_lambda_create_esm_rejects_unresolved_function_arn():original_account = get_account_id()original_region = get_region()