diff --git a/pyiceberg/catalog/glue.py b/pyiceberg/catalog/glue.py index 9ba8775747..a65e12b71c 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 +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 from typing_extensions import override from pyiceberg.catalog import ( @@ -43,6 +47,7 @@ ) from pyiceberg.exceptions import ( CommitFailedException, + CommitStateUnknownException, NamespaceAlreadyExistsError, NamespaceNotEmptyError, NoSuchIcebergTableError, @@ -343,6 +348,33 @@ 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 update whose commit status is being checked +_glue_update_attempts: ContextVar[list[bool] | None] = ContextVar("_glue_update_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", + "ConcurrentModificationException", + "EntityNotFoundException", + "InvalidInputException", + "ResourceNumberLimitExceededException", + "ThrottlingException", + } +) + + +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 update whose commit status is being checked.""" + if (attempts := _glue_update_attempts.get()) is not None: + attempts.append(response is not None and _is_rejection(response[1])) + + class GlueCatalog(MetastoreCatalog): glue: "GlueClient" @@ -395,6 +427,10 @@ 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) + self.glue.meta.events.register( + "needs-retry.glue.UpdateTable", _record_attempt, unique_id="pyiceberg-record-update-attempt" + ) + 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") @@ -439,14 +475,75 @@ def _create_glue_table(self, database_name: str, table_name: str, table_input: " 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: + @contextmanager + def _check_commit_status(self, database_name: str, table_name: str, metadata_location: str) -> Iterator[None]: + """Check whether a Glue update that fails was committed anyway. + + Glue may have applied an update 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 because the table is no longer at the expected version. So the error is only raised as is + if Glue rejected every attempt. Otherwise, the update succeeds if the table confirms it. + + Raises: + CommitStateUnknownException: If Glue may have applied the update, but the table doesn't confirm it. + """ + attempts: list[bool] = [] + token = _glue_update_attempts.set(attempts) 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, + yield + except Exception as e: + # The handler runs after every attempt, including the last, so when a rejection ends the request, every + # attempt has been recorded. An empty record, such as from a client without the handler, doesn't show that + # Glue rejected anything. + if isinstance(e, ClientError) and _is_rejection(e.response) and attempts and all(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, metadata_location) + 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: + # A landed update 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_update_attempts.reset(token) + + def _is_committed(self, database_name: str, table_name: str, metadata_location: str) -> bool: + """Return whether the metadata location is the table's current one or in its metadata log.""" + current_location = self._get_glue_table(database_name, table_name).get("Parameters", {}).get(METADATA_LOCATION) + if current_location == metadata_location: + return True + if current_location is None: + return False + metadata = FromInputFile.table_metadata(self._load_file_io(location=current_location).new_input(current_location)) + return any(entry.metadata_file == metadata_location for entry in metadata.metadata_log) + + def _update_glue_table( + self, + database_name: str, + table_name: str, + table_input: "TableInputTypeDef", + version_id: str, + metadata_location: str, + ) -> None: + skip_archive = property_as_bool(self.properties, GLUE_SKIP_ARCHIVE, GLUE_SKIP_ARCHIVE_DEFAULT) + try: + with self._check_commit_status(database_name, table_name, metadata_location): + 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: @@ -559,6 +656,7 @@ def _create_table_s3tables( table_name=table_name, table_input=table_input, version_id=version_id, + metadata_location=staged_table.metadata_location, ) except Exception: # Clean up the table created in step 1. @@ -689,6 +787,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 update to Glue 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 +841,7 @@ def commit_table( table_name=table_name, table_input=update_table_input, version_id=glue_table_version_id, + metadata_location=updated_staged_table.metadata_location, ) else: # table does not exist, create the table diff --git a/tests/catalog/test_glue.py b/tests/catalog/test_glue.py index 5f1ecab2c7..3ae67a4dbb 100644 --- a/tests/catalog/test_glue.py +++ b/tests/catalog/test_glue.py @@ -14,18 +14,26 @@ # 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 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 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, @@ -98,6 +106,93 @@ 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, before_retry: Callable[[], None] | None = None) -> None: + """Make the client send the next update a second time, as when the response to its first attempt 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("needs-retry.glue.UpdateTable", needs_retry) + + +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 _answer_first_attempt( + catalog: GlueCatalog, + answer: Callable[[AWSPreparedRequest], AWSResponse], + before_answer: Callable[[], None] | None = None, +) -> None: + """Answer the first attempt of the next update in place of Glue.""" + answered = False + + def before_send(request: AWSPreparedRequest, **kwargs: Any) -> AWSResponse | None: + nonlocal answered + if answered: + return None + answered = True + 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("before-send.glue.UpdateTable", before_send) + + +def _raise_read_timeout(request: AWSPreparedRequest) -> AWSResponse: + raise ReadTimeoutError(endpoint_url=request.url) + + +def _server_error(request: AWSPreparedRequest) -> AWSResponse: + return _glue_error_response(request, 500, "InternalServiceException") + + +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 _other_writer(catalog: GlueCatalog) -> GlueCatalog: + """Return another catalog for the same Glue tables, with its own client.""" + return GlueCatalog("glue", **catalog.properties) + + @mock_aws def test_create_table_with_database_location( _glue: boto3.client, @@ -1130,6 +1225,244 @@ def test_commit_overwrite_table_snapshot_properties( assert len(updated_table_metadata.metadata_log) == 2 +@mock_aws +@pytest.mark.parametrize( + "fail", [pytest.param(_raise_read_timeout, id="read-timeout"), pytest.param(_server_error, id="server-error")] +) +def test_commit_table_retried_update_that_landed_succeeds( + monkeypatch: pytest.MonkeyPatch, + _bucket_initialize: None, + moto_endpoint_url: str, + table_schema_simple: Schema, + database_name: str, + table_name: str, + fail: Callable[[AWSPreparedRequest], AWSResponse], +) -> 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 apply_then_fail(request: AWSPreparedRequest) -> AWSResponse: + boto3.client("glue", region_name="us-east-1").update_table(**json.loads(request.body)) + return fail(request) + + # Glue applies the first attempt but its response is lost, so Glue rejects the retry because the table moved past + # its version + _answer_first_attempt(test_catalog, apply_then_fail) + _retry_first_attempt(test_catalog) + 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_succeeds( + 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, 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, but the table no longer shows it. Its files are kept. + _retry_first_attempt(test_catalog, 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 +@pytest.mark.parametrize( + "answer", + [ + 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"), + ], +) +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_first_attempt(test_catalog, 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 +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) + 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", + ), + ], +) +def test_commit_table_append_that_conflicts_after_throttling_is_retried( + 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_first_attempt( + test_catalog, lambda request: _glue_error_response(request, 400, "ThrottlingException"), before_answer=append_concurrently + ) + _retry_first_attempt(test_catalog) + table.append(df) + + assert test_catalog.load_table(identifier).scan().to_arrow().num_rows == 2 + + +@mock_aws +def test_commit_table_retried_update_that_landed_without_attempt_record_succeeds( + 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) + # A client assigned after the catalog was created doesn't record whether Glue rejected each attempt + test_catalog.glue = boto3.client("glue", region_name="us-east-1") + + # The first attempt lands, so Glue rejects the retry because the table moved past its version + _retry_first_attempt(test_catalog) + table.transaction().set_properties(owner="pyiceberg").commit_transaction() + + assert test_catalog.load_table(identifier).properties["owner"] == "pyiceberg" + + @mock_aws @pytest.mark.parametrize("format_version", [1, 2]) def test_create_table_transaction(