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(s3tables): update catalog on v3 update (#1657)
Nahuel Nucera0a8cc3709a9f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 60c0b533..5742c0a4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **S3 Tables / Glue — the Iceberg REST catalogs honour `upgrade-format-version`** — a commit carrying the Iceberg REST `UpgradeFormatVersionUpdate` action (what a Spark job writing with the `format-version` `3` table property sends for an existing table) was silently dropped, so the table's metadata kept reporting version 2 while the commit answered success; real S3 Tables supports Iceberg format version 3. Both catalogs now apply the action: the metadata moves to the requested version, re-asserting the current version is a no-op, and a downgrade or a version above 3 is refused with 400 — committing nothing, since a commit is atomic (the S3 Tables catalog now stages updates on a copy, the Glue catalog never advances its `metadata_location` on a refusal). Creating a table with an explicit `format-version` already worked; the default stays 2.- **CloudFormation — `Fn::Cidr`, `Fn::GetAZs`, `Fn::FindInMap` and the condition functions follow AWS** — `Fn::Cidr` answered `10.0.{i}.0/…` whatever block it was given (now the block is split: `192.168.0.0/16, 2, 8` is `192.168.0.0/24,192.168.1.0/24`, measured; IPv6 included), `Fn::GetAZs` answered a fabricated `a/b/c` for any region (now the stack's own zones, and an empty list for another region, measured), `Fn::FindInMap` answered `""` for a missing key and had no `DefaultValue` (now the default when given, otherwise `Template error: Unable to get mapping for M::x::y` before the stack exists, measured), and `Fn::And`/`Fn::Or`/`Fn::Not` in a value position leaked the unresolved call (now a boolean; as an Output value they are refused with `The Value field of every Outputs member must evaluate to a String.`, measured). Contributed by @iot-rocket.- **CloudFormation — `DescribeStackResource` and `DescribeStackResources` carry `ResourceStatusReason`** — a resource in `DELETE_FAILED` (or any other failed state) kept its reason in the stack events only; the two Describe responses now carry the `ResourceStatusReason` element the API reference defines, absent for a healthy resource; `DescribeStackResource` also names its timestamp `LastUpdatedTimestamp`, the field `StackResourceDetail` defines (it carried a `Timestamp` element that clients drop, so the detail had no timestamp at all). Contributed by @iot-rocket.- **CloudFormation — a removed resource whose delete fails stays in the stack as `DELETE_FAILED`** — when a resource dropped from the template could not be deleted in the cleanup after an update, the stack ended `UPDATE_COMPLETE` (as on AWS) but the resource was dropped from the stack record while it kept existing in the service, and `DeleteStack` never tried again. It now stays listed with `DELETE_FAILED` and the reason (in a nested stack too), the next update with a changed template retries the delete, and `DeleteStack` also reaches the resources the template no longer declares. Contributed by @iot-rocket.diff --git a/ministack/services/glue.py b/ministack/services/glue.pyindex b7012819..0846d74b 100644--- a/ministack/services/glue.py+++ b/ministack/services/glue.py@@ -678,7 +678,12 @@ def _iceberg_rest_commit_table(namespace, table_name, body):return _iceberg_error(f"Table does not exist: {namespace}.{table_name}", "NoSuchTableException", 404)meta_loc = table["Parameters"]["metadata_location"]metadata = _iceberg_fetch_metadata(meta_loc) or {}- _s3t._apply_iceberg_updates(metadata, body.get("updates", []))+ try:+ _s3t._apply_iceberg_updates(metadata, body.get("updates", []))+ except ValueError as exc:+ # A refused update (an illegal format-version change) commits+ # nothing: the stored metadata_location is only advanced below.+ return _iceberg_error(str(exc), "BadRequestException", 400)version = _metadata_version_from_location(meta_loc) + 1new_loc = _iceberg_write_metadata(namespace, table_name, version, metadata)table["Parameters"]["metadata_location"] = new_locdiff --git a/ministack/services/s3tables.py b/ministack/services/s3tables.pyindex c41ef84a..bc59ffaa 100644--- a/ministack/services/s3tables.py+++ b/ministack/services/s3tables.py@@ -788,6 +788,19 @@ def _apply_iceberg_updates(metadata, updates):ids = [o.get("order-id", 0) for o in metadata.get("sort-orders", [])]order_id = max(ids) if ids else 0metadata["default-sort-order-id"] = order_id+ elif action == "upgrade-format-version":+ # Iceberg REST UpgradeFormatVersionUpdate (what Spark commits for+ # a format-version table property on an existing table). Upgrades+ # only: Iceberg refuses downgrades, and S3 Tables supports the+ # format up to v3. Re-asserting the current version is a no-op.+ requested = int(update.get("format-version", 0))+ current = int(metadata.get("format-version", 2))+ if requested < current:+ raise ValueError(f"Cannot downgrade v{current} table to v{requested}")+ if requested > 3:+ raise ValueError(+ f"Cannot upgrade table to unsupported format version: v{requested} (supported: v3)")+ metadata["format-version"] = requestedelif action == "set-properties":metadata.setdefault("properties", {}).update(update.get("updates", {}))elif action == "remove-properties":@@ -808,8 +821,15 @@ def _iceberg_commit_table(namespace, table_name, data, allow_cross_region, buckematches = _iceberg_values(_tables, _pred, allow_cross_region)if matches:table = matches[0]- metadata = table.get("_iceberg_metadata", {})- _apply_iceberg_updates(metadata, data.get("updates", []))+ # Stage the commit on a copy: a refused update (an illegal+ # format-version change) must not leave the earlier updates of the+ # same commit applied — an Iceberg commit is atomic.+ metadata = copy.deepcopy(table.get("_iceberg_metadata", {}))+ try:+ _apply_iceberg_updates(metadata, data.get("updates", []))+ except ValueError as exc:+ return _iceberg_error(str(exc), "BadRequestException", 400)+ table["_iceberg_metadata"] = metadatatable["_metadata_version"] = table.get("_metadata_version", 0) + 1v = table["_metadata_version"]diff --git a/tests/test_glue.py b/tests/test_glue.pyindex 7170944d..7adc3f66 100644--- a/tests/test_glue.py+++ b/tests/test_glue.py@@ -2351,6 +2351,43 @@ def test_iceberg_rest_create_commit_load_shares_glue_catalog():assert doc["metadata"]["current-snapshot-id"] == 42+def test_iceberg_rest_upgrade_format_version_and_refused_downgrade():+ """The Glue-route Iceberg REST catalog honours ``upgrade-format-version``+ (a Glue Spark job writing with the format-version 3 table property), and a+ refused downgrade commits nothing: the metadata_location is not advanced."""+ _svc("glue")._create_database({"DatabaseInput": {"Name": "lake"}})+ status, _ = _call_body(+ "POST",+ f"/iceberg/v1/{_GLUE_ICEBERG_PREFIX}/namespaces/lake/tables",+ {"name": "orders", "schema": {"type": "struct", "schema-id": 0,+ "fields": [{"id": 1, "name": "id", "required": False, "type": "int"}]}},+ )+ assert status == 200+ status, doc = _call_body(+ "POST",+ f"/iceberg/v1/{_GLUE_ICEBERG_PREFIX}/namespaces/lake/tables/orders",+ {"updates": [{"action": "upgrade-format-version", "format-version": 3}]},+ )+ assert status == 200+ assert doc["metadata"]["format-version"] == 3+ status, doc = _call_body("GET", f"/iceberg/v1/{_GLUE_ICEBERG_PREFIX}/namespaces/lake/tables/orders")+ assert status == 200+ assert doc["metadata"]["format-version"] == 3+ loc_before = _svc("glue")._tables["lake/orders"]["Parameters"]["metadata_location"]++ status, doc = _call_body(+ "POST",+ f"/iceberg/v1/{_GLUE_ICEBERG_PREFIX}/namespaces/lake/tables/orders",+ {"updates": [{"action": "upgrade-format-version", "format-version": 2}]},+ )+ assert status == 400+ assert "downgrade" in json.dumps(doc)+ assert _svc("glue")._tables["lake/orders"]["Parameters"]["metadata_location"] == loc_before+ status, doc = _call_body("GET", f"/iceberg/v1/{_GLUE_ICEBERG_PREFIX}/namespaces/lake/tables/orders")+ assert status == 200+ assert doc["metadata"]["format-version"] == 3++def test_iceberg_rest_loads_table_written_with_s3a_scheme():"""Spark's S3FileIO records the metadata location with the ``s3a://`` scheme(a Glue job writing via GlueCatalog). The REST catalog must read that — thediff --git a/tests/test_s3.py b/tests/test_s3.pyindex 91ebcf78..279b48a4 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -2161,7 +2161,8 @@ def test_s3_eventbridge_notification(s3, sqs, eb):# Rule matches the AWS-documented detail-type, not source alone.eb.put_rule(Name="s3-to-sqs-rule",- EventPattern=json.dumps({"source": ["aws.s3"], "detail-type": ["Object Created"]}),+ EventPattern=json.dumps({"source": ["aws.s3"], "detail-type": ["Object Created"],+ "detail": {"bucket": {"name": ["s3-eb-bkt"]}}}),State="ENABLED",)eb.put_targets(@@ -2208,7 +2209,8 @@ def test_s3_eventbridge_notification_dispatches_in_bucket_region(s3):)west_eb.put_rule(Name=rule_name,- EventPattern=json.dumps({"source": ["aws.s3"], "detail-type": ["Object Created"]}),+ EventPattern=json.dumps({"source": ["aws.s3"], "detail-type": ["Object Created"],+ "detail": {"bucket": {"name": [bucket_name]}}}),State="ENABLED",)west_eb.put_targets(@@ -2245,7 +2247,7 @@ def test_s3_eventbridge_notification_copy_reason(s3, sqs, eb):{"source": ["aws.s3"],"detail-type": ["Object Created"],- "detail": {"reason": ["CopyObject"]},+ "detail": {"reason": ["CopyObject"], "bucket": {"name": ["s3-eb-copy-bkt"]}},}),State="ENABLED",@@ -2279,7 +2281,8 @@ def test_s3_eventbridge_notification_object_deleted(s3, sqs, eb):)eb.put_rule(Name="s3-del-rule",- EventPattern=json.dumps({"source": ["aws.s3"], "detail-type": ["Object Deleted"]}),+ EventPattern=json.dumps({"source": ["aws.s3"], "detail-type": ["Object Deleted"],+ "detail": {"bucket": {"name": ["s3-eb-del-bkt"]}}}),State="ENABLED",)eb.put_targets(Rule="s3-del-rule", Targets=[{"Id": "t", "Arn": queue_arn}])@@ -3904,7 +3907,8 @@ def test_s3_eventbridge_notification_on_delete(s3, sqs, eb):# Create EventBridge rule matching S3 events -> SQS targeteb.put_rule(Name="s3-del-to-sqs-rule",- EventPattern=json.dumps({"source": ["aws.s3"]}),+ EventPattern=json.dumps({"source": ["aws.s3"],+ "detail": {"bucket": {"name": [bucket]}}}),State="ENABLED",)eb.put_targets(diff --git a/tests/test_s3tables.py b/tests/test_s3tables.pyindex 49dbb102..83c55c4d 100644--- a/tests/test_s3tables.py+++ b/tests/test_s3tables.py@@ -642,6 +642,63 @@ def test_s3tables_iceberg_transactions_commit(s3tables):+def test_s3tables_iceberg_upgrade_format_version(s3tables):+ """A commit carrying the Iceberg REST ``upgrade-format-version`` action+ (what Spark sends for ``.tableProperty("format-version", "3")`` on an+ existing table) moves the table's metadata to that version; re-asserting+ the current version is a no-op and a downgrade is refused with 400.+ Real S3 Tables supports Iceberg format version 3."""+ bucket_name = f"tb-fv-{_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")++ loaded = _iceberg_json(f"/iceberg/v1/namespaces/{ns}/tables/{table}")+ assert loaded["metadata"]["format-version"] == 2++ resp = _iceberg_json(+ f"/iceberg/v1/namespaces/{ns}/tables/{table}", method="POST",+ payload={"requirements": [],+ "updates": [{"action": "upgrade-format-version", "format-version": 3}]},+ )+ assert resp["metadata"]["format-version"] == 3+ loaded = _iceberg_json(f"/iceberg/v1/namespaces/{ns}/tables/{table}")+ assert loaded["metadata"]["format-version"] == 3++ # Re-asserting the version the table already has is a no-op commit.+ resp = _iceberg_json(+ f"/iceberg/v1/namespaces/{ns}/tables/{table}", method="POST",+ payload={"requirements": [],+ "updates": [{"action": "upgrade-format-version", "format-version": 3}]},+ )+ assert resp["metadata"]["format-version"] == 3++ # A downgrade is refused, and the table keeps its version.+ with pytest.raises(urllib.error.HTTPError) as exc_info:+ _iceberg_json(+ f"/iceberg/v1/namespaces/{ns}/tables/{table}", method="POST",+ payload={"requirements": [],+ "updates": [{"action": "upgrade-format-version", "format-version": 2}]},+ )+ assert exc_info.value.code == 400+ assert b"downgrade" in exc_info.value.read()+ loaded = _iceberg_json(f"/iceberg/v1/namespaces/{ns}/tables/{table}")+ assert loaded["metadata"]["format-version"] == 3+ 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_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)diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.pyindex 9a52c8bb..3b2d2162 100644--- a/tests/test_stepfunctions.py+++ b/tests/test_stepfunctions.py@@ -7839,7 +7839,11 @@ def _drain_queue(sqs, q_url, want, tries=20):return got-def _status_event_rule(eb, sqs, slug):+def _status_event_rule(eb, sqs, slug, sm_arns):+ """A rule scoped to the given state machines, the way a real consumer+ scopes it. The scoping matters to the tests themselves: the suite runs+ sharded, and an unscoped aws.states pattern also catches the status+ events of every standard execution a parallel worker starts."""q_url = sqs.create_queue(QueueName=f"qa-sfn-evt-{slug}")["QueueUrl"]q_arn = sqs.get_queue_attributes(QueueUrl=q_url, AttributeNames=["QueueArn"]@@ -7849,6 +7853,7 @@ def _status_event_rule(eb, sqs, slug):EventPattern=json.dumps({"source": ["aws.states"],"detail-type": ["Step Functions Execution Status Change"],+ "detail": {"stateMachineArn": list(sm_arns)},}),State="ENABLED",)@@ -7862,7 +7867,6 @@ def test_sfn_execution_emits_status_change_events(sfn, eb, sqs):"""A standard execution publishes aws.states / "Step Functions ExecutionStatus Change" to the default bus on start (RUNNING) and completion(SUCCEEDED), with the documented detail fields and epoch-ms dates."""- q_url, rule = _status_event_rule(eb, sqs, "ok")sm_arn = sfn.create_state_machine(name="qa-evt-ok",definition=json.dumps(@@ -7870,6 +7874,7 @@ def test_sfn_execution_emits_status_change_events(sfn, eb, sqs):),roleArn="arn:aws:iam::000000000000:role/R",)["stateMachineArn"]+ q_url, rule = _status_event_rule(eb, sqs, "ok", [sm_arn])try:exec_arn = sfn.start_execution(stateMachineArn=sm_arn, input='{"a": 1}'@@ -7908,7 +7913,6 @@ def test_sfn_execution_emits_status_change_events(sfn, eb, sqs):def test_sfn_failed_and_aborted_executions_emit_status_events(sfn, eb, sqs):"""FAILED carries error/cause and reports REDRIVABLE; a StopExecutionlands ABORTED with error/cause null, per the documented payloads."""- q_url, rule = _status_event_rule(eb, sqs, "failstop")fail_arn = sfn.create_state_machine(name="qa-evt-fail",definition=json.dumps({"StartAt": "Boom", "States": {@@ -7923,6 +7927,7 @@ def test_sfn_failed_and_aborted_executions_emit_status_events(sfn, eb, sqs):}}),roleArn="arn:aws:iam::000000000000:role/R",)["stateMachineArn"]+ q_url, rule = _status_event_rule(eb, sqs, "failstop", [fail_arn, wait_arn])try:sfn.start_execution(stateMachineArn=fail_arn)waiting = sfn.start_execution(stateMachineArn=wait_arn)["executionArn"]@@ -7949,7 +7954,6 @@ def test_sfn_failed_and_aborted_executions_emit_status_events(sfn, eb, sqs):def test_sfn_sync_execution_emits_no_status_events(sfn_sync, sfn, eb, sqs):"""StartSyncExecution is the express-flavored path; express workflowsemit no status events on AWS, so none are published."""- q_url, rule = _status_event_rule(eb, sqs, "sync")sm_arn = sfn.create_state_machine(name="qa-evt-sync",definition=json.dumps(@@ -7957,6 +7961,7 @@ def test_sfn_sync_execution_emits_no_status_events(sfn_sync, sfn, eb, sqs):),roleArn="arn:aws:iam::000000000000:role/R",)["stateMachineArn"]+ q_url, rule = _status_event_rule(eb, sqs, "sync", [sm_arn])try:sfn_sync.start_sync_execution(stateMachineArn=sm_arn, input="{}")msgs = _drain_queue(sqs, q_url, want=1, tries=3)