diff --git a/pyiceberg/catalog/glue.py b/pyiceberg/catalog/glue.py index 9ba8775747..d5b1e04a0b 100644 --- a/pyiceberg/catalog/glue.py +++ b/pyiceberg/catalog/glue.py @@ -17,6 +17,9 @@ import logging +from collections.abc import Iterator, Mapping +from contextlib import contextmanager, nullcontext +from contextvars import ContextVar from typing import ( TYPE_CHECKING, Any, @@ -27,6 +30,7 @@ import boto3 from botocore.config import Config +from botocore.exceptions import ClientError, ParamValidationError from typing_extensions import override from pyiceberg.catalog import ( @@ -43,6 +47,7 @@ ) from pyiceberg.exceptions import ( CommitFailedException, + CommitStateUnknownException, NamespaceAlreadyExistsError, NamespaceNotEmptyError, NoSuchIcebergTableError, @@ -68,6 +73,7 @@ from pyiceberg.serializers import FromInputFile, ToOutputFile from pyiceberg.table import ( CommitTableResponse, + StagedTable, Table, ) from pyiceberg.table.metadata import TableMetadata @@ -343,6 +349,69 @@ def add_glue_catalog_id(params: dict[str, str], **kwargs: Any) -> None: event_system.register("provide-client-params.glue", add_glue_catalog_id) +# Whether Glue rejected each attempt of the write whose commit status is being checked +_glue_write_attempts: ContextVar[list[bool] | None] = ContextVar("_glue_write_attempts", default=None) + + +# Errors with which Glue refuses a request without applying it. Others, such as timeouts, don't show whether it did. +_GLUE_REJECTION_CODES = frozenset( + { + "AccessDeniedException", + "AlreadyExistsException", + "ConcurrentModificationException", + "EntityNotFoundException", + "ExpiredTokenException", + "GlueEncryptionException", + "IncompleteSignature", + "InvalidClientTokenId", + "InvalidInputException", + "InvalidSignatureException", + "MalformedHttpRequestException", + "NotAuthorized", + "OptInRequired", + "RequestEntityTooLargeException", + "RequestExpired", + "ResourceNotReadyException", + "ResourceNumberLimitExceededException", + "ThrottlingException", + "UnknownOperationException", + "UnrecognizedClientException", + "ValidationError", + "ValidationException", + } +) + + +def _is_rejection(response: Mapping[str, Any]) -> bool: + """Return whether a Glue response refuses the attempt that it answers.""" + return response.get("Error", {}).get("Code") in _GLUE_REJECTION_CODES + + +def _record_attempt(response: tuple[Any, Mapping[str, Any]] | None = None, **kwargs: Any) -> None: + """Record whether Glue rejected an attempt of the write whose commit status is being checked.""" + if (attempts := _glue_write_attempts.get()) is not None: + attempts.append(response is not None and _is_rejection(response[1])) + + +def _register_attempt_recorder(glue: "GlueClient") -> None: + """Register the handler that records whether Glue rejected each attempt of a write, once per client.""" + for operation in ("CreateTable", "UpdateTable"): + glue.meta.events.register( + f"needs-retry.glue.{operation}", _record_attempt, unique_id=f"pyiceberg-record-{operation}-attempt" + ) + + +def _proves_not_applied(error: Exception, attempts: list[bool]) -> bool: + """Return whether the error and the recorded attempts show that Glue applied no attempt of the request.""" + if isinstance(error, ParamValidationError): + # Raised before the request is sent + return True + # The handler runs after every attempt, including the last, so when a rejection ends the request, every attempt that + # was sent has been recorded. Glue may have applied any attempt that it didn't reject, and an empty record, such as + # for a request sent from another thread, shows nothing. + return isinstance(error, ClientError) and _is_rejection(error.response) and bool(attempts) and all(attempts) + + class GlueCatalog(MetastoreCatalog): glue: "GlueClient" @@ -395,6 +464,9 @@ def __init__(self, name: str, client: Optional["GlueClient"] = None, **propertie if glue_catalog_id := properties.get(GLUE_ID): _register_glue_catalog_id_with_glue_client(self.glue, glue_catalog_id) + # Registered with the catalog, so that checked writes don't change the client's handlers while other threads use it + _register_attempt_recorder(self.glue) + def _convert_glue_to_iceberg(self, glue_table: "TableTypeDef") -> Table: if (database_name := glue_table.get("DatabaseName")) is None: raise ValueError("Glue table is missing DatabaseName property") @@ -431,22 +503,112 @@ def _convert_glue_to_iceberg(self, glue_table: "TableTypeDef") -> Table: catalog=self, ) - def _create_glue_table(self, database_name: str, table_name: str, table_input: "TableInputTypeDef") -> None: + @contextmanager + def _check_commit_status(self, database_name: str, table_name: str, staged_table: StagedTable) -> Iterator[None]: + """Check whether a Glue write that fails was committed anyway. + + Glue may have applied a write that failed without a response, with a server error, or with a timeout. The client + also retries failed requests, so a request that Glue applied but whose response was lost is sent again, and the + retry may be rejected, for example because the table is no longer at the expected version. So the error is raised + as is if the client rejected the request before sending it, if Glue rejected every attempt, or if a create that + the table doesn't confirm failed because the table exists. Otherwise, the write succeeds if the table confirms it. + + Raises: + CommitStateUnknownException: If Glue may have applied the write, but the table doesn't confirm it. + """ + # The client may have been replaced since the catalog was created + _register_attempt_recorder(self.glue) + attempts: list[bool] = [] + token = _glue_write_attempts.set(attempts) try: - self.glue.create_table(DatabaseName=database_name, TableInput=table_input) + yield + except Exception as e: + if _proves_not_applied(e, attempts): + raise + logger.warning( + f"Commit to {database_name}.{table_name} failed, checking whether it succeeded: {e}", + exc_info=logger.isEnabledFor(logging.DEBUG), + ) + try: + committed = self._is_committed(database_name, table_name, staged_table) + except Exception as check_error: + raise CommitStateUnknownException( + f"Cannot determine whether the commit to {database_name}.{table_name} succeeded: {e}. " + f"Checking the table failed: {check_error}" + ) from check_error + if not committed: + if ( + isinstance(e, ClientError) + and e.operation_name == "CreateTable" + and e.response.get("Error", {}).get("Code") == "AlreadyExistsException" + ): + # Another table holds the name, and no create path deletes files on TableAlreadyExistsError + raise + # A landed write may have left the table's history since, for example when the metadata log was trimmed + raise CommitStateUnknownException( + f"Cannot determine whether the commit to {database_name}.{table_name} succeeded: {e}" + ) from e + logger.info(f"Commit to {database_name}.{table_name} succeeded") + finally: + _glue_write_attempts.reset(token) + + def _is_committed(self, database_name: str, table_name: str, staged_table: StagedTable) -> bool: + """Return whether the table confirms the staged metadata by its location, or for a new table, by its table UUID.""" + current_location = self._get_glue_table(database_name, table_name).get("Parameters", {}).get(METADATA_LOCATION) + if current_location == staged_table.metadata_location: + return True + if current_location is None: + return False + io = self._load_file_io(location=current_location) + metadata = FromInputFile.table_metadata(io.new_input(current_location)) + # An update always logs the location that it replaces, so only a table's first metadata has an empty log. Its + # new table UUID stays after its location leaves the metadata log. + if not staged_table.metadata.metadata_log: + return metadata.table_uuid == staged_table.metadata.table_uuid + return any(entry.metadata_file == staged_table.metadata_location for entry in metadata.metadata_log) + + def _create_glue_table( + self, database_name: str, table_name: str, table_input: "TableInputTypeDef", *, staged_table: StagedTable | None + ) -> None: + """Create a Glue table. + + Args: + database_name: The Glue database to create the table in. + table_name: The name of the table. + table_input: The Glue table to create. + staged_table: The staged table whose new metadata location the table input points at, to check whether a failed + request created the table anyway. None skips the check, when the table input points at existing metadata, + as for a register or rename, or at none, as for a new S3 Tables table. + """ + status_check = ( + self._check_commit_status(database_name, table_name, staged_table) if staged_table is not None else nullcontext() + ) + try: + with status_check: + self.glue.create_table(DatabaseName=database_name, TableInput=table_input) except self.glue.exceptions.AlreadyExistsException as e: raise TableAlreadyExistsError(f"Table {database_name}.{table_name} already exists") from e except self.glue.exceptions.EntityNotFoundException as e: raise NoSuchNamespaceError(f"Database {database_name} does not exist") from e - def _update_glue_table(self, database_name: str, table_name: str, table_input: "TableInputTypeDef", version_id: str) -> None: + def _update_glue_table( + self, + database_name: str, + table_name: str, + table_input: "TableInputTypeDef", + version_id: str, + *, + staged_table: StagedTable, + ) -> None: + skip_archive = property_as_bool(self.properties, GLUE_SKIP_ARCHIVE, GLUE_SKIP_ARCHIVE_DEFAULT) try: - self.glue.update_table( - DatabaseName=database_name, - TableInput=table_input, - SkipArchive=property_as_bool(self.properties, GLUE_SKIP_ARCHIVE, GLUE_SKIP_ARCHIVE_DEFAULT), - VersionId=version_id, - ) + with self._check_commit_status(database_name, table_name, staged_table): + self.glue.update_table( + DatabaseName=database_name, + TableInput=table_input, + SkipArchive=skip_archive, + VersionId=version_id, + ) except self.glue.exceptions.EntityNotFoundException as e: raise NoSuchTableError(f"Table does not exist: {database_name}.{table_name} (Glue table version {version_id})") from e except self.glue.exceptions.ConcurrentModificationException as e: @@ -523,6 +685,7 @@ def _create_table_s3tables( "Name": table_name, "Parameters": {"format": "ICEBERG"}, }, + staged_table=None, ) try: @@ -559,6 +722,7 @@ def _create_table_s3tables( table_name=table_name, table_input=table_input, version_id=version_id, + staged_table=staged_table, ) except Exception: # Clean up the table created in step 1. @@ -608,6 +772,8 @@ def create_table( AlreadyExistsError: If a table with the name already exists. ValueError: If the identifier is invalid, no path is given to store metadata, or a location is specified for an S3 Tables table. + CommitStateUnknownException: If creating the table in Glue failed and whether it was created cannot be + determined. """ database_name, table_name = self.identifier_to_database_and_table(identifier) @@ -635,7 +801,12 @@ def create_table( table_input = _construct_table_input( table_name, staged_table.metadata_location, staged_table.metadata.properties, staged_table.metadata ) - self._create_glue_table(database_name=database_name, table_name=table_name, table_input=table_input) + self._create_glue_table( + database_name=database_name, + table_name=table_name, + table_input=table_input, + staged_table=staged_table, + ) return Table( identifier=self.identifier_to_tuple(identifier), @@ -669,7 +840,7 @@ def register_table(self, identifier: str | Identifier, metadata_location: str, o file = io.new_input(metadata_location) metadata = FromInputFile.table_metadata(file) table_input = _construct_table_input(table_name, metadata_location, properties, metadata) - self._create_glue_table(database_name=database_name, table_name=table_name, table_input=table_input) + self._create_glue_table(database_name=database_name, table_name=table_name, table_input=table_input, staged_table=None) return self.load_table(identifier=identifier) @override @@ -689,6 +860,7 @@ def commit_table( Raises: NoSuchTableError: If a table with the given identifier does not exist. CommitFailedException: Requirement not met, or a conflict with a concurrent commit. + CommitStateUnknownException: If the Glue write failed and whether it was applied cannot be determined. """ table_identifier = table.name() database_name, table_name = self.identifier_to_database_and_table(table_identifier, NoSuchTableError) @@ -742,6 +914,7 @@ def commit_table( table_name=table_name, table_input=update_table_input, version_id=glue_table_version_id, + staged_table=updated_staged_table, ) else: # table does not exist, create the table @@ -751,7 +924,12 @@ def commit_table( properties=updated_staged_table.properties, metadata=updated_staged_table.metadata, ) - self._create_glue_table(database_name=database_name, table_name=table_name, table_input=create_table_input) + self._create_glue_table( + database_name=database_name, + table_name=table_name, + table_input=create_table_input, + staged_table=updated_staged_table, + ) return CommitTableResponse( metadata=updated_staged_table.metadata, metadata_location=updated_staged_table.metadata_location @@ -835,7 +1013,9 @@ def rename_table(self, from_identifier: str | Identifier, to_identifier: str | I ) from e rename_table_input = _construct_rename_table_input(to_table_name=to_table_name, glue_table=glue_table) - self._create_glue_table(database_name=to_database_name, table_name=to_table_name, table_input=rename_table_input) + self._create_glue_table( + database_name=to_database_name, table_name=to_table_name, table_input=rename_table_input, staged_table=None + ) try: self.drop_table(from_identifier) diff --git a/tests/catalog/test_glue.py b/tests/catalog/test_glue.py index 5f1ecab2c7..2bd378705f 100644 --- a/tests/catalog/test_glue.py +++ b/tests/catalog/test_glue.py @@ -14,18 +14,27 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. +import json +from collections.abc import Callable, Iterator +from concurrent.futures import ThreadPoolExecutor from datetime import UTC, datetime, timedelta +from io import BytesIO +from typing import Any from unittest import mock import boto3 import pyarrow as pa import pytest +from botocore.awsrequest import AWSPreparedRequest, AWSResponse from botocore.credentials import AssumeRoleCredentialFetcher +from botocore.exceptions import ClientError, ParamValidationError, ReadTimeoutError from moto import mock_aws from pyiceberg.catalog import _get_aws_session_with_assumed_role from pyiceberg.catalog.glue import GLUE_CONNECTION_S3_TABLES, GlueCatalog from pyiceberg.exceptions import ( + CommitFailedException, + CommitStateUnknownException, NamespaceAlreadyExistsError, NamespaceNotEmptyError, NoSuchIcebergTableError, @@ -37,8 +46,9 @@ from pyiceberg.io.pyarrow import schema_to_pyarrow from pyiceberg.partitioning import PartitionField, PartitionSpec from pyiceberg.schema import Schema +from pyiceberg.table import Table from pyiceberg.transforms import IdentityTransform -from pyiceberg.typedef import Properties +from pyiceberg.typedef import Identifier, Properties from pyiceberg.types import IntegerType from tests.conftest import ( BUCKET_NAME, @@ -98,6 +108,125 @@ def _table_init_with_location(self, database_name, table_name, table_input, *arg s3.create_bucket(Bucket=S3TABLES_WAREHOUSE_LOCATION) +def _patch_moto_for_table_versions(monkeypatch: pytest.MonkeyPatch) -> None: + """Patch moto to reject an UpdateTable with an outdated VersionId, as Glue does.""" + from moto.core.exceptions import JsonRESTError + from moto.glue.responses import GlueResponse + + _original_update_table = GlueResponse.update_table + + def _update_table_with_version_check(self): # type: ignore + table = self.glue_backend.get_table(self.parameters["DatabaseName"], self.parameters["TableInput"]["Name"]) + version_id = table.as_dict()["VersionId"] + if self.parameters.get("VersionId", version_id) != version_id: + raise JsonRESTError("ConcurrentModificationException", "Update table failed due to concurrent modifications.") + return _original_update_table(self) + + monkeypatch.setattr(GlueResponse, "update_table", _update_table_with_version_check) + + +def _retry_first_attempt(catalog: GlueCatalog, operation: str, before_retry: Callable[[], None] | None = None) -> None: + """Make the client send the next request for the operation a second time, as when the response to it is lost.""" + retried = False + + def needs_retry(attempts: int, **kwargs: Any) -> int | None: + nonlocal retried + if retried: + return None + retried = True + if before_retry is not None: + before_retry() + return 0 + + catalog.glue.meta.events.register_first(f"needs-retry.glue.{operation}", needs_retry) + + +def _glue_catalog(moto_endpoint_url: str, database_name: str, **properties: Any) -> GlueCatalog: + """Create a Glue catalog with a database, writing to the moto bucket.""" + catalog = GlueCatalog("glue", **{"s3.endpoint": moto_endpoint_url, "warehouse": f"s3://{BUCKET_NAME}", **properties}) + catalog.create_namespace(namespace=database_name) + return catalog + + +def _glue_catalog_with_replaced_client(moto_endpoint_url: str, database_name: str) -> GlueCatalog: + """Create a Glue catalog whose client is replaced after it was created.""" + catalog = _glue_catalog(moto_endpoint_url, database_name) + catalog.glue = boto3.client("glue", region_name="us-east-1") + return catalog + + +def _other_writer(catalog: GlueCatalog) -> GlueCatalog: + """Return another catalog for the same Glue tables, with its own client.""" + return GlueCatalog("glue", **catalog.properties) + + +class _RawResponse(BytesIO): + def stream(self, **kwargs: Any) -> Iterator[bytes]: + yield self.read() + + +def _glue_error_response(request: AWSPreparedRequest, status: int, code: str) -> AWSResponse: + """Return a Glue error response to the request, as Glue would send it.""" + body = json.dumps({"__type": code, "message": "Answered by the test"}).encode() + return AWSResponse(request.url, status, {}, _RawResponse(body)) + + +def _raise_read_timeout(request: AWSPreparedRequest) -> AWSResponse: + raise ReadTimeoutError(endpoint_url=request.url) + + +def _answer_attempt( + catalog: GlueCatalog, + operation: str, + answer: Callable[[AWSPreparedRequest], AWSResponse], + attempt: int = 1, + before_answer: Callable[[], None] | None = None, +) -> None: + """Answer an attempt of the next request for the operation in place of Glue, which doesn't receive it.""" + sent = 0 + + def before_send(request: AWSPreparedRequest, **kwargs: Any) -> AWSResponse | None: + nonlocal sent + sent += 1 + if sent != attempt: + return None + if before_answer is not None: + before_answer() + response = answer(request) + # Moto handles every request sent to an AWS endpoint, including one that is answered here + request.url = "https://answered.invalid/" + return response + + catalog.glue.meta.events.register_first(f"before-send.glue.{operation}", before_send) + + +def _apply_then_time_out(operation: str) -> Callable[[AWSPreparedRequest], AWSResponse]: + """Return an answer that has Glue apply the request, and then loses the response to a read timeout.""" + + def answer(request: AWSPreparedRequest) -> AWSResponse: + getattr(boto3.client("glue", region_name="us-east-1"), operation)(**json.loads(request.body)) + raise ReadTimeoutError(endpoint_url=request.url) + + return answer + + +def _server_error(request: AWSPreparedRequest) -> AWSResponse: + return _glue_error_response(request, 500, "InternalServiceException") + + +def _throttling(request: AWSPreparedRequest) -> AWSResponse: + return _glue_error_response(request, 400, "ThrottlingException") + + +# Answers that don't show whether Glue applied the request +INCONCLUSIVE_GLUE_ANSWERS = [ + pytest.param(_raise_read_timeout, id="read-timeout"), + pytest.param(_server_error, id="server-error"), + pytest.param(lambda request: _glue_error_response(request, 400, "OperationTimeoutException"), id="operation-timeout"), + pytest.param(lambda request: _glue_error_response(request, 400, "RequestTimeoutException"), id="request-timeout"), +] + + @mock_aws def test_create_table_with_database_location( _glue: boto3.client, @@ -1130,6 +1259,618 @@ def test_commit_overwrite_table_snapshot_properties( assert len(updated_table_metadata.metadata_log) == 2 +@mock_aws +def test_commit_table_retried_update_that_landed_under_another_commit( + monkeypatch: pytest.MonkeyPatch, + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, +) -> None: + _patch_moto_for_table_versions(monkeypatch) + identifier = (database_name, table_name) + test_catalog = _glue_catalog(moto_endpoint_url, database_name) + table = test_catalog.create_table(identifier, table_schema_simple, properties={"write.metadata.previous-versions-max": "1"}) + + def set_property_on_top() -> None: + # Another writer commits on top of the first attempt, which leaves it only in the metadata log + _other_writer(test_catalog).load_table(identifier).transaction().set_properties(other="value").commit_transaction() + + # The first attempt lands, so Glue rejects the retry because the table moved past its version + _retry_first_attempt(test_catalog, "UpdateTable", before_retry=set_property_on_top) + table.transaction().set_properties(owner="pyiceberg").commit_transaction() + + assert test_catalog.load_table(identifier).properties["owner"] == "pyiceberg" + + +@mock_aws +def test_commit_table_retried_update_that_landed_before_a_timeout( + monkeypatch: pytest.MonkeyPatch, + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, +) -> None: + _patch_moto_for_table_versions(monkeypatch) + identifier = (database_name, table_name) + test_catalog = _glue_catalog(moto_endpoint_url, database_name) + table = test_catalog.create_table(identifier, table_schema_simple) + + # Glue applies the first attempt but its response times out, so Glue rejects the retry because the table moved past + # its version + _answer_attempt(test_catalog, "UpdateTable", _apply_then_time_out("update_table")) + _retry_first_attempt(test_catalog, "UpdateTable") + table.transaction().set_properties(owner="pyiceberg").commit_transaction() + + assert test_catalog.load_table(identifier).properties["owner"] == "pyiceberg" + + +@mock_aws +def test_commit_table_retried_update_that_landed_with_requests_on_another_thread( + monkeypatch: pytest.MonkeyPatch, + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, +) -> None: + _patch_moto_for_table_versions(monkeypatch) + identifier = (database_name, table_name) + test_catalog = _glue_catalog(moto_endpoint_url, database_name) + table = test_catalog.create_table(identifier, table_schema_simple) + update_table = test_catalog.glue.update_table + + with ThreadPoolExecutor(max_workers=1) as executor: + # A client that sends requests from another thread leaves the record of attempts empty + monkeypatch.setattr(test_catalog.glue, "update_table", lambda **kwargs: executor.submit(update_table, **kwargs).result()) + # The first attempt lands, so Glue rejects the retry because the table moved past its version + _retry_first_attempt(test_catalog, "UpdateTable") + table.transaction().set_properties(owner="pyiceberg").commit_transaction() + + assert test_catalog.load_table(identifier).properties["owner"] == "pyiceberg" + + +@mock_aws +def test_commit_table_retried_append_whose_snapshot_was_expired( + monkeypatch: pytest.MonkeyPatch, + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, +) -> None: + _patch_moto_for_table_versions(monkeypatch) + identifier = (database_name, table_name) + test_catalog = _glue_catalog(moto_endpoint_url, database_name) + table = test_catalog.create_table(identifier, table_schema_simple) + df = pa.Table.from_pylist([{"foo": "foo_val", "bar": 1, "baz": False}], schema=schema_to_pyarrow(table_schema_simple)) + + def append_on_top_and_expire() -> None: + # The other writer's snapshot still references the manifest of the snapshot it expires + other_table = _other_writer(test_catalog).load_table(identifier) + landed_snapshot_id = other_table.metadata.current_snapshot_id + assert landed_snapshot_id is not None + other_table.append(df) + other_table.maintenance.expire_snapshots().by_id(landed_snapshot_id).commit() + + # The first attempt lands, so Glue rejects the retry because the table moved past its version + _retry_first_attempt(test_catalog, "UpdateTable", before_retry=append_on_top_and_expire) + table.append(df) + + assert test_catalog.load_table(identifier).scan().to_arrow().num_rows == 2 + + +@mock_aws +def test_commit_table_retried_append_that_left_the_metadata_log_has_unknown_state( + monkeypatch: pytest.MonkeyPatch, + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, +) -> None: + _patch_moto_for_table_versions(monkeypatch) + identifier = (database_name, table_name) + test_catalog = _glue_catalog(moto_endpoint_url, database_name) + table = test_catalog.create_table(identifier, table_schema_simple, properties={"write.metadata.previous-versions-max": "1"}) + df = pa.Table.from_pylist([{"foo": "foo_val", "bar": 1, "baz": False}], schema=schema_to_pyarrow(table_schema_simple)) + + def append_on_top_and_expire() -> None: + # Two commits on top of the first attempt push it out of the metadata log + other_table = _other_writer(test_catalog).load_table(identifier) + landed_snapshot_id = other_table.metadata.current_snapshot_id + assert landed_snapshot_id is not None + other_table.append(df) + other_table.maintenance.expire_snapshots().by_id(landed_snapshot_id).commit() + + # The first attempt lands, so Glue rejects the retry because the table moved past its version + _retry_first_attempt(test_catalog, "UpdateTable", before_retry=append_on_top_and_expire) + with pytest.raises(CommitStateUnknownException): + table.append(df) + + assert test_catalog.load_table(identifier).scan().to_arrow().num_rows == 2 + + +@mock_aws +def test_commit_table_retried_append_after_rename_and_register_of_base_has_unknown_state( + monkeypatch: pytest.MonkeyPatch, + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, +) -> None: + _patch_moto_for_table_versions(monkeypatch) + identifier = (database_name, table_name) + renamed_identifier = (database_name, f"{table_name}_renamed") + test_catalog = _glue_catalog(moto_endpoint_url, database_name) + table = test_catalog.create_table(identifier, table_schema_simple) + base_metadata_location = table.metadata_location + df = pa.Table.from_pylist([{"foo": "foo_val", "bar": 1, "baz": False}], schema=schema_to_pyarrow(table_schema_simple)) + + def rename_and_register_base() -> None: + # The first attempt moves to the renamed table, and the base comes back without it under the original name + other_writer = _other_writer(test_catalog) + other_writer.rename_table(identifier, renamed_identifier) + registered = other_writer.register_table(identifier, base_metadata_location) + registered.transaction().set_properties(other="value").commit_transaction() + + # The first attempt lands, so Glue rejects the retry because the table moved past its version + _retry_first_attempt(test_catalog, "UpdateTable", before_retry=rename_and_register_base) + with pytest.raises(CommitStateUnknownException): + table.append(df) + + assert test_catalog.load_table(renamed_identifier).scan().to_arrow().num_rows == 1 + + +@mock_aws +def test_commit_table_retried_update_with_failed_status_check_has_unknown_state( + monkeypatch: pytest.MonkeyPatch, + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, +) -> None: + _patch_moto_for_table_versions(monkeypatch) + identifier = (database_name, table_name) + test_catalog = _glue_catalog(moto_endpoint_url, database_name) + table = test_catalog.create_table(identifier, table_schema_simple) + + def drop_table(**kwargs: Any) -> None: + _other_writer(test_catalog).drop_table(identifier) + + # The first attempt lands, so Glue rejects the retry, and the table is dropped before the commit status is checked + _retry_first_attempt(test_catalog, "UpdateTable") + test_catalog.glue.meta.events.register("after-call.glue.UpdateTable", drop_table) + + with pytest.raises(CommitStateUnknownException): + table.transaction().set_properties(owner="pyiceberg").commit_transaction() + + +@mock_aws +def test_commit_table_conflict_without_retry_raises_commit_failed( + monkeypatch: pytest.MonkeyPatch, + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, +) -> None: + _patch_moto_for_table_versions(monkeypatch) + identifier = (database_name, table_name) + test_catalog = _glue_catalog(moto_endpoint_url, database_name) + table = test_catalog.create_table(identifier, table_schema_simple) + + def set_property_concurrently(**kwargs: Any) -> None: + _other_writer(test_catalog).load_table(identifier).transaction().set_properties(other="value").commit_transaction() + + def drop_table(**kwargs: Any) -> None: + _other_writer(test_catalog).drop_table(identifier) + + test_catalog.glue.meta.events.register("before-call.glue.UpdateTable", set_property_concurrently) + # A check would fail on the dropped table, but a rejection of a request sent once proves it did not land + test_catalog.glue.meta.events.register("after-call.glue.UpdateTable", drop_table) + + with pytest.raises(CommitFailedException, match="Glue detected concurrent update"): + table.transaction().set_properties(owner="pyiceberg").commit_transaction() + + +@mock_aws +@pytest.mark.parametrize( + "glue_catalog", + [ + pytest.param(_glue_catalog, id="catalog-client"), + pytest.param( + lambda url, database: _glue_catalog(url, database, client=boto3.client("glue", region_name="us-east-1")), + id="user-client", + ), + pytest.param(_glue_catalog_with_replaced_client, id="replaced-client"), + ], +) +def test_commit_table_append_that_conflicts_after_throttling( + monkeypatch: pytest.MonkeyPatch, + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, + glue_catalog: Callable[[str, str], GlueCatalog], +) -> None: + _patch_moto_for_table_versions(monkeypatch) + identifier = (database_name, table_name) + test_catalog = glue_catalog(moto_endpoint_url, database_name) + table = test_catalog.create_table(identifier, table_schema_simple) + df = pa.Table.from_pylist([{"foo": "foo_val", "bar": 1, "baz": False}], schema=schema_to_pyarrow(table_schema_simple)) + + def append_concurrently() -> None: + _other_writer(test_catalog).load_table(identifier).append(df) + + # Glue throttles the first attempt while another writer appends, then rejects the retry because the table moved past + # its version. Glue rejected both attempts, so the transaction retries the commit. + _answer_attempt(test_catalog, "UpdateTable", _throttling, before_answer=append_concurrently) + _retry_first_attempt(test_catalog, "UpdateTable") + table.append(df) + + assert test_catalog.load_table(identifier).scan().to_arrow().num_rows == 2 + + +@mock_aws +def test_commit_table_update_that_conflicts_after_server_error_has_unknown_state( + monkeypatch: pytest.MonkeyPatch, + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, +) -> None: + _patch_moto_for_table_versions(monkeypatch) + identifier = (database_name, table_name) + test_catalog = _glue_catalog(moto_endpoint_url, database_name) + table = test_catalog.create_table(identifier, table_schema_simple) + + def set_property_concurrently() -> None: + _other_writer(test_catalog).load_table(identifier).transaction().set_properties(other="value").commit_transaction() + + # Glue fails the first attempt with a server error while another writer commits, then rejects the retry. The first + # attempt may have landed, and the update not being in the table doesn't show that it didn't. + _answer_attempt(test_catalog, "UpdateTable", _server_error, before_answer=set_property_concurrently) + _retry_first_attempt(test_catalog, "UpdateTable") + + with pytest.raises(CommitStateUnknownException): + table.transaction().set_properties(owner="pyiceberg").commit_transaction() + + assert "owner" not in test_catalog.load_table(identifier).properties + + +@mock_aws +def test_commit_table_update_rejected_as_existing_after_server_error_has_unknown_state( + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, +) -> None: + identifier = (database_name, table_name) + test_catalog = _glue_catalog(moto_endpoint_url, database_name) + table = test_catalog.create_table(identifier, table_schema_simple) + + # Glue fails the first attempt with a server error, then rejects the retry because a table exists. An ambiguous update + # stays unknown, since the fallback for an existing table only applies to creates. + _answer_attempt(test_catalog, "UpdateTable", _server_error) + _answer_attempt( + test_catalog, "UpdateTable", lambda request: _glue_error_response(request, 400, "AlreadyExistsException"), attempt=2 + ) + _retry_first_attempt(test_catalog, "UpdateTable") + + with pytest.raises(CommitStateUnknownException): + table.transaction().set_properties(owner="pyiceberg").commit_transaction() + + +@mock_aws +def test_commit_table_with_invalid_skip_archive_raises_value_error( + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, +) -> None: + identifier = (database_name, table_name) + test_catalog = _glue_catalog(moto_endpoint_url, database_name, **{"glue.skip-archive": "not-a-boolean"}) + table = test_catalog.create_table(identifier, table_schema_simple) + + # The property is read before the update is sent + with pytest.raises(ValueError): + table.transaction().set_properties(owner="pyiceberg").commit_transaction() + + +@mock_aws +@pytest.mark.parametrize("answer", INCONCLUSIVE_GLUE_ANSWERS) +def test_commit_table_retried_update_that_failed_after_being_applied( + monkeypatch: pytest.MonkeyPatch, + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, + answer: Callable[[AWSPreparedRequest], AWSResponse], +) -> None: + _patch_moto_for_table_versions(monkeypatch) + identifier = (database_name, table_name) + test_catalog = _glue_catalog(moto_endpoint_url, database_name, **{"glue.max-retries": 1}) + table = test_catalog.create_table(identifier, table_schema_simple) + + # The first attempt lands, and the retry fails without showing whether Glue applied it + _retry_first_attempt(test_catalog, "UpdateTable") + _answer_attempt(test_catalog, "UpdateTable", answer, attempt=2) + table.transaction().set_properties(owner="pyiceberg").commit_transaction() + + assert test_catalog.load_table(identifier).properties["owner"] == "pyiceberg" + + +@mock_aws +@pytest.mark.parametrize("answer", INCONCLUSIVE_GLUE_ANSWERS) +def test_commit_table_update_that_failed_without_being_applied_has_unknown_state( + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, + answer: Callable[[AWSPreparedRequest], AWSResponse], +) -> None: + identifier = (database_name, table_name) + test_catalog = _glue_catalog(moto_endpoint_url, database_name, **{"glue.max-retries": 0}) + table = test_catalog.create_table(identifier, table_schema_simple) + + # Glue may still apply an update that failed without being rejected + _answer_attempt(test_catalog, "UpdateTable", answer) + with pytest.raises(CommitStateUnknownException): + table.transaction().set_properties(owner="pyiceberg").commit_transaction() + + assert "owner" not in test_catalog.load_table(identifier).properties + + +@mock_aws +@pytest.mark.parametrize( + "create", + [ + pytest.param(lambda catalog, identifier, schema: catalog.create_table(identifier, schema), id="create-table"), + pytest.param( + lambda catalog, identifier, schema: catalog.create_table_transaction(identifier, schema).commit_transaction(), + id="create-table-transaction", + ), + ], +) +def test_create_table_retried_request_that_landed( + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, + create: Callable[[GlueCatalog, Identifier, Schema], Table], +) -> None: + identifier = (database_name, table_name) + test_catalog = _glue_catalog(moto_endpoint_url, database_name) + + # The first attempt creates the table, so Glue rejects the retry because the table exists + _retry_first_attempt(test_catalog, "CreateTable") + table = create(test_catalog, identifier, table_schema_simple) + + assert test_catalog.load_table(identifier).metadata_location == table.metadata_location + + +@mock_aws +def test_create_table_retried_request_that_landed_before_a_timeout( + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, +) -> None: + identifier = (database_name, table_name) + test_catalog = _glue_catalog(moto_endpoint_url, database_name) + + # Glue applies the first attempt but its response times out, so Glue rejects the retry because the table exists + _answer_attempt(test_catalog, "CreateTable", _apply_then_time_out("create_table")) + _retry_first_attempt(test_catalog, "CreateTable") + table = test_catalog.create_table(identifier, table_schema_simple) + + assert test_catalog.load_table(identifier).metadata_location == table.metadata_location + + +@mock_aws +def test_create_table_retried_request_whose_location_left_the_metadata_log( + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, +) -> None: + identifier = (database_name, table_name) + test_catalog = _glue_catalog(moto_endpoint_url, database_name) + + def set_properties_on_top() -> None: + # Two commits on top of the new table push its first metadata location out of the metadata log + other_table = _other_writer(test_catalog).load_table(identifier) + other_table.transaction().set_properties(first="value").commit_transaction() + other_table.transaction().set_properties(second="value").commit_transaction() + + # The first attempt creates the table, so Glue rejects the retry because the table exists + _retry_first_attempt(test_catalog, "CreateTable", before_retry=set_properties_on_top) + table = test_catalog.create_table(identifier, table_schema_simple, properties={"write.metadata.previous-versions-max": "1"}) + + assert test_catalog.load_table(identifier).metadata.table_uuid == table.metadata.table_uuid + + +@mock_aws +def test_create_table_retried_request_with_failed_status_check_has_unknown_state( + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, +) -> None: + test_catalog = _glue_catalog(moto_endpoint_url, database_name) + + def deny_get_table(**kwargs: Any) -> None: + raise ClientError( + {"Error": {"Code": "AccessDeniedException", "Message": "Denied"}, "ResponseMetadata": {"HTTPStatusCode": 400}}, + "GetTable", + ) + + # The first attempt creates the table, so Glue rejects the retry, and the commit status can't be checked + _retry_first_attempt(test_catalog, "CreateTable") + test_catalog.glue.meta.events.register("before-call.glue.GetTable", deny_get_table) + + with pytest.raises(CommitStateUnknownException): + test_catalog.create_table((database_name, table_name), table_schema_simple) + + +@mock_aws +@pytest.mark.parametrize( + "create_other_table", + [ + pytest.param(lambda catalog, identifier, schema: catalog.create_table(identifier, schema), id="iceberg-table"), + pytest.param( + lambda catalog, identifier, schema: boto3.client("glue", region_name="us-east-1").create_table( + DatabaseName=identifier[0], TableInput={"Name": identifier[1]} + ), + id="glue-table", + ), + ], +) +def test_create_table_that_conflicts_after_server_error_raises_already_exists( + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, + create_other_table: Callable[[GlueCatalog, Identifier, Schema], object], +) -> None: + identifier = (database_name, table_name) + test_catalog = _glue_catalog(moto_endpoint_url, database_name) + + def create_table_concurrently() -> None: + create_other_table(_other_writer(test_catalog), identifier, table_schema_simple) + + # Glue fails the first attempt with a server error while another writer creates the table, then rejects the retry + # because the table exists. The table isn't this one, so it already existed or replaced this one. + _answer_attempt(test_catalog, "CreateTable", _server_error, before_answer=create_table_concurrently) + _retry_first_attempt(test_catalog, "CreateTable") + + with pytest.raises(TableAlreadyExistsError): + test_catalog.create_table(identifier, table_schema_simple) + + +@mock_aws +def test_create_table_if_not_exists_that_conflicts_after_server_error( + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, +) -> None: + identifier = (database_name, table_name) + test_catalog = _glue_catalog(moto_endpoint_url, database_name) + other_tables: list[Table] = [] + + def create_table_concurrently() -> None: + other_tables.append(_other_writer(test_catalog).create_table(identifier, table_schema_simple)) + + # Another writer creates the table while Glue fails the first attempt with a server error + _answer_attempt(test_catalog, "CreateTable", _server_error, before_answer=create_table_concurrently) + _retry_first_attempt(test_catalog, "CreateTable") + table = test_catalog.create_table_if_not_exists(identifier, table_schema_simple) + + assert table.metadata_location == other_tables[0].metadata_location + + +@mock_aws +def test_create_table_that_failed_without_being_applied_has_unknown_state( + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, +) -> None: + identifier = (database_name, table_name) + test_catalog = _glue_catalog(moto_endpoint_url, database_name, **{"glue.max-retries": 0}) + + # Glue may still apply a create that failed without being rejected + _answer_attempt(test_catalog, "CreateTable", _raise_read_timeout) + with pytest.raises(CommitStateUnknownException): + test_catalog.create_table(identifier, table_schema_simple) + + assert not test_catalog.table_exists(identifier) + + +@mock_aws +def test_create_table_rejected_by_client_validation( + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, +) -> None: + test_catalog = _glue_catalog(moto_endpoint_url, database_name) + + # The client validates the request before sending it + with pytest.raises(ParamValidationError): + test_catalog.create_table((database_name, table_name), table_schema_simple, properties={"": "value"}) + + +@mock_aws +def test_rename_table_that_conflicts_after_server_error_raises_already_exists( + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, +) -> None: + from_identifier = (database_name, table_name) + to_identifier = (database_name, f"{table_name}_renamed") + test_catalog = _glue_catalog(moto_endpoint_url, database_name) + test_catalog.create_table(from_identifier, table_schema_simple) + + def rename_table_concurrently() -> None: + _other_writer(test_catalog).rename_table(from_identifier, to_identifier) + + # Another writer renames the table to the same name during the first attempt. Its table has the metadata that this + # rename would create, so finding that metadata doesn't show that this rename created the table. + _answer_attempt(test_catalog, "CreateTable", _server_error, before_answer=rename_table_concurrently) + _retry_first_attempt(test_catalog, "CreateTable") + + with pytest.raises(TableAlreadyExistsError): + test_catalog.rename_table(from_identifier, to_identifier) + + assert not test_catalog.table_exists(from_identifier) + assert test_catalog.table_exists(to_identifier) + + +@mock_aws +def test_create_table_s3tables_retried_update_that_landed( + monkeypatch: pytest.MonkeyPatch, + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_nested: Schema, + database_name: str, + table_name: str, +) -> None: + _patch_moto_for_s3tables(monkeypatch) + _patch_moto_for_table_versions(monkeypatch) + identifier = (database_name, table_name) + test_catalog = GlueCatalog("s3tables", client=None, **{"s3.endpoint": moto_endpoint_url}) + _create_s3tables_database(test_catalog, database_name) + + # The update that adds the metadata lands, so Glue rejects the retry because the table moved past its version + _retry_first_attempt(test_catalog, "UpdateTable") + table = test_catalog.create_table(identifier, table_schema_nested) + + assert test_catalog.load_table(identifier).metadata_location == table.metadata_location + + @mock_aws @pytest.mark.parametrize("format_version", [1, 2]) def test_create_table_transaction(