From c12ec87bf5f2322c7bb6f29482e579df9457915f Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Tue, 17 Nov 2026 23:46:18 +0900 Subject: [PATCH 1/6] Type put destinations and document path addressing (GH-1404) put() and the async _put() named the destination of a local file by joining its name to the destination string, which was parsed again: a file named x?versionId=v1 was taken for version v1 of the key x, and the upload raised that a version cannot be written. - _put_pairs() returns an S3Path for a destination named after a local file: the destination root parsed, with the rest of the local name added to its key as it is (S3Path.with_key_suffix(), which s3_copy_pairs() of the pairing uses as well). A destination that is the root itself, or one of a list, stays the caller's string. - put_file() and the async _put_file(), also in a transaction, write an S3Path by its bucket and key; _open_path() opens it with open()'s transaction handling, and get_file() reads through it. - _S3LockedCallback names the branches of S3Path sources and destinations by their strings, so that the async _get() and _put() run fsspec's own loops for lists of paths again; _get_pairs() is removed. - docs/filesystem.md documents the addressing of keys that look like version paths (the S3Path methods, the string compositions, and the path string of a file opened with an S3Path) and of bucket//. Co-Authored-By: Claude Opus 5.5 --- docs/filesystem.md | 46 ++++++++++++ pyathena/filesystem/s3.py | 85 +++++++++++++++++----- pyathena/filesystem/s3_async.py | 77 ++++++++------------ pyathena/filesystem/s3_path.py | 24 ++++++ pyathena/filesystem/s3_path_pairing.py | 20 ++--- tests/pyathena/filesystem/test_s3.py | 67 +++++++++++++++++ tests/pyathena/filesystem/test_s3_async.py | 54 ++++++++++++++ tests/pyathena/filesystem/test_s3_path.py | 16 ++++ tests/pyathena/util.py | 4 +- 9 files changed, 313 insertions(+), 80 deletions(-) diff --git a/docs/filesystem.md b/docs/filesystem.md index b5954d306..97d436022 100644 --- a/docs/filesystem.md +++ b/docs/filesystem.md @@ -647,6 +647,52 @@ 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()` and `put_file()`, their asynchronous +counterparts, `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`. The `sign()`, `metadata()`, `getxattr()` and `setxattr()` of the +file, and a pickled copy of the file, use that path string. + +### 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 diff --git a/pyathena/filesystem/s3.py b/pyathena/filesystem/s3.py index 501dafe00..5f27840ed 100644 --- a/pyathena/filesystem/s3.py +++ b/pyathena/filesystem/s3.py @@ -199,6 +199,9 @@ def close(self) -> None: def branched(self, path_1, path_2, **kwargs) -> Callback: """Return a branch of the callback for the transfer of one file. + The paths are passed on as strings: an ``S3Path``, such as a listed + key or a destination named after a local file, as its string. + Args: path_1: The source of the transfer. path_2: The destination of the transfer. @@ -207,6 +210,8 @@ def branched(self, path_1, path_2, **kwargs) -> Callback: Returns: The branch, whose uses take the lock of this callback. """ + path_1 = str(path_1) if isinstance(path_1, S3Path) else path_1 + path_2 = str(path_2) if isinstance(path_2, S3Path) else path_2 with self._lock: return _S3LockedCallback(self._callback.branched(path_1, path_2, **kwargs), self._lock) @@ -3074,7 +3079,7 @@ def get_pair(pair: tuple[str | S3Path, Any]) -> None: is named after the source as a string. """ rp, lp = pair - with locked.branched(str(rp), lp) as child: + with locked.branched(rp, lp) as child: self.get_file(rp, lp, callback=child, **call_kwargs) locked.relative_update(1) @@ -3830,7 +3835,7 @@ def put( call_kwargs = self._batch_kwargs(concurrency, kwargs) locked = _S3LockedCallback(callback, threading.Lock()) - def put_pair(pair: tuple[str, str]) -> None: + def put_pair(pair: tuple[str, str | S3Path]) -> None: """Upload a pair with a branch of the callback. Args: @@ -3846,12 +3851,19 @@ def put_pair(pair: tuple[str, str]) -> None: def _put_pairs( self, lpath, rpath, recursive=False, maxdepth=None, **kwargs - ) -> list[tuple[str, str]]: + ) -> list[tuple[str, str | S3Path]]: """Pair the local sources of ``put()`` with their S3 destinations as fsspec does. The files are uploaded in parallel, so no two files may have the same destination; a local directory uploads nothing. + A destination named after a local file is an ``S3Path``: ``rpath`` + parsed, with the rest of the local name added to its key as it is + (see :meth:`S3Path.with_key_suffix`), so that a file named, e.g., + ``x?versionId=v1`` is written to that key instead of naming a + version. A destination that is ``rpath`` itself, or one of a list of + destinations, is the string that the caller passed. + Args: lpath: Local source path, glob pattern, or list of them. rpath: S3 destination path, or list of paths when ``lpath`` is a @@ -3866,10 +3878,14 @@ def _put_pairs( with their destinations without the protocol. Raises: - ValueError: If two files have the same destination. + ValueError: If two files have the same destination, or ``rpath`` + names a version and a destination is named after a local file + below it. """ if isinstance(lpath, list) and isinstance(rpath, list): - pairs = [(lp, self._strip_protocol(rp)) for lp, rp in zip(lpath, rpath, strict=False)] + pairs: list[tuple[str, str | S3Path]] = [ + (lp, self._strip_protocol(rp)) for lp, rp in zip(lpath, rpath, strict=False) + ] else: source_is_str = isinstance(lpath, str) if source_is_str: @@ -3888,7 +3904,19 @@ def _put_pairs( (has_magic(lpath) and len(lpaths) == 1) or (not has_magic(lpath) and dest_is_dir and not trailing_sep(lpath)) ) - rpaths = other_paths(lpaths, rpath, exists=exists, flatten=not source_is_str) + rpaths: list[str | S3Path] = other_paths( + lpaths, rpath, exists=exists, flatten=not source_is_str + ) + if isinstance(rpath, str) and any(rp != rpath for rp in rpaths): + root = S3Path.parse(rpath) + if root.version_id: + raise ValueError("Cannot write to the file with the version specified.") + # Every destination starts with rpath, which has no trailing + # slash, followed by the rest of the local name. + rpaths = [ + rp if rp == rpath else root.with_key_suffix(cast(str, rp)[len(rpath) :]) + for rp in rpaths + ] pairs = list(zip(lpaths, rpaths, strict=True)) # put_file() uploads nothing for a local directory. files = [rp for lp, rp in pairs if not os.path.isdir(lp)] @@ -3899,7 +3927,7 @@ def _put_pairs( 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, @@ -3914,7 +3942,8 @@ def put_file( 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" (default) or "create". With "create", the file is written as with ``open()`` in ``xb`` mode: raise @@ -3936,12 +3965,12 @@ def put_file( the method returns without performing any operation. Bucket-only destinations (without key) are also not supported. """ - rpath = stringify_path(rpath) + target: str | S3Path = rpath if isinstance(rpath, S3Path) else stringify_path(rpath) if os.path.isdir(lpath): # No support for directory uploads. return - if not S3Path.parse(rpath).key: + if not S3Path.of(target).key: # No support for bucket copy. return @@ -3960,15 +3989,15 @@ def put_file( # The local file is opened first, so that an unreadable one fails # before the remote file is opened. with open(lpath, "rb") as local: - self.open( - rpath, + self._open_path( + target, "xb" if mode == "create" else "wb", block_size=block_size, max_workers=max_workers, s3_additional_kwargs=s3_additional_kwargs, )._write_file_and_close(local, callback) - self.invalidate_cache(rpath) + self._invalidate(S3Path.of(target)) def get_file( self, @@ -4044,11 +4073,7 @@ def get_file( # The remote file is opened first so that no local file is created # when open() finds no object at the path. with contextlib.ExitStack() as stack: - remote = stack.enter_context( - self._open(rpath, "rb", **kwargs) - if isinstance(rpath, S3Path) - else self.open(rpath, "rb", **kwargs) - ) + remote = stack.enter_context(self._open_path(rpath, "rb", **kwargs)) reader: Any = None if codec is not None: # As fsspec's open() wraps the file, but closed with it. @@ -4772,6 +4797,30 @@ def _ls_from_cache(self, path: S3Path) -> list[S3Object] | S3Object | None: # so a bucket missing from it is looked up with HeadBucket. return None + def _open_path(self, path: str | os.PathLike[str] | S3Path, mode: str, **kwargs) -> S3File: + """Open a binary file as ``open()`` does, also for an ``S3Path``. + + A path string is opened with ``open()``. An ``S3Path`` is opened by + its bucket, key and version, and a file written in a transaction of + the filesystem joins it, as with ``open()``. + + Args: + path: S3 path (s3://bucket/key), or an ``S3Path``. + mode: A binary mode of ``open()``. + **kwargs: The other arguments of ``open()``, except + ``compression``. + + Returns: + The file. + """ + if not isinstance(path, S3Path): + return cast(S3File, self.open(path, mode, **kwargs)) + autocommit = kwargs.pop("autocommit", not self._intrans) + file = self._open(path, mode, autocommit=autocommit, **kwargs) + if not autocommit and "r" not in mode: + self.transaction.files.append(file) + return file + def _open( self, path: str | S3Path, diff --git a/pyathena/filesystem/s3_async.py b/pyathena/filesystem/s3_async.py index 555c01445..21d2fc49c 100644 --- a/pyathena/filesystem/s3_async.py +++ b/pyathena/filesystem/s3_async.py @@ -42,6 +42,7 @@ S3File, S3FileSystem, S3FileTarget, + _S3LockedCallback, ) from pyathena.filesystem.s3_core import S3Core from pyathena.filesystem.s3_executor import ItemT, S3Executor, S3MapResult, S3ThreadPool, T @@ -190,11 +191,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 @@ -205,7 +207,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 @@ -541,29 +548,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], @@ -576,7 +583,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 @@ -595,7 +603,7 @@ def _put_file_in_transaction( """ if os.path.isdir(lpath): return - if not S3Path.parse(rpath).key: + if not S3Path.of(rpath).key: return size = os.path.getsize(lpath) @@ -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._sync_fs._invalidate(S3Path.of(rpath)) async def _get_file( self, @@ -930,41 +938,13 @@ async def _get( 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. - """ - 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 + super()._get( + [rp for rp, _ in pairs], + [lp for _, lp in pairs], + # Names the branches after the sources as strings. + callback=_S3LockedCallback(callback, threading.Lock()), + **self._sync_fs._batch_kwargs(concurrency, kwargs), + ) ) async def _put( @@ -1012,7 +992,8 @@ async def _put( super()._put( [lp for lp, _ in files], [rp for _, rp in files], - callback=callback, + # Names the branches after the destinations as strings. + callback=_S3LockedCallback(callback, threading.Lock()), batch_size=batch_size, **kwargs, ) @@ -1659,7 +1640,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, diff --git a/pyathena/filesystem/s3_path.py b/pyathena/filesystem/s3_path.py index 84249c9e4..8477163bb 100644 --- a/pyathena/filesystem/s3_path.py +++ b/pyathena/filesystem/s3_path.py @@ -177,6 +177,30 @@ def target(self) -> S3Path: """ return self.with_version_id(None) if self.version_id == "null" else self + def with_key_suffix(self, suffix: str) -> S3Path: + """Return the path that a suffix names below this one, with the suffix as it is. + + The suffix, such as ``/x?versionId=null`` taken from a listed key or + a local file name, is appended to the key without being parsed, so + that it names a key that ends in what looks like a version ID query. + A bucket path takes the suffix without its leading slash as its key, + and an empty suffix names this path. + + Args: + suffix: The suffix of the key, such as ``/x``. + + Returns: + The path. + + Raises: + ValueError: If this path has a version, which names an object + and no paths below it. + """ + if self.version_id: + raise ValueError(f"Cannot name a path below the versioned path {self}.") + key = f"{self.key}{suffix}" if self.key else suffix.removeprefix("/") + return S3Path(self.bucket, key) + def with_version_id(self, version_id: str | None) -> S3Path: """Return the path with another version ID. diff --git a/pyathena/filesystem/s3_path_pairing.py b/pyathena/filesystem/s3_path_pairing.py index 52a5bf805..5b3e47a3f 100644 --- a/pyathena/filesystem/s3_path_pairing.py +++ b/pyathena/filesystem/s3_path_pairing.py @@ -159,8 +159,9 @@ def s3_copy_pairs( The destination of an ``S3Path`` source, when ``path2`` is a string, is an ``S3Path`` too: ``path2`` parsed, with the suffix that - :meth:`copy_pairs` appends to it added to its key as it is, so that a - key such as ``a/x?versionId=null`` is copied to the key + :meth:`copy_pairs` appends to it added to its key as it is (see + :meth:`~pyathena.filesystem.s3_path.S3Path.with_key_suffix`), so that + a key such as ``a/x?versionId=null`` is copied to the key ``b/x?versionId=null`` instead of being parsed as a version. The other destinations are strings, as :meth:`copy_pairs` returns them. @@ -183,17 +184,10 @@ def s3_copy_pairs( # path2 without its trailing slashes, followed by the suffix. root_name = self.path2.rstrip("/") root = S3Path.parse(root_name) - if root.version_id: - raise ValueError("Cannot copy to a versioned file.") - typed: list[tuple[str | S3Path, str | S3Path]] = [] - for p1, p2 in pairs: - if isinstance(p1, S3Path): - suffix = p2[len(root_name) :] - key = f"{root.key}{suffix}" if root.key else suffix.removeprefix("/") - typed.append((p1, S3Path(root.bucket, key))) - else: - typed.append((p1, p2)) - return typed + return [ + (p1, root.with_key_suffix(p2[len(root_name) :]) if isinstance(p1, S3Path) else p2) + for p1, p2 in pairs + ] def conflict_candidates( self, diff --git a/tests/pyathena/filesystem/test_s3.py b/tests/pyathena/filesystem/test_s3.py index c9a6d3ecd..1459c1091 100644 --- a/tests/pyathena/filesystem/test_s3.py +++ b/tests/pyathena/filesystem/test_s3.py @@ -1369,6 +1369,73 @@ def test_expansion_acts_on_an_object_once(self, call, sent): call(fs) assert [t for t in s3_request_targets(requests) if t[0] != "head_object"] == sent + @pytest.mark.parametrize( + ("source", "kwargs", "sent"), + [ + pytest.param( + "x?versionId=v1", {}, [("put_object", "up/x?versionId=v1", None)], id="file" + ), + pytest.param( + "", {"recursive": True}, [("put_object", "up/x?versionId=v1", None)], id="dir" + ), + pytest.param( + "x?versionId=v1", + {"mode": "create"}, + [ + ("head_object", "up/x?versionId=v1", None), + ("put_object", "up/x?versionId=v1", "*"), + ], + id="create", + ), + ], + ) + def test_put_names_destinations_after_local_files(self, tmp_path, source, kwargs, sent): + # GH-1404: put() writes a local file to the key named after it as it + # is, also when its name ends in what looks like a version ID query, + # and names the branch of the callback after the key as a string. + fs = S3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + store, requests = serve_s3_keys(fs, set()) + (tmp_path / "x?versionId=v1").write_bytes(b"aa") + callback = BranchRecordingCallback() + fs.put(f"{tmp_path}/{source}", "s3://bucket/up/", callback=callback, **kwargs) + assert store == {"up/x?versionId=v1"} + assert [ + (name, request.get("Key"), request.get("IfNoneMatch")) + for name, request in requests + if name != "list_objects_v2" + ] == sent + assert "bucket/up/x?versionId=v1" in callback.destinations + + def test_put_in_transaction_names_destinations_after_local_files(self, tmp_path): + # GH-1404: the file of a destination named after a local file joins + # the transaction, as one opened with open() does. + fs = S3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + store, _ = serve_s3_keys(fs, set()) + (tmp_path / "x?versionId=v1").write_bytes(b"aa") + with fs.transaction: + fs.put(str(tmp_path / "x?versionId=v1"), "s3://bucket/up/") + assert store == set() + assert store == {"up/x?versionId=v1"} + + def test_open_appends_to_path_as_it_is(self): + # GH-1404: a file opened in append mode with an S3Path looks up, + # reads and writes the key as it is. + fs = S3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + _, requests = serve_s3_keys(fs, self.NULL_KEYS) + with S3File(fs, S3Path("bucket", "a/x?versionId=null"), "ab") as f: + f.write(b"bb") + assert s3_request_targets(requests) == [ + ("get_object", "a/x?versionId=null", None), + ("head_object", "a/x?versionId=null", None), + ("put_object", "a/x?versionId=null", None), + ] + def test_expand_path_expands_below_listed_matches(self): # GH-1402: a recursive glob expands below each match by its key prefix. fs = S3FileSystem( diff --git a/tests/pyathena/filesystem/test_s3_async.py b/tests/pyathena/filesystem/test_s3_async.py index eb0b020d6..b76f9719e 100644 --- a/tests/pyathena/filesystem/test_s3_async.py +++ b/tests/pyathena/filesystem/test_s3_async.py @@ -797,6 +797,60 @@ async def test_get_downloads_listed_keys(self, tmp_path): ] assert sorted(callback.sources) == ["bucket/a", "bucket/a/x", "bucket/a/x?versionId=null"] + @pytest.mark.parametrize( + ("source", "kwargs", "sent"), + [ + pytest.param( + "x?versionId=v1", {}, [("put_object", "up/x?versionId=v1", None)], id="file" + ), + pytest.param( + "", {"recursive": True}, [("put_object", "up/x?versionId=v1", None)], id="dir" + ), + pytest.param( + "x?versionId=v1", + {"mode": "create"}, + [ + ("head_object", "up/x?versionId=v1", None), + ("put_object", "up/x?versionId=v1", "*"), + ], + id="create", + ), + ], + ) + @pytest.mark.asyncio + async def test_put_names_destinations_after_local_files(self, tmp_path, source, kwargs, sent): + # GH-1404: _put() writes the keys named after local files as put() + # does, with the branches of the callback named after them as strings. + fs = AioS3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + store, requests = serve_s3_keys(fs._sync_fs, set()) + (tmp_path / "x?versionId=v1").write_bytes(b"aa") + callback = BranchRecordingCallback() + await await_bounded( + fs._put(f"{tmp_path}/{source}", "s3://bucket/up/", callback=callback, **kwargs) + ) + assert store == {"up/x?versionId=v1"} + assert [ + (name, request.get("Key"), request.get("IfNoneMatch")) + for name, request in requests + if name != "list_objects_v2" + ] == sent + assert callback.destinations == ["bucket/up/x?versionId=v1"] + + def test_put_in_transaction_names_destinations_after_local_files(self, tmp_path): + # GH-1404: in a transaction, the file of a destination named after a + # local file joins the transaction of this filesystem. + fs = AioS3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + store, _ = serve_s3_keys(fs._sync_fs, set()) + (tmp_path / "x?versionId=v1").write_bytes(b"aa") + with fs.transaction: + fs.put(str(tmp_path / "x?versionId=v1"), "s3://bucket/up/") + assert store == set() + assert store == {"up/x?versionId=v1"} + @pytest.mark.asyncio async def test_du_cancellation_sends_no_further_lookup(self): # GH-1402: as fsspec's _du(), the lookups of the found entries are diff --git a/tests/pyathena/filesystem/test_s3_path.py b/tests/pyathena/filesystem/test_s3_path.py index c72749c67..3cad9d81e 100644 --- a/tests/pyathena/filesystem/test_s3_path.py +++ b/tests/pyathena/filesystem/test_s3_path.py @@ -62,6 +62,22 @@ def test_of(self): assert S3Path.of(listed) is listed assert S3Path.of("s3://bucket/a/x?versionId=null") == S3Path("bucket", "a/x", "null") + @pytest.mark.parametrize( + ("path", "suffix", "expected"), + [ + (S3Path("bucket", "up"), "/x?versionId=v1", S3Path("bucket", "up/x?versionId=v1")), + (S3Path("bucket"), "/x?versionId=v1", S3Path("bucket", "x?versionId=v1")), + (S3Path("bucket", "up"), "", S3Path("bucket", "up")), + ], + ) + def test_with_key_suffix(self, path, suffix, expected): + # GH-1404: the suffix is added to the key as it is, never parsed. + assert path.with_key_suffix(suffix) == expected + + def test_with_key_suffix_of_version(self): + with pytest.raises(ValueError, match="versioned"): + S3Path("bucket", "up", "v1").with_key_suffix("/x") + def test_empty_key_is_the_bucket(self): # GH-1401: an empty key names the bucket, which the path prints as. assert S3Path("bucket", "") == S3Path("bucket") diff --git a/tests/pyathena/util.py b/tests/pyathena/util.py index 143912293..41dc237a4 100644 --- a/tests/pyathena/util.py +++ b/tests/pyathena/util.py @@ -1815,14 +1815,16 @@ def __fspath__(self): class BranchRecordingCallback(Callback): - """A progress callback that records the source paths of its branches.""" + """A progress callback that records the source and destination paths of its branches.""" def __init__(self): super().__init__() self.sources = [] + self.destinations = [] def branched(self, path_1, path_2, **kwargs): self.sources.append(path_1) + self.destinations.append(path_2) return super().branched(path_1, path_2, **kwargs) From b228a1e1ef90241a8dacb460d7fdc82893ff62cf Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Wed, 18 Nov 2026 00:16:14 +0900 Subject: [PATCH 2/6] Address files by their paths and keep async callbacks unlocked (GH-1404) Review repairs: - url(), metadata(), getxattr() and setxattr() of a file address its bucket, key and version: sign(), metadata(), getxattr() and setxattr() of the filesystems accept an S3Path. A file opened with the S3Path of a key such as a/x?versionId=null signed and looked up the null version of a/x. Only a pickled copy still reopens the path string, which the docs say. - The async _get() and _put() name the branches of their callback after their paths as strings in a transfer loop of their own, as fsspec runs them, instead of taking the lock of _S3LockedCallback on the event loop, which a callback that calls the filesystem could deadlock. - copy() and put() to a destination root that names a version raise their own messages again, and put() and _put() say so. - _put_pairs() returns early when no destination is named after a local file, put_file() parses its destination once, and the async transaction write invalidates through the filesystem. - The append test of a typed path moves to TestS3File, and the sync put test compares the labels of the callback exactly. Co-Authored-By: Claude Opus 5.5 --- docs/filesystem.md | 14 ++-- pyathena/filesystem/s3.py | 79 ++++++++++-------- pyathena/filesystem/s3_async.py | 107 +++++++++++++++++++------ pyathena/filesystem/s3_path_pairing.py | 2 + tests/pyathena/filesystem/test_s3.py | 88 +++++++++++++++----- 5 files changed, 204 insertions(+), 86 deletions(-) diff --git a/docs/filesystem.md b/docs/filesystem.md index 97d436022..f3686a022 100644 --- a/docs/filesystem.md +++ b/docs/filesystem.md @@ -668,10 +668,11 @@ fs.get_file(path, "local-file") fs.put_file("local-file", path) ``` -`info()`, `cat_file()`, `cp_file()`, `get_file()` and `put_file()`, their asynchronous -counterparts, `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. +`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()` @@ -682,8 +683,9 @@ path string, names the version. The same holds for the compositions that pass pa 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`. The `sign()`, `metadata()`, `getxattr()` and `setxattr()` of the -file, and a pickled copy of the file, use that path string. +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 diff --git a/pyathena/filesystem/s3.py b/pyathena/filesystem/s3.py index 5f27840ed..161ff3934 100644 --- a/pyathena/filesystem/s3.py +++ b/pyathena/filesystem/s3.py @@ -199,9 +199,6 @@ def close(self) -> None: def branched(self, path_1, path_2, **kwargs) -> Callback: """Return a branch of the callback for the transfer of one file. - The paths are passed on as strings: an ``S3Path``, such as a listed - key or a destination named after a local file, as its string. - Args: path_1: The source of the transfer. path_2: The destination of the transfer. @@ -210,8 +207,6 @@ def branched(self, path_1, path_2, **kwargs) -> Callback: Returns: The branch, whose uses take the lock of this callback. """ - path_1 = str(path_1) if isinstance(path_1, S3Path) else path_1 - path_2 = str(path_2) if isinstance(path_2, S3Path) else path_2 with self._lock: return _S3LockedCallback(self._callback.branched(path_1, path_2, **kwargs), self._lock) @@ -3079,7 +3074,7 @@ def get_pair(pair: tuple[str | S3Path, Any]) -> None: is named after the source as a string. """ rp, lp = pair - with locked.branched(rp, lp) as child: + with locked.branched(str(rp), lp) as child: self.get_file(rp, lp, callback=child, **call_kwargs) locked.relative_update(1) @@ -3823,8 +3818,10 @@ def put( **kwargs: Additional parameters passed to ``put_file()``. Raises: - ValueError: If two files have the same destination, or - ``batch_size`` is neither positive, -1, nor None. + ValueError: If two files have the same destination, ``rpath`` + names a version and a destination is named after a local + file below it, or ``batch_size`` is neither positive, -1, nor + None. """ lpath, rpath = self._stringify_paths(lpath), self._stringify_paths(rpath) limit = self._batch_limit(batch_size) @@ -3842,7 +3839,8 @@ def put_pair(pair: tuple[str, str | S3Path]) -> None: pair: The local source and its S3 destination. """ lp, rp = pair - with locked.branched(lp, rp) as child: + # Named after the destination as a string. + with locked.branched(lp, str(rp)) as child: self.put_file(lp, rp, callback=child, **call_kwargs) locked.relative_update(1) @@ -3970,7 +3968,8 @@ def put_file( # No support for directory uploads. return - if not S3Path.of(target).key: + s3_path = S3Path.of(target) + if not s3_path.key: # No support for bucket copy. return @@ -3997,7 +3996,7 @@ def put_file( s3_additional_kwargs=s3_additional_kwargs, )._write_file_and_close(local, callback) - self._invalidate(S3Path.of(target)) + self._invalidate(s3_path) def get_file( self, @@ -4120,7 +4119,7 @@ def checksum(self, path: str | os.PathLike[str], **kwargs): return int(info.get("etag").strip('"').split("-")[0], 16) return int(tokenize(info), 16) - def sign(self, path: str | os.PathLike[str], expiration: int = 3600, **kwargs): + def sign(self, path: str | os.PathLike[str] | S3Path, expiration: int = 3600, **kwargs): """Generate a presigned URL for S3 object access. Creates a presigned URL that allows temporary access to an S3 object @@ -4128,7 +4127,8 @@ def sign(self, path: str | os.PathLike[str], expiration: int = 3600, **kwargs): time-limited access to resources. Args: - path: S3 path (s3://bucket/key) to generate URL for. + path: S3 path (s3://bucket/key) to generate URL for, or an + ``S3Path``, whose bucket, key and version are used as they are. expiration: URL expiration time in seconds. Defaults to 3600 (1 hour). **kwargs: Additional parameters including: client_method: S3 operation ('get_object', 'put_object', etc.). @@ -4149,17 +4149,16 @@ def sign(self, path: str | os.PathLike[str], expiration: int = 3600, **kwargs): ... client_method="put_object" ... ) """ - path = stringify_path(path) + s3_path = S3Path.of(path if isinstance(path, S3Path) else stringify_path(path)) client_method = kwargs.pop("client_method", "get_object") - return self.core.generate_presigned_url( - S3Path.parse(path), client_method, expiration, **kwargs - ) + return self.core.generate_presigned_url(s3_path, client_method, 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. Args: - path: S3 path (s3://bucket/key) to get metadata for. + path: S3 path (s3://bucket/key) to get metadata for, or an + ``S3Path``, whose bucket, key and version are used as they are. **kwargs: Additional parameters passed to the HeadObject API. Returns: @@ -4168,18 +4167,20 @@ def metadata(self, path: str | os.PathLike[str], **kwargs) -> S3Metadata: system-defined metadata (content type, encryption settings, etc.) as typed properties. """ - path = stringify_path(path) - s3_path = S3Path.parse(path) + s3_path = S3Path.of(path if isinstance(path, S3Path) else stringify_path(path)) if not s3_path.key: raise ValueError("Cannot get metadata of a bucket.") _logger.debug(f"Head object metadata: {s3_path.uri}") return self.core.head_object(s3_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. 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``, as for :meth:`metadata`. attr_name: The name of the attribute. **kwargs: Additional parameters passed to :meth:`metadata`. @@ -4189,7 +4190,10 @@ def getxattr(self, path: str | os.PathLike[str], attr_name: str, **kwargs) -> st return self.metadata(path, **kwargs).get(attr_name) def setxattr( - self, path: str | os.PathLike[str], copy_kwargs: dict[str, Any] | None = None, **kw_args + self, + path: str | os.PathLike[str] | S3Path, + copy_kwargs: dict[str, Any] | None = None, + **kw_args, ) -> None: """Set the user-defined metadata of the path. @@ -4203,9 +4207,10 @@ def setxattr( ``Expires`` value that botocore cannot parse as a date is not kept. Args: - path: S3 path (s3://bucket/key) to set metadata for. A path with - a version ID is rejected, since copying a version onto the - key would replace the current object with it. + path: S3 path (s3://bucket/key) to set metadata for, or an + ``S3Path``, as for :meth:`metadata`. A path with a version ID + is rejected, since copying a version onto the key would + replace the current object with it. copy_kwargs: Additional parameters to use for the underlying CopyObject API call. They take precedence over the kept system-defined metadata and storage class. Any encryption @@ -4229,8 +4234,7 @@ def setxattr( Raises: ValueError: If the path is a bucket or has a version ID. """ - path = stringify_path(path) - s3_path = S3Path.parse(path) + s3_path = S3Path.of(path if isinstance(path, S3Path) else stringify_path(path)) if not s3_path.key: raise ValueError("Cannot set metadata of a bucket.") if s3_path.version_id: @@ -4238,7 +4242,7 @@ def setxattr( copy_kwargs = copy_kwargs or {} # Looked up with the parameters that authorize the access to the # object as the source of the copy, such as its customer-provided key. - head = self.metadata(path, **self.core.copy_source_params(copy_kwargs)) + head = self.metadata(s3_path, **self.core.copy_source_params(copy_kwargs)) metadata = dict(head) for k, v in kw_args.items(): if v is None: @@ -4246,7 +4250,7 @@ def setxattr( else: metadata[k] = v self.core.replace_object_metadata(s3_path, head, metadata, **copy_kwargs) - self.invalidate_cache(path) + self._invalidate(s3_path) def get_tags(self, path: str | os.PathLike[str]) -> dict[str, str]: """Retrieve the tag key/values for the given path. @@ -5251,6 +5255,11 @@ def __init__( self.append_block = True self._append_size = self.loc = target.appended.get("size", 0) + @property + def _s3_path(self) -> S3Path: + """The bucket, key and version of the object that the file reads or writes.""" + return S3Path(self.bucket, self.key, self.version_id) + def _get_request_kwargs(self, method: str) -> dict[str, Any]: """Select the parameters of the file that an S3 operation accepts. @@ -5858,7 +5867,7 @@ def url(self, expiration: int = 3600, **kwargs) -> str: params = self.fs.core.operation_params( kwargs.get("client_method", "get_object"), self._lookup_kwargs() ) - return cast(str, self.fs.sign(self.path, expiration=expiration, **{**params, **kwargs})) + return cast(str, self.fs.sign(self._s3_path, expiration=expiration, **{**params, **kwargs})) def metadata(self, **kwargs) -> S3Metadata: """Return the metadata of the file. @@ -5876,7 +5885,7 @@ def metadata(self, **kwargs) -> S3Metadata: user-defined metadata and exposes the system-defined metadata as typed properties. """ - return self.fs.metadata(self.path, **{**self._lookup_kwargs(), **kwargs}) + return self.fs.metadata(self._s3_path, **{**self._lookup_kwargs(), **kwargs}) def getxattr(self, xattr_name: str, **kwargs) -> str | None: """Get an attribute from the user-defined metadata of the file. @@ -5892,7 +5901,7 @@ def getxattr(self, xattr_name: str, **kwargs) -> str | None: Returns: The value of the attribute, or None if the attribute is not set. """ - return self.fs.getxattr(self.path, xattr_name, **{**self._lookup_kwargs(), **kwargs}) + return self.fs.getxattr(self._s3_path, xattr_name, **{**self._lookup_kwargs(), **kwargs}) def setxattr(self, copy_kwargs: dict[str, Any] | None = None, **kwargs) -> None: """Set the user-defined metadata of the file. @@ -5924,7 +5933,7 @@ def setxattr(self, copy_kwargs: dict[str, Any] | None = None, **kwargs) -> None: k: v for k, v in lookup_kwargs.items() if not k.startswith("SSECustomer") } self.fs.setxattr( - self.path, + self._s3_path, copy_kwargs={ **destination, **self.fs.core.copy_from_source_params(lookup_kwargs), diff --git a/pyathena/filesystem/s3_async.py b/pyathena/filesystem/s3_async.py index 21d2fc49c..fbecb6cb1 100644 --- a/pyathena/filesystem/s3_async.py +++ b/pyathena/filesystem/s3_async.py @@ -42,7 +42,6 @@ S3File, S3FileSystem, S3FileTarget, - _S3LockedCallback, ) from pyathena.filesystem.s3_core import S3Core from pyathena.filesystem.s3_executor import ItemT, S3Executor, S3MapResult, S3ThreadPool, T @@ -603,7 +602,8 @@ def _put_file_in_transaction( """ if os.path.isdir(lpath): return - if not S3Path.of(rpath).key: + s3_path = S3Path.of(rpath) + if not s3_path.key: return size = os.path.getsize(lpath) @@ -627,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._sync_fs._invalidate(S3Path.of(rpath)) + self._invalidate(s3_path) async def _get_file( self, @@ -937,13 +937,13 @@ 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) + # As fsspec's _get() for lists of paths. + for _, lp in pairs: + # A local path, as copy_pairs() names it. + os.makedirs(os.path.dirname(cast(str, lp)), exist_ok=True) await _S3BatchTasks().run( - super()._get( - [rp for rp, _ in pairs], - [lp for _, lp in pairs], - # Names the branches after the sources as strings. - callback=_S3LockedCallback(callback, threading.Lock()), - **self._sync_fs._batch_kwargs(concurrency, kwargs), + self._transfer_pairs( + self._get_file, pairs, callback, **self._sync_fs._batch_kwargs(concurrency, kwargs) ) ) @@ -981,7 +981,9 @@ 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 ``rpath`` + names a version and a destination is named after a local file + below it. """ lpath, rpath = self._sync_fs._stringify_paths(lpath), self._sync_fs._stringify_paths(rpath) pairs = await self._thread_pool.run( @@ -989,16 +991,62 @@ async def _put( ) 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], - # Names the branches after the destinations as strings. - callback=_S3LockedCallback(callback, threading.Lock()), - 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( + 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 gets a branch of the callback named after its paths, 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)) + + async def run(path1: Any, path2: Any) -> Any: + """Run a transfer with a branch of the callback. + + Args: + path1: The source. + path2: The destination. + + Returns: + The result of the transfer. + """ + with callback.branched( + str(path1) if isinstance(path1, S3Path) else path1, + str(path2) if isinstance(path2, S3Path) else path2, + **kwargs, + ) as child: + return await transfer(path1, path2, callback=child, **kwargs) + + 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. @@ -1766,13 +1814,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`. @@ -1781,13 +1830,14 @@ 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: @@ -1795,13 +1845,16 @@ def metadata(self, path: str | os.PathLike[str], **kwargs) -> S3Metadata: """ 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. @@ -1811,14 +1864,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 diff --git a/pyathena/filesystem/s3_path_pairing.py b/pyathena/filesystem/s3_path_pairing.py index 5b3e47a3f..69cfe828b 100644 --- a/pyathena/filesystem/s3_path_pairing.py +++ b/pyathena/filesystem/s3_path_pairing.py @@ -184,6 +184,8 @@ def s3_copy_pairs( # path2 without its trailing slashes, followed by the suffix. root_name = self.path2.rstrip("/") root = S3Path.parse(root_name) + if root.version_id: + raise ValueError("Cannot copy to a versioned file.") return [ (p1, root.with_key_suffix(p2[len(root_name) :]) if isinstance(p1, S3Path) else p2) for p1, p2 in pairs diff --git a/tests/pyathena/filesystem/test_s3.py b/tests/pyathena/filesystem/test_s3.py index 1459c1091..b4b0340b4 100644 --- a/tests/pyathena/filesystem/test_s3.py +++ b/tests/pyathena/filesystem/test_s3.py @@ -1370,13 +1370,22 @@ def test_expansion_acts_on_an_object_once(self, call, sent): assert [t for t in s3_request_targets(requests) if t[0] != "head_object"] == sent @pytest.mark.parametrize( - ("source", "kwargs", "sent"), + ("source", "kwargs", "sent", "labels"), [ pytest.param( - "x?versionId=v1", {}, [("put_object", "up/x?versionId=v1", None)], id="file" + "x?versionId=v1", + {}, + [("put_object", "up/x?versionId=v1", None)], + ["bucket/up/x?versionId=v1"], + id="file", ), pytest.param( - "", {"recursive": True}, [("put_object", "up/x?versionId=v1", None)], id="dir" + "", + {"recursive": True}, + [("put_object", "up/x?versionId=v1", None)], + # The directory itself is paired with the destination root. + ["bucket/up", "bucket/up/x?versionId=v1"], + id="dir", ), pytest.param( "x?versionId=v1", @@ -1385,11 +1394,12 @@ def test_expansion_acts_on_an_object_once(self, call, sent): ("head_object", "up/x?versionId=v1", None), ("put_object", "up/x?versionId=v1", "*"), ], + ["bucket/up/x?versionId=v1"], id="create", ), ], ) - def test_put_names_destinations_after_local_files(self, tmp_path, source, kwargs, sent): + def test_put_names_destinations_after_local_files(self, tmp_path, source, kwargs, sent, labels): # GH-1404: put() writes a local file to the key named after it as it # is, also when its name ends in what looks like a version ID query, # and names the branch of the callback after the key as a string. @@ -1406,7 +1416,7 @@ def test_put_names_destinations_after_local_files(self, tmp_path, source, kwargs for name, request in requests if name != "list_objects_v2" ] == sent - assert "bucket/up/x?versionId=v1" in callback.destinations + assert sorted(callback.destinations) == labels def test_put_in_transaction_names_destinations_after_local_files(self, tmp_path): # GH-1404: the file of a destination named after a local file joins @@ -1421,21 +1431,6 @@ def test_put_in_transaction_names_destinations_after_local_files(self, tmp_path) assert store == set() assert store == {"up/x?versionId=v1"} - def test_open_appends_to_path_as_it_is(self): - # GH-1404: a file opened in append mode with an S3Path looks up, - # reads and writes the key as it is. - fs = S3FileSystem( - key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True - ) - _, requests = serve_s3_keys(fs, self.NULL_KEYS) - with S3File(fs, S3Path("bucket", "a/x?versionId=null"), "ab") as f: - f.write(b"bb") - assert s3_request_targets(requests) == [ - ("get_object", "a/x?versionId=null", None), - ("head_object", "a/x?versionId=null", None), - ("put_object", "a/x?versionId=null", None), - ] - def test_expand_path_expands_below_listed_matches(self): # GH-1402: a recursive glob expands below each match by its key prefix. fs = S3FileSystem( @@ -8563,6 +8558,59 @@ def test_pandas_write_csv(self, line_count): class TestS3File: + def test_append_to_path_as_it_is(self): + # GH-1404: a file opened in append mode with an S3Path looks up, + # reads and writes the key as it is. + fs = S3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + _, requests = serve_s3_keys(fs, {"a/x", "a/x?versionId=null"}) + with S3File(fs, S3Path("bucket", "a/x?versionId=null"), "ab") as f: + f.write(b"bb") + assert s3_request_targets(requests) == [ + ("get_object", "a/x?versionId=null", None), + ("head_object", "a/x?versionId=null", None), + ("put_object", "a/x?versionId=null", None), + ] + + @pytest.mark.parametrize( + ("call", "sent"), + [ + pytest.param( + lambda f: f.url(), + [("generate_presigned_url", S3Path("bucket", "a/x?versionId=null"))], + id="url", + ), + pytest.param( + lambda f: f.metadata(), [("head_object", "a/x?versionId=null")], id="metadata" + ), + pytest.param( + lambda f: f.getxattr("m"), [("head_object", "a/x?versionId=null")], id="getxattr" + ), + pytest.param( + lambda f: f.setxattr(n="2"), + [("head_object", "a/x?versionId=null"), ("copy_object", "a/x?versionId=null")], + id="setxattr", + ), + ], + ) + def test_path_methods_address_path_as_it_is(self, call, sent): + # GH-1404: the methods of a file opened with an S3Path address its + # bucket, key and version, not its path string, which would name the + # null version of a/x. + fs = S3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + _, requests = serve_s3_keys(fs, {"a/x", "a/x?versionId=null"}) + with S3File(fs, S3Path("bucket", "a/x?versionId=null"), "rb") as f: + del requests[:] + call(f) + assert [ + (name, request["args"][0] if "args" in request else request.get("Key")) + for name, request in requests + if request.get("VersionId") is None and name != "list_objects_v2" + ] == sent + @pytest.mark.parametrize("mode", ["wb", "ab"]) def test_repeated_creation_interrupt(self, mode): # GH-1077: an interrupt of the write's wait for the creation of its From 919067b049120f902eec36eca5296a1aaafc8e5c Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Sat, 21 Nov 2026 21:48:19 +0900 Subject: [PATCH 3/6] Compare the put destinations of the directory test as strings (GH-1404) The destinations that put() names after local files are S3Path objects, so the test of #1398 that sorts them compares their strings. Co-Authored-By: Claude Opus 5.5 --- tests/pyathena/filesystem/test_s3.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/pyathena/filesystem/test_s3.py b/tests/pyathena/filesystem/test_s3.py index b4b0340b4..785664bcd 100644 --- a/tests/pyathena/filesystem/test_s3.py +++ b/tests/pyathena/filesystem/test_s3.py @@ -3276,7 +3276,8 @@ def test_put_directories_with_one_destination(self, tmp_path): "s3://bucket/x/", recursive=True, ) - files = [c.args[1] for c in fs.put_file.call_args_list if not os.path.isdir(c.args[0])] + # The destinations named after the local files are S3Path objects. + files = [str(c.args[1]) for c in fs.put_file.call_args_list if not os.path.isdir(c.args[0])] assert sorted(files) == ["bucket/x/f1", "bucket/x/f2"] def test_copy_skipped_directory_does_not_conflict(self): From 032abc35043f0e7fc000f6b1bccb3936cbd1c8cd Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Sat, 21 Nov 2026 22:08:40 +0900 Subject: [PATCH 4/6] Check versioned roots only for files and branch through branch_coro (GH-1404) Independent review of the rebase onto #1398: - put() and _put() raise for a root that names a version only when a local file is named below it; local directories, which upload nothing, keep their string destinations, so a tree of empty directories uploads nothing again instead of raising. - The transfers of the async _get() and _put() run through the callback's branch_coro(), as fsspec runs them, so that a callback that overrides it sees each transfer, with the paths still named as strings. - The docstrings of put(), _put() and _put_pairs() state which destinations are typed and when a version raises. Co-Authored-By: Claude Opus 5.5 --- pyathena/filesystem/s3.py | 35 +++++++++------- pyathena/filesystem/s3_async.py | 46 +++++++++++++++------- tests/pyathena/filesystem/test_s3.py | 23 +++++++++++ tests/pyathena/filesystem/test_s3_async.py | 33 ++++++++++++++++ 4 files changed, 108 insertions(+), 29 deletions(-) diff --git a/pyathena/filesystem/s3.py b/pyathena/filesystem/s3.py index 161ff3934..3fdbe13a5 100644 --- a/pyathena/filesystem/s3.py +++ b/pyathena/filesystem/s3.py @@ -3818,10 +3818,10 @@ def put( **kwargs: Additional parameters passed to ``put_file()``. Raises: - ValueError: If two files have the same destination, ``rpath`` - names a version and a destination is named after a local - file below it, or ``batch_size`` is neither positive, -1, nor - None. + ValueError: If two files have the same destination, a + destination names a version, also when ``rpath`` names one + and a local file is named below it, or ``batch_size`` is + neither positive, -1, nor None. """ lpath, rpath = self._stringify_paths(lpath), self._stringify_paths(rpath) limit = self._batch_limit(batch_size) @@ -3855,12 +3855,13 @@ def _put_pairs( The files are uploaded in parallel, so no two files may have the same destination; a local directory uploads nothing. - A destination named after a local file is an ``S3Path``: ``rpath`` - parsed, with the rest of the local name added to its key as it is - (see :meth:`S3Path.with_key_suffix`), so that a file named, e.g., - ``x?versionId=v1`` is written to that key instead of naming a - version. A destination that is ``rpath`` itself, or one of a list of - destinations, is the string that the caller passed. + The destination of a local file named after it below ``rpath`` is an + ``S3Path``: ``rpath`` parsed, with the rest of the local name added to + its key as it is (see :meth:`S3Path.with_key_suffix`), so that a file + named, e.g., ``x?versionId=v1`` is written to that key instead of + naming a version. Any other destination, such as ``rpath`` itself, + one of a list of destinations, or that of a local directory, is a + string without the protocol. Args: lpath: Local source path, glob pattern, or list of them. @@ -3877,8 +3878,7 @@ def _put_pairs( Raises: ValueError: If two files have the same destination, or ``rpath`` - names a version and a destination is named after a local file - below it. + names a version and a local file is named below it. """ if isinstance(lpath, list) and isinstance(rpath, list): pairs: list[tuple[str, str | S3Path]] = [ @@ -3905,15 +3905,20 @@ def _put_pairs( rpaths: list[str | S3Path] = other_paths( lpaths, rpath, exists=exists, flatten=not source_is_str ) - if isinstance(rpath, str) and any(rp != rpath for rp in rpaths): + # The files named after their local names below rpath; a local + # directory, which put_file() skips, keeps its string. + named = [ + rp != rpath and not os.path.isdir(lp) for lp, rp in zip(lpaths, rpaths, strict=True) + ] + if isinstance(rpath, str) and any(named): root = S3Path.parse(rpath) if root.version_id: raise ValueError("Cannot write to the file with the version specified.") # Every destination starts with rpath, which has no trailing # slash, followed by the rest of the local name. rpaths = [ - rp if rp == rpath else root.with_key_suffix(cast(str, rp)[len(rpath) :]) - for rp in rpaths + root.with_key_suffix(cast(str, rp)[len(rpath) :]) if typed else rp + for rp, typed in zip(rpaths, named, strict=True) ] pairs = list(zip(lpaths, rpaths, strict=True)) # put_file() uploads nothing for a local directory. diff --git a/pyathena/filesystem/s3_async.py b/pyathena/filesystem/s3_async.py index fbecb6cb1..c1af7d336 100644 --- a/pyathena/filesystem/s3_async.py +++ b/pyathena/filesystem/s3_async.py @@ -981,9 +981,9 @@ async def _put( The return values of the ``_put_file()`` calls, as in fsspec. Raises: - ValueError: If two files have the same destination, or ``rpath`` - names a version and a destination is named after a local file - below it. + ValueError: If two files have the same destination, or a + destination names a version, also when ``rpath`` names one + and a local 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( @@ -1007,8 +1007,9 @@ async def _transfer_pairs( 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 gets a branch of the callback named after its paths, an - ``S3Path`` as its string. + 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()``. @@ -1023,22 +1024,39 @@ async def _transfer_pairs( batch_size = kwargs.pop("batch_size", self.batch_size) callback.set_size(len(pairs)) - async def run(path1: Any, path2: Any) -> Any: - """Run a transfer with a branch of the callback. + def run(path1: Any, path2: Any) -> Awaitable[Any]: + """Return the transfer of a pair, run through the callback's ``branch_coro()``. Args: path1: The source. path2: The destination. Returns: - The result of the transfer. + The coroutine of the transfer. """ - with callback.branched( - str(path1) if isinstance(path1, S3Path) else path1, - str(path2) if isinstance(path2, S3Path) else path2, - **kwargs, - ) as child: - return await transfer(path1, path2, callback=child, **kwargs) + + 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) + + return cast( + Awaitable[Any], + callback.branch_coro(transfer_pair)( + str(path1) if isinstance(path1, S3Path) else path1, + str(path2) if isinstance(path2, S3Path) else path2, + **kwargs, + ), + ) return cast( list[Any], diff --git a/tests/pyathena/filesystem/test_s3.py b/tests/pyathena/filesystem/test_s3.py index 785664bcd..9d2f124cb 100644 --- a/tests/pyathena/filesystem/test_s3.py +++ b/tests/pyathena/filesystem/test_s3.py @@ -1418,6 +1418,29 @@ def test_put_names_destinations_after_local_files(self, tmp_path, source, kwargs ] == sent assert sorted(callback.destinations) == labels + @pytest.mark.parametrize("with_file", [False, True]) + def test_put_below_versioned_root(self, tmp_path, with_file): + # GH-1404: a file named below a root that names a version raises + # before anything is uploaded; local directories, which upload + # nothing, do not. + fs = S3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + store, requests = serve_s3_keys(fs, set()) + (tmp_path / "src" / "empty").mkdir(parents=True) + if with_file: + (tmp_path / "src" / "x").write_bytes(b"aa") + put = lambda: fs.put( # noqa: E731 + f"{tmp_path}/src/", "s3://bucket/up?versionId=v1/", recursive=True + ) + if with_file: + with pytest.raises(ValueError, match="version"): + put() + else: + put() + assert store == set() + assert [name for name, _ in requests if name != "list_objects_v2"] == [] + def test_put_in_transaction_names_destinations_after_local_files(self, tmp_path): # GH-1404: the file of a destination named after a local file joins # the transaction, as one opened with open() does. diff --git a/tests/pyathena/filesystem/test_s3_async.py b/tests/pyathena/filesystem/test_s3_async.py index b76f9719e..f02931fa2 100644 --- a/tests/pyathena/filesystem/test_s3_async.py +++ b/tests/pyathena/filesystem/test_s3_async.py @@ -851,6 +851,39 @@ def test_put_in_transaction_names_destinations_after_local_files(self, tmp_path) assert store == set() assert store == {"up/x?versionId=v1"} + @pytest.mark.asyncio + async def test_transfers_run_through_branch_coro(self, tmp_path): + # GH-1404: as in fsspec, each download and upload runs through the + # callback's branch_coro(), with the paths named as strings. + fs = AioS3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + serve_s3_keys(fs._sync_fs, {"a/x?versionId=null"}) + (tmp_path / "x?versionId=v1").write_bytes(b"aa") + finished = [] + + class Recording(Callback): + def branch_coro(self, fn): + run = super().branch_coro(fn) + + async def recorded(path1, path2, **kwargs): + result = await run(path1, path2, **kwargs) + finished.append((path1, path2)) + return result + + return recorded + + await await_bounded( + fs._get("s3://bucket/a/*", str(tmp_path / "out") + "/", callback=Recording()) + ) + await await_bounded( + fs._put(str(tmp_path / "x?versionId=v1"), "s3://bucket/up/", callback=Recording()) + ) + assert finished == [ + ("bucket/a/x?versionId=null", str(tmp_path / "out" / "x?versionId=null")), + (str(tmp_path / "x?versionId=v1"), "bucket/up/x?versionId=v1"), + ] + @pytest.mark.asyncio async def test_du_cancellation_sends_no_further_lookup(self): # GH-1402: as fsspec's _du(), the lookups of the found entries are From a5e334fa99c3b67e22026f5f44913a147e3b8461 Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Sat, 21 Nov 2026 22:23:44 +0900 Subject: [PATCH 5/6] Join the batch before a callback's branch_coro() runs a transfer (GH-1404) Independent review follow-up: a callback whose branch_coro() wrapper waited before starting a transfer left the transfer outside the batch, so a cancelled _put() or _get() could still upload or write the file afterwards. Each transfer now adds its task to the batch before the wrapper runs. The Raises of put() and _put() say that only the destination of a local file is checked for a version. Co-Authored-By: Claude Opus 5.5 --- pyathena/filesystem/s3.py | 8 ++--- pyathena/filesystem/s3_async.py | 28 +++++++++--------- tests/pyathena/filesystem/test_s3_async.py | 34 ++++++++++++++++++++++ 3 files changed, 53 insertions(+), 17 deletions(-) diff --git a/pyathena/filesystem/s3.py b/pyathena/filesystem/s3.py index 3fdbe13a5..0889ecc76 100644 --- a/pyathena/filesystem/s3.py +++ b/pyathena/filesystem/s3.py @@ -3818,10 +3818,10 @@ def put( **kwargs: Additional parameters passed to ``put_file()``. Raises: - ValueError: If two files have the same destination, a - destination names a version, also when ``rpath`` names one - and a local file is named below it, or ``batch_size`` is - neither positive, -1, nor None. + ValueError: If two files have the same destination, the + destination of a local file names a version, also when + ``rpath`` names one and the file is named below it, or + ``batch_size`` is neither positive, -1, nor None. """ lpath, rpath = self._stringify_paths(lpath), self._stringify_paths(rpath) limit = self._batch_limit(batch_size) diff --git a/pyathena/filesystem/s3_async.py b/pyathena/filesystem/s3_async.py index c1af7d336..9ec8aa989 100644 --- a/pyathena/filesystem/s3_async.py +++ b/pyathena/filesystem/s3_async.py @@ -981,9 +981,9 @@ async def _put( The return values of the ``_put_file()`` calls, as in fsspec. Raises: - ValueError: If two files have the same destination, or a - destination names a version, also when ``rpath`` names one - and a local file is named below it. + 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( @@ -1024,16 +1024,21 @@ async def _transfer_pairs( 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()``. + async def run(path1: Any, path2: Any) -> Any: + """Run the transfer of a pair through the callback's ``branch_coro()``. + + The task of the transfer joins the batch before the callback's + 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. + The result of the transfer. """ + _S3BatchTasks.track() async def transfer_pair(label1: Any, label2: Any, **transfer_kwargs: Any) -> Any: """Transfer the pair, whose branch the labels name. @@ -1049,13 +1054,10 @@ async def transfer_pair(label1: Any, label2: Any, **transfer_kwargs: Any) -> Any """ return await transfer(path1, path2, **transfer_kwargs) - return cast( - Awaitable[Any], - callback.branch_coro(transfer_pair)( - str(path1) if isinstance(path1, S3Path) else path1, - str(path2) if isinstance(path2, S3Path) else path2, - **kwargs, - ), + return await callback.branch_coro(transfer_pair)( + str(path1) if isinstance(path1, S3Path) else path1, + str(path2) if isinstance(path2, S3Path) else path2, + **kwargs, ) return cast( diff --git a/tests/pyathena/filesystem/test_s3_async.py b/tests/pyathena/filesystem/test_s3_async.py index f02931fa2..3c0b1d96e 100644 --- a/tests/pyathena/filesystem/test_s3_async.py +++ b/tests/pyathena/filesystem/test_s3_async.py @@ -884,6 +884,40 @@ async def recorded(path1, path2, **kwargs): (str(tmp_path / "x?versionId=v1"), "bucket/up/x?versionId=v1"), ] + @pytest.mark.asyncio + async def test_cancelled_put_starts_no_waiting_transfer(self, tmp_path): + # GH-1404: a transfer whose branch_coro() wrapper waits before it + # starts belongs to the batch, so a cancellation of _put() stops it + # and it uploads nothing afterwards. + fs = AioS3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + store, _ = serve_s3_keys(fs._sync_fs, set()) + (tmp_path / "x").write_bytes(b"aa") + waiting, release = asyncio.Event(), asyncio.Event() + + class Waiting(Callback): + def branch_coro(self, fn): + run = super().branch_coro(fn) + + async def wait_then_run(path1, path2, **kwargs): + waiting.set() + await release.wait() + return await run(path1, path2, **kwargs) + + return wait_then_run + + task = asyncio.ensure_future( + fs._put(str(tmp_path / "x"), "s3://bucket/up/", callback=Waiting()) + ) + await await_bounded(waiting.wait()) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await await_bounded(task) + release.set() + await asyncio.sleep(0.1) + assert store == set() + @pytest.mark.asyncio async def test_du_cancellation_sends_no_further_lookup(self): # GH-1402: as fsspec's _du(), the lookups of the found entries are From 7eb9cd6b294410c289e4ca8101663cc6156f42dc Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Sat, 21 Nov 2026 22:44:21 +0900 Subject: [PATCH 6/6] Wrap every transfer before any runs, as fsspec does (GH-1404) Independent review follow-up: _transfer_pairs() asked the callback's branch_coro() for the wrapper of a transfer only when the transfer started, so a callback that waits in its wrappers until every transfer is wrapped hung with batch_size=1. The wrappers are now created with the coroutines, before any transfer is scheduled, and the task still joins the batch before its wrapper runs. The cancellation test checks that the waiting wrapper was cancelled before _put() raised. Co-Authored-By: Claude Opus 5.5 --- pyathena/filesystem/s3_async.py | 36 ++++++++++------ tests/pyathena/filesystem/test_s3_async.py | 48 ++++++++++++++++++++-- 2 files changed, 69 insertions(+), 15 deletions(-) diff --git a/pyathena/filesystem/s3_async.py b/pyathena/filesystem/s3_async.py index 9ec8aa989..328736f8f 100644 --- a/pyathena/filesystem/s3_async.py +++ b/pyathena/filesystem/s3_async.py @@ -1024,21 +1024,22 @@ async def _transfer_pairs( batch_size = kwargs.pop("batch_size", self.batch_size) callback.set_size(len(pairs)) - async def run(path1: Any, path2: Any) -> Any: - """Run the transfer of a pair through the callback's ``branch_coro()``. + def run(path1: Any, path2: Any) -> Awaitable[Any]: + """Return the transfer of a pair, run through the callback's ``branch_coro()``. - The task of the transfer joins the batch before the callback's - wrapper runs, so that a cancellation of the batch also stops a - transfer whose wrapper is still waiting to start it. + 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 result of the transfer. + The coroutine of the transfer. """ - _S3BatchTasks.track() async def transfer_pair(label1: Any, label2: Any, **transfer_kwargs: Any) -> Any: """Transfer the pair, whose branch the labels name. @@ -1054,11 +1055,22 @@ async def transfer_pair(label1: Any, label2: Any, **transfer_kwargs: Any) -> Any """ return await transfer(path1, path2, **transfer_kwargs) - return await callback.branch_coro(transfer_pair)( - str(path1) if isinstance(path1, S3Path) else path1, - str(path2) if isinstance(path2, S3Path) else path2, - **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], diff --git a/tests/pyathena/filesystem/test_s3_async.py b/tests/pyathena/filesystem/test_s3_async.py index 3c0b1d96e..1cdb8d889 100644 --- a/tests/pyathena/filesystem/test_s3_async.py +++ b/tests/pyathena/filesystem/test_s3_async.py @@ -884,6 +884,43 @@ async def recorded(path1, path2, **kwargs): (str(tmp_path / "x?versionId=v1"), "bucket/up/x?versionId=v1"), ] + @pytest.mark.asyncio + async def test_transfers_are_wrapped_before_they_run(self, tmp_path): + # GH-1404: as in fsspec, the callback wraps every transfer before any + # runs, also when batch_size lets one run at a time. + fs = AioS3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + store, _ = serve_s3_keys(fs._sync_fs, set()) + for name in ("x", "y"): + (tmp_path / name).write_bytes(b"aa") + wrapped = asyncio.Event() + + class AllWrapped(Callback): + count = 0 + + def branch_coro(self, fn): + run = super().branch_coro(fn) + self.count += 1 + if self.count == 2: + wrapped.set() + + async def wait_then_run(path1, path2, **kwargs): + await wrapped.wait() + return await run(path1, path2, **kwargs) + + return wait_then_run + + await await_bounded( + fs._put( + [str(tmp_path / "x"), str(tmp_path / "y")], + ["s3://bucket/up/x", "s3://bucket/up/y"], + callback=AllWrapped(), + batch_size=1, + ) + ) + assert store == {"up/x", "up/y"} + @pytest.mark.asyncio async def test_cancelled_put_starts_no_waiting_transfer(self, tmp_path): # GH-1404: a transfer whose branch_coro() wrapper waits before it @@ -895,6 +932,7 @@ async def test_cancelled_put_starts_no_waiting_transfer(self, tmp_path): store, _ = serve_s3_keys(fs._sync_fs, set()) (tmp_path / "x").write_bytes(b"aa") waiting, release = asyncio.Event(), asyncio.Event() + stopped = [] class Waiting(Callback): def branch_coro(self, fn): @@ -902,7 +940,11 @@ def branch_coro(self, fn): async def wait_then_run(path1, path2, **kwargs): waiting.set() - await release.wait() + try: + await release.wait() + except asyncio.CancelledError: + stopped.append(path2) + raise return await run(path1, path2, **kwargs) return wait_then_run @@ -914,8 +956,8 @@ async def wait_then_run(path1, path2, **kwargs): task.cancel() with pytest.raises(asyncio.CancelledError): await await_bounded(task) - release.set() - await asyncio.sleep(0.1) + # The waiting wrapper was cancelled, and waited for, before _put() raised. + assert stopped == ["bucket/up/x"] assert store == set() @pytest.mark.asyncio