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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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.
2 changes: 1 addition & 1 deletion benchmarks/pyathena_bench/filesystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@
from botocore.config import Config

from pyathena import connect
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.util import parse_output_location
from pyathena_bench.cases import Case
from pyathena_bench.config import Settings
Expand Down
22 changes: 21 additions & 1 deletion docs/api/filesystem.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -39,6 +39,26 @@ 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.retries_stopped

.. autofunction:: pyathena.filesystem.s3_retry.raise_if_stopped

.. autofunction:: pyathena.filesystem.s3_retry.retry_stop_events

Read-ahead Stream
-----------------

Expand Down
19 changes: 11 additions & 8 deletions docs/filesystem.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand All @@ -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,
Expand Down Expand Up @@ -511,20 +513,21 @@ 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
policy that gives the default codes explicitly. A policy with other `exceptions` is used
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
Expand Down
5 changes: 3 additions & 2 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -761,9 +761,10 @@ 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.
`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()`.
Expand Down
34 changes: 15 additions & 19 deletions pyathena/filesystem/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,49 +10,39 @@
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__)

_FileSystemT = TypeVar("_FileSystemT", bound=AbstractFileSystem)


@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.
Expand All @@ -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
)
Expand Down
2 changes: 1 addition & 1 deletion pyathena/filesystem/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
65 changes: 42 additions & 23 deletions pyathena/filesystem/s3.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 (
Expand All @@ -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 = (
Expand All @@ -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."
)

Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -526,19 +545,19 @@ 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)},
)

@classmethod
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
Expand Down Expand Up @@ -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

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