Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(athena): query s3tables (#2109)
Nahuel Nucera73fe737edce6
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex c02281c3..fe54b6c0 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -75,7 +75,7 @@ jobs:services:redis:- image: redis:7-alpine+ image: public.ecr.aws/docker/library/redis:7-alpineports:- 6379:6379options: >-@@ -162,7 +162,7 @@ jobs:MINISTACK_RDS_PG_CLUSTER_REPLICATION: "1"services:redis:- image: redis:7-alpine+ image: public.ecr.aws/docker/library/redis:7-alpineports:- 6379:6379options: >-diff --git a/ministack/app.py b/ministack/app.pyindex 406927d3..57ddd474 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -2987,6 +2987,9 @@ async def _handle_lifespan(scope, receive, send):))logger.info("Worker thread pool: %d threads", _max_workers)+ from ministack.core.responses import install_docker_hub_fallback++ install_docker_hub_fallback()_run_init_scripts()# Reap any container that survived a hard kill of the previous# process. Persistence strips container ids from snapshots, so anydiff --git a/ministack/core/responses.py b/ministack/core/responses.pyindex bddbe74e..59303d42 100644--- a/ministack/core/responses.py+++ b/ministack/core/responses.py@@ -11,6 +11,7 @@ import contextvarsimport functoolsimport hashlibimport json+import loggingimport osimport reimport uuid@@ -695,6 +696,64 @@ def apply_image_prefix(image: str) -> str:return f"{prefix}/{image}"+def _docker_hub_repository(repository: str) -> str | None:+ """The Docker Hub path of ``repository`` (``library/x`` for official images),+ or None when it names another registry."""+ first, _, rest = repository.partition("/")+ if rest and first in ("docker.io", "index.docker.io", "registry-1.docker.io"):+ repository = rest+ elif rest and ("." in first or ":" in first or first == "localhost"):+ return None+ return repository if "/" in repository else f"library/{repository}"+++def docker_hub_mirrors(repository: str) -> list[str]:+ """Public mirrors of a Docker Hub repository, tried when Docker Hub fails."""+ hub = _docker_hub_repository(repository)+ if hub is None:+ return []+ ecr = f"docker/{hub}" if hub.startswith("library/") else hub+ return [f"public.ecr.aws/{ecr}", f"mirror.gcr.io/{hub}"]+++def install_docker_hub_fallback() -> None:+ """Retry a failed Docker Hub pull from ECR Public, then mirror.gcr.io, and tag+ the result with the name that was asked for. Covers every Docker client,+ including the pull ``containers.run`` makes for a missing image."""+ try:+ from docker.errors import APIError+ from docker.models.images import ImageCollection+ from docker.utils import parse_repository_tag+ except ImportError:+ return+ original = ImageCollection.pull+ if getattr(original, "_ministack_fallback", False):+ return++ def pull(self, repository, tag=None, all_tags=False, **kwargs):+ try:+ return original(self, repository, tag=tag, all_tags=all_tags, **kwargs)+ except APIError as hub_error:+ repo, parsed_tag = parse_repository_tag(repository)+ tag = tag or parsed_tag or "latest"+ if all_tags or ":" in tag: # digests cannot be re-tagged+ raise+ for mirror in docker_hub_mirrors(repo):+ try:+ image = original(self, mirror, tag=tag, **kwargs)+ except APIError:+ continue+ image.tag(repo, tag)+ logging.getLogger("ministack").warning(+ "Docker Hub pull of %s:%s failed (%s); pulled %s:%s instead",+ repo, tag, hub_error.explanation or hub_error, mirror, tag)+ return image+ raise++ pull._ministack_fallback = True+ ImageCollection.pull = pull++def sha256_hash(data: bytes) -> str:return hashlib.sha256(data).hexdigest()diff --git a/ministack/services/athena.py b/ministack/services/athena.pyindex 1718440c..170675fc 100644--- a/ministack/services/athena.py+++ b/ministack/services/athena.py@@ -17,12 +17,12 @@ Supports: StartQueryExecution, GetQueryExecution, GetQueryResults,import asyncioimport copyimport csv-import globimport ioimport jsonimport loggingimport osimport re+import shutilimport timeimport xml.etree.ElementTree as ETfrom dataclasses import dataclass, field@@ -74,8 +74,8 @@ def _ensure_default_workgroup():"State": "ENABLED","Description": "Primary workgroup","CreationTime": int(time.time()),+ # Like AWS's primary workgroup, no query result location until one is set."Configuration": {- "ResultConfiguration": {"OutputLocation": "s3://athena-results/"},# AUTO is the default selection; the effective version is what Athena resolved it to.# https://docs.aws.amazon.com/athena/latest/APIReference/API_EngineVersion.html"EngineVersion": {@@ -478,6 +478,7 @@ class _TableReference:start: intend: intaliased: bool+ catalog: str | None = None# After a table reference, these keywords start the next clause; anything else is an alias.@@ -501,13 +502,13 @@ def _table_references(query):name = cursor.dotted_name(3)if name is None:continue- _, database, table = name # the catalog qualifier is dropped: Glue is the only catalog here+ catalog, database, table = nameif database is None and table in ctes:continueend = cursor.tokens[cursor.i - 1][3]next_kind, next_text = cursor.peek()[:2]aliased = next_kind == "qname" or (next_kind == "name" and next_text not in _CLAUSE_KEYWORDS)- references.append(_TableReference(database, table, start, end, aliased))+ references.append(_TableReference(database, table, start, end, aliased, catalog))return references@@ -822,7 +823,13 @@ def _start_query_execution(data):"OutputLocation") or _workgroups.get(workgroup, {}).get("Configuration", {}).get("ResultConfiguration", {}- ).get("OutputLocation", "s3://athena-results/")+ ).get("OutputLocation")+ if not output_location:+ return error_response_json(+ "InvalidRequestException",+ "No output location provided. An output location is required either through the "+ "Workgroup result configuration setting or as an API input.", 400,+ )db = data.get("QueryExecutionContext", {}).get("Database", "default")catalog = data.get("QueryExecutionContext", {}).get("Catalog", "AwsDataCatalog")# Athena rejects any malformed statement here; with no Trino parser, only this DDL rule is@@ -866,12 +873,12 @@ def _start_query_execution(data):}_executions[query_id] = execution- asyncio.create_task(_execute_query(query_id, query, db, ddl))+ asyncio.create_task(_execute_query(query_id, query, db, ddl, catalog))return json_response({"QueryExecutionId": query_id})-async def _execute_query(query_id, query, database, ddl):+async def _execute_query(query_id, query, database, ddl, catalog=None):execution = _executions.get(query_id)if not execution:return@@ -885,7 +892,7 @@ async def _execute_query(query_id, query, database, ddl):if ddl is not None:results = _run_ddl(ddl, database)elif engine == "duckdb":- results = await _run_duckdb(query, database)+ results = await _run_duckdb(query, database, catalog)else:results = _mock_query_results(query)@@ -913,7 +920,7 @@ async def _execute_query(query_id, query, database, ddl):execution["Status"]["CompletionDateTime"] = int(time.time())-async def _run_duckdb(query, database):+async def _run_duckdb(query, database, catalog=None):"""Run a DuckDB query off the event loop.DuckDB's ``conn.execute()`` is a blocking C-extension call — running it@@ -924,11 +931,15 @@ async def _run_duckdb(query, database):"""import duckdb- rewritten = await _rewrite_data_paths(query, database)+ rewritten, s3_table_buckets, workdirs = await _rewrite_data_paths(query, database, catalog)def _execute_blocking():conn = duckdb.connect(":memory:")try:+ if s3_table_buckets:+ _attach_s3_table_buckets(conn, s3_table_buckets)+ if "read_avro(" in rewritten:+ conn.execute("INSTALL avro; LOAD avro;")result = conn.execute(rewritten)columns = []column_types = []@@ -950,18 +961,32 @@ async def _run_duckdb(query, database):}finally:conn.close()+ for workdir in workdirs:+ shutil.rmtree(workdir, ignore_errors=True)return await asyncio.to_thread(_execute_blocking)-async def _rewrite_data_paths(query, database):- """Replace each Glue table reference with a DuckDB relation over its local S3 data."""+async def _rewrite_data_paths(query, database, catalog=None):+ """Replace each Glue table reference with a DuckDB relation over its local S3 data,+ and each ``s3tablescatalog/<bucket>`` reference with that bucket's attached Iceberg+ catalog. Returns the query and the table bucket ARNs to attach, by alias."""from ministack.services import glue as glue_svcaccount_id = get_account_id()edits = []+ s3_table_buckets = {}+ workdirs = []for ref in _table_references(query):db_name = ref.database or database or "default"+ ref_catalog = ref.catalog or catalog or ""+ if ref_catalog.lower().startswith(_S3_TABLES_CATALOG_PREFIX):+ bucket = ref_catalog[len(_S3_TABLES_CATALOG_PREFIX):]+ bucket_arn = f"arn:aws:s3tables:{get_region()}:{account_id}:bucket/{bucket}"+ alias = s3_table_buckets.setdefault(bucket_arn, f"__s3t{len(s3_table_buckets)}")+ relation = f'{alias}."{db_name.replace(chr(34), chr(34) * 2)}"."{ref.table.replace(chr(34), chr(34) * 2)}"'+ edits.append((ref.start, ref.end, relation + ("" if ref.aliased else f' AS "{ref.table}"')))+ continue# Read directly from glue's internal store rather than going through# the HTTP handler. The store is account-scoped via AccountScopedDict@@ -973,14 +998,8 @@ async def _rewrite_data_paths(query, database):s3_location = (table_data.get("StorageDescriptor") or {}).get("Location")if not s3_location:continue-- p = urlparse(s3_location)- stripped = f"{p.netloc}{p.path}".rstrip("/")- local_dir = f"{ATHENA_DATA_DIR}/{account_id}/{stripped}"- if next(glob.iglob(f"{local_dir}/**/*", recursive=True), None):- relation = _file_relation(f"{local_dir}/**/*.{_data_format(table_data)}", table_data)- else:- relation = _empty_relation(table_data)+ files = _materialize_table_files(s3_location, workdirs)+ relation = _table_relation(table_data, files) if files else _empty_relation(table_data)alias = "" if ref.aliased else f' AS "{ref.table}"'edits.append((ref.start, ref.end, relation + alias))if not ref.aliased:@@ -989,31 +1008,159 @@ async def _rewrite_data_paths(query, database):edits = sorted(set(edits)) # a table named twice yields its column-prefix edits twicefor span_start, span_end, replacement in reversed(edits):query = query[:span_start] + replacement + query[span_end:]- return _rewrite_s3_paths(query)+ return _rewrite_s3_paths(query), {alias: arn for arn, alias in s3_table_buckets.items()}, workdirs-_DUCKDB_TYPE_BY_ATHENA = {- "boolean": "BOOLEAN", "tinyint": "TINYINT", "smallint": "SMALLINT", "int": "INTEGER", "integer": "INTEGER",- "bigint": "BIGINT", "float": "FLOAT", "real": "FLOAT", "double": "DOUBLE", "date": "DATE",- "timestamp": "TIMESTAMP", "binary": "BLOB", "varbinary": "BLOB",-}+def _hidden(relative_key):+ # Trino's Hive reader skips files and directories whose name starts with "_" or ".".+ return any(part.startswith(("_", ".")) for part in relative_key.split("/"))+++def _materialize_table_files(location, workdirs):+ """Copy every object under the table LOCATION out of the S3 store into a+ per-query directory, keeping relative paths for Hive partition folders.+ Athena reads all data under the location, whatever the object names."""+ import tempfile++ from ministack.services import s3 as s3_svc++ parsed = urlparse(location)+ bucket_name, prefix = parsed.netloc, parsed.path.lstrip("/")+ if prefix and not prefix.endswith("/"):+ prefix += "/"+ bucket = s3_svc._buckets.get(bucket_name)+ if bucket is None:+ return []+ keys = sorted(k for k in list(bucket["objects"].keys())+ if k.startswith(prefix) and not k.endswith("/") and not _hidden(k[len(prefix):]))+ if not keys:+ return []+ root = tempfile.mkdtemp(prefix="ministack-athena-")+ workdirs.append(root)+ files = []+ for key in keys:+ data = s3_svc._get_object_data(bucket_name, key)+ if data is None:+ continue+ path = os.path.join(root, key[len(prefix):])+ os.makedirs(os.path.dirname(path), exist_ok=True)+ with open(path, "wb") as fh:+ fh.write(data)+ files.append(path)+ return files++def _datum_text(value):+ if isinstance(value, bool):+ return "true" if value else "false"+ return str(value)-# Readers that accept ``hive_types``, so partition columns get their Glue types.-_HIVE_TYPED_READERS = {"parquet": "read_parquet", "csv": "read_csv", "json": "read_json"}+def _sql_list(paths):+ return "[" + ", ".join("'" + p.replace("'", "''") + "'" for p in paths) + "]"-def _file_relation(pattern, table_data):- """The table's files; partition keys are typed from Glue instead of inferred from the path."""- path = "'" + pattern.replace("'", "''") + "'"- reader = _HIVE_TYPED_READERS.get(_data_format(table_data))- partition_keys = table_data.get("PartitionKeys") or []- if not reader or not partition_keys:- return path # DuckDB reads the files, or reports why not- hive_types = ", ".join(- "'{}': {}".format(str(key.get("Name", "")).replace("'", "''"), _duckdb_type(key)) for key in partition_keys++def _table_relation(table_data, files):+ """A DuckDB relation over the table's files, columns as the table defines them."""+ fmt = _data_format(table_data)+ storage = table_data.get("StorageDescriptor") or {}+ columns = storage.get("Columns") or []+ partitions = _path_partition_keys(table_data, files)+ hive = _hive_options(partitions)+ if fmt == "parquet":+ return f"read_parquet({_sql_list(files)}, union_by_name = true, {hive})"+ if fmt == "json":+ return f"read_json_auto({_sql_list(files)}, union_by_name = true, {hive})"+ if fmt == "avro":+ return f"read_avro({_sql_list(files)})"+ if fmt != "csv" or not columns:+ return f"read_csv_auto({_sql_list(files)}, {hive})"+ serde = storage.get("SerdeInfo") or {}+ params = serde.get("Parameters") or {}+ library = serde.get("SerializationLibrary") or ""+ if "OpenCSVSerde" in library:+ delim, quote = params.get("separatorChar", ","), params.get("quoteChar", '"')+ elif "LazySimpleSerDe" in library:+ # Hive's LazySimpleSerDe splits on Ctrl-A unless field.delim is set, and does not unquote.+ delim, quote = params.get("field.delim", params.get("serialization.format", "\x01")), ""+ delim = "\x01" if delim == "1" else delim+ else:+ delim, quote = params.get("field.delim", ","), '"'+ try:+ skip = int((table_data.get("Parameters") or {}).get("skip.header.line.count", 0))+ except (TypeError, ValueError):+ skip = 0+ names = [str(c.get("Name", "")) for c in columns]+ raw = ", ".join(f"'c{i}': 'VARCHAR'" for i in range(len(names)))+ def lit(value):+ return "'" + value.replace("'", "''") + "'"+ reader = (f"read_csv({_sql_list(files)}, auto_detect = false, header = false, skip = {skip}, delim = {lit(delim)}, "+ f"quote = {lit(quote)}, escape = {lit(quote)}, columns = {{{raw}}}, null_padding = true, "+ f"strict_mode = false, {hive})")+ projected = []+ for i, column in enumerate(columns):+ base = str(column.get("Type", "string")).lower().split("(")[0].strip()+ duck_type = "DECIMAL(38,9)" if base == "decimal" else _DUCKDB_TYPE_BY_ATHENA.get(base, "VARCHAR")+ name = names[i].replace('"', '""')+ projected.append(f'TRY_CAST("c{i}" AS {duck_type}) AS "{name}"')+ in_paths = {str(key.get("Name", "")) for key in partitions}+ for key in table_data.get("PartitionKeys") or []:+ name = str(key.get("Name", "")).replace('"', '""')+ value = f'"{name}"' if key.get("Name") in in_paths else f"CAST(NULL AS {_duckdb_type(key)})"+ projected.append(f'{value} AS "{name}"')+ return f"(SELECT {', '.join(projected)} FROM {reader})"+++def _path_partition_keys(table_data, files):+ """The Glue partition keys every file's path carries as a ``key=value`` folder."""+ def folders(path):+ return {part.split("=", 1)[0] for part in path.split("/")[:-1] if "=" in part}+ present = set.intersection(*(folders(f) for f in files)) if files else set()+ return [key for key in table_data.get("PartitionKeys") or [] if key.get("Name") in present]+++def _hive_options(partitions):+ """Hive partitioning typed from Glue; DuckDB refuses a type for a key no path carries."""+ if not partitions:+ return "hive_partitioning = false"+ types = ", ".join("'{}': {}".format(str(key["Name"]).replace("'", "''"), _duckdb_type(key)) for key in partitions)+ return f"hive_partitioning = true, hive_types = {{{types}}}"+++# Athena names each S3 table bucket's catalog "s3tablescatalog/<bucket>".+_S3_TABLES_CATALOG_PREFIX = "s3tablescatalog/"+++def _attach_s3_table_buckets(conn, buckets):+ """Attach each table bucket through MiniStack's own Iceberg REST catalog, as+ Firehose's Iceberg delivery does; runs on the query's worker thread."""+ port = os.environ.get("GATEWAY_PORT", "4566")+ conn.execute("INSTALL iceberg; LOAD iceberg; INSTALL httpfs; LOAD httpfs;")+ from ministack.services.s3tables import _vended_access_key++ # The access key names the caller's account, so the loopback calls stay in its scope.+ key = _vended_access_key()+ conn.execute(+ f"CREATE SECRET __ms_athena (TYPE S3, KEY_ID '{key}', SECRET 'test', "+ f"ENDPOINT 'localhost:{port}', URL_STYLE 'path', USE_SSL false, REGION '{get_region()}')"+ )+ credential = f"AWS4-HMAC-SHA256 Credential={key}/19700101/{get_region()}/s3tables/aws4_request"+ conn.execute(+ f"CREATE SECRET __ms_athena_catalog (TYPE HTTP, SCOPE 'http://localhost:{port}/iceberg', "+ f"EXTRA_HTTP_HEADERS MAP {{'Authorization': '{credential}'}})")- return f"{reader}({path}, hive_partitioning = true, hive_types = {{{hive_types}}})"+ for alias, bucket_arn in buckets.items():+ conn.execute(+ f"ATTACH '{bucket_arn}' AS {alias} (TYPE ICEBERG, READ_ONLY, "+ f"ENDPOINT 'http://localhost:{port}/iceberg', AUTHORIZATION_TYPE 'none')"+ )+++_DUCKDB_TYPE_BY_ATHENA = {+ "boolean": "BOOLEAN", "tinyint": "TINYINT", "smallint": "SMALLINT", "int": "INTEGER", "integer": "INTEGER",+ "bigint": "BIGINT", "float": "FLOAT", "real": "FLOAT", "double": "DOUBLE", "date": "DATE",+ "timestamp": "TIMESTAMP", "binary": "BLOB", "varbinary": "BLOB",+}def _duckdb_type(column):@@ -1268,7 +1415,8 @@ def _get_query_results(data):result_rows.append({"Data": [{"VarCharValue": col} for col in columns]})for row in page_rows:result_rows.append(- {"Data": [{"VarCharValue": str(v) if v is not None else ""} for v in row]}+ # A NULL is a Datum with no VarCharValue.+ {"Data": [{} if v is None else {"VarCharValue": _datum_text(v)} for v in row]})column_info = []diff --git a/ministack/services/glue.py b/ministack/services/glue.pyindex ffa48f89..33c3cfb7 100644--- a/ministack/services/glue.py+++ b/ministack/services/glue.py@@ -429,15 +429,17 @@ def _iceberg_s3_overrides():MiniStack must return them or the client tries real S3 for the datafiles referenced by the catalog and fails.- Credentials are the fixed `test`/`test` pair (same as the s3tables- Iceberg surface) — MiniStack's S3 doesn't verify signatures, and- echoing ambient AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY into an HTTP- response would leak real credentials from the host environment."""+ The access key names the caller's account (same as the s3tables Iceberg+ surface) — MiniStack's S3 doesn't verify signatures, and echoing ambient+ AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY into an HTTP response would leak+ real credentials from the host environment."""+ from ministack.services.s3tables import _vended_access_key+host = os.environ.get("MINISTACK_HOST", "localhost")port = os.environ.get("GATEWAY_PORT", "4566")return {"s3.endpoint": f"http://{host}:{port}",- "s3.access-key-id": "test",+ "s3.access-key-id": _vended_access_key(),"s3.secret-access-key": "test","s3.path-style-access": "true","s3.region": os.environ.get("MINISTACK_REGION", "us-east-1"),diff --git a/ministack/services/s3tables.py b/ministack/services/s3tables.pyindex b3a65efe..e626ab60 100644--- a/ministack/services/s3tables.py+++ b/ministack/services/s3tables.py@@ -252,7 +252,12 @@ def _create_table_bucket(data):"name": name,"ownerAccountId": get_account_id(),"createdAt": now_iso(),+ "tableBucketId": new_uuid(),+ "type": "customer","tableCount": 0,+ "_encryption": data.get("encryptionConfiguration"),+ "_storageClass": data.get("storageClassConfiguration"),+ "_tags": dict(data.get("tags") or {}),}# Provision the backing S3 bucket so data-plane writes (Parquet, manifests)# have somewhere to land — mirrors real AWS where S3 Tables manages its own@@ -264,15 +269,22 @@ def _create_table_bucket(data):return json_response({"arn": arn})+_BUCKET_FIELDS = ("arn", "name", "ownerAccountId", "createdAt", "tableBucketId", "type")+++def _bucket_view(bucket):+ return {k: bucket[k] for k in _BUCKET_FIELDS if k in bucket}++def _list_table_buckets():- return json_response({"tableBuckets": list(_table_buckets.values())})+ return json_response({"tableBuckets": [_bucket_view(b) for b in _table_buckets.values()]})def _get_table_bucket(arn):bucket = _find_bucket_by_arn(arn)if not bucket:return _bucket_not_found(arn)- return json_response(bucket)+ return json_response(_bucket_view(bucket))def _delete_table_bucket(arn):@@ -406,17 +418,26 @@ def _create_table(bucket_arn, namespace, data):metadata_location = f"s3://{bucket_name}/{namespace}/{table_name}/metadata/v0.metadata.json"arn = _table_arn(bucket_arn, namespace, table_name)+ bucket_record = _find_bucket_by_arn(bucket_arn) or {}_tables[key] = {"name": table_name,+ "type": "customer","tableARN": arn,"namespace": [namespace],"tableBucketARN": bucket_arn,+ "tableBucketId": bucket_record.get("tableBucketId"),+ "versionToken": new_uuid()[:8],"format": fmt,"createdAt": now_iso(),+ "createdBy": get_account_id(),"modifiedAt": now_iso(),+ "modifiedBy": get_account_id(),"ownerAccountId": get_account_id(),"metadataLocation": metadata_location,"warehouseLocation": location,+ "_encryption": data.get("encryptionConfiguration"),+ "_storageClass": data.get("storageClassConfiguration"),+ "_tags": dict(data.get("tags") or {}),"_iceberg_metadata": iceberg_metadata,"_metadata_version": 0,"_schema_fields": schema_fields,@@ -428,7 +449,7 @@ def _create_table(bucket_arn, namespace, data):breaklogger.info("S3Tables: created table %s/%s", namespace, table_name)- return json_response({"tableARN": arn, "versionToken": new_uuid()[:8]})+ return json_response({"tableARN": arn, "versionToken": _tables[key]["versionToken"]})def _list_tables(bucket_arn, namespace=None):@@ -446,15 +467,24 @@ def _list_tables(bucket_arn, namespace=None):result.append({"name": table["name"],+ "type": table.get("type", "customer"),"tableARN": table["tableARN"],"namespace": table["namespace"],- "format": table["format"],"createdAt": table["createdAt"],+ "modifiedAt": table.get("modifiedAt", table["createdAt"]),+ "tableBucketId": table.get("tableBucketId"),})return json_response({"tables": result})+_TABLE_FIELDS = (+ "name", "type", "tableARN", "namespace", "namespaceId", "versionToken", "metadataLocation",+ "warehouseLocation", "createdAt", "createdBy", "managedByService", "modifiedAt", "modifiedBy",+ "ownerAccountId", "format", "tableBucketId",+)++def _get_table(bucket_arn, namespace, table_name):raw_bucket_arn = bucket_arnbucket_arn = _existing_bucket_arn(bucket_arn)@@ -464,7 +494,7 @@ def _get_table(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({k: v for k, v in table.items() if not k.startswith("_")})+ return json_response({k: table[k] for k in _TABLE_FIELDS if table.get(k) is not None})def _delete_table(bucket_arn, namespace, table_name):@@ -523,7 +553,7 @@ def _iceberg_config(query_params=None, headers=None):defaults = {"client.region": get_region(),"s3.endpoint": s3_endpoint,- "s3.access-key-id": "test",+ "s3.access-key-id": _vended_access_key(),"s3.secret-access-key": "test","s3.path-style-access": "true",}@@ -564,6 +594,13 @@ def _resolve_container_ip():return None+def _vended_access_key():+ """The caller's account as the vended access key, so a client's data reads and+ writes stay in that account; the default account keeps ``test``."""+ account = get_account_id()+ return "test" if account == os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000") else account++def _reachable_s3_endpoint():"""S3 endpoint URL that both host-side and container-side callers can reach.@@ -788,7 +825,7 @@ def _iceberg_load_table(namespace, table_name, allow_cross_region, bucket_filter"metadata": metadata,"config": {"s3.endpoint": _reachable_s3_endpoint(),- "s3.access-key-id": "test",+ "s3.access-key-id": _vended_access_key(),"s3.secret-access-key": "test","s3.path-style-access": "true","s3.region": get_region(),@@ -1137,9 +1174,9 @@ async def handle_request(method, path, headers, body, query_params):arn = "/".join(parts[1:])if not arn.startswith("arn:"):arn = f"arn:aws:s3tables:{get_region()}:{get_account_id()}:bucket/{arn}"- # Check for sub-resource paths- if parts[-1] in ("encryption", "maintenance", "metrics", "policy", "storage-class"):- return json_response({}) # stub+ bucket_arn, sub = _split_arn_and_suffix("/".join(parts[1:]), "bucket")+ if sub:+ return _bucket_subresource(method, bucket_arn, sub.split("/"), data)if method == "GET":return _get_table_bucket(arn)if method == "DELETE":@@ -1198,6 +1235,12 @@ async def handle_request(method, path, headers, body, query_params):return _get_table_metadata_location(arn, suffix_parts[0], suffix_parts[1])if method == "PUT":return _update_table_metadata_location(arn, suffix_parts[0], suffix_parts[1], data)+ elif len(suffix_parts) >= 3:+ return _table_subresource(method, arn, suffix_parts[0], suffix_parts[1], suffix_parts[2:], data)++ # POST|GET|DELETE /tag/{resourceArn} -> TagResource|ListTagsForResource|UntagResource+ if len(parts) >= 2 and parts[0] == "tag":+ return _tags_request(method, "/".join(parts[1:]), data, query_params)# GET /get-table?tableBucketARN=&namespace=&name= -> GetTableif parts == ["get-table"] and method == "GET":@@ -1215,6 +1258,201 @@ async def handle_request(method, path, headers, body, query_params):return error_response_json("UnknownOperationException", f"Unknown S3Tables operation: {method} {path}", 400)+# ── Bucket and table sub-resources ──────────────────────────+# Defaults are the documented ones: SSE-S3, STANDARD storage, unreferenced file+# removal 3/10 days, compaction at 512 MB with the auto strategy, and snapshot+# management keeping 1 snapshot for up to 120 hours, all enabled.++_DEFAULT_ENCRYPTION = {"sseAlgorithm": "AES256"}+_DEFAULT_STORAGE_CLASS = {"storageClass": "STANDARD"}+_BUCKET_MAINTENANCE_DEFAULTS = {+ "icebergUnreferencedFileRemoval": {+ "status": "enabled",+ "settings": {"icebergUnreferencedFileRemoval": {"unreferencedDays": 3, "nonCurrentDays": 10}},+ },+}+_TABLE_MAINTENANCE_DEFAULTS = {+ "icebergCompaction": {+ "status": "enabled",+ "settings": {"icebergCompaction": {"targetFileSizeMB": 512, "strategy": "auto"}},+ },+ "icebergSnapshotManagement": {+ "status": "enabled",+ "settings": {"icebergSnapshotManagement": {"minSnapshotsToKeep": 1, "maxSnapshotAgeHours": 120}},+ },+}+++def _no_content():+ return 204, {}, b""+++def _maintenance_view(defaults, stored):+ view = copy.deepcopy(defaults)+ for kind, value in (stored or {}).items():+ merged = copy.deepcopy(view.get(kind, {}))+ if "status" in value:+ merged["status"] = value["status"]+ for setting, fields in (value.get("settings") or {}).items():+ merged.setdefault("settings", {}).setdefault(setting, {}).update(fields or {})+ view[kind] = merged+ return view+++def _bucket_subresource(method, bucket_arn, sub, data):+ bucket = _find_bucket_by_arn(bucket_arn)+ if not bucket:+ return _bucket_not_found(bucket_arn)+ kind = sub[0]+ if kind == "encryption":+ if method == "GET":+ return json_response({"encryptionConfiguration": bucket.get("_encryption") or _DEFAULT_ENCRYPTION})+ if method == "PUT":+ bucket["_encryption"] = data.get("encryptionConfiguration")+ return json_response({})+ if method == "DELETE":+ bucket["_encryption"] = None+ return _no_content()+ if kind == "maintenance":+ if method == "GET":+ return json_response({+ "tableBucketARN": bucket["arn"],+ "configuration": _maintenance_view(_BUCKET_MAINTENANCE_DEFAULTS, bucket.get("_maintenance")),+ })+ if method == "PUT" and len(sub) == 2:+ bucket.setdefault("_maintenance", {})[sub[1]] = data.get("value") or {}+ return _no_content()+ if kind == "policy":+ if method == "GET":+ if not bucket.get("_policy"):+ return error_response_json("NotFoundException", "The specified bucket policy does not exist", 404)+ return json_response({"resourcePolicy": bucket["_policy"]})+ if method == "PUT":+ bucket["_policy"] = data.get("resourcePolicy")+ return json_response({})+ if method == "DELETE":+ bucket.pop("_policy", None)+ return _no_content()+ if kind == "storage-class":+ if method == "GET":+ return json_response({"storageClassConfiguration": bucket.get("_storageClass") or _DEFAULT_STORAGE_CLASS})+ if method == "PUT":+ bucket["_storageClass"] = data.get("storageClassConfiguration")+ return json_response({})+ if kind == "metrics":+ if method == "GET":+ if not bucket.get("_metricsId"):+ return error_response_json("NotFoundException", "The specified metrics configuration does not exist", 404)+ return json_response({"tableBucketARN": bucket["arn"], "id": bucket["_metricsId"]})+ if method == "PUT":+ bucket.setdefault("_metricsId", new_uuid())+ return _no_content()+ if method == "DELETE":+ bucket.pop("_metricsId", None)+ return _no_content()+ return error_response_json("UnknownOperationException", f"Unknown S3Tables operation: {method} {kind}", 400)+++def _table_record(bucket_arn, namespace, name):+ existing = _existing_bucket_arn(bucket_arn)+ if not existing:+ return None, _bucket_not_found(bucket_arn)+ table = _tables.get(_table_key(existing, namespace, name))+ if not table:+ return None, error_response_json("NotFoundException", f"Table {name} not found", 404)+ return table, None+++def _table_subresource(method, bucket_arn, namespace, name, sub, data):+ table, error = _table_record(bucket_arn, namespace, name)+ if error:+ return error+ bucket = _find_bucket_by_arn(table["tableBucketARN"]) or {}+ kind = sub[0]+ if kind == "encryption" and method == "GET":+ return json_response({"encryptionConfiguration": table.get("_encryption")+ or bucket.get("_encryption") or _DEFAULT_ENCRYPTION})+ if kind == "storage-class" and method == "GET":+ return json_response({"storageClassConfiguration": table.get("_storageClass")+ or bucket.get("_storageClass") or _DEFAULT_STORAGE_CLASS})+ if kind == "maintenance":+ if method == "GET":+ return json_response({+ "tableARN": table["tableARN"],+ "configuration": _maintenance_view(_TABLE_MAINTENANCE_DEFAULTS, table.get("_maintenance")),+ })+ if method == "PUT" and len(sub) == 2:+ table.setdefault("_maintenance", {})[sub[1]] = data.get("value") or {}+ return _no_content()+ if kind == "maintenance-job-status" and method == "GET":+ return json_response({"tableARN": table["tableARN"], "status": {+ job: {"status": "Not_Yet_Run"}+ for job in ("icebergCompaction", "icebergSnapshotManagement", "icebergUnreferencedFileRemoval")+ }})+ if kind == "policy":+ if method == "GET":+ if not table.get("_policy"):+ return error_response_json("NotFoundException", "The specified table policy does not exist", 404)+ return json_response({"resourcePolicy": table["_policy"]})+ if method == "PUT":+ table["_policy"] = data.get("resourcePolicy")+ return json_response({})+ if method == "DELETE":+ table.pop("_policy", None)+ return _no_content()+ if kind == "rename" and method == "PUT":+ return _rename_table(table, namespace, name, data)+ return error_response_json("UnknownOperationException", f"Unknown S3Tables operation: {method} {kind}", 400)+++def _rename_table(table, namespace, name, data):+ bucket_arn = table["tableBucketARN"]+ new_namespace = data.get("newNamespaceName") or namespace+ new_name = data.get("newName") or name+ if not _namespaces.get(_ns_key(bucket_arn, new_namespace)):+ return error_response_json("NotFoundException", f"Namespace {new_namespace} not found", 404)+ new_key = _table_key(bucket_arn, new_namespace, new_name)+ if new_key in _tables:+ return error_response_json("ConflictException", f"Table {new_name} already exists", 409)+ token = data.get("versionToken")+ if token and token != table.get("versionToken"):+ return error_response_json("ConflictException", "The version token does not match the current version", 409)+ del _tables[_table_key(bucket_arn, namespace, name)]+ table["name"], table["namespace"] = new_name, [new_namespace]+ table["modifiedAt"], table["modifiedBy"] = now_iso(), get_account_id()+ table["versionToken"] = new_uuid()[:8]+ _tables[new_key] = table+ return _no_content()+++def _tagged_record(resource_arn):+ bucket = _find_bucket_by_arn(resource_arn)+ if bucket and bucket["arn"] == resource_arn:+ return bucket+ for table in _tables.values():+ if table.get("tableARN") == resource_arn:+ return table+ return None+++def _tags_request(method, resource_arn, data, query_params):+ record = _tagged_record(unquote(resource_arn))+ if record is None:+ return error_response_json("NotFoundException", f"Resource not found: {resource_arn}", 404)+ tags = record.setdefault("_tags", {})+ if method == "GET":+ return json_response({"tags": tags})+ if method == "POST":+ tags.update(data.get("tags") or {})+ return json_response({})+ if method == "DELETE":+ keys = query_params.get("tagKeys") or []+ for key in keys if isinstance(keys, list) else [keys]:+ tags.pop(key, None)+ return _no_content()+ return error_response_json("UnknownOperationException", f"Unknown S3Tables operation: {method} tag", 400)++def _split_arn_and_suffix(path_str, resource_type):"""Split 'arn:aws:s3tables:region:account:bucket/name/extra/stuff' into (arn, 'extra/stuff').diff --git a/tests/conftest.py b/tests/conftest.pyindex e4a4c2be..78f7c64b 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -19,6 +19,11 @@ import boto3import pytestfrom botocore.config import Config+from ministack.core.responses import install_docker_hub_fallback++# Fixtures that pull images themselves get the same Docker Hub fallback as the server.+install_docker_hub_fallback()+ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")ENDPOINT_HOST = urlparse(ENDPOINT).hostname# The port the services advertise themselves on, read the way they read it: andiff --git a/tests/test_athena.py b/tests/test_athena.pyindex 098ebda4..f31bb124 100644--- a/tests/test_athena.py+++ b/tests/test_athena.py@@ -9,31 +9,19 @@ import duckdbimport pytestfrom botocore.config import Configfrom botocore.exceptions import ClientError+from conftest import make_client@pytest.fixture-def persisted_parquet_store(monkeypatch, tmp_path):- """Make a local Parquet file visible to MiniStack's Glue-backed Athena reader."""- from ministack.services import s3 as s3mod+def persisted_parquet_store(s3):+ """Uploads table data through the S3 API, the way a client stores it on AWS."""- monkeypatch.setattr(s3mod, "DATA_DIR", str(tmp_path))- monkeypatch.setattr(s3mod, "S3_PERSIST", True)- endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+ class _Uploader:+ @staticmethod+ def _persist_object(bucket, key, body):+ s3.put_object(Bucket=bucket, Key=key, Body=body)- def configure(path):- request = urllib.request.Request(- f"{endpoint}/_ministack/config",- data=json.dumps({"athena.ATHENA_DATA_DIR": path}).encode(),- headers={"Content-Type": "application/json"},- method="POST",- )- urllib.request.urlopen(request, timeout=5).close()-- configure(str(tmp_path))- try:- yield s3mod- finally:- configure(os.environ.get("S3_DATA_DIR", "/tmp/ministack-data/s3"))+ return _Uploader()def test_athena_queries_glue_backed_parquet(@@ -790,11 +778,8 @@ def test_athena_mixed_glue_and_s3_uri(athena, glue, monkeypatch, tmp_path):)urllib.request.urlopen(req, timeout=5)- s3mod._persist_object(- bucket_name,- "tables/users/data.csv",- b"id,name\n1,alice\n2,bob"- )+ make_client("s3").put_object(Bucket=bucket_name, Key="tables/users/data.csv",+ Body=b"id,name\n1,alice\n2,bob")s3mod._persist_object(bucket_name,@@ -860,6 +845,13 @@ def _create_s3_results_bucket(s3):s3.create_bucket(Bucket="athena-results")[email protected](autouse=True)+def _primary_result_location(athena):+ """AWS's primary workgroup has no result location until the user sets one."""+ athena.update_work_group(WorkGroup="primary", ConfigurationUpdates={+ "ResultConfigurationUpdates": {"OutputLocation": "s3://athena-results/"}})++def test_athena_list_and_get_databases_from_glue(athena, glue):"""ListDatabases / GetDatabase read the Glue Data Catalog, so a catalog client thatwalks databases before tables sees what Glue holds."""@@ -911,7 +903,8 @@ def _seed_users(monkeypatch, tmp_path, glue, db_name):headers={"Content-Type": "application/json"}, method="POST",)urllib.request.urlopen(req, timeout=5)- s3mod._persist_object("athena-results", f"{db_name}/users/data.csv", b"id,email\n1,[email protected]\n2,[email protected]")+ make_client("s3").put_object(Bucket="athena-results", Key=f"{db_name}/users/data.csv",+ Body=b"id,email\n1,[email protected]\n2,[email protected]")glue.create_database(DatabaseInput={"Name": db_name})glue.create_table(DatabaseName=db_name, TableInput={"Name": "users",@@ -919,7 +912,7 @@ def _seed_users(monkeypatch, tmp_path, glue, db_name):"Columns": [{"Name": "id", "Type": "bigint"}, {"Name": "email", "Type": "string"}],"Location": f"s3://athena-results/{db_name}/users/",},- "Parameters": {"classification": "csv"},+ "Parameters": {"classification": "csv", "skip.header.line.count": "1"},})@@ -1246,7 +1239,8 @@ def test_table_references_qualified_quoted_and_aliased():query = 'SELECT u.id FROM "awsdatacatalog"."acme"."users" u JOIN orders ON u.id = orders.uid'refs = _table_references(query)assert refs == [- _TableReference("acme", "users", query.index('"awsdatacatalog"'), query.index(" u JOIN"), aliased=True),+ _TableReference("acme", "users", query.index('"awsdatacatalog"'), query.index(" u JOIN"), aliased=True,+ catalog="awsdatacatalog"),_TableReference(None, "orders", query.index("orders ON"), query.index(" ON u.id"), aliased=False),]@@ -1259,3 +1253,192 @@ def test_table_references_skip_ctes_and_keep_clause_keywords_unaliased():assert _table_references("SELECT 1") == []assert _table_references("SELECT 1 FROM a.b.c.d") == []assert [r.aliased for r in _table_references('SELECT * FROM t AS "x" LIMIT 1')] == [True]+++def _s3tables_writer(bucket_arn, key_id="test"):+ """A client-side DuckDB attached to the bucket's Iceberg REST catalog, the way+ Spark or PyIceberg would write an S3 table; skips when the extensions are unavailable."""+ from urllib.parse import urlparse++ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+ parsed = urlparse(endpoint)+ con = duckdb.connect()+ try:+ con.execute("INSTALL iceberg; LOAD iceberg; INSTALL httpfs; LOAD httpfs;")+ con.execute(f"CREATE SECRET s (TYPE S3, KEY_ID '{key_id}', SECRET 'test', "+ f"ENDPOINT '{parsed.hostname}:{parsed.port or 4566}', URL_STYLE 'path', "+ f"USE_SSL false, REGION 'us-east-1')")+ # SigV4 clients carry their account in the Credential scope; DuckDB only signs AWS hosts.+ credential = f"AWS4-HMAC-SHA256 Credential={key_id}/19700101/us-east-1/s3tables/aws4_request"+ con.execute(f"CREATE SECRET h (TYPE HTTP, SCOPE '{endpoint}/iceberg', "+ f"EXTRA_HTTP_HEADERS MAP {{'Authorization': '{credential}'}})")+ con.execute(f"ATTACH '{bucket_arn}' AS cat (TYPE ICEBERG, ENDPOINT '{endpoint}/iceberg', "+ f"AUTHORIZATION_TYPE 'none')")+ except Exception as exc: # pragma: no cover - environment dependent+ con.close()+ pytest.skip(f"DuckDB Iceberg REST writes unavailable: {exc}")+ return con+++def _athena_rows(athena, query, context, output=None):+ extra = {"ResultConfiguration": {"OutputLocation": output}} if output else {}+ query_id = athena.start_query_execution(QueryString=query, QueryExecutionContext=context,+ **extra)["QueryExecutionId"]+ for _ in range(100):+ execution = athena.get_query_execution(QueryExecutionId=query_id)["QueryExecution"]+ if execution["Status"]["State"] in ("SUCCEEDED", "FAILED", "CANCELLED"):+ break+ time.sleep(0.2)+ if execution["Status"]["State"] != "SUCCEEDED":+ return execution["Status"]["State"], None+ rows = athena.get_query_results(QueryExecutionId=query_id)["ResultSet"]["Rows"]+ return "SUCCEEDED", [[d.get("VarCharValue") for d in r["Data"]] for r in rows[1:]]+++def test_athena_queries_s3_tables_through_s3tablescatalog(athena):+ """Both documented forms: "s3tablescatalog/<bucket>".ns.table, and the context+ Catalog s3tablescatalog/<bucket> with an unqualified table. Each bucket reads its own rows."""+ s3t = boto3.client("s3tables", endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),+ region_name="us-east-1", aws_access_key_id="test", aws_secret_access_key="test")+ suffix = _uuid_mod.uuid4().hex[:8]+ names = {}+ for label, rows in (("one", "(1, 'apple'), (2, 'pear')"), ("two", "(7, 'plum')")):+ name = f"ath-s3t-{label}-{suffix}"+ arn = s3t.create_table_bucket(name=name)["arn"]+ s3t.create_namespace(tableBucketARN=arn, namespace=["sales"])+ con = _s3tables_writer(arn)+ con.execute("CREATE TABLE cat.sales.orders (id INTEGER, item VARCHAR)")+ con.execute(f"INSERT INTO cat.sales.orders VALUES {rows}")+ con.close()+ names[label] = name++ state, rows = _athena_rows(+ athena, f'SELECT id, item FROM "s3tablescatalog/{names["one"]}"."sales"."orders" ORDER BY id',+ {"Database": "default"})+ assert (state, rows) == ("SUCCEEDED", [["1", "apple"], ["2", "pear"]])++ state, rows = _athena_rows(+ athena, "SELECT o.id, o.item FROM orders o",+ {"Catalog": f"s3tablescatalog/{names['two']}", "Database": "sales"})+ assert (state, rows) == ("SUCCEEDED", [["7", "plum"]])++ state, _ = _athena_rows(+ athena, f'SELECT * FROM "s3tablescatalog/{names["one"]}"."sales"."missing"', {"Database": "default"})+ assert state == "FAILED"+++def test_athena_reads_glue_csv_by_position_from_every_visible_object(athena, glue, s3):+ """S3 objects are read whatever their names, without S3_PERSIST; hidden "_"/"." files and+ folders are skipped; CSV fields map to the Glue columns by position, a value that does not+ cast reads as NULL and a missing trailing field as NULL."""+ suffix = _uuid_mod.uuid4().hex[:8]+ bucket, database = f"ath-csv-{suffix}", f"csv_{suffix}"+ s3.create_bucket(Bucket=bucket)+ s3.put_object(Bucket=bucket, Key="t/part-00000", Body=b"1,alice\n2,bob\n")+ s3.put_object(Bucket=bucket, Key="t/more/part-00001.csv", Body=b"x,carol\n4\n")+ s3.put_object(Bucket=bucket, Key="t/_SUCCESS", Body=b"")+ s3.put_object(Bucket=bucket, Key="t/.part-00000.crc", Body=b"garbage,garbage\n")+ s3.put_object(Bucket=bucket, Key="t/_temporary/0/part-9", Body=b"9,ghost\n")+ s3.put_object(Bucket=bucket, Key="other/part-00000", Body=b"8,elsewhere\n")+ glue.create_database(DatabaseInput={"Name": database})+ glue.create_table(DatabaseName=database, TableInput={+ "Name": "people",+ "StorageDescriptor": {+ "Columns": [{"Name": "id", "Type": "int"}, {"Name": "name", "Type": "string"}],+ "Location": f"s3://{bucket}/t/",+ "SerdeInfo": {"SerializationLibrary": "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe",+ "Parameters": {"field.delim": ","}},+ },+ "Parameters": {"classification": "csv"},+ })+ state, rows = _athena_rows(athena, "SELECT id, name FROM people ORDER BY name NULLS LAST",+ {"Database": database})+ assert (state, rows) == ("SUCCEEDED", [["1", "alice"], ["2", "bob"], [None, "carol"], ["4", None]])+++def test_athena_csv_skip_header_line_count(athena, glue, s3):+ suffix = _uuid_mod.uuid4().hex[:8]+ bucket, database = f"ath-hdr-{suffix}", f"hdr_{suffix}"+ s3.create_bucket(Bucket=bucket)+ s3.put_object(Bucket=bucket, Key="t/a.csv", Body=b"id,name\n1,alice\n")+ glue.create_database(DatabaseInput={"Name": database})+ for name, params in (("skipped", {"skip.header.line.count": "1"}), ("kept", {})):+ glue.create_table(DatabaseName=database, TableInput={+ "Name": name,+ "StorageDescriptor": {+ "Columns": [{"Name": "id", "Type": "int"}, {"Name": "name", "Type": "string"}],+ "Location": f"s3://{bucket}/t/",+ "SerdeInfo": {"SerializationLibrary": "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe",+ "Parameters": {"field.delim": ","}},+ },+ "Parameters": {"classification": "csv", **params},+ })+ assert _athena_rows(athena, "SELECT id, name FROM skipped", {"Database": database}) == (+ "SUCCEEDED", [["1", "alice"]])+ assert _athena_rows(athena, "SELECT id, name FROM kept ORDER BY name", {"Database": database}) == (+ "SUCCEEDED", [["1", "alice"], [None, "name"]])+++def test_athena_s3_tables_query_in_a_non_default_account():+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+ kw = dict(endpoint_url=endpoint, region_name="us-east-1",+ aws_access_key_id="111111111111", aws_secret_access_key="test")+ s3t, athena = boto3.client("s3tables", **kw), boto3.client("athena", **kw)+ name = f"ath-s3t-acct-{_uuid_mod.uuid4().hex[:8]}"+ boto3.client("s3", **kw).create_bucket(Bucket=f"{name}-results")+ arn = s3t.create_table_bucket(name=name)["arn"]+ assert ":111111111111:" in arn+ s3t.create_namespace(tableBucketARN=arn, namespace=["sales"])+ con = _s3tables_writer(arn, key_id="111111111111")+ con.execute("CREATE TABLE cat.sales.orders (id INTEGER)")+ con.execute("INSERT INTO cat.sales.orders VALUES (5)")+ con.close()+ assert _athena_rows(athena, "SELECT id FROM orders",+ {"Catalog": f"s3tablescatalog/{name}", "Database": "sales"},+ output=f"s3://{name}-results/") == ("SUCCEEDED", [["5"]])++++def test_athena_start_query_without_output_location_is_refused():+ athena = _client("us-east-1")+ workgroup = f"ath-noout-{_uuid_mod.uuid4().hex[:8]}"+ athena.create_work_group(Name=workgroup)+ with pytest.raises(ClientError) as exc:+ athena.start_query_execution(QueryString="SELECT 1", WorkGroup=workgroup)+ err = exc.value.response+ assert err["Error"]["Code"] == "InvalidRequestException"+ assert err["Error"]["Message"] == ("No output location provided. An output location is required either "+ "through the Workgroup result configuration setting or as an API input.")+ assert err["ResponseMetadata"]["HTTPStatusCode"] == 400+ query_id = athena.start_query_execution(+ QueryString="SELECT 1", WorkGroup=workgroup,+ ResultConfiguration={"OutputLocation": "s3://athena-results/"})["QueryExecutionId"]+ assert query_id+++def test_athena_reads_avro_tables(athena, glue, s3, tmp_path):+ path = tmp_path / "rows.avro"+ con = duckdb.connect()+ try:+ con.execute("INSTALL avro; LOAD avro;")+ con.execute(f"COPY (SELECT 1::INT AS id, 'a' AS name UNION ALL SELECT 2, 'b') TO '{path}' (FORMAT avro)")+ except Exception as exc: # pragma: no cover - environment dependent+ pytest.skip(f"DuckDB Avro unavailable: {exc}")+ finally:+ con.close()+ suffix = _uuid_mod.uuid4().hex[:8]+ bucket, database = f"ath-avro-{suffix}", f"avro_{suffix}"+ s3.create_bucket(Bucket=bucket)+ s3.put_object(Bucket=bucket, Key="t/part-00000", Body=path.read_bytes())+ glue.create_database(DatabaseInput={"Name": database})+ glue.create_table(DatabaseName=database, TableInput={+ "Name": "rows",+ "StorageDescriptor": {+ "Columns": [{"Name": "id", "Type": "int"}, {"Name": "name", "Type": "string"}],+ "Location": f"s3://{bucket}/t/",+ "SerdeInfo": {"SerializationLibrary": "org.apache.hadoop.hive.serde2.avro.AvroSerDe"},+ },+ "Parameters": {"classification": "avro"},+ })+ assert _athena_rows(athena, "SELECT id, name FROM rows ORDER BY id", {"Database": database}) == (+ "SUCCEEDED", [["1", "a"], ["2", "b"]])diff --git a/tests/test_ministack.py b/tests/test_ministack.pyindex 3918d282..2d9108cb 100644--- a/tests/test_ministack.py+++ b/tests/test_ministack.py@@ -1154,3 +1154,45 @@ def test_unknown_scope_still_falls_through_to_s3():def test_implemented_scope_routes_normally():assert detect_service("POST", "/", _auth("dynamodb"), {}) == "dynamodb"assert detect_service("POST", "/", _auth("states"), {}) == "states"+++def test_docker_hub_mirrors_cover_hub_images_only():+ from ministack.core.responses import docker_hub_mirrors++ assert docker_hub_mirrors("postgres") == ["public.ecr.aws/docker/library/postgres", "mirror.gcr.io/library/postgres"]+ assert docker_hub_mirrors("docker.io/library/redis") == ["public.ecr.aws/docker/library/redis", "mirror.gcr.io/library/redis"]+ assert docker_hub_mirrors("rancher/k3s") == ["public.ecr.aws/rancher/k3s", "mirror.gcr.io/rancher/k3s"]+ for other_registry in ("public.ecr.aws/lambda/python", "localhost:5000/app", "ghcr.io/org/app", "proxy.corp.net/postgres"):+ assert docker_hub_mirrors(other_registry) == []+++def test_failed_docker_hub_pull_falls_back_to_a_mirror_and_keeps_the_name(monkeypatch):+ from docker.errors import APIError+ from docker.models.images import ImageCollection++ from ministack.core.responses import install_docker_hub_fallback++ pulled, tagged = [], []++ class _Image:+ def tag(self, repository, tag):+ tagged.append(f"{repository}:{tag}")++ def registry(self, repository, tag=None, all_tags=False, **kwargs):+ pulled.append(f"{repository}:{tag}" if tag else repository)+ if repository.startswith("mirror.gcr.io/"):+ return _Image()+ raise APIError("500 Server Error: registry unavailable")++ monkeypatch.setattr(ImageCollection, "pull", registry)+ install_docker_hub_fallback()++ ImageCollection.pull(None, "rancher/k3s:v1.31.4-k3s1", platform="linux/amd64")+ assert pulled == ["rancher/k3s:v1.31.4-k3s1", "public.ecr.aws/rancher/k3s:v1.31.4-k3s1",+ "mirror.gcr.io/rancher/k3s:v1.31.4-k3s1"]+ assert tagged == ["rancher/k3s:v1.31.4-k3s1"]++ pulled.clear()+ with pytest.raises(APIError, match="registry unavailable"):+ ImageCollection.pull(None, "public.ecr.aws/lambda/python:3.12")+ assert pulled == ["public.ecr.aws/lambda/python:3.12"]diff --git a/tests/test_s3tables.py b/tests/test_s3tables.pyindex 7aa80803..fbdd7ba8 100644--- a/tests/test_s3tables.py+++ b/tests/test_s3tables.py@@ -1248,3 +1248,101 @@ def test_s3tables_iceberg_rest_sequence_numbers_and_requirements(s3tables):s3tables.delete_table(tableBucketARN=arn, namespace="ns", name="t")s3tables.delete_namespace(tableBucketARN=arn, namespace="ns")s3tables.delete_table_bucket(tableBucketARN=arn)+++def test_s3tables_bucket_subresources_defaults_and_updates(s3tables):+ """Documented defaults until set: SSE-S3, STANDARD, unreferenced file removal 3/10 days."""+ arn = s3tables.create_table_bucket(name=f"sub-{_uuid_mod.uuid4().hex[:8]}",+ tags={"team": "data"})["arn"]+ got = s3tables.get_table_bucket(tableBucketARN=arn)+ assert set(got) - {"ResponseMetadata"} <= {"arn", "name", "ownerAccountId", "createdAt", "tableBucketId", "type"}+ assert got["type"] == "customer" and got["tableBucketId"]++ assert s3tables.get_table_bucket_encryption(tableBucketARN=arn)["encryptionConfiguration"] == {+ "sseAlgorithm": "AES256"}+ s3tables.put_table_bucket_encryption(tableBucketARN=arn, encryptionConfiguration={+ "sseAlgorithm": "aws:kms", "kmsKeyArn": "arn:aws:kms:us-east-1:000000000000:key/k"})+ assert s3tables.get_table_bucket_encryption(tableBucketARN=arn)["encryptionConfiguration"]["sseAlgorithm"] == "aws:kms"+ s3tables.delete_table_bucket_encryption(tableBucketARN=arn)+ assert s3tables.get_table_bucket_encryption(tableBucketARN=arn)["encryptionConfiguration"] == {+ "sseAlgorithm": "AES256"}++ removal = s3tables.get_table_bucket_maintenance_configuration(tableBucketARN=arn)["configuration"][+ "icebergUnreferencedFileRemoval"]+ assert removal == {"status": "enabled", "settings": {"icebergUnreferencedFileRemoval": {+ "unreferencedDays": 3, "nonCurrentDays": 10}}}+ s3tables.put_table_bucket_maintenance_configuration(+ tableBucketARN=arn, type="icebergUnreferencedFileRemoval",+ value={"status": "enabled", "settings": {"icebergUnreferencedFileRemoval": {"unreferencedDays": 4}}})+ removal = s3tables.get_table_bucket_maintenance_configuration(tableBucketARN=arn)["configuration"][+ "icebergUnreferencedFileRemoval"]+ assert removal["settings"]["icebergUnreferencedFileRemoval"] == {"unreferencedDays": 4, "nonCurrentDays": 10}++ with pytest.raises(ClientError) as exc:+ s3tables.get_table_bucket_policy(tableBucketARN=arn)+ assert exc.value.response["Error"]["Code"] == "NotFoundException"+ s3tables.put_table_bucket_policy(tableBucketARN=arn, resourcePolicy='{"Version":"2012-10-17","Statement":[]}')+ assert s3tables.get_table_bucket_policy(tableBucketARN=arn)["resourcePolicy"].startswith('{"Version"')+ s3tables.delete_table_bucket_policy(tableBucketARN=arn)++ assert s3tables.get_table_bucket_storage_class(tableBucketARN=arn)["storageClassConfiguration"] == {+ "storageClass": "STANDARD"}+ s3tables.put_table_bucket_storage_class(tableBucketARN=arn,+ storageClassConfiguration={"storageClass": "INTELLIGENT_TIERING"})+ assert s3tables.get_table_bucket_storage_class(tableBucketARN=arn)["storageClassConfiguration"][+ "storageClass"] == "INTELLIGENT_TIERING"++ s3tables.put_table_bucket_metrics_configuration(tableBucketARN=arn)+ assert s3tables.get_table_bucket_metrics_configuration(tableBucketARN=arn)["id"]+ s3tables.delete_table_bucket_metrics_configuration(tableBucketARN=arn)++ assert s3tables.list_tags_for_resource(resourceArn=arn)["tags"] == {"team": "data"}+ s3tables.tag_resource(resourceArn=arn, tags={"env": "dev"})+ s3tables.untag_resource(resourceArn=arn, tagKeys=["team"])+ assert s3tables.list_tags_for_resource(resourceArn=arn)["tags"] == {"env": "dev"}+++def test_s3tables_table_subresources_and_rename(s3tables):+ arn = s3tables.create_table_bucket(name=f"tsub-{_uuid_mod.uuid4().hex[:8]}")["arn"]+ for ns in ("a", "b"):+ s3tables.create_namespace(tableBucketARN=arn, namespace=[ns])+ created = s3tables.create_table(tableBucketARN=arn, namespace="a", name="t", format="ICEBERG",+ tags={"k": "v"})+ table = s3tables.get_table(tableBucketARN=arn, namespace="a", name="t")+ assert table["type"] == "customer" and table["versionToken"] == created["versionToken"]+ assert "tableBucketARN" not in table++ config = s3tables.get_table_maintenance_configuration(tableBucketARN=arn, namespace="a", name="t")["configuration"]+ assert config["icebergCompaction"] == {"status": "enabled", "settings": {"icebergCompaction": {+ "targetFileSizeMB": 512, "strategy": "auto"}}}+ assert config["icebergSnapshotManagement"] == {"status": "enabled", "settings": {"icebergSnapshotManagement": {+ "minSnapshotsToKeep": 1, "maxSnapshotAgeHours": 120}}}+ s3tables.put_table_maintenance_configuration(+ tableBucketARN=arn, namespace="a", name="t", type="icebergCompaction",+ value={"status": "disabled", "settings": {"icebergCompaction": {"targetFileSizeMB": 256}}})+ compaction = s3tables.get_table_maintenance_configuration(+ tableBucketARN=arn, namespace="a", name="t")["configuration"]["icebergCompaction"]+ assert compaction["status"] == "disabled"+ assert compaction["settings"]["icebergCompaction"]["targetFileSizeMB"] == 256++ status = s3tables.get_table_maintenance_job_status(tableBucketARN=arn, namespace="a", name="t")["status"]+ assert {v["status"] for v in status.values()} == {"Not_Yet_Run"}+ assert s3tables.get_table_encryption(tableBucketARN=arn, namespace="a", name="t")[+ "encryptionConfiguration"] == {"sseAlgorithm": "AES256"}+ assert s3tables.get_table_storage_class(tableBucketARN=arn, namespace="a", name="t")[+ "storageClassConfiguration"] == {"storageClass": "STANDARD"}++ with pytest.raises(ClientError) as exc:+ s3tables.get_table_policy(tableBucketARN=arn, namespace="a", name="t")+ assert exc.value.response["Error"]["Code"] == "NotFoundException"+ s3tables.put_table_policy(tableBucketARN=arn, namespace="a", name="t", resourcePolicy="{}")+ assert s3tables.get_table_policy(tableBucketARN=arn, namespace="a", name="t")["resourcePolicy"] == "{}"++ assert s3tables.list_tags_for_resource(resourceArn=created["tableARN"])["tags"] == {"k": "v"}++ s3tables.rename_table(tableBucketARN=arn, namespace="a", name="t", newNamespaceName="b", newName="t2")+ renamed = s3tables.get_table(tableBucketARN=arn, namespace="b", name="t2")+ assert renamed["tableARN"] == created["tableARN"] and renamed["namespace"] == ["b"]+ with pytest.raises(ClientError) as exc:+ s3tables.get_table(tableBucketARN=arn, namespace="a", name="t")+ assert exc.value.response["Error"]["Code"] == "NotFoundException"