diff --git a/docs/filesystem.md b/docs/filesystem.md index 6119e957e..b5954d306 100644 --- a/docs/filesystem.md +++ b/docs/filesystem.md @@ -150,8 +150,11 @@ Local paths that do not exist yet are compared as strings, after `os.path.normcase`, so on a case-insensitive filesystem other than Windows, such as the default one of macOS, give `get` destinations that differ by more than case. A `cp` of an object onto itself, such as with -`MetadataDirective="REPLACE"`, is no conflict. `get` with `outfile` writes the objects -into it one after another, in order. +`MetadataDirective="REPLACE"`, is no conflict. `mv` raises for the same pairs as `cp`. +A source of `cp` or `mv` without an object at its key, such as a key prefix given in a +list, writes no destination and does not conflict; the sources without a version whose +destinations conflict are looked up with HeadObject before anything is copied. `get` +with `outfile` writes the objects into it one after another, in order. `rm` deletes up to 1,000 objects per DeleteObjects request, `batch_size` requests at a time. Its `max_workers` argument is a deprecated alias of `batch_size`. diff --git a/pyathena/filesystem/s3.py b/pyathena/filesystem/s3.py index 858590e46..501dafe00 100644 --- a/pyathena/filesystem/s3.py +++ b/pyathena/filesystem/s3.py @@ -2709,6 +2709,8 @@ def mv(self, path1, path2, recursive=False, maxdepth=None, batch_size=None, **kw GetBucketVersioning once per bucket during the move's planning and requires ``s3:GetBucketVersioning``. The result is not cached across moves. Directory buckets do not support versioning and need no lookup. + A source without a version whose destination conflicts with another + pair is looked up with HeadObject during the planning too. The files are copied in parallel as ``copy()`` copies them, and are deleted once every copy has succeeded; nothing is deleted after a @@ -2731,9 +2733,12 @@ def mv(self, path1, path2, recursive=False, maxdepth=None, batch_size=None, **kw Raises: ValueError: If two sources have the same destination, or a destination is another source, including one left in place, - which is checked before anything is copied. A directory with - no object at its key, which is not copied, does not conflict. - Also if ``batch_size`` is neither positive, -1, nor None. + which is checked before anything is copied. A source without + an object at its key, such as a directory, writes no + destination and does not conflict. Also if ``batch_size`` is + neither positive, -1, nor None. + FileNotFoundError: If a source does not exist, once the running + copies have ended; nothing is deleted. OSError: If bucket versioning cannot be read. """ path1, path2 = self._stringify_paths(path1), self._stringify_paths(path2) @@ -2810,7 +2815,6 @@ def _conflict_lookups( pairing: S3PathPairing, pairs: list[tuple[str | S3Path, str | S3Path]], source_params: Mapping[str, Any] | None = None, - copy: bool = False, ) -> tuple[set[str | S3Path], set[str]]: """Look up what the conflict checks of a move or a copy need. @@ -2822,7 +2826,6 @@ def _conflict_lookups( source_params: The parameters of the requests that read the sources (see :meth:`S3Core.copy_source_params`), sent with the lookups of the sources. - copy: Whether the pairs are those of a copy. Returns: The conflict candidates with no object at their key, and the @@ -2846,7 +2849,7 @@ def _conflict_lookups( missing = { source for source in pairing.conflict_candidates( - pairs, versioning_enabled_buckets=versioned_buckets, copy=copy + pairs, versioning_enabled_buckets=versioned_buckets ) if self._head_object(S3Path.of(source), lookup_kwargs=lookup_kwargs) is None } @@ -2924,9 +2927,7 @@ def _checked_copy_pairs( pairing = S3PathPairing(path1, path2, recursive=recursive, maxdepth=maxdepth) pairs = self._copy_pairs(pairing) if pairs: - missing, versioned_buckets = self._conflict_lookups( - pairing, pairs, source_params, copy=True - ) + missing, versioned_buckets = self._conflict_lookups(pairing, pairs, source_params) pairing.check_copy_pairs( pairs, missing=missing, versioning_enabled_buckets=versioned_buckets ) @@ -2975,9 +2976,9 @@ def copy( Raises: ValueError: If two sources have the same destination, or a - destination is another source, except for a directory with no - object at its key, which is not copied. Also if - ``batch_size`` is neither positive, -1, nor None. + destination is another source, except for a source without an + object at its key, such as a directory, which is not copied. + Also if ``batch_size`` is neither positive, -1, nor None. OSError: If bucket versioning cannot be read for the checks. """ path1, path2 = self._stringify_paths(path1), self._stringify_paths(path2) diff --git a/pyathena/filesystem/s3_async.py b/pyathena/filesystem/s3_async.py index 63604e36b..555c01445 100644 --- a/pyathena/filesystem/s3_async.py +++ b/pyathena/filesystem/s3_async.py @@ -763,8 +763,11 @@ async def _mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs) -> N Raises: ValueError: If two sources have the same destination, or a destination is another source, including one left in place, - which is checked before anything is copied. A directory with - no object at its key, which is not copied, does not conflict. + which is checked before anything is copied. A source without + an object at its key, such as a directory, writes no + destination and does not conflict. + FileNotFoundError: If a source does not exist, once the other + copies have ended; nothing is deleted. OSError: If bucket versioning cannot be read. """ path1, path2 = self._sync_fs._stringify_paths(path1), self._sync_fs._stringify_paths(path2) diff --git a/pyathena/filesystem/s3_path_pairing.py b/pyathena/filesystem/s3_path_pairing.py index 8083ff0bf..52a5bf805 100644 --- a/pyathena/filesystem/s3_path_pairing.py +++ b/pyathena/filesystem/s3_path_pairing.py @@ -200,42 +200,39 @@ def conflict_candidates( pairs: Sequence[tuple[str | S3Path, str | S3Path]], *, versioning_enabled_buckets: Collection[str] = (), - copy: bool = False, ) -> list[str | S3Path]: - """Return the sources of a move whose conflicts depend on an object at their key. + """Return the sources of a move or a copy whose conflicts depend on an object at their key. - A source with another source below it may be a directory. If no object - exists at its key, it is not copied, so it writes no destination and - is left out of the conflict checks of :meth:`move_pairs`. A path with - a version always names an object. For a copy, any source may be a - directory, such as a prefix given in a list, which the copy skips - (see :meth:`check_copy_pairs`). + A source without a version may be a directory, such as a prefix given + in a list or one with other sources below it. If no object exists at + its key, it is not copied, so it writes no destination and is left + out of the conflict checks of :meth:`move_pairs` and + :meth:`check_copy_pairs`. A path with a version always names an + object. Args: - pairs: The sources and destinations of the move, as + pairs: The sources and destinations of the move or the copy, as :meth:`copy_pairs` or :meth:`s3_copy_pairs` of this pairing returns them. A string is parsed; an ``S3Path`` is used as it is. versioning_enabled_buckets: Buckets whose versioning is enabled. Their ``null`` versions are distinct from their unversioned - keys. Use the same collection for :meth:`move_pairs`. - copy: Whether the pairs are those of a copy, whose candidates - include every source without a version whose destination - conflicts. + keys. Use the same collection for :meth:`move_pairs` or + :meth:`check_copy_pairs`. Returns: - The sources that have another source below them and a - destination that conflicts, one per pair in the order of the - pairs, as their :attr:`~pyathena.filesystem.s3_path.S3Path.target`: - in ``bucket/key`` form for a source string, and as an ``S3Path`` - for an ``S3Path`` source. Empty if nothing needs to be looked up. + The sources without a version whose destination conflicts, one + per pair in the order of the pairs, as their + :attr:`~pyathena.filesystem.s3_path.S3Path.target`: in + ``bucket/key`` form for a source string, and as an ``S3Path`` for + an ``S3Path`` source. Empty if nothing needs to be looked up. Raises: TypeError: If ``versioning_enabled_buckets`` is a string. """ return [ pair.source if isinstance(pair.path1, S3Path) else str(pair.source) - for pair in self._moves(pairs, versioning_enabled_buckets, copy)[2] + for pair in self._moves(pairs, versioning_enabled_buckets)[2] ] def move_pairs( @@ -266,8 +263,8 @@ def move_pairs( Raises: ValueError: If two sources have the same destination, or a destination is another source, including one left in place, - except for a directory with no object at its key, which is not - copied. Also if ``missing`` is needed and None. + except for a source without a version in ``missing``, which + writes no destination. Also if ``missing`` is needed and None. TypeError: If ``missing`` is a string instead of a collection. Also if ``versioning_enabled_buckets`` is a string. """ @@ -301,9 +298,9 @@ def check_copy_pairs( Raises: ValueError: If two sources have the same destination, or a - destination is another source, except for a directory with no - object at its key, which is not copied. Also if ``missing`` is - needed and None. + destination is another source, except for a source without a + version in ``missing``, which writes no destination. Also if + ``missing`` is needed and None. TypeError: If ``missing`` is a string instead of a collection. Also if ``versioning_enabled_buckets`` is a string. """ @@ -335,15 +332,14 @@ def _check( """ if isinstance(missing, str): raise TypeError("missing is a collection of paths, not a path.") - named, sources, candidates = self._moves( - pairs, versioning_enabled_buckets, operation == "copy" - ) + named, sources, candidates = self._moves(pairs, versioning_enabled_buckets) if missing is None and candidates: raise ValueError("missing is needed to check the pairs.") - # A directory without an object at its key writes no destination. - skipped = {pair.source for pair in candidates}.intersection( + # A source without an object at its key, such as a directory, writes + # no destination. + skipped = { self._target(S3Path.of(path), versioning_enabled_buckets) for path in missing or () - ) + } # A path with a version always names an object, so it writes its # destination even when the key has no current object. writers = Counter( @@ -416,14 +412,12 @@ def _target(path: S3Path, versioning_enabled_buckets: Collection[str]) -> S3Path def _moves( pairs: Sequence[tuple[str | S3Path, str | S3Path]], versioning_enabled_buckets: Collection[str] = (), - copy: bool = False, ) -> tuple[list[_NamedPair], set[S3Path], list[_NamedPair]]: - """Compare the paths of a move by what they name. + """Compare the paths of a move or a copy by what they name. Args: - pairs: The sources and destinations of the move. + pairs: The sources and destinations of the move or the copy. versioning_enabled_buckets: Buckets whose versioning is enabled. - copy: Whether every conflicting source is a candidate. Returns: Each pair with whether its source has a version and the targets @@ -452,21 +446,12 @@ def _moves( ) # The sources left in place count too; a copy onto one overwrites it. sources = {pair.source for pair in named} - # A source with another source below it may be a directory, named - # as it is listed: the parents of a name are cut at its last slash. - directories: set[str] = set() - for source in sources: - parent = source.name.rpartition("/")[0] - while parent and parent not in directories: - directories.add(parent) - parent = parent.rpartition("/")[0] counts = Counter(pair.destination for pair in named if pair.source != pair.destination) candidates = [ pair for pair in named if pair.source != pair.destination and (counts[pair.destination] > 1 or pair.destination in sources) - and (copy or pair.source.name in directories) and not pair.versioned ] return named, sources, candidates diff --git a/tests/pyathena/filesystem/test_s3.py b/tests/pyathena/filesystem/test_s3.py index 1f431027d..c9a6d3ecd 100644 --- a/tests/pyathena/filesystem/test_s3.py +++ b/tests/pyathena/filesystem/test_s3.py @@ -2329,6 +2329,8 @@ def test_cp_file_directory(self): ], ) def test_mv_conflicting_destinations(self, path1, path2): + # The sources whose destinations conflict are looked up, and objects + # at their keys raise before anything is copied. fs = self._make_fs() fs.info = mock.MagicMock() fs._call.return_value = {} @@ -2336,13 +2338,14 @@ def test_mv_conflicting_destinations(self, path1, path2): with pytest.raises(ValueError, match="Cannot move"): fs.mv(path1, path2, recursive=True) fs.info.assert_not_called() + expected = {fs._client.head_object} if any(S3Path.parse(p).version_id == "null" for p in path1): - fs._call.assert_called_once_with(fs._client.get_bucket_versioning, Bucket="bucket") - else: - fs._call.assert_not_called() + expected.add(fs._client.get_bucket_versioning) + assert {c.args[0] for c in fs._call.call_args_list} == expected def test_mv_conflicting_destinations_of_listed_sources(self): - # A list of sources is mapped without looking up the destination. + # A list of sources is mapped without looking up the destination; + # only the sources are looked up. fs = self._make_fs() fs._expand_paths = mock.MagicMock( return_value=[(p, S3Path.parse(p)) for p in ("bucket/x/a", "bucket/y/a")] @@ -2352,7 +2355,21 @@ def test_mv_conflicting_destinations_of_listed_sources(self): with pytest.raises(ValueError, match="same destination"): fs.mv(["s3://bucket/x/a", "s3://bucket/y/a"], "s3://bucket/out", recursive=True) fs.isdir.assert_not_called() - fs._call.assert_not_called() + assert sorted((c.args[0], c.kwargs["Key"]) for c in fs._call.call_args_list) == [ + (fs._client.head_object, "x/a"), + (fs._client.head_object, "y/a"), + ] + + def test_mv_skipped_directory_does_not_conflict(self): + # GH-1397: a listed source without an object at its key, a prefix + # that the move skips, writes no destination, so its destination + # being another source is no conflict, as with copy(). It used to + # be looked up only with another source below it. + fs = self._make_fs() + store = self._serve_keys(fs, {"dir/a", "x"}) + + fs.mv(["s3://bucket/dir", "s3://bucket/x"], ["s3://bucket/x", "s3://bucket/y"]) + assert store == {"dir/a", "y"} def test_mv_keeps_given_paths(self): # The destination keeps its trailing slash, as with copy(), and the diff --git a/tests/pyathena/filesystem/test_s3_path_pairing.py b/tests/pyathena/filesystem/test_s3_path_pairing.py index 933758c7e..6a8a01c24 100644 --- a/tests/pyathena/filesystem/test_s3_path_pairing.py +++ b/tests/pyathena/filesystem/test_s3_path_pairing.py @@ -233,7 +233,7 @@ def test_move_pairs_distinguishes_null_version_source(self): pairing = _pairing(pairs) with pytest.raises(ValueError, match="another path"): - pairing.move_pairs(pairs) + pairing.move_pairs(pairs, missing=set()) assert pairing.move_pairs(pairs, versioning_enabled_buckets={"bucket"}) == pairs @pytest.mark.parametrize("method", ["conflict_candidates", "move_pairs"]) @@ -257,24 +257,25 @@ def test_move_bucket_names_are_a_collection(self, method): ) def test_move_pairs_conflicts(self, pairs, match): with pytest.raises(ValueError, match=match): - _pairing(pairs).move_pairs(pairs) + _pairing(pairs).move_pairs(pairs, missing=set()) def test_move_pairs_directory_without_object(self): - # A source with another source below it may be a directory; one - # without an object at its key is not copied, so its destination - # does not conflict. + # A source without a version may be a directory, with or without + # another source below it; one without an object at its key is not + # copied, so its destination does not conflict. pairs = [ ("s3://bucket/d", "s3://bucket/e"), ("s3://bucket/d/x", "s3://bucket/e"), ("s3://bucket/e/y", "s3://bucket/out"), ] - assert _pairing(pairs).conflict_candidates(pairs) == ["bucket/d"] + assert _pairing(pairs).conflict_candidates(pairs) == ["bucket/d", "bucket/d/x"] with pytest.raises(ValueError, match="missing"): _pairing(pairs).move_pairs(pairs) with pytest.raises(ValueError, match="same destination"): _pairing(pairs).move_pairs(pairs, missing=set()) assert _pairing(pairs).move_pairs(pairs, missing={"bucket/d"}) == pairs + assert _pairing(pairs).move_pairs(pairs, missing={"bucket/d/x"}) == pairs # The missing sources can be given in any form that names them. assert _pairing(pairs).move_pairs(pairs, missing={"s3://bucket/d"}) == pairs @@ -290,14 +291,12 @@ def test_move_pairs_keeps_listed_keys_apart_from_versions(self): def test_move_pairs_path_conflict_candidates(self): # GH-1403: the candidates of S3Path sources are S3Path objects, and - # missing ones may be given as such; their directories are named as - # they are listed. + # missing ones may be given as such; a key that ends in what looks + # like a version ID query is no version. directory = S3Path("bucket", "d?versionId=v1") - pairs = [ - (directory, S3Path("bucket", "e")), - (S3Path("bucket", "d?versionId=v1/x"), S3Path("bucket", "e")), - ] - assert _pairing(pairs).conflict_candidates(pairs) == [directory] + listed = S3Path("bucket", "d?versionId=v1/x") + pairs = [(directory, S3Path("bucket", "e")), (listed, S3Path("bucket", "e"))] + assert _pairing(pairs).conflict_candidates(pairs) == [directory, listed] assert _pairing(pairs).move_pairs(pairs, missing={directory}) == pairs def test_move_pairs_missing_is_a_collection(self): @@ -315,16 +314,17 @@ def test_conflict_candidates_one_per_pair(self): assert _pairing(pairs).conflict_candidates(pairs) == ["bucket/d", "bucket/d"] def test_move_pairs_version_names_an_object(self): - # A version is never taken for a directory. + # A version is never taken for a directory, even with another source + # below its key, so it is not looked up. pairs = [ ("s3://bucket/d?versionId=null", "s3://bucket/out"), ("s3://bucket/d/x", "s3://bucket/x"), ("s3://bucket/a", "s3://bucket/out"), ] - assert _pairing(pairs).conflict_candidates(pairs) == [] + assert _pairing(pairs).conflict_candidates(pairs) == ["bucket/a"] with pytest.raises(ValueError, match="same destination"): - _pairing(pairs).move_pairs(pairs) + _pairing(pairs).move_pairs(pairs, missing=set()) def test_move_pairs_version_of_missing_directory_key(self): # The "null" version of a key without a current object still names an @@ -336,7 +336,7 @@ def test_move_pairs_version_of_missing_directory_key(self): ("src/d/x", "dst/x"), ] - assert _pairing(pairs).conflict_candidates(pairs) == ["src/d"] + assert _pairing(pairs).conflict_candidates(pairs) == ["src/d", "src/a"] with pytest.raises(ValueError, match="same destination"): _pairing(pairs).move_pairs(pairs, missing={"src/d"}) diff --git a/tests/pyathena/util.py b/tests/pyathena/util.py index 18e9de745..143912293 100644 --- a/tests/pyathena/util.py +++ b/tests/pyathena/util.py @@ -1526,12 +1526,12 @@ def stub_move_with_source_params(stubber): """Queue the requests of a move of bucket/a and bucket/a/x onto bucket/c. The move is made with MOVE_SOURCE_PARAMS, and no object exists at - bucket/a. Because bucket/a has bucket/a/x below it and the same - destination, the move depends on whether bucket/a is an object; the copy - of bucket/a looks it up again, and skips it as a directory. The lookups - of the sources receive the parameters that authorize the access to the - source, and the deletion of the copied source those that DeleteObjects - accepts. + bucket/a. Because both sources have the same destination, the move + depends on whether they are objects, so both are looked up. The copy of + bucket/a looks it up again and skips it as a directory, and the copy of + bucket/a/x uses its cached lookup. The lookups of the sources receive + the parameters that authorize the access to the source, and the deletion + of the copied source those that DeleteObjects accepts. Args: stubber: The Stubber of the S3 client. @@ -1542,13 +1542,17 @@ def stub_move_with_source_params(stubber): "RequestPayer": "requester", "ExpectedBucketOwner": "111111111111", } - for _ in range(2): - stubber.add_client_error( - "head_object", - service_error_code="404", - http_status_code=404, - expected_params={"Bucket": "bucket", "Key": "a", **lookup}, - ) + # A lookup of bucket/a, which finds no object. + missing_a = { + "service_error_code": "404", + "http_status_code": 404, + "expected_params": {"Bucket": "bucket", "Key": "a", **lookup}, + } + stubber.add_client_error("head_object", **missing_a) + stubber.add_response( + "head_object", {"ContentLength": 1}, {"Bucket": "bucket", "Key": "a/x", **lookup} + ) + stubber.add_client_error("head_object", **missing_a) stubber.add_response( "list_objects_v2", {"KeyCount": 1, "Contents": [{"Key": "a/x"}]}, @@ -1561,9 +1565,6 @@ def stub_move_with_source_params(stubber): "ExpectedBucketOwner": "111111111111", }, ) - stubber.add_response( - "head_object", {"ContentLength": 1}, {"Bucket": "bucket", "Key": "a/x", **lookup} - ) stubber.add_response( "copy_object", {},