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: DynamoDB conditional checks, ESM visibility timeout, Lambda stdo… (#11)
Nahuel Nucera135476499a30
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a24b35df..ac92b17b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,22 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [1.0.5] — 2026-03-26++### Fixed+- **DynamoDB `UpdateItem` condition expression on missing item**: `ConditionExpression` such as `attribute_exists(...)` now correctly evaluates against the existing stored item (or empty if missing) — was incorrectly evaluating against the in-progress mutation, causing `ConditionalCheckFailedException` to never fire on missing items+- **DynamoDB key schema validation**: `GetItem`, `DeleteItem`, `UpdateItem`, `BatchWriteItem`, `BatchGetItem` now validate that supplied key attributes match the table schema in name and type — returns `ValidationException: The provided key element does not match the schema`+- **ESM visibility timeout**: SQS → Lambda event source mapping now respects the queue's configured `VisibilityTimeout` instead of hardcoding 30 s — prevents retry storms and duplicate deliveries when Lambda fails+- **Lambda stdout/stderr separation**: handler logs now go to stderr, response payload to stdout — matches AWS Lambda runtime contract; fixes log pollution in response payloads+- **Lambda timeout error**: `subprocess.TimeoutExpired` path now captures and returns stdout/stderr in the error log instead of returning an empty string+- **ECS `_maybe_mark_stopped` container status**: calls `container.reload()` before checking status to get live state from Docker — was reading stale cached status+- **ECS `stoppedAt`/`stoppingAt` timestamps**: now stored as ISO 8601 strings matching AWS ECS API format — was storing Unix epoch float+- **ECS cluster task count**: `_recount_cluster()` now recomputes running/pending counts from all tasks instead of decrementing — prevents count drift on concurrent task terminations+- **Step Functions service integrations**: Task state now dispatches to real MiniStack services via `arn:aws:states:::` resource URIs — `sqs:sendMessage`, `sns:publish`, `dynamodb:putItem`, `dynamodb:getItem`, `dynamodb:deleteItem`, `dynamodb:updateItem`, `ecs:runTask`, `ecs:runTask.sync` — was returning input passthrough instead of invoking the service+- 392 integration tests — all passing, including against Docker image++---+## [1.0.4] — 2026-03-26### Fixeddiff --git a/services/cloudwatch.py b/services/cloudwatch.pyindex 9f6721ba..3917d69a 100644--- a/services/cloudwatch.py+++ b/services/cloudwatch.py@@ -38,6 +38,7 @@ _dashboards: dict = {} # dashboard_name -> {DashboardName, DashboardBody, LastM# Timestamp helpers# ---------------------------------------------------------------------------+def _parse_ts(value):"""Parse ISO-8601 string, epoch float, or None into a Unix timestamp."""if value is None:@@ -52,9 +53,13 @@ def _parse_ts(value):return float(value)except ValueError:pass- for fmt in ("%Y-%m-%dT%H:%M:%S.%fZ", "%Y-%m-%dT%H:%M:%SZ",- "%Y-%m-%dT%H:%M:%S.%f%z", "%Y-%m-%dT%H:%M:%S%z",- "%Y-%m-%dT%H:%M:%S"):+ for fmt in (+ "%Y-%m-%dT%H:%M:%S.%fZ",+ "%Y-%m-%dT%H:%M:%SZ",+ "%Y-%m-%dT%H:%M:%S.%f%z",+ "%Y-%m-%dT%H:%M:%S%z",+ "%Y-%m-%dT%H:%M:%S",+ ):try:dt = datetime.strptime(value, fmt)if dt.tzinfo is None:@@ -73,6 +78,7 @@ def _ts_iso(epoch):# Metric eviction# ---------------------------------------------------------------------------+def _evict_old_metrics():cutoff = time.time() - TWO_WEEKS_SECONDSempty_keys = []@@ -88,6 +94,7 @@ def _evict_old_metrics():# Statistics helpers# ---------------------------------------------------------------------------+def _calc_stats(values):if not values:return {}@@ -113,6 +120,7 @@ def _stat_value(stats, stat_name):# Alarm evaluation# ---------------------------------------------------------------------------+def _evaluate_alarm(alarm):ns = alarm.get("Namespace")mn = alarm.get("MetricName")@@ -167,24 +175,29 @@ def _evaluate_all_alarms():def _record_history(alarm_name, old_state, new_state, reason):- _alarm_history.append({- "AlarmName": alarm_name,- "AlarmType": "MetricAlarm",- "Timestamp": _ts_iso(time.time()),- "HistoryItemType": "StateUpdate",- "HistorySummary": f"Alarm updated from {old_state} to {new_state}",- "HistoryData": json.dumps({- "version": "1.0",- "oldState": {"stateValue": old_state},- "newState": {"stateValue": new_state, "stateReason": reason},- }),- })+ _alarm_history.append(+ {+ "AlarmName": alarm_name,+ "AlarmType": "MetricAlarm",+ "Timestamp": _ts_iso(time.time()),+ "HistoryItemType": "StateUpdate",+ "HistorySummary": f"Alarm updated from {old_state} to {new_state}",+ "HistoryData": json.dumps(+ {+ "version": "1.0",+ "oldState": {"stateValue": old_state},+ "newState": {"stateValue": new_state, "stateReason": reason},+ }+ ),+ }+ )# ---------------------------------------------------------------------------# Request dispatcher# ---------------------------------------------------------------------------+async def handle_request(method, path, headers, body, query_params):content_type = headers.get("content-type", "")target = headers.get("x-amz-target", "")@@ -198,6 +211,7 @@ async def handle_request(method, path, headers, body, query_params):if is_cbor:try:import cbor2+cbor_data = cbor2.loads(body) or {}except Exception as e:logger.error(f"CBOR decode error: {e}")@@ -249,7 +263,9 @@ async def handle_request(method, path, headers, body, query_params):handler = handlers.get(action)if not handler:- return _error("InvalidAction", f"Unknown action: {action}", 400, is_cbor or is_json)+ return _error(+ "InvalidAction", f"Unknown action: {action}", 400, is_cbor or is_json+ )return handler(params, cbor_data, is_cbor, is_json)@@ -257,6 +273,7 @@ async def handle_request(method, path, headers, body, query_params):# PutMetricData# ---------------------------------------------------------------------------+def _put_metric_data(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:namespace = cbor_data.get("Namespace", "")@@ -269,28 +286,35 @@ def _put_metric_data(params, cbor_data, is_cbor, is_json=False):counts = md.get("Counts", [1.0] * len(values))for v, c in zip(values, counts):for _ in range(int(c)):- _metrics[(namespace, mn, _dims_key(dims))].append({- "Timestamp": _parse_ts(md.get("Timestamp")) or time.time(),- "Value": float(v),- "Unit": md.get("Unit", "None"),- "Dimensions": dims,- })+ _metrics[(namespace, mn, _dims_key(dims))].append(+ {+ "Timestamp": _parse_ts(md.get("Timestamp"))+ or time.time(),+ "Value": float(v),+ "Unit": md.get("Unit", "None"),+ "Dimensions": dims,+ }+ )elif "StatisticValues" in md:sv = md["StatisticValues"]- _metrics[(namespace, mn, _dims_key(dims))].append({- "Timestamp": _parse_ts(md.get("Timestamp")) or time.time(),- "Value": sv.get("Sum", 0) / max(sv.get("SampleCount", 1), 1),- "Unit": md.get("Unit", "None"),- "Dimensions": dims,- "_stat": sv,- })+ _metrics[(namespace, mn, _dims_key(dims))].append(+ {+ "Timestamp": _parse_ts(md.get("Timestamp")) or time.time(),+ "Value": sv.get("Sum", 0) / max(sv.get("SampleCount", 1), 1),+ "Unit": md.get("Unit", "None"),+ "Dimensions": dims,+ "_stat": sv,+ }+ )else:- _metrics[(namespace, mn, _dims_key(dims))].append({- "Timestamp": _parse_ts(md.get("Timestamp")) or time.time(),- "Value": float(md.get("Value", 0)),- "Unit": md.get("Unit", "None"),- "Dimensions": dims,- })+ _metrics[(namespace, mn, _dims_key(dims))].append(+ {+ "Timestamp": _parse_ts(md.get("Timestamp")) or time.time(),+ "Value": float(md.get("Value", 0)),+ "Unit": md.get("Unit", "None"),+ "Dimensions": dims,+ }+ )else:namespace = _p(params, "Namespace")i = 1@@ -303,12 +327,18 @@ def _put_metric_data(params, cbor_data, is_cbor, is_json=False):dims = {}j = 1while _p(params, f"MetricData.member.{i}.Dimensions.member.{j}.Name"):- dims[_p(params, f"MetricData.member.{i}.Dimensions.member.{j}.Name")] = \- _p(params, f"MetricData.member.{i}.Dimensions.member.{j}.Value")+ dims[+ _p(params, f"MetricData.member.{i}.Dimensions.member.{j}.Name")+ ] = _p(params, f"MetricData.member.{i}.Dimensions.member.{j}.Value")j += 1- _metrics[(namespace, mn, _dims_key(dims))].append({- "Timestamp": ts, "Value": value, "Unit": unit, "Dimensions": dims,- })+ _metrics[(namespace, mn, _dims_key(dims))].append(+ {+ "Timestamp": ts,+ "Value": value,+ "Unit": unit,+ "Dimensions": dims,+ }+ )i += 1_evaluate_all_alarms()@@ -324,6 +354,7 @@ def _put_metric_data(params, cbor_data, is_cbor, is_json=False):# ListMetrics# ---------------------------------------------------------------------------+def _list_metrics(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:namespace = cbor_data.get("Namespace")@@ -345,13 +376,18 @@ def _list_metrics(params, cbor_data, is_cbor, is_json=False):if key in seen:continueseen.add(key)- dims = [{"Name": k, "Value": v}- for k, v in (points[0].get("Dimensions", {}) if points else {}).items()]+ dims = [+ {"Name": k, "Value": v}+ for k, v in (points[0].get("Dimensions", {}) if points else {}).items()+ ]if req_dims:match = all(- any(d["Name"] == rd.get("Name") and (not rd.get("Value") or d["Value"] == rd["Value"])- for d in dims)+ any(+ d["Name"] == rd.get("Name")+ and (not rd.get("Value") or d["Value"] == rd["Value"])+ for d in dims+ )for rd in req_dims)if not match:@@ -368,18 +404,25 @@ def _list_metrics(params, cbor_data, is_cbor, is_json=False):for item in result:dims_xml = "".join(f"<member><Name>{d['Name']}</Name><Value>{d['Value']}</Value></member>"- for d in item["Dimensions"])- members += (f"<member><Namespace>{item['Namespace']}</Namespace>"- f"<MetricName>{item['MetricName']}</MetricName>"- f"<Dimensions>{dims_xml}</Dimensions></member>")- return _xml(200, "ListMetricsResponse",- f"<ListMetricsResult><Metrics>{members}</Metrics></ListMetricsResult>")+ for d in item["Dimensions"]+ )+ members += (+ f"<member><Namespace>{item['Namespace']}</Namespace>"+ f"<MetricName>{item['MetricName']}</MetricName>"+ f"<Dimensions>{dims_xml}</Dimensions></member>"+ )+ return _xml(+ 200,+ "ListMetricsResponse",+ f"<ListMetricsResult><Metrics>{members}</Metrics></ListMetricsResult>",+ )# ---------------------------------------------------------------------------# GetMetricStatistics — with time-range filtering + period aggregation# ---------------------------------------------------------------------------+def _get_metric_statistics(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:namespace = cbor_data.get("Namespace")@@ -422,7 +465,10 @@ def _get_metric_statistics(params, cbor_data, is_cbor, is_json=False):for ts in sorted(buckets):vals = buckets[ts]stats = _calc_stats(vals)- dp = {"Timestamp": _ts_iso(ts), "Unit": all_points[0]["Unit"] if all_points else "None"}+ dp = {+ "Timestamp": _ts_iso(ts),+ "Unit": all_points[0]["Unit"] if all_points else "None",+ }for s in req_stats:if s in stats:dp[s] = stats[s]@@ -434,9 +480,12 @@ def _get_metric_statistics(params, cbor_data, is_cbor, is_json=False):return _json_ok({"Datapoints": datapoints, "Label": metric_name})if not datapoints:- return _xml(200, "GetMetricStatisticsResponse",- f"<GetMetricStatisticsResult><Datapoints/><Label>{metric_name}</Label>"- f"</GetMetricStatisticsResult>")+ return _xml(+ 200,+ "GetMetricStatisticsResponse",+ f"<GetMetricStatisticsResult><Datapoints/><Label>{metric_name}</Label>"+ f"</GetMetricStatisticsResult>",+ )dps = ""for dp in datapoints:inner = f"<Timestamp>{dp['Timestamp']}</Timestamp>"@@ -444,23 +493,64 @@ def _get_metric_statistics(params, cbor_data, is_cbor, is_json=False):if k not in ("Timestamp",):inner += f"<{k}>{v}</{k}>"dps += f"<member>{inner}</member>"- return _xml(200, "GetMetricStatisticsResponse",- f"<GetMetricStatisticsResult><Datapoints>{dps}</Datapoints>"- f"<Label>{metric_name}</Label></GetMetricStatisticsResult>")+ return _xml(+ 200,+ "GetMetricStatisticsResponse",+ f"<GetMetricStatisticsResult><Datapoints>{dps}</Datapoints>"+ f"<Label>{metric_name}</Label></GetMetricStatisticsResult>",+ )# ---------------------------------------------------------------------------# GetMetricData — modern multi-query API# ---------------------------------------------------------------------------+def _get_metric_data(params, cbor_data, is_cbor, is_json=False):- if not (is_cbor or is_json):- return _error("InvalidParameterValue",- "GetMetricData is only supported via JSON/CBOR", 400, False)+ if is_cbor or is_json:+ queries = cbor_data.get("MetricDataQueries", [])+ start_time = _parse_ts(cbor_data.get("StartTime"))+ end_time = _parse_ts(cbor_data.get("EndTime"))+ else:+ # Query protocol (form-encoded). Support the subset used by our tests.+ queries = []+ qi = 1+ while _p(params, f"MetricDataQueries.member.{qi}.Id"):+ qid = _p(params, f"MetricDataQueries.member.{qi}.Id")+ label = _p(params, f"MetricDataQueries.member.{qi}.Label") or qid+ return_data = _p(params, f"MetricDataQueries.member.{qi}.ReturnData")+ return_data = return_data != "false"+ ns = _p(+ params,+ f"MetricDataQueries.member.{qi}.MetricStat.Metric.Namespace",+ )+ mn = _p(+ params,+ f"MetricDataQueries.member.{qi}.MetricStat.Metric.MetricName",+ )+ period = int(+ _p(params, f"MetricDataQueries.member.{qi}.MetricStat.Period") or "60"+ )+ stat_name = (+ _p(params, f"MetricDataQueries.member.{qi}.MetricStat.Stat")+ or "Average"+ )+ queries.append(+ {+ "Id": qid,+ "Label": label,+ "ReturnData": return_data,+ "MetricStat": {+ "Metric": {"Namespace": ns, "MetricName": mn},+ "Period": period,+ "Stat": stat_name,+ },+ }+ )+ qi += 1- queries = cbor_data.get("MetricDataQueries", [])- start_time = _parse_ts(cbor_data.get("StartTime"))- end_time = _parse_ts(cbor_data.get("EndTime"))+ start_time = _parse_ts(_p(params, "StartTime"))+ end_time = _parse_ts(_p(params, "EndTime"))results = []for q in queries:@@ -469,12 +559,18 @@ def _get_metric_data(params, cbor_data, is_cbor, is_json=False):return_data = q.get("ReturnData", True)if q.get("Expression"):- results.append({- "Id": qid, "Label": label,- "StatusCode": "InternalError",- "Messages": [{"Code": "Unsupported", "Value": "Expressions not implemented"}],- "Timestamps": [], "Values": [],- })+ results.append(+ {+ "Id": qid,+ "Label": label,+ "StatusCode": "InternalError",+ "Messages": [+ {"Code": "Unsupported", "Value": "Expressions not implemented"}+ ],+ "Timestamps": [],+ "Values": [],+ }+ )continuems = q.get("MetricStat", {})@@ -506,21 +602,46 @@ def _get_metric_data(params, cbor_data, is_cbor, is_json=False):values.append(_stat_value(stats, stat_name))if return_data:- results.append({- "Id": qid, "Label": label,- "Timestamps": timestamps, "Values": values,- "StatusCode": "Complete",- })+ results.append(+ {+ "Id": qid,+ "Label": label,+ "Timestamps": timestamps,+ "Values": values,+ "StatusCode": "Complete",+ }+ )if is_cbor:return _cbor_ok({"MetricDataResults": results})- return _json_ok({"MetricDataResults": results})+ if is_json:+ return _json_ok({"MetricDataResults": results})++ members = ""+ for r in results:+ ts_members = "".join(f"<member>{t}</member>" for t in r.get("Timestamps", []))+ val_members = "".join(f"<member>{v}</member>" for v in r.get("Values", []))+ members += (+ "<member>"+ f"<Id>{r.get('Id','')}</Id>"+ f"<Label>{r.get('Label','')}</Label>"+ f"<StatusCode>{r.get('StatusCode','Complete')}</StatusCode>"+ f"<Timestamps>{ts_members}</Timestamps>"+ f"<Values>{val_members}</Values>"+ "</member>"+ )+ return _xml(+ 200,+ "GetMetricDataResponse",+ f"<GetMetricDataResult><MetricDataResults>{members}</MetricDataResults></GetMetricDataResult>",+ )# ---------------------------------------------------------------------------# Alarms# ---------------------------------------------------------------------------+def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:name = cbor_data.get("AlarmName", "")@@ -534,13 +655,19 @@ def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):"ExtendedStatistic": cbor_data.get("ExtendedStatistic"),"Period": int(cbor_data.get("Period", 60)),"EvaluationPeriods": int(cbor_data.get("EvaluationPeriods", 1)),- "DatapointsToAlarm": int(cbor_data.get("DatapointsToAlarm")- or cbor_data.get("EvaluationPeriods", 1)),+ "DatapointsToAlarm": int(+ cbor_data.get("DatapointsToAlarm")+ or cbor_data.get("EvaluationPeriods", 1)+ ),"Threshold": float(cbor_data.get("Threshold", 0)),"ComparisonOperator": cbor_data.get("ComparisonOperator"),"TreatMissingData": cbor_data.get("TreatMissingData", "missing"),- "StateValue": _alarms[name]["StateValue"] if name in _alarms else "INSUFFICIENT_DATA",- "StateReason": _alarms[name]["StateReason"] if name in _alarms else "Unchecked: Initial alarm creation",+ "StateValue": _alarms[name]["StateValue"]+ if name in _alarms+ else "INSUFFICIENT_DATA",+ "StateReason": _alarms[name]["StateReason"]+ if name in _alarms+ else "Unchecked: Initial alarm creation","StateUpdatedTimestamp": time.time(),"ActionsEnabled": cbor_data.get("ActionsEnabled", True),"AlarmActions": cbor_data.get("AlarmActions", []),@@ -555,10 +682,12 @@ def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):dims = []di = 1while _p(params, f"Dimensions.member.{di}.Name"):- dims.append({- "Name": _p(params, f"Dimensions.member.{di}.Name"),- "Value": _p(params, f"Dimensions.member.{di}.Value"),- })+ dims.append(+ {+ "Name": _p(params, f"Dimensions.member.{di}.Name"),+ "Value": _p(params, f"Dimensions.member.{di}.Value"),+ }+ )di += 1alarm_actions = []ai = 1@@ -580,13 +709,20 @@ def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):"ExtendedStatistic": _p(params, "ExtendedStatistic") or None,"Period": int(_p(params, "Period") or "60"),"EvaluationPeriods": int(_p(params, "EvaluationPeriods") or "1"),- "DatapointsToAlarm": int(_p(params, "DatapointsToAlarm")- or _p(params, "EvaluationPeriods") or "1"),+ "DatapointsToAlarm": int(+ _p(params, "DatapointsToAlarm")+ or _p(params, "EvaluationPeriods")+ or "1"+ ),"Threshold": float(_p(params, "Threshold") or "0"),"ComparisonOperator": _p(params, "ComparisonOperator"),"TreatMissingData": _p(params, "TreatMissingData") or "missing",- "StateValue": _alarms[name]["StateValue"] if name in _alarms else "INSUFFICIENT_DATA",- "StateReason": _alarms[name]["StateReason"] if name in _alarms else "Unchecked: Initial alarm creation",+ "StateValue": _alarms[name]["StateValue"]+ if name in _alarms+ else "INSUFFICIENT_DATA",+ "StateReason": _alarms[name]["StateReason"]+ if name in _alarms+ else "Unchecked: Initial alarm creation","StateUpdatedTimestamp": time.time(),"ActionsEnabled": _p(params, "ActionsEnabled") != "false","AlarmActions": alarm_actions,@@ -601,8 +737,12 @@ def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):_alarms[name] = alarmif is_new:- _record_history(name, "INSUFFICIENT_DATA", "INSUFFICIENT_DATA",- "Unchecked: Initial alarm creation")+ _record_history(+ name,+ "INSUFFICIENT_DATA",+ "INSUFFICIENT_DATA",+ "Unchecked: Initial alarm creation",+ )_evaluate_alarm(alarm)@@ -614,33 +754,61 @@ def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):def _put_composite_alarm(params, cbor_data, is_cbor, is_json=False):- if not (is_cbor or is_json):- return _error("InvalidParameterValue",- "PutCompositeAlarm only supported via JSON/CBOR", 400, False)- name = cbor_data.get("AlarmName", "")+ if is_cbor or is_json:+ name = cbor_data.get("AlarmName", "")+ alarm_rule = cbor_data.get("AlarmRule", "")+ desc = cbor_data.get("AlarmDescription", "")+ actions_enabled = cbor_data.get("ActionsEnabled", True)+ alarm_actions = cbor_data.get("AlarmActions", [])+ ok_actions = cbor_data.get("OKActions", [])+ insuff_actions = cbor_data.get("InsufficientDataActions", [])+ else:+ name = _p(params, "AlarmName")+ alarm_rule = _p(params, "AlarmRule")+ desc = _p(params, "AlarmDescription")+ actions_enabled = _p(params, "ActionsEnabled") != "false"+ alarm_actions = []+ ai = 1+ while _p(params, f"AlarmActions.member.{ai}"):+ alarm_actions.append(_p(params, f"AlarmActions.member.{ai}"))+ ai += 1+ ok_actions = []+ oi = 1+ while _p(params, f"OKActions.member.{oi}"):+ ok_actions.append(_p(params, f"OKActions.member.{oi}"))+ oi += 1+ insuff_actions = []+ ii = 1+ while _p(params, f"InsufficientDataActions.member.{ii}"):+ insuff_actions.append(_p(params, f"InsufficientDataActions.member.{ii}"))+ ii += 1+_composite_alarms[name] = {"AlarmName": name,"AlarmArn": f"arn:aws:cloudwatch:{REGION}:{ACCOUNT_ID}:alarm:{name}",- "AlarmDescription": cbor_data.get("AlarmDescription", ""),- "AlarmRule": cbor_data.get("AlarmRule", ""),+ "AlarmDescription": desc,+ "AlarmRule": alarm_rule,"StateValue": "INSUFFICIENT_DATA","StateReason": "Unchecked: Initial alarm creation","StateUpdatedTimestamp": time.time(),- "ActionsEnabled": cbor_data.get("ActionsEnabled", True),- "AlarmActions": cbor_data.get("AlarmActions", []),- "OKActions": cbor_data.get("OKActions", []),- "InsufficientDataActions": cbor_data.get("InsufficientDataActions", []),+ "ActionsEnabled": actions_enabled,+ "AlarmActions": alarm_actions,+ "OKActions": ok_actions,+ "InsufficientDataActions": insuff_actions,"AlarmConfigurationUpdatedTimestamp": time.time(),}if is_cbor:return _cbor_ok({})- return _json_ok({})+ if is_json:+ return _json_ok({})+ return _xml(200, "PutCompositeAlarmResponse", "<PutCompositeAlarmResult/>")# ---------------------------------------------------------------------------# DescribeAlarms# ---------------------------------------------------------------------------+def _describe_alarms(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:names = cbor_data.get("AlarmNames", [])@@ -649,11 +817,18 @@ def _describe_alarms(params, cbor_data, is_cbor, is_json=False):alarm_types = cbor_data.get("AlarmTypes", ["MetricAlarm", "CompositeAlarm"])max_records = cbor_data.get("MaxRecords", 100)else:- names = [_p(params, f"AlarmNames.member.{i}")- for i in range(1, 101) if _p(params, f"AlarmNames.member.{i}")]+ names = [+ _p(params, f"AlarmNames.member.{i}")+ for i in range(1, 101)+ if _p(params, f"AlarmNames.member.{i}")+ ]prefix = _p(params, "AlarmNamePrefix")state = _p(params, "StateValue")- alarm_types = ["MetricAlarm", "CompositeAlarm"]+ alarm_types = [+ _p(params, f"AlarmTypes.member.{i}")+ for i in range(1, 11)+ if _p(params, f"AlarmTypes.member.{i}")+ ] or ["MetricAlarm", "CompositeAlarm"]max_records = int(_p(params, "MaxRecords") or "100")metric_alarms = []@@ -682,25 +857,47 @@ def _describe_alarms(params, cbor_data, is_cbor, is_json=False):metric_alarms = metric_alarms[:max_records]if is_cbor:- return _cbor_ok({"MetricAlarms": metric_alarms, "CompositeAlarms": composite_results})+ return _cbor_ok(+ {"MetricAlarms": metric_alarms, "CompositeAlarms": composite_results}+ )if is_json:- return _json_ok({"MetricAlarms": metric_alarms, "CompositeAlarms": composite_results})+ return _json_ok(+ {"MetricAlarms": metric_alarms, "CompositeAlarms": composite_results}+ )- members = "".join(+ metric_members = "".join(f"<member><AlarmName>{a['AlarmName']}</AlarmName><AlarmArn>{a['AlarmArn']}</AlarmArn>"f"<StateValue>{a['StateValue']}</StateValue><MetricName>{a.get('MetricName','')}</MetricName>"f"<Namespace>{a.get('Namespace','')}</Namespace><Threshold>{a.get('Threshold','')}</Threshold>"- f"<ComparisonOperator>{a.get('ComparisonOperator','')}</ComparisonOperator></member>"+ f"<ComparisonOperator>{a.get('ComparisonOperator','')}</ComparisonOperator>"+ f"<EvaluationPeriods>{a.get('EvaluationPeriods','')}</EvaluationPeriods>"+ f"<StateReason>{a.get('StateReason','')}</StateReason>"+ f"</member>"for a in metric_alarms)- return _xml(200, "DescribeAlarmsResponse",- f"<DescribeAlarmsResult><MetricAlarms>{members}</MetricAlarms></DescribeAlarmsResult>")+ comp_members = "".join(+ f"<member><AlarmName>{a['AlarmName']}</AlarmName><AlarmArn>{a['AlarmArn']}</AlarmArn>"+ f"<AlarmRule>{a.get('AlarmRule','')}</AlarmRule>"+ f"<StateValue>{a.get('StateValue','')}</StateValue>"+ f"<StateReason>{a.get('StateReason','')}</StateReason>"+ f"</member>"+ for a in composite_results+ )+ return _xml(+ 200,+ "DescribeAlarmsResponse",+ f"<DescribeAlarmsResult>"+ f"<MetricAlarms>{metric_members}</MetricAlarms>"+ f"<CompositeAlarms>{comp_members}</CompositeAlarms>"+ f"</DescribeAlarmsResult>",+ )# ---------------------------------------------------------------------------# DescribeAlarmsForMetric# ---------------------------------------------------------------------------+def _describe_alarms_for_metric(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:namespace = cbor_data.get("Namespace", "")@@ -709,8 +906,11 @@ def _describe_alarms_for_metric(params, cbor_data, is_cbor, is_json=False):namespace = _p(params, "Namespace")metric_name = _p(params, "MetricName")- result = [a for a in _alarms.values()- if a.get("Namespace") == namespace and a.get("MetricName") == metric_name]+ result = [+ a+ for a in _alarms.values()+ if a.get("Namespace") == namespace and a.get("MetricName") == metric_name+ ]if is_cbor:return _cbor_ok({"MetricAlarms": result})@@ -722,15 +922,19 @@ def _describe_alarms_for_metric(params, cbor_data, is_cbor, is_json=False):f"<StateValue>{a['StateValue']}</StateValue></member>"for a in result)- return _xml(200, "DescribeAlarmsForMetricResponse",- f"<DescribeAlarmsForMetricResult><MetricAlarms>{members}</MetricAlarms>"- f"</DescribeAlarmsForMetricResult>")+ return _xml(+ 200,+ "DescribeAlarmsForMetricResponse",+ f"<DescribeAlarmsForMetricResult><MetricAlarms>{members}</MetricAlarms>"+ f"</DescribeAlarmsForMetricResult>",+ )# ---------------------------------------------------------------------------# DescribeAlarmHistory# ---------------------------------------------------------------------------+def _describe_alarm_history(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:alarm_name = cbor_data.get("AlarmName")@@ -768,15 +972,19 @@ def _describe_alarm_history(params, cbor_data, is_cbor, is_json=False):f"<HistorySummary>{h['HistorySummary']}</HistorySummary></member>"for h in items)- return _xml(200, "DescribeAlarmHistoryResponse",- f"<DescribeAlarmHistoryResult><AlarmHistoryItems>{members}</AlarmHistoryItems>"- f"</DescribeAlarmHistoryResult>")+ return _xml(+ 200,+ "DescribeAlarmHistoryResponse",+ f"<DescribeAlarmHistoryResult><AlarmHistoryItems>{members}</AlarmHistoryItems>"+ f"</DescribeAlarmHistoryResult>",+ )# ---------------------------------------------------------------------------# DeleteAlarms / Enable / Disable# ---------------------------------------------------------------------------+def _delete_alarms(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:names = cbor_data.get("AlarmNames", [])@@ -803,8 +1011,11 @@ def _enable_alarm_actions(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:names = cbor_data.get("AlarmNames", [])else:- names = [_p(params, f"AlarmNames.member.{i}")- for i in range(1, 101) if _p(params, f"AlarmNames.member.{i}")]+ names = [+ _p(params, f"AlarmNames.member.{i}")+ for i in range(1, 101)+ if _p(params, f"AlarmNames.member.{i}")+ ]for n in names:if n in _alarms:_alarms[n]["ActionsEnabled"] = True@@ -821,8 +1032,11 @@ def _disable_alarm_actions(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:names = cbor_data.get("AlarmNames", [])else:- names = [_p(params, f"AlarmNames.member.{i}")- for i in range(1, 101) if _p(params, f"AlarmNames.member.{i}")]+ names = [+ _p(params, f"AlarmNames.member.{i}")+ for i in range(1, 101)+ if _p(params, f"AlarmNames.member.{i}")+ ]for n in names:if n in _alarms:_alarms[n]["ActionsEnabled"] = False@@ -839,6 +1053,7 @@ def _disable_alarm_actions(params, cbor_data, is_cbor, is_json=False):# SetAlarmState — with history recording# ---------------------------------------------------------------------------+def _set_alarm_state(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:name = cbor_data.get("AlarmName", "")@@ -853,7 +1068,9 @@ def _set_alarm_state(params, cbor_data, is_cbor, is_json=False):alarm = _alarms.get(name) or _composite_alarms.get(name)if not alarm:- return _error("ResourceNotFound", f"Alarm {name} not found", 404, is_cbor or is_json)+ return _error(+ "ResourceNotFound", f"Alarm {name} not found", 404, is_cbor or is_json+ )old_state = alarm["StateValue"]alarm["StateValue"] = new_state@@ -876,6 +1093,7 @@ def _set_alarm_state(params, cbor_data, is_cbor, is_json=False):# TagResource / UntagResource / ListTagsForResource# ---------------------------------------------------------------------------+def _tag_resource(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:arn = cbor_data.get("ResourceARN", "")@@ -885,10 +1103,12 @@ def _tag_resource(params, cbor_data, is_cbor, is_json=False):tags = []i = 1while _p(params, f"Tags.member.{i}.Key"):- tags.append({- "Key": _p(params, f"Tags.member.{i}.Key"),- "Value": _p(params, f"Tags.member.{i}.Value"),- })+ tags.append(+ {+ "Key": _p(params, f"Tags.member.{i}.Key"),+ "Value": _p(params, f"Tags.member.{i}.Value"),+ }+ )i += 1if arn not in _resource_tags:@@ -900,7 +1120,7 @@ def _tag_resource(params, cbor_data, is_cbor, is_json=False):return _cbor_ok({})if is_json:return _json_ok({})- return _xml(200, "TagResourceResponse", "")+ return _xml(200, "TagResourceResponse", "<TagResourceResult/>")def _untag_resource(params, cbor_data, is_cbor, is_json=False):@@ -923,7 +1143,7 @@ def _untag_resource(params, cbor_data, is_cbor, is_json=False):return _cbor_ok({})if is_json:return _json_ok({})- return _xml(200, "UntagResourceResponse", "")+ return _xml(200, "UntagResourceResponse", "<UntagResourceResult/>")def _list_tags_for_resource(params, cbor_data, is_cbor, is_json=False):@@ -940,15 +1160,21 @@ def _list_tags_for_resource(params, cbor_data, is_cbor, is_json=False):return _json_ok({"Tags": tags})members = "".join(- f"<member><Key>{t['Key']}</Key><Value>{t['Value']}</Value></member>" for t in tags)- return _xml(200, "ListTagsForResourceResponse",- f"<ListTagsForResourceResult><Tags>{members}</Tags></ListTagsForResourceResult>")+ f"<member><Key>{t['Key']}</Key><Value>{t['Value']}</Value></member>"+ for t in tags+ )+ return _xml(+ 200,+ "ListTagsForResourceResponse",+ f"<ListTagsForResourceResult><Tags>{members}</Tags></ListTagsForResourceResult>",+ )# ---------------------------------------------------------------------------# Dashboards# ---------------------------------------------------------------------------+def _put_dashboard(params, cbor_data, is_cbor, is_json=False):if is_cbor or is_json:name = cbor_data.get("DashboardName", "")@@ -958,7 +1184,12 @@ def _put_dashboard(params, cbor_data, is_cbor, is_json=False):body = _p(params, "DashboardBody")if not name:- return _error("InvalidParameterValue", "DashboardName is required", 400, is_cbor or is_json)+ return _error(+ "InvalidParameterValue",+ "DashboardName is required",+ 400,+ is_cbor or is_json,+ )_dashboards[name] = {"DashboardName": name,@@ -972,8 +1203,11 @@ def _put_dashboard(params, cbor_data, is_cbor, is_json=False):return _cbor_ok({"DashboardValidationMessages": []})if is_json:return _json_ok({"DashboardValidationMessages": []})- return _xml(200, "PutDashboardResponse",- "<PutDashboardResult><DashboardValidationMessages/></PutDashboardResult>")+ return _xml(+ 200,+ "PutDashboardResponse",+ "<PutDashboardResult><DashboardValidationMessages/></PutDashboardResult>",+ )def _get_dashboard(params, cbor_data, is_cbor, is_json=False):@@ -984,26 +1218,38 @@ def _get_dashboard(params, cbor_data, is_cbor, is_json=False):dash = _dashboards.get(name)if not dash:- return _error("ResourceNotFound", f"Dashboard {name} does not exist", 404, is_cbor or is_json)+ return _error(+ "ResourceNotFound",+ f"Dashboard {name} does not exist",+ 404,+ is_cbor or is_json,+ )if is_cbor:- return _cbor_ok({- "DashboardArn": dash["DashboardArn"],- "DashboardBody": dash["DashboardBody"],- "DashboardName": dash["DashboardName"],- })+ return _cbor_ok(+ {+ "DashboardArn": dash["DashboardArn"],+ "DashboardBody": dash["DashboardBody"],+ "DashboardName": dash["DashboardName"],+ }+ )if is_json:- return _json_ok({- "DashboardArn": dash["DashboardArn"],- "DashboardBody": dash["DashboardBody"],- "DashboardName": dash["DashboardName"],- })- return _xml(200, "GetDashboardResponse",- f"<GetDashboardResult>"- f"<DashboardArn>{dash['DashboardArn']}</DashboardArn>"- f"<DashboardBody>{dash['DashboardBody']}</DashboardBody>"- f"<DashboardName>{dash['DashboardName']}</DashboardName>"- f"</GetDashboardResult>")+ return _json_ok(+ {+ "DashboardArn": dash["DashboardArn"],+ "DashboardBody": dash["DashboardBody"],+ "DashboardName": dash["DashboardName"],+ }+ )+ return _xml(+ 200,+ "GetDashboardResponse",+ f"<GetDashboardResult>"+ f"<DashboardArn>{dash['DashboardArn']}</DashboardArn>"+ f"<DashboardBody>{dash['DashboardBody']}</DashboardBody>"+ f"<DashboardName>{dash['DashboardName']}</DashboardName>"+ f"</GetDashboardResult>",+ )def _delete_dashboards(params, cbor_data, is_cbor, is_json=False):@@ -1023,7 +1269,7 @@ def _delete_dashboards(params, cbor_data, is_cbor, is_json=False):return _cbor_ok({})if is_json:return _json_ok({})- return _xml(200, "DeleteDashboardsResponse", "")+ return _xml(200, "DeleteDashboardsResponse", "<DeleteDashboardsResult/>")def _list_dashboards(params, cbor_data, is_cbor, is_json=False):@@ -1037,12 +1283,14 @@ def _list_dashboards(params, cbor_data, is_cbor, is_json=False):if prefix and not name.startswith(prefix):continuedash = _dashboards[name]- entries.append({- "DashboardName": dash["DashboardName"],- "DashboardArn": dash["DashboardArn"],- "Size": dash["Size"],- "LastModified": _ts_iso(dash["LastModified"]),- })+ entries.append(+ {+ "DashboardName": dash["DashboardName"],+ "DashboardArn": dash["DashboardArn"],+ "Size": dash["Size"],+ "LastModified": _ts_iso(dash["LastModified"]),+ }+ )if is_cbor:return _cbor_ok({"DashboardEntries": entries})@@ -1051,20 +1299,26 @@ def _list_dashboards(params, cbor_data, is_cbor, is_json=False):members = ""for e in entries:- members += (f"<member>"- f"<DashboardName>{e['DashboardName']}</DashboardName>"- f"<DashboardArn>{e['DashboardArn']}</DashboardArn>"- f"<Size>{e['Size']}</Size>"- f"<LastModified>{e['LastModified']}</LastModified>"- f"</member>")- return _xml(200, "ListDashboardsResponse",- f"<ListDashboardsResult><DashboardEntries>{members}</DashboardEntries></ListDashboardsResult>")+ members += (+ f"<member>"+ f"<DashboardName>{e['DashboardName']}</DashboardName>"+ f"<DashboardArn>{e['DashboardArn']}</DashboardArn>"+ f"<Size>{e['Size']}</Size>"+ f"<LastModified>{e['LastModified']}</LastModified>"+ f"</member>"+ )+ return _xml(+ 200,+ "ListDashboardsResponse",+ f"<ListDashboardsResult><DashboardEntries>{members}</DashboardEntries></ListDashboardsResult>",+ )# ---------------------------------------------------------------------------# Protocol / encoding helpers# ---------------------------------------------------------------------------+def _dims_key(dims: dict) -> str:return "|".join(f"{k}={v}" for k, v in sorted(dims.items()))@@ -1077,10 +1331,15 @@ def _p(params, key, default=""):def _cbor_ok(data: dict):try:import cbor2+body = cbor2.dumps(data)except Exception:body = json.dumps(data).encode()- return 200, {"Content-Type": "application/cbor", "smithy-protocol": "rpc-v2-cbor"}, body+ return (+ 200,+ {"Content-Type": "application/cbor", "smithy-protocol": "rpc-v2-cbor"},+ body,+ )def _json_ok(data: dict):@@ -1088,11 +1347,13 @@ def _json_ok(data: dict):def _xml(status, root_tag, inner):- body = (f'<?xml version="1.0" encoding="UTF-8"?>\n'- f'<{root_tag} xmlns="http://monitoring.amazonaws.com/doc/2010-08-01/">\n'- f' {inner}\n'- f' <ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>\n'- f'</{root_tag}>').encode("utf-8")+ body = (+ f'<?xml version="1.0" encoding="UTF-8"?>\n'+ f'<{root_tag} xmlns="http://monitoring.amazonaws.com/doc/2010-08-01/">\n'+ f" {inner}\n"+ f" <ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>\n"+ f"</{root_tag}>"+ ).encode("utf-8")return status, {"Content-Type": "application/xml"}, body@@ -1100,17 +1361,23 @@ def _error(code, message, status, use_json=False):if use_json:try:import cbor2+body = cbor2.dumps({"__type": code, "message": message})return status, {"Content-Type": "application/cbor"}, bodyexcept Exception:pass- return status, {"Content-Type": "application/json"}, \- json.dumps({"__type": code, "message": message}).encode()- body = (f'<?xml version="1.0" encoding="UTF-8"?>\n'- f'<ErrorResponse xmlns="http://monitoring.amazonaws.com/doc/2010-08-01/">\n'- f' <Error><Code>{code}</Code><Message>{message}</Message></Error>\n'- f' <RequestId>{new_uuid()}</RequestId>\n'- f'</ErrorResponse>').encode("utf-8")+ return (+ status,+ {"Content-Type": "application/json"},+ json.dumps({"__type": code, "message": message}).encode(),+ )+ body = (+ f'<?xml version="1.0" encoding="UTF-8"?>\n'+ f'<ErrorResponse xmlns="http://monitoring.amazonaws.com/doc/2010-08-01/">\n'+ f" <Error><Code>{code}</Code><Message>{message}</Message></Error>\n"+ f" <RequestId>{new_uuid()}</RequestId>\n"+ f"</ErrorResponse>"+ ).encode("utf-8")return status, {"Content-Type": "application/xml"}, bodydiff --git a/services/dynamodb.py b/services/dynamodb.pyindex c76115e7..8c10308d 100644--- a/services/dynamodb.py+++ b/services/dynamodb.py@@ -304,8 +304,9 @@ def _get_item(data):return error_response_json("ResourceNotFoundException", f"Requested resource not found: Table: {name} not found", 400)key = data.get("Key", {})- pk_val = _extract_key_val(key.get(table["pk_name"]))- sk_val = _extract_key_val(key.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"+ pk_val, sk_val, key_err = _resolve_table_key_values(table, key, allow_extra=False)+ if key_err:+ return key_erritem = table["items"].get(pk_val, {}).get(sk_val)result = {}@@ -322,8 +323,9 @@ def _delete_item(data):return error_response_json("ResourceNotFoundException", f"Requested resource not found: Table: {name} not found", 400)key = data.get("Key", {})- pk_val = _extract_key_val(key.get(table["pk_name"]))- sk_val = _extract_key_val(key.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"+ pk_val, sk_val, key_err = _resolve_table_key_values(table, key, allow_extra=False)+ if key_err:+ return key_errold_item = table["items"].get(pk_val, {}).get(sk_val)cond_expr = data.get("ConditionExpression")@@ -349,8 +351,9 @@ def _update_item(data):return error_response_json("ResourceNotFoundException", f"Requested resource not found: Table: {name} not found", 400)key = data.get("Key", {})- pk_val = _extract_key_val(key.get(table["pk_name"]))- sk_val = _extract_key_val(key.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"+ pk_val, sk_val, key_err = _resolve_table_key_values(table, key, allow_extra=False)+ if key_err:+ return key_errexisting = table["items"].get(pk_val, {}).get(sk_val)old_item = copy.deepcopy(existing) if existing else None@@ -358,7 +361,8 @@ def _update_item(data):cond_expr = data.get("ConditionExpression")if cond_expr:- if not _evaluate_condition(cond_expr, item, data.get("ExpressionAttributeValues", {}), data.get("ExpressionAttributeNames", {})):+ cond_target = existing or {}+ if not _evaluate_condition(cond_expr, cond_target, data.get("ExpressionAttributeValues", {}), data.get("ExpressionAttributeNames", {})):return error_response_json("ConditionalCheckFailedException", "The conditional request failed", 400)update_expr = data.get("UpdateExpression", "")@@ -530,13 +534,15 @@ def _batch_write_item(data):for req in requests:if "PutRequest" in req:item = req["PutRequest"]["Item"]- pk_val = _extract_key_val(item.get(table["pk_name"]))- sk_val = _extract_key_val(item.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"+ pk_val, sk_val, key_err = _resolve_table_key_values(table, item, allow_extra=True)+ if key_err:+ return key_errtable["items"][pk_val][sk_val] = itemelif "DeleteRequest" in req:key = req["DeleteRequest"]["Key"]- pk_val = _extract_key_val(key.get(table["pk_name"]))- sk_val = _extract_key_val(key.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"+ pk_val, sk_val, key_err = _resolve_table_key_values(table, key, allow_extra=False)+ if key_err:+ return key_errtable["items"].get(pk_val, {}).pop(sk_val, None)_update_counts(table)return json_response({"UnprocessedItems": unprocessed})@@ -555,8 +561,9 @@ def _batch_get_item(data):proj = config.get("ProjectionExpression")config_ean = config.get("ExpressionAttributeNames", {})for key in config.get("Keys", []):- pk_val = _extract_key_val(key.get(table["pk_name"]))- sk_val = _extract_key_val(key.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"+ pk_val, sk_val, key_err = _resolve_table_key_values(table, key, allow_extra=False)+ if key_err:+ return key_erritem = table["items"].get(pk_val, {}).get(sk_val)if item:if proj:@@ -1478,6 +1485,29 @@ def _extract_key_val(attr):return str(attr)+def _resolve_table_key_values(table, attrs, allow_extra):+ attrs = attrs if isinstance(attrs, dict) else {}+ expected_names = {table["pk_name"]}+ if table["sk_name"]:+ expected_names.add(table["sk_name"])+ if not allow_extra and set(attrs.keys()) != expected_names:+ return "", "", _key_schema_validation_error()+ for key_name in expected_names:+ if key_name not in attrs:+ return "", "", _key_schema_validation_error()+ expected_type = _get_attr_type(table, key_name)+ raw_value = attrs.get(key_name)+ if not isinstance(raw_value, dict) or set(raw_value.keys()) != {expected_type}:+ return "", "", _key_schema_validation_error()+ pk_val = _extract_key_val(attrs.get(table["pk_name"]))+ sk_val = _extract_key_val(attrs.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"+ return pk_val, sk_val, None+++def _key_schema_validation_error():+ return error_response_json("ValidationException", "The provided key element does not match the schema", 400)++def _resolve_index_keys(table, index_name):if not index_name:return table["pk_name"], table["sk_name"], Falsediff --git a/services/ecs.py b/services/ecs.pyindex 5eb7c306..c377e2d1 100644--- a/services/ecs.py+++ b/services/ecs.py@@ -808,7 +808,12 @@ def _maybe_mark_stopped(task):for docker_id in task["_docker_ids"]:try:container = docker_client.containers.get(docker_id)- if container.status != "exited":+ # docker SDK caches status; refresh before checking lifecycle+ try:+ container.reload()+ except Exception:+ pass+ if getattr(container, "status", None) != "exited":all_stopped = Falsebreakresult = container.wait()@@ -820,18 +825,20 @@ def _maybe_mark_stopped(task):if not all_stopped:return+ now = _iso()task["lastStatus"] = "STOPPED"task["desiredStatus"] = "STOPPED"- task["stoppedAt"] = time.time()+ task["stoppingAt"] = task.get("stoppingAt") or now+ task["stoppedAt"] = nowtask["stoppedReason"] = "Essential container exited"task["stopCode"] = "EssentialContainerExited"for c in task.get("containers", []):c["lastStatus"] = "STOPPED"c["exitCode"] = exit_code- cluster_name = _resolve_cluster_name(task.get("clusterArn", "").split("/")[-1] if "/" in task.get("clusterArn", "") else "")- if cluster_name in _clusters:- _clusters[cluster_name]["runningTasksCount"] = max(0, _clusters[cluster_name]["runningTasksCount"] - 1)+ cname = _cluster_name_from_arn(task.get("clusterArn", ""))+ if cname:+ _recount_cluster(cname)def _list_tasks(data):diff --git a/services/lambda_svc.py b/services/lambda_svc.pyindex 5191c5bd..51d5089c 100644--- a/services/lambda_svc.py+++ b/services/lambda_svc.py@@ -23,6 +23,9 @@ SQS event source mappings poll the queue in a background thread."""import os+import asyncio+import importlib+from typing import Anyimport copyimport jsonimport time@@ -46,9 +49,10 @@ LAMBDA_EXECUTOR = os.environ.get("LAMBDA_EXECUTOR", "local").lower()LAMBDA_DOCKER_VOLUME_MOUNT = os.environ.get("LAMBDA_REMOTE_DOCKER_VOLUME_MOUNT", "")try:- import docker as docker_lib+ docker_lib: Any = importlib.import_module("docker")_docker_available = Trueexcept ImportError:+ docker_lib = None_docker_available = False_functions: dict = {} # function_name -> FunctionRecord@@ -67,6 +71,11 @@ import sys, os, jsonsys.path.insert(0, os.environ["_LAMBDA_CODE_DIR"])+_REAL_STDOUT = sys.__stdout__+# Match AWS Lambda semantics: logs go to CloudWatch (stderr here),+# while the Invoke response payload must be clean JSON on stdout.+sys.stdout = sys.stderr+for _ld in filter(None, os.environ.get("_LAMBDA_LAYERS_DIRS", "").split(os.pathsep)):_py = os.path.join(_ld, "python")if os.path.isdir(_py):@@ -95,7 +104,8 @@ for _part in _mod_path.split(".")[1:]:_mod = getattr(_mod, _part)_result = getattr(_mod, _fn_name)(event, LambdaContext())if _result is not None:- print(json.dumps(_result))+ _REAL_STDOUT.write(json.dumps(_result))+ _REAL_STDOUT.flush()"""# Docker variant: paths fixed to /var/task (code) and /opt (layers).@@ -104,6 +114,11 @@ import sys, os, jsonsys.path.insert(0, "/var/task")+_REAL_STDOUT = sys.__stdout__+# Match AWS Lambda semantics: logs go to CloudWatch (stderr here),+# while the Invoke response payload must be clean JSON on stdout.+sys.stdout = sys.stderr+for _ld in filter(None, os.environ.get("_LAMBDA_LAYERS_DIRS", "").split(":")):_py = os.path.join(_ld, "python")if os.path.isdir(_py):@@ -132,7 +147,8 @@ for _part in _mod_path.split(".")[1:]:_mod = getattr(_mod, _part)_result = getattr(_mod, _fn_name)(event, LambdaContext())if _result is not None:- print(json.dumps(_result))+ _REAL_STDOUT.write(json.dumps(_result))+ _REAL_STDOUT.flush()"""@@ -186,6 +202,18 @@ def _now_iso() -> str:return time.strftime("%Y-%m-%dT%H:%M:%S.000+0000")+def _normalize_endpoint_url(value: str) -> str:+ v = (value or "").strip()+ if not v:+ return ""+ if v.startswith("http://") or v.startswith("https://"):+ return v+ host = v.rstrip("/")+ if ":" not in host:+ host = f"{host}:4566"+ return f"http://{host}"++def _build_config(name: str, data: dict, code_zip: bytes | None = None) -> dict:code_size = len(code_zip) if code_zip else 0code_sha = base64.b64encode(hashlib.sha256(code_zip).digest()).decode() if code_zip else ""@@ -408,7 +436,7 @@ async def handle_request(method: str, path: str, headers: dict,# Invokeif method == "POST" and sub == "invocations":- return _invoke(func_name, data, headers, path_qualifier)+ return await _invoke(func_name, data, headers, path_qualifier)# PublishVersionif method == "POST" and sub == "versions":@@ -641,8 +669,8 @@ def _update_config(name: str, data: dict):# Invoke# ----------------------------------------------------------------------------def _invoke(name: str, event: dict, headers: dict,- path_qualifier: str | None = None):+async def _invoke(name: str, event: dict, headers: dict,+ path_qualifier: str | None = None):if name not in _functions:return error_response_json("ResourceNotFoundException",@@ -684,8 +712,9 @@ def _invoke(name: str, event: dict, headers: dict,).start()return 202, {"X-Amz-Executed-Version": executed_version}, b""- # RequestResponse — synchronous execution- result = _execute_function(exec_record, event)+ # RequestResponse — execute in worker thread so nested SDK calls+ # from the Lambda process can still reach this ASGI server.+ result = await asyncio.to_thread(_execute_function, exec_record, event)resp_headers: dict = {"Content-Type": "application/json",@@ -851,7 +880,11 @@ def _execute_function_docker(func: dict, event: dict) -> dict:"_LAMBDA_TIMEOUT": str(timeout),"_LAMBDA_LAYERS_DIRS": ":".join(container_layer_dirs),}- endpoint = os.environ.get("AWS_ENDPOINT_URL", "")+ endpoint = _normalize_endpoint_url(os.environ.get("AWS_ENDPOINT_URL", ""))+ if not endpoint:+ endpoint = _normalize_endpoint_url(env_vars.get("AWS_ENDPOINT_URL", ""))+ if not endpoint:+ endpoint = _normalize_endpoint_url(env_vars.get("LOCALSTACK_HOSTNAME", ""))if endpoint:container_env["AWS_ENDPOINT_URL"] = endpointcontainer_env.update(env_vars)@@ -1000,7 +1033,11 @@ def _execute_function_local(func: dict, event: dict) -> dict:"_LAMBDA_TIMEOUT": str(timeout),"_LAMBDA_LAYERS_DIRS": os.pathsep.join(layers_dirs),})- endpoint = os.environ.get("AWS_ENDPOINT_URL", "")+ endpoint = _normalize_endpoint_url(os.environ.get("AWS_ENDPOINT_URL", ""))+ if not endpoint:+ endpoint = _normalize_endpoint_url(env_vars.get("AWS_ENDPOINT_URL", ""))+ if not endpoint:+ endpoint = _normalize_endpoint_url(env_vars.get("LOCALSTACK_HOSTNAME", ""))if endpoint:env["AWS_ENDPOINT_URL"] = endpointenv.update(env_vars)@@ -1034,14 +1071,31 @@ def _execute_function_local(func: dict, event: dict) -> dict:"log": log_tail,}- except subprocess.TimeoutExpired:+ except subprocess.TimeoutExpired as exc:+ try:+ _stdout = getattr(exc, "stdout", None) or ""+ if isinstance(_stdout, bytes):+ _stdout = _stdout.decode("utf-8", errors="replace")+ _stdout = str(_stdout).strip()+ except Exception:+ _stdout = ""+ try:+ _stderr = getattr(exc, "stderr", None) or ""+ if isinstance(_stderr, bytes):+ _stderr = _stderr.decode("utf-8", errors="replace")+ _stderr = str(_stderr).strip()+ except Exception:+ _stderr = ""+ _log = "\n".join([p for p in (_stderr, _stdout) if p])+ if not _log:+ _log = "Lambda timed out (no stderr/stdout captured)."return {"body": {"errorMessage": f"Task timed out after {timeout}.00 seconds","errorType": "Runtime.ExitError",},"error": True,- "log": "",+ "log": _log,}except Exception as e:logger.error(f"Lambda execution error: {e}")@@ -1751,22 +1805,15 @@ def _poll_once():batch_size = esm.get("BatchSize", 10)now = time.time()- batch = []- for msg in list(queue["messages"]):- if len(batch) >= batch_size:- break- if msg["visible_at"] <= now and msg.get("receipt_handle") is None:- batch.append(msg)+ batch = _sqs._receive_messages_for_esm(queue_url, batch_size)if not batch:continue- for msg in batch:- msg["receipt_handle"] = new_uuid()- msg["visible_at"] = now + 30-records = []for msg in batch:+ # sqs._collect_msgs already increments receive_count and sets first_receive_at+ first_recv = msg.get("first_receive_at") or nowrecords.append({"messageId": msg["id"],"receiptHandle": msg["receipt_handle"],@@ -1775,10 +1822,10 @@ def _poll_once():"ApproximateReceiveCount": str(msg.get("receive_count", 1)),"SentTimestamp": str(int(msg["sent_at"] * 1000)),"SenderId": ACCOUNT_ID,- "ApproximateFirstReceiveTimestamp": str(int(now * 1000)),+ "ApproximateFirstReceiveTimestamp": str(int(first_recv * 1000)),},- "messageAttributes": msg.get("attributes", {}),- "md5OfBody": msg["md5"],+ "messageAttributes": msg.get("message_attributes", {}),+ "md5OfBody": msg.get("md5_body") or msg.get("md5") or "","eventSource": "aws:sqs","eventSourceARN": source_arn,"awsRegion": REGION,@@ -1788,19 +1835,29 @@ def _poll_once():result = _execute_function(_functions[func_name], event)if result.get("error"):- for msg in batch:- msg["receipt_handle"] = None- msg["visible_at"] = now+ # Surface Lambda failure details (otherwise debugging is impossible).+ # `result` follows the shape returned by `_execute_function_*`:+ # - body: Lambda payload (often contains errorType/errorMessage on failure)+ # - log: stderr / traceback tail (best signal for root cause)+ err_body = result.get("body") or {}+ err_type = None+ err_msg = None+ if isinstance(err_body, dict):+ err_type = err_body.get("errorType")+ err_msg = err_body.get("errorMessage")+ err_log = result.get("log") or ""esm["LastProcessingResult"] = "FAILED"logger.warning(- f"ESM: Lambda {func_name} failed processing batch from {queue_name}",+ "ESM: Lambda %s failed processing batch from %s (errorType=%s errorMessage=%s)\n%s",+ func_name,+ queue_name,+ err_type,+ err_msg,+ err_log,)else:- receipt_handles = {msg["receipt_handle"] for msg in batch}- queue["messages"] = [- m for m in queue["messages"]- if m.get("receipt_handle") not in receipt_handles- ]+ receipt_handles = {msg["receipt_handle"] for msg in batch if msg.get("receipt_handle")}+ _sqs._delete_messages_for_esm(queue_url, receipt_handles)esm["LastProcessingResult"] = f"OK - {len(batch)} records"logger.info(f"ESM: Lambda {func_name} processed {len(batch)} messages from {queue_name}",diff --git a/services/sqs.py b/services/sqs.pyindex f07cbaab..e20a3909 100644--- a/services/sqs.py+++ b/services/sqs.py@@ -1182,3 +1182,40 @@ def _url_from_path(path: str) -> str:def reset():_queues.clear()_queue_name_to_url.clear()+++# ────────────────────────────────────────────────────────────+# ESM helpers (internal)+# ────────────────────────────────────────────────────────────+#+# Lambda Event Source Mapping (SQS → Lambda) should behave like a real client:+# - "receive" makes messages invisible for the queue VisibilityTimeout and assigns ReceiptHandle+# - "delete" removes by ReceiptHandle+#+# The ESM poller lives in `services/lambda_svc.py` and runs in a background thread+# (non-async), so we provide sync helpers that reuse the same core SQS logic as+# ReceiveMessage/DeleteMessageBatch.+++def _receive_messages_for_esm(queue_url: str, max_number: int) -> list[dict]:+ """Receive up to max_number messages for ESM consumption.++ Returns the *internal* message dicts (with receipt_handle set) so the ESM poller+ can build AWS Lambda SQS event payloads and then delete via receipt handles.+ """+ q = _get_q(queue_url)+ max_n = min(int(max_number or 1), 10)+ vis = int(q["attributes"].get("VisibilityTimeout", "30"))+ _dlq_sweep(q)+ return _collect_msgs(q, max_n, vis)+++def _delete_messages_for_esm(queue_url: str, receipt_handles: set[str]) -> None:+ """Best-effort delete of messages received by ESM."""+ if not receipt_handles:+ return+ q = _get_q(queue_url)+ q["messages"] = [+ m for m in q["messages"]+ if not (m.get("receipt_handle") is not None and m.get("receipt_handle") in receipt_handles)+ ]diff --git a/tests/test_services.py b/tests/test_services.pyindex 26a88d77..f8751133 100644--- a/tests/test_services.py+++ b/tests/test_services.py@@ -1653,6 +1653,94 @@ def test_ddb_update_item_remove(ddb):assert resp["Attributes"]["keep"]["S"] == "stay"+def test_ddb_update_item_condition_on_missing_item_fails(ddb):+ """Missing item + attribute_exists(...) condition must fail with ConditionalCheckFailedException."""+ try:+ ddb.delete_table(TableName="t_update_cond_missing")+ except Exception:+ pass+ ddb.create_table(+ TableName="t_update_cond_missing",+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ missing_key = {"pk": {"S": "missing-update-item"}}+ with pytest.raises(ClientError) as exc:+ ddb.update_item(+ TableName="t_update_cond_missing",+ Key=missing_key,+ UpdateExpression="SET v = :v",+ ExpressionAttributeValues={":v": {"S": "x"}},+ ConditionExpression="attribute_exists(pk)",+ ReturnValues="ALL_NEW",+ )+ assert exc.value.response["Error"]["Code"] == "ConditionalCheckFailedException"+++def test_ddb_get_item_missing_sort_key_fails_validation(ddb):+ try:+ ddb.delete_table(TableName="t_get_missing_sk")+ except Exception:+ pass+ ddb.create_table(+ TableName="t_get_missing_sk",+ KeySchema=[+ {"AttributeName": "pk", "KeyType": "HASH"},+ {"AttributeName": "sk", "KeyType": "RANGE"},+ ],+ AttributeDefinitions=[+ {"AttributeName": "pk", "AttributeType": "S"},+ {"AttributeName": "sk", "AttributeType": "S"},+ ],+ BillingMode="PAY_PER_REQUEST",+ )+ with pytest.raises(ClientError) as exc:+ ddb.get_item(TableName="t_get_missing_sk", Key={"pk": {"S": "q_pk"}})+ assert exc.value.response["Error"]["Code"] == "ValidationException"+ assert exc.value.response["Error"]["Message"] == "The provided key element does not match the schema"+++def test_ddb_get_item_wrong_key_type_fails_validation(ddb):+ try:+ ddb.delete_table(TableName="t_get_wrong_type")+ except Exception:+ pass+ ddb.create_table(+ TableName="t_get_wrong_type",+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ ddb.put_item(TableName="t_get_wrong_type", Item={"pk": {"S": "typed-key"}})+ with pytest.raises(ClientError) as exc:+ ddb.get_item(TableName="t_get_wrong_type", Key={"pk": {"N": "123"}})+ assert exc.value.response["Error"]["Code"] == "ValidationException"+ assert exc.value.response["Error"]["Message"] == "The provided key element does not match the schema"+++def test_ddb_update_item_extra_key_attribute_fails_validation(ddb):+ try:+ ddb.delete_table(TableName="t_update_extra_key")+ except Exception:+ pass+ ddb.create_table(+ TableName="t_update_extra_key",+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ with pytest.raises(ClientError) as exc:+ ddb.update_item(+ TableName="t_update_extra_key",+ Key={"pk": {"S": "k1"}, "sk": {"S": "unexpected"}},+ UpdateExpression="SET v = :v",+ ExpressionAttributeValues={":v": {"S": "x"}},+ )+ assert exc.value.response["Error"]["Code"] == "ValidationException"+ assert exc.value.response["Error"]["Message"] == "The provided key element does not match the schema"++def test_ddb_update_item_add(ddb):ddb.put_item(TableName="t_hash_only", Item={"pk": {"S": "upd_add"}, "counter": {"N": "5"}})resp = ddb.update_item(@@ -2125,6 +2213,67 @@ def test_lambda_esm_sqs_comprehensive(lam, sqs):lam.delete_event_source_mapping(UUID=esm_uuid)+def test_lambda_esm_sqs_failure_respects_visibility_timeout(lam, sqs):+ """On Lambda failure, the message should remain in-flight until VisibilityTimeout expires."""+ import io+ import zipfile as zf++ for fn in ("esm-fail-func",):+ try:+ lam.delete_function(FunctionName=fn)+ except Exception:+ pass++ code = b"def handler(event, context):\n" b" raise Exception('boom')\n"+ buf = io.BytesIO()+ with zf.ZipFile(buf, "w") as z:+ z.writestr("index.py", code)++ lam.create_function(+ FunctionName="esm-fail-func",+ Runtime="python3.9",+ Role="arn:aws:iam::000000000000:role/test-role",+ Handler="index.handler",+ Code={"ZipFile": buf.getvalue()},+ Timeout=3,+ )++ q_url = sqs.create_queue(+ QueueName="esm-fail-queue",+ Attributes={"VisibilityTimeout": "1"},+ )["QueueUrl"]+ q_arn = sqs.get_queue_attributes(QueueUrl=q_url, AttributeNames=["QueueArn"])[+ "Attributes"+ ]["QueueArn"]++ resp = lam.create_event_source_mapping(+ EventSourceArn=q_arn,+ FunctionName="esm-fail-func",+ BatchSize=1,+ Enabled=True,+ )+ esm_uuid = resp["UUID"]++ sqs.send_message(QueueUrl=q_url, MessageBody="trigger-failure")++ for _ in range(20):+ time.sleep(0.2)+ cur = lam.get_event_source_mapping(UUID=esm_uuid)+ if cur.get("LastProcessingResult") == "FAILED":+ break++ lam.update_event_source_mapping(UUID=esm_uuid, Enabled=False)++ msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=0)+ assert not msgs.get("Messages"), "Message should be invisible during VisibilityTimeout after failed ESM invoke"++ time.sleep(1.2)+ msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=0)+ assert msgs.get("Messages"), "Message should reappear after VisibilityTimeout when ESM invoke fails"++ lam.delete_event_source_mapping(UUID=esm_uuid)++# ===================================================================# IAM — comprehensive tests# ===================================================================