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
48 changes: 48 additions & 0 deletions docs/filesystem.md
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,54 @@ The opt-in S3 versioning integration tests create dedicated temporary buckets an
check unversioned, enabled, and suspended states. See [Testing](testing.md) for the
command and required test permissions.

## Path addressing

### Keys that look like version paths

A path string that ends in a version ID query names that version:
`s3://YOUR_S3_BUCKET/a/x?versionId=v1` is version `v1` of the key `a/x`. A key that
itself ends in such a query, such as `a/x?versionId=v1`, cannot be named by a path
string, and there is no escape syntax. An `S3Path` names it by its bucket, key and
version as they are:

```python
from pyathena.filesystem.s3_path import S3Path

path = S3Path("YOUR_S3_BUCKET", "a/x?versionId=v1")
fs.info(path)
fs.cat_file(path)
fs.cp_file(path, S3Path("YOUR_S3_BUCKET", "b/x?versionId=v1"))
fs.get_file(path, "local-file")
fs.put_file("local-file", path)
```

`info()`, `cat_file()`, `cp_file()`, `get_file()`, `put_file()`, `sign()`, `metadata()`,
`getxattr()` and `setxattr()`, their asynchronous counterparts, `S3File`, `S3Core` and
`S3PathPairing` accept an `S3Path`. `S3Path.of()` parses a path string and returns an
`S3Path` as it is. `S3Path("YOUR_S3_BUCKET", "")` is the bucket path, as
`S3Path("YOUR_S3_BUCKET")` is.

`find()`, `walk()`, `tree()`, `glob()` and `expand_path()` list such keys by their
buckets and keys, and `rm()`, `chmod()`, `cat()`, `du()`, `copy()`, `mv()` and `get()`
act on the keys that they list in the same way. `put()` writes a local file to the key
named after the file, also when its name ends in such a query. The names that these
methods return are strings, so the name of such a key, passed back to a method as a
path string, names the version. The same holds for the compositions that pass path
strings, such as `fsspec.open()`, `fsspec.open_files()` and `get_mapper()` (`FSMap`).

A file opened with an `S3Path` of such a key, without a version, has the name of the
key as its `path`. Its `url()`, `metadata()`, `getxattr()` and `setxattr()` address its
bucket, key and version, and a pickled copy of the file reopens its `path`, which names
the version.

### Bucket paths with a trailing double slash

`s3://YOUR_S3_BUCKET//` names the key `/` for `cat_file()`, `rm_file()` and a
non-recursive `chmod()`, and the bucket for `info()` and the listings, such as `ls()`
and `find()`, which remove trailing slashes. A recursive `chmod()` of it changes the ACLs
of the objects that `find()` lists, including the key `/`, and not the ACL of the
bucket. A write to it, such as `pipe_file()`, raises `ValueError`.

## Bucket lifecycle

Bucket creation and deletion are infrastructure-level changes and are disabled by
Expand Down
149 changes: 106 additions & 43 deletions pyathena/filesystem/s3.py

Large diffs are not rendered by default.

194 changes: 132 additions & 62 deletions pyathena/filesystem/s3_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,11 +190,12 @@ def run(self) -> None:
if stopped:
raise CancelledError("Stopped before the transaction could commit the write.")

