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 conformance validation (#1207)
Nahuel Nucera01a8e7258178
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bae8cef3..e83beb37 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,16 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added+- **SNS — `ListPlatformApplications`** — the mobile-push action returned `InvalidAction` even though platform applications created with `CreatePlatformApplication` were already stored. It now lists the caller's platform applications with their attributes and `NextToken` pagination; results are account+region scoped, matching AWS's per-region platform applications. Reported by @ctalibard-sk.+- **Kinesis Data Firehose — `AWS::KinesisFirehose::DeliveryStream` CloudFormation support** — stacks containing a delivery stream failed with `Unsupported resource type` even though the Firehose API already implemented `CreateDeliveryStream`. The resource now provisions through CloudFormation into the existing Firehose control plane (S3, Extended S3, Iceberg, and the other destination configs), `Ref` returns the delivery stream name, and `Fn::GetAtt Arn` returns its ARN. Reported by @ryan-bennett.+- **Kinesis Data Firehose — Apache Iceberg (S3 Tables) delivery** — a DirectPut delivery stream with an `IcebergDestinationConfiguration` now actually writes records into the target S3 Tables Iceberg table, not just provisions the stream. Each record routes to its destination table from the `DestinationTableConfigurationList` (or a transform Lambda's `metadata.otfMetadata`), and the row operation follows real Firehose Merge-on-Read semantics: `insert` by default, `update`/`delete` matched on the table's `UniqueKeys` (a record whose operation needs keys but has none is dropped to the error path, as on AWS). Rows are written through the S3 Tables Iceberg REST catalog using the bundled DuckDB engine and are immediately queryable. Reported by @ryan-bennett.++### Fixed+- **DynamoDB — validation and read metering aligned with real AWS** — a batch of parity fixes driven by the dynamodb-conformance suite. Numeric values with surrounding whitespace or underscores (`" 5"`, `"1_000"`) are now rejected; document nesting is capped at 32 levels; partition and sort key values are capped at 2048 and 1024 bytes and expression strings at 4096 bytes. `CreateTable` validates index `Projection` settings (`INCLUDE` requires `NonKeyAttributes`, `KEYS_ONLY` forbids them, unknown types are rejected) and rejects a `StreamSpecification` with `StreamEnabled: false` alongside a `StreamViewType`. `UpdateTable` merges `AttributeDefinitions` by name and prunes ones no longer referenced by the key schema or any index. `PutItem`, `UpdateItem`, and `BatchWriteItem` reject wrong-typed, non-scalar, or empty values written into a secondary-index key attribute. `Query` and `Scan` reject incompatible `Select`/`ProjectionExpression` combinations with the AWS messages, and a composite index excludes items missing its range key (sparse indexes). `ConditionExpression` `BETWEEN` validates that the lower bound does not exceed the upper at parse time. PartiQL `UPDATE`/`DELETE` return `{"Items": []}` rather than an empty object. Eventually-consistent reads now meter 0.5 RCU (strongly-consistent reads 1.0). Empty binary set members are accepted; only empty string-set members are rejected.+- **S3 Tables — Iceberg REST catalog returned AWS-shaped errors instead of the spec envelope** — the `/iceberg` endpoints returned `{"__type": "NotFoundException", ...}` on a missing namespace or table, but the Iceberg REST OpenAPI requires `{"error": {"message", "type", "code"}}`. Spec-compliant REST clients (DuckDB, Spark, Trino) treat a `LoadTable` 404 as "proceed to create", but only when it is a proper `NoSuchTableException`; the AWS shape made them abort, so writing to an S3 Tables Iceberg table over the REST catalog failed. Errors on the `/iceberg` surface now use the REST spec envelope (`NoSuchTableException` / `NoSuchNamespaceException`), leaving the S3 Tables control plane's AWS error shape unchanged.+- **Lambda (Docker executor) — Docker-in-Docker ZIP functions failed with `invalid mount config for type "bind"`** — when MiniStack ran inside a container and `LAMBDA_REMOTE_DOCKER_VOLUME_MOUNT` was set (as the README previously advised), the runtime container was created with a bind mount whose source was the *volume name* rather than an absolute path, so Docker rejected it with `mount path must be absolute` and every ZIP invocation failed. In-container runs now always populate the sibling container's `/var/task` (and `/var/runtime` for `provided.*`) via `docker cp` over the host socket — no shared volume required. `LAMBDA_REMOTE_DOCKER_VOLUME_MOUNT` is deprecated and ignored. Reported by @smoores-dev.+## [1.4.6] — 2026-07-24### Addeddiff --git a/README.md b/README.mdindex 450506da..18e76655 100644--- a/README.md+++ b/README.md@@ -914,7 +914,7 @@ Supported runtimes and the AWS public ECR images MiniStack pulls for them:Containers are named `lambda-<random-hex-16>` and pooled across invocations. Idle containers are reaped after `LAMBDA_WARM_TTL_SECONDS` (default 300s) — no manual cleanup needed. The pool is also drained on `/_ministack/reset`.-**Docker-in-Docker:** when MiniStack itself runs inside a container, set `LAMBDA_REMOTE_DOCKER_VOLUME_MOUNT` to a Docker named volume that is also mounted at `/var/task` inside the MiniStack container. MiniStack writes the Lambda code into the volume so the sibling Lambda container (started via the host Docker socket) can read it. Not needed when MiniStack runs directly on the host.+**Docker-in-Docker:** when MiniStack itself runs inside a container (with the host Docker socket mounted), it detects that automatically and copies each Lambda's code into the sibling runtime container over the socket. No shared volume or extra configuration is required. The legacy `LAMBDA_REMOTE_DOCKER_VOLUME_MOUNT` env var is deprecated and ignored.**Networking:** when MiniStack runs in Docker Compose, set `DOCKER_NETWORK` to the Compose network name. All container-backed services (Lambda, RDS, EKS, ElastiCache) then attach to that network so Lambda code can reach MiniStack at `http://<ministack-service-name>:4566`. The legacy `LAMBDA_DOCKER_NETWORK` is still accepted (Lambda only) as a fallback.@@ -930,17 +930,12 @@ services:environment:LAMBDA_EXECUTOR: dockerDOCKER_NETWORK: ${COMPOSE_PROJECT_NAME}_infra-network- LAMBDA_REMOTE_DOCKER_VOLUME_MOUNT: ${COMPOSE_PROJECT_NAME}_lambda-docker-volumeAWS_DEFAULT_REGION: ${AWS_REGION:-eu-central-1}volumes:- /var/run/docker.sock:/var/run/docker.sock- - lambda-docker-volume:/var/tasknetworks:- infra-network-volumes:- lambda-docker-volume:-networks:infra-network:```diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex e005b65e..6c869efe 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -34,6 +34,7 @@ import ministack.services.ec2 as _ec2import ministack.services.ecr as _ecrimport ministack.services.ecs as _ecsimport ministack.services.eventbridge as _eb+import ministack.services.firehose as _firehoseimport ministack.services.iam as _iamimport ministack.services.iot as _iotimport ministack.services.kinesis as _kinesis@@ -5222,6 +5223,59 @@ def _s3tables_table_delete(physical_id, props):_s3tables._tables.pop(_s3tables._table_key(bucket_arn, namespace, table_name), None)+# --- Kinesis Data Firehose DeliveryStream ---++def _firehose_delivery_stream_create(logical_id, props, stack_name):+ # CFN Properties mirror the CreateDeliveryStream API shape (destination+ # configs, DeliveryStreamType, Tags), so pass them straight through to the+ # existing Firehose control plane. Ref returns the stream name; Fn::GetAtt+ # Arn returns the stream ARN.+ name = props.get("DeliveryStreamName") or _physical_name(+ stack_name, logical_id, max_len=64+ )+ data = dict(props)+ data["DeliveryStreamName"] = name+ status, _headers, body = _firehose._create_delivery_stream(data)+ if status >= 400:+ raise ValueError(+ f"AWS::KinesisFirehose::DeliveryStream create failed: {body!r}"+ )+ return name, {"Arn": _firehose._stream_arn(name)}+++def _firehose_delivery_stream_update(physical_id, old_props, new_props, stack_name):+ # DeliveryStreamName, DeliveryStreamType, and the source configs require+ # replacement; destination configuration changes apply in place.+ replace_keys = (+ "DeliveryStreamName", "DeliveryStreamType",+ "KinesisStreamSourceConfiguration", "MSKSourceConfiguration",+ )+ if any(new_props.get(k) != old_props.get(k) for k in replace_keys):+ new_id, attrs = _firehose_delivery_stream_create(+ physical_id, new_props, stack_name+ )+ _firehose_delivery_stream_delete(physical_id, old_props)+ return new_id, attrs+ stream = _firehose._streams.get(physical_id)+ if stream is None:+ return _firehose_delivery_stream_create(physical_id, new_props, stack_name)+ dtype, cfg = _firehose._resolve_dest_type_and_config(new_props)+ if dtype and cfg is not None:+ stream["destinations"] = [{+ "id": _firehose._next_dest_id(),+ "type": dtype,+ "config": cfg,+ "records": [],+ }]+ stream["version"] = stream.get("version", 1) + 1+ stream["updated_at"] = _firehose.now_epoch()+ return physical_id, {"Arn": _firehose._stream_arn(physical_id)}+++def _firehose_delivery_stream_delete(physical_id, props):+ _firehose._delete_delivery_stream({"DeliveryStreamName": physical_id})++_RESOURCE_HANDLERS = {"AWS::OpenSearchService::Domain": {"create": _opensearch_domain_create,@@ -5288,6 +5342,11 @@ _RESOURCE_HANDLERS = {"AWS::Events::Rule": {"create": _eb_rule_create, "delete": _eb_rule_delete},"AWS::Events::EventBus": {"create": _eb_event_bus_create, "delete": _eb_event_bus_delete},"AWS::Kinesis::Stream": {"create": _kinesis_stream_create, "delete": _kinesis_stream_delete},+ "AWS::KinesisFirehose::DeliveryStream": {+ "create": _firehose_delivery_stream_create,+ "update": _firehose_delivery_stream_update,+ "delete": _firehose_delivery_stream_delete,+ },"AWS::Lambda::Permission": {"create": _lambda_permission_create, "delete": _lambda_permission_delete},"AWS::Lambda::Version": {"create": _lambda_version_create},"AWS::CloudFormation::WaitCondition": {"create": _cfn_wait_condition_create},diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.pyindex 277244f6..6f1ee180 100644--- a/ministack/services/dynamodb.py+++ b/ministack/services/dynamodb.py@@ -248,6 +248,13 @@ _DDB_TXN_MAX_BYTES = 4 * 1024 * 1024# Batch caps._DDB_BATCH_WRITE_MAX = 25_DDB_BATCH_GET_MAX = 100+# Expression size limit (bytes of the expression string).+_DDB_EXPR_MAX_BYTES = 4096+# Key attribute value length limits.+_DDB_KEY_MAX_BYTES = 2048+_DDB_SORT_KEY_MAX_BYTES = 1024+# Document nesting depth limit (32 levels, leaf is at level 32 means 31 nesting levels for containers).+_DDB_MAX_NESTING_DEPTH = 32def _ddb_canonicalize_number(s: str) -> str | None:@@ -263,7 +270,11 @@ def _ddb_canonicalize_number(s: str) -> str | None:return Noneif not isinstance(s, str) or not s:return None- raw = s.strip()+ # AWS rejects numbers with whitespace or underscores even though Python's+ # Decimal() accepts them (e.g. " 5", "5 ", "1_000").+ if s != s.strip() or '_' in s:+ return None+ raw = s# Reject empty / sign-only / non-numeric.try:d = Decimal(raw)@@ -314,10 +325,15 @@ def _ddb_canonicalize_number(s: str) -> str | None:return sign_str + text-def _validate_attribute_value(attr_name: str, value: dict) -> tuple | None:+def _validate_attribute_value(attr_name: str, value: dict, _depth: int = 1) -> tuple | None:"""Recursively validate a single attribute value. Returns an error responsetuple if invalid, or None if OK. May mutate `value` to canonicalize numbers.+ _depth starts at 1 (top-level attribute value); containers increment before+ recursing. AWS enforces a maximum nesting depth of 32 levels."""+ if _depth > _DDB_MAX_NESTING_DEPTH:+ return error_response_json("ValidationException",+ "One or more parameter values were invalid: document path length exceeded limit", 400)if not isinstance(value, dict) or not value:return error_response_json("ValidationException","Supplied AttributeValue has more than one datatypes set, must contain exactly one of the supported datatypes", 400)@@ -385,10 +401,13 @@ def _validate_attribute_value(attr_name: str, value: dict) -> tuple | None:"One or more parameter values were invalid: Binary sets should not be empty", 400)seen = set()for b in vval:+ # Empty binary members (zero-length) ARE allowed in BS sets — only+ # empty SS members (empty strings) are forbidden. Binary key attributes+ # are forbidden separately; here we only validate the set value.key = b if isinstance(b, str) else (b.decode("latin-1") if isinstance(b, bytes) else None)- if key is None or key == "":+ if key is None:return error_response_json("ValidationException",- "One or more parameter values were invalid: Binary set element may not be empty", 400)+ "One or more parameter values were invalid: Binary set element must be binary type", 400)if key in seen:return error_response_json("ValidationException",f"One or more parameter values were invalid: Input collection [{', '.join(str(v) for v in vval)}] contains duplicates.", 400)@@ -398,7 +417,7 @@ def _validate_attribute_value(attr_name: str, value: dict) -> tuple | None:return error_response_json("ValidationException","One or more parameter values were invalid: List must be a list", 400)for sub in vval:- err = _validate_attribute_value(attr_name, sub)+ err = _validate_attribute_value(attr_name, sub, _depth + 1)if err:return errelif vtype == "M":@@ -406,7 +425,7 @@ def _validate_attribute_value(attr_name: str, value: dict) -> tuple | None:return error_response_json("ValidationException","One or more parameter values were invalid: Map must be a map", 400)for k, sub in vval.items():- err = _validate_attribute_value(attr_name, sub)+ err = _validate_attribute_value(attr_name, sub, _depth + 1)if err:return errelse:@@ -500,6 +519,26 @@ def _validate_item(item: dict, pk_name: str | None = None, sk_name: str | None =err = _validate_attribute_value(name, value)if err:return err+ # Key attribute value length limits: partition key max 2048 bytes, sort key max 1024 bytes.+ for key_name, max_bytes in ((pk_name, _DDB_KEY_MAX_BYTES), (sk_name, _DDB_SORT_KEY_MAX_BYTES)):+ if not key_name or key_name not in item:+ continue+ raw = item[key_name]+ if not isinstance(raw, dict) or len(raw) != 1:+ continue+ (ktype, kval), = raw.items()+ key_bytes = 0+ if ktype == "S" and isinstance(kval, str):+ key_bytes = len(kval.encode("utf-8"))+ elif ktype == "B":+ try:+ key_bytes = len(base64.b64decode(kval)) if isinstance(kval, str) else len(kval)+ except Exception:+ key_bytes = len(kval) if isinstance(kval, (str, bytes)) else 0+ if key_bytes > max_bytes:+ return error_response_json("ValidationException",+ f"One or more parameter values were invalid: Aggregated size of all range keys has exceeded the size limit of 1024 bytes" if key_name == sk_name else+ f"One or more parameter values were invalid: Aggregated size of all hash keys has exceeded the size limit of 2048 bytes", 400)size = _item_size_bytes(item)if size > _DDB_ITEM_MAX_BYTES:return error_response_json("ValidationException",@@ -999,6 +1038,28 @@ def _create_table(data):f"One or more parameter values were invalid: Duplicate index name: {iname}", 400)if iname:seen_index_names.add(iname)++ # Validate index Projection settings.+ for idx in gsis + lsis:+ idx_name = idx.get("IndexName", "<unnamed>")+ proj = idx.get("Projection") or {}+ ptype = proj.get("ProjectionType", "ALL")+ if ptype not in _VALID_PROJECTION_TYPES:+ return error_response_json("ValidationException",+ f"One or more parameter values were invalid: Unknown ProjectionType: {ptype}", 400)+ if ptype == "INCLUDE" and not proj.get("NonKeyAttributes"):+ return error_response_json("ValidationException",+ f"One or more parameter values were invalid: INCLUDE ProjectionType requires NonKeyAttributes to be specified", 400)+ if ptype == "KEYS_ONLY" and proj.get("NonKeyAttributes"):+ return error_response_json("ValidationException",+ f"One or more parameter values were invalid: KEYS_ONLY projection type is not compatible with NonKeyAttributes", 400)++ # Validate StreamSpecification: StreamEnabled:false with StreamViewType is invalid.+ stream_spec = data.get("StreamSpecification")+ if stream_spec and stream_spec.get("StreamEnabled") is False and stream_spec.get("StreamViewType"):+ return error_response_json("ValidationException",+ "One or more parameter values were invalid: StreamViewType can only be specified when StreamEnabled is true", 400)+# Every attribute referenced in any index KeySchema must be in AttributeDefinitions.referenced_attrs = set()for ks in key_schema:@@ -1157,7 +1218,12 @@ def _update_table(data):if new_billing == "PAY_PER_REQUEST":table["ProvisionedThroughput"] = {"ReadCapacityUnits": 0, "WriteCapacityUnits": 0}if "AttributeDefinitions" in data:- table["AttributeDefinitions"] = data["AttributeDefinitions"]+ # Merge incoming AttributeDefinitions with existing ones (union by name).+ # New definitions override existing ones with the same name.+ existing_ad = {ad["AttributeName"]: ad for ad in table.get("AttributeDefinitions", [])}+ for ad in data["AttributeDefinitions"]:+ existing_ad[ad["AttributeName"]] = ad+ table["AttributeDefinitions"] = list(existing_ad.values())if "StreamSpecification" in data:table["StreamSpecification"] = data["StreamSpecification"]if "SSESpecification" in data:@@ -1227,6 +1293,19 @@ def _update_table(data):if "ProvisionedThroughput" in update["Update"]:gsi["ProvisionedThroughput"] = update["Update"]["ProvisionedThroughput"]+ # After all GSI changes, prune AttributeDefinitions to only those attributes+ # still referenced by the table's KeySchema or remaining indexes.+ referenced = set()+ for ks in table.get("KeySchema", []):+ referenced.add(ks.get("AttributeName"))+ for idx in table.get("GlobalSecondaryIndexes", []) + table.get("LocalSecondaryIndexes", []):+ for ks in idx.get("KeySchema", []):+ referenced.add(ks.get("AttributeName"))+ table["AttributeDefinitions"] = [+ ad for ad in table.get("AttributeDefinitions", [])+ if ad["AttributeName"] in referenced+ ]+return json_response({"TableDescription": _table_description(name)})@@ -1321,6 +1400,12 @@ def _validate_expression_attrs(data, expression_fields: tuple) -> tuple | None:no expression field references them at all, AND when any defined aliasisn't used by any of the expressions, AND when any `:foo` or `#bar`referenced by an expression isn't defined."""+ # Expression string length limit: 4096 bytes each.+ for fname in expression_fields:+ body = data.get(fname) or ""+ if body and len(body.encode("utf-8")) > _DDB_EXPR_MAX_BYTES:+ return error_response_json("ValidationException",+ f"Invalid {fname}: expression size exceeds maximum allowed size of {_DDB_EXPR_MAX_BYTES} bytes", 400)has_any_expr = any(data.get(f) for f in expression_fields)eav = data.get("ExpressionAttributeValues")ean = data.get("ExpressionAttributeNames")@@ -1427,6 +1512,10 @@ def _put_item(data):item = data.get("Item", {})err = _validate_item(item, table.get("pk_name"), table.get("sk_name"))+ if err:+ return err+ # Validate GSI/LSI key attribute types and values.+ err = _validate_index_key_values(table, item)if err:return err# Hash key must be present.@@ -1672,6 +1761,10 @@ def _update_item(data):# AWS rejects updates with invalid valueserr = _validate_item(item, table.get("pk_name"), table.get("sk_name"))+ if err:+ return err+ # Validate GSI/LSI key attribute types and values after the update is applied.+ err = _validate_index_key_values(table, item)if err:return err@@ -1790,7 +1883,17 @@ def _query(data):"ALL_PROJECTED_ATTRIBUTES can be used only when Querying an index", 400)if select == "SPECIFIC_ATTRIBUTES" and not data.get("ProjectionExpression") and not data.get("AttributesToGet"):return error_response_json("ValidationException",- "SPECIFIC_ATTRIBUTES requires ProjectionExpression or AttributesToGet", 400)+ "1 validation error detected: Must specify either a ProjectionExpression or non-empty AttributesToGet when Select is SPECIFIC_ATTRIBUTES", 400)+ # ALL_ATTRIBUTES or COUNT cannot be combined with ProjectionExpression.+ if select in ("ALL_ATTRIBUTES", "COUNT") and data.get("ProjectionExpression"):+ return error_response_json("ValidationException",+ f"One or more parameter values were invalid: Select value {select} is not compatible with ProjectionExpression", 400)+ if select == "ALL_PROJECTED_ATTRIBUTES" and data.get("ProjectionExpression") and not index_name:+ return error_response_json("ValidationException",+ "Cannot specify the ProjectionExpression when ALL_PROJECTED_ATTRIBUTES Select is used without an index", 400)+ if select == "ALL_PROJECTED_ATTRIBUTES" and data.get("ProjectionExpression") and index_name:+ return error_response_json("ValidationException",+ "Cannot specify the ProjectionExpression when ALL_PROJECTED_ATTRIBUTES Select is used", 400)pk_name, sk_name, is_gsi = _resolve_index_keys(table, index_name)# ConsistentRead on a GSI is invalid (only LSIs support strongly-consistent reads).@@ -1888,6 +1991,10 @@ def _query(data):for pk_bucket in table["items"].values():for it in pk_bucket.values():if pk_name in it and _extract_key_val(it[pk_name]) == pk_val:+ # Sparse index: for composite GSIs/LSIs, items that have the index+ # hash key but are missing the index range key are excluded.+ if sk_name and sk_name not in it:+ continuecandidates.append(it)else:candidates = list(table["items"].get(pk_val, {}).values())@@ -2058,7 +2165,17 @@ def _scan(data):"ALL_PROJECTED_ATTRIBUTES can be used only when Scanning an index", 400)if select == "SPECIFIC_ATTRIBUTES" and not data.get("ProjectionExpression") and not data.get("AttributesToGet"):return error_response_json("ValidationException",- "SPECIFIC_ATTRIBUTES requires ProjectionExpression or AttributesToGet", 400)+ "1 validation error detected: Must specify either a ProjectionExpression or non-empty AttributesToGet when Select is SPECIFIC_ATTRIBUTES", 400)+ # ALL_ATTRIBUTES or COUNT cannot be combined with ProjectionExpression.+ if select in ("ALL_ATTRIBUTES", "COUNT") and data.get("ProjectionExpression"):+ return error_response_json("ValidationException",+ f"One or more parameter values were invalid: Select value {select} is not compatible with ProjectionExpression", 400)+ if select == "ALL_PROJECTED_ATTRIBUTES" and data.get("ProjectionExpression") and not index_name:+ return error_response_json("ValidationException",+ "ALL_PROJECTED_ATTRIBUTES can be used only when Scanning an index. Cannot specify the ProjectionExpression when ALL_PROJECTED_ATTRIBUTES Select is used without an index", 400)+ if select == "ALL_PROJECTED_ATTRIBUTES" and data.get("ProjectionExpression") and index_name:+ return error_response_json("ValidationException",+ "Cannot specify the ProjectionExpression when ALL_PROJECTED_ATTRIBUTES Select is used", 400)# ConsistentRead on a GSI is invalid.if index_name and data.get("ConsistentRead"):_, _, is_gsi_scan = _resolve_index_keys(table, index_name)@@ -2305,7 +2422,9 @@ def _partiql_update(table, parsed):for attr, val in set_attrs.items():item[attr] = val- return json_response({})+ # AWS ExecuteStatement returns {"Items": []} for UPDATE/DELETE (not an+ # empty object). Some SDKs check for the Items key presence.+ return json_response({"Items": []})def _partiql_delete(table, parsed):@@ -2325,7 +2444,9 @@ def _partiql_delete(table, parsed):if not table["items"][pk_key]:del table["items"][pk_key]_update_counts(table)- return json_response({})+ # AWS ExecuteStatement returns {"Items": []} for UPDATE/DELETE (not an+ # empty object). Some SDKs check for the Items key presence.+ return json_response({"Items": []})# ---------------------------------------------------------------------------@@ -2785,6 +2906,9 @@ def _batch_write_item(data):_, _, key_err = _resolve_table_key_values(table, item, allow_extra=True)if key_err:return key_err+ err = _validate_index_key_values(table, item)+ if err:+ return errkey_repr = (table_name,_extract_key_val(item.get(table.get("pk_name") or "")),_extract_key_val(item.get(table.get("sk_name") or "")) if table.get("sk_name") else None)@@ -4656,6 +4780,20 @@ def _evaluate_condition(expr, item, attr_values, attr_names,err = _check_reserved_keyword_usage(tokens)if err:raise ValueError(err)+ # AWS validates BETWEEN bounds at parse time for ConditionExpression too:+ # lower must be <= upper, or it's a ValidationException (not ConditionalCheckFailed).+ for i, tok in enumerate(tokens):+ if (tok[0] == "IDENT" and tok[1].upper() == "BETWEEN"+ and i + 3 < len(tokens)+ and tokens[i + 1][0] == "VALUE_REF"+ and tokens[i + 2][0] == "IDENT" and tokens[i + 2][1].upper() == "AND"+ and tokens[i + 3][0] == "VALUE_REF"):+ _lo = attr_values.get(tokens[i + 1][1])+ _hi = attr_values.get(tokens[i + 3][1])+ _berr = _between_bounds_error(_lo, _hi)+ if _berr:+ raise ValueError(+ f"Invalid {slot}: The BETWEEN operator requires upper bound to be greater than or equal to lower bound")return _ExprEval(tokens, item, attr_values, attr_names).evaluate()except ValueError as e:msg = str(e)@@ -5230,6 +5368,42 @@ def _key_schema_validation_error():return error_response_json("ValidationException", "The provided key element does not match the schema", 400)+def _validate_index_key_values(table: dict, item: dict) -> tuple | None:+ """Validate that any GSI/LSI key attributes present in `item` have the+ correct type and are not empty. AWS rejects puts/updates that would write+ a wrong-typed, non-scalar, or empty-string/binary value into a secondary+ index key attribute. Items missing a GSI key attribute entirely are fine —+ they just won't appear in that sparse GSI."""+ attr_defs = {ad["AttributeName"]: ad["AttributeType"]+ for ad in (table.get("AttributeDefinitions") or [])}+ for idx in (table.get("GlobalSecondaryIndexes") or []) + (table.get("LocalSecondaryIndexes") or []):+ for ks in (idx.get("KeySchema") or []):+ key_name = ks.get("AttributeName")+ if not key_name or key_name not in item:+ continue # sparse index — item simply won't appear in this index+ expected_type = attr_defs.get(key_name)+ if not expected_type:+ continue+ raw = item[key_name]+ if not isinstance(raw, dict) or len(raw) != 1:+ return error_response_json("ValidationException",+ f"One or more parameter values were invalid: Type mismatch for Index Key {key_name} Expected: {expected_type} Actual: map", 400)+ actual_type = next(iter(raw))+ # Must be a scalar type (S, N, B) — not SS, NS, BS, L, M, BOOL, NULL+ if actual_type not in ("S", "N", "B"):+ return error_response_json("ValidationException",+ f"One or more parameter values were invalid: Type mismatch for Index Key {key_name} Expected: {expected_type} Actual: {actual_type}", 400)+ if actual_type != expected_type:+ return error_response_json("ValidationException",+ f"One or more parameter values were invalid: Type mismatch for Index Key {key_name} Expected: {expected_type} Actual: {actual_type}", 400)+ # Reject empty string/binary for index keys+ err = _empty_key_value_error(key_name, raw)+ if err:+ return error_response_json("ValidationException",+ f"One or more parameter values were invalid: Condition parameter type does not match schema type", 400)+ return None++def _key_type_mismatch_reason(table, attrs):"""Return the AWS message for a key attribute present with the wrong type,else None. Unlike an empty key value (which real AWS rejects up front with a@@ -5897,10 +6071,16 @@ def _add_consumed_capacity(result, data, table_name, write=False):returntable = _tables.get(table_name, {})gsi_count = len(table.get("GlobalSecondaryIndexes", [])) if write else 0- units = 1.0 + gsi_count+ # Eventually-consistent reads (ConsistentRead not set or False) cost 0.5 RCU;+ # strongly-consistent reads cost 1.0 RCU. Writes always cost 1.0 WCU.+ if write:+ units = 1.0 + gsi_count+ else:+ consistent = data.get("ConsistentRead", False)+ units = 1.0 if consistent else 0.5cap = {"TableName": table_name, "CapacityUnits": units}if rc == "INDEXES":- cap["Table"] = {"CapacityUnits": 1.0}+ cap["Table"] = {"CapacityUnits": units}if write and gsi_count:cap["GlobalSecondaryIndexes"] = {gsi["IndexName"]: {"CapacityUnits": 1.0}diff --git a/ministack/services/firehose.py b/ministack/services/firehose.pyindex 51223878..19e130fb 100644--- a/ministack/services/firehose.py+++ b/ministack/services/firehose.py@@ -232,7 +232,8 @@ def _resolve_dest_update_config(data: dict):return None, None-def _apply_lambda_processors(stream: dict, dest: dict, records: list) -> list:+def _apply_lambda_processors(stream: dict, dest: dict, records: list,+ metadata_sink: dict = None) -> list:"""Apply a destination's ProcessingConfiguration Lambda processors to abatch of records.@@ -326,6 +327,13 @@ def _apply_lambda_processors(stream: dict, dest: dict, records: list) -> list:# rather than silently dropping.next_round.append((rid, raw))continue+ # Iceberg routing: capture the record's otfMetadata+ # (destinationDatabaseName / destinationTableName / operation) that+ # a transform Lambda attaches under `metadata.otfMetadata`.+ if metadata_sink is not None:+ otf = (r.get("metadata") or {}).get("otfMetadata")+ if isinstance(otf, dict):+ metadata_sink[rid] = otfoutcome = r.get("result", "Ok")if outcome in ("Dropped", "ProcessingFailed"):continue@@ -376,6 +384,158 @@ def _deliver_to_s3(stream: dict, dest: dict, record_data: bytes):logger.warning("Firehose S3 delivery failed: %s", e)+def _gateway_port() -> str:+ return os.environ.get("GATEWAY_PORT", "4566")+++# Iceberg commits use optimistic concurrency: two writes racing on the same+# table conflict and one loses. Real Firehose buffers and writes in batches;+# MiniStack delivers per record, so serialize the commits to avoid conflicts.+_ICEBERG_WRITE_LOCK = threading.Lock()+++def _iceberg_unique_keys(table_cfgs: list, db: str, table: str) -> list:+ for tc in table_cfgs:+ if (tc.get("DestinationDatabaseName") == db+ and tc.get("DestinationTableName") == table):+ return list(tc.get("UniqueKeys") or [])+ return []+++def _iceberg_write_group(warehouse: str, db: str, table: str, keys: list, group: dict):+ """Write one (db, table) batch into the Iceberg table via DuckDB, the+ engine MiniStack already ships. Runs on a worker thread (it makes loopback+ HTTP calls back into the gateway, so it must not run on the event loop).++ Mirrors real Firehose Merge-on-Read semantics: ``insert`` appends,+ ``update``/``delete`` match on the destination table's UniqueKeys.+ """+ import os as _os+ import tempfile++ import duckdb++ port = _gateway_port()+ region = get_region()+ con = duckdb.connect()+ con.execute("INSTALL iceberg; LOAD iceberg; INSTALL httpfs; LOAD httpfs;")+ tbl = f'__cat."{db}"."{table}"'++ def _tmp(recs):+ fh = tempfile.NamedTemporaryFile("w", suffix=".json", delete=False)+ json.dump(recs, fh)+ fh.close()+ return fh.name++ _ICEBERG_WRITE_LOCK.acquire()+ try:+ con.execute(+ f"CREATE SECRET __ms_fh (TYPE S3, KEY_ID 'test', SECRET 'test', "+ f"ENDPOINT 'localhost:{port}', URL_STYLE 'path', USE_SSL false, "+ f"REGION '{region}')"+ )+ con.execute(+ f"ATTACH '{warehouse}' AS __cat (TYPE ICEBERG, "+ f"ENDPOINT 'http://localhost:{port}/iceberg', AUTHORIZATION_TYPE 'none')"+ )+ if group.get("insert"):+ path = _tmp(group["insert"])+ con.execute(+ f"INSERT INTO {tbl} BY NAME "+ f"SELECT * FROM read_json(?, format='array')", [path])+ _os.unlink(path)+ if group.get("update") and keys:+ cols = [row[0] for row in con.execute(f"DESCRIBE {tbl}").fetchall()]+ set_cols = [c for c in cols if c not in keys] or keys+ on = " AND ".join(f't."{k}" = s."{k}"' for k in keys)+ set_clause = ", ".join(f'"{c}" = s."{c}"' for c in set_cols)+ path = _tmp(group["update"])+ con.execute(+ f"MERGE INTO {tbl} AS t USING "+ f"(SELECT * FROM read_json(?, format='array')) AS s ON {on} "+ f"WHEN MATCHED THEN UPDATE SET {set_clause}", [path])+ _os.unlink(path)+ if group.get("delete") and keys:+ on = " AND ".join(f't."{k}" = s."{k}"' for k in keys)+ path = _tmp(group["delete"])+ con.execute(+ f"MERGE INTO {tbl} AS t USING "+ f"(SELECT * FROM read_json(?, format='array')) AS s ON {on} "+ f"WHEN MATCHED THEN DELETE", [path])+ _os.unlink(path)+ finally:+ try:+ con.close()+ finally:+ _ICEBERG_WRITE_LOCK.release()+++def _deliver_to_iceberg(stream: dict, dest: dict, records: list):+ """Deliver a batch of records to an Apache Iceberg destination (S3 Tables).++ Per-record routing follows real Firehose: a transform Lambda's+ ``otfMetadata`` (destinationDatabaseName / destinationTableName / operation)+ takes precedence, otherwise the single ``DestinationTableConfigurationList``+ entry is used. Operation defaults to ``insert``; ``update``/``delete``+ require the destination table's ``UniqueKeys`` (otherwise AWS routes the+ record to the S3 error bucket — here we log and skip).+ """+ cfg = dest.get("config") or {}+ warehouse = (cfg.get("CatalogConfiguration") or {}).get("CatalogARN", "")+ table_cfgs = cfg.get("DestinationTableConfigurationList") or []+ default_tc = table_cfgs[0] if table_cfgs else {}+ name = stream.get("name", "?")++ meta: dict = {}+ processed = _apply_lambda_processors(stream, dest, records, metadata_sink=meta)++ groups: dict = {}+ for rid, payload in processed:+ try:+ record = json.loads(payload)+ except (ValueError, TypeError):+ logger.warning("Firehose %s: non-JSON record for Iceberg "+ "destination dropped (AWS routes to S3 error bucket)", name)+ continue+ otf = meta.get(rid) or {}+ db = otf.get("destinationDatabaseName") or default_tc.get("DestinationDatabaseName")+ table = otf.get("destinationTableName") or default_tc.get("DestinationTableName")+ op = (otf.get("operation") or "insert").lower()+ if op not in ("insert", "update", "delete"):+ op = "insert"+ if not db or not table:+ logger.warning("Firehose %s: record has no destination database/table; "+ "routed to S3 error bucket", name)+ continue+ keys = _iceberg_unique_keys(table_cfgs, db, table)+ if op in ("update", "delete") and not keys:+ logger.warning("Firehose %s: '%s' on %s.%s requires UniqueKeys; "+ "record routed to S3 error bucket", name, op, db, table)+ continue+ g = groups.setdefault(+ (warehouse, db, table, tuple(keys)),+ {"insert": [], "update": [], "delete": []},+ )+ g[op].append(record)++ if not groups:+ return++ def _run():+ for (wh, db, table, keys), group in groups.items():+ try:+ _iceberg_write_group(wh, db, table, list(keys), group)+ except Exception as exc:+ logger.warning("Firehose %s: Iceberg delivery to %s.%s failed: %s",+ name, db, table, exc)++ try:+ loop = asyncio.get_running_loop()+ loop.run_in_executor(None, _run)+ except RuntimeError:+ _run()++def _record_id() -> str:"""Generate a Firehose-style RecordId (long numeric string)."""ts = int(time.time() * 1000)@@ -586,6 +746,8 @@ def _put_record(data: dict):stream, dest, [(record_id, decoded)]):_deliver_to_s3(stream, dest, payload)+ elif dest["type"] == "Iceberg":+ _deliver_to_iceberg(stream, dest, [(record_id, decoded)])return json_response({"RecordId": record_id, "Encrypted": False})@@ -622,6 +784,8 @@ def _put_record_batch(data: dict):stream, dest, [(record_id, decoded)]):_deliver_to_s3(stream, dest, payload)+ elif dest["type"] == "Iceberg":+ _deliver_to_iceberg(stream, dest, [(record_id, decoded)])responses.append({"RecordId": record_id, "Encrypted": False})except Exception as e:failed += 1diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 35f63750..1ab41c69 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -137,6 +137,8 @@ def _account_from_arn(arn: str) -> str:REGION = os.environ.get("MINISTACK_REGION", os.environ.get("AWS_DEFAULT_REGION", "us-east-1"))LAMBDA_EXECUTOR = os.environ.get("LAMBDA_EXECUTOR", "local").lower()+# Deprecated and ignored (#1205): in-container runs now populate the sibling+# Lambda container via docker cp. Kept defined to avoid breaking any importer.LAMBDA_DOCKER_VOLUME_MOUNT = os.environ.get("LAMBDA_REMOTE_DOCKER_VOLUME_MOUNT", "")LAMBDA_DOCKER_NETWORK = os.environ.get("DOCKER_NETWORK", "") or os.environ.get("LAMBDA_DOCKER_NETWORK", "")LAMBDA_DOCKER_FLAGS = os.environ.get("LAMBDA_DOCKER_FLAGS", "")@@ -3378,18 +3380,18 @@ def _spawn_lambda_container(config: dict, code_zip: bytes | None):_cp_layers = bool(layers_dirs)mounts: list = []if package_type == "Zip":- host_code_dir = LAMBDA_DOCKER_VOLUME_MOUNT or code_dir- if LAMBDA_DOCKER_VOLUME_MOUNT:- mounts.append(docker_lib.types.Mount("/var/task", host_code_dir, type="bind", read_only=True))- if is_provided:- mounts.append(docker_lib.types.Mount("/var/runtime", host_code_dir, type="bind", read_only=True))- elif _running_in_container():- # DinD: host daemon can't see our tmpfs — populate via docker cp after create+ if _running_in_container():+ # DinD: the host Docker daemon can't see our tmpfs, so populate the+ # runtime container's /var/task (and /var/runtime for provided) via+ # docker cp after create. This supersedes the legacy+ # LAMBDA_REMOTE_DOCKER_VOLUME_MOUNT named-volume mount, which is now+ # a deprecated no-op: it mounted the volume name as a bind path,+ # which Docker rejects with "mount path must be absolute" (#1205)._use_docker_cp = Trueelse:- mounts.append(docker_lib.types.Mount("/var/task", host_code_dir, type="bind", read_only=True))+ mounts.append(docker_lib.types.Mount("/var/task", code_dir, type="bind", read_only=True))if is_provided:- mounts.append(docker_lib.types.Mount("/var/runtime", host_code_dir, type="bind", read_only=True))+ mounts.append(docker_lib.types.Mount("/var/runtime", code_dir, type="bind", read_only=True))# CMD / EntryPointrun_kwargs: dict = {diff --git a/ministack/services/s3tables.py b/ministack/services/s3tables.pyindex 899b465b..54647026 100644--- a/ministack/services/s3tables.py+++ b/ministack/services/s3tables.py@@ -204,6 +204,7 @@ def _initial_iceberg_metadata(table_name, schema_fields, location):"sort-orders": [{"order-id": 0, "fields": []}],"properties": {}, "current-snapshot-id": -1, "refs": {},"snapshots": [], "statistics": [], "snapshot-log": [], "metadata-log": [],+ "next-row-id": 0,}@@ -443,6 +444,19 @@ def _iceberg_config():}, "overrides": {}})+def _iceberg_error(message, exc_type, code):+ """Iceberg REST catalog error envelope, per the Iceberg REST OpenAPI+ ``ErrorModel`` (``{"error": {"message", "type", "code"}}``). This is the+ shape spec-compliant REST clients (DuckDB, Spark, Trino) require, and is+ distinct from the AWS ``{"__type", "message"}`` shape the S3 Tables control+ plane returns. A client hitting LoadTable on a not-yet-created table must+ receive a proper ``NoSuchTableException`` so it proceeds to create it."""+ body = json.dumps(+ {"error": {"message": message, "type": exc_type, "code": code}}+ ).encode("utf-8")+ return code, {"Content-Type": "application/json"}, body++def _iceberg_allows_cross_region(headers):return _SIGV4_CREDENTIAL_REGION_RE.search(headers.get("authorization", "")) is None@@ -457,7 +471,7 @@ def _iceberg_list_namespaces(allow_cross_region):def _iceberg_get_namespace(namespace, allow_cross_region):if _iceberg_values(_namespaces, lambda ns: _namespace_name(ns) == namespace, allow_cross_region):return json_response({"namespace": [namespace], "properties": {}})- return error_response_json("NotFoundException", f"Namespace {namespace} not found", 404)+ return _iceberg_error(f"Namespace {namespace} not found", "NoSuchNamespaceException", 404)def _iceberg_list_tables(namespace, allow_cross_region):@@ -484,7 +498,7 @@ def _iceberg_load_table(namespace, table_name, allow_cross_region):"s3.region": get_region(), "client.region": get_region(),},})- return error_response_json("NotFoundException", f"Table {namespace}.{table_name} not found", 404)+ return _iceberg_error(f"Table {namespace}.{table_name} not found", "NoSuchTableException", 404)def _iceberg_commit_table(namespace, table_name, data, allow_cross_region):@@ -509,10 +523,20 @@ def _iceberg_commit_table(namespace, table_name, data, allow_cross_region):"snapshot-id": update.get("snapshot-id", -1),"type": update.get("type", "branch")}elif action == "add-schema":- metadata.setdefault("schemas", []).append(update.get("schema", {}))+ new_schema = update.get("schema", {})+ metadata.setdefault("schemas", []).append(new_schema)+ # Advance last-column-id to the highest field ID in the new+ # schema, so a client allocating the next column's ID (e.g.+ # DuckDB ALTER TABLE ADD COLUMN) doesn't collide with these.+ field_ids = [f["id"] for f in new_schema.get("fields", []) if "id" in f]+ if field_ids:+ metadata["last-column-id"] = max(metadata.get("last-column-id", 0), max(field_ids))elif action == "set-current-schema":metadata["current-schema-id"] = update.get("schema-id", 0)- elif action == "add-partition-spec":+ elif action in ("add-spec", "add-partition-spec"):+ # "add-spec" is the Iceberg REST spec's action name (what+ # duckdb-iceberg sends); "add-partition-spec" is a non-standard+ # alias some hand-rolled callers use. Accept both.metadata.setdefault("partition-specs", []).append(update.get("spec", {}))elif action == "set-default-spec":metadata["default-spec-id"] = update.get("spec-id", 0)@@ -536,7 +560,7 @@ def _iceberg_commit_table(namespace, table_name, data, allow_cross_region):table["modifiedAt"] = now_iso()return json_response({"metadata-location": new_loc, "metadata": metadata})- return error_response_json("NotFoundException", f"Table {namespace}.{table_name} not found", 404)+ return _iceberg_error(f"Table {namespace}.{table_name} not found", "NoSuchTableException", 404)def _iceberg_create_table(namespace, data, allow_cross_region):@@ -547,7 +571,15 @@ def _iceberg_create_table(namespace, data, allow_cross_region):if matches:bucket_arn = matches[0].get("tableBucketARN")if not bucket_arn:- return error_response_json("NotFoundException", f"Namespace {namespace} not found", 404)+ return _iceberg_error(f"Namespace {namespace} not found", "NoSuchNamespaceException", 404)++ # createTable is not idempotent: a create for a table that already exists is+ # a 409, matching the Iceberg REST spec and the S3 Tables control plane. A+ # resent create must not silently replace the table (wiping its snapshots).+ key = _table_key(bucket_arn, namespace, table_name)+ if key in _tables:+ return _iceberg_error(+ f"Table already exists: {namespace}.{table_name}", "AlreadyExistsException", 409)schema_fields = [{"name": f.get("name", ""), "type": f.get("type", "string") if isinstance(f.get("type"), str) else "string","required": f.get("required", False)} for f in schema.get("fields", [])]@@ -557,9 +589,15 @@ def _iceberg_create_table(namespace, data, allow_cross_region):iceberg_metadata = _initial_iceberg_metadata(table_name, schema_fields, location)if schema:iceberg_metadata["schemas"] = [schema]+ partition_spec = data.get("partition-spec")+ if partition_spec:+ # Echo back the client's requested partition spec as the default, so a+ # later commit initialized from this response matches it instead of+ # asserting an empty spec back at us.+ iceberg_metadata["partition-specs"] = [partition_spec]+ iceberg_metadata["default-spec-id"] = partition_spec.get("spec-id", 0)metadata_location = f"s3://{bucket_name}/{namespace}/{table_name}/metadata/v0.metadata.json"arn = _table_arn(bucket_arn, namespace, table_name)- key = _table_key(bucket_arn, namespace, table_name)table = {"name": table_name, "tableARN": arn, "namespace": [namespace],diff --git a/ministack/services/sns.py b/ministack/services/sns.pyindex f19db67a..c7d588c7 100644--- a/ministack/services/sns.py+++ b/ministack/services/sns.py@@ -6,7 +6,8 @@ Supports: CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttrGetSubscriptionAttributes, SetSubscriptionAttributes,Publish, PublishBatch,ListTagsForResource, TagResource, UntagResource,- CreatePlatformApplication, DeletePlatformApplication,+ CreatePlatformApplication, ListPlatformApplications,+ DeletePlatformApplication,CreatePlatformEndpoint, GetEndpointAttributes, SetEndpointAttributes,DeleteEndpoint.SNS → Lambda fanout dispatches via _execute_function (synchronous).@@ -182,6 +183,7 @@ async def handle_request(method: str, path: str, headers: dict, body: bytes, que"TagResource": _tag_resource,"UntagResource": _untag_resource,"CreatePlatformApplication": _create_platform_application,+ "ListPlatformApplications": _list_platform_applications,"CreatePlatformEndpoint": _create_platform_endpoint,"DeletePlatformApplication": _delete_platform_application,"GetEndpointAttributes": _get_endpoint_attributes,@@ -1162,6 +1164,41 @@ def _create_platform_application(params):f"</CreatePlatformApplicationResult>")+def _list_platform_applications(params):+ # https://docs.aws.amazon.com/sns/latest/api/API_ListPlatformApplications.html+ # Returns up to 100 per page; NextToken is the numeric offset of the next+ # page. The store is account+region scoped, so .values() already filters to+ # the caller's region, matching AWS's per-region platform applications.+ all_apps = list(_platform_applications.values())+ next_token = _p(params, "NextToken")+ start = 0+ if next_token:+ try:+ start = int(next_token)+ except ValueError:+ start = 0+ page = all_apps[start:start + 100]+ members = "".join(+ "<member>"+ f"<PlatformApplicationArn>{_xml_escape(app['arn'])}</PlatformApplicationArn>"+ "<Attributes>"+ + "".join(+ f"<entry><key>{_xml_escape(k)}</key><value>{_xml_escape(v)}</value></entry>"+ for k, v in app.get("attributes", {}).items()+ )+ + "</Attributes>"+ "</member>"+ for app in page+ )+ next_token_xml = ""+ if start + 100 < len(all_apps):+ next_token_xml = f"<NextToken>{start + 100}</NextToken>"+ return _xml(200, "ListPlatformApplicationsResponse",+ f"<ListPlatformApplicationsResult>"+ f"<PlatformApplications>{members}</PlatformApplications>"+ f"{next_token_xml}</ListPlatformApplicationsResult>")++def _create_platform_endpoint(params):app_arn = _p(params, "PlatformApplicationArn")token = _p(params, "Token")diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 65106859..c1d33d67 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -5600,6 +5600,107 @@ def test_cfn_logs_resource_policy_identity_and_lifecycle(cfn):assert stack["StackStatus"] == "DELETE_COMPLETE"+def test_cfn_kinesisfirehose_delivery_stream_shares_firehose_state(cfn, fh):+ """AWS::KinesisFirehose::DeliveryStream provisions through CloudFormation and+ shares state with the Firehose API; Ref returns the name, GetAtt Arn the ARN."""+ suffix = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-firehose-{suffix}"+ stream_name = f"cfn-fh-{suffix}"+ template = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "Stream": {+ "Type": "AWS::KinesisFirehose::DeliveryStream",+ "Properties": {+ "DeliveryStreamName": stream_name,+ "DeliveryStreamType": "DirectPut",+ "ExtendedS3DestinationConfiguration": {+ "BucketARN": "arn:aws:s3:::cfn-fh-bucket",+ "RoleARN": "arn:aws:iam::000000000000:role/firehose-role",+ "Prefix": "raw/",+ },+ },+ },+ },+ "Outputs": {+ "RefName": {"Value": {"Ref": "Stream"}},+ "StreamArn": {"Value": {"Fn::GetAtt": ["Stream", "Arn"]}},+ },+ }+ try:+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}+ assert outputs["RefName"] == stream_name+ assert outputs["StreamArn"].endswith(f":deliverystream/{stream_name}")++ desc = fh.describe_delivery_stream(+ DeliveryStreamName=stream_name+ )["DeliveryStreamDescription"]+ assert desc["DeliveryStreamStatus"] == "ACTIVE"+ assert desc["DeliveryStreamARN"] == outputs["StreamArn"]+ finally:+ try:+ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+ except ClientError:+ pass++ with pytest.raises(ClientError) as exc:+ fh.describe_delivery_stream(DeliveryStreamName=stream_name)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_cfn_kinesisfirehose_iceberg_destination_provisions(cfn, fh):+ """Regression for #1206: a stack with an Iceberg-destination Firehose stream+ no longer fails with Unsupported resource type and reaches CREATE_COMPLETE."""+ suffix = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-fh-iceberg-{suffix}"+ stream_name = f"cfn-fh-ice-{suffix}"+ template = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "Stream": {+ "Type": "AWS::KinesisFirehose::DeliveryStream",+ "Properties": {+ "DeliveryStreamName": stream_name,+ "DeliveryStreamType": "DirectPut",+ "IcebergDestinationConfiguration": {+ "RoleARN": "arn:aws:iam::000000000000:role/firehose-role",+ "CatalogConfiguration": {+ "CatalogARN": "arn:aws:glue:us-east-1:000000000000:catalog"+ },+ "S3Configuration": {+ "BucketARN": "arn:aws:s3:::cfn-fh-ice-bucket",+ "RoleARN": "arn:aws:iam::000000000000:role/firehose-role",+ },+ "DestinationTableConfigurationList": [{+ "DestinationDatabaseName": "analytics",+ "DestinationTableName": "events",+ "UniqueKeys": ["id"],+ }],+ },+ },+ },+ },+ "Outputs": {"RefName": {"Value": {"Ref": "Stream"}}},+ }+ try:+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ assert fh.describe_delivery_stream(+ DeliveryStreamName=stream_name+ )["DeliveryStreamDescription"]["DeliveryStreamStatus"] == "ACTIVE"+ finally:+ try:+ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+ except ClientError:+ pass++def test_cfn_change_set_detects_parameter_driven_change(cfn, s3):"""A change set must detect a parameter-driven property change (e.g. a LambdaCode S3Key behind a Ref) so `aws cloudformation deploy` doesn't silentlydiff --git a/tests/test_firehose.py b/tests/test_firehose.pyindex ed55312b..7f2c18b7 100644--- a/tests/test_firehose.py+++ b/tests/test_firehose.py@@ -855,3 +855,83 @@ def test_firehose_kinesis_source_ingest_is_region_scoped():_fh.reset()set_request_account_id(original_account)set_request_region(original_region)+++def _iceberg_test_con(bucket_arn):+ """DuckDB connection attached to MiniStack's S3 Tables Iceberg REST catalog.+ Skips the test if the iceberg/httpfs extensions or REST-catalog writes are+ unavailable in this environment (e.g. offline CI or an old DuckDB)."""+ import duckdb++ parsed = urlparse(ENDPOINT)+ host = parsed.hostname or "localhost"+ port = parsed.port or 4566+ con = duckdb.connect()+ try:+ con.execute("INSTALL iceberg; LOAD iceberg; INSTALL httpfs; LOAD httpfs;")+ con.execute(+ f"CREATE SECRET s (TYPE S3, KEY_ID 'test', SECRET 'test', "+ f"ENDPOINT '{host}:{port}', URL_STYLE 'path', USE_SSL false, "+ f"REGION 'us-east-1')"+ )+ con.execute(+ f"ATTACH '{bucket_arn}' AS cat (TYPE ICEBERG, "+ f"ENDPOINT '{ENDPOINT}/iceberg', AUTHORIZATION_TYPE 'none')"+ )+ except Exception as exc: # pragma: no cover - environment dependent+ con.close()+ pytest.skip(f"DuckDB Iceberg REST writes unavailable: {exc}")+ return con+++def test_firehose_iceberg_delivery_writes_queryable_rows(fh):+ """DirectPut records delivered to an Iceberg (S3 Tables) destination are+ written into the table via the Iceberg REST catalog and are queryable,+ matching real Amazon Data Firehose. Operation defaults to insert."""+ suffix = _uuid_mod.uuid4().hex[:8]+ s3t = _regional_client("s3tables", "us-east-1")+ bucket = s3t.create_table_bucket(name=f"fh-ice-{suffix}")["arn"]+ s3t.create_namespace(tableBucketARN=bucket, namespace=["analytics"])+ con = _iceberg_test_con(bucket)+ con.execute("CREATE TABLE cat.analytics.events (id INTEGER, name VARCHAR)")+ con.close()++ stream = f"fh-ice-{suffix}"+ fh.create_delivery_stream(+ DeliveryStreamName=stream,+ DeliveryStreamType="DirectPut",+ IcebergDestinationConfiguration={+ "RoleARN": "arn:aws:iam::000000000000:role/firehose-role",+ "CatalogConfiguration": {"CatalogARN": bucket},+ "S3Configuration": {+ "BucketARN": "arn:aws:s3:::fh-ice-errors",+ "RoleARN": "arn:aws:iam::000000000000:role/firehose-role",+ },+ "DestinationTableConfigurationList": [{+ "DestinationDatabaseName": "analytics",+ "DestinationTableName": "events",+ "UniqueKeys": ["id"],+ }],+ },+ )+ try:+ fh.put_record(+ DeliveryStreamName=stream,+ Record={"Data": json.dumps({"id": 1, "name": "alice"}).encode()},+ )+ rows = None+ for _ in range(60):+ try:+ q = _iceberg_test_con(bucket)+ rows = q.execute(+ "SELECT id, name FROM cat.analytics.events ORDER BY id"+ ).fetchall()+ q.close()+ if rows == [(1, "alice")]:+ break+ except Exception:+ pass+ time.sleep(0.5)+ assert rows == [(1, "alice")]+ finally:+ fh.delete_delivery_stream(DeliveryStreamName=stream)diff --git a/tests/test_s3tables.py b/tests/test_s3tables.pyindex 3c7ed7d2..81ff7348 100644--- a/tests/test_s3tables.py+++ b/tests/test_s3tables.py@@ -479,6 +479,21 @@ def test_s3tables_iceberg_catalog_prefers_signed_region_for_duplicate_names():pass+def test_iceberg_rest_error_uses_spec_envelope():+ """The /iceberg REST surface must return the Iceberg REST OpenAPI ErrorModel+ ({"error": {message, type, code}}), not the AWS {"__type"} shape. A LoadTable+ on a missing table must be a proper NoSuchTableException so spec-compliant+ writers (DuckDB, Spark) proceed to create it instead of aborting."""+ with pytest.raises(urllib.error.HTTPError) as exc:+ _iceberg_json("/iceberg/v1/catalog/namespaces/nope/tables/missing")+ assert exc.value.code == 404+ body = json.loads(exc.value.read().decode("utf-8"))+ assert "__type" not in body+ assert body["error"]["type"] == "NoSuchTableException"+ assert body["error"]["code"] == 404+ assert body["error"]["message"]++def test_s3tables_iceberg_catalog_no_prefix_url_format(s3tables):"""S3 Tables uses /iceberg/v1/namespaces/... (no catalog prefix in path,warehouse in query param) — the format DuckDB sends with ENDPOINT_TYPE s3_tables@@ -625,3 +640,239 @@ def test_s3tables_iceberg_transactions_commit(s3tables):except Exception:passs3tables.delete_table_bucket(tableBucketARN=bucket_arn)++++def test_s3tables_iceberg_create_table_rejects_resend_instead_of_wiping_data(s3tables):+ """CreateTable is not idempotent per the Iceberg REST spec -- a resent create+ (e.g. a client retry after a lost response to a create that already landed)+ must be rejected with a conflict, matching the S3 Tables control-plane path's+ existing 409 behaviour. Before this guard, a resend silently replaced the+ table's metadata with a fresh empty one, discarding any snapshots/schema+ already committed -- worse than a crash, since nothing signals data was lost."""+ bucket_name = f"tb-createretry-{_uuid_mod.uuid4().hex[:6]}"+ bucket_arn = s3tables.create_table_bucket(name=bucket_name)["arn"]+ ns = f"ns_{_uuid_mod.uuid4().hex[:6]}"+ table = f"t_{_uuid_mod.uuid4().hex[:6]}"+ try:+ s3tables.create_namespace(tableBucketARN=bucket_arn, namespace=[ns])++ _iceberg_json(+ f"/iceberg/v1/namespaces/{ns}/tables",+ method="POST",+ payload={"name": table, "schema": {"type": "struct", "schema-id": 0, "fields": []}},+ )+ # Commit a snapshot so there's real state a resent create could destroy.+ snapshot_id = 42+ _iceberg_json(+ f"/iceberg/v1/namespaces/{ns}/tables/{table}",+ method="POST",+ payload={+ "requirements": [],+ "updates": [+ {+ "action": "add-snapshot",+ "snapshot": {+ "snapshot-id": snapshot_id,+ "sequence-number": 1,+ "timestamp-ms": 1700000000000,+ "manifest-list": f"s3://{bucket_name}/{ns}/{table}/metadata/snap.avro",+ "summary": {"operation": "append"},+ },+ },+ ],+ },+ )++ # Resend the identical create, simulating a retry of a create whose first+ # response was lost.+ try:+ _iceberg_json(+ f"/iceberg/v1/namespaces/{ns}/tables",+ method="POST",+ payload={"name": table, "schema": {"type": "struct", "schema-id": 0, "fields": []}},+ )+ assert False, "expected a 409 conflict on resent CreateTable"+ except urllib.error.HTTPError as e:+ assert e.code == 409+ body = json.loads(e.read().decode("utf-8"))+ assert body["error"]["type"] == "AlreadyExistsException"++ # The original snapshot must still be there -- not wiped by the resend.+ loaded = _iceberg_json(f"/iceberg/v1/namespaces/{ns}/tables/{table}")+ snap_ids = [s.get("snapshot-id") for s in loaded["metadata"]["snapshots"]]+ assert snapshot_id in snap_ids, "resent create-table must not wipe existing table state"+ finally:+ try:+ s3tables.delete_table(tableBucketARN=bucket_arn, namespace=ns, name=table)+ except Exception:+ pass+ try:+ s3tables.delete_namespace(tableBucketARN=bucket_arn, namespace=ns)+ except Exception:+ pass+ s3tables.delete_table_bucket(tableBucketARN=bucket_arn)++++def test_s3tables_iceberg_add_schema_advances_last_column_id(s3tables):+ """Each add-schema commit must bump last-column-id to the new schema's highest+ field ID, so a client allocating the *next* column's ID (e.g. DuckDB's+ ALTER TABLE ... ADD COLUMN) doesn't collide with a previous add-schema's fields."""+ bucket_name = f"tb-lcid-{_uuid_mod.uuid4().hex[:6]}"+ bucket_arn = s3tables.create_table_bucket(name=bucket_name)["arn"]+ ns = f"ns_{_uuid_mod.uuid4().hex[:6]}"+ table = f"t_{_uuid_mod.uuid4().hex[:6]}"+ try:+ s3tables.create_namespace(tableBucketARN=bucket_arn, namespace=[ns])+ s3tables.create_table(tableBucketARN=bucket_arn, namespace=ns, name=table, format="ICEBERG")++ _iceberg_json(+ f"/iceberg/v1/namespaces/{ns}/tables/{table}",+ method="POST",+ payload={+ "requirements": [],+ "updates": [+ {+ "action": "add-schema",+ "schema": {+ "type": "struct", "schema-id": 1,+ "fields": [{"id": 1, "name": "colA", "required": False, "type": "string"}],+ },+ },+ {"action": "set-current-schema", "schema-id": 1},+ ],+ },+ )+ first = _iceberg_json(f"/iceberg/v1/namespaces/{ns}/tables/{table}")+ assert first["metadata"]["last-column-id"] == 1++ _iceberg_json(+ f"/iceberg/v1/namespaces/{ns}/tables/{table}",+ method="POST",+ payload={+ "requirements": [],+ "updates": [+ {+ "action": "add-schema",+ "schema": {+ "type": "struct", "schema-id": 2,+ "fields": [+ {"id": 1, "name": "colA", "required": False, "type": "string"},+ {"id": 2, "name": "colB", "required": False, "type": "long"},+ ],+ },+ },+ {"action": "set-current-schema", "schema-id": 2},+ ],+ },+ )+ second = _iceberg_json(f"/iceberg/v1/namespaces/{ns}/tables/{table}")+ metadata = second["metadata"]+ assert metadata["last-column-id"] == 2++ current_schema = next(s for s in metadata["schemas"] if s["schema-id"] == metadata["current-schema-id"])+ field_ids = [f["id"] for f in current_schema["fields"]]+ assert field_ids == [1, 2], "field IDs must not collide across separate add-schema commits"+ finally:+ try:+ s3tables.delete_table(tableBucketARN=bucket_arn, namespace=ns, name=table)+ except Exception:+ pass+ try:+ s3tables.delete_namespace(tableBucketARN=bucket_arn, namespace=ns)+ except Exception:+ pass+ s3tables.delete_table_bucket(tableBucketARN=bucket_arn)++++def test_s3tables_iceberg_add_spec_uses_real_wire_action_name(s3tables):+ """The Iceberg REST spec's real action name for adding a partition spec is+ "add-spec" (what duckdb-iceberg actually sends) — not "add-partition-spec",+ a non-standard name only some hand-rolled callers use. Both must work."""+ bucket_name = f"tb-spec-{_uuid_mod.uuid4().hex[:6]}"+ bucket_arn = s3tables.create_table_bucket(name=bucket_name)["arn"]+ ns = f"ns_{_uuid_mod.uuid4().hex[:6]}"+ table = f"t_{_uuid_mod.uuid4().hex[:6]}"+ try:+ s3tables.create_namespace(tableBucketARN=bucket_arn, namespace=[ns])+ s3tables.create_table(tableBucketARN=bucket_arn, namespace=ns, name=table, format="ICEBERG")++ _iceberg_json(+ f"/iceberg/v1/namespaces/{ns}/tables/{table}",+ method="POST",+ payload={+ "requirements": [],+ "updates": [+ {+ "action": "add-spec",+ "spec": {+ "spec-id": 1,+ "fields": [{"source-id": 1, "field-id": 1000, "name": "day_col", "transform": "day"}],+ },+ },+ {"action": "set-default-spec", "spec-id": 1},+ ],+ },+ )+ loaded = _iceberg_json(f"/iceberg/v1/namespaces/{ns}/tables/{table}")+ metadata = loaded["metadata"]+ spec_ids = [s["spec-id"] for s in metadata["partition-specs"]]+ assert 1 in spec_ids, "add-spec must append the new partition spec"+ assert metadata["default-spec-id"] == 1+ finally:+ try:+ s3tables.delete_table(tableBucketARN=bucket_arn, namespace=ns, name=table)+ except Exception:+ pass+ try:+ s3tables.delete_namespace(tableBucketARN=bucket_arn, namespace=ns)+ except Exception:+ pass+ s3tables.delete_table_bucket(tableBucketARN=bucket_arn)++++def test_s3tables_iceberg_create_table_honors_requested_partition_spec(s3tables):+ """The create-table endpoint's response must echo back the partition spec the+ client actually asked for, not a hardcoded empty one -- clients (e.g.+ duckdb-iceberg) initialize their own local table state from this response, so an+ empty echo here gets asserted right back at the server on the very next commit,+ permanently losing the partition spec even though it was in the original request."""+ bucket_name = f"tb-createspec-{_uuid_mod.uuid4().hex[:6]}"+ bucket_arn = s3tables.create_table_bucket(name=bucket_name)["arn"]+ ns = f"ns_{_uuid_mod.uuid4().hex[:6]}"+ table = f"t_{_uuid_mod.uuid4().hex[:6]}"+ try:+ s3tables.create_namespace(tableBucketARN=bucket_arn, namespace=[ns])++ created = _iceberg_json(+ f"/iceberg/v1/namespaces/{ns}/tables",+ method="POST",+ payload={+ "name": table,+ "schema": {+ "type": "struct", "schema-id": 0,+ "fields": [{"id": 1, "name": "ts", "required": False, "type": "timestamp"}],+ },+ "partition-spec": {+ "spec-id": 0,+ "fields": [{"source-id": 1, "field-id": 1000, "name": "day_ts", "transform": "day"}],+ },+ },+ )+ metadata = created["metadata"]+ spec = next(s for s in metadata["partition-specs"] if s["spec-id"] == metadata["default-spec-id"])+ assert spec["fields"], "create-table response must echo back the requested partition spec, not an empty one"+ assert spec["fields"][0]["transform"] == "day"+ finally:+ try:+ s3tables.delete_table(tableBucketARN=bucket_arn, namespace=ns, name=table)+ except Exception:+ pass+ try:+ s3tables.delete_namespace(tableBucketARN=bucket_arn, namespace=ns)+ except Exception:+ pass+ s3tables.delete_table_bucket(tableBucketARN=bucket_arn)diff --git a/tests/test_sns.py b/tests/test_sns.pyindex e4a75c11..f96ce630 100644--- a/tests/test_sns.py+++ b/tests/test_sns.py@@ -1544,6 +1544,20 @@ def test_sns_create_platform_application(sns):assert ":app/GCM/intg-sns-pe-create-app" in app_arn+def test_sns_list_platform_applications(sns):+ name = f"intg-sns-list-app-{_uuid_mod.uuid4().hex[:8]}"+ app_arn = sns.create_platform_application(+ Name=name, Platform="GCM", Attributes={"PlatformCredential": "cred-xyz"},+ )["PlatformApplicationArn"]+ try:+ apps = sns.list_platform_applications()["PlatformApplications"]+ mine = [a for a in apps if a["PlatformApplicationArn"] == app_arn]+ assert len(mine) == 1+ assert mine[0]["Attributes"].get("PlatformCredential") == "cred-xyz"+ finally:+ sns.delete_platform_application(PlatformApplicationArn=app_arn)++def test_sns_platform_applications_and_endpoints_are_region_scoped(sns):west = _regional_client("sns", "us-west-2")name = f"mr-sns-platform-region-{_uuid_mod.uuid4().hex[:8]}"