From d68b464764c1edbf3653e1ce4dfcb03fc2ceeccb Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Sat, 21 Nov 2026 23:28:12 +0900 Subject: [PATCH 01/10] Make the filesystem package independent of the rest of PyAthena (GH-1388) The filesystem now imports nothing from PyAthena outside pyathena/filesystem/, so that it can be released on its own later. - pyathena.filesystem.s3_retry owns the retry policy (S3RetryConfig, any object with the attributes of RetryConfig is accepted), the retry function, and its own stop scopes. pyathena.util.stop_retries_on() and unstoppable_retries() also enter the filesystem's scopes, so closing a cursor still stops the S3 retries of its reads. - pyathena.filesystem.util keeps the filesystem's own override, user agent, and create_in_thread(). - s3_filesystem() moves to pyathena.fs; pyathena.filesystem.s3_filesystem stays as a deprecated copy that warns until the next major version. - A test fails when a module of the package imports PyAthena outside it. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 3 +- benchmarks/pyathena_bench/filesystem.py | 2 +- docs/api/filesystem.rst | 18 +- docs/filesystem.md | 19 +- docs/usage.md | 2 +- pyathena/filesystem/__init__.py | 34 +- pyathena/filesystem/reader.py | 2 +- pyathena/filesystem/s3.py | 65 ++-- pyathena/filesystem/s3_async.py | 16 +- pyathena/filesystem/s3_core.py | 39 ++- pyathena/filesystem/s3_executor.py | 26 +- pyathena/filesystem/s3_object.py | 2 +- pyathena/filesystem/s3_path.py | 2 +- pyathena/filesystem/s3_retry.py | 318 ++++++++++++++++++ pyathena/filesystem/s3_writer.py | 8 +- pyathena/filesystem/util.py | 180 ++++++++++ pyathena/fs.py | 65 ++++ pyathena/pandas/result_set.py | 2 +- pyathena/polars/result_set.py | 2 +- pyathena/s3fs/result_set.py | 2 +- pyathena/util.py | 15 +- pyproject.toml | 2 +- .../filesystem/test_fsspec_conformance.py | 2 +- tests/pyathena/filesystem/test_init.py | 21 +- tests/pyathena/filesystem/test_package.py | 62 ++++ tests/pyathena/filesystem/test_s3.py | 6 +- tests/pyathena/filesystem/test_s3_async.py | 5 +- tests/pyathena/filesystem/test_s3_executor.py | 3 +- tests/pyathena/filesystem/test_s3_retry.py | 249 ++++++++++++++ tests/pyathena/test_connection.py | 2 +- tests/pyathena/test_util.py | 38 +++ tests/pyathena/util.py | 13 +- 32 files changed, 1107 insertions(+), 118 deletions(-) create mode 100644 pyathena/filesystem/s3_retry.py create mode 100644 pyathena/filesystem/util.py create mode 100644 pyathena/fs.py create mode 100644 tests/pyathena/filesystem/test_package.py create mode 100644 tests/pyathena/filesystem/test_s3_retry.py diff --git a/AGENTS.md b/AGENTS.md index 1b9605742..d9a1d1945 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -132,6 +132,7 @@ Each cursor type lives in its own subpackage (`pandas/`, `arrow/`, `polars/`, `s - Match `s3fs` library behavior where possible (users migrate from it) - Use `delimiter="/"` in S3 API calls to minimize requests - Handle edge cases: empty paths, trailing slashes, bucket-only paths +- Import nothing from PyAthena outside `pyathena/filesystem/`; PyAthena-side helpers such as `pyathena.fs.s3_filesystem()` live outside the package (`tests/pyathena/filesystem/test_package.py` checks it) ### Version Management @@ -140,4 +141,4 @@ Versions are derived from git tags via `hatch-vcs` — never edit `pyathena/_ver ### Google-style Docstrings Follow the [docstring rules](docs/contributing.md#write-docstrings), which `just lint` checks with ruff's pydocstyle rules for `pyathena/`. -Mark overrides with `pyathena.util.override` instead of repeating the base method's docstring. +Mark overrides with `pyathena.util.override` (`pyathena.filesystem.util.override` in `pyathena/filesystem/`) instead of repeating the base method's docstring. diff --git a/benchmarks/pyathena_bench/filesystem.py b/benchmarks/pyathena_bench/filesystem.py index a10354585..82125650d 100644 --- a/benchmarks/pyathena_bench/filesystem.py +++ b/benchmarks/pyathena_bench/filesystem.py @@ -19,7 +19,7 @@ from botocore.config import Config from pyathena import connect -from pyathena.filesystem import s3_filesystem +from pyathena.fs import s3_filesystem from pyathena.filesystem.s3 import S3FileSystem from pyathena.filesystem.s3_async import AioS3FileSystem from pyathena.util import parse_output_location diff --git a/docs/api/filesystem.rst b/docs/api/filesystem.rst index 3b7dc202d..b17354c2f 100644 --- a/docs/api/filesystem.rst +++ b/docs/api/filesystem.rst @@ -16,7 +16,7 @@ This section covers S3 filesystem integration and object management. S3 FileSystem ------------- -.. autofunction:: pyathena.filesystem.s3_filesystem +.. autofunction:: pyathena.fs.s3_filesystem .. autoclass:: pyathena.filesystem.s3.S3FileSystem :members: @@ -39,6 +39,22 @@ Async S3 FileSystem .. autoclass:: pyathena.filesystem.s3_async.AioS3StreamedFile :members: +Retries +------- + +.. autoclass:: pyathena.filesystem.s3_retry.S3RetryConfig + :members: + +.. autoclass:: pyathena.filesystem.s3_retry.RetryPolicy + +.. autofunction:: pyathena.filesystem.s3_retry.retry_api_call + +.. autofunction:: pyathena.filesystem.s3_retry.stop_retries_on + +.. autofunction:: pyathena.filesystem.s3_retry.unstoppable_retries + +.. autofunction:: pyathena.filesystem.s3_retry.raise_if_stopped + Read-ahead Stream ----------------- diff --git a/docs/filesystem.md b/docs/filesystem.md index b5954d306..40b3396cb 100644 --- a/docs/filesystem.md +++ b/docs/filesystem.md @@ -57,13 +57,13 @@ arguments: import boto3 from pyathena import connect -from pyathena.filesystem import s3_filesystem from pyathena.filesystem.s3 import S3FileSystem +from pyathena.fs import s3_filesystem fs = s3_filesystem(connect(s3_staging_dir="s3://YOUR_S3_BUCKET/path/to/", region_name="us-west-2")) -# Or with a boto3 S3 client, and optionally a pyathena.util.RetryConfig. +# Or with a boto3 S3 client, and optionally a retry policy (see "Retries"). fs = S3FileSystem(client=boto3.client("s3", region_name="us-west-2")) # Or with direct credentials (s3fs-compatible arguments). @@ -86,7 +86,9 @@ arguments of the filesystem, and `AioS3FileSystem` as its second argument. The `connection` argument of `S3FileSystem` and `AioS3FileSystem` is deprecated and emits a `DeprecationWarning`; it will be removed in the next major version. It is -subject to the same restrictions as `client`. +subject to the same restrictions as `client`. `pyathena.filesystem.s3_filesystem()` is a +deprecated name of `pyathena.fs.s3_filesystem()` and emits a `DeprecationWarning`; it +will be removed in the next major version. The S3 client computes checksums of uploads and validates those of downloads by botocore's `request_checksum_calculation` and `response_checksum_validation` options, @@ -511,9 +513,10 @@ S3 also answers `403` for a key that does not exist. ## Retries -Each request is sent with a `pyathena.util.RetryConfig`: the `retry_config` of the -filesystem, the retry policy of the connection for `s3_filesystem()`, or -`RetryConfig()`. If the `exceptions` of the policy are the default codes +Each request is sent with a retry policy: the `retry_config` of the filesystem, the +retry policy of the connection for `s3_filesystem()`, or `S3RetryConfig()` +(`pyathena.filesystem.s3_retry`). A `pyathena.util.RetryConfig` is accepted as a policy +too, with the same arguments. If the `exceptions` of the policy are the default codes (`THROTTLING_ERROR_CODES`), the requests also retry the S3 error codes `SlowDown`, `ServiceUnavailable`, `InternalError`, and `RequestTimeout` (`S3Core.RETRY_ERROR_CODES`), with the attempts and waits of the policy. That includes a @@ -521,10 +524,10 @@ policy that gives the default codes explicitly. A policy with other `exceptions` as given: ```python -from pyathena.util import RetryConfig +from pyathena.filesystem.s3_retry import S3RetryConfig # Retries only SlowDown, in up to 3 attempts. -fs = S3FileSystem(retry_config=RetryConfig(exceptions=["SlowDown"], attempt=3)) +fs = S3FileSystem(retry_config=S3RetryConfig(exceptions=["SlowDown"], attempt=3)) ``` botocore also retries these errors within each attempt, as the retry mode of the S3 diff --git a/docs/usage.md b/docs/usage.md index 95847bc48..84fa04acc 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -761,7 +761,7 @@ The Glue request does not carry the connection's workgroup; turn the fallback of ## S3 client -A connection builds one S3 client on first use and shares it with the result sets of its cursors, the filesystems created with `pyathena.filesystem.s3_filesystem()`, and the Spark cursors. +A connection builds one S3 client on first use and shares it with the result sets of its cursors, the filesystems created with `pyathena.fs.s3_filesystem()`, and the Spark cursors. The result sets of `Cursor`, `DictCursor`, and their asynchronous versions do not use it, so these cursors build no S3 client. `ArrowCursor`, and `PolarsCursor` for Parquet (`unload=True`) and chunked results, read the query results through their libraries' own S3 clients and use the shared client for their other S3 requests. diff --git a/pyathena/filesystem/__init__.py b/pyathena/filesystem/__init__.py index 86a6e1b1f..8fce953b9 100644 --- a/pyathena/filesystem/__init__.py +++ b/pyathena/filesystem/__init__.py @@ -10,15 +10,13 @@ from __future__ import annotations import logging -from typing import TYPE_CHECKING, Any, TypeVar, overload +import warnings +from typing import Any, TypeVar, overload import fsspec from fsspec import AbstractFileSystem -from pyathena.filesystem.s3 import S3FileSystem - -if TYPE_CHECKING: - from pyathena.connection import Connection +from pyathena.filesystem.s3 import S3FileSystem, _Connection _logger = logging.getLogger(__name__) @@ -26,33 +24,25 @@ @overload -def s3_filesystem(connection: Connection[Any], **kwargs: Any) -> S3FileSystem: ... +def s3_filesystem(connection: _Connection, **kwargs: Any) -> S3FileSystem: ... @overload def s3_filesystem( - connection: Connection[Any], filesystem_class: type[_FileSystemT], **kwargs: Any + connection: _Connection, filesystem_class: type[_FileSystemT], **kwargs: Any ) -> _FileSystemT: ... def s3_filesystem( - connection: Connection[Any], + connection: _Connection, filesystem_class: type[AbstractFileSystem] = S3FileSystem, **kwargs: Any, ) -> AbstractFileSystem: """Create an S3 filesystem with the S3 client and retry policy of a connection. - The filesystem borrows ``connection.s3_client``, which the connection - shares with its result sets, and uses ``connection.retry_config``. A - policy with the default ``exceptions`` also retries the transient S3 error - codes (:attr:`~pyathena.filesystem.s3_core.S3Core.RETRY_ERROR_CODES`). - Closing the filesystem does not close the client. A filesystem created - this way cannot be pickled; see :class:`~pyathena.filesystem.s3.S3FileSystem`. - - Example: - >>> from pyathena import connect - >>> from pyathena.filesystem import s3_filesystem - >>> fs = s3_filesystem(connect(s3_staging_dir="s3://my-bucket/path/")) + Deprecated; use :func:`pyathena.fs.s3_filesystem`, which this function + matches apart from a ``DeprecationWarning``. It will be removed in the + next major version. Args: connection: The PyAthena connection. @@ -64,6 +54,12 @@ def s3_filesystem( Returns: The filesystem. """ + warnings.warn( + "pyathena.filesystem.s3_filesystem is deprecated and will be removed in the next " + "major version. Use pyathena.fs.s3_filesystem.", + DeprecationWarning, + stacklevel=2, + ) return filesystem_class( client=connection.s3_client, retry_config=connection.retry_config, **kwargs ) diff --git a/pyathena/filesystem/reader.py b/pyathena/filesystem/reader.py index 9d49316d5..b4aebb4d5 100644 --- a/pyathena/filesystem/reader.py +++ b/pyathena/filesystem/reader.py @@ -15,7 +15,7 @@ from concurrent.futures import Future, ThreadPoolExecutor, wait from typing import Any -from pyathena.util import override +from pyathena.filesystem.util import override class ReadAheadStream(io.RawIOBase): diff --git a/pyathena/filesystem/s3.py b/pyathena/filesystem/s3.py index 501dafe00..a60415085 100644 --- a/pyathena/filesystem/s3.py +++ b/pyathena/filesystem/s3.py @@ -22,7 +22,7 @@ from datetime import datetime from glob import has_magic from io import BytesIO -from typing import TYPE_CHECKING, Any, BinaryIO, ClassVar, cast +from typing import Any, BinaryIO, ClassVar, Protocol, cast from urllib.parse import unquote_plus import fsspec @@ -38,7 +38,6 @@ from fsspec.spec import AbstractBufferedFile from fsspec.utils import check_contained, isfilelike, other_paths, stringify_path, tokenize -import pyathena from pyathena.filesystem.s3_core import S3Core, S3DeleteBatch, S3DeleteResult from pyathena.filesystem.s3_errors import S3ClientError from pyathena.filesystem.s3_executor import ( @@ -60,14 +59,32 @@ ) from pyathena.filesystem.s3_path import S3Path from pyathena.filesystem.s3_path_pairing import S3PathPairing +from pyathena.filesystem.s3_retry import ( + RetryPolicy, + S3RetryConfig, + raise_if_stopped, + unstoppable_retries, +) from pyathena.filesystem.s3_writer import _S3WriteSession -from pyathena.util import RetryConfig, override, raise_if_stopped, unstoppable_retries - -if TYPE_CHECKING: - from pyathena.connection import Connection +from pyathena.filesystem.util import override, user_agent_extra _logger = logging.getLogger(__name__) + +class _Connection(Protocol): + """The attributes of a PyAthena connection that the deprecated ``connection`` reads.""" + + @property + def s3_client(self) -> BaseClient: + """The S3 client of the connection.""" + ... + + @property + def retry_config(self) -> RetryPolicy: + """The retry policy of the connection.""" + ... + + # The message of the TypeError that a filesystem with an injected client, and # the files that it opens for reading, raise when they are pickled. _UNPICKLABLE_CLIENT_MESSAGE = ( @@ -79,7 +96,7 @@ # The DeprecationWarning of the connection argument of the filesystems. _CONNECTION_DEPRECATION_MESSAGE = ( "The connection argument of {cls} is deprecated and will be removed in the next " - "major version. Use pyathena.filesystem.s3_filesystem(connection), or pass " + "major version. Use pyathena.fs.s3_filesystem(connection), or pass " "client=connection.s3_client and retry_config=connection.retry_config." ) @@ -408,7 +425,7 @@ class S3FileSystem(AbstractFileSystem): def __init__( self, - connection: Connection[Any] | None = None, + connection: _Connection | None = None, default_block_size: int | None = None, default_cache_type: str | None = None, max_workers: int | None = None, @@ -419,20 +436,20 @@ def __init__( *args, batch_size: int | None = None, client: BaseClient | None = None, - retry_config: RetryConfig | None = None, + retry_config: RetryPolicy | None = None, **kwargs, ) -> None: """Create a filesystem for Amazon S3. The filesystem sends its requests with the boto3 S3 client given as ``client``, or with a client that it builds from s3fs-compatible - arguments in ``kwargs``. :func:`pyathena.filesystem.s3_filesystem` + arguments in ``kwargs``. :func:`pyathena.fs.s3_filesystem` creates one with the S3 client and retry policy of a PyAthena connection. Args: connection: Deprecated; use ``client`` and ``retry_config``, or - :func:`pyathena.filesystem.s3_filesystem`. A PyAthena connection + :func:`pyathena.fs.s3_filesystem`. A PyAthena connection whose S3 client (``Connection.s3_client``) and retry policy the filesystem uses, with a ``DeprecationWarning``. default_block_size: The block size for reads and writes; defaults to @@ -477,8 +494,10 @@ def __init__( client: The boto3 S3 client that the filesystem sends its requests with. The filesystem does not close it. A filesystem with a given client cannot be pickled. - retry_config: The retry policy of the requests; defaults to - ``RetryConfig()``. A policy with the default ``exceptions`` + retry_config: The retry policy of the requests, such as an + :class:`~pyathena.filesystem.s3_retry.S3RetryConfig` or a + :class:`pyathena.util.RetryConfig`; defaults to + ``S3RetryConfig()``. A policy with the default ``exceptions`` also retries the transient S3 error codes (:attr:`~pyathena.filesystem.s3_core.S3Core.RETRY_ERROR_CODES`). **kwargs: Passed to ``fsspec.AbstractFileSystem``; without @@ -526,7 +545,7 @@ def __init__( request_kwargs.setdefault("RequestPayer", "requester") self._core = S3Core( client, - retry_config=retry_config if retry_config is not None else RetryConfig(), + retry_config=retry_config if retry_config is not None else S3RetryConfig(), request_kwargs={**request_kwargs, **S3Core.copy_from_source_params(request_kwargs)}, ) @@ -534,11 +553,11 @@ def __init__( def _resolve_injected_client( cls, filesystem_class: type[AbstractFileSystem], - connection: Connection[Any] | None, + connection: _Connection | None, client: BaseClient | None, - retry_config: RetryConfig | None, + retry_config: RetryPolicy | None, kwargs: Mapping[str, Any], - ) -> tuple[BaseClient | None, RetryConfig | None]: + ) -> tuple[BaseClient | None, RetryPolicy | None]: """Check the injected client of a filesystem and resolve it from a connection. Warns that ``connection`` is deprecated, and rejects the arguments that @@ -625,7 +644,7 @@ def _client(self) -> BaseClient: return self._core.client @property - def _retry_config(self) -> RetryConfig: + def _retry_config(self) -> RetryPolicy: """The retry policy of the requests (``core.retry_config``).""" return self._core.retry_config @@ -683,10 +702,10 @@ def _get_client_compatible_with_s3fs( if max_workers is not None: config_kwargs.setdefault("max_pool_connections", max_workers) - user_agent_extra = config_kwargs.pop("user_agent_extra", None) - if user_agent_extra and pyathena.user_agent_extra not in user_agent_extra: - user_agent_extra = f"{pyathena.user_agent_extra} {user_agent_extra}" - config_kwargs.update({"user_agent_extra": user_agent_extra or pyathena.user_agent_extra}) + extra = config_kwargs.pop("user_agent_extra", None) + if extra and user_agent_extra not in extra: + extra = f"{user_agent_extra} {extra}" + config_kwargs.update({"user_agent_extra": extra or user_agent_extra}) if connect_timeout := kwargs.pop("connect_timeout", None): config_kwargs.update({"connect_timeout": connect_timeout}) if read_timeout := kwargs.pop("read_timeout", None): @@ -5897,7 +5916,7 @@ def _fetch_range(self, start: int, end: int) -> bytes: ones make no further attempt, and its error is raised once they have ended. Once an enclosing stop scope is stopped, such as that of a batch operation after another object failed, no further request is - sent (see :func:`~pyathena.util.raise_if_stopped`). + sent (see :func:`~pyathena.filesystem.s3_retry.raise_if_stopped`). Args: start: The offset of the first byte to read. diff --git a/pyathena/filesystem/s3_async.py b/pyathena/filesystem/s3_async.py index 555c01445..e09f3c6f2 100644 --- a/pyathena/filesystem/s3_async.py +++ b/pyathena/filesystem/s3_async.py @@ -35,7 +35,6 @@ from fsspec.implementations.local import make_path_posix from fsspec.utils import stringify_path -from pyathena.aio.util import create_in_thread from pyathena.filesystem.s3 import ( _UNPICKLABLE_CLIENT_MESSAGE, CompressedBuffer, @@ -55,16 +54,17 @@ ) from pyathena.filesystem.s3_path import S3Path from pyathena.filesystem.s3_path_pairing import S3PathPairing +from pyathena.filesystem.s3_retry import retries_stopped from pyathena.filesystem.s3_writer import _S3WriteSession, _S3WriteState -from pyathena.util import override, retries_stopped +from pyathena.filesystem.util import create_in_thread, override if TYPE_CHECKING: from datetime import datetime from botocore.client import BaseClient - from pyathena.connection import Connection - from pyathena.util import RetryConfig + from pyathena.filesystem.s3 import _Connection + from pyathena.filesystem.s3_retry import RetryPolicy _logger = logging.getLogger(__name__) @@ -304,7 +304,7 @@ class AioS3FileSystem(AsyncFileSystem): def __init__( self, - connection: Connection[Any] | None = None, + connection: _Connection | None = None, default_block_size: int | None = None, default_cache_type: str | None = None, max_workers: int | None = None, @@ -317,14 +317,14 @@ def __init__( batch_size: int | None = None, *, client: BaseClient | None = None, - retry_config: RetryConfig | None = None, + retry_config: RetryPolicy | None = None, **kwargs, ) -> None: """Initialize the filesystem and its internal ``S3FileSystem``. Args: connection: Deprecated; use ``client`` and ``retry_config``, or - :func:`pyathena.filesystem.s3_filesystem` with + :func:`pyathena.fs.s3_filesystem` with ``AioS3FileSystem``. A PyAthena connection whose S3 client and retry policy the filesystem uses, with a ``DeprecationWarning``. default_block_size: Passed to the internal ``S3FileSystem``. @@ -1711,7 +1711,7 @@ async def open_async( The lookups of the mode, as in ``open()``, run in the threads of the filesystem. If the caller is cancelled, a file opened after the cancellation is closed without committing anything (see - :func:`~pyathena.aio.util.create_in_thread`). See + :func:`~pyathena.filesystem.util.create_in_thread`). See :class:`AioS3StreamedFile` for how the file reads, writes, and commits. Args: diff --git a/pyathena/filesystem/s3_core.py b/pyathena/filesystem/s3_core.py index f4bde2f07..791d9c009 100644 --- a/pyathena/filesystem/s3_core.py +++ b/pyathena/filesystem/s3_core.py @@ -33,14 +33,16 @@ S3PutObject, ) from pyathena.filesystem.s3_path import S3Path -from pyathena.util import ( +from pyathena.filesystem.s3_retry import ( THROTTLING_ERROR_CODES, - RetryConfig, - _with_exceptions, - override, + RetryPolicy, + S3RetryConfig, + _PolicyT, retry_api_call, unstoppable_retries, + with_exceptions, ) +from pyathena.filesystem.util import override _logger = logging.getLogger(__name__) @@ -594,27 +596,29 @@ class S3Core: def __init__( self, client: BaseClient, - retry_config: RetryConfig | None = None, + retry_config: RetryPolicy | None = None, request_kwargs: Mapping[str, Any] | None = None, ) -> None: """Create the operations on a client. Args: client: The boto3 S3 client to send the requests with. - retry_config: The retry policy of the requests; defaults to - ``RetryConfig()``. The requests are sent with the policy that + retry_config: The retry policy of the requests, such as an + :class:`~pyathena.filesystem.s3_retry.S3RetryConfig` or a + :class:`pyathena.util.RetryConfig`; defaults to + ``S3RetryConfig()``. The requests are sent with the policy that :meth:`resolve_retry_config` returns for it. request_kwargs: Parameters sent with every operation that accepts them, such as ``{"RequestPayer": "requester"}``. """ self._client = client - self._retry_config = self.resolve_retry_config( - retry_config if retry_config else RetryConfig() + self._retry_config: RetryPolicy = self.resolve_retry_config( + retry_config if retry_config else S3RetryConfig() ) self._request_kwargs = dict(request_kwargs) if request_kwargs else {} @classmethod - def resolve_retry_config(cls, retry_config: RetryConfig) -> RetryConfig: + def resolve_retry_config(cls, retry_config: _PolicyT) -> _PolicyT: """Resolve the retry policy that S3 requests are sent with. A policy whose ``exceptions`` are the default codes @@ -626,13 +630,12 @@ def resolve_retry_config(cls, retry_config: RetryConfig) -> RetryConfig: retry_config: The retry policy. Returns: - A copy of the policy that also retries ``RETRY_ERROR_CODES`` with - the same attempts and waits, or the policy itself. + A copy of the policy, of the same type, that also retries + ``RETRY_ERROR_CODES`` with the same attempts and waits, or the + policy itself. """ if set(retry_config.exceptions) == set(THROTTLING_ERROR_CODES): - return _with_exceptions( - retry_config, (*retry_config.exceptions, *cls.RETRY_ERROR_CODES) - ) + return with_exceptions(retry_config, (*retry_config.exceptions, *cls.RETRY_ERROR_CODES)) return retry_config @property @@ -641,7 +644,7 @@ def client(self) -> BaseClient: return self._client @property - def retry_config(self) -> RetryConfig: + def retry_config(self) -> RetryPolicy: """The retry policy of the requests, with ``RETRY_ERROR_CODES`` if they were added.""" return self._retry_config @@ -725,7 +728,7 @@ def call(self, method: str | Callable[..., Any], **request) -> dict[str, Any]: position = body.tell() body.seek(position) except (AttributeError, OSError, ValueError): - config = _with_exceptions(config, ()) + config = with_exceptions(config, ()) else: # Each attempt calls the client again, which sends the stream # from its current position, where the last attempt left it. @@ -1184,7 +1187,7 @@ def abort_multipart_upload(self, upload: S3MultipartUpload, **params) -> None: """Abort a multipart upload with AbortMultipartUpload. An abort cleans up, so the stop scopes of the caller do not stop its - retries (see :func:`~pyathena.util.unstoppable_retries`). + retries (see :func:`~pyathena.filesystem.s3_retry.unstoppable_retries`). Args: upload: The multipart upload returned by creation or listing. diff --git a/pyathena/filesystem/s3_executor.py b/pyathena/filesystem/s3_executor.py index 4b5ba0518..2457f94f5 100644 --- a/pyathena/filesystem/s3_executor.py +++ b/pyathena/filesystem/s3_executor.py @@ -26,7 +26,8 @@ from multiprocessing import cpu_count from typing import Any, ClassVar, Generic, TypeVar, cast -from pyathena.util import override, stop_retries_on +from pyathena.filesystem.s3_retry import stop_retries_on +from pyathena.filesystem.util import override T = TypeVar("T") ItemT = TypeVar("ItemT") @@ -500,8 +501,9 @@ class S3Executor(metaclass=ABCMeta): Both ``submit`` and ``shutdown`` mirror the ``concurrent.futures.Executor`` interface so that ``as_completed()`` and ``Future.cancel()`` work unchanged. Each submitted callable runs with a copy of the context variables of its - submitter, so that the stop scopes of :func:`~pyathena.util.stop_retries_on` - reach the requests that it makes. + submitter, so that the stop scopes of + :func:`~pyathena.filesystem.s3_retry.stop_retries_on` reach the requests + that it makes. """ @abstractmethod @@ -523,13 +525,13 @@ async def run(self, fn: Callable[..., T], *args: Any, **kwargs: Any) -> T: """Run a blocking call in the executor and wait for it. Cancelling the waiting task cancels a call that has not started. A - running call makes no further attempt of its AWS API calls, as with - :func:`~pyathena.aio.util.run_in_thread`, and a write in it sends no - further part and does not commit (see - :func:`~pyathena.util.raise_if_stopped`); the task waits for the call - to end before it re-raises the cancellation, also when the event loop - shuts down with ``asyncio.run()``. A repeated cancellation stops that - wait, and the call then ends in the executor. + running call makes no further attempt of its AWS API calls (see + :func:`~pyathena.filesystem.s3_retry.stop_retries_on`), and a write in + it sends no further part and does not commit (see + :func:`~pyathena.filesystem.s3_retry.raise_if_stopped`); the task waits + for the call to end before it re-raises the cancellation, also when the + event loop shuts down with ``asyncio.run()``. A repeated cancellation + stops that wait, and the call then ends in the executor. Args: fn: The blocking callable. @@ -689,8 +691,8 @@ def map( Every item is submitted at once, and the executor applies its own limit, such as the ``max_workers`` of a scope. Each call runs in a - scope of :func:`~pyathena.util.stop_retries_on` that the stop of the - batch ends. + scope of :func:`~pyathena.filesystem.s3_retry.stop_retries_on` that the + stop of the batch ends. With ``stop_on_failure``, the first failure that counts stops the batch: the calls that have not started are cancelled, the running diff --git a/pyathena/filesystem/s3_object.py b/pyathena/filesystem/s3_object.py index 1c9874cad..a4b37308b 100644 --- a/pyathena/filesystem/s3_object.py +++ b/pyathena/filesystem/s3_object.py @@ -9,7 +9,7 @@ from typing import TYPE_CHECKING, Any from pyathena.filesystem.s3_path import S3Path -from pyathena.util import override +from pyathena.filesystem.util import override if TYPE_CHECKING: from pyathena.filesystem.s3_core import S3Bucket, S3ObjectSummary diff --git a/pyathena/filesystem/s3_path.py b/pyathena/filesystem/s3_path.py index 84249c9e4..fed1c5e37 100644 --- a/pyathena/filesystem/s3_path.py +++ b/pyathena/filesystem/s3_path.py @@ -15,7 +15,7 @@ from re import Pattern from typing import ClassVar -from pyathena.util import override +from pyathena.filesystem.util import override @dataclass(frozen=True) diff --git a/pyathena/filesystem/s3_retry.py b/pyathena/filesystem/s3_retry.py new file mode 100644 index 000000000..831619566 --- /dev/null +++ b/pyathena/filesystem/s3_retry.py @@ -0,0 +1,318 @@ +# Copyright 2026 The PyAthena authors +# +# Licensed under the MIT License. +# See LICENSE or https://opensource.org/licenses/MIT. +# +# SPDX-License-Identifier: MIT + +"""The retry policy of the S3 requests of the filesystem and the scopes that stop them.""" + +from __future__ import annotations + +import copy +import logging +import threading +import time +from collections.abc import Callable, Iterable, Iterator +from concurrent.futures import CancelledError +from contextlib import contextmanager +from contextvars import ContextVar +from typing import Any, Protocol, TypeVar + +import tenacity +from tenacity import ( + RetryCallState, + after_log, + retry_if_exception, + stop_after_attempt, + wait_exponential, + wait_random, +) + +#: The error codes that a retry policy retries by default. +THROTTLING_ERROR_CODES: tuple[str, ...] = ("ThrottlingException", "TooManyRequestsException") + + +class RetryPolicy(Protocol): + """The attributes of a retry policy that the filesystem reads. + + These are ``exceptions``, ``attempt``, ``multiplier``, ``max_delay``, and + ``exponential_base``, with the meaning that :class:`S3RetryConfig` + describes. :class:`S3RetryConfig` and :class:`pyathena.util.RetryConfig` + have them. + """ + + exceptions: tuple[str, ...] + attempt: int + multiplier: int + max_delay: int + exponential_base: int + + +_PolicyT = TypeVar("_PolicyT", bound=RetryPolicy) + + +class S3RetryConfig: + """The retry policy of the S3 requests of a filesystem. + + The requests are retried with exponential backoff and uniform jitter when + their error code is in ``exceptions``. A policy with the default + ``exceptions`` also retries the transient S3 error codes (see + :meth:`~pyathena.filesystem.s3_core.S3Core.resolve_retry_config`). + + Attributes: + exceptions: The error codes to retry. + attempt: Maximum number of attempts, including the first call. + multiplier: Base multiplier for exponential backoff in seconds. Each + wait also adds uniform random jitter of up to one multiplier. + max_delay: Maximum exponential delay between retries in seconds, + before jitter is added. + exponential_base: Base for exponential backoff calculation. + """ + + def __init__( + self, + exceptions: Iterable[str] = THROTTLING_ERROR_CODES, + attempt: int = 8, + multiplier: int = 1, + max_delay: int = 100, + exponential_base: int = 2, + ) -> None: + """Initialize the retry policy. + + Args: + exceptions: Error code, or iterable of error codes, to retry. + Stored as a tuple. + attempt: Maximum number of attempts, including the first call. + multiplier: Base multiplier for exponential backoff in seconds, and + the upper bound of the random jitter added to each wait. + max_delay: Maximum exponential delay between retries in seconds, + before jitter is added. + exponential_base: Base for exponential backoff calculation. + """ + self.exceptions = (exceptions,) if isinstance(exceptions, str) else tuple(exceptions) + self.attempt = attempt + self.multiplier = multiplier + self.max_delay = max_delay + self.exponential_base = exponential_base + + +def with_exceptions(config: _PolicyT, exceptions: Iterable[str]) -> _PolicyT: + """Copy a retry policy with other error codes to retry. + + Args: + config: The retry policy to copy. + exceptions: The error codes that the copy retries. + + Returns: + A shallow copy of the policy, of the same type; ``config`` is unchanged. + """ + copied = copy.copy(config) + copied.exceptions = tuple(exceptions) + return copied + + +def is_retryable_error(ex: BaseException, config: RetryPolicy) -> bool: + """Return whether an exception has an error code that a retry policy retries. + + Args: + ex: The exception raised by an AWS API call. + config: The retry policy. + + Returns: + True if the error code of the response of the exception is in + ``config.exceptions``. + """ + response = getattr(ex, "response", None) + error = response.get("Error") if isinstance(response, dict) else None + code = error.get("Code") if isinstance(error, dict) else None + return isinstance(code, str) and code in config.exceptions + + +# The events of the enclosing stop scopes of retry_api_call(); see stop_retries_on(). +_RETRY_STOP_EVENTS: ContextVar[tuple[threading.Event, ...]] = ContextVar( + "pyathena_filesystem_retry_stop_events", default=() +) +# The longest that a backoff wait sleeps before it checks again whether the +# retries are stopped, unless it can wait for the single event of a scope. +_STOP_POLL_INTERVAL = 0.1 + + +@contextmanager +def stop_retries_on(event: threading.Event) -> Iterator[None]: + """Stop the retries of the S3 requests in this context once an event is set. + + A call of :func:`retry_api_call` in the block makes no further attempt + once the event is set, ends its backoff wait, and raises the error of its + last attempt. That includes the calls in threads that run a copy of this + context, as ``asyncio.to_thread()`` runs its function. The scopes nest: a + call stops when the event of any enclosing scope is set. The stop is + cooperative: a request that has been sent, and the retries of botocore + itself, still run to their end. + + :func:`pyathena.util.stop_retries_on` also opens a scope of this function. + + Args: + event: The event that stops the retries. + + Yields: + None. + """ + token = _RETRY_STOP_EVENTS.set((*_RETRY_STOP_EVENTS.get(), event)) + try: + yield + finally: + _RETRY_STOP_EVENTS.reset(token) + + +@contextmanager +def unstoppable_retries() -> Iterator[None]: + """Run the retries of the S3 requests in this block to their end. + + The events of the enclosing :func:`stop_retries_on` scopes do not stop + the calls of :func:`retry_api_call` in the block, which retry by their + policy. For cleanup that has to run to its end even when the work that it + cleans up was stopped, such as the abort of a multipart upload. A scope + that :func:`stop_retries_on` opens in the block stops the retries again. + + :func:`pyathena.util.unstoppable_retries` also opens a scope of this + function. + + Yields: + None. + """ + token = _RETRY_STOP_EVENTS.set(()) + try: + yield + finally: + _RETRY_STOP_EVENTS.reset(token) + + +def retries_stopped() -> bool: + """Return whether an event of the enclosing stop scopes is set. + + Returns: + Whether an event of the enclosing :func:`stop_retries_on` scopes, + apart from those that :func:`unstoppable_retries` clears, is set. + """ + return any(event.is_set() for event in _RETRY_STOP_EVENTS.get()) + + +def raise_if_stopped(operation: str) -> None: + """Raise if an event of the enclosing stop scopes is set. + + A writer calls this before a request that adds to or commits a write, + such as a part or the completion of a multipart upload, so that a write + whose owner has stopped, such as a batch operation after the failure of + another object, sends nothing more. The retries that + :func:`stop_retries_on` stops do not cover the first attempt of a new + request. The scopes that :func:`unstoppable_retries` clears do not stop + the writer either. + + Args: + operation: What the caller was about to do, for the error message. + + Raises: + concurrent.futures.CancelledError: If an event of the enclosing + :func:`stop_retries_on` scopes is set. + """ + if retries_stopped(): + raise CancelledError(f"Stopped before it could {operation}.") + + +def retry_api_call( + func: Callable[..., Any], + config: RetryPolicy, + logger: logging.Logger | None = None, + *args, + **kwargs, +) -> Any: + """Call an AWS API with the retries of a policy, which the stop scopes stop. + + The call is retried with exponential backoff and uniform jitter while it + fails with an error code in ``config.exceptions``, up to + ``config.attempt`` attempts. Once an event of the enclosing + :func:`stop_retries_on` scopes is set, no further attempt is made and the + error of the last attempt is raised. + + Args: + func: The AWS API function to call. + config: The retry policy. + logger: Optional logger for retry attempt logging. + *args: Positional arguments to pass to the function. + **kwargs: Keyword arguments to pass to the function. + + Returns: + The result of the successful function call. + + Raises: + BaseException: The error of the last attempt, once the attempts are + exhausted or the retries are stopped, or an error that the policy + does not retry. + """ + events = _RETRY_STOP_EVENTS.get() + + def stopped() -> bool: + """Whether an event of the enclosing scopes is set.""" + return any(event.is_set() for event in events) + + # The error of the attempt before a backoff wait, raised if the wait is stopped. + failures: list[BaseException] = [] + # A single event can be waited for; anything else is polled. + wait_for_event = len(events) == 1 + + def record_failure(retry_state: RetryCallState) -> None: + """Keep the error of the failed attempt, which a stopped wait raises. + + Args: + retry_state: The state of the call before the backoff wait. + """ + outcome = retry_state.outcome + if outcome is not None and (error := outcome.exception()) is not None: + failures[:] = [error] + + def sleep(seconds: float) -> None: + """Wait before the next attempt, ending the wait once the retries are stopped. + + Args: + seconds: The backoff time. + + Raises: + BaseException: The error of the last attempt, instead of + making the next one, if the retries are stopped. + """ + deadline = time.monotonic() + seconds + while not stopped(): + remaining = deadline - time.monotonic() + if remaining <= 0: + return + if wait_for_event: + events[0].wait(remaining) + else: + time.sleep(min(remaining, _STOP_POLL_INTERVAL)) + raise failures[0] + + # Without a stop, tenacity's own sleep is kept. + stop_kwargs: dict[str, Any] = {"before_sleep": record_failure, "sleep": sleep} if events else {} + + retry = tenacity.Retrying( + retry=retry_if_exception(lambda ex: is_retryable_error(ex, config) and not stopped()), + stop=stop_after_attempt(config.attempt), + # Uniform jitter of up to one multiplier keeps concurrent clients from + # retrying in lockstep after a shared throttling response. + wait=wait_exponential( + multiplier=config.multiplier, + max=config.max_delay, + exp_base=config.exponential_base, + ) + + wait_random(0, config.multiplier), + after=after_log(logger, logger.getEffectiveLevel()) if logger else None, # type: ignore[arg-type] + reraise=True, + **stop_kwargs, + ) + try: + return retry(func, *args, **kwargs) + finally: + # The traceback of a raised error keeps this frame, which would keep + # the error in a reference cycle through the list. + failures.clear() diff --git a/pyathena/filesystem/s3_writer.py b/pyathena/filesystem/s3_writer.py index 7727bc825..e013a0a61 100644 --- a/pyathena/filesystem/s3_writer.py +++ b/pyathena/filesystem/s3_writer.py @@ -25,7 +25,7 @@ S3PutObject, ) from pyathena.filesystem.s3_path import S3Path -from pyathena.util import raise_if_stopped, stop_retries_on +from pyathena.filesystem.s3_retry import raise_if_stopped, stop_retries_on T = TypeVar("T") @@ -486,7 +486,7 @@ def start(self) -> None: Raises: S3MultipartStateError: If a request has already been sent. concurrent.futures.CancelledError: If an enclosing stop scope has - been stopped (see :func:`~pyathena.util.raise_if_stopped`). + been stopped (see :func:`~pyathena.filesystem.s3_retry.raise_if_stopped`). """ raise_if_stopped(f"create a multipart upload to {self._path.uri}") creation: Future[S3MultipartUpload] = Future() @@ -630,7 +630,7 @@ def put(self, body: bytes | None) -> S3PutObject: failed, or has been discarded. concurrent.futures.CancelledError: If an enclosing stop scope has been stopped before the request (see - :func:`~pyathena.util.raise_if_stopped`); the write fails then. + :func:`~pyathena.filesystem.s3_retry.raise_if_stopped`); the write fails then. """ return self._commit(_S3WriteState.IDLE, lambda: self._put_object(body)) @@ -653,7 +653,7 @@ def complete(self) -> S3CompleteMultipartUpload: earlier or has been discarded. concurrent.futures.CancelledError: If an enclosing stop scope has been stopped before the request (see - :func:`~pyathena.util.raise_if_stopped`); the write fails then. + :func:`~pyathena.filesystem.s3_retry.raise_if_stopped`); the write fails then. """ return self._commit(_S3WriteState.ACTIVE, self._complete_parts) diff --git a/pyathena/filesystem/util.py b/pyathena/filesystem/util.py new file mode 100644 index 000000000..b673d9e86 --- /dev/null +++ b/pyathena/filesystem/util.py @@ -0,0 +1,180 @@ +# Copyright 2026 The PyAthena authors +# +# Licensed under the MIT License. +# See LICENSE or https://opensource.org/licenses/MIT. +# +# SPDX-License-Identifier: MIT + +"""Helpers of the filesystem: the user agent, ``override``, and constructing in a thread.""" + +from __future__ import annotations + +import asyncio +import contextvars +import logging +import operator +import threading +from collections.abc import Callable +from concurrent.futures import Future +from importlib.metadata import PackageNotFoundError, version +from typing import TYPE_CHECKING, Any, Protocol, TypeVar, overload + +from pyathena.filesystem.s3_retry import stop_retries_on, unstoppable_retries + +_logger = logging.getLogger(__name__) + +_T = TypeVar("_T") + +# Replace with ``from typing import override`` when Python 3.11 support ends. +if TYPE_CHECKING: + from typing_extensions import override +else: + + def override(func): + """Mark a method as overriding a base class method (PEP 698). + + Type checkers use ``typing_extensions.override`` and report a marked + method whose base class method does not exist. At runtime this + decorator does nothing. + + Args: + func: The overriding method. + + Returns: + The method unchanged. + """ + return func + + +try: + _version = version("PyAthena") +except PackageNotFoundError: + _version = "unknown" +#: The ``user_agent_extra`` of the botocore configuration of the clients that +#: the filesystem builds. +user_agent_extra: str = f"PyAthena/{_version}" + + +class _Closable(Protocol): + def close(self) -> Any: ... + + +_ClosableT = TypeVar("_ClosableT", bound=_Closable) + + +class _Executor(Protocol): + def submit(self, fn: Callable[..., _T], /, *args: Any) -> Future[_T]: ... + + +# The default release of create_in_thread(): the blocking close() of the object. +_CLOSE = operator.methodcaller("close") + + +@overload +async def create_in_thread( + factory: Callable[[], _ClosableT], /, *, executor: _Executor | None = ... +) -> _ClosableT: ... + + +@overload +async def create_in_thread( + factory: Callable[[], _T], + /, + *, + release: Callable[[_T], Any], + executor: _Executor | None = ..., +) -> _T: ... + + +async def create_in_thread( + factory: Callable[[], Any], + /, + *, + release: Callable[[Any], Any] = _CLOSE, + executor: _Executor | None = None, +) -> Any: + """Run a blocking constructor of a closable object in the default executor. + + Like ``asyncio.to_thread()``, the constructor runs in the event loop's + default executor, or in ``executor``, with the caller's context. If the + caller is cancelled, a construction that has not started is skipped, the + retries of a running one are stopped (see + :func:`~pyathena.filesystem.s3_retry.stop_retries_on`), an object + constructed after the cancellation is released by the constructing + thread, and an object constructed just before it is released in a new + thread: nothing else can release it, and a close by the garbage collector + could block the event loop's thread. The release needs neither the event + loop nor its executor, which may be shutting down. + + Args: + factory: The constructor, which takes no arguments; bind them with + ``functools.partial()``. + release: The blocking function that releases an object constructed for + a cancelled caller, for an object whose ``close()`` is a coroutine. + Defaults to calling the object's ``close()``. + executor: The executor that runs the constructor instead of the + default executor, such as the thread pool of a filesystem. + + Returns: + The constructed object. + """ + lock = threading.Lock() + cancelled = threading.Event() + constructed: list[Any] = [] + + def construct() -> Any: + """Construct the object in a scope that the cancellation stops. + + Returns: + The object, or None if the caller was cancelled, after which an + object constructed here is released here. + """ + if cancelled.is_set(): + return None + with stop_retries_on(cancelled): + obj = factory() + with lock: + if not cancelled.is_set(): + constructed.append(obj) + return obj + _release_logging_errors(obj, release) + return None + + context = contextvars.copy_context() + future = ( + asyncio.get_running_loop().run_in_executor(None, context.run, construct) + if executor is None + else asyncio.wrap_future(executor.submit(context.run, construct)) + ) + try: + # Unlike asyncio.shield(), asyncio.wait() reports nothing when the + # construction fails after the caller is cancelled. + await asyncio.wait((future,)) + except asyncio.CancelledError: + with lock: + cancelled.set() + # Retrieve a later construction error, which nobody else awaits. + future.add_done_callback(lambda f: f.cancelled() or f.exception()) + if constructed: + threading.Thread( + target=_release_logging_errors, + args=(constructed[0], release), + name="create_in_thread-close", + ).start() + raise + return future.result() + + +def _release_logging_errors(obj: Any, release: Callable[[Any], Any] = _CLOSE) -> None: + """Release an object for a cancelled caller, logging an error that nobody else sees. + + Args: + obj: The object to release. + release: The blocking function that releases it. Defaults to its + ``close()``. + """ + try: + with unstoppable_retries(): + release(obj) + except Exception: + _logger.exception(f"Failed to close {obj!r} after a cancellation.") diff --git a/pyathena/fs.py b/pyathena/fs.py new file mode 100644 index 000000000..b817f3308 --- /dev/null +++ b/pyathena/fs.py @@ -0,0 +1,65 @@ +# Copyright 2026 The PyAthena authors +# +# Licensed under the MIT License. +# See LICENSE or https://opensource.org/licenses/MIT. +# +# SPDX-License-Identifier: MIT + +"""The S3 filesystems of PyAthena connections.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, TypeVar, overload + +from fsspec import AbstractFileSystem + +from pyathena.filesystem.s3 import S3FileSystem + +if TYPE_CHECKING: + from pyathena.connection import Connection + +_FileSystemT = TypeVar("_FileSystemT", bound=AbstractFileSystem) + + +@overload +def s3_filesystem(connection: Connection[Any], **kwargs: Any) -> S3FileSystem: ... + + +@overload +def s3_filesystem( + connection: Connection[Any], filesystem_class: type[_FileSystemT], **kwargs: Any +) -> _FileSystemT: ... + + +def s3_filesystem( + connection: Connection[Any], + filesystem_class: type[AbstractFileSystem] = S3FileSystem, + **kwargs: Any, +) -> AbstractFileSystem: + """Create an S3 filesystem with the S3 client and retry policy of a connection. + + The filesystem borrows ``connection.s3_client``, which the connection + shares with its result sets, and uses ``connection.retry_config``. A + policy with the default ``exceptions`` also retries the transient S3 error + codes (:attr:`~pyathena.filesystem.s3_core.S3Core.RETRY_ERROR_CODES`). + Closing the filesystem does not close the client. A filesystem created + this way cannot be pickled; see :class:`~pyathena.filesystem.s3.S3FileSystem`. + + Example: + >>> from pyathena import connect + >>> from pyathena.fs import s3_filesystem + >>> fs = s3_filesystem(connect(s3_staging_dir="s3://my-bucket/path/")) + + Args: + connection: The PyAthena connection. + filesystem_class: ``S3FileSystem``, ``AioS3FileSystem``, or a subclass of + either. + **kwargs: The other arguments of the filesystem, except the arguments + from which it builds a client. + + Returns: + The filesystem. + """ + return filesystem_class( + client=connection.s3_client, retry_config=connection.retry_config, **kwargs + ) diff --git a/pyathena/pandas/result_set.py b/pyathena/pandas/result_set.py index feb6e052f..3f32c9eef 100644 --- a/pyathena/pandas/result_set.py +++ b/pyathena/pandas/result_set.py @@ -31,8 +31,8 @@ from pyathena.arrow.util import to_column_info from pyathena.converter import Converter, _parse_time_zone, _to_datetime_with_tz, _to_time from pyathena.error import DataError, ProgrammingError -from pyathena.filesystem import s3_filesystem from pyathena.filesystem.s3 import S3FileSystem +from pyathena.fs import s3_filesystem from pyathena.model import AthenaQueryExecution from pyathena.pandas.reader import _BINARY_NULL, BinaryCSVReader from pyathena.result_set import ( diff --git a/pyathena/polars/result_set.py b/pyathena/polars/result_set.py index c728ba5dd..52297fdc2 100644 --- a/pyathena/polars/result_set.py +++ b/pyathena/polars/result_set.py @@ -34,8 +34,8 @@ from pyathena.arrow.reader import ParquetChunkReader from pyathena.converter import Converter, _to_default from pyathena.error import DataError, ProgrammingError -from pyathena.filesystem import s3_filesystem from pyathena.filesystem.s3 import S3FileSystem +from pyathena.fs import s3_filesystem from pyathena.model import AthenaQueryExecution from pyathena.polars.converter import _to_datetimes from pyathena.polars.util import to_column_info, to_microseconds diff --git a/pyathena/s3fs/result_set.py b/pyathena/s3fs/result_set.py index 4d2432fdd..4d84179eb 100644 --- a/pyathena/s3fs/result_set.py +++ b/pyathena/s3fs/result_set.py @@ -18,9 +18,9 @@ from pyathena.converter import Converter from pyathena.error import OperationalError, ProgrammingError -from pyathena.filesystem import s3_filesystem from pyathena.filesystem.s3 import S3FileSystem from pyathena.filesystem.s3_async import AioS3FileSystem +from pyathena.fs import s3_filesystem from pyathena.model import AthenaQueryExecution from pyathena.result_set import AthenaResultSet from pyathena.s3fs.reader import AthenaCSVReader, CSVReader diff --git a/pyathena/util.py b/pyathena/util.py index 90a6ee6c1..a7e45d669 100644 --- a/pyathena/util.py +++ b/pyathena/util.py @@ -24,6 +24,7 @@ ) from pyathena import DataError +from pyathena.filesystem import s3_retry _T = TypeVar("_T") @@ -310,6 +311,10 @@ def stop_retries_on(event: threading.Event) -> Iterator[None]: cooperative: a request that has been sent, and the retries of botocore itself, still run to their end. + The block is also a scope of + :func:`pyathena.filesystem.s3_retry.stop_retries_on`, which stops the + retries of the requests of the S3 filesystem in the same way. + Args: event: The event that stops the retries. @@ -318,7 +323,8 @@ def stop_retries_on(event: threading.Event) -> Iterator[None]: """ token = _RETRY_STOP_EVENTS.set((*_RETRY_STOP_EVENTS.get(), event)) try: - yield + with s3_retry.stop_retries_on(event): + yield finally: _RETRY_STOP_EVENTS.reset(token) @@ -334,12 +340,17 @@ def unstoppable_retries() -> Iterator[None]: was cancelled, or a request that stops a query. A scope that :func:`stop_retries_on` opens in the block stops the retries again. + The block is also a scope of + :func:`pyathena.filesystem.s3_retry.unstoppable_retries`, in which the + requests of the S3 filesystem retry to their end too. + Yields: None. """ token = _RETRY_STOP_EVENTS.set(()) try: - yield + with s3_retry.unstoppable_retries(): + yield finally: _RETRY_STOP_EVENTS.reset(token) diff --git a/pyproject.toml b/pyproject.toml index 8184ca6bf..74cc03a0d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -212,7 +212,7 @@ ignore = [ [tool.ruff.lint.pydocstyle] convention = "google" # Overrides marked with @override inherit the base method's documentation. -ignore-decorators = ["pyathena.util.override"] +ignore-decorators = ["pyathena.util.override", "pyathena.filesystem.util.override"] [tool.ruff.lint.per-file-ignores] "tests/**" = [ diff --git a/tests/pyathena/filesystem/test_fsspec_conformance.py b/tests/pyathena/filesystem/test_fsspec_conformance.py index a76647ad6..cddce8646 100644 --- a/tests/pyathena/filesystem/test_fsspec_conformance.py +++ b/tests/pyathena/filesystem/test_fsspec_conformance.py @@ -14,8 +14,8 @@ import fsspec.tests.abstract as abstract import pytest -from pyathena.filesystem import s3_filesystem from pyathena.filesystem.s3_async import AioS3FileSystem +from pyathena.fs import s3_filesystem from tests import ENV from tests.pyathena.conftest import connect diff --git a/tests/pyathena/filesystem/test_init.py b/tests/pyathena/filesystem/test_init.py index cdff2e2ea..3c0c85672 100644 --- a/tests/pyathena/filesystem/test_init.py +++ b/tests/pyathena/filesystem/test_init.py @@ -6,13 +6,16 @@ # SPDX-License-Identifier: MIT import logging +from types import SimpleNamespace +import boto3 import fsspec import pytest from fsspec.registry import _registry, known_implementations -from pyathena.filesystem import register_s3_filesystem +from pyathena.filesystem import register_s3_filesystem, s3_filesystem from pyathena.filesystem.s3 import S3FileSystem +from pyathena.filesystem.s3_retry import S3RetryConfig class _DummyFileSystem: @@ -53,3 +56,19 @@ def test_register_s3_filesystem_overwrites_existing_registration(registry_state, with caplog.at_level(logging.WARNING, logger="pyathena.filesystem"): register_s3_filesystem() assert not caplog.text + + +def test_s3_filesystem_is_deprecated(): + # GH-1388: the function moved to pyathena.fs; the old name warns at its + # caller and builds the same filesystem from the connection. + client = boto3.client( + "s3", region_name="us-east-1", aws_access_key_id="dummy", aws_secret_access_key="dummy" + ) + connection = SimpleNamespace(s3_client=client, retry_config=S3RetryConfig(attempt=3)) + with pytest.warns(DeprecationWarning, match=r"Use pyathena\.fs\.s3_filesystem") as record: + fs = s3_filesystem(connection, max_workers=2) + with fs: + assert record[0].filename == __file__ + assert fs.core.client is client + assert fs.core.retry_config.attempt == 3 + assert fs.max_workers == 2 diff --git a/tests/pyathena/filesystem/test_package.py b/tests/pyathena/filesystem/test_package.py new file mode 100644 index 000000000..38fc605a4 --- /dev/null +++ b/tests/pyathena/filesystem/test_package.py @@ -0,0 +1,62 @@ +# Copyright 2026 The PyAthena authors +# +# Licensed under the MIT License. +# See LICENSE or https://opensource.org/licenses/MIT. +# +# SPDX-License-Identifier: MIT + +import ast +from pathlib import Path + +import pytest + +import pyathena.filesystem + +_PACKAGE = "pyathena.filesystem" +_ROOT = Path(pyathena.filesystem.__file__).parent + + +def _module_name(path): + return ".".join((_PACKAGE, *path.relative_to(_ROOT).with_suffix("").parts)).removesuffix( + ".__init__" + ) + + +def _outside_package(name): + return (name == "pyathena" or name.startswith("pyathena.")) and not ( + name == _PACKAGE or name.startswith(f"{_PACKAGE}.") + ) + + +def _imports_outside_package(path): + """List the imports of PyAthena modules outside the package, with their lines. + + All imports count, including those under ``TYPE_CHECKING``; relative + imports are resolved against the module. + """ + module = _module_name(path) + # The package that a relative import of level 1 starts from. + package = module if path.name == "__init__.py" else module.rpartition(".")[0] + found = [] + for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): + if isinstance(node, ast.Import): + names = [alias.name for alias in node.names] + elif isinstance(node, ast.ImportFrom): + base = node.module or "" + if node.level: + parent = package.rsplit(".", node.level - 1)[0] if node.level > 1 else package + base = f"{parent}.{base}" if base else parent + # ``from pyathena import filesystem`` names a submodule of the package. + names = [base] if base != "pyathena" else [f"pyathena.{a.name}" for a in node.names] + else: + continue + found.extend((node.lineno, name) for name in names if _outside_package(name)) + return found + + +@pytest.mark.parametrize( + "path", sorted(_ROOT.rglob("*.py")), ids=lambda p: str(p.relative_to(_ROOT)) +) +def test_imports_nothing_outside_package(path): + # GH-1388: the filesystem depends on nothing in PyAthena outside its package. + assert _imports_outside_package(path) == [] diff --git a/tests/pyathena/filesystem/test_s3.py b/tests/pyathena/filesystem/test_s3.py index c9a6d3ecd..8e4c5072b 100644 --- a/tests/pyathena/filesystem/test_s3.py +++ b/tests/pyathena/filesystem/test_s3.py @@ -46,7 +46,7 @@ from fsspec.implementations.memory import MemoryFileSystem import pyathena -from pyathena.filesystem import register_s3_filesystem, s3_filesystem +from pyathena.filesystem import register_s3_filesystem from pyathena.filesystem.s3 import ( CompressedBuffer, S3File, @@ -58,8 +58,10 @@ from pyathena.filesystem.s3_executor import S3Executor, S3ThreadPool, _S3Batch, _S3PoolScope from pyathena.filesystem.s3_object import S3MultipartUpload, S3Object, S3ObjectType, S3StorageClass from pyathena.filesystem.s3_path import S3Path +from pyathena.filesystem.s3_retry import raise_if_stopped from pyathena.filesystem.s3_writer import S3MultipartStateError, _S3WriteSession -from pyathena.util import RetryConfig, raise_if_stopped, stop_retries_on +from pyathena.fs import s3_filesystem +from pyathena.util import RetryConfig, stop_retries_on from tests import ENV from tests.pyathena.conftest import connect from tests.pyathena.util import ( diff --git a/tests/pyathena/filesystem/test_s3_async.py b/tests/pyathena/filesystem/test_s3_async.py index eb0b020d6..b10ecb281 100644 --- a/tests/pyathena/filesystem/test_s3_async.py +++ b/tests/pyathena/filesystem/test_s3_async.py @@ -23,7 +23,6 @@ from botocore.stub import Stubber from fsspec.callbacks import Callback -from pyathena.filesystem import s3_filesystem from pyathena.filesystem.s3 import S3FileSystem from pyathena.filesystem.s3_async import ( AioS3File, @@ -42,8 +41,10 @@ S3ObjectVersion, ) from pyathena.filesystem.s3_path import S3Path +from pyathena.filesystem.s3_retry import raise_if_stopped from pyathena.filesystem.s3_writer import S3MultipartStateError, _S3WriteSession -from pyathena.util import RetryConfig, raise_if_stopped, stop_retries_on +from pyathena.fs import s3_filesystem +from pyathena.util import RetryConfig, stop_retries_on from tests import ENV from tests.pyathena.conftest import connect from tests.pyathena.util import ( diff --git a/tests/pyathena/filesystem/test_s3_executor.py b/tests/pyathena/filesystem/test_s3_executor.py index 558d84961..83240f07c 100644 --- a/tests/pyathena/filesystem/test_s3_executor.py +++ b/tests/pyathena/filesystem/test_s3_executor.py @@ -28,7 +28,8 @@ _S3Batch, _S3PoolScope, ) -from pyathena.util import RetryConfig, override, retry_api_call, stop_retries_on +from pyathena.filesystem.s3_retry import retry_api_call +from pyathena.util import RetryConfig, override, stop_retries_on from tests.pyathena.util import ( EVENT_TIMEOUT, OpcodeInterrupter, diff --git a/tests/pyathena/filesystem/test_s3_retry.py b/tests/pyathena/filesystem/test_s3_retry.py new file mode 100644 index 000000000..6d494a73c --- /dev/null +++ b/tests/pyathena/filesystem/test_s3_retry.py @@ -0,0 +1,249 @@ +# Copyright 2026 The PyAthena authors +# +# Licensed under the MIT License. +# See LICENSE or https://opensource.org/licenses/MIT. +# +# SPDX-License-Identifier: MIT + +import contextvars +import threading +import time +from concurrent.futures import CancelledError, ThreadPoolExecutor + +import pytest +import tenacity.nap +from botocore.exceptions import ClientError + +from pyathena.filesystem.s3_retry import ( + S3RetryConfig, + is_retryable_error, + raise_if_stopped, + retries_stopped, + retry_api_call, + stop_retries_on, + unstoppable_retries, + with_exceptions, +) +from tests.pyathena.util import ( + EVENT_TIMEOUT, + StoppingOperation, + ThrottledOperation, + throttling_error, +) + + +class _Policy: + """A retry policy of another type, such as ``pyathena.util.RetryConfig``.""" + + def __init__(self, exceptions): + self.exceptions = exceptions + self.attempt = 3 + self.multiplier = 0 + self.max_delay = 0 + self.exponential_base = 2 + + +def _error(code, message="message"): + return ClientError({"Error": {"Code": code, "Message": message}}, "GetObject") + + +class TestS3RetryConfig: + def test_defaults(self): + config = S3RetryConfig() + assert config.exceptions == ("ThrottlingException", "TooManyRequestsException") + assert (config.attempt, config.multiplier, config.max_delay, config.exponential_base) == ( + 8, + 1, + 100, + 2, + ) + + @pytest.mark.parametrize("policy_type", [tuple, list, iter, str]) + def test_captures_exceptions(self, policy_type): + codes = ["SlowDown", "InternalError"] + exceptions = codes[0] if policy_type is str else policy_type(codes) + config = S3RetryConfig(exceptions=exceptions) + codes.append("RequestTimeout") + assert config.exceptions == ( + ("SlowDown",) if policy_type is str else ("SlowDown", "InternalError") + ) + + +@pytest.mark.parametrize( + "config", + [S3RetryConfig(exceptions=("SlowDown",), attempt=3), _Policy(("SlowDown",))], + ids=["S3RetryConfig", "other"], +) +def test_with_exceptions(config): + copied = with_exceptions(config, ["SlowDown", "InternalError"]) + assert type(copied) is type(config) + assert copied.exceptions == ("SlowDown", "InternalError") + assert copied.attempt == 3 + assert config.exceptions == ("SlowDown",) + + +@pytest.mark.parametrize( + ("error", "expected"), + [ + (_error("SlowDown"), True), + (_error("NoSuchKey"), False), + # Unlike pyathena.util.is_retryable_error(), Glue errors that Athena + # wraps are not unwrapped. + ( + _error( + "MetadataException", + "Rate exceeded (Service: AmazonDataCatalog; Status Code: 400; " + "Error Code: SlowDown; Request ID: example; Proxy: null)", + ), + False, + ), + (ValueError("no response"), False), + ], + ids=["listed", "unlisted", "metadata-exception", "no-response"], +) +def test_is_retryable_error(error, expected): + assert is_retryable_error(error, _Policy(("SlowDown",))) is expected + + +def test_retry_api_call_retries_listed_codes(): + operation = ThrottledOperation(failures=2) + assert retry_api_call(operation, S3RetryConfig(multiplier=0)) == "success" + assert operation.calls == 3 + # An error that the policy does not list is raised at once. + calls = 0 + + def missing(): + nonlocal calls + calls += 1 + raise _error("NoSuchKey") + + with pytest.raises(ClientError): + retry_api_call(missing, S3RetryConfig(multiplier=0)) + assert calls == 1 + + +@pytest.mark.parametrize( + ("multiplier", "max_delay", "expected_bases"), + [ + (1, 100, [1, 2, 4, 8, 16, 32]), + (2, 10, [2, 4, 8, 10, 10, 10]), + (0, 0, [0, 0, 0, 0, 0, 0]), + ], +) +def test_retry_api_call_waits_with_jitter(monkeypatch, multiplier, max_delay, expected_bases): + sleeps = [] + monkeypatch.setattr(tenacity.nap.time, "sleep", sleeps.append) + error = throttling_error("GetObject") + calls = 0 + + def call(): + nonlocal calls + calls += 1 + raise error + + config = S3RetryConfig(attempt=7, multiplier=multiplier, max_delay=max_delay) + with pytest.raises(ClientError): + retry_api_call(call, config) + assert calls == 7 + assert len(sleeps) == len(expected_bases) + jitters = [waited - base for waited, base in zip(sleeps, expected_bases, strict=True)] + assert all(0 <= jitter <= multiplier for jitter in jitters) + if multiplier: + assert max(jitters) - min(jitters) > multiplier / 100 + + +@pytest.mark.parametrize("stop_in", ["request", "backoff"]) +def test_retry_api_call_stopped_by_event(stop_in): + # Without the stop, the backoff wait would take at least EVENT_TIMEOUT seconds. + event = threading.Event() + call = StoppingOperation(event.set, stop_in) + started = time.monotonic() + with stop_retries_on(event), pytest.raises(ClientError) as caught: + retry_api_call(call, S3RetryConfig(attempt=2, multiplier=EVENT_TIMEOUT)) + call.join() + assert time.monotonic() - started < EVENT_TIMEOUT + assert caught.value is call.error + assert call.calls == 1 + + +def test_retry_api_call_stopped_before_call(): + # A call in a stopped scope makes its first attempt, but no retry. + event = threading.Event() + event.set() + call = StoppingOperation(event.set, "request") + with stop_retries_on(event), pytest.raises(ClientError): + retry_api_call(call, S3RetryConfig(multiplier=0)) + assert call.calls == 1 + + +def test_retry_api_call_stopped_by_enclosing_scope(): + outer = threading.Event() + call = StoppingOperation(outer.set, "backoff") + with ( + stop_retries_on(outer), + stop_retries_on(threading.Event()), + pytest.raises(ClientError), + ): + retry_api_call(call, S3RetryConfig(attempt=2, multiplier=EVENT_TIMEOUT)) + call.join() + assert call.calls == 1 + + +def test_retry_api_call_stopped_in_copied_context(): + # A thread that runs a copy of the context, as the request pool of a + # filesystem does, sees the scopes of its submitter. + event = threading.Event() + event.set() + operation = ThrottledOperation(failures=2) + with stop_retries_on(event), ThreadPoolExecutor(max_workers=1) as executor: + future = executor.submit( + contextvars.copy_context().run, + retry_api_call, + operation, + S3RetryConfig(multiplier=0), + ) + with pytest.raises(ClientError): + future.result(EVENT_TIMEOUT) + assert operation.calls == 1 + + +def test_retry_api_call_unstoppable(): + event = threading.Event() + event.set() + operation = ThrottledOperation(failures=2) + with stop_retries_on(event), unstoppable_retries(): + assert retry_api_call(operation, S3RetryConfig(multiplier=0)) == "success" + assert operation.calls == 3 + # A scope opened in the unstoppable block stops the retries again. + operation = ThrottledOperation(failures=2) + with ( + stop_retries_on(event), + unstoppable_retries(), + stop_retries_on(event), + pytest.raises(ClientError), + ): + retry_api_call(operation, S3RetryConfig(multiplier=0)) + assert operation.calls == 1 + + +def test_retry_api_call_scope_ends_with_block(): + event = threading.Event() + with stop_retries_on(event): + event.set() + operation = ThrottledOperation(failures=2) + assert retry_api_call(operation, S3RetryConfig(multiplier=0)) == "success" + assert operation.calls == 3 + + +def test_raise_if_stopped(): + event = threading.Event() + with stop_retries_on(event): + assert not retries_stopped() + raise_if_stopped("upload part 1") + event.set() + assert retries_stopped() + with pytest.raises(CancelledError, match=r"Stopped before it could upload part 1\."): + raise_if_stopped("upload part 1") + with unstoppable_retries(): + assert not retries_stopped() + raise_if_stopped("abort the upload") diff --git a/tests/pyathena/test_connection.py b/tests/pyathena/test_connection.py index 1d9d28ca3..e2bab2a67 100644 --- a/tests/pyathena/test_connection.py +++ b/tests/pyathena/test_connection.py @@ -37,7 +37,7 @@ from pyathena.converter import DefaultTypeConverter from pyathena.cursor import Cursor, DictCursor from pyathena.error import OperationalError, ProgrammingError -from pyathena.filesystem import s3_filesystem +from pyathena.fs import s3_filesystem from pyathena.pandas.async_cursor import AsyncPandasCursor from pyathena.pandas.cursor import PandasCursor from pyathena.polars.async_cursor import AsyncPolarsCursor diff --git a/tests/pyathena/test_util.py b/tests/pyathena/test_util.py index cd528f9bb..643a84ae5 100644 --- a/tests/pyathena/test_util.py +++ b/tests/pyathena/test_util.py @@ -1,3 +1,4 @@ +import contextvars import threading import time from concurrent.futures import ThreadPoolExecutor @@ -7,6 +8,7 @@ from botocore.exceptions import ClientError from pyathena import DataError +from pyathena.filesystem import s3_retry from pyathena.util import ( RetryConfig, _is_throttling_error, @@ -413,6 +415,42 @@ def test_retry_api_call_scope_ends_with_block(): assert operation.calls == 3 +@pytest.mark.parametrize("thread", [False, True], ids=["same-thread", "copied-context"]) +def test_stop_retries_on_stops_filesystem_retries(thread): + """GH-1388: a scope of stop_retries_on() also stops the retries of the S3 filesystem.""" + event = threading.Event() + event.set() + operation = ThrottledOperation(failures=2) + config = s3_retry.S3RetryConfig(multiplier=0) + + def call(): + if not thread: + return s3_retry.retry_api_call(operation, config) + with ThreadPoolExecutor(max_workers=1) as executor: + return executor.submit( + contextvars.copy_context().run, s3_retry.retry_api_call, operation, config + ).result(EVENT_TIMEOUT) + + with stop_retries_on(event), pytest.raises(ClientError): + call() + assert operation.calls == 1 + + +@pytest.mark.parametrize("scope", ["pyathena", "filesystem"]) +def test_unstoppable_retries_covers_filesystem_retries(scope): + """GH-1388: in unstoppable_retries(), the retries of the S3 filesystem run to their end. + + That holds for the stop scopes of PyAthena and those of the filesystem itself. + """ + event = threading.Event() + event.set() + operation = ThrottledOperation(failures=2) + enclosing = stop_retries_on if scope == "pyathena" else s3_retry.stop_retries_on + with enclosing(event), unstoppable_retries(): + assert s3_retry.retry_api_call(operation, s3_retry.S3RetryConfig(multiplier=0)) == "success" + assert operation.calls == 3 + + @pytest.mark.parametrize("scope", ["innermost", "enclosing"]) def test_wait_with_retry_stop_relays_stop(scope): """A stop of a scope of the waiting caller is relayed to the work, whose outcome is returned.""" diff --git a/tests/pyathena/util.py b/tests/pyathena/util.py index 143912293..3ff77fec5 100644 --- a/tests/pyathena/util.py +++ b/tests/pyathena/util.py @@ -37,6 +37,7 @@ from pyathena.connection import Connection from pyathena.error import ProgrammingError +from pyathena.filesystem import s3_retry from pyathena.filesystem.s3 import S3FileSystem from pyathena.filesystem.s3_async import AioS3FileSystem from pyathena.filesystem.s3_core import S3Core @@ -44,7 +45,7 @@ from pyathena.glue import GlueMetadataClient from pyathena.model import AthenaCalculationExecutionStatus, AthenaQueryExecution from pyathena.spark.common import SparkBaseCursor -from pyathena.util import RetryConfig, override, retry_api_call +from pyathena.util import RetryConfig, override _queries = Environment( loader=FileSystemLoader(Path(__file__).parents[1].resolve() / "resources" / "queries") @@ -168,9 +169,11 @@ def __call__(self, *args, **kwargs): def retried(operation, config): """Return a stub of an ``S3Core`` request method that retries an operation. - The stub sends the operation with :func:`~pyathena.util.retry_api_call` - in the thread that calls it, as ``S3Core.call()`` does, so that the stop - scopes of that thread reach its retries. + The stub sends the operation with + :func:`~pyathena.filesystem.s3_retry.retry_api_call` in the thread that + calls it, as ``S3Core.call()`` does, so that the stop scopes of that + thread, those of the filesystem and of :func:`pyathena.util.stop_retries_on`, + reach its retries. Args: operation: The stubbed AWS API operation, such as a @@ -182,7 +185,7 @@ def retried(operation, config): """ def request(*args, **kwargs): - return retry_api_call(operation, config) + return s3_retry.retry_api_call(operation, config) return request From 1324abc4b052988560a2865bc0d398ad3451392e Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Sat, 21 Nov 2026 23:59:51 +0900 Subject: [PATCH 02/10] Sort the imports of the filesystem benchmark (GH-1388) Co-Authored-By: Claude Opus 5.5 --- benchmarks/pyathena_bench/filesystem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/benchmarks/pyathena_bench/filesystem.py b/benchmarks/pyathena_bench/filesystem.py index 82125650d..b7dd6cc2e 100644 --- a/benchmarks/pyathena_bench/filesystem.py +++ b/benchmarks/pyathena_bench/filesystem.py @@ -19,9 +19,9 @@ from botocore.config import Config from pyathena import connect -from pyathena.fs import s3_filesystem from pyathena.filesystem.s3 import S3FileSystem from pyathena.filesystem.s3_async import AioS3FileSystem +from pyathena.fs import s3_filesystem from pyathena.util import parse_output_location from pyathena_bench.cases import Case from pyathena_bench.config import Settings From fb362c7b52a93349c5a97800358bdbb1b4a915b3 Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Sun, 22 Nov 2026 00:47:46 +0900 Subject: [PATCH 03/10] Let the filesystem's stop scopes stop PyAthena's retries too (GH-1388) The filesystem's own scopes, such as those of a cancelled call in its thread pool, stopped only the filesystem's retries. A callable that used pyathena.util.retry_api_call() in S3ThreadPool.run() kept retrying after the cancellation, which it did not before the split. PyAthena's retries and stop checks now observe the filesystem's scopes as well, through s3_retry.retry_stop_events(). Also: the boundary test checks literal import_module()/__import__() names and .pyi files; the aio result-set tests stub their requests with PyAthena's retry function again; the stopped-before-call test no longer sets the event during the request. Co-Authored-By: Claude Opus 5.5 --- pyathena/filesystem/s3_retry.py | 13 ++++++ pyathena/util.py | 31 +++++++++++--- tests/pyathena/aio/test_common.py | 8 ++-- tests/pyathena/filesystem/test_package.py | 23 +++++++++-- tests/pyathena/filesystem/test_s3_retry.py | 9 +++-- tests/pyathena/test_util.py | 47 +++++++++++++++------- tests/pyathena/util.py | 17 ++++---- 7 files changed, 110 insertions(+), 38 deletions(-) diff --git a/pyathena/filesystem/s3_retry.py b/pyathena/filesystem/s3_retry.py index 831619566..c4ae11c42 100644 --- a/pyathena/filesystem/s3_retry.py +++ b/pyathena/filesystem/s3_retry.py @@ -188,6 +188,19 @@ def unstoppable_retries() -> Iterator[None]: _RETRY_STOP_EVENTS.reset(token) +def retry_stop_events() -> tuple[threading.Event, ...]: + """Return the events of the enclosing stop scopes. + + :mod:`pyathena.util` reads them, so that these scopes also stop the + retries of PyAthena's own AWS API calls. + + Returns: + The events of the enclosing :func:`stop_retries_on` scopes, apart + from those that :func:`unstoppable_retries` clears, outermost first. + """ + return _RETRY_STOP_EVENTS.get() + + def retries_stopped() -> bool: """Return whether an event of the enclosing stop scopes is set. diff --git a/pyathena/util.py b/pyathena/util.py index a7e45d669..6421a7e2f 100644 --- a/pyathena/util.py +++ b/pyathena/util.py @@ -294,6 +294,22 @@ def is_retryable_error(ex: BaseException, config: RetryConfig) -> bool: _RETRY_STOP_EVENTS: ContextVar[tuple[threading.Event, ...]] = ContextVar( "pyathena_retry_stop_events", default=() ) + + +def _stop_events() -> tuple[threading.Event, ...]: + """Return the events of the enclosing stop scopes, those of the S3 filesystem included. + + A scope of :func:`stop_retries_on` is also one of the filesystem, so its + event appears once. + + Returns: + The events of the enclosing scopes of :func:`stop_retries_on` and of + :func:`pyathena.filesystem.s3_retry.stop_retries_on`, apart from those + that the unstoppable blocks clear. + """ + return tuple(dict.fromkeys((*_RETRY_STOP_EVENTS.get(), *s3_retry.retry_stop_events()))) + + # The longest that a backoff wait sleeps before it checks again whether the # retries are stopped, unless it can wait for the single event of a scope. _STOP_POLL_INTERVAL = 0.1 @@ -313,7 +329,9 @@ def stop_retries_on(event: threading.Event) -> Iterator[None]: The block is also a scope of :func:`pyathena.filesystem.s3_retry.stop_retries_on`, which stops the - retries of the requests of the S3 filesystem in the same way. + retries of the requests of the S3 filesystem in the same way. Conversely, + the scopes that the filesystem opens, such as those of its thread pools, + also stop the calls of :func:`retry_api_call` in them. Args: event: The event that stops the retries. @@ -359,10 +377,11 @@ def retries_stopped() -> bool: """Return whether an event of the enclosing stop scopes is set. Returns: - Whether an event of the enclosing :func:`stop_retries_on` scopes, - apart from those that :func:`unstoppable_retries` clears, is set. + Whether an event of the enclosing :func:`stop_retries_on` scopes, or + of those of :func:`pyathena.filesystem.s3_retry.stop_retries_on`, + apart from those that the unstoppable blocks clear, is set. """ - return any(event.is_set() for event in _RETRY_STOP_EVENTS.get()) + return any(event.is_set() for event in _stop_events()) def raise_if_stopped(operation: str) -> None: @@ -407,7 +426,7 @@ def wait_with_retry_stop(future: Future[_T], *, stop: threading.Event) -> _T: BaseException: The exception of the work, such as the error of the last attempt of a call whose retries were stopped. """ - events = _RETRY_STOP_EVENTS.get() + events = _stop_events() while events and not future.done(): if any(event.is_set() for event in events): stop.set() @@ -461,7 +480,7 @@ def retry_api_call( This includes recognized Glue error codes wrapped in MetadataException. Other errors are propagated without retrying. """ - events = _RETRY_STOP_EVENTS.get() + events = _stop_events() def stopped() -> bool: """Whether an event of the enclosing scopes is set.""" diff --git a/tests/pyathena/aio/test_common.py b/tests/pyathena/aio/test_common.py index 570a55003..dc58e2e8b 100644 --- a/tests/pyathena/aio/test_common.py +++ b/tests/pyathena/aio/test_common.py @@ -19,7 +19,7 @@ from pyathena.aio.s3fs.cursor import AioS3FSCursor from pyathena.error import OperationalError, ProgrammingError from pyathena.pandas.result_set import PandasDataFrameIterator -from pyathena.util import RetryConfig +from pyathena.util import RetryConfig, retry_api_call from tests.pyathena.util import EVENT_TIMEOUT, ThrottledOperation, retried _ALL_CURSOR_CLASSES = [ @@ -179,7 +179,7 @@ def close(): result_set = MagicMock(is_closed=False) result_set.close.side_effect = close getattr(result_set, method).side_effect = retried( - operation, RetryConfig(attempt=2, multiplier=EVENT_TIMEOUT) + operation, RetryConfig(attempt=2, multiplier=EVENT_TIMEOUT), retry_api_call ) cursor.result_set = result_set task = asyncio.create_task(getattr(cursor, method)(*args)) @@ -402,7 +402,9 @@ async def test_cancelled_iter_chunks_detaches_result_set(self, cursor_class): connection=MagicMock(), converter=None, formatter=None, retry_config=None ) operation = ThrottledOperation(block=True) - chunks = _Chunks(retried(operation, RetryConfig(attempt=2, multiplier=EVENT_TIMEOUT))) + chunks = _Chunks( + retried(operation, RetryConfig(attempt=2, multiplier=EVENT_TIMEOUT), retry_api_call) + ) closed = threading.Event() result_set = MagicMock(is_closed=False) result_set.close.side_effect = closed.set diff --git a/tests/pyathena/filesystem/test_package.py b/tests/pyathena/filesystem/test_package.py index 38fc605a4..23a590b5c 100644 --- a/tests/pyathena/filesystem/test_package.py +++ b/tests/pyathena/filesystem/test_package.py @@ -31,8 +31,9 @@ def _outside_package(name): def _imports_outside_package(path): """List the imports of PyAthena modules outside the package, with their lines. - All imports count, including those under ``TYPE_CHECKING``; relative - imports are resolved against the module. + All imports count, including those under ``TYPE_CHECKING`` and the calls + of ``importlib.import_module()`` or ``__import__()`` with a literal name; + relative imports are resolved against the module. """ module = _module_name(path) # The package that a relative import of level 1 starts from. @@ -48,6 +49,20 @@ def _imports_outside_package(path): base = f"{parent}.{base}" if base else parent # ``from pyathena import filesystem`` names a submodule of the package. names = [base] if base != "pyathena" else [f"pyathena.{a.name}" for a in node.names] + elif ( + isinstance(node, ast.Call) + and ( + (isinstance(node.func, ast.Attribute) and node.func.attr == "import_module") + or ( + isinstance(node.func, ast.Name) + and node.func.id in ("import_module", "__import__") + ) + ) + and node.args + and isinstance(node.args[0], ast.Constant) + and isinstance(node.args[0].value, str) + ): + names = [node.args[0].value] else: continue found.extend((node.lineno, name) for name in names if _outside_package(name)) @@ -55,7 +70,9 @@ def _imports_outside_package(path): @pytest.mark.parametrize( - "path", sorted(_ROOT.rglob("*.py")), ids=lambda p: str(p.relative_to(_ROOT)) + "path", + sorted(p for pattern in ("*.py", "*.pyi") for p in _ROOT.rglob(pattern)), + ids=lambda p: str(p.relative_to(_ROOT)), ) def test_imports_nothing_outside_package(path): # GH-1388: the filesystem depends on nothing in PyAthena outside its package. diff --git a/tests/pyathena/filesystem/test_s3_retry.py b/tests/pyathena/filesystem/test_s3_retry.py index 6d494a73c..963677e96 100644 --- a/tests/pyathena/filesystem/test_s3_retry.py +++ b/tests/pyathena/filesystem/test_s3_retry.py @@ -167,13 +167,14 @@ def test_retry_api_call_stopped_by_event(stop_in): def test_retry_api_call_stopped_before_call(): - # A call in a stopped scope makes its first attempt, but no retry. + # A call in a scope whose event is already set makes its first attempt, + # but no retry. event = threading.Event() event.set() - call = StoppingOperation(event.set, "request") + operation = ThrottledOperation(failures=2) with stop_retries_on(event), pytest.raises(ClientError): - retry_api_call(call, S3RetryConfig(multiplier=0)) - assert call.calls == 1 + retry_api_call(operation, S3RetryConfig(multiplier=0)) + assert operation.calls == 1 def test_retry_api_call_stopped_by_enclosing_scope(): diff --git a/tests/pyathena/test_util.py b/tests/pyathena/test_util.py index 643a84ae5..5ead23fd0 100644 --- a/tests/pyathena/test_util.py +++ b/tests/pyathena/test_util.py @@ -1,7 +1,6 @@ -import contextvars import threading import time -from concurrent.futures import ThreadPoolExecutor +from concurrent.futures import CancelledError, ThreadPoolExecutor import pytest import tenacity.nap @@ -15,6 +14,8 @@ _without_retries, is_retryable_error, parse_output_location, + raise_if_stopped, + retries_stopped, retry_api_call, stop_retries_on, strtobool, @@ -415,27 +416,45 @@ def test_retry_api_call_scope_ends_with_block(): assert operation.calls == 3 -@pytest.mark.parametrize("thread", [False, True], ids=["same-thread", "copied-context"]) -def test_stop_retries_on_stops_filesystem_retries(thread): +def test_stop_retries_on_stops_filesystem_retries(): """GH-1388: a scope of stop_retries_on() also stops the retries of the S3 filesystem.""" event = threading.Event() event.set() operation = ThrottledOperation(failures=2) - config = s3_retry.S3RetryConfig(multiplier=0) + with stop_retries_on(event), pytest.raises(ClientError): + s3_retry.retry_api_call(operation, s3_retry.S3RetryConfig(multiplier=0)) + assert operation.calls == 1 - def call(): - if not thread: - return s3_retry.retry_api_call(operation, config) - with ThreadPoolExecutor(max_workers=1) as executor: - return executor.submit( - contextvars.copy_context().run, s3_retry.retry_api_call, operation, config - ).result(EVENT_TIMEOUT) - with stop_retries_on(event), pytest.raises(ClientError): - call() +def test_filesystem_scope_stops_retries(): + """GH-1388: a stop scope that the S3 filesystem opens also stops PyAthena's retries. + + Such as that of a call that a cancelled task runs in the filesystem's thread pool. + """ + event = threading.Event() + event.set() + operation = ThrottledOperation(failures=2) + with s3_retry.stop_retries_on(event): + assert retries_stopped() + with pytest.raises(CancelledError): + raise_if_stopped("continue") + with pytest.raises(ClientError): + retry_api_call(operation, RetryConfig(multiplier=0)) assert operation.calls == 1 +def test_wait_with_retry_stop_relays_filesystem_stop(): + """GH-1388: the stop of a scope that the S3 filesystem opens is relayed to the work.""" + event, stop = threading.Event(), threading.Event() + event.set() + with ThreadPoolExecutor(max_workers=1) as executor: + future = executor.submit(stop.wait, EVENT_TIMEOUT) + with s3_retry.stop_retries_on(event): + started = time.monotonic() + assert wait_with_retry_stop(future, stop=stop) is True + assert time.monotonic() - started < EVENT_TIMEOUT + + @pytest.mark.parametrize("scope", ["pyathena", "filesystem"]) def test_unstoppable_retries_covers_filesystem_retries(scope): """GH-1388: in unstoppable_retries(), the retries of the S3 filesystem run to their end. diff --git a/tests/pyathena/util.py b/tests/pyathena/util.py index 3ff77fec5..087b3c0a5 100644 --- a/tests/pyathena/util.py +++ b/tests/pyathena/util.py @@ -166,26 +166,27 @@ def __call__(self, *args, **kwargs): return "success" -def retried(operation, config): - """Return a stub of an ``S3Core`` request method that retries an operation. +def retried(operation, config, retry=s3_retry.retry_api_call): + """Return a stub of a request method that retries an operation. - The stub sends the operation with - :func:`~pyathena.filesystem.s3_retry.retry_api_call` in the thread that - calls it, as ``S3Core.call()`` does, so that the stop scopes of that - thread, those of the filesystem and of :func:`pyathena.util.stop_retries_on`, - reach its retries. + The stub sends the operation with ``retry`` in the thread that calls it, + so that the stop scopes of that thread reach its retries. The default, + :func:`~pyathena.filesystem.s3_retry.retry_api_call`, retries as + ``S3Core.call()`` does; pass :func:`pyathena.util.retry_api_call` for a + request of PyAthena's own, such as one of a result set. Args: operation: The stubbed AWS API operation, such as a :class:`ThrottledOperation`. config: The retry policy. + retry: The retry function. Returns: The stub, which accepts and ignores any arguments. """ def request(*args, **kwargs): - return s3_retry.retry_api_call(operation, config) + return retry(operation, config) return request From 6e195e13f4153c4b3410b23f9730866b5055b606 Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Sun, 22 Nov 2026 00:48:45 +0900 Subject: [PATCH 04/10] List the stop-scope functions of the filesystem in the API reference (GH-1388) Co-Authored-By: Claude Opus 5.5 --- docs/api/filesystem.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/api/filesystem.rst b/docs/api/filesystem.rst index b17354c2f..3c29ada0b 100644 --- a/docs/api/filesystem.rst +++ b/docs/api/filesystem.rst @@ -53,8 +53,12 @@ Retries .. autofunction:: pyathena.filesystem.s3_retry.unstoppable_retries +.. autofunction:: pyathena.filesystem.s3_retry.retries_stopped + .. autofunction:: pyathena.filesystem.s3_retry.raise_if_stopped +.. autofunction:: pyathena.filesystem.s3_retry.retry_stop_events + Read-ahead Stream ----------------- From f0564cabb8ce28ee689624ea98f1aa410d20dce7 Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Sun, 22 Nov 2026 01:40:29 +0900 Subject: [PATCH 05/10] Keep one retry stop state, owned by the filesystem (GH-1388) PyAthena's stop scopes now are the filesystem's: pyathena.util's stop_retries_on(), unstoppable_retries(), and retries_stopped() use pyathena.filesystem.s3_retry, and retry_api_call() and wait_with_retry_stop() read s3_retry.retry_stop_events(). Reading the union of two variables still let a stopped PyAthena scope stop a PyAthena retry in the filesystem's unstoppable block, which the single variable before the split did not; the dependency still points only from PyAthena to the filesystem. The bridge tests now set the event after entering the scope, and the boundary test resolves relative import_module() names and treats __init__.pyi as a package initializer. A TODO records that importing pyathena now loads the filesystem, to revisit once it is its own distribution. Co-Authored-By: Claude Opus 5.5 --- pyathena/util.py | 71 ++++++++--------------- tests/pyathena/filesystem/test_package.py | 20 +++++-- tests/pyathena/test_util.py | 58 ++++++++++-------- 3 files changed, 73 insertions(+), 76 deletions(-) diff --git a/pyathena/util.py b/pyathena/util.py index 6421a7e2f..59b49568c 100644 --- a/pyathena/util.py +++ b/pyathena/util.py @@ -9,7 +9,6 @@ from collections.abc import Callable, Iterable, Iterator from concurrent.futures import CancelledError, Future, wait from contextlib import contextmanager -from contextvars import ContextVar from re import Pattern from typing import TYPE_CHECKING, Any, TypeVar @@ -24,6 +23,11 @@ ) from pyathena import DataError + +# TODO Importing the filesystem's retry module runs pyathena/filesystem/__init__.py, +# so ``import pyathena`` also loads fsspec, boto3, and the filesystem, which +# cursors that read no files through it do not need. Revisit when the filesystem +# becomes its own distribution (GH-1315); see GH-1388. from pyathena.filesystem import s3_retry _T = TypeVar("_T") @@ -290,26 +294,6 @@ def is_retryable_error(ex: BaseException, config: RetryConfig) -> bool: ) -# The events of the enclosing stop scopes of retry_api_call(); see stop_retries_on(). -_RETRY_STOP_EVENTS: ContextVar[tuple[threading.Event, ...]] = ContextVar( - "pyathena_retry_stop_events", default=() -) - - -def _stop_events() -> tuple[threading.Event, ...]: - """Return the events of the enclosing stop scopes, those of the S3 filesystem included. - - A scope of :func:`stop_retries_on` is also one of the filesystem, so its - event appears once. - - Returns: - The events of the enclosing scopes of :func:`stop_retries_on` and of - :func:`pyathena.filesystem.s3_retry.stop_retries_on`, apart from those - that the unstoppable blocks clear. - """ - return tuple(dict.fromkeys((*_RETRY_STOP_EVENTS.get(), *s3_retry.retry_stop_events()))) - - # The longest that a backoff wait sleeps before it checks again whether the # retries are stopped, unless it can wait for the single event of a scope. _STOP_POLL_INTERVAL = 0.1 @@ -327,11 +311,11 @@ def stop_retries_on(event: threading.Event) -> Iterator[None]: cooperative: a request that has been sent, and the retries of botocore itself, still run to their end. - The block is also a scope of - :func:`pyathena.filesystem.s3_retry.stop_retries_on`, which stops the - retries of the requests of the S3 filesystem in the same way. Conversely, - the scopes that the filesystem opens, such as those of its thread pools, - also stop the calls of :func:`retry_api_call` in them. + The scopes are those of + :func:`pyathena.filesystem.s3_retry.stop_retries_on`, which the S3 + filesystem opens too, such as for the calls of its thread pools: a scope + of either stops the retries of PyAthena's AWS API calls and of the + filesystem's requests alike. Args: event: The event that stops the retries. @@ -339,12 +323,8 @@ def stop_retries_on(event: threading.Event) -> Iterator[None]: Yields: None. """ - token = _RETRY_STOP_EVENTS.set((*_RETRY_STOP_EVENTS.get(), event)) - try: - with s3_retry.stop_retries_on(event): - yield - finally: - _RETRY_STOP_EVENTS.reset(token) + with s3_retry.stop_retries_on(event): + yield @contextmanager @@ -358,30 +338,27 @@ def unstoppable_retries() -> Iterator[None]: was cancelled, or a request that stops a query. A scope that :func:`stop_retries_on` opens in the block stops the retries again. - The block is also a scope of - :func:`pyathena.filesystem.s3_retry.unstoppable_retries`, in which the - requests of the S3 filesystem retry to their end too. + The block is one of + :func:`pyathena.filesystem.s3_retry.unstoppable_retries`, which the S3 + filesystem opens too, such as for its cleanup requests: in a block of + either, PyAthena's AWS API calls and the filesystem's requests retry to + their end alike. Yields: None. """ - token = _RETRY_STOP_EVENTS.set(()) - try: - with s3_retry.unstoppable_retries(): - yield - finally: - _RETRY_STOP_EVENTS.reset(token) + with s3_retry.unstoppable_retries(): + yield def retries_stopped() -> bool: """Return whether an event of the enclosing stop scopes is set. Returns: - Whether an event of the enclosing :func:`stop_retries_on` scopes, or - of those of :func:`pyathena.filesystem.s3_retry.stop_retries_on`, - apart from those that the unstoppable blocks clear, is set. + Whether an event of the enclosing :func:`stop_retries_on` scopes, + apart from those that :func:`unstoppable_retries` clears, is set. """ - return any(event.is_set() for event in _stop_events()) + return s3_retry.retries_stopped() def raise_if_stopped(operation: str) -> None: @@ -426,7 +403,7 @@ def wait_with_retry_stop(future: Future[_T], *, stop: threading.Event) -> _T: BaseException: The exception of the work, such as the error of the last attempt of a call whose retries were stopped. """ - events = _stop_events() + events = s3_retry.retry_stop_events() while events and not future.done(): if any(event.is_set() for event in events): stop.set() @@ -480,7 +457,7 @@ def retry_api_call( This includes recognized Glue error codes wrapped in MetadataException. Other errors are propagated without retrying. """ - events = _stop_events() + events = s3_retry.retry_stop_events() def stopped() -> bool: """Whether an event of the enclosing scopes is set.""" diff --git a/tests/pyathena/filesystem/test_package.py b/tests/pyathena/filesystem/test_package.py index 23a590b5c..b62dcf4ba 100644 --- a/tests/pyathena/filesystem/test_package.py +++ b/tests/pyathena/filesystem/test_package.py @@ -37,16 +37,21 @@ def _imports_outside_package(path): """ module = _module_name(path) # The package that a relative import of level 1 starts from. - package = module if path.name == "__init__.py" else module.rpartition(".")[0] + package = module if path.stem == "__init__" else module.rpartition(".")[0] + + def resolve(name, level): + """Resolve a module name relative to the package by ``level`` dots.""" + if not level: + return name + parent = package.rsplit(".", level - 1)[0] if level > 1 else package + return f"{parent}.{name}" if name else parent + found = [] for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): if isinstance(node, ast.Import): names = [alias.name for alias in node.names] elif isinstance(node, ast.ImportFrom): - base = node.module or "" - if node.level: - parent = package.rsplit(".", node.level - 1)[0] if node.level > 1 else package - base = f"{parent}.{base}" if base else parent + base = resolve(node.module or "", node.level) # ``from pyathena import filesystem`` names a submodule of the package. names = [base] if base != "pyathena" else [f"pyathena.{a.name}" for a in node.names] elif ( @@ -62,7 +67,10 @@ def _imports_outside_package(path): and isinstance(node.args[0], ast.Constant) and isinstance(node.args[0].value, str) ): - names = [node.args[0].value] + # A relative name, such as ``import_module("..util", __package__)``. + name = node.args[0].value + level = len(name) - len(name.lstrip(".")) + names = [resolve(name[level:], level)] else: continue found.extend((node.lineno, name) for name in names if _outside_package(name)) diff --git a/tests/pyathena/test_util.py b/tests/pyathena/test_util.py index 5ead23fd0..f91925945 100644 --- a/tests/pyathena/test_util.py +++ b/tests/pyathena/test_util.py @@ -416,43 +416,34 @@ def test_retry_api_call_scope_ends_with_block(): assert operation.calls == 3 -def test_stop_retries_on_stops_filesystem_retries(): +@pytest.mark.parametrize("stop_in", ["request", "backoff"]) +def test_stop_retries_on_stops_filesystem_retries(stop_in): """GH-1388: a scope of stop_retries_on() also stops the retries of the S3 filesystem.""" event = threading.Event() - event.set() - operation = ThrottledOperation(failures=2) + call = StoppingOperation(event.set, stop_in) with stop_retries_on(event), pytest.raises(ClientError): - s3_retry.retry_api_call(operation, s3_retry.S3RetryConfig(multiplier=0)) - assert operation.calls == 1 + s3_retry.retry_api_call(call, s3_retry.S3RetryConfig(attempt=2, multiplier=EVENT_TIMEOUT)) + call.join() + assert call.calls == 1 -def test_filesystem_scope_stops_retries(): +@pytest.mark.parametrize("stop_in", ["request", "backoff"]) +def test_filesystem_scope_stops_retries(stop_in): """GH-1388: a stop scope that the S3 filesystem opens also stops PyAthena's retries. Such as that of a call that a cancelled task runs in the filesystem's thread pool. """ event = threading.Event() - event.set() - operation = ThrottledOperation(failures=2) + call = StoppingOperation(event.set, stop_in) with s3_retry.stop_retries_on(event): + assert not retries_stopped() + with pytest.raises(ClientError): + retry_api_call(call, RetryConfig(attempt=2, multiplier=EVENT_TIMEOUT)) + call.join() assert retries_stopped() with pytest.raises(CancelledError): raise_if_stopped("continue") - with pytest.raises(ClientError): - retry_api_call(operation, RetryConfig(multiplier=0)) - assert operation.calls == 1 - - -def test_wait_with_retry_stop_relays_filesystem_stop(): - """GH-1388: the stop of a scope that the S3 filesystem opens is relayed to the work.""" - event, stop = threading.Event(), threading.Event() - event.set() - with ThreadPoolExecutor(max_workers=1) as executor: - future = executor.submit(stop.wait, EVENT_TIMEOUT) - with s3_retry.stop_retries_on(event): - started = time.monotonic() - assert wait_with_retry_stop(future, stop=stop) is True - assert time.monotonic() - started < EVENT_TIMEOUT + assert call.calls == 1 @pytest.mark.parametrize("scope", ["pyathena", "filesystem"]) @@ -470,6 +461,27 @@ def test_unstoppable_retries_covers_filesystem_retries(scope): assert operation.calls == 3 +def test_filesystem_unstoppable_block_covers_retries(): + """GH-1388: in the S3 filesystem's unstoppable block, PyAthena's retries run to their end.""" + event = threading.Event() + event.set() + operation = ThrottledOperation(failures=2) + with stop_retries_on(event), s3_retry.unstoppable_retries(): + assert not retries_stopped() + assert retry_api_call(operation, RetryConfig(multiplier=0)) == "success" + assert operation.calls == 3 + + +def test_wait_with_retry_stop_relays_filesystem_stop(): + """GH-1388: the stop of a scope that the S3 filesystem opens is relayed to the work.""" + event, stop = threading.Event(), threading.Event() + with ThreadPoolExecutor(max_workers=1) as executor: + future = executor.submit(stop.wait, EVENT_TIMEOUT) + with s3_retry.stop_retries_on(event): + event.set() + assert wait_with_retry_stop(future, stop=stop) is True + + @pytest.mark.parametrize("scope", ["innermost", "enclosing"]) def test_wait_with_retry_stop_relays_stop(scope): """A stop of a scope of the waiting caller is relayed to the work, whose outcome is returned.""" From 5f922709347b25f8b6a91e7ea4d3043bfab455f6 Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Sun, 22 Nov 2026 01:53:03 +0900 Subject: [PATCH 06/10] Stop the bridge tests' scopes while the retries and waits run (GH-1388) The relay test stops the filesystem's scope only after the waiter has checked it, the backoff cases assert that the stop ended the wait early, and the boundary test resolves relative import_module() names against a literal package argument. Co-Authored-By: Claude Opus 5.5 --- tests/pyathena/filesystem/test_package.py | 13 ++++++++----- tests/pyathena/test_util.py | 17 ++++++++++++++--- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/tests/pyathena/filesystem/test_package.py b/tests/pyathena/filesystem/test_package.py index b62dcf4ba..ae5395f0f 100644 --- a/tests/pyathena/filesystem/test_package.py +++ b/tests/pyathena/filesystem/test_package.py @@ -39,11 +39,11 @@ def _imports_outside_package(path): # The package that a relative import of level 1 starts from. package = module if path.stem == "__init__" else module.rpartition(".")[0] - def resolve(name, level): - """Resolve a module name relative to the package by ``level`` dots.""" + def resolve(name, level, anchor=package): + """Resolve a module name relative to ``anchor`` by ``level`` dots.""" if not level: return name - parent = package.rsplit(".", level - 1)[0] if level > 1 else package + parent = anchor.rsplit(".", level - 1)[0] if level > 1 else anchor return f"{parent}.{name}" if name else parent found = [] @@ -67,10 +67,13 @@ def resolve(name, level): and isinstance(node.args[0], ast.Constant) and isinstance(node.args[0].value, str) ): - # A relative name, such as ``import_module("..util", __package__)``. + # A relative name, such as ``import_module("..util", __package__)``, + # resolves against a literal ``package`` if one is given. name = node.args[0].value level = len(name) - len(name.lstrip(".")) - names = [resolve(name[level:], level)] + anchors = [*node.args[1:2], *(k.value for k in node.keywords if k.arg == "package")] + literal = [a.value for a in anchors if isinstance(a, ast.Constant)] + names = [resolve(name[level:], level, *literal[:1])] else: continue found.extend((node.lineno, name) for name in names if _outside_package(name)) diff --git a/tests/pyathena/test_util.py b/tests/pyathena/test_util.py index f91925945..86c2e07f9 100644 --- a/tests/pyathena/test_util.py +++ b/tests/pyathena/test_util.py @@ -419,11 +419,14 @@ def test_retry_api_call_scope_ends_with_block(): @pytest.mark.parametrize("stop_in", ["request", "backoff"]) def test_stop_retries_on_stops_filesystem_retries(stop_in): """GH-1388: a scope of stop_retries_on() also stops the retries of the S3 filesystem.""" + # Without the stop, the backoff wait would take at least EVENT_TIMEOUT seconds. event = threading.Event() call = StoppingOperation(event.set, stop_in) + started = time.monotonic() with stop_retries_on(event), pytest.raises(ClientError): s3_retry.retry_api_call(call, s3_retry.S3RetryConfig(attempt=2, multiplier=EVENT_TIMEOUT)) call.join() + assert time.monotonic() - started < EVENT_TIMEOUT assert call.calls == 1 @@ -435,11 +438,13 @@ def test_filesystem_scope_stops_retries(stop_in): """ event = threading.Event() call = StoppingOperation(event.set, stop_in) + started = time.monotonic() with s3_retry.stop_retries_on(event): assert not retries_stopped() with pytest.raises(ClientError): retry_api_call(call, RetryConfig(attempt=2, multiplier=EVENT_TIMEOUT)) call.join() + assert time.monotonic() - started < EVENT_TIMEOUT assert retries_stopped() with pytest.raises(CancelledError): raise_if_stopped("continue") @@ -474,11 +479,17 @@ def test_filesystem_unstoppable_block_covers_retries(): def test_wait_with_retry_stop_relays_filesystem_stop(): """GH-1388: the stop of a scope that the S3 filesystem opens is relayed to the work.""" - event, stop = threading.Event(), threading.Event() + event, stop = _CheckedEvent(), threading.Event() + + def work(): + # The scope stops once the waiter has checked it, during the wait. + event.checked.wait(EVENT_TIMEOUT) + event.set() + return stop.wait(EVENT_TIMEOUT) + with ThreadPoolExecutor(max_workers=1) as executor: - future = executor.submit(stop.wait, EVENT_TIMEOUT) + future = executor.submit(work) with s3_retry.stop_retries_on(event): - event.set() assert wait_with_retry_stop(future, stop=stop) is True From ec8ffbeb6bffaf354f1348df148a0813aad6f47a Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Sun, 22 Nov 2026 02:03:58 +0900 Subject: [PATCH 07/10] Stop the relay test's scope after the waiter's second check (GH-1388) A wait that checks the scopes only once could see the stop that the worker set right after the first check. The boundary test also reads import_module() calls whose arguments are all keywords and ignores a package that is not a string. Co-Authored-By: Claude Opus 5.5 --- tests/pyathena/filesystem/test_package.py | 17 ++++++++++++----- tests/pyathena/test_util.py | 17 ++++++++++++++--- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/tests/pyathena/filesystem/test_package.py b/tests/pyathena/filesystem/test_package.py index ae5395f0f..266901f24 100644 --- a/tests/pyathena/filesystem/test_package.py +++ b/tests/pyathena/filesystem/test_package.py @@ -63,16 +63,23 @@ def resolve(name, level, anchor=package): and node.func.id in ("import_module", "__import__") ) ) - and node.args - and isinstance(node.args[0], ast.Constant) - and isinstance(node.args[0].value, str) + and isinstance( + target := next( + iter([*node.args[:1], *(k.value for k in node.keywords if k.arg == "name")]), + None, + ), + ast.Constant, + ) + and isinstance(target.value, str) ): # A relative name, such as ``import_module("..util", __package__)``, # resolves against a literal ``package`` if one is given. - name = node.args[0].value + name = target.value level = len(name) - len(name.lstrip(".")) anchors = [*node.args[1:2], *(k.value for k in node.keywords if k.arg == "package")] - literal = [a.value for a in anchors if isinstance(a, ast.Constant)] + literal = [ + a.value for a in anchors if isinstance(a, ast.Constant) and isinstance(a.value, str) + ] names = [resolve(name[level:], level, *literal[:1])] else: continue diff --git a/tests/pyathena/test_util.py b/tests/pyathena/test_util.py index 86c2e07f9..0b91bb434 100644 --- a/tests/pyathena/test_util.py +++ b/tests/pyathena/test_util.py @@ -479,11 +479,22 @@ def test_filesystem_unstoppable_block_covers_retries(): def test_wait_with_retry_stop_relays_filesystem_stop(): """GH-1388: the stop of a scope that the S3 filesystem opens is relayed to the work.""" - event, stop = _CheckedEvent(), threading.Event() + stop = threading.Event() + checks = threading.Semaphore(0) + + class CountedEvent(threading.Event): + def is_set(self): + result = super().is_set() + checks.release() + return result + + event = CountedEvent() def work(): - # The scope stops once the waiter has checked it, during the wait. - event.checked.wait(EVENT_TIMEOUT) + # The scope stops after the waiter's second check, so only a wait + # that keeps checking sees the stop. + for _ in range(2): + checks.acquire(timeout=EVENT_TIMEOUT) event.set() return stop.wait(EVENT_TIMEOUT) From 35c42ec8d5476263a10fed3b6fff32f83f83b174 Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Sun, 22 Nov 2026 02:10:52 +0900 Subject: [PATCH 08/10] Resolve import_module() anchors as Python does in the boundary test (GH-1388) A relative name resolves against __package__, __name__, or a string literal; another package argument is not followed. The relay test's worker fails instead of setting the event when the waiter stops checking. Co-Authored-By: Claude Opus 5.5 --- tests/pyathena/filesystem/test_package.py | 22 ++++++++++++++++------ tests/pyathena/test_util.py | 3 ++- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/tests/pyathena/filesystem/test_package.py b/tests/pyathena/filesystem/test_package.py index 266901f24..6df44bfc3 100644 --- a/tests/pyathena/filesystem/test_package.py +++ b/tests/pyathena/filesystem/test_package.py @@ -73,14 +73,24 @@ def resolve(name, level, anchor=package): and isinstance(target.value, str) ): # A relative name, such as ``import_module("..util", __package__)``, - # resolves against a literal ``package`` if one is given. + # resolves against its ``package``: ``__package__``, ``__name__``, + # or a string literal. Another anchor is not followed. name = target.value level = len(name) - len(name.lstrip(".")) - anchors = [*node.args[1:2], *(k.value for k in node.keywords if k.arg == "package")] - literal = [ - a.value for a in anchors if isinstance(a, ast.Constant) and isinstance(a.value, str) - ] - names = [resolve(name[level:], level, *literal[:1])] + anchor = next( + iter([*node.args[1:2], *(k.value for k in node.keywords if k.arg == "package")]), + None, + ) + if not level: + names = [name] + elif anchor is None or (isinstance(anchor, ast.Name) and anchor.id == "__package__"): + names = [resolve(name[level:], level)] + elif isinstance(anchor, ast.Name) and anchor.id == "__name__": + names = [resolve(name[level:], level, module)] + elif isinstance(anchor, ast.Constant) and isinstance(anchor.value, str): + names = [resolve(name[level:], level, anchor.value)] + else: + continue else: continue found.extend((node.lineno, name) for name in names if _outside_package(name)) diff --git a/tests/pyathena/test_util.py b/tests/pyathena/test_util.py index 0b91bb434..e797927e5 100644 --- a/tests/pyathena/test_util.py +++ b/tests/pyathena/test_util.py @@ -494,7 +494,8 @@ def work(): # The scope stops after the waiter's second check, so only a wait # that keeps checking sees the stop. for _ in range(2): - checks.acquire(timeout=EVENT_TIMEOUT) + if not checks.acquire(timeout=EVENT_TIMEOUT): + return False event.set() return stop.wait(EVENT_TIMEOUT) From d2854c0cf886c641ccccfbb3eecfa56f95801d57 Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Sun, 22 Nov 2026 02:17:23 +0900 Subject: [PATCH 09/10] Reject any dynamic import in the filesystem package (GH-1388) Resolving the anchors of import_module() calls could not follow every form, such as __spec__.parent or an alias of the function. The package needs no dynamic import, so the boundary test now reports any call of import_module() or __import__() and any import of import_module. Co-Authored-By: Claude Opus 5.5 --- tests/pyathena/filesystem/test_package.py | 58 +++++++---------------- 1 file changed, 16 insertions(+), 42 deletions(-) diff --git a/tests/pyathena/filesystem/test_package.py b/tests/pyathena/filesystem/test_package.py index 6df44bfc3..9f551998b 100644 --- a/tests/pyathena/filesystem/test_package.py +++ b/tests/pyathena/filesystem/test_package.py @@ -31,19 +31,19 @@ def _outside_package(name): def _imports_outside_package(path): """List the imports of PyAthena modules outside the package, with their lines. - All imports count, including those under ``TYPE_CHECKING`` and the calls - of ``importlib.import_module()`` or ``__import__()`` with a literal name; - relative imports are resolved against the module. + All imports count, including those under ``TYPE_CHECKING``; relative + imports are resolved against the module. Any call of + ``importlib.import_module()`` or ``__import__()`` is reported too. """ module = _module_name(path) # The package that a relative import of level 1 starts from. package = module if path.stem == "__init__" else module.rpartition(".")[0] - def resolve(name, level, anchor=package): - """Resolve a module name relative to ``anchor`` by ``level`` dots.""" + def resolve(name, level): + """Resolve a module name relative to the package by ``level`` dots.""" if not level: return name - parent = anchor.rsplit(".", level - 1)[0] if level > 1 else anchor + parent = package.rsplit(".", level - 1)[0] if level > 1 else package return f"{parent}.{name}" if name else parent found = [] @@ -51,46 +51,20 @@ def resolve(name, level, anchor=package): if isinstance(node, ast.Import): names = [alias.name for alias in node.names] elif isinstance(node, ast.ImportFrom): + if node.module == "importlib" and any(a.name == "import_module" for a in node.names): + # Also catches a call through an alias of the function. + found.append((node.lineno, "")) base = resolve(node.module or "", node.level) # ``from pyathena import filesystem`` names a submodule of the package. names = [base] if base != "pyathena" else [f"pyathena.{a.name}" for a in node.names] - elif ( - isinstance(node, ast.Call) - and ( - (isinstance(node.func, ast.Attribute) and node.func.attr == "import_module") - or ( - isinstance(node.func, ast.Name) - and node.func.id in ("import_module", "__import__") - ) - ) - and isinstance( - target := next( - iter([*node.args[:1], *(k.value for k in node.keywords if k.arg == "name")]), - None, - ), - ast.Constant, - ) - and isinstance(target.value, str) + elif isinstance(node, ast.Call) and ( + (isinstance(node.func, ast.Attribute) and node.func.attr == "import_module") + or (isinstance(node.func, ast.Name) and node.func.id in ("import_module", "__import__")) ): - # A relative name, such as ``import_module("..util", __package__)``, - # resolves against its ``package``: ``__package__``, ``__name__``, - # or a string literal. Another anchor is not followed. - name = target.value - level = len(name) - len(name.lstrip(".")) - anchor = next( - iter([*node.args[1:2], *(k.value for k in node.keywords if k.arg == "package")]), - None, - ) - if not level: - names = [name] - elif anchor is None or (isinstance(anchor, ast.Name) and anchor.id == "__package__"): - names = [resolve(name[level:], level)] - elif isinstance(anchor, ast.Name) and anchor.id == "__name__": - names = [resolve(name[level:], level, module)] - elif isinstance(anchor, ast.Constant) and isinstance(anchor.value, str): - names = [resolve(name[level:], level, anchor.value)] - else: - continue + # A dynamic import cannot be resolved statically, and the package + # needs none; any one fails the check. + found.append((node.lineno, "")) + continue else: continue found.extend((node.lineno, name) for name in names if _outside_package(name)) From a831618fe47a8b2f246ccc792596eff75687568e Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Sun, 22 Nov 2026 11:04:41 +0900 Subject: [PATCH 10/10] Name the client of chunked Polars Parquet reads in the usage guide (GH-1388) With PyArrow installed and no read options, chunked Parquet results of PolarsCursor are read through PyAthena's filesystem with the connection's shared S3 client, not through Polars' own. Co-Authored-By: Claude Opus 5.5 --- docs/usage.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/usage.md b/docs/usage.md index 84fa04acc..a4782cc05 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -763,7 +763,8 @@ The Glue request does not carry the connection's workgroup; turn the fallback of A connection builds one S3 client on first use and shares it with the result sets of its cursors, the filesystems created with `pyathena.fs.s3_filesystem()`, and the Spark cursors. The result sets of `Cursor`, `DictCursor`, and their asynchronous versions do not use it, so these cursors build no S3 client. -`ArrowCursor`, and `PolarsCursor` for Parquet (`unload=True`) and chunked results, read the query results through their libraries' own S3 clients and use the shared client for their other S3 requests. +`ArrowCursor`, and `PolarsCursor` for Parquet (`unload=True`) and chunked CSV results, read the query results through their libraries' own S3 clients and use the shared client for their other S3 requests. +`PolarsCursor` reads chunked Parquet results through the shared client instead when PyArrow is installed and `execute()` is given no read options. The S3 client is built from the connection's session, region, and client arguments, with the botocore `config` merged with `s3_config`. It does not use the connection's `endpoint_url` and `api_version`, which are Athena's, and neither do the S3 requests of `pyathena.pandas.util.to_sql()`.