diff --git a/docs/filesystem.md b/docs/filesystem.md index 8a28f94ba..d847a5f73 100644 --- a/docs/filesystem.md +++ b/docs/filesystem.md @@ -712,6 +712,14 @@ version, named as `ls(versions=True)` names it, without listing the keys under t path. They look the version up as `info()` does: if HeadObject reports it missing, `ls()` raises `FileNotFoundError` and `find()` returns nothing, and other errors, such as the `400 Bad Request` of a version ID that the bucket rejects, are raised. +`info()` of a version other than `null` that the path or `version_id` names gives the +entry the name `bucket/key?versionId=`, as `ls(versions=True)` names a version, and +`du("s3://YOUR_S3_BUCKET/key?versionId=", total=False)` names its size the same +way; an entry looked up without a version, or with the `null` version, is named after +its key. The `version_id` of an entry looked up with HeadObject is the version that +HeadObject reports, or else the requested one, also without `version_aware`, which +alone pins reads to it. An entry listed with +ListObjectsV2, such as one that `info()` answers from a cached listing, has none. ```python fs = s3_filesystem( diff --git a/pyathena/filesystem/s3.py b/pyathena/filesystem/s3.py index b478030cf..f981bf1b1 100644 --- a/pyathena/filesystem/s3.py +++ b/pyathena/filesystem/s3.py @@ -937,6 +937,11 @@ def _head_object( evicts its entries and, unless a version was requested, the cached listing of its parent that still lists it. + The entry records the ``VersionId`` that HeadObject returns, or else + the requested version, and is named after the request (see + :meth:`S3Object.from_metadata`). Only a ``version_aware`` filesystem + pins its reads to the recorded version. + Args: path: The path of the object, optionally with a version ID. refresh: If True, bypass the cache and call HeadObject. @@ -946,7 +951,6 @@ def _head_object( Returns: The object, or None if it does not exist. """ - version_id = path.version_id lookup_kwargs = lookup_kwargs or {} file = None if refresh else self._listing_cache.get_lookup(path, lookup_kwargs) if file is None: @@ -962,13 +966,9 @@ def _head_object( # An error that S3 returned has been evicted above. self._listing_cache.evict_missing(path) return None - if self.version_aware and not version_id: - # Pin the version of the object so that subsequent reads see - # the version observed here even if the object is overwritten. - version_id = metadata.version_id - file = S3Object.from_metadata(metadata, version_id=version_id) - # Cached under the path as looked up, so that the lookup of the - # key stays cached under the key when the version is pinned. + file = S3Object.from_metadata(metadata) + # Cached under the path as looked up, apart from the lookups of + # the key and of its other versions. self._listing_cache.put_lookup(path, lookup_kwargs, file) return file @@ -1168,7 +1168,7 @@ def _ls_version(self, s3_path: S3Path, refresh: bool = False) -> list[S3Object]: A version names one object, which has nothing below it, so no directory is listed. The entry is named as ``ls(versions=True)`` - names a version. + names a version (see :meth:`_head_object`). Args: s3_path: The key path with a version ID. @@ -1178,13 +1178,7 @@ def _ls_version(self, s3_path: S3Path, refresh: bool = False) -> list[S3Object]: The entry of the version, or an empty list if it does not exist. """ file = self._head_object(s3_path, refresh=refresh) - if not file: - return [] - if s3_path.version_id != "null": - # The cached entry of the lookup is named without the version. - file = file.copy() - file.name = str(s3_path) - return [file] + return [file] if file else [] def _ls_object_versions(self, path: str) -> list[S3Object]: """List a prefix including all versions of the objects. @@ -1895,13 +1889,14 @@ def du(self, path, total=True, maxdepth=None, withdirs=False, **kwargs): Unlike fsspec, which looks up each path that ``find()`` returns, the sizes are those of the entries that ``find()`` lists, as a cached - listing holds them, with no further request. Each entry is named by - its bucket and key without a version (see :meth:`S3Object.to_path`): - an object by the name that ``info()`` gives it, also the version that - the path names, and a directory such as ``bucket/d/`` of the keys - ``d//x`` by its key, or by its bucket if its key is empty. The sizes - of the entries of one name, such as an object and the key prefix of - the same name, are added. + listing holds them, with no further request. An object is named as + ``info()`` names it: by its bucket and key, or, for a version other + than ``"null"`` that the path names, as ``bucket/key?versionId=``. + A directory is named as the listing names it, by its bucket and key + (see :meth:`S3Object.to_path`), such as ``bucket/d/`` of the keys + ``d//x``, or by its bucket if its key is empty. The sizes of the + entries of one name, such as an object and the key prefix of the same + name, are added. Args: path: The path to search under. @@ -1921,7 +1916,10 @@ def du(self, path, total=True, maxdepth=None, withdirs=False, **kwargs): info = self._info_entry(path) sizes[info["name"]] = info["size"] for entry in self._find(path, maxdepth=maxdepth, withdirs=withdirs, **kwargs): - name = entry.to_path().name + if entry["type"] == S3ObjectType.S3_OBJECT_TYPE_FILE: + name = entry["name"] + else: + name = entry.to_path().name sizes[name] = sizes.get(name, 0) + entry["size"] return sum(sizes.values()) if total else sizes @@ -5220,7 +5218,9 @@ def created(self, path: str | os.PathLike[str]) -> datetime | None: Returns: The last-modified time of the object, or None for a bucket or a - directory, which have none. + directory, which have none. The creation date of a bucket is in + the :class:`~pyathena.filesystem.s3_object.S3Bucket` of + ``core.list_buckets()``. """ return self.modified(path) diff --git a/pyathena/filesystem/s3_object.py b/pyathena/filesystem/s3_object.py index 015a0a455..fbdc3e310 100644 --- a/pyathena/filesystem/s3_object.py +++ b/pyathena/filesystem/s3_object.py @@ -269,7 +269,7 @@ def to_path(self) -> S3Path: directory ``bucket/`` of the key ``/x``, names the bucket, as in :class:`S3Path`. The entry of the root gives ``S3Path("")``. A version ID that the entry records, such as that of a version entry or of a - ``version_aware`` lookup, is not part of the path. + HeadObject lookup, is not part of the path. Returns: The path of the bucket, the directory or the object. @@ -392,23 +392,24 @@ def from_version(cls, version: S3ObjectVersion) -> S3Object: return cls._from_listing(version, **fields) @classmethod - def from_metadata(cls, metadata: S3Metadata, version_id: str | None = None) -> S3Object: + def from_metadata(cls, metadata: S3Metadata) -> S3Object: """Build the file entry of an object looked up with HeadObject. The S3 API fields that the response does not have are left out, except ``Metadata``, which botocore always returns. ``version_id`` is - always set, to None for an entry without a version, and ``type``, + always set: to the ``VersionId`` that HeadObject returned, or else to + the version of the looked up path, or None. ``type``, ``bucket``, ``key``, ``name``, ``size``, ``content_length`` (0 without ``ContentLength``) and ``storage_class`` are set as the constructor sets them. Args: metadata: The metadata of the object, with the looked up path. - version_id: The version ID of the entry, which may be pinned or - omitted apart from the looked up path. Returns: - The file entry, named ``bucket/key``. + The file entry, named after the looked up path, as + :meth:`from_version` names a version: ``bucket/key?versionId=`` + for a version other than ``null``, and ``bucket/key`` otherwise. Raises: ValueError: If the metadata has no object path. @@ -436,13 +437,19 @@ def from_metadata(cls, metadata: S3Metadata, version_id: str | None = None) -> S "Metadata": metadata.user_metadata, "LastModified": metadata.last_modified, } - return cls( + path = metadata.path + entry = cls( init={k: v for k, v in fields.items() if v is not None}, type=S3ObjectType.S3_OBJECT_TYPE_FILE, - bucket=metadata.path.bucket, - key=metadata.path.key, - version_id=version_id, + bucket=path.bucket, + key=path.key, + version_id=metadata.version_id or path.version_id, ) + if path.version_id and path.version_id != "null": + # The name comes from the request, the metadata from the + # response. + entry["name"] = str(path) + return entry @classmethod def from_bucket(cls, bucket: S3Bucket) -> S3Object: diff --git a/tests/pyathena/filesystem/test_s3.py b/tests/pyathena/filesystem/test_s3.py index 1da5221bd..82efaa7a0 100644 --- a/tests/pyathena/filesystem/test_s3.py +++ b/tests/pyathena/filesystem/test_s3.py @@ -412,22 +412,72 @@ def test_missing_object_keeps_cached_parent_listing_without_it(self): @pytest.mark.parametrize("version_aware", [False, True]) def test_info_version_aware_heads_listed_file(self, version_aware): - # Only in version-aware mode is the version that HeadObject reports - # pinned, and is a listed file looked up, since the listed entry has - # no version to pin. + # Only in version-aware mode is a listed file looked up, since the + # listed entry has no version to pin. GH-1529: the entry of a lookup + # records the version that HeadObject reports in either mode. fs = self._make_fs() fs.version_aware = version_aware fs._listing_cache.put_listing("bucket/d", "/", [self._file_object("d/direct")]) fs.core.call.return_value = {"ContentLength": 4, "VersionId": "v1"} - expected = "v1" if version_aware else None - assert fs.info("s3://bucket/d/direct").version_id == expected - assert fs.info("s3://bucket/other").version_id == expected + assert fs.info("s3://bucket/d/direct").version_id == ("v1" if version_aware else None) + assert fs.info("s3://bucket/other").version_id == "v1" looked_up = ["d/direct", "other"] if version_aware else ["other"] assert fs.core.call.call_args_list == [ mock.call(fs.core.client.head_object, Bucket="bucket", Key=key) for key in looked_up ] + @pytest.mark.parametrize( + ("path", "version_id", "reported", "name", "recorded"), + [ + ("s3://bucket/d/key?versionId=v1", None, "v1", "bucket/d/key?versionId=v1", "v1"), + ("s3://bucket/d/key", "v1", "v1", "bucket/d/key?versionId=v1", "v1"), + ("s3://bucket/d/key?versionId=null", None, "null", "bucket/d/key", "null"), + # Without a reported version, the requested one is recorded. + ("s3://bucket/d/key?versionId=v1", None, None, "bucket/d/key?versionId=v1", "v1"), + # The name comes from the request, the version from the response. + ("s3://bucket/d/key?versionId=v1", None, "v2", "bucket/d/key?versionId=v1", "v2"), + ], + ids=["path-version", "version_id", "null-version", "unreported", "reported-first"], + ) + def test_info_names_an_explicit_version(self, path, version_id, reported, name, recorded): + # GH-1529: info() names an explicitly requested version other than + # "null" as ls() and find() do, from the request; the entry of any + # other lookup keeps the name of its key, though HeadObject reports a + # version, and a lookup of the key afterwards is not named after it. + # The reported version is recorded, or else the requested one. + fs = self._make_fs() + fs.core.call.return_value = {"ContentLength": 4, "VersionId": reported} + + actual = fs.info(path, version_id=version_id) + assert (actual["name"], actual["version_id"]) == (name, recorded) + if name != "bucket/d/key": + assert fs.info("s3://bucket/d/key")["name"] == "bucket/d/key" + + def test_read_without_version_aware_is_not_pinned(self): + # GH-1529: the entry records the version that HeadObject reports also + # without version_aware, and the reads of a filesystem that is not + # version-aware are still not pinned to it. + fs = S3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + sent = [] + + def answer(name, request): + # As the client receives the request. + sent.append((name, request)) + if name == "head_object": + return {"ContentLength": 2, "ETag": '"e"', "VersionId": "v1"} + return {"Body": io.BytesIO(b"aa"), "ContentLength": 2, "ETag": '"e"'} + + answer_s3_requests(fs, answer) + assert fs.info("s3://bucket/key")["version_id"] == "v1" + with fs.open("s3://bucket/key", "rb") as f: + assert f.read() == b"aa" + gets = [request for name, request in sent if name == "get_object"] + assert gets + assert all("VersionId" not in request for request in gets) + def test_exists_version_ignores_cached_parent_listing(self): # The listing describes the current versions, so a version missing # from it is looked up with HeadObject. @@ -2393,9 +2443,9 @@ def test_walk_ignores_other_keyword_arguments(self, path, kwargs, expected): ), pytest.param( # A path with a version still names the version, and its size - # is named by its key, as info() names it. + # is named as info() names it, with the version (GH-1529). lambda fs: fs.du("s3://bucket/a/x?versionId=v1", total=False), - {"bucket/a/x": 2}, + {"bucket/a/x?versionId=v1": 2}, [("head_object", "a/x", "v1")], id="du-version", ), @@ -2599,28 +2649,31 @@ 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( - ("path", "version_id", "sent"), + ("path", "version_id", "sent", "name"), [ ( S3Path("bucket", "a/x?versionId=null"), None, ("head_object", "a/x?versionId=null", None), + "bucket/a/x?versionId=null", ), + # GH-1529: an explicit version names the entry, after the key. ( S3Path("bucket", "a/x?versionId=null"), "v2", ("head_object", "a/x?versionId=null", "v2"), + "bucket/a/x?versionId=null?versionId=v2", ), ], ) - def test_info_looks_up_path_as_it_is(self, path, version_id, sent): + def test_info_looks_up_path_as_it_is(self, path, version_id, sent, name): # GH-1403: info() looks an S3Path up by its bucket, key and version, # as given or from version_id, never by parsing its name. fs = S3FileSystem( key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True ) _, requests = serve_s3_keys(fs, self.NULL_KEYS) - assert fs.info(path, version_id=version_id)["name"] == "bucket/a/x?versionId=null" + assert fs.info(path, version_id=version_id)["name"] == name assert s3_request_targets(requests) == [sent] @pytest.mark.parametrize( @@ -10853,7 +10906,11 @@ def test_info_file(self, fs): assert info.etag is not None assert info.type == S3ObjectType.S3_OBJECT_TYPE_FILE assert info.storage_class == S3StorageClass.S3_STORAGE_CLASS_STANDARD - assert info.version_id == s3_path.version_id + # GH-1529: the version that HeadObject reports, if the bucket is + # versioned. + assert info.version_id == fs.core.client.head_object( + Bucket=s3_path.bucket, Key=s3_path.key + ).get("VersionId") def test_find(self, fs): dir_ = f"s3://{ENV.s3_staging_bucket}/{ENV.s3_staging_key}{ENV.schema}/filesystem/test_find"