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
feat(s3tables): CloudFormation + DuckDB Iceberg integration (#1101)
Adam Woods06703a578518
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 96e9b36b..855cbb6c 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -41,6 +41,7 @@ import ministack.services.pipes as _pipesimport ministack.services.rds as _rdsimport ministack.services.route53 as _r53import ministack.services.s3 as _s3+import ministack.services.s3tables as _s3tablesimport ministack.services.secretsmanager as _smimport ministack.services.ses as _sesimport ministack.services.sns as _sns@@ -4349,9 +4350,82 @@ def _backup_plan_delete(physical_id, props):_backup._plans.pop(physical_id, None)+def _s3tables_bucket_create(logical_id, props, stack_name):+ name = props.get("TableBucketName") or _physical_name(stack_name, logical_id, lowercase=True, max_len=63)+ arn = _s3tables._bucket_arn(name)+ _s3tables._table_buckets[name] = {+ "arn": arn, "name": name,+ "ownerAccountId": get_account_id(),+ "createdAt": now_iso(), "tableCount": 0,+ }+ _s3._buckets.setdefault(name, {"created": now_iso(), "objects": {}, "region": get_region()})+ return arn, {"TableBucketARN": arn}+++def _s3tables_bucket_delete(physical_id, props):+ name = physical_id.rsplit("/", 1)[-1]+ _s3tables._table_buckets.pop(name, None)+ _s3._buckets.pop(name, None)+++def _s3tables_namespace_create(logical_id, props, stack_name):+ bucket_arn = props.get("TableBucketARN", "")+ namespace = props.get("Namespace", "")+ key = _s3tables._ns_key(bucket_arn, namespace)+ _s3tables._namespaces[key] = {+ "namespace": [namespace], "createdAt": now_iso(),+ "createdBy": get_account_id(), "ownerAccountId": get_account_id(),+ "tableBucketARN": bucket_arn,+ }+ return f"{bucket_arn}|{namespace}", {"TableBucketARN": bucket_arn, "Namespace": namespace}+++def _s3tables_namespace_delete(physical_id, props):+ bucket_arn = props.get("TableBucketARN", "")+ namespace = props.get("Namespace", "")+ _s3tables._namespaces.pop(_s3tables._ns_key(bucket_arn, namespace), None)+++def _s3tables_table_create(logical_id, props, stack_name):+ bucket_arn = props.get("TableBucketARN", "")+ namespace = props.get("Namespace", "")+ table_name = props.get("TableName", "")+ bucket_name = bucket_arn.rsplit("/", 1)[-1]+ location = f"s3://{bucket_name}/{namespace}/{table_name}"+ iceberg_metadata = _s3tables._initial_iceberg_metadata(table_name, [], location)+ metadata_location = f"s3://{bucket_name}/{namespace}/{table_name}/metadata/v0.metadata.json"+ table_arn = _s3tables._table_arn(bucket_arn, namespace, table_name)+ key = _s3tables._table_key(bucket_arn, namespace, table_name)+ _s3tables._tables[key] = {+ "name": table_name, "tableARN": table_arn, "namespace": [namespace],+ "tableBucketARN": bucket_arn, "format": "ICEBERG",+ "createdAt": now_iso(), "modifiedAt": now_iso(),+ "ownerAccountId": get_account_id(),+ "metadataLocation": metadata_location, "warehouseLocation": location,+ "_iceberg_metadata": iceberg_metadata, "_metadata_version": 0,+ "_schema_fields": [],+ }+ for b in _s3tables._table_buckets.values():+ if b["arn"] == bucket_arn:+ b["tableCount"] = b.get("tableCount", 0) + 1+ break+ return table_arn, {"TableArn": table_arn, "TableBucketARN": bucket_arn,+ "Namespace": namespace, "TableName": table_name}+++def _s3tables_table_delete(physical_id, props):+ bucket_arn = props.get("TableBucketARN", "")+ namespace = props.get("Namespace", "")+ table_name = props.get("TableName", "")+ _s3tables._tables.pop(_s3tables._table_key(bucket_arn, namespace, table_name), None)++_RESOURCE_HANDLERS = {"AWS::S3::Bucket": {"create": _s3_create, "update": _s3_update, "delete": _s3_delete},"AWS::S3::BucketPolicy": {"create": _s3_bucket_policy_create, "delete": _s3_bucket_policy_delete},+ "AWS::S3Tables::TableBucket": {"create": _s3tables_bucket_create, "delete": _s3tables_bucket_delete},+ "AWS::S3Tables::Namespace": {"create": _s3tables_namespace_create, "delete": _s3tables_namespace_delete},+ "AWS::S3Tables::Table": {"create": _s3tables_table_create, "delete": _s3tables_table_delete},"AWS::SQS::Queue": {"create": _sqs_create, "delete": _sqs_delete},"AWS::SNS::Topic": {"create": _sns_create, "delete": _sns_delete},"AWS::SNS::Subscription": {"create": _sns_sub_create, "delete": _sns_sub_delete},diff --git a/ministack/services/s3tables.py b/ministack/services/s3tables.pyindex c3691e18..899b465b 100644--- a/ministack/services/s3tables.py+++ b/ministack/services/s3tables.py@@ -53,6 +53,12 @@ _MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")_GATEWAY_PORT = os.environ.get("GATEWAY_PORT", "4566")_SIGV4_CREDENTIAL_REGION_RE = re.compile(r"Credential=[^/]+/[^/]+/([^/]+)/")++def _gateway_url() -> str:+ from ministack.core import tls as _tls+ scheme = "https" if _tls.use_ssl_enabled() else "http"+ return f"{scheme}://{_MINISTACK_HOST}:{_GATEWAY_PORT}"+# ── In-memory state ────────────────────────────────────────_table_buckets = AccountRegionScopedDict()@@ -212,6 +218,11 @@ def _create_table_bucket(data):arn = _bucket_arn(name)_table_buckets[name] = {"arn": arn, "name": name, "ownerAccountId": get_account_id(),"createdAt": now_iso(), "tableCount": 0}+ # Provision the backing S3 bucket so data-plane writes (Parquet, manifests)+ # have somewhere to land — mirrors real AWS where S3 Tables manages its own+ # underlying storage transparently.+ import ministack.services.s3 as _s3+ _s3._buckets.setdefault(name, {"created": now_iso(), "objects": {}, "region": get_region()})logger.info("S3Tables: created table bucket %s", name)return json_response({"arn": arn})@@ -246,6 +257,8 @@ def _delete_table_bucket(arn):if key.startswith(arn + "\x00"):del _namespaces[key]del _table_buckets[name]+ import ministack.services.s3 as _s3+ _s3._buckets.pop(name, None)return json_response({})@@ -421,7 +434,13 @@ def _update_table_metadata_location(bucket_arn, namespace, table_name, data):# ── Iceberg REST catalog (data plane for Spark) ───────────def _iceberg_config():- return json_response({"defaults": {}, "overrides": {}})+ return json_response({"defaults": {+ "client.region": get_region(),+ "s3.endpoint": _gateway_url(),+ "s3.access-key-id": "test",+ "s3.secret-access-key": "test",+ "s3.path-style-access": "true",+ }, "overrides": {}})def _iceberg_allows_cross_region(headers):@@ -461,7 +480,8 @@ def _iceberg_load_table(namespace, table_name, allow_cross_region):"metadata": table.get("_iceberg_metadata", {}),"config": {"s3.access-key-id": "test", "s3.secret-access-key": "test",- "s3.endpoint": f"http://{_MINISTACK_HOST}:{_GATEWAY_PORT}", "s3.path-style-access": "true",+ "s3.endpoint": _gateway_url(), "s3.path-style-access": "true",+ "s3.region": get_region(), "client.region": get_region(),},})return error_response_json("NotFoundException", f"Table {namespace}.{table_name} not found", 404)@@ -566,38 +586,62 @@ async def _handle_iceberg_request(method, path, headers, body, query_params):if parts[1] == "v1" and len(parts) == 3 and parts[2] == "config" and method == "GET":return _iceberg_config()- if len(parts) < 4:+ # POST /iceberg/v1/transactions/commit — DuckDB atomic multi-table commit+ if parts[1] == "v1" and parts[2] == "transactions" and method == "POST":+ data = json.loads(body) if body else {}+ for change in data.get("table-changes", []):+ ident = change.get("identifier", {})+ ns = ident.get("namespace", [""])+ ns = ns[0] if isinstance(ns, list) else ns+ tbl = ident.get("name", "")+ result = _iceberg_commit_table(ns, tbl, change, allow_cross_region)+ if result and result[0] not in (200, 204):+ return result+ return json_response({})++ if len(parts) < 3:+ return None++ # Support two URL formats:+ # Standard Iceberg REST: /iceberg/v1/{prefix}/namespaces/...+ # S3 Tables (no prefix): /iceberg/v1/namespaces/... (warehouse in query param)+ if parts[2] == "namespaces":+ ns_idx = 2+ elif len(parts) >= 4 and parts[3] == "namespaces":+ ns_idx = 3+ else:return None- # parts[2] = prefix (catalog name), parts[3] = "namespaces"- if parts[3] == "namespaces":- if len(parts) == 4 and method == "GET":- return _iceberg_list_namespaces(allow_cross_region)- if len(parts) == 5 and method == "GET":- return _iceberg_get_namespace(parts[4], allow_cross_region)- if len(parts) >= 6 and parts[5] == "tables":- namespace = parts[4]- if len(parts) == 6:- if method == "GET":- return _iceberg_list_tables(namespace, allow_cross_region)- if method == "POST":- data = json.loads(body) if body else {}- return _iceberg_create_table(namespace, data, allow_cross_region)- if len(parts) == 7:- table_name = parts[6]- if method == "GET":- return _iceberg_load_table(namespace, table_name, allow_cross_region)- if method == "POST":- data = json.loads(body) if body else {}- return _iceberg_commit_table(namespace, table_name, data, allow_cross_region)- if method == "HEAD":- if _iceberg_values(- _tables,- lambda table: _namespace_name(table) == namespace and table["name"] == table_name,- allow_cross_region,- ):- return 200, {}, b""- return 404, {}, b""+ rest = parts[ns_idx + 1:] # segments after "namespaces"++ if len(rest) == 0 and method == "GET":+ return _iceberg_list_namespaces(allow_cross_region)+ if len(rest) == 1 and method == "GET":+ return _iceberg_get_namespace(rest[0], allow_cross_region)+ if len(rest) >= 2 and rest[1] == "tables":+ namespace = rest[0]+ table_rest = rest[2:]+ if len(table_rest) == 0:+ if method == "GET":+ return _iceberg_list_tables(namespace, allow_cross_region)+ if method == "POST":+ data = json.loads(body) if body else {}+ return _iceberg_create_table(namespace, data, allow_cross_region)+ if len(table_rest) == 1:+ table_name = table_rest[0]+ if method == "GET":+ return _iceberg_load_table(namespace, table_name, allow_cross_region)+ if method == "POST":+ data = json.loads(body) if body else {}+ return _iceberg_commit_table(namespace, table_name, data, allow_cross_region)+ if method == "HEAD":+ if _iceberg_values(+ _tables,+ lambda table: _namespace_name(table) == namespace and table["name"] == table_name,+ allow_cross_region,+ ):+ return 200, {}, b""+ return 404, {}, b""return Nonediff --git a/tests/conftest.py b/tests/conftest.pyindex 21e38a6e..806efa6b 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -552,3 +552,8 @@ def inspector2():@pytest.fixture(scope="session")def mq():return make_client("mq")++[email protected](scope="session")+def s3tables():+ return make_client("s3tables")diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 655f6ada..582a08a0 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -4642,3 +4642,62 @@ def test_cfn_sam_transform_missing_translator_falls_back(monkeypatch):# Templates that don't use the SAM transform are unaffected.plain = {"Resources": {"B": {"Type": "AWS::S3::Bucket", "Properties": {}}}}assert _apply_sam_transform_if_applicable(plain) is plain+++def test_cfn_s3tables_resources(cfn, s3tables):+ """CloudFormation can provision AWS::S3Tables::TableBucket, Namespace, and Table."""+ template = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "Bucket": {+ "Type": "AWS::S3Tables::TableBucket",+ "Properties": {"TableBucketName": "cfn-s3tables-test"},+ },+ "Ns": {+ "Type": "AWS::S3Tables::Namespace",+ "Properties": {+ "TableBucketARN": {"Fn::GetAtt": ["Bucket", "TableBucketARN"]},+ "Namespace": "myns",+ },+ "DependsOn": "Bucket",+ },+ "Table": {+ "Type": "AWS::S3Tables::Table",+ "Properties": {+ "TableBucketARN": {"Fn::GetAtt": ["Bucket", "TableBucketARN"]},+ "Namespace": "myns",+ "TableName": "mytable",+ "OpenTableFormat": "ICEBERG",+ },+ "DependsOn": "Ns",+ },+ },+ "Outputs": {+ "BucketArn": {"Value": {"Fn::GetAtt": ["Bucket", "TableBucketARN"]}},+ "TableArn": {"Value": {"Fn::GetAtt": ["Table", "TableArn"]}},+ },+ }++ stack_name = "cfn-s3tables-t01"+ try:+ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+ except Exception:+ pass++ 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.get("Outputs", [])}+ bucket_arn = outputs["BucketArn"]+ table_arn = outputs["TableArn"]+ assert "cfn-s3tables-test" in bucket_arn+ assert "mytable" in table_arn++ table = s3tables.get_table(tableBucketARN=bucket_arn, namespace="myns", name="mytable")+ assert table["name"] == "mytable"+ assert table["format"] == "ICEBERG"++ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)diff --git a/tests/test_s3tables.py b/tests/test_s3tables.pyindex 4e403c78..3c7ed7d2 100644--- a/tests/test_s3tables.py+++ b/tests/test_s3tables.py@@ -11,6 +11,7 @@ Shapes verified against `botocore.data.s3tables.2024-12-01.service-2`."""import json+import osimport urllib.errorimport urllib.requestimport uuid as _uuid_mod@@ -21,7 +22,7 @@ from botocore.config import Configfrom botocore.exceptions import ClientError-_ENDPOINT = "http://localhost:4566"+_ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")def _iceberg_json(path, method="GET", payload=None, region_name=None, authorization=None):@@ -86,6 +87,44 @@ def test_s3tables_create_list_get_delete_bucket(s3tables):assert exc.value.response["Error"]["Code"] in ("NotFoundException", "404")+def test_s3tables_table_bucket_provisions_backing_s3_bucket(s3tables):+ """Creating a table bucket must automatically provision a same-named S3 bucket+ so that data-plane writes (Parquet files, manifests) have storage to land in —+ mirroring real AWS where S3 Tables manages underlying storage transparently."""+ import boto3+ from botocore.config import Config+ name = f"tb-backing-{_uuid_mod.uuid4().hex[:8]}"+ arn = s3tables.create_table_bucket(name=name)["arn"]+ try:+ s3_client = boto3.client(+ "s3",+ endpoint_url=_ENDPOINT,+ aws_access_key_id="test",+ aws_secret_access_key="test",+ region_name="us-east-1",+ config=Config(retries={"mode": "standard"}),+ )+ # The backing bucket must be accessible via the S3 API+ s3_client.head_bucket(Bucket=name)++ # And must accept object writes (simulating a Parquet data file)+ s3_client.put_object(Bucket=name, Key="ns/tbl/data/part-0.parquet", Body=b"parquet")+ obj = s3_client.get_object(Bucket=name, Key="ns/tbl/data/part-0.parquet")+ assert obj["Body"].read() == b"parquet"+ # Deleting the table bucket must also remove the backing S3 bucket+ s3tables.delete_table_bucket(tableBucketARN=arn)+ from botocore.exceptions import ClientError as _CE+ with pytest.raises(_CE) as exc:+ s3_client.head_bucket(Bucket=name)+ assert exc.value.response["Error"]["Code"] in ("404", "NoSuchBucket")+ except Exception:+ try:+ s3tables.delete_table_bucket(tableBucketARN=arn)+ except Exception:+ pass+ raise++def test_s3tables_get_bucket_missing_returns_not_found(s3tables):fake_arn = "arn:aws:s3tables:us-east-1:000000000000:bucket/does-not-exist-xyz"with pytest.raises(ClientError) as exc:@@ -438,3 +477,151 @@ def test_s3tables_iceberg_catalog_prefers_signed_region_for_duplicate_names():client.delete_table_bucket(tableBucketARN=bucket_arn)except Exception:pass+++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+ or an explicit ENDPOINT pointing at the catalog root."""+ bucket_name = f"tb-noprefix-{_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",+ metadata={"iceberg": {"schema": {"fields": [{"name": "id", "type": "long"}]}}},+ )++ # List namespaces — no prefix+ resp = _iceberg_json("/iceberg/v1/namespaces")+ ns_names = [+ (n[0] if isinstance(n, list) else n)+ for n in resp.get("namespaces", [])+ ]+ assert ns in ns_names++ # List tables — no prefix+ resp = _iceberg_json(f"/iceberg/v1/namespaces/{ns}/tables")+ assert {"namespace": [ns], "name": table} in resp.get("identifiers", [])++ # Load table — no prefix+ resp = _iceberg_json(f"/iceberg/v1/namespaces/{ns}/tables/{table}")+ assert resp.get("metadata-location", "").startswith(f"s3://{bucket_name}/{ns}/{table}/")+ assert resp.get("metadata", {}).get("table-uuid")+ 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_config_returns_s3_defaults():+ """GET /iceberg/v1/config must return S3 connection defaults so clients+ don't need out-of-band credential / endpoint configuration."""+ resp = _iceberg_json("/iceberg/v1/config")+ defaults = resp.get("defaults", {})+ assert "s3.endpoint" in defaults, "s3.endpoint missing from config defaults"+ assert "s3.access-key-id" in defaults, "s3.access-key-id missing from config defaults"+ assert "s3.secret-access-key" in defaults, "s3.secret-access-key missing from config defaults"+ assert "s3.path-style-access" in defaults, "s3.path-style-access missing from config defaults"+ assert "client.region" in defaults, "client.region missing from config defaults"+++def test_s3tables_iceberg_load_table_includes_region(s3tables):+ """LoadTable response config must include s3.region and client.region so+ DuckDB / Spark can route S3 data-file requests to the right region."""+ bucket_name = f"tb-region-{_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")++ resp = _iceberg_json(f"/iceberg/v1/namespaces/{ns}/tables/{table}")+ config = resp.get("config", {})+ assert "s3.region" in config, "s3.region missing from LoadTable config"+ assert "client.region" in config, "client.region missing from LoadTable config"+ 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_transactions_commit(s3tables):+ """POST /iceberg/v1/transactions/commit — DuckDB uses this endpoint for+ atomic multi-table commits when writing data."""+ bucket_name = f"tb-txn-{_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")++ snapshot_id = 1234567890+ resp = _iceberg_json(+ "/iceberg/v1/transactions/commit",+ method="POST",+ payload={+ "table-changes": [+ {+ "identifier": {"namespace": [ns], "name": table},+ "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"},+ },+ },+ {+ "action": "set-snapshot-ref",+ "ref-name": "main",+ "type": "branch",+ "snapshot-id": snapshot_id,+ },+ ],+ }+ ]+ },+ )+ # A successful commit returns 200 with an empty body (or minimal body)+ assert resp is not None++ # Verify the snapshot was recorded in the table metadata+ loaded = _iceberg_json(f"/iceberg/v1/namespaces/{ns}/tables/{table}")+ metadata = loaded.get("metadata", {})+ snap_ids = [s.get("snapshot-id") for s in metadata.get("snapshots", [])]+ assert snapshot_id in snap_ids, f"snapshot {snapshot_id} not found after commit"+ assert metadata.get("current-snapshot-id") == snapshot_id+ 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)