def open(self, path: str, mode: str, **kwargs) -> S3File:
def open(self, path: str | S3Path, mode: str, **kwargs) -> S3File:
"""Open the file of the write, which joins the transaction unless the write is stopped.

Args:
path: S3 path (s3://bucket/key) of the file.
path: S3 path (s3://bucket/key) of the file, or an ``S3Path``,
which is opened by its bucket and key.
mode: The binary write mode of the file.
**kwargs: The other arguments of ``open()``, except
``compression``. With ``autocommit=True``, as with
Expand All @@ -205,7 +206,12 @@ def open(self, path: str, mode: str, **kwargs) -> S3File:
The file.
"""
autocommit = kwargs.pop("autocommit", False)
file = self._fs._open(self._fs._strip_protocol(path), mode, autocommit=autocommit, **kwargs)
file = self._fs._open(
path if isinstance(path, S3Path) else self._fs._strip_protocol(path),
mode,
autocommit=autocommit,
**kwargs,
)
with self._lock:
self._files.append(file)
# Under the lock, so that a cancellation either finds the file
Expand Down Expand Up @@ -541,29 +547,29 @@ def _pipe_file_in_transaction(
async def _put_file(
self,
lpath: str | os.PathLike[str],
rpath: str | os.PathLike[str],
rpath: str | os.PathLike[str] | S3Path,
callback=_DEFAULT_CALLBACK,
mode: str = "overwrite",
**kwargs,
) -> None:
_S3BatchTasks.track()
rpath = stringify_path(rpath)
target: str | S3Path = rpath if isinstance(rpath, S3Path) else stringify_path(rpath)
if self._intrans:
# See _pipe_file.
await self._write_in_transaction(
functools.partial(
self._put_file_in_transaction, lpath, rpath, callback, mode, **kwargs
self._put_file_in_transaction, lpath, target, callback, mode, **kwargs
)
)
return
await self._thread_pool.run(
self._sync_fs.put_file, lpath, rpath, callback=callback, mode=mode, **kwargs
self._sync_fs.put_file, lpath, target, callback=callback, mode=mode, **kwargs
)

def _put_file_in_transaction(
self,
lpath: str | os.PathLike[str],
rpath: str,
rpath: str | S3Path,
callback,
mode: str,
open_file: Callable[..., S3File],
Expand All @@ -576,7 +582,8 @@ def _put_file_in_transaction(

Args:
lpath: Local file path to upload.
rpath: S3 destination path (s3://bucket/key).
rpath: S3 destination path (s3://bucket/key), or an ``S3Path``,
whose bucket and key are written as they are.
callback: Progress callback for tracking upload progress.
mode: "overwrite" or "create". With "create", the file is
opened in ``xb`` mode: raise FileExistsError when the object
Expand All @@ -595,7 +602,8 @@ def _put_file_in_transaction(
"""
if os.path.isdir(lpath):
return
if not S3Path.parse(rpath).key:
s3_path = S3Path.of(rpath)
if not s3_path.key:
return

size = os.path.getsize(lpath)
Expand All @@ -619,7 +627,7 @@ def _put_file_in_transaction(
max_workers=max_workers,
s3_additional_kwargs=s3_additional_kwargs,
)._write_file_and_close(local, callback)
self.invalidate_cache(rpath)
self._invalidate(s3_path)

async def _get_file(
self,
Expand Down Expand Up @@ -929,42 +937,14 @@ async def _get(
batch_size = kwargs.get("batch_size", self.batch_size)
if batch_size is not None and batch_size > 0:
concurrency = min(concurrency, batch_size)
await _S3BatchTasks().run(
self._get_pairs(pairs, callback, **self._sync_fs._batch_kwargs(concurrency, kwargs))
)

async def _get_pairs(
self, pairs: list[tuple[str | S3Path, Any]], callback: Any, **kwargs
) -> None:
"""Download the pairs of a ``get()`` as fsspec's ``_get()`` downloads lists of paths.

Each download gets a branch of the callback named after the string of
its source, and the sources that a listing returns are downloaded by
their buckets and keys.

Args:
pairs: The S3 sources and their local destinations.
callback: Progress callback.
**kwargs: Passed to ``_get_file()``, and ``batch_size``, the
number of downloads to run at once.
"""
# As fsspec's _get() for lists of paths.
for _, lp in pairs:
os.makedirs(os.path.dirname(lp), exist_ok=True)
batch_size = kwargs.pop("batch_size", self.batch_size)
callback.set_size(len(pairs))

async def get_pair(rp: str | S3Path, lp: Any) -> None:
"""Download a pair with a branch of the callback.

Args:
rp: The S3 source.
lp: The local destination.
"""
with callback.branched(str(rp), lp, **kwargs) as child:
await self._get_file(rp, lp, callback=child, **kwargs)

await _run_coros_in_chunks(
[get_pair(rp, lp) for rp, lp in pairs], batch_size=batch_size, callback=callback
# A local path, as copy_pairs() names it.
os.makedirs(os.path.dirname(cast(str, lp)), exist_ok=True)
await _S3BatchTasks().run(
self._transfer_pairs(
self._get_file, pairs, callback, **self._sync_fs._batch_kwargs(concurrency, kwargs)
)
)

async def _put(
Expand Down Expand Up @@ -1001,23 +981,104 @@ async def _put(
The return values of the ``_put_file()`` calls, as in fsspec.

Raises:
ValueError: If two files have the same destination.
ValueError: If two files have the same destination, or the
destination of a local file names a version, also when
``rpath`` names one and the file is named below it.
"""
lpath, rpath = self._sync_fs._stringify_paths(lpath), self._sync_fs._stringify_paths(rpath)
pairs = await self._thread_pool.run(
self._sync_fs._put_pairs, lpath, rpath, recursive=recursive, maxdepth=maxdepth, **kwargs
)
files = [(lp, rp) for lp, rp in pairs if not os.path.isdir(lp)]
return await _S3BatchTasks().run(
super()._put(
[lp for lp, _ in files],
[rp for _, rp in files],
callback=callback,
batch_size=batch_size,
**kwargs,
self._transfer_pairs(
self._put_file, files, callback, batch_size=batch_size or self.batch_size, **kwargs
)
)

async def _transfer_pairs(

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Self-review round one (implementation behavior): FINDINGS, repaired in e9bc32d

Scope: the full diff 89ffcd97..522d2cab.

Passes:

  • /code-review at high effort.
  • /simplify, with four cleanup agents: reuse (CLEAN), simplification, efficiency (CLEAN) and altitude.

Findings and repairs:

  1. The async _get()/_put() took a threading.Lock on the event loop (/code-review). The wrapped callback took it on the loop thread while worker threads held it for their child callbacks. That stalls the loop, and deadlocks it if a child callback calls a sync method of the filesystem, which waits on the loop.
  2. The path methods of a file opened with an S3Path used its path string (altitude).
    • For S3Path("bucket", "a/x?versionId=null"), url(), metadata() and getxattr() signed and read the null version of a/x, and setxattr() rejected the file as a version.
    • The docs listed this as a limit, and named sign(), which S3File does not have (its method is url()).
    • Repair: the filesystems' sign(), metadata(), getxattr() and setxattr() accept an S3Path, and S3File passes its bucket, key and version (_s3_path). The docs now name only pickling as the limit.
    • Test: TestS3File::test_path_methods_address_path_as_it_is; all four cases fail at 522d2ca.
  3. The versioned-root errors changed (/code-review, altitude). copy() of listed sources and put() raised with_key_suffix()'s generic message.
    • Repair: s3_copy_pairs() raises Cannot copy to a versioned file. again, and _put_pairs() raises Cannot write to the file with the version specified., the message that the string path gave at open(). The Raises of put() and _put() say so.
  4. Cleanups (simplification):
    • _put_pairs() returns early when no destination is named after a local file.
    • put_file() and the async transaction write parse their destination once.
    • The latter invalidates through self._invalidate().
  5. Tests (/code-review):
    • The append test of a typed path moved to TestS3File.
    • The sync put test compares the callback's labels exactly (dir includes the directory's bucket/up).

Deferred, with reasons:

Validation:

  • just lint, just docs lint and just benchmark test pass.
  • The filesystem suite against AWS, in parts: 1043 + 715 + 103 passed, 6 skipped.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rebase onto #1398, and independent review of the resolution (relayed result, Codex): FINDINGS (4), repaired in 0ee4e26

Rebase:

Reviewer and run:

Coverage, in the reviewer's words: the duplicate check "still runs before transfers start", explicit destinations "compare as protocol-stripped strings", generated children "compare by S3Path fields, and the only string that can appear alongside them is their distinct root", and async outfile downloads "still run one at a time in pair order".

Findings and repairs:

  1. Medium: a directory-only upload below a versioned root raised. For example, put(["a/empty", "b/empty"], "s3://bucket/key?versionId=v1", recursive=True) named destinations for the directories and raised, though it uploads nothing. The same put() of empty directories was deferred in round one as intended; this finding reverses that.
    • Repair: only a local file named below the root gets a typed destination, and only then is the root's version checked. A directory keeps its string destination, which put_file() skips.
    • Test: test_put_below_versioned_root[False] fails at d1789ce. [True] keeps the raise for a file.
  2. Medium: the async transfers bypassed Callback.branch_coro(). fsspec's _put() ran each upload through callback.branch_coro(self._put_file). _transfer_pairs() called branched() directly, so a callback that overrides branch_coro() lost its records.
    • Repair: _transfer_pairs() runs each transfer through callback.branch_coro(). The coroutine it wraps receives the string labels and transfers the paths as they are.
    • Test: test_transfers_run_through_branch_coro (async _get and _put) fails at d1789ce.
  3. Low: the Raises of put()/_put() described the version error too narrowly. A local file put directly to a version path also raises, at open(). Repair: they now say "a destination names a version, also when rpath names one and a local file is named below it".
  4. Low: _put_pairs() said a destination in a list is the caller's string. In fact the protocol is stripped. Repair: "a string without the protocol".

Validation at 0ee4e26:

  • just lint and just benchmark test pass.
  • The filesystem suite against AWS, in parts: 1050 + 720 + 103 passed, 6 skipped.

An independent follow-up of these repairs follows.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent follow-up of the rebase repairs (relayed result, Codex): FINDINGS (4). 2 were repaired in 798b7d3; 2 predate #1426 and are added to #1427

Reviewer and run:

  • Reviewer: Codex CLI codex exec, model gpt-6.2-astra, reasoning effort max, read-only. Session 01a1fe39-a600-7620-8194-a6c1db3ed553.
  • Scope: a detached snapshot of 0ee4e26, reviewing d1789cee..0ee4e262.
  • This was a static review.

Coverage, in the reviewer's words: upload pairing "preserves literal suffixes for files named below the root, keeps directory destinations as strings, and checks duplicate file destinations before scheduling uploads", plus the callback arguments, batching, return values, cancellation, the two new tests and the docstrings.

Findings:

  1. High: an upload could start after cancellation. If a branch_coro() wrapper awaited before invoking the transfer, the transfer's task had not yet joined _S3BatchTasks. A cancelled _put() then raised CancelledError to the caller, and the wrapper uploaded the file once released; _get() likewise wrote the local file.
    • Repair: each transfer's coroutine adds its task to the batch (_S3BatchTasks.track()) before it awaits the wrapper.
    • Test: test_cancelled_put_starts_no_waiting_transfer fails at 0ee4e26 (the file is uploaded after the cancellation).
  2. Medium: _get() returns None, where fsspec returns the list of the transfer results. This predates Type put destinations and document path addressing (GH-1404) #1426; the async _get() has returned None since before Act on listed identities in pairing and copy/mv/get (GH-1403) #1421. It is added to Share the upload body of put_file() with the async transaction write, and check put sources once #1427 (comment).
  3. Low: a skipped _put() of a single directory calls set_size(0) and returns [], where fsspec returns None. This also predates Type put destinations and document path addressing (GH-1404) #1426; added to Share the upload body of put_file() with the async transaction write, and check put sources once #1427.
  4. Low: the Raises of put()/_put() overstated the version check. A list destination with a version is accepted when its source is a directory, which uploads nothing.
    • Repair: they now say "the destination of a local file names a version".

Validation at 798b7d3:

  • just lint passes.
  • The filesystem tests other than test_s3.py: 1051 passed, 3 skipped. They include test_s3_async.py and the fsspec conformance tests, against AWS.
  • test_s3.py is unaffected (only a docstring changed in s3.py) and passed at 0ee4e26: 720 + 103 passed, 3 skipped.
  • CI at 0ee4e26 passed.

An independent follow-up of this repair follows.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rebase onto #1423, and independent follow-up of the cancellation repair (relayed result, Codex): FINDINGS (3). 2 were repaired in 7eb9cd6; 1 is accepted within the interrupt guarantee

Rebase:

Reviewer and run:

  • Reviewer: Codex CLI codex exec, model gpt-6.2-astra, reasoning effort max, read-only. Session 01a1fe47-6d6c-7531-b9de-7f50a540855b.
  • Scope: a detached snapshot of 798b7d3, reviewing 0ee4e262..798b7d3e.
  • This was a static review.
  • Covered, in the reviewer's words: "both _put() and _get() now cancel and wait for the wrapper before propagating cancellation. fsspec still enforces batch_size, leaves unscheduled pairs idle, and preserves _put() result order."

Findings:

  1. Medium: deferring branch_coro() could deadlock a callback. fsspec creates every wrapper before any transfer runs. With batch_size=1, a callback that waits in its wrappers until both are created hung on the first file.
    • Repair: _transfer_pairs() asks branch_coro() for each wrapper when it creates the coroutines, before any is scheduled. The task still joins the batch before its wrapper runs.
    • Test: test_transfers_are_wrapped_before_they_run fails at 798b7d3.
  2. Low: the cancellation test could pass with an upload pending. It slept 100 ms after releasing the wrapper.
    • Repair: the wrapper records its cancellation, and the test asserts it right after _put() raises, before anything is released.
  3. Medium (accepted): batch cancellation can interrupt a transfer's cleanup when a wrapper runs the transfer in a task of its own. If that child task already received a per-file cancellation, the batch's cancellation of the tracked wrapper is a second cancellation, which can stop S3Executor.run()'s wait for the running request.
    • This requires a callback whose branch_coro() wrapper creates its own task. It is a repeated interrupt of one operation, which the filesystem's interrupt guarantee covers only to the extent of no permanent hang.
    • The simple wrapper case (a wrapper that awaits before starting the transfer) is the one that Type put destinations and document path addressing (GH-1404) #1426 fixes, and keeping its task out of the batch would bring back the upload after cancellation. No change.

Validation at 7eb9cd6, rebased on 703aaad:

  • just lint and just benchmark test pass.
  • The filesystem suite against AWS, in parts: 1052 + 721 + 103 passed, 6 skipped.
  • CI at 798b7d3 (before the rebase) passed.

self,
transfer: Callable[..., Awaitable[Any]],
pairs: list[tuple[Any, Any]],
callback: Any,
**kwargs,
) -> list[Any]:
"""Run the transfers of lists of paths as fsspec's ``_get()`` and ``_put()`` do.

Each transfer receives its paths as they are, so that a listed key or
a destination named after a local file is transferred by its bucket
and key, and runs through the callback's ``branch_coro()``, as in
fsspec, with the paths as the names of its branch, an ``S3Path`` as
its string.

Args:
transfer: ``_get_file()`` or ``_put_file()``.
pairs: The sources and destinations.
callback: Progress callback.
**kwargs: Passed to the transfers, and ``batch_size``, the
number of transfers to run at once.

Returns:
The results of the transfers, as fsspec's ``_put()`` returns them.
"""
batch_size = kwargs.pop("batch_size", self.batch_size)
callback.set_size(len(pairs))

def run(path1: Any, path2: Any) -> Awaitable[Any]:
"""Return the transfer of a pair, run through the callback's ``branch_coro()``.

The callback wraps the transfer when the coroutine is created,
before any transfer is scheduled, as in fsspec. The task of the
transfer joins the batch before the wrapper runs, so that a
cancellation of the batch also stops a transfer whose wrapper is
still waiting to start it.

Args:
path1: The source.
path2: The destination.

Returns:
The coroutine of the transfer.
"""

async def transfer_pair(label1: Any, label2: Any, **transfer_kwargs: Any) -> Any:
"""Transfer the pair, whose branch the labels name.

Args:
label1: The name of the source in the branch.
label2: The name of the destination in the branch.
**transfer_kwargs: The arguments of the transfer, with the
branch of the callback.

Returns:
The result of the transfer.
"""
return await transfer(path1, path2, **transfer_kwargs)

branched = callback.branch_coro(transfer_pair)

async def tracked() -> Any:
"""Run the wrapped transfer as a task of the batch.

Returns:
The result of the transfer.
"""
_S3BatchTasks.track()
return await branched(
str(path1) if isinstance(path1, S3Path) else path1,
str(path2) if isinstance(path2, S3Path) else path2,
**kwargs,
)

return tracked()

return cast(
list[Any],
await _run_coros_in_chunks(
[run(p1, p2) for p1, p2 in pairs], batch_size=batch_size, callback=callback
),
)

async def _pipe(self, path, value=None, batch_size=None, **kwargs) -> list[Any]:
"""Write bytes into one or more paths.

Expand Down Expand Up @@ -1659,7 +1720,7 @@ async def _expand_path(self, path, recursive=False, maxdepth=None, **kwargs) ->

def _open(
self,
path: str,
path: str | S3Path,
mode: str = "rb",
block_size: int | None = None,
cache_type: str | None = None,
Expand Down Expand Up @@ -1785,13 +1846,14 @@ def rmdir(self, path: str | os.PathLike[str]) -> None:
"""
self._sync_fs.rmdir(path)

def sign(self, path: str | os.PathLike[str], expiration: int = 3600, **kwargs) -> str:
def sign(self, path: str | os.PathLike[str] | S3Path, expiration: int = 3600, **kwargs) -> str:
"""Generate a presigned URL for S3 object access.

See :meth:`S3FileSystem.sign`.

Args:
path: S3 path (s3://bucket/key) to generate the URL for.
path: S3 path (s3://bucket/key) to generate the URL for, or an
``S3Path``, as for :meth:`S3FileSystem.sign`.
expiration: URL expiration time in seconds.
**kwargs: Additional parameters passed to :meth:`S3FileSystem.sign`.

Expand All @@ -1800,27 +1862,31 @@ def sign(self, path: str | os.PathLike[str], expiration: int = 3600, **kwargs) -
"""
return cast(str, self._sync_fs.sign(path, expiration=expiration, **kwargs))

def metadata(self, path: str | os.PathLike[str], **kwargs) -> S3Metadata:
def metadata(self, path: str | os.PathLike[str] | S3Path, **kwargs) -> S3Metadata:
"""Return the metadata of the path.

See :meth:`S3FileSystem.metadata`.

Args:
path: S3 path (s3://bucket/key) to get metadata for.
path: S3 path (s3://bucket/key) to get metadata for, or an
``S3Path``, as for :meth:`S3FileSystem.metadata`.
**kwargs: Additional parameters passed to the HeadObject API.

Returns:
S3Metadata of the object.
"""
return self._sync_fs.metadata(path, **kwargs)

def getxattr(self, path: str | os.PathLike[str], attr_name: str, **kwargs) -> str | None:
def getxattr(
self, path: str | os.PathLike[str] | S3Path, attr_name: str, **kwargs
) -> str | None:
"""Get an attribute from the user-defined metadata of the path.

See :meth:`S3FileSystem.getxattr`.

Args:
path: S3 path (s3://bucket/key) to get the attribute for.
path: S3 path (s3://bucket/key) to get the attribute for, or an
``S3Path``.
attr_name: The name of the attribute.
**kwargs: Additional parameters passed to the HeadObject API.

Expand All @@ -1830,14 +1896,18 @@ def getxattr(self, path: str | os.PathLike[str], attr_name: str, **kwargs) -> st
return self._sync_fs.getxattr(path, attr_name, **kwargs)

def setxattr(
self, path: str | os.PathLike[str], copy_kwargs: dict[str, Any] | None = None, **kwargs
self,
path: str | os.PathLike[str] | S3Path,
copy_kwargs: dict[str, Any] | None = None,
**kwargs,
) -> None:
"""Set the user-defined metadata of the path.

See :meth:`S3FileSystem.setxattr`.

Args:
path: S3 path (s3://bucket/key) to set metadata for.
path: S3 path (s3://bucket/key) to set metadata for, or an
``S3Path``.
copy_kwargs: Additional parameters to use for the underlying
CopyObject API call.
**kwargs: Key-value pairs of metadata to set; a None value deletes the
Expand Down
Loading