Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 106 additions & 6 deletions pyiceberg/catalog/glue.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 (
Expand All @@ -43,6 +47,7 @@
)
from pyiceberg.exceptions import (
CommitFailedException,
CommitStateUnknownException,
NamespaceAlreadyExistsError,
NamespaceNotEmptyError,
NoSuchIcebergTableError,
Expand Down Expand Up @@ -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"

Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
Loading