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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/filesystem.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<id>`, as `ls(versions=True)` names a version, and
`du("s3://YOUR_S3_BUCKET/key?versionId=<id>", 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

R1-2 (repaired). The guide said that a listed entry has no version, but entries of ls(versions=True) have one. It now says ListObjectsV2. It also named the entry "the same name" as the path, although ?version_id= and similar spellings are normalized to ?versionId=; it now gives the form bucket/key?versionId=<id>.

R1-3 (repaired). The to_path() docstring and a comment in _head_object still equated a recorded version with a pinned one.

R1-4 (repaired). The current row of test_info_names_an_explicit_version repeated test_info_version_aware_heads_listed_file[False]'s evidence and is removed.

R1-5 (kept as decided; this line). Without version_aware, info()["version_id"] is the reported version after a HeadObject and None when info() answers from a cached ListObjectsV2 listing. #1529 item 2 decided to record HeadObject's version and to keep the key sets of listed entries, so the split by source is intended. The guide now states it.

R1-6 (no change). The live test_info_file asserts version_id is None for an unversioned path. That holds for the test environment's bucket, which is not versioned, and is the correct answer there.

Self-review round two (claims, callers, operator, evidence), full pass over the repaired head:

  • Claims: "no other code under pyathena/ reads an entry's version_id" (grep in s3.py/s3_async.py: two readers, both gated); "to_api_repr() does not emit it" (_API_FIELD_TO_S3_OBJECT_FIELD has no VersionId); "a later lookup of the key keeps its name" (put_lookup keys an explicit version apart, and a test covers it).
  • Callers and operator: the requests are unchanged (matrix: no row adds or drops a request); only the entries' names for explicit versions and the recorded version differ.
  • Evidence: offline only; the AWS jobs run when Ready.

Result: CLEAN for round two.


```python
fs = s3_filesystem(
Expand Down
50 changes: 25 additions & 25 deletions pyathena/filesystem/s3.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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:
Expand All @@ -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

Expand Down Expand Up @@ -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.
Expand All @@ -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.
Expand Down Expand Up @@ -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=<id>``.
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.
Expand All @@ -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

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

Expand Down
27 changes: 17 additions & 10 deletions pyathena/filesystem/s3_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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=<id>``
for a version other than ``null``, and ``bucket/key`` otherwise.

Raises:
ValueError: If the metadata has no object path.
Expand Down Expand Up @@ -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,

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent review (relayed), round one. Reviewer: Codex CLI 0.172.0, gpt-6.2-astra, codex exec -s read-only, session 01a22ca2-d272-78b1-860d-35e10372ca05. Base 059a3c67, head 961ea1c1, detached snapshot. The prompt held the diff, the decision and the conventions, without the PR text or prior findings. Static review.

Covered (as reported): info(), _path_info, _head_object, cache lookup and eviction, the entry factories, ls/find/walk/du/glob, copy/move/download/delete planning, S3FileTarget, sync and async reads, and the remaining readers of name and version_id. It confirmed that both file implementations gate pinning on version_aware, that to_api_repr() excludes VersionId, that ListObjectsV2 entries omit version_id, that bucket entries keep their key set and created(bucket) is None, and that the changed tests distinguish the two revisions.

Result: FINDINGS, 3 Medium and 2 Low. Repaired in d7820f3b: IR-1, IR-3, IR-4, IR-5. Already covered: IR-2.

  • IR-1 (Medium, repaired; this line). The requested version took precedence over the VersionId that HeadObject returned. The response's version is recorded first now, and the requested one only when the response has none (new test row unreported). This matches "the metadata from the response".
  • IR-3 (Medium, repaired). The AWS test_info_file compared info.version_id with the version of an unqualified path, which would fail on a versioned staging bucket. It now expects the version that HeadObject reports.
  • IR-4 (Low, repaired). The non-pinning test recorded requests at S3Core.call(). It now uses answer_s3_requests and checks the GetObject requests as the client receives them. Ungating S3FileTarget's pinning fails it (checked).
  • IR-5 (Low, repaired). The guide implied that du(version_id=...) names a version; only a version in the path does. The du() docstring now names directories as the listing does, not as info() does.
  • IR-2 (Medium, already covered). Removing from_metadata(version_id=...) is a 5.0.0 API change, listed in the PR's release notes.

just lint and just docs lint pass; offline filesystem suite 2248 passed; the matrix shows the 4 expected differences only.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent review (relayed), follow-ups. Codex CLI 0.172.0, gpt-6.2-astra, codex exec -s read-only, static. (1) Session 01a22cb0-a4d0-7e03-b558-d711b04cf765, range 961ea1c1..d7820f3b: two test findings: no case distinguished the precedence of the reported and the requested version, and the AWS expectation went through the same conversion as info(). Repaired in 01753da8: a reported-first row (request v1, report v2: name keeps v1, version_id is v2; the reverse precedence fails it, checked), and the AWS test reads VersionId from the client response. (2) Session 01a22cb7-8178-77d2-b497-5ebc208337b1, range d7820f3b..01753da8: CLEAN.

)
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:
Expand Down
81 changes: 69 additions & 12 deletions tests/pyathena/filesystem/test_s3.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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",
),
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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"
Expand Down