Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(glue): adding iceberg-spark catalog for glue 5 (#1518)

Nahuel Nucera1f85d060946f
diff --git a/ministack/app.py b/ministack/app.py
index 136d0a27..5a781fa2 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -38,9 +38,7 @@ if _VERSION == "dev":
pass
# Matches host headers like "{apiId}.execute-api.<host>" or "{apiId}.execute-api.<host>:4566"
-_EXECUTE_API_RE = re.compile(
- r"^([a-f0-9]{8})\.execute-api\." + re.escape(_MINISTACK_HOST) + r"(?::\d+)?$"
-)
+_EXECUTE_API_RE = re.compile(r"^([a-f0-9]{8})\.execute-api\." + re.escape(_MINISTACK_HOST) + r"(?::\d+)?$")
# Lambda Function URL: {urlId}.lambda-url.{region}.<anything>[:port]. The stored
# FunctionUrl carries AWS's own `.on.aws` suffix, so we match any suffix rather
# than only _MINISTACK_HOST — pointing a proxy or an /etc/hosts entry at the
@@ -99,6 +97,8 @@ def _ws_resolve_iot_account_id(scope: dict, ws_headers: dict) -> str:
if access_key and re.match(r"^\d{12}$", access_key):
return access_key
return os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
+
+
# Virtual-hosted S3 bucket extraction. AWS-aligned per
# docs.aws.amazon.com/AmazonS3/latest/userguide/VirtualHosting.html and
# bucketnamingrules.html (HTTP vhost — ministack is HTTP). Works for any
@@ -143,6 +143,8 @@ def _extract_s3_vhost_bucket(host: str):
if first_tail_segment == "s3" or first_tail_segment.startswith(("s3-", "s3express-")):
return candidate
return None
+
+
_S3_VHOST_EXCLUDE_RE = re.compile(
r"\.(execute-api|lambda-url|alb|emr|efs|elasticache|s3-control|appsync-api|appsync-realtime-api|iot)\."
)
@@ -153,15 +155,44 @@ _RDS_DATA_PATHS = ("/Execute", "/BeginTransaction", "/CommitTransaction", "/Roll
_S3_CONTROL_PREFIX = "/v20180820/"
_SES_V2_PREFIX = "/v2/email"
_ALB_PATH_PREFIX = "/_alb/"
-_NON_S3_VHOST_NAMES = frozenset({
- "s3", "s3-control", "sqs", "sns", "dynamodb", "lambda", "iam", "sts",
- "secretsmanager", "logs", "ssm", "events", "kinesis", "monitoring", "ses",
- "states", "ecs", "rds", "rds-data", "elasticache", "glue", "athena", "airflow",
- "apigateway", "cloudformation", "autoscaling", "codebuild", "transfer", "cur",
- "cloudfront-kvs",
- "appsync-api", "appsync-realtime-api",
- "inspector2", "dsql",
-})
+_NON_S3_VHOST_NAMES = frozenset(
+ {
+ "s3",
+ "s3-control",
+ "sqs",
+ "sns",
+ "dynamodb",
+ "lambda",
+ "iam",
+ "sts",
+ "secretsmanager",
+ "logs",
+ "ssm",
+ "events",
+ "kinesis",
+ "monitoring",
+ "ses",
+ "states",
+ "ecs",
+ "rds",
+ "rds-data",
+ "elasticache",
+ "glue",
+ "athena",
+ "airflow",
+ "apigateway",
+ "cloudformation",
+ "autoscaling",
+ "codebuild",
+ "transfer",
+ "cur",
+ "cloudfront-kvs",
+ "appsync-api",
+ "appsync-realtime-api",
+ "inspector2",
+ "dsql",
+ }
+)
from ministack.core import container_reaper
from ministack.core.concurrency import spawn_background
@@ -244,8 +275,7 @@ def _get_module(name: str):
_MAIN_LOOP = None
-def call_service_handler_sync(handler, method, path, headers, body, query_params,
- timeout: float | None = None):
+def call_service_handler_sync(handler, method, path, headers, body, query_params, timeout: float | None = None):
"""Call an async service handler from a worker thread and return its result.
In-process callers used to drive handlers with ``coro.send(None)``, relying
@@ -275,8 +305,7 @@ def call_service_handler_sync(handler, method, path, headers, body, query_params
"not from the event loop — await the handler directly instead"
)
- future = asyncio.run_coroutine_threadsafe(
- handler(method, path, headers, body, query_params), loop)
+ future = asyncio.run_coroutine_threadsafe(handler(method, path, headers, body, query_params), loop)
return future.result(timeout)
@@ -395,31 +424,62 @@ SERVICE_HANDLERS = {
# below. Symmetry between save and restore is enforced by
# tests/test_persistence.py.
_state_map = {
- "apigateway": "apigateway", "apigateway_v1": "apigateway_v1",
+ "apigateway": "apigateway",
+ "apigateway_v1": "apigateway_v1",
"cloudformation": "cloudformation",
- "sqs": "sqs", "sns": "sns", "ssm": "ssm",
- "secretsmanager": "secretsmanager", "iam": "iam",
- "dynamodb": "dynamodb", "kms": "kms", "eventbridge": "eventbridge",
- "cloudwatch_logs": "cloudwatch_logs", "kinesis": "kinesis",
- "ec2": "ec2", "route53": "route53", "cognito": "cognito",
- "ecr": "ecr", "cloudwatch": "cloudwatch", "s3": "s3",
- "lambda": "lambda_svc", "lambda_microvms": "lambda_microvms",
- "rds": "rds", "ecs": "ecs",
- "elasticache": "elasticache", "appsync": "appsync",
+ "sqs": "sqs",
+ "sns": "sns",
+ "ssm": "ssm",
+ "secretsmanager": "secretsmanager",
+ "iam": "iam",
+ "dynamodb": "dynamodb",
+ "kms": "kms",
+ "eventbridge": "eventbridge",
+ "cloudwatch_logs": "cloudwatch_logs",
+ "kinesis": "kinesis",
+ "ec2": "ec2",
+ "route53": "route53",
+ "cognito": "cognito",
+ "ecr": "ecr",
+ "cloudwatch": "cloudwatch",
+ "s3": "s3",
+ "lambda": "lambda_svc",
+ "lambda_microvms": "lambda_microvms",
+ "rds": "rds",
+ "ecs": "ecs",
+ "elasticache": "elasticache",
+ "appsync": "appsync",
"appsync_events": "appsync_events",
- "stepfunctions": "stepfunctions", "alb": "alb",
- "glue": "glue", "mwaa": "mwaa", "efs": "efs", "waf": "waf",
- "athena": "athena", "emr": "emr", "cloudfront": "cloudfront",
- "codebuild": "codebuild", "batch": "batch", "acm": "acm", "firehose": "firehose",
- "ses": "ses", "ses_v2": "ses_v2",
- "servicediscovery": "servicediscovery", "s3files": "s3files",
- "appconfig": "appconfig", "transfer": "transfer",
- "scheduler": "scheduler", "autoscaling": "autoscaling",
- "eks": "eks", "backup": "backup", "pipes": "pipes",
+ "stepfunctions": "stepfunctions",
+ "alb": "alb",
+ "glue": "glue",
+ "mwaa": "mwaa",
+ "efs": "efs",
+ "waf": "waf",
+ "athena": "athena",
+ "emr": "emr",
+ "cloudfront": "cloudfront",
+ "codebuild": "codebuild",
+ "batch": "batch",
+ "acm": "acm",
+ "firehose": "firehose",
+ "ses": "ses",
+ "ses_v2": "ses_v2",
+ "servicediscovery": "servicediscovery",
+ "s3files": "s3files",
+ "appconfig": "appconfig",
+ "transfer": "transfer",
+ "scheduler": "scheduler",
+ "autoscaling": "autoscaling",
+ "eks": "eks",
+ "backup": "backup",
+ "pipes": "pipes",
"cloudfront_keyvaluestore": "cloudfront_keyvaluestore",
"resource_groups": "resource_groups",
- "cloudtrail": "cloudtrail", "iot": "iot",
- "inspector2": "inspector2", "dsql": "dsql",
+ "cloudtrail": "cloudtrail",
+ "iot": "iot",
+ "inspector2": "inspector2",
+ "dsql": "dsql",
"mediaconnect": "mediaconnect",
"mq": "mq",
"opensearch": "opensearch",
@@ -998,24 +1058,24 @@ async def _handle_sqs_messages_request(method: str, path: str, headers: dict, qu
msgs = queue.get("messages") or []
rendered = []
for m in msgs:
- rendered.append({
- "MessageId": m.get("id"),
- "Body": m.get("body", ""),
- "MD5OfBody": m.get("md5_body"),
- "MD5OfMessageAttributes": m.get("md5_attrs"),
- "SentTimestamp": int(m.get("sent_at", 0)),
- "VisibleAt": int(m.get("visible_at", 0)),
- "IsVisible": m.get("visible_at", 0) <= now,
- "ReceiveCount": m.get("receive_count", 0),
- "FirstReceiveTimestamp": (
- int(m["first_receive_at"]) if m.get("first_receive_at") else None
- ),
- "MessageAttributes": m.get("message_attributes") or {},
- "Attributes": m.get("sys") or {},
- "MessageGroupId": m.get("group_id"),
- "MessageDeduplicationId": m.get("dedup_id"),
- "SequenceNumber": m.get("seq"),
- })
+ rendered.append(
+ {
+ "MessageId": m.get("id"),
+ "Body": m.get("body", ""),
+ "MD5OfBody": m.get("md5_body"),
+ "MD5OfMessageAttributes": m.get("md5_attrs"),
+ "SentTimestamp": int(m.get("sent_at", 0)),
+ "VisibleAt": int(m.get("visible_at", 0)),
+ "IsVisible": m.get("visible_at", 0) <= now,
+ "ReceiveCount": m.get("receive_count", 0),
+ "FirstReceiveTimestamp": (int(m["first_receive_at"]) if m.get("first_receive_at") else None),
+ "MessageAttributes": m.get("message_attributes") or {},
+ "Attributes": m.get("sys") or {},
+ "MessageGroupId": m.get("group_id"),
+ "MessageDeduplicationId": m.get("dedup_id"),
+ "SequenceNumber": m.get("seq"),
+ }
+ )
per_account.setdefault(acct, {}).setdefault(region, {})[qurl] = rendered
response = {"messages": per_account}
@@ -1103,7 +1163,7 @@ def _handle_iot_ca_request(method: str, path: str):
200,
{
"Content-Type": "application/x-pem-file",
- "Content-Disposition": "attachment; filename=\"ministack-iot-ca.pem\"",
+ "Content-Disposition": 'attachment; filename="ministack-iot-ca.pem"',
},
cert_pem.encode("utf-8"),
)
@@ -1200,20 +1260,21 @@ async def _handle_admin_config_request(path: str, method: str, body: bytes):
return 200, {"Content-Type": "application/json"}, json.dumps({"applied": applied}).encode()
-async def _handle_post_body_shortcuts(method: str, path: str, headers: dict, body: bytes, query_params: dict, request_id: str):
+async def _handle_post_body_shortcuts(
+ method: str, path: str, headers: dict, body: bytes, query_params: dict, request_id: str
+):
"""Handle body-dependent routes before the generic service router."""
# CloudFormation custom resource ResponseURL intercept
if method == "PUT" and path.startswith("/_ministack/cfn-response/"):
- token = path[len("/_ministack/cfn-response/"):]
+ token = path[len("/_ministack/cfn-response/") :]
try:
payload = json.loads(body) if body else {}
except (json.JSONDecodeError, ValueError):
payload = {}
from ministack.services.cloudformation import custom_resource as _cfn_cr
+
if not _cfn_cr.deliver_response(token, payload):
- logging.getLogger("cloudformation").warning(
- "CFN ResponseURL PUT for unknown token %r — ignoring", token
- )
+ logging.getLogger("cloudformation").warning("CFN ResponseURL PUT for unknown token %r — ignoring", token)
return 200, {}, b""
response = await _handle_cognito_body_request(method, path, headers, body, query_params)
@@ -1366,9 +1427,7 @@ async def _handle_ecr_registry_request(method: str, path: str, headers: dict, bo
"""
if not _is_ecr_registry_path(path):
return None
- return await _get_module("ecr").handle_registry_request(
- method, path, headers, body, query_params
- )
+ return await _get_module("ecr").handle_registry_request(method, path, headers, body, query_params)
def _parse_execute_api_url(host: str, path: str) -> tuple[str, str, str] | None:
@@ -1487,8 +1546,7 @@ async def _handle_execute_api_request(
return None
api_id, tentative_stage, execute_path = parsed
- denied = _enforce_data_plane("apigateway", "execute-api:Invoke",
- headers, query_params, "")
+ denied = _enforce_data_plane("apigateway", "execute-api:Invoke", headers, query_params, "")
if denied:
return denied
@@ -1507,15 +1565,11 @@ async def _handle_execute_api_request(
stage, execute_path = _resolve_stage_and_path(api_id, tentative_stage, execute_path)
apigw_v1 = _get_module("apigateway_v1")
if apigw_v1.find_api_scope(api_id) is not None:
- return await apigw_v1.handle_execute(
- api_id, stage, method, execute_path, headers, body, query_params
- )
+ return await apigw_v1.handle_execute(api_id, stage, method, execute_path, headers, body, query_params)
apigw_v2 = _get_module("apigateway")
if apigw_v2.find_api_scope(api_id) is None:
return 404, {"Content-Type": "application/json"}, json.dumps({"message": "Not Found"}).encode()
- return await apigw_v2.handle_execute(
- api_id, stage, execute_path, method, headers, body, query_params
- )
+ return await apigw_v2.handle_execute(api_id, stage, execute_path, method, headers, body, query_params)
except Exception as e:
logger.exception("Error in execute-api dispatch: %s", e)
return 500, {"Content-Type": "application/json"}, json.dumps({"message": str(e)}).encode()
@@ -1554,17 +1608,14 @@ def _parse_lambda_url(host: str, path: str) -> tuple[str, str] | None:
return None
-async def _handle_lambda_url_request(
- host: str, path: str, method: str, headers: dict, body: bytes, query_params: dict
-):
+async def _handle_lambda_url_request(host: str, path: str, method: str, headers: dict, body: bytes, query_params: dict):
"""Handle Lambda Function URL data plane requests (Host-based + path-based)."""
parsed = _parse_lambda_url(host, path)
if parsed is None:
return None
url_id, function_path = parsed
- denied = _enforce_data_plane("lambda", "lambda:InvokeFunctionUrl",
- headers, query_params, "")
+ denied = _enforce_data_plane("lambda", "lambda:InvokeFunctionUrl", headers, query_params, "")
if denied:
return denied
@@ -1643,13 +1694,11 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: d
# IAM enforcement for S3 virtual-hosted requests
if AUTH:
from ministack.core.iam_actions import _s3_action, extract_resource_arn
+
s3_action = _s3_action(method, vhost_path, query_params)
if s3_action:
- s3_resource = extract_resource_arn(
- "s3", method, vhost_path, headers, body, query_params, "", "")
- denied = _enforce_data_plane("s3", f"s3:{s3_action}", headers,
- query_params, "",
- resource_arn=s3_resource)
+ s3_resource = extract_resource_arn("s3", method, vhost_path, headers, body, query_params, "", "")
+ denied = _enforce_data_plane("s3", f"s3:{s3_action}", headers, query_params, "", resource_arn=s3_resource)
if denied:
return denied
@@ -1657,8 +1706,7 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: d
# Pass the original (pre-rewrite) URI as signed_path so a presigned
# virtual-hosted URL, which signed the canonical URI without the bucket,
# verifies against what the client actually signed.
- return await _get_module("s3").handle_request(
- method, vhost_path, headers, body, query_params, signed_path=path)
+ return await _get_module("s3").handle_request(method, vhost_path, headers, body, query_params, signed_path=path)
except Exception as e:
logger.exception("Error handling virtual-hosted S3 request: %s", e)
from xml.sax.saxutils import escape as _xml_esc
@@ -1690,28 +1738,47 @@ def _with_data_plane_headers(response, request_id: str, include_s3_id: bool = Fa
return status, headers, body
-def _enforce_data_plane(service: str, iam_action: str, headers: dict,
- query_params: dict, request_id: str,
- resource_arn: str = "*"):
+def _enforce_data_plane(
+ service: str, iam_action: str, headers: dict, query_params: dict, request_id: str, resource_arn: str = "*"
+):
"""Enforce IAM auth on a data-plane path. Returns error tuple or None."""
if not AUTH:
return None
from ministack.core.iam_actions import access_denied_response
from ministack.core.iam_evaluator import AuthError, enforce
+
access_key = extract_access_key_id(headers, query_params)
- denied = enforce(access_key, iam_action, service,
- extract_region(headers, query_params),
- resource_arn=resource_arn)
+ denied = enforce(access_key, iam_action, service, extract_region(headers, query_params), resource_arn=resource_arn)
if denied:
if isinstance(denied, AuthError):
return access_denied_response(
- service, iam_action, "", request_id,
- error_code=denied.code, message=denied.message, headers=headers)
- return access_denied_response(
- service, iam_action, denied.principal_arn, request_id, headers=headers)
+ service, iam_action, "", request_id, error_code=denied.code, message=denied.message, headers=headers
+ )
+ return access_denied_response(service, iam_action, denied.principal_arn, request_id, headers=headers)
return None
+def _iceberg_targets_glue_catalog(path, query_params):
+ """Decide whether an ``/iceberg`` REST request belongs to the Glue Data
+ Catalog (Glue jobs + Firehose lakehouse) or to S3 Tables.
+
+ Glue catalog paths carry a ``catalogs/`` segment (from the prefix its
+ ``/config`` hands back). The initial config call has no prefix yet, so it is
+ routed by the ``warehouse`` query value: S3 Tables uses an
+ ``arn:aws:s3tables:`` ARN or an ``s3tablescatalog`` warehouse; anything else
+ (a Glue catalog ARN) is the Glue Data Catalog. A bare config call with no
+ warehouse keeps the historical default of S3 Tables.
+ """
+ if "/catalogs/" in path:
+ return True
+ warehouse = query_params.get("warehouse", "") if query_params else ""
+ if isinstance(warehouse, list):
+ warehouse = warehouse[0] if warehouse else ""
+ if not warehouse:
+ return False
+ return "s3tablescatalog" not in warehouse and not warehouse.startswith("arn:aws:s3tables:")
+
+
async def _handle_special_data_plane_request(
method: str,
path: str,
@@ -1721,10 +1788,25 @@ async def _handle_special_data_plane_request(
request_id: str,
):
"""Handle special-case service entrypoints before the generic router."""
- # Iceberg REST catalog — route /iceberg/* to s3tables service
+ # Iceberg REST catalog — /iceberg/* is served by two catalogs that share the
+ # prefix: the Glue Data Catalog (the lakehouse a Glue job and Firehose both
+ # write) and S3 Tables. Dispatch between them so a table one writer commits,
+ # the other reads. Must not fall through to S3 (which reads "iceberg" as a
+ # bucket name).
if path.startswith("/iceberg"):
try:
- return await _get_module("s3tables").handle_request(method, path, headers, body, query_params)
+ if _iceberg_targets_glue_catalog(path, query_params):
+ result = _get_module("glue")._handle_iceberg_rest(method, path, query_params, body=body)
+ else:
+ result = await _get_module("s3tables").handle_request(method, path, headers, body, query_params)
+ if result is not None:
+ return result
+ # Neither catalog matched the path: a proper Iceberg REST error,
+ # not an empty 200 a client would read as success.
+ return 404, {"Content-Type": "application/json"}, json.dumps(
+ {"error": {"message": f"Unknown Iceberg REST path: {path}",
+ "type": "NotFoundException", "code": 404}}
+ ).encode()
except Exception as e:
logger.exception("Error in Iceberg REST catalog: %s", e)
return 500, {"Content-Type": "application/json"}, json.dumps({"error": str(e)}).encode()
@@ -1814,9 +1896,7 @@ def _ct_resources(service: str, method: str, path: str, body: bytes) -> list:
return []
resources = [{"ResourceName": parts[0], "ResourceType": "AWS::S3::Bucket"}]
if len(parts) >= 2:
- resources.append(
- {"ResourceName": "/".join(parts[1:]), "ResourceType": "AWS::S3::Object"}
- )
+ resources.append({"ResourceName": "/".join(parts[1:]), "ResourceType": "AWS::S3::Object"})
return resources
if service in ("dynamodb", "lambda", "sqs", "sns", "kinesis"):
@@ -1869,6 +1949,7 @@ def _ct_request_params(headers: dict, body: bytes, query_params: dict) -> dict:
if "form" in ct:
try:
from urllib.parse import parse_qs as _pqs
+
raw = {k: v[0] if len(v) == 1 else v for k, v in _pqs(body.decode("utf-8", errors="replace")).items()}
return raw
except Exception:
@@ -1957,12 +2038,14 @@ def _unknown_query_error(body: bytes, request_id: str):
action = ""
try:
from urllib.parse import parse_qs
+
action = (parse_qs(body.decode("utf-8", "replace")).get("Action") or [""])[0]
except Exception:
pass
msg = (
f"The action {action} is not valid for this web service."
- if action else "The requested action is not valid for this web service."
+ if action
+ else "The requested action is not valid for this web service."
)
msg = msg.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
xml = (
@@ -2005,24 +2088,26 @@ async def _dispatch_service_request(
)
from ministack.core.iam_evaluator import AuthError, enforce
from ministack.core.responses import get_account_id
- iam_action = extract_iam_action(
- service, method, path, headers, body, routing_params)
+
+ iam_action = extract_iam_action(service, method, path, headers, body, routing_params)
if iam_action is not None:
access_key = extract_access_key_id(headers, query_params)
resource_arn = extract_resource_arn(
- service, method, path, headers, body,
- routing_params, region, get_account_id())
- denied = enforce(access_key, iam_action, service, region,
- resource_arn=resource_arn)
+ service, method, path, headers, body, routing_params, region, get_account_id()
+ )
+ denied = enforce(access_key, iam_action, service, region, resource_arn=resource_arn)
if denied:
if isinstance(denied, AuthError):
return access_denied_response(
- service, iam_action, "", request_id,
- error_code=denied.code, message=denied.message,
- headers=headers)
- return access_denied_response(
- service, iam_action, denied.principal_arn, request_id,
- headers=headers)
+ service,
+ iam_action,
+ "",
+ request_id,
+ error_code=denied.code,
+ message=denied.message,
+ headers=headers,
+ )
+ return access_denied_response(service, iam_action, denied.principal_arn, request_id, headers=headers)
handler = SERVICE_HANDLERS.get(service)
if not handler:
@@ -2106,19 +2191,19 @@ async def app(scope, receive, send):
if parsed:
ws_api_id, _stage, _execute_path = parsed
await _get_module("apigateway").handle_websocket(
- scope, receive, send, ws_api_id, path_override=_execute_path,
+ scope,
+ receive,
+ send,
+ ws_api_id,
+ path_override=_execute_path,
)
elif appsync_rt_m:
- await _get_module("appsync_events").handle_websocket(
- scope, receive, send, appsync_rt_m.group(1)
- )
+ await _get_module("appsync_events").handle_websocket(scope, receive, send, appsync_rt_m.group(1))
else:
# IoT MQTT-over-WS — resolve account_id from SigV4 query
# params or Authorization header, fall back to default.
account_id = _ws_resolve_iot_account_id(scope, ws_headers)
- await _get_module("iot").handle_websocket(
- scope, receive, send, account_id, ws_region
- )
+ await _get_module("iot").handle_websocket(scope, receive, send, account_id, ws_region)
except Exception:
logger.exception("Error in WebSocket dispatch")
try:
@@ -2256,13 +2341,13 @@ async def _handle_lifespan(scope, receive, send):
# predates the instance labels. Holding the gateway port means any
# such container is ours. Shutdown deliberately does not do this —
# another instance may be live on this daemon.
- _reap = spawn_background(_stop_docker_containers, True,
- thread_name="ministack-boot-reap")
+ _reap = spawn_background(_stop_docker_containers, True, thread_name="ministack-boot-reap")
_reap.join(timeout=_DOCKER_REAP_BOOT_DEADLINE)
if _reap.is_alive():
logger.warning(
- "Docker orphan reap still running after %ss; continuing "
- "startup without it", _DOCKER_REAP_BOOT_DEADLINE)
+ "Docker orphan reap still running after %ss; continuing " "startup without it",
+ _DOCKER_REAP_BOOT_DEADLINE,
+ )
if PERSIST_STATE:
_load_persisted_state()
# Start the Transfer Family SFTP listener after persistence is
@@ -2300,9 +2385,7 @@ async def _handle_lifespan(scope, receive, send):
# costs heap.
_iot_mtls_env = os.environ.get("IOT_MTLS_ENABLED", "").strip().lower()
if _iot_mtls_env in ("0", "false", "no", "off"):
- logger.debug(
- "IOT_MTLS_ENABLED=%s — skipping iot module import.", _iot_mtls_env
- )
+ logger.debug("IOT_MTLS_ENABLED=%s — skipping iot module import.", _iot_mtls_env)
else:
try:
from ministack.services import iot as _iot_svc
@@ -2324,12 +2407,14 @@ async def _handle_lifespan(scope, receive, send):
# don't race; lifespan.startup is the canonical place to spin it up.
try:
from ministack.services import eventbridge as _eb_mod
+
_eb_mod.start_scheduler()
except Exception as e:
logger.warning("EventBridge scheduler startup failed: %s", e)
# EventBridge Scheduler standalone schedules also need a firing loop (#958).
try:
from ministack.services import scheduler as _sched_mod
+
_sched_mod.start_scheduler()
except Exception as e:
logger.warning("Scheduler startup failed: %s", e)
@@ -2372,7 +2457,7 @@ _DOCKER_REAP_BOOT_DEADLINE = 10.0
def _reaper_docker_client():
"""Docker client for the periodic reaper, or None when there is no daemon."""
sock = os.environ.get("DOCKER_HOST") or "unix:///var/run/docker.sock"
- if sock.startswith("unix://") and not os.path.exists(sock[len("unix://"):]):
+ if sock.startswith("unix://") and not os.path.exists(sock[len("unix://") :]):
return None
try:
import docker
@@ -2828,6 +2913,7 @@ def main():
# hypercorn CLI. Self-signed cert auto-generated under TMPDIR, or BYO
# via MINISTACK_SSL_CERT + MINISTACK_SSL_KEY.
from ministack.core import tls as _tls
+
if _tls.use_ssl_enabled():
config.certfile, config.keyfile = _tls.resolve_tls_material()
diff --git a/ministack/services/firehose.py b/ministack/services/firehose.py
index 41149415..1ff682b3 100644
--- a/ministack/services/firehose.py
+++ b/ministack/services/firehose.py
@@ -25,7 +25,7 @@ import threading
import time
from ministack.core.arn import ArnParseError, parse_arn
-from ministack.core.concurrency import spawn_background
+from ministack.core.concurrency import run_reentrant, spawn_background
from ministack.core.persistence import load_state
from ministack.core.responses import (
AccountRegionScopedDict,
@@ -46,7 +46,7 @@ _S3_BUCKET_NAME_RE = re.compile(
# ─── in-memory state ──────────────────────────────────────────────────────────
-_streams = AccountRegionScopedDict() # (account, region, name) -> stream descriptor
+_streams = AccountRegionScopedDict() # (account, region, name) -> stream descriptor
_lock = threading.Lock()
_dest_counter = 0
@@ -74,13 +74,13 @@ try:
restore_state(_restored)
except Exception:
import logging
- logging.getLogger(__name__).exception(
- "Failed to restore persisted state; continuing with fresh store"
- )
+
+ logging.getLogger(__name__).exception("Failed to restore persisted state; continuing with fresh store")
# ─── helpers ─────────────────────────────────────────────────────────────────
+
def _stream_arn(name: str) -> str:
return f"arn:aws:firehose:{get_region()}:{get_account_id()}:deliverystream/{name}"
@@ -157,8 +157,12 @@ def _dest_description(dest: dict) -> dict:
"ErrorOutputPrefix": cfg.get("ErrorOutputPrefix", ""),
"S3BackupMode": cfg.get("S3BackupMode", "Disabled"),
}
- for opt in ("ProcessingConfiguration", "CloudWatchLoggingOptions",
- "DataFormatConversionConfiguration", "DynamicPartitioningConfiguration"):
+ for opt in (
+ "ProcessingConfiguration",
+ "CloudWatchLoggingOptions",
+ "DataFormatConversionConfiguration",
+ "DynamicPartitioningConfiguration",
+ ):
if opt in cfg:
desc[opt] = cfg[opt]
out[key] = desc
@@ -233,8 +237,7 @@ def _resolve_dest_update_config(data: dict):
return None, None
-def _apply_lambda_processors(stream: dict, dest: dict, records: list,
- metadata_sink: dict = None) -> list:
+def _apply_lambda_processors(stream: dict, dest: dict, records: list, metadata_sink: dict = None) -> list:
"""Apply a destination's ProcessingConfiguration Lambda processors to a
batch of records.
@@ -270,6 +273,7 @@ def _apply_lambda_processors(stream: dict, dest: dict, records: list,
return records
from ministack.services import lambda_svc
+
current = list(records)
stream_arn = stream.get("arn", "")
stream_name = stream.get("name", "?")
@@ -282,7 +286,8 @@ def _apply_lambda_processors(stream: dict, dest: dict, records: list,
if func_record is None:
logger.warning(
"Firehose %s: processor Lambda %s not found; passing records through",
- stream_name, arn,
+ stream_name,
+ arn,
)
continue
now_ms = int(time.time() * 1000)
@@ -302,12 +307,17 @@ def _apply_lambda_processors(stream: dict, dest: dict, records: list,
try:
result = lambda_svc._execute_function(func_record, event)
except Exception as exc:
- logger.warning("Firehose %s: processor Lambda %s invocation failed: %s; passing through",
- stream_name, arn, exc)
+ logger.warning(
+ "Firehose %s: processor Lambda %s invocation failed: %s; passing through", stream_name, arn, exc
+ )
continue
if result.get("error"):
- logger.warning("Firehose %s: processor Lambda %s returned error: %s; passing through",
- stream_name, arn, result.get("body"))
+ logger.warning(
+ "Firehose %s: processor Lambda %s returned error: %s; passing through",
+ stream_name,
+ arn,
+ result.get("body"),
+ )
continue
body = result.get("body")
if isinstance(body, (str, bytes)):
@@ -316,8 +326,9 @@ def _apply_lambda_processors(stream: dict, dest: dict, records: list,
except (ValueError, TypeError):
body = None
if not isinstance(body, dict) or "records" not in body:
- logger.warning("Firehose %s: processor Lambda %s returned malformed body; passing through",
- stream_name, arn)
+ logger.warning(
+ "Firehose %s: processor Lambda %s returned malformed body; passing through", stream_name, arn
+ )
continue
by_id = {r.get("recordId"): r for r in body.get("records", []) if isinstance(r, dict)}
next_round = []
@@ -397,8 +408,7 @@ _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):
+ if tc.get("DestinationDatabaseName") == db and tc.get("DestinationTableName") == table:
return list(tc.get("UniqueKeys") or [])
return []
@@ -441,9 +451,7 @@ def _iceberg_write_group(warehouse: str, db: str, table: str, keys: list, group:
)
if group.get("insert"):
path = _tmp(group["insert"])
- con.execute(
- f"INSERT INTO {tbl} BY NAME "
- f"SELECT * FROM read_json(?, format='array')", [path])
+ 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()]
@@ -454,7 +462,9 @@ def _iceberg_write_group(warehouse: str, db: str, table: str, keys: list, group:
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])
+ 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)
@@ -462,7 +472,9 @@ def _iceberg_write_group(warehouse: str, db: str, table: str, keys: list, group:
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])
+ f"WHEN MATCHED THEN DELETE",
+ [path],
+ )
_os.unlink(path)
finally:
try:
@@ -495,8 +507,9 @@ def _deliver_to_iceberg(stream: dict, dest: dict, records: list):
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)
+ 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")
@@ -505,13 +518,17 @@ def _deliver_to_iceberg(stream: dict, dest: dict, records: list):
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)
+ 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)
+ 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)),
@@ -527,8 +544,7 @@ def _deliver_to_iceberg(stream: dict, dest: dict, records: list):
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)
+ logger.warning("Firehose %s: Iceberg delivery to %s.%s failed: %s", name, db, table, exc)
# Inline if no thread can be started: losing delivery records silently is
# worse than blocking this caller. (Before this ran on `spawn_background`,
@@ -569,7 +585,8 @@ def ingest_from_kinesis_source(stream_arn: str, records: list) -> None:
now_ts = now_epoch()
with _lock:
targets = [
- s for s in _streams.values()
+ s
+ for s in _streams.values()
if s.get("type") == "KinesisStreamAsSource"
and s.get("status") == "ACTIVE"
and (s.get("kinesis_source") or {}).get("KinesisStreamARN") == stream_arn
@@ -591,19 +608,19 @@ def ingest_from_kinesis_source(stream_arn: str, records: list) -> None:
plan.append((stream, dest, rid, raw))
for stream, dest, rid, raw in plan:
try:
- for _rid, payload in _apply_lambda_processors(
- stream, dest, [(rid, raw)]
- ):
+ for _rid, payload in _apply_lambda_processors(stream, dest, [(rid, raw)]):
_deliver_to_s3(stream, dest, payload)
except Exception as exc:
logger.warning(
"Firehose Kinesis-source delivery to %s failed: %s",
- stream.get("name"), exc,
+ stream.get("name"),
+ exc,
)
# ─── operations ──────────────────────────────────────────────────────────────
+
def _create_delivery_stream(data: dict):
name = data.get("DeliveryStreamName", "")
if not name:
@@ -630,12 +647,14 @@ def _create_delivery_stream(data: dict):
validation_error = _validate_s3_destination_config(dtype, cfg)
if validation_error:
return validation_error
- destinations.append({
- "id": _next_dest_id(),
- "type": dtype,
- "config": cfg,
- "records": [],
- })
+ destinations.append(
+ {
+ "id": _next_dest_id(),
+ "type": dtype,
+ "config": cfg,
+ "records": [],
+ }
+ )
stream_type = data.get("DeliveryStreamType", "DirectPut")
now = now_epoch()
@@ -659,6 +678,7 @@ def _create_delivery_stream(data: dict):
_fh_role = ks_cfg.get("RoleARN", "")
if _fh_role:
from ministack.core.iam_evaluator import validate_role_arn
+
_fh_role_err = validate_role_arn(_fh_role)
if _fh_role_err:
return _invalid(_fh_role_err)
@@ -716,15 +736,17 @@ def _list_delivery_streams(data: dict):
if start:
try:
idx = names.index(start)
- names = names[idx + 1:]
+ names = names[idx + 1 :]
except ValueError:
pass
has_more = len(names) > limit
- return json_response({
- "DeliveryStreamNames": names[:limit],
- "HasMoreDeliveryStreams": has_more,
- })
+ return json_response(
+ {
+ "DeliveryStreamNames": names[:limit],
+ "HasMoreDeliveryStreams": has_more,
+ }
+ )
def _put_record(data: dict):
@@ -752,9 +774,7 @@ def _put_record(data: dict):
dest["records"].append({"id": record_id, "data": raw_data, "ts": now_epoch()})
if dest["type"] in ("ExtendedS3", "S3"):
# Apply ProcessingConfiguration.Lambda transforms before S3.
- for _rid, payload in _apply_lambda_processors(
- stream, dest, [(record_id, decoded)]
- ):
+ for _rid, payload in _apply_lambda_processors(stream, dest, [(record_id, decoded)]):
_deliver_to_s3(stream, dest, payload)
elif dest["type"] == "Iceberg":
_deliver_to_iceberg(stream, dest, [(record_id, decoded)])
@@ -790,25 +810,27 @@ def _put_record_batch(data: dict):
for dest in stream["destinations"]:
dest["records"].append({"id": record_id, "data": raw_data, "ts": now_epoch()})
if dest["type"] in ("ExtendedS3", "S3"):
- for _rid, payload in _apply_lambda_processors(
- stream, dest, [(record_id, decoded)]
- ):
+ for _rid, payload in _apply_lambda_processors(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 += 1
- responses.append({
- "ErrorCode": "ServiceUnavailableException",
- "ErrorMessage": str(e),
- })
-
- return json_response({
- "FailedPutCount": failed,
- "Encrypted": False,
- "RequestResponses": responses,
- })
+ responses.append(
+ {
+ "ErrorCode": "ServiceUnavailableException",
+ "ErrorMessage": str(e),
+ }
+ )
+
+ return json_response(
+ {
+ "FailedPutCount": failed,
+ "Encrypted": False,
+ "RequestResponses": responses,
+ }
+ )
def _update_destination(data: dict):
@@ -905,15 +927,17 @@ def _list_tags_for_delivery_stream(data: dict):
if start:
try:
idx = next(i for i, t in enumerate(all_tags) if t["Key"] == start)
- all_tags = all_tags[idx + 1:]
+ all_tags = all_tags[idx + 1 :]
except StopIteration:
pass
has_more = len(all_tags) > limit
- return json_response({
- "Tags": all_tags[:limit],
- "HasMoreTags": has_more,
- })
+ return json_response(
+ {
+ "Tags": all_tags[:limit],
+ "HasMoreTags": has_more,
+ }
+ )
def _start_delivery_stream_encryption(data: dict):
@@ -966,9 +990,8 @@ _HANDLERS = {
}
-async def handle_request(method, path, headers, body, query_params):
+def _handle_request_sync(method, path, headers, body, query_params):
target = headers.get("x-amz-target", "")
- # Target format: Firehose_20150804.OperationName
action = target.split(".")[-1] if "." in target else ""
if not action:
@@ -984,3 +1007,17 @@ async def handle_request(method, path, headers, body, query_params):
return error_response_json("InvalidArgumentException", "Request body is not valid JSON.", 400)
return handler(data)
+
+
+async def handle_request(method, path, headers, body, query_params):
+ """Dispatch off the event loop.
+
+ PutRecord with an Iceberg destination delivers via DuckDB, which makes
+ loopback HTTP calls back to the gateway. Running the handler on the event
+ loop thread deadlocks: the background thread's POST waits for the event
+ loop, which is blocked on handler(). run_reentrant gives the handler its
+ own thread so the event loop stays free for the loopback.
+ """
+ return await run_reentrant(
+ _handle_request_sync, method, path, headers, body, query_params, thread_name="ministack-firehose-dispatch"
+ )
diff --git a/ministack/services/glue.py b/ministack/services/glue.py
index 68fe4e9c..7ee52bdc 100644
--- a/ministack/services/glue.py
+++ b/ministack/services/glue.py
@@ -53,6 +53,7 @@ DOCKER_NETWORK = os.environ.get("DOCKER_NETWORK", "")
# Glue Docker image — maps GlueVersion to the amazon/aws-glue-libs tag.
# Users can override via GLUE_DOCKER_IMAGE env var.
_GLUE_VERSION_IMAGES = {
+ "5.0": "amazon/aws-glue-libs:5",
"4.0": "amazon/aws-glue-libs:glue_libs_4.0.0_image_01",
"3.0": "amazon/aws-glue-libs:glue_libs_3.0.0_image_01",
}
@@ -67,6 +68,7 @@ def _get_docker():
if _docker is None:
try:
import docker
+
_docker = docker.from_env(timeout=_DOCKER_TIMEOUT)
except Exception:
pass
@@ -82,10 +84,8 @@ def _get_ministack_network(docker_client):
_ministack_network = DOCKER_NETWORK
return DOCKER_NETWORK
try:
- self_container = docker_client.containers.get(
- os.environ.get("HOSTNAME", ""))
- nets = list(
- self_container.attrs["NetworkSettings"]["Networks"].keys())
+ self_container = docker_client.containers.get(os.environ.get("HOSTNAME", ""))
+ nets = list(self_container.attrs["NetworkSettings"]["Networks"].keys())
if nets:
_ministack_network = nets[0]
return nets[0]
@@ -107,22 +107,23 @@ def _is_spark_job(job):
cmd_name = job.get("Command", {}).get("Name", "")
return cmd_name in ("glueetl", "gluestreaming")
+
_databases = AccountRegionScopedDict()
-_tables = AccountRegionScopedDict() # "db_name/table_name" -> table dict
-_partitions = AccountRegionScopedDict() # "db_name/table_name" -> [partition, ...]
+_tables = AccountRegionScopedDict() # "db_name/table_name" -> table dict
+_partitions = AccountRegionScopedDict() # "db_name/table_name" -> [partition, ...]
_partition_indexes = AccountRegionScopedDict() # "db_name/table_name" -> [index, ...]
_connections = AccountRegionScopedDict()
_crawlers = AccountRegionScopedDict()
_jobs = AccountRegionScopedDict()
-_job_runs = AccountRegionScopedDict() # job_name -> [run, ...]
-_tags = AccountScopedDict() # arn -> {key: value, ...}
+_job_runs = AccountRegionScopedDict() # job_name -> [run, ...]
+_tags = AccountScopedDict() # arn -> {key: value, ...}
_security_configs = AccountRegionScopedDict()
_classifiers = AccountRegionScopedDict()
-_triggers = AccountRegionScopedDict() # trigger_name -> trigger dict
-_workflows = AccountRegionScopedDict() # workflow_name -> workflow dict
-_workflow_runs = AccountRegionScopedDict() # workflow_name -> [run, ...]
+_triggers = AccountRegionScopedDict() # trigger_name -> trigger dict
+_workflows = AccountRegionScopedDict() # workflow_name -> workflow dict
+_workflow_runs = AccountRegionScopedDict() # workflow_name -> [run, ...]
_user_defined_functions = AccountRegionScopedDict() # "db_name/function_name" -> udf dict
-_table_column_statistics = AccountRegionScopedDict() # "db/table" -> {column_name: stats}
+_table_column_statistics = AccountRegionScopedDict() # "db/table" -> {column_name: stats}
_partition_column_statistics = AccountRegionScopedDict() # "db/table" -> [{"Values": [...], "Stats": {col: stats}}]
_ALL_STATE = {
@@ -180,9 +181,8 @@ try:
restore_state(_restored)
except Exception:
import logging
- logging.getLogger(__name__).exception(
- "Failed to restore persisted state; continuing with fresh store"
- )
+
+ logging.getLogger(__name__).exception("Failed to restore persisted state; continuing with fresh store")
def _arn(resource_type, name):
@@ -243,22 +243,20 @@ def _validate_tag_resource_arn(arn):
def _is_taggable_glue_resource(resource):
if resource == "catalog":
return True
- return any(
- resource.startswith(prefix) and resource != prefix
- for prefix in _GLUE_SIMPLE_TAGGABLE_RESOURCE_PREFIXES
- ) or any(
- resource.startswith(prefix) and resource != prefix
- for prefix in _GLUE_COLON_TAGGABLE_RESOURCE_PREFIXES
- ) or any(
- _has_min_path_parts(resource, prefix, min_parts)
- for prefix, min_parts in _GLUE_PATH_TAGGABLE_RESOURCE_MIN_PARTS.items()
+ return (
+ any(resource.startswith(prefix) and resource != prefix for prefix in _GLUE_SIMPLE_TAGGABLE_RESOURCE_PREFIXES)
+ or any(resource.startswith(prefix) and resource != prefix for prefix in _GLUE_COLON_TAGGABLE_RESOURCE_PREFIXES)
+ or any(
+ _has_min_path_parts(resource, prefix, min_parts)
+ for prefix, min_parts in _GLUE_PATH_TAGGABLE_RESOURCE_MIN_PARTS.items()
+ )
)
def _has_min_path_parts(resource, prefix, min_parts):
if not resource.startswith(prefix):
return False
- parts = resource[len(prefix):].split("/")
+ parts = resource[len(prefix) :].split("/")
return len(parts) >= min_parts and all(parts)
@@ -274,7 +272,7 @@ def _handle_request_sync(method, path, headers, body, query_params):
# dispatch already lands `glue`-signed requests here, so a plain
# path check is all that's needed to tell the two protocols apart.
if path.startswith("/iceberg"):
- return _handle_iceberg_rest(method, path, query_params)
+ return _handle_iceberg_rest(method, path, query_params, body=body)
target = headers.get("x-amz-target", "")
action = target.split(".")[-1] if "." in target else ""
@@ -453,23 +451,26 @@ def _iceberg_fetch_metadata(metadata_location):
"""Read the metadata.json at an ``s3://bucket/key`` URI from MiniStack's
S3 and return it parsed, or None if the URI is malformed, the object is
missing, or the body isn't valid JSON."""
- if not metadata_location or not metadata_location.startswith("s3://"):
+ # Spark's S3FileIO writes `s3a://` locations; DuckDB and our REST catalog
+ # write `s3://`. Both point at the same MiniStack S3 object, so accept either.
+ scheme = next((s for s in ("s3://", "s3a://") if metadata_location and metadata_location.startswith(s)), None)
+ if scheme is None:
return None
- rest = metadata_location[len("s3://"):]
+ rest = metadata_location[len(scheme) :]
if "/" not in rest:
return None
bucket, key = rest.split("/", 1)
if not bucket or not key:
return None
from ministack.services import s3 as _s3
+
data = _s3._get_object_data(bucket, key)
if data is None:
return None
try:
return json.loads(data.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
- logger.warning("Iceberg metadata.json at %s did not parse: %s",
- metadata_location, exc)
+ logger.warning("Iceberg metadata.json at %s did not parse: %s", metadata_location, exc)
return None
@@ -484,27 +485,57 @@ def _iceberg_table_entry(db_name, table_name):
return table
+def _iceberg_latest_metadata_location(metadata_location):
+ """A writer (DuckDB, Spark) commits by writing the next ``vN.metadata.json``
+ to S3, and does not always drive it through the REST commit endpoint, so the
+ table's stored pointer can lag. Scan the metadata directory for the newest
+ ``.metadata.json`` and return it, falling back to the stored pointer."""
+ scheme = next((s for s in ("s3://", "s3a://") if metadata_location and metadata_location.startswith(s)), None)
+ if scheme is None:
+ return metadata_location
+ try:
+ from ministack.services import s3 as _s3
+
+ rest = metadata_location[len(scheme) :]
+ bucket, key = rest.split("/", 1)
+ meta_dir = "/".join(key.split("/")[:-1]) + "/"
+ bucket_data = _s3._ensure_bucket(bucket)
+ if not bucket_data:
+ return metadata_location
+ meta_files = sorted(
+ k for k in bucket_data.get("objects", {}) if k.startswith(meta_dir) and k.endswith(".metadata.json")
+ )
+ if meta_files:
+ # Order by version number, not lexically: v10 must sort after v2.
+ meta_files.sort(key=lambda k: _metadata_version_from_location(k))
+ return f"{scheme}{bucket}/{meta_files[-1]}"
+ except Exception:
+ pass
+ return metadata_location
+
+
def _iceberg_load_table(db_name, table_name):
table = _iceberg_table_entry(db_name, table_name)
if table is None:
- return _iceberg_error(
- f"Table does not exist: {db_name}.{table_name}",
- "NoSuchTableException", 404)
- metadata_location = table["Parameters"]["metadata_location"]
+ return _iceberg_error(f"Table does not exist: {db_name}.{table_name}", "NoSuchTableException", 404)
+ metadata_location = _iceberg_latest_metadata_location(table["Parameters"]["metadata_location"])
# Missing/unparseable metadata.json is a 404, not a 200 with empty
# metadata — DuckDB would treat the latter as a real-but-empty table
# and silently return wrong query results.
metadata = _iceberg_fetch_metadata(metadata_location)
if metadata is None:
return _iceberg_error(
- f"Table metadata not readable: {db_name}.{table_name} "
- f"(metadata_location={metadata_location})",
- "NoSuchTableException", 404)
- return _iceberg_json({
- "metadata-location": metadata_location,
- "metadata": metadata,
- "config": _iceberg_s3_overrides(),
- })
+ f"Table metadata not readable: {db_name}.{table_name} " f"(metadata_location={metadata_location})",
+ "NoSuchTableException",
+ 404,
+ )
+ return _iceberg_json(
+ {
+ "metadata-location": metadata_location,
+ "metadata": metadata,
+ "config": _iceberg_s3_overrides(),
+ }
+ )
def _iceberg_maybe_log_tls_hint():
@@ -523,71 +554,234 @@ def _iceberg_maybe_log_tls_hint():
)
-def _handle_iceberg_rest(method, path, query_params):
+# The default warehouse for Glue Data Catalog Iceberg tables. Spark's
+# GlueCatalog writes here (see the injected `warehouse=s3a://...` conf), and
+# the REST catalog writes here too so a table Firehose commits and a table a
+# Glue job commits land in the same place.
+_GLUE_WAREHOUSE_BUCKET = "ministack-glue-warehouse"
+
+
+def _metadata_version_from_location(metadata_location):
+ """Extract the integer N from a ``.../vN.metadata.json`` location, or -1 if
+ it doesn't match, so a commit can allocate the next version."""
+ if not metadata_location:
+ return -1
+ tail = metadata_location.rsplit("/", 1)[-1]
+ if tail.startswith("v") and tail.endswith(".metadata.json"):
+ try:
+ return int(tail[1:-len(".metadata.json")])
+ except ValueError:
+ return -1
+ return -1
+
+
+def _iceberg_write_metadata(namespace, table_name, version, metadata):
+ """Write ``metadata`` as ``vN.metadata.json`` under the Glue warehouse and
+ return its ``s3://`` location. Clients (DuckDB, Spark) read by location."""
+ from ministack.services import s3 as _s3
+
+ if _s3._ensure_bucket(_GLUE_WAREHOUSE_BUCKET) is None:
+ _s3._create_bucket(_GLUE_WAREHOUSE_BUCKET, b"", {})
+ key = f"{namespace}/{table_name}/metadata/v{version}.metadata.json"
+ _s3._put_object(
+ _GLUE_WAREHOUSE_BUCKET, key, json.dumps(metadata).encode("utf-8"),
+ {"content-type": "application/json"},
+ )
+ return f"s3://{_GLUE_WAREHOUSE_BUCKET}/{key}"
+
+
+def _iceberg_rest_create_namespace(body):
+ """POST namespaces -- create a Glue database to back an Iceberg namespace."""
+ ns_field = body.get("namespace", [])
+ ns = ns_field[0] if isinstance(ns_field, list) and ns_field else (ns_field or "")
+ if not ns:
+ return _iceberg_error("Missing namespace", "BadRequestException", 400)
+ if ns not in _databases:
+ _databases[ns] = {
+ "Name": ns,
+ "Description": "",
+ "LocationUri": None,
+ "Parameters": body.get("properties", {}) or {},
+ "CreateTime": int(time.time()),
+ "CatalogId": get_account_id(),
+ }
+ return _iceberg_json({"namespace": [ns], "properties": _databases[ns].get("Parameters", {})})
+
+
+def _iceberg_rest_create_table(namespace, body):
+ """POST namespaces/{ns}/tables -- register a Glue Iceberg table and write
+ its initial metadata.json to the warehouse."""
+ from ministack.services import s3tables as _s3t
+
+ if namespace not in _databases:
+ return _iceberg_error(f"Namespace does not exist: {namespace}", "NoSuchNamespaceException", 404)
+ table_name = body.get("name", "")
+ key = f"{namespace}/{table_name}"
+ # createTable is not idempotent -- a resent create must not wipe snapshots.
+ if key in _tables:
+ return _iceberg_error(f"Table already exists: {namespace}.{table_name}", "AlreadyExistsException", 409)
+
+ schema = body.get("schema", {})
+ 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", [])
+ ]
+ location = body.get("location") or f"s3://{_GLUE_WAREHOUSE_BUCKET}/{namespace}/{table_name}"
+ metadata = _s3t._initial_iceberg_metadata(table_name, schema_fields, location)
+ if schema:
+ metadata["schemas"] = [schema]
+ partition_spec = body.get("partition-spec")
+ if partition_spec:
+ metadata["partition-specs"] = [partition_spec]
+ metadata["default-spec-id"] = partition_spec.get("spec-id", 0)
+ metadata_location = _iceberg_write_metadata(namespace, table_name, 0, metadata)
+
+ _tables[key] = {
+ "Name": table_name,
+ "DatabaseName": namespace,
+ "Description": "",
+ "Owner": "",
+ "CreateTime": int(time.time()),
+ "UpdateTime": int(time.time()),
+ "LastAccessTime": int(time.time()),
+ "StorageDescriptor": {
+ "Location": location,
+ "Columns": [{"Name": f["name"], "Type": f["type"]} for f in schema_fields],
+ },
+ "PartitionKeys": [],
+ "TableType": "EXTERNAL_TABLE",
+ # `table_type=ICEBERG` is how Iceberg's GlueCatalog recognises the table,
+ # and `metadata_location` is the pointer both it and this REST catalog
+ # follow. Writing them here means a Firehose-created table is a normal
+ # Glue table that a Spark job's GlueCatalog can load.
+ "Parameters": {"table_type": "ICEBERG", "metadata_location": metadata_location},
+ "CatalogId": get_account_id(),
+ "VersionId": "1",
+ }
+ return _iceberg_json({"metadata-location": metadata_location, "metadata": metadata})
+
+
+def _iceberg_rest_commit_table(namespace, table_name, body):
+ """POST namespaces/{ns}/tables/{tbl} -- apply an Iceberg commit against a
+ Glue table: read current metadata, apply the updates, write the next
+ metadata.json, and advance the table's metadata_location."""
+ from ministack.services import s3tables as _s3t
+
+ table = _iceberg_table_entry(namespace, table_name)
+ if table is None:
+ 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", []))
+ version = _metadata_version_from_location(meta_loc) + 1
+ new_loc = _iceberg_write_metadata(namespace, table_name, version, metadata)
+ table["Parameters"]["metadata_location"] = new_loc
+ table["UpdateTime"] = int(time.time())
+ return _iceberg_json({"metadata-location": new_loc, "metadata": metadata})
+
+
+def _iceberg_rest_commit_transaction(body):
+ """POST transactions/commit -- DuckDB's atomic multi-table commit."""
+ for change in body.get("table-changes", []):
+ ident = change.get("identifier", {})
+ ns_field = ident.get("namespace", [""])
+ ns = ns_field[0] if isinstance(ns_field, list) and ns_field else (ns_field or "")
+ tbl = ident.get("name", "")
+ result = _iceberg_rest_commit_table(ns, tbl, change)
+ if result and result[0] not in (200, 204):
+ return result
+ return _iceberg_json({})
+
+
+def _handle_iceberg_rest(method, path, query_params, body=None):
_iceberg_maybe_log_tls_hint()
parts = [unquote(p) for p in path.strip("/").split("/") if p]
- # parts: ["iceberg", "v1", ...]
if len(parts) < 3 or parts[0] != "iceberg" or parts[1] != "v1":
- return _iceberg_error(f"Unknown Iceberg REST path: {path}",
- "NotFoundException", 404)
+ return _iceberg_error(f"Unknown Iceberg REST path: {path}", "NotFoundException", 404)
+
+ # Parse JSON body for write operations
+ if body is None:
+ body = {}
+ elif isinstance(body, bytes):
+ try:
+ body = json.loads(body) if body else {}
+ except (json.JSONDecodeError, TypeError):
+ body = {}
- # GET /iceberg/v1/config?warehouse=<id> — called once on ATTACH. The
- # prefix tells the client to build subsequent URLs as
- # /v1/catalogs/{warehouse}/... — Glue's prefix shape.
+ # GET /iceberg/v1/config
if parts[2] == "config" and len(parts) == 3 and method == "GET":
warehouse = query_params.get("warehouse", "")
if isinstance(warehouse, list):
warehouse = warehouse[0] if warehouse else ""
defaults = {"prefix": f"catalogs/{warehouse}"} if warehouse else {}
- return _iceberg_json({"defaults": defaults,
- "overrides": _iceberg_s3_overrides()})
+ return _iceberg_json({"defaults": defaults, "overrides": _iceberg_s3_overrides()})
- # Everything else: /v1/catalogs/{catalog}/namespaces[/{ns}[/tables[/{tbl}]]]
- # The catalog id is accepted but not validated — MiniStack is
- # single-catalog per account, scoping happens via the SigV4 account id.
- if len(parts) < 5 or parts[2] != "catalogs" or parts[4] != "namespaces":
- return _iceberg_error(
- f"Operation not supported: {method} {path}",
- "UnsupportedOperationException", 501)
+ # /v1/catalogs/{catalog}/namespaces[/{ns}[/tables[/{tbl}]]]
+ if len(parts) < 5 or parts[2] != "catalogs":
+ return _iceberg_error(f"Operation not supported: {method} {path}", "UnsupportedOperationException", 501)
+
+ # POST /v1/catalogs/{catalog}/transactions/commit -- DuckDB's atomic commit
+ if parts[4] == "transactions" and method == "POST":
+ return _iceberg_rest_commit_transaction(body)
- if len(parts) == 5 and method == "GET": # ListNamespaces
- return _iceberg_json(
- {"namespaces": [[name] for name in sorted(_databases.keys())]})
+ if parts[4] != "namespaces":
+ return _iceberg_error(f"Operation not supported: {method} {path}", "UnsupportedOperationException", 501)
- if len(parts) == 6 and method == "GET": # GetNamespace
+ # -- Namespace operations --
+
+ if len(parts) == 5 and method == "GET":
+ return _iceberg_json({"namespaces": [[name] for name in sorted(_databases.keys())]})
+
+ if len(parts) == 5 and method == "POST":
+ return _iceberg_rest_create_namespace(body)
+
+ if len(parts) == 6:
ns = parts[5]
- if ns not in _databases:
- return _iceberg_error(f"Namespace does not exist: {ns}",
- "NoSuchNamespaceException", 404)
- return _iceberg_json({"namespace": [ns], "properties": {}})
+ if method == "GET":
+ if ns not in _databases:
+ return _iceberg_error(f"Namespace does not exist: {ns}", "NoSuchNamespaceException", 404)
+ return _iceberg_json({"namespace": [ns], "properties": _databases[ns].get("Parameters", {})})
+ if method == "HEAD":
+ return (200 if ns in _databases else 404), {}, b""
+
+ # -- Table operations --
if len(parts) >= 7 and parts[6] == "tables":
ns = parts[5]
- if len(parts) == 7 and method == "GET": # ListTables
- if ns not in _databases:
- return _iceberg_error(f"Namespace does not exist: {ns}",
- "NoSuchNamespaceException", 404)
- prefix = f"{ns}/"
- names = sorted(
- t["Name"] for k, t in _tables.items()
- if k.startswith(prefix)
- and (t.get("Parameters") or {}).get("metadata_location"))
- return _iceberg_json(
- {"identifiers": [{"namespace": [ns], "name": n} for n in names]})
+ if len(parts) == 7:
+ if method == "GET":
+ if ns not in _databases:
+ return _iceberg_error(f"Namespace does not exist: {ns}", "NoSuchNamespaceException", 404)
+ prefix = f"{ns}/"
+ names = sorted(
+ t["Name"]
+ for k, t in _tables.items()
+ if k.startswith(prefix) and (t.get("Parameters") or {}).get("metadata_location")
+ )
+ return _iceberg_json({"identifiers": [{"namespace": [ns], "name": n} for n in names]})
+ if method == "POST":
+ return _iceberg_rest_create_table(ns, body)
+
if len(parts) == 8:
- if method == "GET": # LoadTable — the hot path
- return _iceberg_load_table(ns, parts[7])
- if method == "HEAD": # TableExists
- exists = _iceberg_table_entry(ns, parts[7]) is not None
+ tbl = parts[7]
+ if method == "GET":
+ return _iceberg_load_table(ns, tbl)
+ if method == "POST":
+ return _iceberg_rest_commit_table(ns, tbl, body)
+ if method == "HEAD":
+ exists = _iceberg_table_entry(ns, tbl) is not None
return (200 if exists else 404), {}, b""
- return _iceberg_error(
- f"Operation not supported: {method} {path}",
- "UnsupportedOperationException", 501)
+ return _iceberg_error(f"Operation not supported: {method} {path}", "UnsupportedOperationException", 501)
# ---- Databases ----
+
def _create_database(data):
db_input = data.get("DatabaseInput", {})
name = db_input.get("Name")
@@ -650,6 +844,7 @@ def _update_database(data):
# ---- Tables ----
+
def _create_table(data):
db_name = data.get("DatabaseName")
if db_name not in _databases:
@@ -736,9 +931,18 @@ def _update_table(data):
f"Table {name} was modified by another process. Expected VersionId={current_version}, got {requested_version}.",
400,
)
- safe_keys = {"Description", "Owner", "StorageDescriptor", "PartitionKeys",
- "TableType", "Parameters", "ViewOriginalText", "ViewExpandedText",
- "ViewDefinition", "IsMultiDialectView"}
+ safe_keys = {
+ "Description",
+ "Owner",
+ "StorageDescriptor",
+ "PartitionKeys",
+ "TableType",
+ "Parameters",
+ "ViewOriginalText",
+ "ViewExpandedText",
+ "ViewDefinition",
+ "IsMultiDialectView",
+ }
for k in safe_keys:
if k in table_input:
_tables[key][k] = table_input[k]
@@ -757,8 +961,12 @@ def _batch_delete_table(data):
for name in names:
key = f"{db_name}/{name}"
if key not in _tables:
- errors.append({"TableName": name, "ErrorDetail": {
- "ErrorCode": "EntityNotFoundException", "ErrorMessage": "Table not found"}})
+ errors.append(
+ {
+ "TableName": name,
+ "ErrorDetail": {"ErrorCode": "EntityNotFoundException", "ErrorMessage": "Table not found"},
+ }
+ )
else:
del _tables[key]
_partitions.pop(key, None)
@@ -770,6 +978,7 @@ def _batch_delete_table(data):
# ---- Partitions ----
+
def _create_partition(data):
db_name = data.get("DatabaseName")
table_name = data.get("TableName")
@@ -781,17 +990,18 @@ def _create_partition(data):
values = partition_input.get("Values", [])
for existing in _partitions[key]:
if existing.get("Values") == values:
- return error_response_json("AlreadyExistsException",
- f"Partition with values {values} already exists", 400)
+ return error_response_json("AlreadyExistsException", f"Partition with values {values} already exists", 400)
- _partitions[key].append({
- **partition_input,
- "DatabaseName": db_name,
- "TableName": table_name,
- "CreationTime": int(time.time()),
- "LastAccessTime": int(time.time()),
- "CatalogId": get_account_id(),
- })
+ _partitions[key].append(
+ {
+ **partition_input,
+ "DatabaseName": db_name,
+ "TableName": table_name,
+ "CreationTime": int(time.time()),
+ "LastAccessTime": int(time.time()),
+ "CatalogId": get_account_id(),
+ }
+ )
return json_response({})
@@ -803,9 +1013,7 @@ def _delete_partition(data):
if key in _partitions:
_partitions[key] = [p for p in _partitions[key] if p.get("Values") != values]
if key in _partition_column_statistics:
- _partition_column_statistics[key] = [
- e for e in _partition_column_statistics[key] if e.get("Values") != values
- ]
+ _partition_column_statistics[key] = [e for e in _partition_column_statistics[key] if e.get("Values") != values]
return json_response({})
@@ -838,17 +1046,22 @@ def _batch_create_partition(data):
values = pi.get("Values", [])
dupe = any(p.get("Values") == values for p in _partitions[key])
if dupe:
- errors.append({"PartitionValues": values, "ErrorDetail": {
- "ErrorCode": "AlreadyExistsException",
- "ErrorMessage": "Partition already exists"}})
+ errors.append(
+ {
+ "PartitionValues": values,
+ "ErrorDetail": {"ErrorCode": "AlreadyExistsException", "ErrorMessage": "Partition already exists"},
+ }
+ )
else:
- _partitions[key].append({
- **pi,
- "DatabaseName": db_name,
- "TableName": table_name,
- "CreationTime": int(time.time()),
- "CatalogId": get_account_id(),
- })
+ _partitions[key].append(
+ {
+ **pi,
+ "DatabaseName": db_name,
+ "TableName": table_name,
+ "CreationTime": int(time.time()),
+ "CatalogId": get_account_id(),
+ }
+ )
return json_response({"Errors": errors})
@@ -879,8 +1092,7 @@ def _batch_update_partition(data):
table_name = data.get("TableName")
key = f"{db_name}/{table_name}"
if key not in _tables:
- return error_response_json("EntityNotFoundException",
- f"Table {table_name} not found in {db_name}", 400)
+ return error_response_json("EntityNotFoundException", f"Table {table_name} not found in {db_name}", 400)
parts = _partitions.get(key, [])
errors = []
for entry in data.get("Entries", []):
@@ -892,25 +1104,31 @@ def _batch_update_partition(data):
target = p
break
if target is None:
- errors.append({"PartitionValueList": values, "ErrorDetail": {
- "ErrorCode": "EntityNotFoundException",
- "ErrorMessage": "Partition not found"}})
+ errors.append(
+ {
+ "PartitionValueList": values,
+ "ErrorDetail": {"ErrorCode": "EntityNotFoundException", "ErrorMessage": "Partition not found"},
+ }
+ )
continue
creation_time = target.get("CreationTime")
target.clear()
- target.update({
- **partition_input,
- "DatabaseName": db_name,
- "TableName": table_name,
- "CreationTime": creation_time,
- "LastAccessTime": int(time.time()),
- "CatalogId": get_account_id(),
- })
+ target.update(
+ {
+ **partition_input,
+ "DatabaseName": db_name,
+ "TableName": table_name,
+ "CreationTime": creation_time,
+ "LastAccessTime": int(time.time()),
+ "CatalogId": get_account_id(),
+ }
+ )
return json_response({"Errors": errors})
# ---- Partition Indexes ----
+
def _create_partition_index(data):
db_name = data.get("DatabaseName")
table_name = data.get("TableName")
@@ -920,11 +1138,13 @@ def _create_partition_index(data):
_partition_indexes[key] = []
raw_keys = index_input.get("Keys", [])
key_schema = [{"Name": k} if isinstance(k, str) else k for k in raw_keys]
- _partition_indexes[key].append({
- "IndexName": index_input.get("IndexName", ""),
- "Keys": key_schema,
- "IndexStatus": "ACTIVE",
- })
+ _partition_indexes[key].append(
+ {
+ "IndexName": index_input.get("IndexName", ""),
+ "Keys": key_schema,
+ "IndexStatus": "ACTIVE",
+ }
+ )
return json_response({})
@@ -937,6 +1157,7 @@ def _get_partition_indexes(data):
# ---- Column Statistics ----
+
def _partition_stats_entry(key, values):
for entry in _partition_column_statistics.get(key, []):
if entry.get("Values") == values:
@@ -949,17 +1170,19 @@ def _update_column_statistics_for_table(data):
table_name = data.get("TableName")
key = f"{db_name}/{table_name}"
if key not in _tables:
- return error_response_json("EntityNotFoundException",
- f"Table {table_name} not found in {db_name}", 400)
+ return error_response_json("EntityNotFoundException", f"Table {table_name} not found in {db_name}", 400)
stats_list = data.get("ColumnStatisticsList", [])
bucket = _table_column_statistics.setdefault(key, {})
errors = []
for cs in stats_list:
col = cs.get("ColumnName")
if not col:
- errors.append({"ColumnStatistics": cs, "Error": {
- "ErrorCode": "InvalidInputException",
- "ErrorMessage": "ColumnName is required"}})
+ errors.append(
+ {
+ "ColumnStatistics": cs,
+ "Error": {"ErrorCode": "InvalidInputException", "ErrorMessage": "ColumnName is required"},
+ }
+ )
continue
bucket[col] = cs
return json_response({"Errors": errors})
@@ -970,8 +1193,7 @@ def _get_column_statistics_for_table(data):
table_name = data.get("TableName")
key = f"{db_name}/{table_name}"
if key not in _tables:
- return error_response_json("EntityNotFoundException",
- f"Table {table_name} not found in {db_name}", 400)
+ return error_response_json("EntityNotFoundException", f"Table {table_name} not found in {db_name}", 400)
bucket = _table_column_statistics.get(key, {})
stats_list = []
errors = []
@@ -979,9 +1201,15 @@ def _get_column_statistics_for_table(data):
if col in bucket:
stats_list.append(bucket[col])
else:
- errors.append({"ColumnName": col, "Error": {
- "ErrorCode": "EntityNotFoundException",
- "ErrorMessage": f"Column statistics for {col} not found"}})
+ errors.append(
+ {
+ "ColumnName": col,
+ "Error": {
+ "ErrorCode": "EntityNotFoundException",
+ "ErrorMessage": f"Column statistics for {col} not found",
+ },
+ }
+ )
return json_response({"ColumnStatisticsList": stats_list, "Errors": errors})
@@ -991,8 +1219,7 @@ def _delete_column_statistics_for_table(data):
column_name = data.get("ColumnName")
key = f"{db_name}/{table_name}"
if key not in _tables:
- return error_response_json("EntityNotFoundException",
- f"Table {table_name} not found in {db_name}", 400)
+ return error_response_json("EntityNotFoundException", f"Table {table_name} not found in {db_name}", 400)
# Real Glue's Delete* operations are idempotent — deleting stats for a
# column that never had any returns 200 with an empty body.
_table_column_statistics.get(key, {}).pop(column_name, None)
@@ -1005,8 +1232,7 @@ def _update_column_statistics_for_partition(data):
values = data.get("PartitionValues", [])
key = f"{db_name}/{table_name}"
if not any(p.get("Values") == values for p in _partitions.get(key, [])):
- return error_response_json("EntityNotFoundException",
- f"Partition with values {values} not found", 400)
+ return error_response_json("EntityNotFoundException", f"Partition with values {values} not found", 400)
entry = _partition_stats_entry(key, values)
if entry is None:
entry = {"Values": values, "Stats": {}}
@@ -1015,9 +1241,12 @@ def _update_column_statistics_for_partition(data):
for cs in data.get("ColumnStatisticsList", []):
col = cs.get("ColumnName")
if not col:
- errors.append({"ColumnStatistics": cs, "Error": {
- "ErrorCode": "InvalidInputException",
- "ErrorMessage": "ColumnName is required"}})
+ errors.append(
+ {
+ "ColumnStatistics": cs,
+ "Error": {"ErrorCode": "InvalidInputException", "ErrorMessage": "ColumnName is required"},
+ }
+ )
continue
entry["Stats"][col] = cs
return json_response({"Errors": errors})
@@ -1029,11 +1258,9 @@ def _get_column_statistics_for_partition(data):
values = data.get("PartitionValues", [])
key = f"{db_name}/{table_name}"
if key not in _tables:
- return error_response_json("EntityNotFoundException",
- f"Table {table_name} not found in {db_name}", 400)
+ return error_response_json("EntityNotFoundException", f"Table {table_name} not found in {db_name}", 400)
if not any(p.get("Values") == values for p in _partitions.get(key, [])):
- return error_response_json("EntityNotFoundException",
- f"Partition with values {values} not found", 400)
+ return error_response_json("EntityNotFoundException", f"Partition with values {values} not found", 400)
entry = _partition_stats_entry(key, values)
bucket = entry["Stats"] if entry else {}
stats_list = []
@@ -1042,9 +1269,15 @@ def _get_column_statistics_for_partition(data):
if col in bucket:
stats_list.append(bucket[col])
else:
- errors.append({"ColumnName": col, "Error": {
- "ErrorCode": "EntityNotFoundException",
- "ErrorMessage": f"Column statistics for {col} not found"}})
+ errors.append(
+ {
+ "ColumnName": col,
+ "Error": {
+ "ErrorCode": "EntityNotFoundException",
+ "ErrorMessage": f"Column statistics for {col} not found",
+ },
+ }
+ )
return json_response({"ColumnStatisticsList": stats_list, "Errors": errors})
@@ -1055,8 +1288,7 @@ def _delete_column_statistics_for_partition(data):
column_name = data.get("ColumnName")
key = f"{db_name}/{table_name}"
if not any(p.get("Values") == values for p in _partitions.get(key, [])):
- return error_response_json("EntityNotFoundException",
- f"Partition with values {values} not found", 400)
+ return error_response_json("EntityNotFoundException", f"Partition with values {values} not found", 400)
entry = _partition_stats_entry(key, values)
if entry is not None:
entry.get("Stats", {}).pop(column_name, None)
@@ -1065,6 +1297,7 @@ def _delete_column_statistics_for_partition(data):
# ---- Connections ----
+
def _create_connection(data):
conn_input = data.get("ConnectionInput", {})
name = conn_input.get("Name")
@@ -1094,6 +1327,7 @@ def _get_connections(data):
# ---- Crawlers ----
+
def _create_crawler(data):
name = data.get("Name")
if name in _crawlers:
@@ -1101,6 +1335,7 @@ def _create_crawler(data):
_glue_role = data.get("Role", "")
if _glue_role:
from ministack.core.iam_evaluator import validate_role_arn
+
_glue_role_err = validate_role_arn(_glue_role)
if _glue_role_err:
return error_response_json("InvalidInputException", _glue_role_err, 400)
@@ -1156,9 +1391,20 @@ def _update_crawler(data):
if name not in _crawlers:
return error_response_json("EntityNotFoundException", f"Crawler {name} not found", 400)
crawler = _crawlers[name]
- updatable = {"Role", "DatabaseName", "Description", "Targets", "Schedule",
- "Classifiers", "TablePrefix", "SchemaChangePolicy", "RecrawlPolicy",
- "LineageConfiguration", "Configuration", "CrawlerSecurityConfiguration"}
+ updatable = {
+ "Role",
+ "DatabaseName",
+ "Description",
+ "Targets",
+ "Schedule",
+ "Classifiers",
+ "TablePrefix",
+ "SchemaChangePolicy",
+ "RecrawlPolicy",
+ "LineageConfiguration",
+ "Configuration",
+ "CrawlerSecurityConfiguration",
+ }
for k in updatable:
if k in data:
if k == "Schedule":
@@ -1177,8 +1423,7 @@ def _start_crawler(data):
return error_response_json("EntityNotFoundException", f"Crawler {name} not found", 400)
crawler = _crawlers[name]
if crawler["State"] == "RUNNING":
- return error_response_json("CrawlerRunningException",
- f"Crawler {name} is already running", 400)
+ return error_response_json("CrawlerRunningException", f"Crawler {name} is already running", 400)
crawler["State"] = "RUNNING"
crawler["CrawlElapsedTime"] = 0
@@ -1216,8 +1461,7 @@ def _stop_crawler(data):
if name not in _crawlers:
return error_response_json("EntityNotFoundException", f"Crawler {name} not found", 400)
if _crawlers[name]["State"] != "RUNNING":
- return error_response_json("CrawlerNotRunningException",
- f"Crawler {name} is not running", 400)
+ return error_response_json("CrawlerNotRunningException", f"Crawler {name} is not running", 400)
_crawlers[name]["State"] = "STOPPING"
_crawlers[name]["State"] = "READY"
return json_response({})
@@ -1229,21 +1473,24 @@ def _get_crawler_metrics(data):
for name in crawler_names:
crawler = _crawlers.get(name)
if crawler:
- metrics.append({
- "CrawlerName": name,
- "TimeLeftSeconds": 0.0,
- "StillEstimating": False,
- "LastRuntimeSeconds": crawler.get("CrawlElapsedTime", 0) / 1000.0,
- "MedianRuntimeSeconds": crawler.get("CrawlElapsedTime", 0) / 1000.0,
- "TablesCreated": 0,
- "TablesUpdated": 0,
- "TablesDeleted": 0,
- })
+ metrics.append(
+ {
+ "CrawlerName": name,
+ "TimeLeftSeconds": 0.0,
+ "StillEstimating": False,
+ "LastRuntimeSeconds": crawler.get("CrawlElapsedTime", 0) / 1000.0,
+ "MedianRuntimeSeconds": crawler.get("CrawlElapsedTime", 0) / 1000.0,
+ "TablesCreated": 0,
+ "TablesUpdated": 0,
+ "TablesDeleted": 0,
+ }
+ )
return json_response({"CrawlerMetricsList": metrics})
# ---- Jobs ----
+
def _create_job(data):
name = data.get("Name")
if not name:
@@ -1297,10 +1544,21 @@ def _update_job(data):
job_update = data.get("JobUpdate", {})
if name not in _jobs:
return error_response_json("EntityNotFoundException", f"Job {name} not found", 400)
- updatable = {"Description", "Role", "Command", "DefaultArguments",
- "NonOverridableArguments", "Connections", "MaxRetries", "Timeout",
- "GlueVersion", "NumberOfWorkers", "WorkerType", "MaxCapacity",
- "SecurityConfiguration"}
+ updatable = {
+ "Description",
+ "Role",
+ "Command",
+ "DefaultArguments",
+ "NonOverridableArguments",
+ "Connections",
+ "MaxRetries",
+ "Timeout",
+ "GlueVersion",
+ "NumberOfWorkers",
+ "WorkerType",
+ "MaxCapacity",
+ "SecurityConfiguration",
+ }
for k in updatable:
if k in job_update:
_jobs[name][k] = job_update[k]
@@ -1332,6 +1590,7 @@ def _resolve_script(script_location):
# Fetch from in-memory S3
try:
import ministack.services.s3 as _s3_svc
+
s3_bucket = _s3_svc._buckets.get(bucket)
if s3_bucket:
obj = s3_bucket.get("objects", {}).get(key)
@@ -1436,7 +1695,8 @@ def _execute_subprocess(run, job, args, resolved):
env[env_key] = str(v)
proc = subprocess.run(
["python3", resolved],
- capture_output=True, text=True,
+ capture_output=True,
+ text=True,
timeout=min(job.get("Timeout", 300), 600),
env=env,
)
@@ -1487,12 +1747,60 @@ runpy.run_path(_script, run_name="__main__")
"""
+def _extract_python_error(logs: str) -> str:
+ """Pull the Python traceback out of Spark's mixed output.
+
+ Spark routes everything through stdout, so a Python traceback is buried
+ under hundreds of Java INFO lines. Look for the last ``Traceback`` block
+ and return everything from there to the end of the error.
+ """
+ marker = "Traceback (most recent call last):"
+ idx = logs.rfind(marker)
+ if idx == -1:
+ return ""
+ return logs[idx:].strip()
+
+
+_LOOPBACK_HOSTS = ("localhost", "127.0.0.1", "host.docker.internal")
+
+
+def _translate_loopback_conf(value: str, ministack_host: str, ministack_port: str) -> str:
+ """Rewrite loopback references to MiniStack in a user Spark conf value.
+
+ A ``--conf`` value carrying ``localhost:4566`` (or ``127.0.0.1`` /
+ ``host.docker.internal``) was written from the submitting host's point of
+ view; inside the job container those names do not reach MiniStack, so the
+ Iceberg REST client falls back to a dead endpoint. From inside the
+ container they can only have meant "MiniStack as the submitter saw it", so
+ the host part is rewritten to the resolved gateway address. Only the
+ gateway port qualifies — any other host or port passes through untouched,
+ so a conf pointing at an external REST catalog keeps working.
+ """
+ for h in _LOOPBACK_HOSTS:
+ value = re.sub(
+ rf"(?<![\w.-]){re.escape(h)}:{ministack_port}(?!\d)",
+ f"{ministack_host}:{ministack_port}",
+ value,
+ )
+ return value
+
+
def _execute_spark_docker(run, job, job_name, args, script_path, docker_client):
"""Run a Glue Spark job inside an amazon/aws-glue-libs Docker container."""
glue_version = job.get("GlueVersion", "4.0")
image = _glue_image_for_version(glue_version)
container_name = f"ministack-glue-{job_name}-{run['Id'][:8]}"
+ # Ensure the default Iceberg warehouse bucket exists so CREATE TABLE
+ # ... USING iceberg works without the user pre-creating it.
+ try:
+ from ministack.services import s3 as _s3
+
+ if _s3._ensure_bucket("ministack-glue-warehouse") is None:
+ _s3._create_bucket("ministack-glue-warehouse", b"", {})
+ except Exception:
+ pass
+
# Remove stale container with same name
try:
existing = docker_client.containers.get(container_name)
@@ -1505,12 +1813,12 @@ def _execute_spark_docker(run, job, job_name, args, script_path, docker_client):
# Determine MiniStack's S3 endpoint from inside the container.
# If on a Docker network, use the ministack container's IP; otherwise localhost.
ministack_host = os.environ.get("MINISTACK_HOST", "")
- ministack_port = os.environ.get("EDGE_PORT", "4566")
+ ministack_port = (os.environ.get("GATEWAY_PORT")
+ or os.environ.get("EDGE_PORT") or "4566")
if ms_network and not ministack_host:
# Try to resolve from HOSTNAME
try:
- ms_container = docker_client.containers.get(
- os.environ.get("HOSTNAME", ""))
+ ms_container = docker_client.containers.get(os.environ.get("HOSTNAME", ""))
ms_container.reload()
nets = ms_container.attrs.get("NetworkSettings", {}).get("Networks", {})
ip = nets.get(ms_network, {}).get("IPAddress", "")
@@ -1519,7 +1827,37 @@ def _execute_spark_docker(run, job, job_name, args, script_path, docker_client):
except Exception:
pass
if not ministack_host:
- ministack_host = "host.docker.internal"
+ # HOSTNAME lookup failed. Try to find our own container by name on the
+ # network — the compose service name or the container name both work.
+ for name in ("ministack", os.environ.get("HOSTNAME", "")):
+ if not name:
+ continue
+ try:
+ c = docker_client.containers.get(name)
+ c.reload()
+ nets = c.attrs.get("NetworkSettings", {}).get("Networks", {})
+ for net_name, net_info in nets.items():
+ ip = net_info.get("IPAddress", "")
+ if ip:
+ ministack_host = ip
+ if not ms_network:
+ ms_network = net_name
+ break
+ if ministack_host:
+ break
+ except Exception:
+ pass
+ if not ministack_host:
+ # Last resort: resolve the gateway address, which is how
+ # host.docker.internal resolves on Docker Desktop. On Linux the
+ # extra_hosts entry maps it to host-gateway, so this is what the
+ # Spark container would see — use it directly rather than relying
+ # on the name, which the Java SDK may resolve to 127.0.0.1.
+ try:
+ import socket
+ ministack_host = socket.gethostbyname("host.docker.internal")
+ except Exception:
+ ministack_host = "host.docker.internal"
s3_endpoint = f"http://{ministack_host}:{ministack_port}"
@@ -1532,45 +1870,129 @@ def _execute_spark_docker(run, job, job_name, args, script_path, docker_client):
# Extra py files (Glue --extra-py-files)
extra_py = args.get("--extra-py-files", "")
- # Build environment for the container
+ # Build environment for the container.
+ # Both Python (boto3) and Java (AWS SDK v2) credential chains read these.
+ # Hardcoded to "test" so the Glue container always authenticates against
+ # MiniStack regardless of what the host env carries.
container_env = {
- "AWS_ACCESS_KEY_ID": os.environ.get("AWS_ACCESS_KEY_ID", "test"),
- "AWS_SECRET_ACCESS_KEY": os.environ.get("AWS_SECRET_ACCESS_KEY", "test"),
+ "AWS_ACCESS_KEY_ID": "test",
+ "AWS_SECRET_ACCESS_KEY": "test",
"AWS_DEFAULT_REGION": get_region(),
"AWS_REGION": get_region(),
- # Route the script's own SDK clients (boto3 et al) at MiniStack, the
- # same injection Lambda containers, CodeBuild and ECS RunTask do.
- # Only the S3A conf below covered Spark reads/writes; a bare
- # boto3.client("s3") in the script escaped to real AWS and failed
- # InvalidAccessKeyId (#1492).
"AWS_ENDPOINT_URL": s3_endpoint,
+ # Java AWS SDK v2 reads AWS_ENDPOINT_URL only from 2.21 (late 2023);
+ # the Glue images ship older SDKs, and Iceberg's S3FileIO does the
+ # actual S3 PutObject through them — so set the service-specific var
+ # (and the system property below) explicitly.
+ "AWS_ENDPOINT_URL_S3": s3_endpoint,
"DISABLE_SSL": "true",
}
# Build the spark-submit command.
- # The aws-glue-libs image has /home/glue_user/spark/bin/spark-submit.
+ ak = container_env["AWS_ACCESS_KEY_ID"]
+ sk = container_env["AWS_SECRET_ACCESS_KEY"]
cmd = [
"spark-submit",
- "--master", "local[*]",
- "--conf", f"spark.hadoop.fs.s3a.endpoint={s3_endpoint}",
- "--conf", "spark.hadoop.fs.s3a.path.style.access=true",
- "--conf", f"spark.hadoop.fs.s3a.access.key={container_env['AWS_ACCESS_KEY_ID']}",
- "--conf", f"spark.hadoop.fs.s3a.secret.key={container_env['AWS_SECRET_ACCESS_KEY']}",
- "--conf", "spark.hadoop.fs.s3a.impl=org.apache.hadoop.fs.s3a.S3AFileSystem",
- "--conf", "spark.hadoop.fs.s3a.connection.ssl.enabled=false",
+ "--master",
+ "local[*]",
+ # Java SDK v2 system property: Iceberg's S3FileIO reads this for
+ # the S3 endpoint when the env var is not picked up.
+ "--conf",
+ f"spark.driver.extraJavaOptions=-Daws.endpointUrlS3={s3_endpoint}",
+ "--conf",
+ f"spark.executor.extraJavaOptions=-Daws.endpointUrlS3={s3_endpoint}",
+ # S3A (Hadoop filesystem for s3a:// paths)
+ "--conf",
+ f"spark.hadoop.fs.s3a.endpoint={s3_endpoint}",
+ "--conf",
+ "spark.hadoop.fs.s3a.path.style.access=true",
+ "--conf",
+ f"spark.hadoop.fs.s3a.access.key={ak}",
+ "--conf",
+ f"spark.hadoop.fs.s3a.secret.key={sk}",
+ "--conf",
+ "spark.hadoop.fs.s3a.impl=org.apache.hadoop.fs.s3a.S3AFileSystem",
+ "--conf",
+ "spark.hadoop.fs.s3a.connection.ssl.enabled=false",
]
+ # Iceberg GlueCatalog conf -- add when the user's job or --conf references
+ # iceberg, or when --datalake-formats includes it. Glue 5 has Iceberg on
+ # the classpath by default; Glue 4 only when --datalake-formats is set.
+ conf_arg = args.get("--conf", "")
+ datalake_formats = args.get("--datalake-formats", "")
+ uses_iceberg = (
+ "iceberg" in conf_arg.lower() or "iceberg" in datalake_formats.lower() or glue_version.startswith("5")
+ )
+ if uses_iceberg:
+ cmd.extend(
+ [
+ "--conf",
+ "spark.sql.catalog.spark_catalog=org.apache.iceberg.spark.SparkSessionCatalog",
+ "--conf",
+ "spark.sql.catalog.spark_catalog.catalog-impl=org.apache.iceberg.aws.glue.GlueCatalog",
+ "--conf",
+ f"spark.sql.catalog.spark_catalog.glue.endpoint={s3_endpoint}",
+ "--conf",
+ # `s3://`, not `s3a://`: Iceberg's S3FileIO (io-impl above) and
+ # DuckDB both address objects with the `s3://` scheme via the AWS
+ # SDK. An `s3a://` warehouse stamps `s3a://` into table metadata,
+ # which DuckDB's httpfs cannot write to — so a Firehose commit to
+ # a Spark-created table silently no-ops. Keeping both engines on
+ # `s3://` is what lets them share one table.
+ "spark.sql.catalog.spark_catalog.warehouse=s3://ministack-glue-warehouse/",
+ "--conf",
+ "spark.sql.catalog.spark_catalog.io-impl=org.apache.iceberg.aws.s3.S3FileIO",
+ "--conf",
+ f"spark.sql.catalog.spark_catalog.s3.endpoint={s3_endpoint}",
+ "--conf",
+ "spark.sql.catalog.spark_catalog.s3.path-style-access=true",
+ "--conf",
+ f"spark.sql.catalog.spark_catalog.s3.access-key-id={ak}",
+ "--conf",
+ f"spark.sql.catalog.spark_catalog.s3.secret-access-key={sk}",
+ ]
+ )
+
# Add extra-py-files if present
if extra_py:
cmd.extend(["--py-files", extra_py])
# Add Spark/Iceberg conf from job arguments
conf_arg = args.get("--conf", "")
+ user_confs = []
if conf_arg:
for conf in conf_arg.split(" --conf "):
conf = conf.strip()
if conf:
- cmd.extend(["--conf", conf])
+ translated = _translate_loopback_conf(conf, ministack_host, ministack_port)
+ cmd.extend(["--conf", translated])
+ user_confs.append(translated)
+
+ # Iceberg's S3FileIO creates its own S3 client per catalog. If the user
+ # defined a catalog (spark.sql.catalog.<name>=...) but did not set its
+ # s3.endpoint, the write path resolves to localhost. Inject the MiniStack
+ # endpoint for every user catalog that doesn't already have one.
+ if uses_iceberg:
+ user_conf_str = " ".join(user_confs)
+ catalog_names = set()
+ for uc in user_confs:
+ m = re.match(r"spark\.sql\.catalog\.(\w+)=", uc)
+ # spark_catalog gets the full GlueCatalog block above; every
+ # other user-defined catalog (including one named "default")
+ # gets its S3FileIO endpoint injected here.
+ if m and m.group(1) != "spark_catalog":
+ catalog_names.add(m.group(1))
+ for cat in sorted(catalog_names):
+ prefix = f"spark.sql.catalog.{cat}"
+ if f"{prefix}.s3.endpoint=" not in user_conf_str:
+ cmd.extend(["--conf", f"{prefix}.s3.endpoint={s3_endpoint}"])
+ if f"{prefix}.s3.path-style-access=" not in user_conf_str:
+ cmd.extend(["--conf", f"{prefix}.s3.path-style-access=true"])
+ if f"{prefix}.s3.access-key-id=" not in user_conf_str:
+ cmd.extend(["--conf", f"{prefix}.s3.access-key-id={ak}"])
+ if f"{prefix}.s3.secret-access-key=" not in user_conf_str:
+ cmd.extend(["--conf", f"{prefix}.s3.secret-access-key={sk}"])
# The script path inside the container; spark-submit is handed the
# bootstrap, which re-runs the real script as __main__ (see
@@ -1581,6 +2003,21 @@ def _execute_spark_docker(run, job, job_name, args, script_path, docker_client):
# Append Glue job arguments (--key value pairs) after the script
cmd.extend(spark_args)
+ # --additional-python-modules: pip install before spark-submit,
+ # matching real Glue which installs packages before the script runs.
+ # The Glue 5 image has entrypoint ["bash", "-l"], so we must override
+ # the entrypoint to avoid double-bash invocation.
+ extra_modules = args.get("--additional-python-modules", "")
+ _entrypoint_override = None
+ if extra_modules:
+ pkgs = [p.strip() for p in extra_modules.split(",") if p.strip()]
+ if pkgs:
+ pip_cmd = "pip install --quiet --no-warn-script-location " + " ".join(f"'{p}'" for p in pkgs)
+ spark_cmd = " ".join(f"'{c}'" for c in cmd)
+ cmd = [f"{pip_cmd} && exec {spark_cmd}"]
+ _entrypoint_override = ["bash", "-lc"]
+ logger.info("Glue: will install additional modules for %s: %s", job_name, pkgs)
+
container_kwargs = {
"image": image,
"name": container_name,
@@ -1588,14 +2025,22 @@ def _execute_spark_docker(run, job, job_name, args, script_path, docker_client):
"environment": container_env,
"detach": True,
"labels": container_reaper.own_labels("glue", job_name=job_name),
+ # host.docker.internal resolves natively on Docker Desktop but not on
+ # a Linux engine; map it so a user conf pointing at the host resolves
+ # there too.
+ "extra_hosts": {"host.docker.internal": "host-gateway"},
}
+ if _entrypoint_override:
+ container_kwargs["entrypoint"] = _entrypoint_override
if ms_network:
container_kwargs["network"] = ms_network
logger.info(
"Glue: starting Spark container for %s (image=%s, network=%s)",
- job_name, image, ms_network or "host",
+ job_name,
+ image,
+ ms_network or "host",
)
try:
@@ -1603,12 +2048,12 @@ def _execute_spark_docker(run, job, job_name, args, script_path, docker_client):
# Copy script into container (avoids Docker-in-Docker volume mount issues)
import io
import tarfile
+
script_data = open(script_path, "rb").read()
boot_data = _GLUE_BOOT_SCRIPT.format(script=container_script).encode()
tar_buf = io.BytesIO()
with tarfile.open(fileobj=tar_buf, mode="w") as tar:
- for name, data in ((os.path.basename(script_path), script_data),
- ("_ministack_boot.py", boot_data)):
+ for name, data in ((os.path.basename(script_path), script_data), ("_ministack_boot.py", boot_data)):
info = tarfile.TarInfo(name=name)
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
@@ -1629,18 +2074,24 @@ def _execute_spark_docker(run, job, job_name, args, script_path, docker_client):
try:
result = container.wait(timeout=min(job.get("Timeout", 2880) * 60, 3600))
exit_code = result.get("StatusCode", -1)
- logs = container.logs(tail=200).decode("utf-8", errors="replace")
+ # Capture the full output. Spark routes Python tracebacks through
+ # stdout (not stderr), so tail=200 loses them under Java INFO lines.
+ all_logs = container.logs().decode("utf-8", errors="replace")
+ if all_logs:
+ logger.info("Glue: %s output:\n%s", job_name, all_logs[-16000:])
if exit_code == 0:
run["JobRunState"] = "SUCCEEDED"
logger.info("Glue: Spark job %s completed successfully", job_name)
else:
run["JobRunState"] = "FAILED"
- run["ErrorMessage"] = logs[-2000:] if logs else f"Exit code {exit_code}"
+ # Extract the Python traceback if present, otherwise full logs
+ error_output = _extract_python_error(all_logs) or all_logs or f"Exit code {exit_code}"
+ run["ErrorMessage"] = error_output[-8000:]
logger.warning("Glue: Spark job %s failed (exit %d)", job_name, exit_code)
except Exception as e:
run["JobRunState"] = "FAILED"
- run["ErrorMessage"] = f"Container execution error: {e}"[:2000]
+ run["ErrorMessage"] = f"Container execution error: {e}"[:4000]
logger.warning("Glue: Spark container for %s error: %s", job_name, e)
finally:
try:
@@ -1678,27 +2129,38 @@ def _batch_stop_job_run(data):
run["LastModifiedOn"] = int(time.time())
successful.append({"JobName": job_name, "JobRunId": run_id})
else:
- errors.append({"JobName": job_name, "JobRunId": run_id,
- "ErrorDetail": {"ErrorCode": "InvalidInputException",
- "ErrorMessage": f"Run {run_id} is in state {run['JobRunState']}"}})
+ errors.append(
+ {
+ "JobName": job_name,
+ "JobRunId": run_id,
+ "ErrorDetail": {
+ "ErrorCode": "InvalidInputException",
+ "ErrorMessage": f"Run {run_id} is in state {run['JobRunState']}",
+ },
+ }
+ )
found = True
break
if not found:
- errors.append({"JobName": job_name, "JobRunId": run_id,
- "ErrorDetail": {"ErrorCode": "EntityNotFoundException",
- "ErrorMessage": "Run not found"}})
+ errors.append(
+ {
+ "JobName": job_name,
+ "JobRunId": run_id,
+ "ErrorDetail": {"ErrorCode": "EntityNotFoundException", "ErrorMessage": "Run not found"},
+ }
+ )
return json_response({"SuccessfulSubmissions": successful, "Errors": errors})
# ---- Security Configurations ----
+
def _create_security_configuration(data):
name = data.get("Name")
if not name:
return error_response_json("InvalidInputException", "Name is required", 400)
if name in _security_configs:
- return error_response_json("AlreadyExistsException",
- f"Security configuration {name} already exists", 400)
+ return error_response_json("AlreadyExistsException", f"Security configuration {name} already exists", 400)
_security_configs[name] = {
"Name": name,
"CreatedTimeStamp": int(time.time()),
@@ -1710,8 +2172,7 @@ def _create_security_configuration(data):
def _delete_security_configuration(data):
name = data.get("Name")
if name not in _security_configs:
- return error_response_json("EntityNotFoundException",
- f"Security configuration {name} not found", 400)
+ return error_response_json("EntityNotFoundException", f"Security configuration {name} not found", 400)
del _security_configs[name]
return json_response({})
@@ -1720,8 +2181,7 @@ def _get_security_configuration(data):
name = data.get("Name")
config = _security_configs.get(name)
if not config:
- return error_response_json("EntityNotFoundException",
- f"Security configuration {name} not found", 400)
+ return error_response_json("EntityNotFoundException", f"Security configuration {name} not found", 400)
return json_response({"SecurityConfiguration": config})
@@ -1731,6 +2191,7 @@ def _get_security_configurations(data):
# ---- Classifiers ----
+
def _create_classifier(data):
grok = data.get("GrokClassifier")
xml_cls = data.get("XMLClassifier")
@@ -1739,17 +2200,21 @@ def _create_classifier(data):
classifier = grok or xml_cls or json_cls or csv_cls
if not classifier:
- return error_response_json("InvalidInputException",
- "Must provide one of GrokClassifier, XMLClassifier, JsonClassifier, CsvClassifier", 400)
+ return error_response_json(
+ "InvalidInputException",
+ "Must provide one of GrokClassifier, XMLClassifier, JsonClassifier, CsvClassifier",
+ 400,
+ )
name = classifier.get("Name")
if not name:
return error_response_json("InvalidInputException", "Classifier name is required", 400)
if name in _classifiers:
- return error_response_json("AlreadyExistsException",
- f"Classifier {name} already exists", 400)
+ return error_response_json("AlreadyExistsException", f"Classifier {name} already exists", 400)
- cls_type = "GrokClassifier" if grok else "XMLClassifier" if xml_cls else "JsonClassifier" if json_cls else "CsvClassifier"
+ cls_type = (
+ "GrokClassifier" if grok else "XMLClassifier" if xml_cls else "JsonClassifier" if json_cls else "CsvClassifier"
+ )
_classifiers[name] = {
cls_type: {**classifier, "CreationTime": int(time.time()), "LastUpdated": int(time.time()), "Version": 1},
}
@@ -1778,6 +2243,7 @@ def _delete_classifier(data):
# ---- Triggers ----
+
def _create_trigger(data):
name = data.get("Name")
if not name:
@@ -1888,6 +2354,7 @@ def _get_triggers(data):
# ---- Workflows ----
+
def _create_workflow(data):
name = data.get("Name")
if not name:
@@ -1953,8 +2420,12 @@ def _start_workflow_run(data):
"StartedOn": int(time.time()),
"CompletedOn": None,
"Statistics": {
- "TotalActions": 0, "RunningActions": 0, "StoppedActions": 0,
- "SucceededActions": 0, "FailedActions": 0, "TimeoutActions": 0,
+ "TotalActions": 0,
+ "RunningActions": 0,
+ "StoppedActions": 0,
+ "SucceededActions": 0,
+ "FailedActions": 0,
+ "TimeoutActions": 0,
},
"WorkflowRunProperties": dict(_workflows[name].get("DefaultRunProperties", {})),
}
@@ -1964,6 +2435,7 @@ def _start_workflow_run(data):
# ---- User Defined Functions ----
+
def _udf_key(db_name: str, func_name: str) -> str:
return f"{db_name}/{func_name}"
@@ -2006,7 +2478,9 @@ def _update_user_defined_function(data):
func_name = data.get("FunctionName")
key = _udf_key(db_name, func_name)
if key not in _user_defined_functions:
- return error_response_json("EntityNotFoundException", f"User-defined function {func_name} not found in {db_name}", 400)
+ return error_response_json(
+ "EntityNotFoundException", f"User-defined function {func_name} not found in {db_name}", 400
+ )
fn_input = data.get("FunctionInput") or {}
existing = _user_defined_functions[key]
for field in ("ClassName", "OwnerName", "OwnerType", "ResourceUris"):
@@ -2026,7 +2500,9 @@ def _delete_user_defined_function(data):
func_name = data.get("FunctionName")
key = _udf_key(db_name, func_name)
if key not in _user_defined_functions:
- return error_response_json("EntityNotFoundException", f"User-defined function {func_name} not found in {db_name}", 400)
+ return error_response_json(
+ "EntityNotFoundException", f"User-defined function {func_name} not found in {db_name}", 400
+ )
del _user_defined_functions[key]
return json_response({})
@@ -2037,7 +2513,9 @@ def _get_user_defined_function(data):
key = _udf_key(db_name, func_name)
udf = _user_defined_functions.get(key)
if not udf:
- return error_response_json("EntityNotFoundException", f"User-defined function {func_name} not found in {db_name}", 400)
+ return error_response_json(
+ "EntityNotFoundException", f"User-defined function {func_name} not found in {db_name}", 400
+ )
return json_response({"UserDefinedFunction": udf})
@@ -2064,9 +2542,9 @@ def _translate_java_regex_quote(pattern):
out.append(pattern[i:start])
end = pattern.find(r"\E", start + 2)
if end == -1:
- out.append(re.escape(pattern[start + 2:]))
+ out.append(re.escape(pattern[start + 2 :]))
break
- out.append(re.escape(pattern[start + 2:end]))
+ out.append(re.escape(pattern[start + 2 : end]))
i = end + 2
return "".join(out)
@@ -2101,6 +2579,7 @@ def _get_user_defined_functions(data):
# ---- Tags ----
+
def _tag_resource(data):
arn = data.get("ResourceArn", "")
validation_error = _validate_tag_resource_arn(arn)
@@ -2130,6 +2609,7 @@ def _get_tags(data):
# ---- Helpers ----
+
def _simple_glob_match(pattern, name):
"""Very simple glob matching: * matches anything."""
return fnmatch.fnmatch(name, pattern)
@@ -2169,4 +2649,5 @@ async def handle_request(method, path, headers, body, query_params):
behind the call waiting on it.
"""
return await run_reentrant(
- _handle_request_sync, method, path, headers, body, query_params, thread_name="ministack-glue-dispatch")
+ _handle_request_sync, method, path, headers, body, query_params, thread_name="ministack-glue-dispatch"
+ )
diff --git a/ministack/services/s3tables.py b/ministack/services/s3tables.py
index 298ddda7..f46dea3a 100644
--- a/ministack/services/s3tables.py
+++ b/ministack/services/s3tables.py
@@ -56,18 +56,21 @@ _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()
-_namespaces = AccountRegionScopedDict() # "bucket_arn\x00namespace" -> ns dict
-_tables = AccountRegionScopedDict() # "bucket_arn\x00namespace\x00table" -> table dict
+_namespaces = AccountRegionScopedDict() # "bucket_arn\x00namespace" -> ns dict
+_tables = AccountRegionScopedDict() # "bucket_arn\x00namespace\x00table" -> table dict
# ── Persistence ────────────────────────────────────────────
+
def get_state():
return {
"table_buckets": copy.deepcopy(_table_buckets),
@@ -96,6 +99,7 @@ if PERSIST_STATE:
# ── Helpers ────────────────────────────────────────────────
+
def _bucket_arn(name):
return f"arn:aws:s3tables:{get_region()}:{get_account_id()}:bucket/{name}"
@@ -119,7 +123,7 @@ def _bucket_name_from_arn(bucket_arn):
prefix = "bucket/"
if not spec.resource.startswith(prefix):
return None
- name = spec.resource[len(prefix):]
+ name = spec.resource[len(prefix) :]
if not name or "/" in name:
return None
return name
@@ -182,34 +186,59 @@ def _set_bucket_region_value(store, bucket_arn, key, value):
def _to_iceberg_type(kind):
- return {"string": "string", "int": "int", "long": "long", "boolean": "boolean",
- "date": "date", "timestamp": "timestamptz", "float": "float", "double": "double"
- }.get(kind, "string")
+ return {
+ "string": "string",
+ "int": "int",
+ "long": "long",
+ "boolean": "boolean",
+ "date": "date",
+ "timestamp": "timestamptz",
+ "float": "float",
+ "double": "double",
+ }.get(kind, "string")
def _initial_iceberg_metadata(table_name, schema_fields, location):
table_uuid = new_uuid()
fields = []
for i, f in enumerate(schema_fields):
- fields.append({"id": i + 1, "name": f["name"], "required": f.get("required", False),
- "type": _to_iceberg_type(f.get("type", "string"))})
+ fields.append(
+ {
+ "id": i + 1,
+ "name": f["name"],
+ "required": f.get("required", False),
+ "type": _to_iceberg_type(f.get("type", "string")),
+ }
+ )
schema = {"type": "struct", "schema-id": 0, "fields": fields}
return {
- "format-version": 3, "table-uuid": table_uuid, "location": location,
- "last-sequence-number": 0, "last-updated-ms": int(time.time() * 1000),
- "last-column-id": len(schema_fields), "current-schema-id": 0,
- "schemas": [schema], "default-spec-id": 0,
+ "format-version": 2,
+ "table-uuid": table_uuid,
+ "location": location,
+ "last-sequence-number": 0,
+ "last-updated-ms": int(time.time() * 1000),
+ "last-column-id": len(schema_fields),
+ "current-schema-id": 0,
+ "schemas": [schema],
+ "default-spec-id": 0,
"partition-specs": [{"spec-id": 0, "fields": []}],
- "last-partition-id": 999, "default-sort-order-id": 0,
+ "last-partition-id": 999,
+ "default-sort-order-id": 0,
"sort-orders": [{"order-id": 0, "fields": []}],
- "properties": {}, "current-snapshot-id": -1, "refs": {},
- "snapshots": [], "statistics": [], "snapshot-log": [], "metadata-log": [],
+ "properties": {},
+ "current-snapshot-id": -1,
+ "refs": {},
+ "snapshots": [],
+ "statistics": [],
+ "snapshot-log": [],
+ "metadata-log": [],
"next-row-id": 0,
}
# ── S3 Tables control plane ───────────────────────────────
+
def _create_table_bucket(data):
name = data.get("name", "")
if not name:
@@ -217,12 +246,18 @@ def _create_table_bucket(data):
if name in _table_buckets:
return error_response_json("ConflictException", f"Table bucket {name} already exists", 409)
arn = _bucket_arn(name)
- _table_buckets[name] = {"arn": arn, "name": name, "ownerAccountId": get_account_id(),
- "createdAt": now_iso(), "tableCount": 0}
+ _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})
@@ -259,6 +294,7 @@ def _delete_table_bucket(arn):
del _namespaces[key]
del _table_buckets[name]
import ministack.services.s3 as _s3
+
_s3._buckets.pop(name, None)
return 204, {}, b"" # AWS answers 204 No Content on the deletes
@@ -275,9 +311,13 @@ def _create_namespace(bucket_arn, data):
key = _ns_key(bucket_arn, namespace)
if key in _namespaces:
return error_response_json("ConflictException", f"Namespace {namespace} already exists", 409)
- _namespaces[key] = {"namespace": [namespace], "createdAt": now_iso(),
- "createdBy": get_account_id(), "ownerAccountId": get_account_id(),
- "tableBucketARN": bucket_arn}
+ _namespaces[key] = {
+ "namespace": [namespace],
+ "createdAt": now_iso(),
+ "createdBy": get_account_id(),
+ "ownerAccountId": get_account_id(),
+ "tableBucketARN": bucket_arn,
+ }
logger.info("S3Tables: created namespace %s", namespace)
return json_response({"namespace": [namespace], "tableBucketARN": bucket_arn})
@@ -331,24 +371,53 @@ def _create_table(bucket_arn, namespace, data):
schema_fields = []
metadata = data.get("metadata", {})
iceberg_meta = metadata.get("iceberg", {})
- schema_def = iceberg_meta.get("schema", {})
+ schema_def = iceberg_meta.get("schema", iceberg_meta.get("schemaV2", {}))
for f in schema_def.get("field", schema_def.get("fields", [])):
- schema_fields.append({"name": f["name"], "type": f.get("type", "string"),
- "required": f.get("required", False)})
+ schema_fields.append({"name": f["name"], "type": f.get("type", "string"), "required": f.get("required", False)})
+ logger.debug(
+ "S3Tables: create_table %s/%s schema_fields=%d metadata_keys=%s",
+ namespace,
+ table_name,
+ len(schema_fields),
+ list(metadata.keys()) if metadata else "none",
+ )
bucket_name = bucket_arn.rsplit("/", 1)[-1]
location = f"s3://{bucket_name}/{namespace}/{table_name}"
iceberg_metadata = _initial_iceberg_metadata(table_name, schema_fields, location)
+ # Preserve field names from the input but ensure the schema has the
+ # Iceberg-required structure: {"type": "struct", "schema-id": 0, "fields": [
+ # {"id": 1, "name": "...", "type": "string", "required": false}, ...]}
+ raw_schema = iceberg_meta.get("schema", iceberg_meta.get("schemaV2"))
+ if raw_schema and raw_schema.get("fields"):
+ fields = []
+ for i, f in enumerate(raw_schema["fields"]):
+ fields.append(
+ {
+ "id": f.get("id", i + 1),
+ "name": f["name"],
+ "type": _to_iceberg_type(f.get("type", "string")) if isinstance(f.get("type"), str) else "string",
+ "required": f.get("required", False),
+ }
+ )
+ iceberg_metadata["schemas"] = [{"type": "struct", "schema-id": 0, "fields": fields}]
+ iceberg_metadata["last-column-id"] = len(fields)
metadata_location = f"s3://{bucket_name}/{namespace}/{table_name}/metadata/v0.metadata.json"
arn = _table_arn(bucket_arn, namespace, table_name)
_tables[key] = {
- "name": table_name, "tableARN": arn, "namespace": [namespace],
- "tableBucketARN": bucket_arn, "format": fmt,
- "createdAt": now_iso(), "modifiedAt": now_iso(),
+ "name": table_name,
+ "tableARN": arn,
+ "namespace": [namespace],
+ "tableBucketARN": bucket_arn,
+ "format": fmt,
+ "createdAt": now_iso(),
+ "modifiedAt": now_iso(),
"ownerAccountId": get_account_id(),
- "metadataLocation": metadata_location, "warehouseLocation": location,
- "_iceberg_metadata": iceberg_metadata, "_metadata_version": 0,
+ "metadataLocation": metadata_location,
+ "warehouseLocation": location,
+ "_iceberg_metadata": iceberg_metadata,
+ "_metadata_version": 0,
"_schema_fields": schema_fields,
}
@@ -373,9 +442,15 @@ def _list_tables(bucket_arn, namespace=None):
table_ns = table["namespace"][0] if isinstance(table["namespace"], list) else table["namespace"]
if namespace and table_ns != namespace:
continue
- result.append({"name": table["name"], "tableARN": table["tableARN"],
- "namespace": table["namespace"], "format": table["format"],
- "createdAt": table["createdAt"]})
+ result.append(
+ {
+ "name": table["name"],
+ "tableARN": table["tableARN"],
+ "namespace": table["namespace"],
+ "format": table["format"],
+ "createdAt": table["createdAt"],
+ }
+ )
return json_response({"tables": result})
@@ -412,8 +487,7 @@ def _get_table_metadata_location(bucket_arn, namespace, table_name):
table = _tables.get(key)
if not table:
return error_response_json("NotFoundException", f"Table {table_name} not found", 404)
- return json_response({"metadataLocation": table["metadataLocation"],
- "versionToken": new_uuid()[:8]})
+ return json_response({"metadataLocation": table["metadataLocation"], "versionToken": new_uuid()[:8]})
def _update_table_metadata_location(bucket_arn, namespace, table_name, data):
@@ -428,20 +502,82 @@ def _update_table_metadata_location(bucket_arn, namespace, table_name, data):
new_loc = data.get("metadataLocation", "")
table["metadataLocation"] = new_loc
table["modifiedAt"] = now_iso()
- return json_response({"metadataLocation": new_loc, "name": table_name,
- "versionToken": new_uuid()[:8]})
+ return json_response({"metadataLocation": new_loc, "name": table_name, "versionToken": new_uuid()[:8]})
# ── Iceberg REST catalog (data plane for Spark) ───────────
-def _iceberg_config():
- return json_response({"defaults": {
+
+def _iceberg_config(query_params=None, headers=None):
+ warehouse = ""
+ if query_params:
+ warehouse = query_params.get("warehouse", "")
+ if isinstance(warehouse, list):
+ warehouse = warehouse[0] if warehouse else ""
+ s3_endpoint = _reachable_s3_endpoint()
+ # S3 connection properties go in ``defaults`` so a client that already
+ # supplies them (e.g. a Spark job with its own s3.endpoint pointing at
+ # host.docker.internal) is not overridden. Iceberg REST spec: ``defaults``
+ # are used only when the client has no value; ``overrides`` always win.
+ defaults = {
"client.region": get_region(),
- "s3.endpoint": _gateway_url(),
+ "s3.endpoint": s3_endpoint,
"s3.access-key-id": "test",
"s3.secret-access-key": "test",
"s3.path-style-access": "true",
- }, "overrides": {}})
+ }
+ overrides = {}
+ if warehouse:
+ overrides["prefix"] = warehouse
+ return json_response({"defaults": defaults, "overrides": overrides})
+
+
+def _resolve_container_ip():
+ """Return our own container IP on the Docker network, or None.
+
+ This is the address a sibling container (e.g. a Glue Spark job) can use
+ to reach MiniStack. Cached after the first successful resolution.
+ """
+ if hasattr(_resolve_container_ip, "_cached"):
+ return _resolve_container_ip._cached
+ ip = os.environ.get("MINISTACK_HOST", "")
+ if ip and ip not in ("localhost", "127.0.0.1", "host.docker.internal"):
+ _resolve_container_ip._cached = ip
+ return ip
+ try:
+ import docker
+ client = docker.from_env()
+ hostname = os.environ.get("HOSTNAME", "")
+ if hostname:
+ container = client.containers.get(hostname)
+ container.reload()
+ nets = container.attrs.get("NetworkSettings", {}).get("Networks", {})
+ for net_info in nets.values():
+ addr = net_info.get("IPAddress", "")
+ if addr:
+ _resolve_container_ip._cached = addr
+ return addr
+ except Exception:
+ pass
+ _resolve_container_ip._cached = None
+ return None
+
+
+def _reachable_s3_endpoint():
+ """S3 endpoint URL that both host-side and container-side callers can reach.
+
+ Used in every Iceberg REST response that carries s3.endpoint — the
+ /v1/config response and each LoadTable response. The Iceberg S3FileIO
+ builds its S3 client from this value, so returning localhost when the
+ caller is a Docker container means every S3 write (PutObject during
+ S3OutputStream.close) fails with Connection refused.
+ """
+ resolved = _resolve_container_ip()
+ if resolved:
+ from ministack.core import tls as _tls
+ scheme = "https" if _tls.use_ssl_enabled() else "http"
+ return f"{scheme}://{resolved}:{_GATEWAY_PORT}"
+ return _gateway_url()
def _iceberg_error(message, exc_type, code):
@@ -451,9 +587,7 @@ def _iceberg_error(message, exc_type, code):
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")
+ body = json.dumps({"error": {"message": message, "type": exc_type, "code": code}}).encode("utf-8")
return code, {"Content-Type": "application/json"}, body
@@ -468,103 +602,212 @@ def _iceberg_list_namespaces(allow_cross_region):
return json_response({"namespaces": result})
+def _iceberg_create_namespace(data, allow_cross_region, bucket_filter=None):
+ """POST /iceberg/v1/namespaces — Iceberg REST createNamespace.
+
+ Delegates to the control-plane CreateNamespace, which stores the record.
+ The Iceberg REST spec returns the namespace and its properties on success,
+ and AlreadyExistsException (409) when the namespace exists.
+ """
+ ns_list = data.get("namespace", [])
+ ns_name = ns_list[0] if isinstance(ns_list, list) and ns_list else data.get("namespace", "")
+ if not ns_name:
+ return _iceberg_error("namespace is required", "BadRequestException", 400)
+ # Find the table bucket to create the namespace in. When the prefix
+ # carries a bucket filter (from the /v1/config warehouse), use that;
+ # otherwise fall back to the first visible bucket.
+ if bucket_filter:
+ buckets = _iceberg_values(
+ _table_buckets, lambda b: b.get("arn", "").endswith("/" + bucket_filter),
+ allow_cross_region)
+ else:
+ buckets = _iceberg_values(_table_buckets, lambda _b: True, allow_cross_region)
+ if not buckets:
+ return _iceberg_error("No table bucket found", "NoSuchNamespaceException", 404)
+ bucket = buckets[0]
+ bucket_arn = bucket.get("arn", "")
+ # Check if namespace already exists.
+ existing = _iceberg_values(
+ _namespaces, lambda ns: _namespace_name(ns) == ns_name, allow_cross_region)
+ if existing:
+ return _iceberg_error(
+ f"Namespace already exists: {ns_name}", "AlreadyExistsException", 409)
+ _create_namespace(bucket_arn, {"namespace": [ns_name]})
+ return json_response({"namespace": [ns_name], "properties": data.get("properties", {})})
+
+
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 _iceberg_error(f"Namespace {namespace} not found", "NoSuchNamespaceException", 404)
-def _iceberg_list_tables(namespace, allow_cross_region):
+def _iceberg_list_tables(namespace, allow_cross_region, bucket_filter=None):
+ def _pred(table):
+ if _namespace_name(table) != namespace:
+ return False
+ if bucket_filter:
+ return table.get("tableBucketARN", "").endswith("/" + bucket_filter)
+ return True
+
result = []
- for table in _iceberg_values(_tables, lambda table: _namespace_name(table) == namespace, allow_cross_region):
+ for table in _iceberg_values(_tables, _pred, allow_cross_region):
result.append({"namespace": [namespace], "name": table["name"]})
return json_response({"identifiers": result})
-def _iceberg_load_table(namespace, table_name, allow_cross_region):
- matches = _iceberg_values(
- _tables,
- lambda table: _namespace_name(table) == namespace and table["name"] == table_name,
- allow_cross_region,
- )
+def _iceberg_load_table(namespace, table_name, allow_cross_region, bucket_filter=None):
+ def _pred(table):
+ if _namespace_name(table) != namespace or table["name"] != table_name:
+ return False
+ if bucket_filter:
+ return table.get("tableBucketARN", "").endswith("/" + bucket_filter)
+ return True
+
+ matches = _iceberg_values(_tables, _pred, allow_cross_region)
if matches:
table = matches[0]
- return json_response({
- "metadata-location": table.get("metadataLocation", ""),
- "metadata": table.get("_iceberg_metadata", {}),
- "config": {
- "s3.access-key-id": "test", "s3.secret-access-key": "test",
- "s3.endpoint": _gateway_url(), "s3.path-style-access": "true",
- "s3.region": get_region(), "client.region": get_region(),
- },
- })
+ # Try to read the latest metadata from S3 (source of truth). Writers
+ # like DuckDB commit by writing metadata.json directly to S3 without
+ # going through the REST commit endpoint, so the in-memory metadata
+ # can be stale. Fall back to in-memory if S3 read fails.
+ metadata = table.get("_iceberg_metadata", {})
+ meta_loc = table.get("metadataLocation", "")
+ if meta_loc and meta_loc.startswith("s3://"):
+ try:
+ import ministack.services.s3 as _s3
+
+ rest = meta_loc[len("s3://") :]
+ bkt, key = rest.split("/", 1)
+ # Find the latest metadata file in the metadata directory
+ meta_dir = "/".join(key.split("/")[:-1]) + "/"
+ bucket_data = _s3._ensure_bucket(bkt)
+ if bucket_data:
+ meta_files = sorted(
+ k
+ for k in bucket_data.get("objects", {})
+ if k.startswith(meta_dir) and k.endswith(".metadata.json")
+ )
+ if meta_files:
+ # Order vN.metadata.json numerically: lexically v10
+ # sorts before v2, so from the 10th commit on the scan
+ # would serve v9 forever. Spark-style zero-padded
+ # names all map to -1 and keep their lexical order.
+ from ministack.services.glue import _metadata_version_from_location
+
+ meta_files.sort(key=_metadata_version_from_location)
+ latest_key = meta_files[-1]
+ raw = _s3._get_object_data(bkt, latest_key)
+ if raw:
+ metadata = json.loads(raw)
+ meta_loc = f"s3://{bkt}/{latest_key}"
+ except Exception:
+ pass # fall back to in-memory
+ return json_response(
+ {
+ "metadata-location": meta_loc,
+ "metadata": metadata,
+ "config": {
+ "s3.endpoint": _reachable_s3_endpoint(),
+ "s3.access-key-id": "test",
+ "s3.secret-access-key": "test",
+ "s3.path-style-access": "true",
+ "s3.region": get_region(),
+ "client.region": get_region(),
+ },
+ }
+ )
return _iceberg_error(f"Table {namespace}.{table_name} not found", "NoSuchTableException", 404)
-def _iceberg_commit_table(namespace, table_name, data, allow_cross_region):
- matches = _iceberg_values(
- _tables,
- lambda table: _namespace_name(table) == namespace and table["name"] == table_name,
- allow_cross_region,
- )
+def _apply_iceberg_updates(metadata, updates):
+ """Apply a list of Iceberg REST commit ``updates`` to a table ``metadata``
+ dict in place. Shared by the S3 Tables and Glue Data Catalog Iceberg REST
+ catalogs so both apply commits (from DuckDB, Spark, ...) identically."""
+ for update in updates:
+ action = update.get("action", "")
+ if action == "add-snapshot":
+ snapshot = update.get("snapshot", {})
+ metadata.setdefault("snapshots", []).append(snapshot)
+ metadata["current-snapshot-id"] = snapshot.get("snapshot-id", -1)
+ metadata["last-updated-ms"] = int(time.time() * 1000)
+ metadata["last-sequence-number"] = metadata.get("last-sequence-number", 0) + 1
+ elif action == "set-snapshot-ref":
+ metadata.setdefault("refs", {})[update.get("ref-name", "main")] = {
+ "snapshot-id": update.get("snapshot-id", -1),
+ "type": update.get("type", "branch"),
+ }
+ elif action == "add-schema":
+ new_schema = update.get("schema", {})
+ existing = metadata.setdefault("schemas", [])
+ # Idempotent by schema-id: a client re-declaring its current,
+ # unchanged schema on every write (Spark does this) must not pile
+ # up a second entry with the same id -- Iceberg's schemasById()
+ # crashes on load with "Multiple entries with same key" if it does.
+ if not any(s.get("schema-id") == new_schema.get("schema-id") for s in existing):
+ existing.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":
+ schema_id = update.get("schema-id", 0)
+ if schema_id == -1:
+ # -1 means "the schema added earlier in this commit".
+ ids = [s.get("schema-id", 0) for s in metadata.get("schemas", [])]
+ schema_id = max(ids) if ids else 0
+ metadata["current-schema-id"] = schema_id
+ 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.
+ new_spec = update.get("spec", {})
+ specs = metadata.setdefault("partition-specs", [])
+ # Idempotent by spec-id, for the same reason as add-schema above.
+ if not any(s.get("spec-id") == new_spec.get("spec-id") for s in specs):
+ specs.append(new_spec)
+ elif action == "set-default-spec":
+ spec_id = update.get("spec-id", 0)
+ if spec_id == -1:
+ ids = [s.get("spec-id", 0) for s in metadata.get("partition-specs", [])]
+ spec_id = max(ids) if ids else 0
+ metadata["default-spec-id"] = spec_id
+ elif action == "add-sort-order":
+ new_order = update.get("sort-order", {})
+ orders = metadata.setdefault("sort-orders", [])
+ # Idempotent by order-id, for the same reason as add-schema above.
+ if not any(o.get("order-id") == new_order.get("order-id") for o in orders):
+ orders.append(new_order)
+ elif action == "set-default-sort-order":
+ order_id = update.get("sort-order-id", 0)
+ if order_id == -1:
+ ids = [o.get("order-id", 0) for o in metadata.get("sort-orders", [])]
+ order_id = max(ids) if ids else 0
+ metadata["default-sort-order-id"] = order_id
+ elif action == "set-properties":
+ metadata.setdefault("properties", {}).update(update.get("updates", {}))
+ elif action == "remove-properties":
+ for r in update.get("removals", []):
+ metadata.get("properties", {}).pop(r, None)
+ elif action == "set-location":
+ metadata["location"] = update.get("location", "")
+
+
+def _iceberg_commit_table(namespace, table_name, data, allow_cross_region, bucket_filter=None):
+ def _pred(table):
+ if _namespace_name(table) != namespace or table["name"] != table_name:
+ return False
+ if bucket_filter:
+ return table.get("tableBucketARN", "").endswith("/" + bucket_filter)
+ return True
+
+ matches = _iceberg_values(_tables, _pred, allow_cross_region)
if matches:
table = matches[0]
metadata = table.get("_iceberg_metadata", {})
- for update in data.get("updates", []):
- action = update.get("action", "")
- if action == "add-snapshot":
- snapshot = update.get("snapshot", {})
- metadata.setdefault("snapshots", []).append(snapshot)
- metadata["current-snapshot-id"] = snapshot.get("snapshot-id", -1)
- metadata["last-updated-ms"] = int(time.time() * 1000)
- metadata["last-sequence-number"] = metadata.get("last-sequence-number", 0) + 1
- elif action == "set-snapshot-ref":
- metadata.setdefault("refs", {})[update.get("ref-name", "main")] = {
- "snapshot-id": update.get("snapshot-id", -1),
- "type": update.get("type", "branch")}
- elif action == "add-schema":
- new_schema = update.get("schema", {})
- existing = metadata.setdefault("schemas", [])
- # Idempotent by schema-id: a client re-declaring its current,
- # unchanged schema on every write (Spark does this) must not pile
- # up a second entry with the same id -- Iceberg's schemasById()
- # crashes on load with "Multiple entries with same key" if it does.
- if not any(s.get("schema-id") == new_schema.get("schema-id") for s in existing):
- existing.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 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.
- new_spec = update.get("spec", {})
- specs = metadata.setdefault("partition-specs", [])
- # Idempotent by spec-id, for the same reason as add-schema above.
- if not any(s.get("spec-id") == new_spec.get("spec-id") for s in specs):
- specs.append(new_spec)
- elif action == "set-default-spec":
- metadata["default-spec-id"] = update.get("spec-id", 0)
- elif action == "add-sort-order":
- new_order = update.get("sort-order", {})
- orders = metadata.setdefault("sort-orders", [])
- # Idempotent by order-id, for the same reason as add-schema above.
- if not any(o.get("order-id") == new_order.get("order-id") for o in orders):
- orders.append(new_order)
- elif action == "set-default-sort-order":
- metadata["default-sort-order-id"] = update.get("sort-order-id", 0)
- elif action == "set-properties":
- metadata.setdefault("properties", {}).update(update.get("updates", {}))
- elif action == "remove-properties":
- for r in update.get("removals", []):
- metadata.get("properties", {}).pop(r, None)
- elif action == "set-location":
- metadata["location"] = update.get("location", "")
+ _apply_iceberg_updates(metadata, data.get("updates", []))
table["_metadata_version"] = table.get("_metadata_version", 0) + 1
v = table["_metadata_version"]
@@ -572,6 +815,18 @@ def _iceberg_commit_table(namespace, table_name, data, allow_cross_region):
new_loc = f"s3://{bucket_name}/{namespace}/{table_name}/metadata/v{v}.metadata.json"
table["metadataLocation"] = new_loc
table["modifiedAt"] = now_iso()
+ # Write the metadata.json to S3 so clients reading by location
+ # (DuckDB, Spark) see the committed state.
+ try:
+ import ministack.services.s3 as _s3
+
+ _s3._buckets.setdefault(bucket_name, {"created": now_iso(), "objects": {}, "region": get_region()})
+ meta_key = f"{namespace}/{table_name}/metadata/v{v}.metadata.json"
+ _s3._put_object(
+ bucket_name, meta_key, json.dumps(metadata).encode("utf-8"), {"content-type": "application/json"}
+ )
+ except Exception as exc:
+ logger.debug("s3tables: failed to write metadata.json for %s.%s: %s", namespace, table_name, exc)
return json_response({"metadata-location": new_loc, "metadata": metadata})
return _iceberg_error(f"Table {namespace}.{table_name} not found", "NoSuchTableException", 404)
@@ -592,15 +847,24 @@ def _iceberg_create_table(namespace, data, allow_cross_region):
# 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)
+ 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", [])]
+ 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", [])
+ ]
bucket_name = bucket_arn.rsplit("/", 1)[-1]
location = data.get("location", f"s3://{bucket_name}/{namespace}/{table_name}")
iceberg_metadata = _initial_iceberg_metadata(table_name, schema_fields, location)
+ # Honor a format-version from the client's request or properties.
+ fmt_ver = data.get("format-version") or data.get("properties", {}).get("format-version")
+ if fmt_ver is not None:
+ iceberg_metadata["format-version"] = int(fmt_ver)
if schema:
iceberg_metadata["schemas"] = [schema]
partition_spec = data.get("partition-spec")
@@ -614,12 +878,18 @@ def _iceberg_create_table(namespace, data, allow_cross_region):
arn = _table_arn(bucket_arn, namespace, table_name)
table = {
- "name": table_name, "tableARN": arn, "namespace": [namespace],
- "tableBucketARN": bucket_arn, "format": "ICEBERG",
- "createdAt": now_iso(), "modifiedAt": now_iso(),
+ "name": table_name,
+ "tableARN": 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,
+ "metadataLocation": metadata_location,
+ "warehouseLocation": location,
+ "_iceberg_metadata": iceberg_metadata,
+ "_metadata_version": 0,
"_schema_fields": schema_fields,
}
_set_bucket_region_value(_tables, bucket_arn, key, table)
@@ -628,6 +898,7 @@ def _iceberg_create_table(namespace, data, allow_cross_region):
# ── Iceberg REST router ───────────────────────────────────
+
async def _handle_iceberg_request(method, path, headers, body, query_params):
parts = [p for p in path.strip("/").split("/") if p]
allow_cross_region = _iceberg_allows_cross_region(headers)
@@ -636,10 +907,14 @@ async def _handle_iceberg_request(method, path, headers, body, query_params):
return None
if parts[1] == "v1" and len(parts) == 3 and parts[2] == "config" and method == "GET":
- return _iceberg_config()
-
- # POST /iceberg/v1/transactions/commit — DuckDB atomic multi-table commit
- if parts[1] == "v1" and parts[2] == "transactions" and method == "POST":
+ return _iceberg_config(query_params, headers)
+
+ # POST /iceberg/v1/transactions/commit — DuckDB atomic multi-table commit.
+ # DuckDB prepends the /v1/config prefix (the warehouse) to every path, so
+ # this arrives as /iceberg/v1/{prefix}/transactions/commit. Match on the
+ # `transactions` segment wherever it lands, not a fixed position — otherwise
+ # a prefixed commit is silently dropped and the delivery writes nothing.
+ if parts[1] == "v1" and method == "POST" and "transactions" in parts[2:]:
data = json.loads(body) if body else {}
for change in data.get("table-changes", []):
ident = change.get("identifier", {})
@@ -657,17 +932,35 @@ async def _handle_iceberg_request(method, path, headers, body, query_params):
# 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:
+ #
+ # The prefix carries the warehouse value from /v1/config, which for S3
+ # Tables is ``{account}:s3tablescatalog/{bucket-name}``. Extract the
+ # bucket name to scope table lookups -- without it, tables with the same
+ # name in different buckets collide and the wrong schema is returned.
+ # The prefix from /v1/config can contain ``/`` (e.g.
+ # ``000000000000:s3tablescatalog/bucket-name``), which splits into
+ # multiple URL segments. Scan for ``namespaces`` and treat everything
+ # between ``v1`` and ``namespaces`` as the prefix.
+ bucket_filter = None
+ ns_idx = None
+ for i in range(2, len(parts)):
+ if parts[i] == "namespaces":
+ ns_idx = i
+ break
+ if ns_idx is None:
return None
+ if ns_idx > 2:
+ prefix = unquote("/".join(parts[2:ns_idx]))
+ if ":s3tablescatalog/" in prefix:
+ bucket_filter = prefix.split(":s3tablescatalog/", 1)[1]
- rest = parts[ns_idx + 1:] # segments after "namespaces"
+ 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) == 0 and method == "POST":
+ data = json.loads(body) if body else {}
+ return _iceberg_create_namespace(data, allow_cross_region, bucket_filter)
if len(rest) == 1 and method == "GET":
return _iceberg_get_namespace(rest[0], allow_cross_region)
if len(rest) >= 2 and rest[1] == "tables":
@@ -675,17 +968,17 @@ async def _handle_iceberg_request(method, path, headers, body, query_params):
table_rest = rest[2:]
if len(table_rest) == 0:
if method == "GET":
- return _iceberg_list_tables(namespace, allow_cross_region)
+ return _iceberg_list_tables(namespace, allow_cross_region, bucket_filter)
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)
+ return _iceberg_load_table(namespace, table_name, allow_cross_region, bucket_filter)
if method == "POST":
data = json.loads(body) if body else {}
- return _iceberg_commit_table(namespace, table_name, data, allow_cross_region)
+ return _iceberg_commit_table(namespace, table_name, data, allow_cross_region, bucket_filter)
if method == "HEAD":
if _iceberg_values(
_tables,
@@ -699,6 +992,7 @@ async def _handle_iceberg_request(method, path, headers, body, query_params):
# ── S3 Tables control plane REST router ────────────────────
+
async def handle_request(method, path, headers, body, query_params):
# Iceberg REST catalog
if path.startswith("/iceberg"):
@@ -761,7 +1055,11 @@ async def handle_request(method, path, headers, body, query_params):
arn, suffix = _split_arn_and_suffix(remaining, "bucket")
if not suffix:
# GET /tables/{arn} -> ListTables
- namespace = query_params.get("namespace", [""])[0] if isinstance(query_params.get("namespace"), list) else query_params.get("namespace", "")
+ namespace = (
+ query_params.get("namespace", [""])[0]
+ if isinstance(query_params.get("namespace"), list)
+ else query_params.get("namespace", "")
+ )
return _list_tables(arn, namespace or None)
# suffix could be "namespace", "namespace/table", or "namespace/table/metadata-location"
suffix_parts = suffix.split("/")
@@ -781,13 +1079,18 @@ async def handle_request(method, path, headers, body, query_params):
# GET /get-table?tableBucketARN=&namespace=&name= -> GetTable
if parts == ["get-table"] and method == "GET":
+
def _qp(name):
- v = query_params.get(name, [""])[0] if isinstance(query_params.get(name), list) else query_params.get(name, "")
+ v = (
+ query_params.get(name, [""])[0]
+ if isinstance(query_params.get(name), list)
+ else query_params.get(name, "")
+ )
return v
+
return _get_table(_qp("tableBucketARN"), _qp("namespace"), _qp("name"))
- return error_response_json("UnknownOperationException",
- f"Unknown S3Tables operation: {method} {path}", 400)
+ return error_response_json("UnknownOperationException", f"Unknown S3Tables operation: {method} {path}", 400)
def _split_arn_and_suffix(path_str, resource_type):
@@ -805,12 +1108,12 @@ def _split_arn_and_suffix(path_str, resource_type):
return path_str, ""
# arn:...:bucket/name — find the end of the bucket name
- after_type = path_str[idx + len(f":{resource_type}/"):]
+ after_type = path_str[idx + len(f":{resource_type}/") :]
# The bucket name is the next segment before any '/'
slash_idx = after_type.find("/")
if slash_idx == -1:
# No suffix, whole thing is the ARN
return path_str, ""
- arn = path_str[:idx + len(f":{resource_type}/") + slash_idx]
- suffix = after_type[slash_idx + 1:]
+ arn = path_str[: idx + len(f":{resource_type}/") + slash_idx]
+ suffix = after_type[slash_idx + 1 :]
return arn, suffix
diff --git a/tests/test_glue.py b/tests/test_glue.py
index 9f20ce3c..7170944d 100644
--- a/tests/test_glue.py
+++ b/tests/test_glue.py
@@ -47,12 +47,14 @@ def test_glue_catalog(glue):
resp = glue.get_table(DatabaseName="test_db", Name="test_table")
assert resp["Table"]["Name"] == "test_table"
+
def test_glue_list(glue):
dbs = glue.get_databases()
assert any(d["Name"] == "test_db" for d in dbs["DatabaseList"])
tables = glue.get_tables(DatabaseName="test_db")
assert any(t["Name"] == "test_table" for t in tables["TableList"])
+
def test_glue_job(glue):
glue.create_job(
Name="test-job",
@@ -65,6 +67,7 @@ def test_glue_job(glue):
runs = glue.get_job_runs(JobName="test-job")
assert len(runs["JobRuns"]) == 1
+
def test_glue_crawler(glue):
glue.create_crawler(
Name="test-crawler",
@@ -86,9 +89,7 @@ def test_glue_catalog_jobs_and_crawlers_are_region_scoped():
crawler_name = "glue-regional-crawler"
def create_resources(client, region):
- client.create_database(
- DatabaseInput={"Name": db_name, "Description": region}
- )
+ client.create_database(DatabaseInput={"Name": db_name, "Description": region})
client.create_table(
DatabaseName=db_name,
TableInput={
@@ -138,47 +139,39 @@ def test_glue_catalog_jobs_and_crawlers_are_region_scoped():
east_run_id = create_resources(east, "us-east-1")
west_run_id = create_resources(west, "us-west-2")
- assert [db["Description"] for db in east.get_databases()["DatabaseList"]
- if db["Name"] == db_name] == ["us-east-1"]
- assert [db["Description"] for db in west.get_databases()["DatabaseList"]
- if db["Name"] == db_name] == ["us-west-2"]
- assert [table["Description"] for table in east.get_tables(
- DatabaseName=db_name
- )["TableList"]] == ["us-east-1"]
- assert [table["Description"] for table in west.get_tables(
- DatabaseName=db_name
- )["TableList"]] == ["us-west-2"]
- assert east.get_partitions(
- DatabaseName=db_name, TableName=table_name
- )["Partitions"][0]["Values"] == ["us-east-1"]
- assert west.get_partitions(
- DatabaseName=db_name, TableName=table_name
- )["Partitions"][0]["Values"] == ["us-west-2"]
- assert [job["Description"] for job in east.get_jobs()["Jobs"]
- if job["Name"] == job_name] == ["us-east-1"]
- assert [job["Description"] for job in west.get_jobs()["Jobs"]
- if job["Name"] == job_name] == ["us-west-2"]
- assert [run["Id"] for run in east.get_job_runs(JobName=job_name)["JobRuns"]] == [
- east_run_id
+ assert [db["Description"] for db in east.get_databases()["DatabaseList"] if db["Name"] == db_name] == [
+ "us-east-1"
]
- assert [run["Id"] for run in west.get_job_runs(JobName=job_name)["JobRuns"]] == [
- west_run_id
+ assert [db["Description"] for db in west.get_databases()["DatabaseList"] if db["Name"] == db_name] == [
+ "us-west-2"
]
- assert [crawler["Description"] for crawler in east.get_crawlers()["Crawlers"]
- if crawler["Name"] == crawler_name] == ["us-east-1"]
- assert [crawler["Description"] for crawler in west.get_crawlers()["Crawlers"]
- if crawler["Name"] == crawler_name] == ["us-west-2"]
+ assert [table["Description"] for table in east.get_tables(DatabaseName=db_name)["TableList"]] == ["us-east-1"]
+ assert [table["Description"] for table in west.get_tables(DatabaseName=db_name)["TableList"]] == ["us-west-2"]
+ assert east.get_partitions(DatabaseName=db_name, TableName=table_name)["Partitions"][0]["Values"] == [
+ "us-east-1"
+ ]
+ assert west.get_partitions(DatabaseName=db_name, TableName=table_name)["Partitions"][0]["Values"] == [
+ "us-west-2"
+ ]
+ assert [job["Description"] for job in east.get_jobs()["Jobs"] if job["Name"] == job_name] == ["us-east-1"]
+ assert [job["Description"] for job in west.get_jobs()["Jobs"] if job["Name"] == job_name] == ["us-west-2"]
+ assert [run["Id"] for run in east.get_job_runs(JobName=job_name)["JobRuns"]] == [east_run_id]
+ assert [run["Id"] for run in west.get_job_runs(JobName=job_name)["JobRuns"]] == [west_run_id]
+ assert [
+ crawler["Description"] for crawler in east.get_crawlers()["Crawlers"] if crawler["Name"] == crawler_name
+ ] == ["us-east-1"]
+ assert [
+ crawler["Description"] for crawler in west.get_crawlers()["Crawlers"] if crawler["Name"] == crawler_name
+ ] == ["us-west-2"]
east.delete_database(Name=db_name)
with pytest.raises(ClientError) as exc:
east.get_database(Name=db_name)
assert exc.value.response["Error"]["Code"] == "EntityNotFoundException"
- assert west.get_table(DatabaseName=db_name, Name=table_name)["Table"][
- "Description"
- ] == "us-west-2"
- assert west.get_partitions(
- DatabaseName=db_name, TableName=table_name
- )["Partitions"][0]["Values"] == ["us-west-2"]
+ assert west.get_table(DatabaseName=db_name, Name=table_name)["Table"]["Description"] == "us-west-2"
+ assert west.get_partitions(DatabaseName=db_name, TableName=table_name)["Partitions"][0]["Values"] == [
+ "us-west-2"
+ ]
finally:
for client in (east, west):
for operation, kwargs in (
@@ -191,6 +184,7 @@ def test_glue_catalog_jobs_and_crawlers_are_region_scoped():
except ClientError:
pass
+
def test_glue_database_location_uri(glue):
glue.create_database(DatabaseInput={"Name": "db_no_location"})
resp = glue.get_database(Name="db_no_location")
@@ -200,6 +194,7 @@ def test_glue_database_location_uri(glue):
resp = glue.get_database(Name="db_with_location")
assert resp["Database"]["LocationUri"] == "s3://my-bucket/warehouse/"
+
def test_glue_database_v2(glue):
glue.create_database(DatabaseInput={"Name": "glue_db_v2", "Description": "v2 DB"})
resp = glue.get_database(Name="glue_db_v2")
@@ -218,6 +213,7 @@ def test_glue_database_v2(glue):
glue.get_database(Name="glue_db_v2")
assert exc.value.response["Error"]["Code"] == "EntityNotFoundException"
+
def test_glue_table_v2(glue):
glue.create_database(DatabaseInput={"Name": "glue_tbl_v2db"})
glue.create_table(
@@ -253,6 +249,7 @@ def test_glue_table_v2(glue):
glue.get_table(DatabaseName="glue_tbl_v2db", Name="tbl_v2")
assert exc.value.response["Error"]["Code"] == "EntityNotFoundException"
+
def test_glue_view_original_text_roundtrip(glue):
glue.create_database(DatabaseInput={"Name": "glue_view_db"})
original = "/* Presto View: eyJjYXRhbG9nIjoiaWNlYmVyZyJ9 */"
@@ -283,6 +280,7 @@ def test_glue_view_original_text_roundtrip(glue):
assert resp2["Table"]["ViewOriginalText"] == original + " v2"
assert resp2["Table"]["ViewExpandedText"] == expanded + " v2"
+
def test_glue_list_v2(glue):
glue.create_database(DatabaseInput={"Name": "glue_lst_v2db"})
glue.create_table(
@@ -318,6 +316,7 @@ def test_glue_list_v2(glue):
assert "lt_a" in names
assert "lt_b" in names
+
def test_glue_job_v2(glue):
glue.create_job(
Name="glue-job-v2",
@@ -339,6 +338,7 @@ def test_glue_job_v2(glue):
runs = glue.get_job_runs(JobName="glue-job-v2")["JobRuns"]
assert any(r["Id"] == run_id for r in runs)
+
def test_glue_crawler_v2(glue):
glue.create_database(DatabaseInput={"Name": "glue_cr_v2db"})
glue.create_crawler(
@@ -355,6 +355,7 @@ def test_glue_crawler_v2(glue):
cr2 = glue.get_crawler(Name="glue-cr-v2")["Crawler"]
assert cr2["State"] == "RUNNING"
+
def test_glue_tags_v2(glue):
glue.create_database(DatabaseInput={"Name": "glue_tag_v2db"})
arn = "arn:aws:glue:us-east-1:000000000000:database/glue_tag_v2db"
@@ -422,9 +423,7 @@ def test_glue_tag_resource_accepts_supported_arn_shapes(resource):
set_request_account_id("000000000000")
set_request_region("us-east-1")
- status, body = _glue_json(
- _glue._tag_resource({"ResourceArn": arn, "TagsToAdd": {"env": "test"}})
- )
+ status, body = _glue_json(_glue._tag_resource({"ResourceArn": arn, "TagsToAdd": {"env": "test"}}))
assert status == 200
assert body == {}
@@ -501,6 +500,7 @@ def test_glue_create_database_persists_tags(glue):
tags = glue.get_tags(ResourceArn=arn)["Tags"]
assert tags == {"env": "prod", "owner": "data-platform"}
+
def test_glue_partition_v2(glue):
glue.create_database(DatabaseInput={"Name": "glue_part_v2db"})
glue.create_table(
@@ -558,6 +558,7 @@ def test_glue_partition_v2(glue):
parts = glue.get_partitions(DatabaseName="glue_part_v2db", TableName="ptbl_v2")
assert len(parts["Partitions"]) == 2
+
def test_glue_connection_v2(glue):
glue.create_connection(
ConnectionInput={
@@ -582,6 +583,7 @@ def test_glue_connection_v2(glue):
glue.get_connection(Name="glue-conn-v2")
assert exc.value.response["Error"]["Code"] == "EntityNotFoundException"
+
def test_glue_trigger(glue):
glue.create_trigger(Name="test-trig", Type="ON_DEMAND", Actions=[{"JobName": "nonexistent-job"}])
resp = glue.get_trigger(Name="test-trig")
@@ -595,6 +597,7 @@ def test_glue_trigger(glue):
assert resp3["Trigger"]["State"] == "DEACTIVATED"
glue.delete_trigger(Name="test-trig")
+
def test_glue_workflow(glue):
glue.create_workflow(Name="test-wf", Description="Test workflow")
resp = glue.get_workflow(Name="test-wf")
@@ -603,6 +606,7 @@ def test_glue_workflow(glue):
assert "RunId" in run
glue.delete_workflow(Name="test-wf")
+
def test_glue_partition_crud(glue):
"""CreatePartition / GetPartition / GetPartitions / DeletePartition."""
glue.create_database(DatabaseInput={"Name": "qa-glue-partdb"})
@@ -650,6 +654,7 @@ def test_glue_partition_crud(glue):
parts2 = glue.get_partitions(DatabaseName="qa-glue-partdb", TableName="qa-glue-parttbl")["Partitions"]
assert len(parts2) == 0
+
def test_glue_duplicate_partition_error(glue):
"""CreatePartition with duplicate values raises AlreadyExistsException."""
glue.create_database(DatabaseInput={"Name": "qa-glue-duppartdb"})
@@ -695,6 +700,7 @@ def test_glue_duplicate_partition_error(glue):
# BatchDeleteTable
# ---------------------------------------------------------------------------
+
def test_glue_batch_delete_table(glue):
db = "qa-bdt-db"
glue.create_database(DatabaseInput={"Name": db})
@@ -730,6 +736,7 @@ def test_glue_batch_delete_table(glue):
# BatchGetPartition
# ---------------------------------------------------------------------------
+
def test_glue_batch_get_partition(glue):
db = "qa-bgp-db"
tbl = "qa-bgp-tbl"
@@ -784,6 +791,7 @@ def test_glue_batch_get_partition(glue):
# BatchCreatePartition
# ---------------------------------------------------------------------------
+
def test_glue_batch_create_partition(glue):
db = "qa-bcp-db"
tbl = "qa-bcp-tbl"
@@ -859,6 +867,7 @@ def test_glue_batch_create_partition(glue):
# BatchUpdatePartition
# ---------------------------------------------------------------------------
+
def test_glue_batch_update_partition(glue):
db = "qa-bup-db"
tbl = "qa-bup-tbl"
@@ -967,6 +976,7 @@ def test_glue_batch_update_partition(glue):
# GetCrawlerMetrics
# ---------------------------------------------------------------------------
+
def test_glue_get_crawler_metrics(glue):
name = "qa-metrics-cr"
glue.create_crawler(
@@ -988,6 +998,7 @@ def test_glue_get_crawler_metrics(glue):
# UpdateCrawler
# ---------------------------------------------------------------------------
+
def test_glue_update_crawler(glue):
name = "qa-upd-cr"
glue.create_crawler(
@@ -1009,6 +1020,7 @@ def test_glue_update_crawler(glue):
# StopCrawler
# ---------------------------------------------------------------------------
+
def test_glue_stop_crawler(glue):
name = "qa-stop-cr"
glue.create_crawler(
@@ -1035,6 +1047,7 @@ def test_glue_stop_crawler(glue):
# CreateJob / DeleteJob / GetJobs / UpdateJob
# ---------------------------------------------------------------------------
+
def test_glue_create_delete_job(glue):
name = "qa-cd-job"
resp = glue.create_job(
@@ -1095,6 +1108,7 @@ def test_glue_update_job(glue):
# BatchStopJobRun
# ---------------------------------------------------------------------------
+
def test_glue_batch_stop_job_run(glue):
name = "qa-bsjr-job"
glue.create_job(
@@ -1133,6 +1147,7 @@ def test_glue_batch_stop_job_run(glue):
# SecurityConfigurations (Create / Delete / Get / GetAll)
# ---------------------------------------------------------------------------
+
def test_glue_security_configuration_crud(glue):
name = "qa-sec-cfg"
resp = glue.create_security_configuration(
@@ -1171,6 +1186,7 @@ def test_glue_security_configuration_duplicate(glue):
# Classifiers (Create / Get / GetAll / Delete)
# ---------------------------------------------------------------------------
+
def test_glue_classifier_crud(glue):
name = "qa-cls-grok"
glue.create_classifier(
@@ -1224,6 +1240,7 @@ def test_glue_classifier_duplicate(glue):
# BatchGetTriggers
# ---------------------------------------------------------------------------
+
def test_glue_batch_get_triggers(glue):
names = ["qa-bgt-a", "qa-bgt-b"]
for n in names:
@@ -1242,6 +1259,7 @@ def test_glue_batch_get_triggers(glue):
# GetTriggers
# ---------------------------------------------------------------------------
+
def test_glue_get_triggers(glue):
names = ["qa-gt-x", "qa-gt-y"]
for n in names:
@@ -1264,6 +1282,7 @@ def test_glue_get_triggers(glue):
# UpdateWorkflow
# ---------------------------------------------------------------------------
+
def test_glue_update_workflow(glue):
name = "qa-upd-wf"
glue.create_workflow(Name=name, Description="orig")
@@ -1284,6 +1303,7 @@ def test_glue_update_workflow(glue):
# CreatePartitionIndex / GetPartitionIndexes
# ---------------------------------------------------------------------------
+
def test_glue_partition_indexes(glue):
db = "qa-pidx-db"
tbl = "qa-pidx-tbl"
@@ -1329,11 +1349,13 @@ def test_glue_partition_indexes(glue):
# ── Spark job image selection (1.3.50) ─────────────────────
+
def test_glue_spark_skips_docker_when_image_missing(glue):
"""glueetl job falls back to subprocess when the Spark Docker image is not pulled.
The job should not crash MiniStack — it either runs via subprocess (and fails
on pyspark import) or stubs as SUCCEEDED if the script can't be resolved."""
import time
+
job_name = "test-spark-no-image"
try:
glue.delete_job(JobName=job_name)
@@ -1358,9 +1380,10 @@ def test_glue_spark_skips_docker_when_image_missing(glue):
# Script can't be resolved (nonexistent S3 path) so it should stub as SUCCEEDED
# The key assertion: it does NOT hang or crash — it reaches a terminal state
- assert run["JobRunState"] in ("SUCCEEDED", "FAILED"), (
- f"Job should reach terminal state without Docker image. Got: {run['JobRunState']}"
- )
+ assert run["JobRunState"] in (
+ "SUCCEEDED",
+ "FAILED",
+ ), f"Job should reach terminal state without Docker image. Got: {run['JobRunState']}"
def test_glue_spark_image_for_version_maps_to_official_aws_image():
@@ -1618,16 +1641,18 @@ def test_glue_start_job_run_resolves_script_in_worker_thread(tmp_path, monkeypat
s3mod._persist_object("glue-scripts", "etl/main.py", b"print('ok')\n")
persisted = s3mod._object_disk_path("glue-scripts", "etl/main.py")
- gluemod._create_job({
- "Name": "ctx-job",
- "Command": {"Name": "pythonshell", "ScriptLocation": "s3://glue-scripts/etl/main.py"},
- })
+ gluemod._create_job(
+ {
+ "Name": "ctx-job",
+ "Command": {"Name": "pythonshell", "ScriptLocation": "s3://glue-scripts/etl/main.py"},
+ }
+ )
gluemod._start_job_run({"JobName": "ctx-job"})
assert done.wait(5), "worker thread never invoked _resolve_script"
- assert captured["account"] == account, (
- f"worker ran under {captured.get('account')!r}, not caller account {account!r}"
- )
+ assert (
+ captured["account"] == account
+ ), f"worker ran under {captured.get('account')!r}, not caller account {account!r}"
assert captured["region"] == region
assert captured["resolved"] is not None
assert os.path.samefile(captured["resolved"], persisted)
@@ -1660,11 +1685,13 @@ def test_glue_crawler_completes_for_non_default_account(monkeypatch):
region_token = respmod._request_region.set(region)
try:
gluemod._crawlers.pop_scoped(account, region, name, None)
- gluemod._create_crawler({
- "Name": name,
- "Role": "arn:aws:iam::555555555555:role/GlueRole",
- "Targets": {"S3Targets": [{"Path": "s3://b/data/"}]},
- })
+ gluemod._create_crawler(
+ {
+ "Name": name,
+ "Role": "arn:aws:iam::555555555555:role/GlueRole",
+ "Targets": {"S3Targets": [{"Path": "s3://b/data/"}]},
+ }
+ )
gluemod._start_crawler({"Name": name})
assert gluemod._crawlers[name]["State"] == "RUNNING"
@@ -1673,9 +1700,9 @@ def test_glue_crawler_completes_for_non_default_account(monkeypatch):
while time.time() < deadline and gluemod._crawlers[name]["State"] != "READY":
time.sleep(0.05)
- assert gluemod._crawlers[name]["State"] == "READY", (
- "crawler stuck in RUNNING — finish timer ran under the wrong account"
- )
+ assert (
+ gluemod._crawlers[name]["State"] == "READY"
+ ), "crawler stuck in RUNNING — finish timer ran under the wrong account"
last_crawl = gluemod._crawlers[name]["LastCrawl"]
assert last_crawl is not None and last_crawl["Status"] == "SUCCEEDED"
finally:
@@ -1705,9 +1732,7 @@ def test_glue_legacy_account_scoped_state_falls_back_to_ambient_region():
return store
state = {
- "databases": legacy_store(
- "legacy-db", {"Name": "legacy-db", "CatalogId": account}
- ),
+ "databases": legacy_store("legacy-db", {"Name": "legacy-db", "CatalogId": account}),
"tables": legacy_store(
"legacy-db/legacy-table",
{
@@ -1716,12 +1741,7 @@ def test_glue_legacy_account_scoped_state_falls_back_to_ambient_region():
"CatalogId": account,
"StorageDescriptor": {
"SchemaReference": {
- "SchemaId": {
- "SchemaArn": (
- "arn:aws:glue:us-west-2:123456789012:"
- "schema/registry/schema"
- )
- }
+ "SchemaId": {"SchemaArn": ("arn:aws:glue:us-west-2:123456789012:" "schema/registry/schema")}
}
},
},
@@ -1743,9 +1763,7 @@ def test_glue_legacy_account_scoped_state_falls_back_to_ambient_region():
{
"Id": "legacy-run",
"JobName": "legacy-job",
- "Arguments": {
- "--key": "arn:aws:kms:us-west-2:123456789012:key/legacy"
- },
+ "Arguments": {"--key": "arn:aws:kms:us-west-2:123456789012:key/legacy"},
}
],
),
@@ -1756,18 +1774,10 @@ def test_glue_legacy_account_scoped_state_falls_back_to_ambient_region():
set_request_region(region)
gluemod.restore_state(state)
- assert gluemod._databases.get_scoped(account, region, "legacy-db")[
- "Name"
- ] == "legacy-db"
- assert gluemod._tables.get_scoped(
- account, region, "legacy-db/legacy-table"
- )["Name"] == "legacy-table"
- assert gluemod._partitions.get_scoped(
- account, region, "legacy-db/legacy-table"
- )[0]["Values"] == ["legacy"]
- assert gluemod._job_runs.get_scoped(account, region, "legacy-job")[0][
- "Id"
- ] == "legacy-run"
+ assert gluemod._databases.get_scoped(account, region, "legacy-db")["Name"] == "legacy-db"
+ assert gluemod._tables.get_scoped(account, region, "legacy-db/legacy-table")["Name"] == "legacy-table"
+ assert gluemod._partitions.get_scoped(account, region, "legacy-db/legacy-table")[0]["Values"] == ["legacy"]
+ assert gluemod._job_runs.get_scoped(account, region, "legacy-job")[0]["Id"] == "legacy-run"
for store, key in (
(gluemod._databases, "legacy-db"),
@@ -1787,17 +1797,13 @@ def test_glue_reset_clears_every_store_across_regions():
from ministack.services import glue as gluemod
account = "123456789012"
- regional_stores = {
- key: store for key, store in gluemod._ALL_STATE.items() if key != "tags"
- }
+ regional_stores = {key: store for key, store in gluemod._ALL_STATE.items() if key != "tags"}
assert len(regional_stores) == 16
for index, store in enumerate(regional_stores.values()):
store.set_scoped(account, "us-east-1", f"east-{index}", {"scope": "east"})
store.set_scoped(account, "us-west-2", f"west-{index}", {"scope": "west"})
- gluemod._tags._data[
- (account, "arn:aws:glue:us-east-1:123456789012:database/tagged")
- ] = {"team": "platform"}
+ gluemod._tags._data[(account, "arn:aws:glue:us-east-1:123456789012:database/tagged")] = {"team": "platform"}
gluemod.reset()
@@ -1842,6 +1848,7 @@ def test_glue_resolve_script_isolated_per_account(tmp_path, monkeypatch):
# ---- Column Statistics ----
+
def _make_int_column_stats(column_name):
return {
"ColumnName": column_name,
@@ -1886,28 +1893,37 @@ def test_glue_column_statistics_for_table_crud(glue):
stats_id = _make_int_column_stats("id")
stats_amount = _make_int_column_stats("amount")
upd = glue.update_column_statistics_for_table(
- DatabaseName=db, TableName=table,
+ DatabaseName=db,
+ TableName=table,
ColumnStatisticsList=[stats_id, stats_amount],
)
assert upd.get("Errors", []) == []
got = glue.get_column_statistics_for_table(
- DatabaseName=db, TableName=table, ColumnNames=["id", "amount"],
+ DatabaseName=db,
+ TableName=table,
+ ColumnNames=["id", "amount"],
)
assert {s["ColumnName"] for s in got["ColumnStatisticsList"]} == {"id", "amount"}
assert got.get("Errors", []) == []
missing = glue.get_column_statistics_for_table(
- DatabaseName=db, TableName=table, ColumnNames=["id", "missing"],
+ DatabaseName=db,
+ TableName=table,
+ ColumnNames=["id", "missing"],
)
assert [s["ColumnName"] for s in missing["ColumnStatisticsList"]] == ["id"]
assert missing["Errors"][0]["ColumnName"] == "missing"
glue.delete_column_statistics_for_table(
- DatabaseName=db, TableName=table, ColumnName="id",
+ DatabaseName=db,
+ TableName=table,
+ ColumnName="id",
)
after = glue.get_column_statistics_for_table(
- DatabaseName=db, TableName=table, ColumnNames=["id", "amount"],
+ DatabaseName=db,
+ TableName=table,
+ ColumnNames=["id", "amount"],
)
assert [s["ColumnName"] for s in after["ColumnStatisticsList"]] == ["amount"]
@@ -1915,7 +1931,9 @@ def test_glue_column_statistics_for_table_crud(glue):
def test_glue_column_statistics_for_table_missing_table(glue):
with pytest.raises(ClientError) as exc:
glue.get_column_statistics_for_table(
- DatabaseName="nope-db", TableName="nope-tbl", ColumnNames=["id"],
+ DatabaseName="nope-db",
+ TableName="nope-tbl",
+ ColumnNames=["id"],
)
assert exc.value.response["Error"]["Code"] == "EntityNotFoundException"
@@ -1926,7 +1944,9 @@ def test_glue_delete_column_statistics_for_table_unknown_column_is_idempotent(gl
# Real AWS Glue returns 200 / empty body when deleting stats for a column
# that never had any — Delete* operations are idempotent.
glue.delete_column_statistics_for_table(
- DatabaseName=db, TableName=table, ColumnName="never-set",
+ DatabaseName=db,
+ TableName=table,
+ ColumnName="never-set",
)
@@ -1934,7 +1954,8 @@ def test_glue_column_statistics_cleared_on_table_delete(glue):
db, table = "qa-glue-colstats-cleanup-db", "qa-glue-colstats-cleanup"
_setup_stats_table(glue, db, table)
glue.update_column_statistics_for_table(
- DatabaseName=db, TableName=table,
+ DatabaseName=db,
+ TableName=table,
ColumnStatisticsList=[_make_int_column_stats("id")],
)
glue.delete_table(DatabaseName=db, Name=table)
@@ -1947,12 +1968,16 @@ def test_glue_column_statistics_cleared_on_table_delete(glue):
"StorageDescriptor": {
"Columns": [{"Name": "id", "Type": "int"}],
"Location": f"s3://bucket/{db}/{table}/",
- "InputFormat": "", "OutputFormat": "", "SerdeInfo": {},
+ "InputFormat": "",
+ "OutputFormat": "",
+ "SerdeInfo": {},
},
},
)
got = glue.get_column_statistics_for_table(
- DatabaseName=db, TableName=table, ColumnNames=["id"],
+ DatabaseName=db,
+ TableName=table,
+ ColumnNames=["id"],
)
assert got["ColumnStatisticsList"] == []
assert got["Errors"][0]["ColumnName"] == "id"
@@ -1962,12 +1987,16 @@ def test_glue_column_statistics_for_partition_crud(glue):
db, table = "qa-glue-colstats-part-db", "qa-glue-colstats-part"
_setup_stats_table(glue, db, table, partitioned=True)
glue.create_partition(
- DatabaseName=db, TableName=table,
+ DatabaseName=db,
+ TableName=table,
PartitionInput={
"Values": ["2024-01-01"],
"StorageDescriptor": {
- "Columns": [], "Location": f"s3://bucket/{db}/{table}/dt=2024-01-01",
- "InputFormat": "", "OutputFormat": "", "SerdeInfo": {},
+ "Columns": [],
+ "Location": f"s3://bucket/{db}/{table}/dt=2024-01-01",
+ "InputFormat": "",
+ "OutputFormat": "",
+ "SerdeInfo": {},
},
},
)
@@ -1975,25 +2004,32 @@ def test_glue_column_statistics_for_partition_crud(glue):
stats_id = _make_int_column_stats("id")
stats_amount = _make_int_column_stats("amount")
upd = glue.update_column_statistics_for_partition(
- DatabaseName=db, TableName=table,
+ DatabaseName=db,
+ TableName=table,
PartitionValues=["2024-01-01"],
ColumnStatisticsList=[stats_id, stats_amount],
)
assert upd.get("Errors", []) == []
got = glue.get_column_statistics_for_partition(
- DatabaseName=db, TableName=table,
- PartitionValues=["2024-01-01"], ColumnNames=["id", "amount"],
+ DatabaseName=db,
+ TableName=table,
+ PartitionValues=["2024-01-01"],
+ ColumnNames=["id", "amount"],
)
assert {s["ColumnName"] for s in got["ColumnStatisticsList"]} == {"id", "amount"}
glue.delete_column_statistics_for_partition(
- DatabaseName=db, TableName=table,
- PartitionValues=["2024-01-01"], ColumnName="amount",
+ DatabaseName=db,
+ TableName=table,
+ PartitionValues=["2024-01-01"],
+ ColumnName="amount",
)
after = glue.get_column_statistics_for_partition(
- DatabaseName=db, TableName=table,
- PartitionValues=["2024-01-01"], ColumnNames=["id", "amount"],
+ DatabaseName=db,
+ TableName=table,
+ PartitionValues=["2024-01-01"],
+ ColumnNames=["id", "amount"],
)
assert [s["ColumnName"] for s in after["ColumnStatisticsList"]] == ["id"]
assert after["Errors"][0]["ColumnName"] == "amount"
@@ -2004,7 +2040,8 @@ def test_glue_column_statistics_for_partition_missing_partition(glue):
_setup_stats_table(glue, db, table, partitioned=True)
with pytest.raises(ClientError) as exc:
glue.update_column_statistics_for_partition(
- DatabaseName=db, TableName=table,
+ DatabaseName=db,
+ TableName=table,
PartitionValues=["never"],
ColumnStatisticsList=[_make_int_column_stats("id")],
)
@@ -2032,9 +2069,7 @@ def _svc(name):
def _call(method, path, query_params=None):
- status, headers, body = asyncio.run(
- _svc("glue").handle_request(method, path, {}, b"", query_params or {})
- )
+ status, headers, body = asyncio.run(_svc("glue").handle_request(method, path, {}, b"", query_params or {}))
payload = json.loads(body) if body else None
return status, headers, payload
@@ -2084,9 +2119,7 @@ def test_s3tables_signed_iceberg_request_still_routes_to_s3tables():
def test_config_returns_glue_catalogs_prefix_and_s3_overrides():
- status, headers, payload = _call(
- "GET", "/iceberg/v1/config", {"warehouse": ["000000000000"]}
- )
+ status, headers, payload = _call("GET", "/iceberg/v1/config", {"warehouse": ["000000000000"]})
assert status == 200
assert headers["Content-Type"] == "application/json"
# Glue's prefix shape — subsequent client URLs become
@@ -2120,18 +2153,14 @@ def test_list_namespaces_returns_glue_databases():
def test_get_namespace_404s_when_database_missing():
- status, _, payload = _call(
- "GET", "/iceberg/v1/catalogs/000000000000/namespaces/nope"
- )
+ status, _, payload = _call("GET", "/iceberg/v1/catalogs/000000000000/namespaces/nope")
assert status == 404
assert payload["error"]["type"] == "NoSuchNamespaceException"
def test_get_namespace_returns_shape_when_database_exists():
_svc("glue")._databases["db"] = {"Name": "db"}
- status, _, payload = _call(
- "GET", "/iceberg/v1/catalogs/000000000000/namespaces/db"
- )
+ status, _, payload = _call("GET", "/iceberg/v1/catalogs/000000000000/namespaces/db")
assert status == 200
assert payload == {"namespace": ["db"], "properties": {}}
@@ -2142,9 +2171,7 @@ def test_get_namespace_returns_shape_when_database_exists():
def test_list_tables_404s_when_namespace_missing():
"""Real Iceberg REST returns NoSuchNamespaceException for ListTables on
an unknown namespace — not an empty 200 list."""
- status, _, payload = _call(
- "GET", "/iceberg/v1/catalogs/000000000000/namespaces/nope/tables"
- )
+ status, _, payload = _call("GET", "/iceberg/v1/catalogs/000000000000/namespaces/nope/tables")
assert status == 404
assert payload["error"]["type"] == "NoSuchNamespaceException"
@@ -2159,11 +2186,11 @@ def test_list_tables_hides_non_iceberg_glue_tables():
"Parameters": {"metadata_location": "s3://lake/t/metadata/v0.metadata.json"},
}
_svc("glue")._tables["db/csv_table"] = {
- "Name": "csv_table", "DatabaseName": "db", "Parameters": {},
+ "Name": "csv_table",
+ "DatabaseName": "db",
+ "Parameters": {},
}
- _, _, payload = _call(
- "GET", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables"
- )
+ _, _, payload = _call("GET", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables")
assert [t["name"] for t in payload["identifiers"]] == ["iceberg_table"]
assert payload["identifiers"][0]["namespace"] == ["db"]
@@ -2215,9 +2242,7 @@ def test_load_table_404s_when_metadata_object_missing():
"DatabaseName": "db",
"Parameters": {"metadata_location": "s3://lake/orphan/metadata/v0.metadata.json"},
}
- status, _, payload = _call(
- "GET", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables/orphan"
- )
+ status, _, payload = _call("GET", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables/orphan")
assert status == 404
assert payload["error"]["type"] == "NoSuchTableException"
assert payload["error"]["code"] == 404
@@ -2232,17 +2257,13 @@ def test_load_table_404s_when_metadata_json_unparseable():
"DatabaseName": "db",
"Parameters": {"metadata_location": f"s3://lake/{key}"},
}
- status, _, payload = _call(
- "GET", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables/broken"
- )
+ status, _, payload = _call("GET", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables/broken")
assert status == 404
assert payload["error"]["type"] == "NoSuchTableException"
def test_load_table_404s_on_unknown_table():
- status, _, payload = _call(
- "GET", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables/missing"
- )
+ status, _, payload = _call("GET", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables/missing")
assert status == 404
assert payload["error"]["type"] == "NoSuchTableException"
@@ -2250,9 +2271,7 @@ def test_load_table_404s_on_unknown_table():
def test_load_table_404s_on_non_iceberg_table():
_svc("glue")._databases["db"] = {"Name": "db"}
_svc("glue")._tables["db/csv"] = {"Name": "csv", "DatabaseName": "db", "Parameters": {}}
- status, _, payload = _call(
- "GET", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables/csv"
- )
+ status, _, payload = _call("GET", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables/csv")
assert status == 404
@@ -2271,31 +2290,105 @@ def test_head_returns_200_for_iceberg_table():
def test_head_returns_404_for_non_iceberg_table():
_svc("glue")._databases["db"] = {"Name": "db"}
_svc("glue")._tables["db/csv"] = {"Name": "csv", "DatabaseName": "db", "Parameters": {}}
- status, _, _ = _call(
- "HEAD", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables/csv"
- )
+ status, _, _ = _call("HEAD", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables/csv")
assert status == 404
# ── Fall-throughs ────────────────────────────────────────────
-def test_post_to_table_returns_501_unsupported():
- """Read-only surface: writes get an explicit 501 envelope instead of a
- silent success that never persisted anything."""
- status, _, payload = _call(
- "POST", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables/t"
+def test_commit_to_missing_table_returns_no_such_table():
+ """The Glue Data Catalog Iceberg REST catalog is writable (Firehose and
+ Glue jobs commit through it), so a POST is a real commit rather than a
+ blanket 501. A commit against a table that does not exist returns
+ NoSuchTableException, not a silent success."""
+ status, _, payload = _call("POST", "/iceberg/v1/catalogs/000000000000/namespaces/db/tables/t")
+ assert status == 404
+ assert payload["error"]["type"] == "NoSuchTableException"
+
+
+def _call_body(method, path, body=None):
+ raw = json.dumps(body).encode() if body is not None else b""
+ status, _headers, resp = asyncio.run(_svc("glue").handle_request(method, path, {}, raw, {}))
+ return status, (json.loads(resp) if resp else None)
+
+
+_GLUE_ICEBERG_CATALOG = "arn:aws:glue:us-east-1:000000000000:catalog"
+_GLUE_ICEBERG_PREFIX = f"catalogs/{_GLUE_ICEBERG_CATALOG}"
+
+
+def test_iceberg_rest_create_commit_load_shares_glue_catalog():
+ """A table created and committed through the Glue Data Catalog Iceberg REST
+ catalog (Firehose's write path) is a real Glue table the Glue API — and thus
+ a Spark job's GlueCatalog — sees. This shared store is what lets Firehose
+ and Glue jobs converge on one table."""
+ _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 == 501
- assert payload["error"]["type"] == "UnsupportedOperationException"
+ assert status == 200
+ # Same store as the Glue API: it is a real Glue Iceberg table.
+ table = _svc("glue")._tables["lake/orders"]
+ assert table["Parameters"]["table_type"] == "ICEBERG"
+ assert table["TableType"] == "EXTERNAL_TABLE"
+ # Commit a snapshot (what DuckDB does after writing data files).
+ status, doc = _call_body(
+ "POST",
+ f"/iceberg/v1/{_GLUE_ICEBERG_PREFIX}/namespaces/lake/tables/orders",
+ {"updates": [
+ {"action": "add-snapshot", "snapshot": {"snapshot-id": 42, "sequence-number": 1,
+ "timestamp-ms": 1, "manifest-list": "s3://x/m.avro", "summary": {"operation": "append"}}},
+ {"action": "set-snapshot-ref", "ref-name": "main", "type": "branch", "snapshot-id": 42}]},
+ )
+ assert status == 200
+ assert doc["metadata"]["current-snapshot-id"] == 42
+ # loadTable reflects the committed snapshot.
+ status, doc = _call_body("GET", f"/iceberg/v1/{_GLUE_ICEBERG_PREFIX}/namespaces/lake/tables/orders")
+ assert status == 200
+ assert doc["metadata"]["current-snapshot-id"] == 42
+
+
+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 — the
+ same MiniStack object as ``s3://`` — so a Glue-job-written table is loadable
+ by Firehose's DuckDB. Regression for the last convergence gap."""
+ _svc("glue")._create_database({"DatabaseInput": {"Name": "lake"}})
+ from ministack.services import s3tables as _s3t
+
+ meta = _s3t._initial_iceberg_metadata(
+ "orders", [{"name": "id", "type": "int"}], "s3a://ministack-glue-warehouse/lake.db/orders")
+ key = "lake.db/orders/metadata/00000-x.metadata.json"
+ _svc("s3")._buckets["ministack-glue-warehouse"] = {"objects": {key: {"body": json.dumps(meta).encode()}}}
+ _svc("glue")._tables["lake/orders"] = {
+ "Name": "orders", "DatabaseName": "lake", "TableType": "EXTERNAL_TABLE",
+ "Parameters": {"table_type": "ICEBERG",
+ "metadata_location": f"s3a://ministack-glue-warehouse/{key}"}}
+ status, doc = _call_body("GET", f"/iceberg/v1/{_GLUE_ICEBERG_PREFIX}/namespaces/lake/tables/orders")
+ assert status == 200
+ assert doc["metadata-location"].startswith("s3a://")
+ assert doc["metadata"]["schemas"]
+
+
+def test_iceberg_dispatch_routes_glue_vs_s3tables():
+ """The app-level dispatch keeps Firehose and Glue on the Glue Data Catalog
+ while S3 Tables clients keep their own catalog."""
+ from ministack.app import _iceberg_targets_glue_catalog as targets_glue
+
+ assert targets_glue("/iceberg/v1/catalogs/x/namespaces/db/tables", {}) is True
+ assert targets_glue("/iceberg/v1/config", {"warehouse": "arn:aws:glue:us-east-1:000000000000:catalog"}) is True
+ assert targets_glue("/iceberg/v1/config", {"warehouse": "arn:aws:s3tables:us-east-1:000000000000:bucket/b"}) is False
+ assert targets_glue("/iceberg/v1/config", {"warehouse": "000000000000:s3tablescatalog/b"}) is False
+ assert targets_glue("/iceberg/v1/config", {}) is False
def test_non_catalogs_prefix_returns_501():
"""Bare-warehouse prefixes (`/v1/{warehouse}/namespaces`) are the
S3 Tables shape, not Glue's — reject rather than guess."""
- status, _, payload = _call(
- "GET", "/iceberg/v1/000000000000/namespaces"
- )
+ status, _, payload = _call("GET", "/iceberg/v1/000000000000/namespaces")
assert status == 501
@@ -2309,7 +2402,8 @@ def test_glue_json_rpc_surface_unaffected():
Iceberg branch — same module, two protocols."""
status, _, body = asyncio.run(
_svc("glue").handle_request(
- "POST", "/",
+ "POST",
+ "/",
{"x-amz-target": "AWSGlue.CreateDatabase"},
json.dumps({"DatabaseInput": {"Name": "rpc_db"}}).encode(),
{},
@@ -2338,8 +2432,8 @@ def test_glue_spark_container_env_points_sdk_at_ministack(tmp_path, monkeypatch)
def put_archive(self, path, data):
import io
import tarfile
- with tarfile.open(fileobj=io.BytesIO(
- data.read() if hasattr(data, "read") else data)) as tar:
+
+ with tarfile.open(fileobj=io.BytesIO(data.read() if hasattr(data, "read") else data)) as tar:
for m in tar.getmembers():
archived[m.name] = tar.extractfile(m).read().decode()
@@ -2369,14 +2463,12 @@ def test_glue_spark_container_env_points_sdk_at_ministack(tmp_path, monkeypatch)
script = tmp_path / "job.py"
script.write_text("print('hi')")
run = {"Id": "jr_test1492"}
- _glue._execute_spark_docker(
- run, {"Timeout": 1}, "envjob", {}, str(script), _FakeDocker())
+ _glue._execute_spark_docker(run, {"Timeout": 1}, "envjob", {}, str(script), _FakeDocker())
env = created["environment"]
assert env["AWS_ENDPOINT_URL"] == "http://host.docker.internal:4566"
# The SDK endpoint and the Spark S3A endpoint must agree.
- s3a = [c for c in created["command"]
- if isinstance(c, str) and c.startswith("spark.hadoop.fs.s3a.endpoint=")]
+ s3a = [c for c in created["command"] if isinstance(c, str) and c.startswith("spark.hadoop.fs.s3a.endpoint=")]
assert s3a == [f"spark.hadoop.fs.s3a.endpoint={env['AWS_ENDPOINT_URL']}"]
# spark-submit is handed the bootstrap, which patches create_client for
# botocore versions predating AWS_ENDPOINT_URL (Glue 4.0 ships 1.27) and
@@ -2386,3 +2478,104 @@ def test_glue_spark_container_env_points_sdk_at_ministack(tmp_path, monkeypatch)
assert "'/tmp/job.py'" in archived["_ministack_boot.py"]
assert "create_client" in archived["_ministack_boot.py"]
assert run["JobRunState"] == "SUCCEEDED"
+
+
+def test_glue_translate_loopback_conf_rewrites_only_gateway_loopbacks():
+ from ministack.services.glue import _translate_loopback_conf
+
+ host, port = "172.21.0.3", "4566"
+ # Loopback hosts on the gateway port are rewritten to the resolved address.
+ assert _translate_loopback_conf(
+ "spark.sql.catalog.ms.uri=http://host.docker.internal:4566/iceberg",
+ host, port,
+ ) == "spark.sql.catalog.ms.uri=http://172.21.0.3:4566/iceberg"
+ assert _translate_loopback_conf(
+ "spark.hadoop.fs.s3a.endpoint=http://localhost:4566",
+ host, port,
+ ) == "spark.hadoop.fs.s3a.endpoint=http://172.21.0.3:4566"
+ assert _translate_loopback_conf(
+ "a=http://127.0.0.1:4566/x", host, port,
+ ) == "a=http://172.21.0.3:4566/x"
+
+ # An external catalog, a different port, and a host merely containing a
+ # loopback name all pass through untouched.
+ for untouched in (
+ "spark.sql.catalog.ext.uri=https://polaris.example.com:8181/api",
+ "a=http://localhost:8080/other",
+ "a=http://localhost:45660/x",
+ "a=http://notlocalhost:4566/x",
+ "a=http://my.localhost.example:4566/x",
+ ):
+ assert _translate_loopback_conf(untouched, host, port) == untouched
+
+
+def test_iceberg_rest_apply_updates_resolves_minus_one_sentinels():
+ """Spark 3.5 commits `set-current-schema` / `set-default-spec` with -1,
+ meaning "the one added earlier in this commit". Taking -1 literally leaves
+ the table pointing at a schema id that does not exist."""
+ from ministack.services.s3tables import _apply_iceberg_updates
+
+ metadata = {"schemas": [{"schema-id": 0}], "partition-specs": [{"spec-id": 0}],
+ "sort-orders": [{"order-id": 0}]}
+ _apply_iceberg_updates(metadata, [
+ {"action": "add-schema", "schema": {"schema-id": 3, "fields": [{"id": 7}]}},
+ {"action": "set-current-schema", "schema-id": -1},
+ {"action": "add-spec", "spec": {"spec-id": 2}},
+ {"action": "set-default-spec", "spec-id": -1},
+ {"action": "add-sort-order", "sort-order": {"order-id": 4}},
+ {"action": "set-default-sort-order", "sort-order-id": -1},
+ ])
+ assert metadata["current-schema-id"] == 3
+ assert metadata["default-spec-id"] == 2
+ assert metadata["default-sort-order-id"] == 4
+ assert metadata["last-column-id"] == 7
+ # Explicit ids still pass through untouched.
+ _apply_iceberg_updates(metadata, [{"action": "set-current-schema", "schema-id": 0}])
+ assert metadata["current-schema-id"] == 0
+
+
+def test_iceberg_rest_create_namespace_and_transaction_commit():
+ """POST namespaces creates a Glue database; transactions/commit (DuckDB's
+ atomic multi-table commit) applies each table change and 404s on a
+ missing table instead of reporting success."""
+ status, doc = _call_body(
+ "POST", f"/iceberg/v1/{_GLUE_ICEBERG_PREFIX}/namespaces", {"namespace": ["txlake"]})
+ assert status == 200
+ assert doc["namespace"] == ["txlake"]
+ assert "txlake" in _svc("glue")._databases
+
+ status, _ = _call_body(
+ "POST", f"/iceberg/v1/{_GLUE_ICEBERG_PREFIX}/namespaces/txlake/tables",
+ {"name": "events", "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}/transactions/commit",
+ {"table-changes": [{"identifier": {"namespace": ["txlake"], "name": "events"},
+ "updates": [{"action": "add-snapshot", "snapshot": {
+ "snapshot-id": 7, "sequence-number": 1, "timestamp-ms": 1,
+ "manifest-list": "s3://x/m.avro", "summary": {"operation": "append"}}}]}]})
+ assert status == 200
+ _, doc = _call_body("GET", f"/iceberg/v1/{_GLUE_ICEBERG_PREFIX}/namespaces/txlake/tables/events")
+ assert doc["metadata"]["current-snapshot-id"] == 7
+ # The commit advanced the metadata pointer and wrote the new version to S3.
+ assert doc["metadata-location"].endswith("/v1.metadata.json")
+
+ status, doc = _call_body(
+ "POST", f"/iceberg/v1/{_GLUE_ICEBERG_PREFIX}/transactions/commit",
+ {"table-changes": [{"identifier": {"namespace": ["txlake"], "name": "ghost"},
+ "updates": []}]})
+ assert status == 404
+ assert doc["error"]["type"] == "NoSuchTableException"
+
+
+def test_glue_extract_python_error_finds_last_traceback():
+ from ministack.services.glue import _extract_python_error
+
+ logs = ("INFO spark stuff\nTraceback (most recent call last):\n File x\nOldError: a\n"
+ "INFO more\nTraceback (most recent call last):\n File y\nValueError: real\n")
+ out = _extract_python_error(logs)
+ assert out.startswith("Traceback")
+ assert "ValueError: real" in out and "OldError" not in out
+ assert _extract_python_error("just INFO lines") == ""
diff --git a/tests/test_s3tables.py b/tests/test_s3tables.py
index 40abc837..49dbb102 100644
--- a/tests/test_s3tables.py
+++ b/tests/test_s3tables.py
@@ -21,7 +21,6 @@ import pytest
from botocore.config import Config
from botocore.exceptions import ClientError
-
_ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
@@ -1022,3 +1021,85 @@ def test_s3tables_deletes_answer_204(s3tables):
assert r["ResponseMetadata"]["HTTPStatusCode"] == 204
r = s3tables.delete_table_bucket(tableBucketARN=arn)
assert r["ResponseMetadata"]["HTTPStatusCode"] == 204
+
+
+def test_s3tables_iceberg_load_table_serves_the_numerically_latest_metadata(s3tables, s3):
+ """LoadTable's scan for the newest metadata.json must order vN numerically:
+ lexically v10 sorts before v2, so from the 10th commit on a lexical scan
+ serves v9 forever while the table keeps advancing."""
+ bucket_name = f"tb-vsort-{_uuid_mod.uuid4().hex[:6]}"
+ bucket_arn = s3tables.create_table_bucket(name=bucket_name)["arn"]
+ ns, table = "vsortns", "vsorttbl"
+ try:
+ s3tables.create_namespace(tableBucketARN=bucket_arn, namespace=[ns])
+ s3tables.create_table(tableBucketARN=bucket_arn, namespace=ns, name=table, format="ICEBERG")
+
+ base = _iceberg_json(f"/iceberg/v1/namespaces/{ns}/tables/{table}")["metadata"]
+ for v in range(1, 12):
+ doc = dict(base, **{"last-sequence-number": v})
+ s3.put_object(
+ Bucket=bucket_name,
+ Key=f"{ns}/{table}/metadata/v{v}.metadata.json",
+ Body=json.dumps(doc).encode(),
+ )
+
+ resp = _iceberg_json(f"/iceberg/v1/namespaces/{ns}/tables/{table}")
+ assert resp["metadata-location"].endswith("/v11.metadata.json"), resp["metadata-location"]
+ assert resp["metadata"]["last-sequence-number"] == 11
+ 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_prefixed_lookup_scopes_to_the_bucket(s3tables):
+ """Two table buckets holding a same-named table must resolve per the
+ ``{account}:s3tablescatalog/{bucket}`` prefix — without the filter the
+ first match wins and the wrong table's schema comes back."""
+ ns, table = "scopens", "orders"
+ arns = {}
+ try:
+ for b in ("tb-scope-a", "tb-scope-b"):
+ arns[b] = s3tables.create_table_bucket(name=b)["arn"]
+ s3tables.create_namespace(tableBucketARN=arns[b], namespace=[ns])
+ s3tables.create_table(
+ tableBucketARN=arns[b], namespace=ns, name=table, format="ICEBERG",
+ metadata={"iceberg": {"schema": {"fields": [
+ {"name": f"col_{b[-1]}", "type": "string"}]}}},
+ )
+ for b in ("tb-scope-a", "tb-scope-b"):
+ resp = _iceberg_json(
+ f"/iceberg/v1/000000000000:s3tablescatalog/{b}/namespaces/{ns}/tables/{table}")
+ fields = resp["metadata"]["schemas"][0]["fields"]
+ assert [f["name"] for f in fields] == [f"col_{b[-1]}"], (b, fields)
+ finally:
+ for b, arn in arns.items():
+ try:
+ s3tables.delete_table(tableBucketARN=arn, namespace=ns, name=table)
+ s3tables.delete_namespace(tableBucketARN=arn, namespace=ns)
+ except Exception:
+ pass
+ try:
+ s3tables.delete_table_bucket(tableBucketARN=arn)
+ except Exception:
+ pass
+
+
+def test_iceberg_unknown_path_answers_404_envelope():
+ """A path neither catalog serves must be an Iceberg error envelope, not an
+ empty 200 a client would read as success."""
+ import urllib.error
+
+ try:
+ _iceberg_json("/iceberg/v9/definitely/not/a/route")
+ raise AssertionError("expected HTTP error")
+ except urllib.error.HTTPError as e:
+ assert e.code == 404
+ doc = json.loads(e.read())
+ assert doc["error"]["type"] == "NotFoundException"