Skip to content

Remove one protocol, s3:: included, from the paths of every method, and reject an S3Path version without a key (GH-1491) - #1615

Merged
laughingman7743 merged 9 commits into
masterfrom
fix/1491-protocol-remover
Nov 30, 2026
Merged

laughingman7743 merged 9 commits into
masterfrom
fix/1491-protocol-remover

Conversation

@laughingman7743

@laughingman7743 laughingman7743 commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

WHAT

Part (a1) of the entry point of #1491: one protocol remover for every path that a method reads, as decided on 2026-11-30 (decision 1 of the split).

  • S3Path.remove_protocol(path, protocols=S3Path.PROTOCOLS) removes at most one protocol, written with :// or, as fsspec chains it, with ::. It raises ValueError when another of the protocols follows the one removed. S3Path.parse() uses it (new optional protocols argument, default ("s3", "s3a")).
    • The methods that parse a path as given now accept s3::bucket/key and s3a::bucket/key, which raised Invalid S3 path format there: cat_file, rm_file, rm, touch, cp_file, the copy/mv destinations, the key check of put_file, sign, metadata, xattrs, tags, chmod, list_multipart_uploads and object_version_info.
    • The prefixes of the protocols are built once per protocols, so _strip_protocol() is not slower than before.
    • The methods that strip the protocol first already accepted these spellings.
  • _strip_protocol(), _parent() and unstrip_protocol() of S3FileSystem and AioS3FileSystem were verbatim copies over fsspec's implementations. Each is now one line that passes the class's protocol to S3Path.strip_protocol(), S3Path.parent_name() or S3Path.unstrip_protocol().
    • fsspec's _strip_protocol() removed one prefix per protocol, so s3://s3://bucket/k, s3::s3://bucket/k, s3a://s3://bucket/k and s3://s3a://bucket/k reached the key k in the strip-first methods, writes included (pipe_file, copy, mv). They now raise ValueError before any request.
    • Exceptions to that, unchanged until (a2): isfile() still returns False for them, because fsspec's isfile catches Exception. copy()/mv() raise only after looking up the source, because they parse a destination after that lookup.
    • unstrip_protocol("s3::bucket/k") returns s3://bucket/k (was s3://s3::bucket/k). A :// alias such as s3a:// is kept.
    • get_mapper("s3::") reads bucket/key as get_mapper("s3://") does. Before, fsspec joined that root with the keys as /bucket/key. Both get_mapper() overrides write a root that starts with a :: protocol with ://; any other root is passed as it is.
    • _parent() joins the parent to a subclass's root_marker once, as fsspec does.
  • S3Path.__post_init__() rejects a version without a key (approved item 2 of issuecomment-7258834035). S3Path("bucket", None, "v1"), S3Path("bucket").with_version_id("v1") and info("s3://bucket", version_id="v1") raise ValueError. The first two built a bucket path with a version, which info() returned as the bucket, ignoring the version. A version of the key / (bucket//?versionId=v1) still names an object.
  • cat_file() sizes a negative or empty range of a version given by version_id by the key as written, as it already did for a version in the path. Before, it sized the name without its trailing slash: for s3://bucket// that became the new ValueError of a bucket with a version, and for s3://bucket/dir/ it sized the version of dir.
  • docs/filesystem.md:
  • S3Path.PATTERN stays a public regular expression for the default protocols, now including s3:: and s3a::. It is built from S3Path.PROTOCOLS. parse() matches the protocol-free part after remove_protocol().
  • S3Path.version_separators() is removed. It has no caller since _strip_protocol() uses S3Path.strip_protocol(). It is on no release tag; 4.x has it through the Keep the slashes that end a version ID in path strings (GH-1469) #1481 backport.
  • parse() takes protocols, which (a2) passes as () for the names the filesystem has already stripped. Until then, the strip-first methods of a subclass with other protocols still remove a default protocol a second time, as on master.

Out of scope, in (a2), whose prerequisites #1555, #1587, #1561 and #1599 have merged, as decided:

  • the filesystem entry in every method, with the S3Path passed inward and accepted everywhere;
  • the subclass protocols in the methods that parse as given;
  • isfile() catching only OSError;
  • reopening from the resolved S3Path;
  • validating the literal names of expand_path();
  • retiring the any-string helpers;
  • the docs of fsspec compositions (item 6);
  • validating every path before a batch dispatches its reads (item 4). Until then, cat_ranges() returns the ValueError of a doubled or otherwise invalid path for its range, as on master.

Trailing slashes keep their current targets (#1511). The trailing-slash cp_file() source lookup was already fixed by #1510.

Release notes (5.0.0, master only):

  • Every method accepts s3:: and s3a:: paths.
  • A path with two leading protocols, such as s3://s3://bucket/key, raises ValueError instead of naming bucket/key in some methods.
  • unstrip_protocol("s3::bucket/key") returns s3://bucket/key.
  • S3Path with a version but no key raises ValueError, also through with_version_id() and info(bucket_path, version_id=...).
  • New public classmethods: S3Path.remove_protocol, strip_protocol, parent_name, unstrip_protocol, and the protocols argument of S3Path.parse. S3Path.version_separators is removed; mention it only if a 4.x release ships it first.

WHY

#1491 (a), the entry point, split into (a1) and (a2) in the decisions of 2026-11-30 (Codex and Claude Fable 5.2 consulted). The audit is #1493: decisions 1 and 2, defects 1, 2 and 16. (a1) shares no hunks with the open filesystem PRs, so it lands first, and (a2) builds the entry on its remover.

TEST

Tested commit: f735c12, on master 06d4802 (after #1555, #1561, #1587, #1602 and #1618).

  • just lint: pass. just docs lint: pass.
  • just test offline: 4,875 passed, against 4,745 on 06d4802. The 130 added cases are:
    • the s3:: and doubled-prefix runs of the shared PATH_CALLS (sync and aio);
    • the doubled-destination cases;
    • the S3Path, mapper (including a subclass with other protocols), _parent and ranged cat_file cases. No live AWS run; no AWS request or response changes, only which spellings reach them.
  • Sphinx (uv run sphinx-build -b html docs <out>): 281 warnings, the same list as 06d4802 built in the same run.
  • The new tests were run against the merge-base code. They fail there, except the guards of behavior that the merge base already had: the _parent root marker, and the doubled-destination cases of the methods that already raised. Every s3:: case of the methods that parsed as given fails there, as do the doubled-prefix cases of the strip-first methods (mv, copy, pipe, glob, put, get, tree, get_mapper), the remove_protocol/unstrip_protocol cases, test_version_without_key and test_info_version_of_bucket. The doubled-prefix cases of the parse-as-given methods pass on both, because they already raised.
  • One case of test_is_bucket is removed: S3Path("bucket", None, "v1") can no longer be constructed, and test_version_without_key checks that.

Differential check

The check runs offline with moto mock_aws() per case. Every case starts from the same seeded versioned bucket: k, key@v1/v2, key?versionId=, key?versionId=/, the decoy keyXversionId=, dir/, dir/a, dir/b, x/y, /@s1, and one pending upload of key. Each case gets a fresh filesystem and an empty request log. It records the result, the exception, the request multiset, the versions, delete markers and uploads after the call, and the local files.

  • Matrix: 27 spellings × 50 operations × sync / aio sync wrappers / aio coroutines = 3,915 cases.
    • Spellings: s3://bucket/k, s3a://bucket/k, bucket/k, an os.PathLike, s3::bucket/k, the doubled s3://s3://, s3::s3://, s3a://s3://, s3://s3a://, s3://s3::, S3Path(bucket, k), s3://bucket/dir/, s3::bucket/dir/, S3Path(bucket, dir/), s3://bucket, s3://bucket//, s3::bucket, S3Path(bucket), s3://, "", s3://bucket/key?versionId=v1, s3::bucket/key?versionId=v1, S3Path(bucket, key, v1), S3Path(bucket, key?versionId=/), s3://bucket/key?versionId=/, S3Path(bucket, None, v1) and s3://bad bucket/k.
    • Operations: the 48 of (b)'s matrix (Read a version ID query only after a key, and not as a glob (GH-1491) #1551), plus reopen (the file's __reduce__ reopen) and unstrip_protocol.
  • Merge base 06d4802, run twice: identical except the requests of failing recursive cat() cells. Since Run the aio batch operations with the sync failure policy (GH-1456) #1555, aio fails fast there too, so which parallel GetObjects are sent depends on the schedule (R6).
  • Expected differences, written before the implementation (E1-E3); any other cell must equal the merge base (E4):
    • E1: every s3::X cell equals the merge-base cell of s3://X.
    • E2: every doubled-prefix cell raises ValueError with no request and no change, except unstrip_protocol, which formats and does not validate (s3::s3://bucket/k → s3://s3://bucket/k).
    • E3: every S3Path(bucket, None, v1) cell raises ValueError at construction.
  • Refinements found on the first branch run, each checked by hand. Each is existing behavior of another spelling or is in (a2)'s scope:
    • R1: an exception message that names the caller's string says s3::….
    • R2: mv() returns early only for equal strings, so a move of s3://bucket/k onto s3::bucket/k sends the HeadObject that the s3a:// alias already sends.
    • R3: isfile() of a doubled prefix returns False.
    • R4: copy()/mv() to a doubled destination raise after the HeadObject of the source, with no write.
    • R5: an S3Path passed to a method that does not take one yet (rm_file, touch, tags, chmod, list_multipart_uploads, object_version_info) fails with AttributeError instead of TypeError.
    • R6: the schedule-dependent request logs are excluded: get -r of the bucket root (any spelling), and every recursive cat() that raises. Their results, exceptions, store and local files are still compared.
  • Branch f735c12, run twice, against both merge-base runs: no case outside the rules, and no expected difference missing. 937 or 938 cases differ from the merge base, depending on the R6 schedule:
    • 425 doubled prefix. In 48 of them the merge base wrote to the store, through copy, copy -r, mv and pipe_file.
    • 245 or 246 s3::, the extra ones being R6 cells.
    • 145 S3Path(bucket, None, v1).
    • 120 R5.
    • 1 to 3 R6 cells of other spellings.

The checker is attached as an inline review comment on s3_path.py. The harness is /tmp/pyathena-1491a/harness/matrix.py, built from (b)'s harness with the spellings above, and rebuilt identically after a WSL restart cleared /tmp.

🤖 Generated with Claude Code

laughingman7743 added a commit that referenced this pull request Nov 30, 2026
…ors (GH-1491)

From the first self-review of #1615:

- remove_protocol() built the prefixes of the protocols on every call, so
  _strip_protocol() took about 2.5 times as long as before. The prefixes are
  cached per protocols, which a class gives as a string or a tuple.
- S3Path.PATTERN is built from S3Path.PROTOCOLS, so the protocols are listed
  once.
- S3Path.version_separators() has no caller since _strip_protocol() uses
  strip_protocol(); it was not released.
- info() and with_version_id() state the ValueError of a version ID given
  with a bucket path.
- The Protocols section states that copy() and mv() look their sources up
  before they read the destinations, and that unstrip_protocol() does not
  check the path.
- The _strip_protocol() docstrings refer to S3Path.strip_protocol() instead
  of repeating it, and the doubled-protocol tests of both filesystems use
  the same local directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
return cls(match.group("bucket"), match.group("key"), match.group("version_id"))

@classmethod
def remove_protocol(cls, path: str, protocols: str | tuple[str, ...] = PROTOCOLS) -> str:

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Self-review round one (behavior and implementation): FINDINGS → repaired in 28118e4.

Scope: git diff 79b0f8ef8ee3603800dff4e872b3c2ad7efa83d6..28118e41d49065d7c7f447f8ec1743bf684bc82c (merge base 79b0f8e, head 28118e4). Covered: S3Path.remove_protocol/strip_protocol/parent_name/unstrip_protocol/parse/PATTERN/__post_init__, the sync and aio _strip_protocol/_parent/unstrip_protocol forwarders, the callers of S3Path.parse() and _strip_protocol() in s3.py, s3_async.py, s3_path_pairing.py and s3_cache.py, the new and reorganized tests, and the docs/filesystem.md changes. Passes: /code-review high and /simplify (reuse, simplification, efficiency, altitude), plus my own pass.

Verified and repaired:

  1. remove_protocol() built the prefixes on every call. Measured: _strip_protocol took about 2.5 times as long as on the merge base (+0.5 µs per path, which matters when expanding or listing many entries). The prefixes are now cached per protocols (s3_path.py:148). Measured afterwards: 295 ns, against 380 ns on the merge base.
  2. S3Path.PATTERN listed the protocols again. It is now built from PROTOCOLS.
  3. S3Path.version_separators() had no caller left. It is removed: it is on no release tag, and only on unreleased 4.x through the Keep the slashes that end a version ID in path strings (GH-1469) #1481 backport.
  4. info() and with_version_id() did not state the new ValueError. They now do.
  5. The Protocols section claimed that every method raises. It now states the copy()/mv() source lookup before a doubled destination raises (R4), and that unstrip_protocol() does not check.
  6. The aio _strip_protocol docstring repeated the sync one; both now refer to S3Path.strip_protocol. The aio doubled-protocol test used another local layout than the sync one; both now use the same.

Checked, no change:

  • info("s3://bucket//", version_id="v1") raises while cat_file() of the same arguments reads version v1 of the key /. The lookups strip bucket// to the bucket, and the single-object methods address the key as written: decision 3 of Settle one contract for caller-supplied S3 path strings #1493. Address the key as written in the single-object methods, pipe_file, put_file and get_file included #1511 keeps that split, so this is by design. test_info_version_of_bucket pins the lookup side.
  • A subclass with other protocols can still pass a doubled prefix such as myfs://s3://b/k through the strip-first methods. S3Path.parse() removes the default protocol a second time, and the merge base behaves the same way. Parsing the stripped names without a protocol is part of (a2)'s entry (parse(name, protocols=())).
  • AttributeError instead of TypeError for an S3Path passed to a method that does not take one yet (R5). (a2) makes these methods take it.
  • Sharing the three test converters through a factory, and protocol = S3Path.PROTOCOLS on the filesystems: small gains, left as they are.

Evidence on 28118e4:

  • just lint passes.
  • just test offline: 4,627 passed.
  • just docs lint passes.
  • Sphinx: 281 warnings, the same list as the merge base built in the same environment.
  • The differential check, branch run twice against both merge-base runs: 0 problems, none missing.

Comment thread docs/filesystem.md

## Path addressing

### Protocols

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Self-review round two (claims, callers and evidence): FINDINGS (description only) → PR body corrected; no code change.

Scope: git diff 79b0f8ef8ee3603800dff4e872b3c2ad7efa83d6..28118e41d49065d7c7f447f8ec1743bf684bc82c, the PR body, the four commit messages, the changed docstrings, docs/filesystem.md (all of it, searched for statements this change makes obsolete), and issue premises repeated in the PR (#1491 decisions, #1493 defects 1, 2, 16).

Claims checked against evidence:

  • s3:: now works in the methods that parsed as given. The matrix shows which methods' s3:: cells changed on the branch: cat_file, chmod, the copy/mv/cp_file destinations, cp_file, tags, getxattr/setxattr, list_multipart_uploads, metadata, object_version_info, put_file, rm, rm_file, sign, touch and unstrip_protocol. Correction: the PR body omitted put_file, whose destination key check parsed as given. It is now listed.
  • Doubled prefixes used to reach k, writes included. On the merge base, 4 of the 5 doubled spellings returned results in 86 cells each. 48 cells changed the store, through copy, copy -r, mv and pipe_file. Confirmed.
  • Doubled prefixes now raise before any request. E2 holds, except R3 (isfile returns False) and R4 (copy/mv send the source HeadObject first). The PR body and the docs state both exceptions.
  • The version-without-key cases. Correction: with_version_id() built a bucket path with a version; it did not "return the bucket". Only info() returned the bucket. Reworded.
  • The docs on bucket// ("touch() and the destination of cp_file() write the key /; pipe_file() and put_file() raise"). Matrix on 28118e4, sync, aio and aio coroutines: touch sends PutObject Key=/, and cp_file_to sends CopyObject Key=/. pipe_file raises Cannot write to a bucket. and put_file raises The path does not contain a key. Confirmed.
  • S3Path.PATTERN. It still matches what parse() returns for the valid spellings of test_parse, including s3::, bucket//?versionId=v1 and newline keys. It does not match the doubled spellings. Docs line 847 ("use S3Path.PATTERN") still holds.
  • "version_separators is unreleased." git tag --contains 8a7cca5f is empty. origin/4.x has it through 6c78870. The release note now says to mention the removal only if a 4.x release ships it first.
  • Tested revision, counts and Sphinx. Correction: the tested commit was updated to 28118e4, the differing count to "935 or 936 (R6)", and Sphinx to 281 warnings, the same list as the merge base built in the same environment. The earlier 202 came from another environment state, and the base and the branch were identical there too.

Caller compatibility:

  • S3Path.parse(path) keeps its positional form; protocols is a new keyword with a default.
  • PATTERN only gains s3::/s3a::.
  • Breaking changes for 5.0.0, listed in the release notes: S3Path(bucket, None, v) raises; doubled prefixes raise; _strip_protocol raises for a doubled prefix inside fsspec helpers such as fsspec.open("s3://s3://b/k").
  • Pickled S3Path objects reconstruct without __post_init__, so old pickles still load.

Operational effects: no change to requests, retries or caching. Only which spellings reach them changes. No live AWS run is needed; none was made.

Evidence:

  • The new tests were rerun against the merge-base code 79b0f8e: 66 cases fail there. Every case that this PR changes is among them, so each new test fails without its behavior.
  • The doubled-prefix cases of the parse-as-given methods also pass on the base, because they already raised.
  • test_path_like_paths keeps its test IDs; the collected IDs are identical, sync and aio.

)
_NAME_PATTERN: ClassVar[Pattern[str]] = re.compile(rf"\A{_NAME}", re.DOTALL)
# A path with one of the default protocols, or without one.
PATTERN: ClassVar[Pattern[str]] = re.compile(

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.

Differential check, for reviewers: the judge script of the matrix (expect_a1.py). It compares a branch run with a merge-base run under the expected differences E1-E4 and the refinements R1-R6 described in the PR body. The harness that produces the runs is /tmp/pyathena-1491a/harness/matrix.py (moto per case; 27 spellings × 50 operations × sync/aio/aio coroutines).

expect_a1.py
"""Check a branch run of the (a1) matrix against the base run and the expected differences.

Usage: expect_a1.py BASE.jsonl BRANCH.jsonl [-v]

Expected differences of (a1), written before the implementation:

E1. "s3::" is accepted by every method: each cell of an "s3::X" spelling on the
    branch equals the base cell of "s3://X" (result, exception, requests, store
    and local files), for every method and mode, unstrip_protocol included
    ("s3::bucket/k" -> "s3://bucket/k").
E2. A doubled prefix raises ValueError before any request in every method:
    exception "ValueError: ...", no requests, store and local files unchanged
    (equal to the base cell of a read-only method). Except unstrip_protocol,
    which formats and does not validate: "s3::s3://bucket/k" ->
    "s3://s3://bucket/k" (it converts the s3:: prefix), the other four doubled
    spellings already start with an alias and are returned as they are.
E3. S3Path("bucket", None, v1) raises ValueError at construction: every cell
    of "S3Path:bucket||{v1}" is "ValueError: ...", no requests, no change.
E4. Every other cell equals its base cell.

Refinements added after the first branch run (each checked by hand, reported
to the maintainer; all are existing behavior of other spellings, or (a2)'s
scope):

R1. An exception message that names the caller's string says "s3::..." where
    the s3:// cell says "s3://..." (same exception type and requests).
R2. mv() returns early only when the two strings are equal, so moving
    "s3://bucket/k" onto "s3::bucket/k" sends the HeadObject that the s3a://
    alias sends: mv_to of an "s3::X" spelling equals the base cell of "s3a://X"
    where one exists.
R3. isfile() still swallows the ValueError of a doubled prefix (fsspec's
    isfile catches Exception; item 1 is (a2)): result False, no requests.
R4. copy()/mv() parse a destination after the source lookups (audit defect 1,
    the single conversion of (a2)): a doubled destination raises ValueError
    after the HeadObject of the source "k", with no writes.
R5. An S3Path passed to a method that does not take one yet (rm_file, touch,
    tags, chmod, list_multipart_uploads, object_version_info) still fails,
    with AttributeError ('startswith') instead of TypeError; (a2) makes them
    take it.
R6. Known schedule noise, as in the (b) harness: cat(recursive=True) of
    "dir/" fails fast on the GetObject of "dir", so how many parallel
    GetObjects are sent varies, and whether the recursive get() of the bucket
    root sends HeadObject/ListObjectsV2 for "dir" depends on the thread
    schedule; the exception, store and local files are compared, not the
    requests.
"""

import re

import json
import sys

FIELDS = ("result", "exc", "requests", "state", "local")
S3C = {
    "s3::bucket/k": "s3://bucket/k",
    "s3::bucket/dir/": "s3://bucket/dir/",
    "s3::bucket": "s3://bucket",
    "s3::bucket/key?versionId={v1}": "s3://bucket/key?versionId={v1}",
}
DOUBLED = [
    "s3://s3://bucket/k",
    "s3::s3://bucket/k",
    "s3a://s3://bucket/k",
    "s3://s3a://bucket/k",
    "s3://s3::bucket/k",
]
UNSTRIP_DOUBLED = {"s3::s3://bucket/k": "s3://s3://bucket/k"}
NOISY = {
    ("cat_rec", "s3://bucket/dir/"),
    ("get_rec", "s3://bucket"),
    ("get_rec", "s3://bucket//"),
    ("get_rec", "S3Path:bucket"),
}
R2_ALIAS = {"s3::bucket/k": "s3a://bucket/k"}
R5_METHODS = {
    "rm_file", "touch", "touch_notrunc", "get_tags", "put_tags", "chmod",
    "list_multipart_uploads", "object_version_info",
}


def same_message(branch_exc, ref_exc):
    """R1: the same exception, with the caller's s3:: spelling in the message."""
    if branch_exc == ref_exc:
        return True
    return bool(branch_exc and ref_exc) and branch_exc.replace("s3::", "s3://") == ref_exc


def load(path):
    return {(r["mode"], r["method"], r["spelling"]): r for r in map(json.loads, open(path))}


def main():
    base, branch = load(sys.argv[1]), load(sys.argv[2])
    verbose = "-v" in sys.argv
    seed = base[("sync", "info", "s3://bucket/k")]
    problems = []
    counts = {"E1": 0, "E2": 0, "E3": 0, "E4": 0}
    for key, rb in sorted(branch.items()):
        mode, method, spelling = key
        if rb.get("harness_error"):
            problems.append((key, "harness_error", rb["harness_error"][-300:]))
            continue
        if spelling in S3C:
            rule, ref = "E1", base[(mode, method, S3C[spelling])]
            if method == "mv_to" and spelling in R2_ALIAS:
                ref = base[(mode, method, R2_ALIAS[spelling])]
            bad = [f for f in FIELDS if f != "exc" and rb.get(f) != ref.get(f)]
            if not same_message(rb.get("exc"), ref.get("exc")):
                bad.append("exc")
            if method == "cat_rec" and spelling == "s3::bucket/dir/" and bad == ["requests"]:
                bad = []  # R6
        elif spelling in DOUBLED and method == "unstrip_protocol":
            rule = "E2"
            want = UNSTRIP_DOUBLED.get(spelling, spelling)
            bad = [] if rb.get("result") == want and not rb.get("exc") else ["result"]
        elif spelling in DOUBLED and method == "isfile":
            rule = "E2"  # R3
            bad = [] if rb.get("result") is False and not rb.get("requests") else ["result"]
        elif spelling in DOUBLED or spelling == "S3Path:bucket||{v1}":
            rule = "E2" if spelling in DOUBLED else "E3"
            bad = []
            if not (rb.get("exc") or "").startswith("ValueError"):
                bad.append("exc")
            source_lookup = ['["HeadObject", {"Bucket": "bucket", "Key": "k"}]']
            if rb.get("requests") and not (
                method in ("copy_to", "mv_to") and rb["requests"] == source_lookup  # R4
            ):
                bad.append("requests")
            if rb.get("state") != seed["state"]:
                bad.append("state")
            if rb.get("local"):
                bad.append("local")
        else:
            rule, ref = "E4", base[key]
            bad = [f for f in FIELDS if rb.get(f) != ref.get(f)]
            if bad == ["requests"] and (method, spelling) in NOISY:
                bad = []  # R6
            if (
                bad == ["exc"]
                and spelling.startswith("S3Path:")
                and method in R5_METHODS
                and (ref.get("exc") or "").startswith("TypeError")
                and re.match(r"AttributeError: 'S3Path' object has no attribute", rb.get("exc") or "")
            ):
                bad = []  # R5
        counts[rule] += 1
        if bad:
            problems.append((key, rule, bad))
    missing = sorted(set(base) - set(branch))
    print(f"cases={len(branch)} rules={counts} problems={len(problems)} missing={len(missing)}")
    for key, rule, bad in problems:
        print("PROBLEM", rule, key, bad)
        if verbose and isinstance(bad, list):
            ref = base.get(key)
            for f in bad:
                print(f"    {f}: base={json.dumps(ref.get(f) if ref else None)[:300]}")
                print(f"    {f}: branch={json.dumps(branch[key].get(f))[:300]}")
    return 1 if problems or missing else 0


if __name__ == "__main__":
    sys.exit(main())

return cls(match.group("bucket"), match.group("key"), match.group("version_id"))

@classmethod
def remove_protocol(cls, path: str, protocols: str | tuple[str, ...] = PROTOCOLS) -> str:

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): Codex CLI codex exec -s read-only (model gpt-6.2-astra; session 01a22c91-b37b-7a23-a956-c852a7ee488a).

Scope:

  • Merge base 79b0f8e, head 28118e4, reviewed in a detached snapshot of 28118e4. The snapshot was unchanged afterwards.
  • The prompt was neutral: the agreed contract and the repository conventions. It included no PR number, description, commits or earlier findings.
  • Read-only; no tests, network or AWS. This is a static review.

Result: FINDINGS. The reviewer's report, verbatim:

Codex report

Static review. I verified that the supplied diff matches 79b0f8ef..28118e41. I used local source inspection only. The tracked worktree is clean. Serena reported initializing ignored .serena/ metadata.

Surfaces covered

  • S3Path parsing, public regex and helpers, protocol caching, bucket/version validation, and slash-only keys.
  • Sync and aio path handling for roots, aliases, trailing slashes, version queries, lists, os.PathLike inputs, transfers, and traversal.
  • Installed fsspec 2026.9.0 paths through open_files, FSMap, _parent, expansion, walk, glob, and find.
  • Filesystem documentation and all added, moved, or removed test cases. The named PathLike cases survive the reorganization. The removed keyless-version case has constructor-rejection coverage.

FINDINGS

  1. Medium — A ranged read of the key / changes exception type. With an accessible bucket, fs.cat_file("s3://bucket//", start=0, end=0, version_id="v1") now raises ValueError. Its size lookup strips the slashes and applies v1 to a keyless path. The merge base raised FileNotFoundError, which the filesystem guide explicitly specifies for this range and spelling. A caller catching that documented exception now misses it. s3.py:4238 · s3_path.py:115 · filesystem.md:393

  2. Medium — A mapper rooted at s3:: cannot read an existing key. fs.get_mapper("s3::")["bucket/key"] passes /bucket/key to cat() and raises ValueError. fs.get_mapper("s3://")["bucket/key"] reads bucket/key. Both filesystem classes pass the raw root to FSMap, which joins it with "x" before stripping the protocol. That join inserts a slash after s3::. s3.py:2025 · s3_async.py:1858 · fsspec/mapping.py:46

  3. Medium — _parent() doubles a subclass’s root marker. With root_marker="/", _parent("/bucket/a/key") now returns //bucket/a. The merge base returned /bucket/a. This also happens when the input comes from a previous _parent() call. Both wrappers prepend the marker without removing one already present. s3.py:2060 · s3_async.py:1893

  4. Medium — The change removes a public method. S3Path.version_separators("bucket/key?versionId=v1//") returned "//" at the merge base and now raises AttributeError. The API reference includes S3Path’s public members. Retaining this method is compatible with the new stripping implementation. s3_path.py:331, deletion site · API reference:93

  5. Medium — cat_ranges() does not raise for a doubled prefix by default. fs.cat_ranges(["s3://s3://bucket/key"], 0, 1) returns a one-element list containing a ValueError on both filesystems. Parsing happens inside the per-range read, where the default on_error="return" collects the exception. Checking doubled prefixes before dispatch would preserve ordinary per-range error handling and meet the agreed validation contract. s3.py:4137 · s3_async.py:1397 · filesystem.md:754

  6. Medium — The protocol documentation overstates where the spellings are interchangeable. With PyAthena registered, fsspec.open_files("s3::bucket/key")[0].path is "". Likewise, fsspec.get_mapper("s3::bucket/prefix").root is "". fsspec splits :: into two URL-chain components before PyAthena sees the path. Scope the equivalence to paths passed directly to the filesystem and show s3:// for these module-level APIs. filesystem.md:751 · fsspec/core.py:345

  7. Low — The documented source-lookup order has exceptions. For p = "s3://s3://bucket/key", fs.mv(p, p) returns None before any lookup. Conversely, fs.copy(["bucket/missing"], [p]) raises the destination ValueError before looking up the source because two lists are paired as given. The source-first caveat applies to scalar paths that undergo a source lookup. filesystem.md:755 · s3.py:2923 · s3.py:3016

  8. Low — The protocol cache retains arbitrary caller input indefinitely. A long-lived caller passing successive protocols=f"tenant{i}" values to S3Path.parse("bucket/key", ...) retains one cache entry per value for the life of the process. The default filesystem uses a fixed tuple. A bounded cache would also cover callers using the new public argument. s3_path.py:241

Test findings

  1. Medium — The doubled-prefix tests miss two ways an invalid destination could be written. If remove_protocol() rejected only an identical second prefix, the mixed-prefix parse() tests would still pass because the bucket regex rejects the leftover colon. Yet pipe_file("s3://s3a://bucket/key", b"x") could strip one prefix at each layer and write bucket/key. The filesystem matrix uses only s3://s3://. Its copy and move cases also double both operands, so source rejection masks a destination-only regression. A direct mixed-prefix helper assertion and a valid-source/doubled-destination case would distinguish these failures. test_s3_path.py:124 · test_s3.py:3126 · test_s3_async.py:1086

  2. Low — Two directly observable results bypass the new tests. Removing :: from S3Path.PATTERN would make PATTERN.fullmatch("s3::bucket/key") return None while every parser test still passes, since parse() now uses _NAME_PATTERN. Both positive filesystem matrices also exclude tree(), so tree("s3::bucket/dir") could lose its descendants undetected. Its echoed root and its descendants can be checked separately in one sync test because the aio tree() delegates to it. s3_path.py:93 · test_s3.py:3103 · test_s3_async.py:1057

  3. Low — New tests pin undocumented error wording and repeat the slash-key assertion. Changing the constructor error to ValueError("A version requires an object key") preserves the contract but fails the constructor and info() tests. The positive assertion about S3Path("bucket", "/", "v1") also runs identically for both key parameters. Existing parse and request-target tests already verify that exact key and version. test_s3_path.py:177 · test_s3.py:2358 · test_s3.py:765

  4. Low — Inserting the parser cases renumbers existing pytest selectors. For example, test_parse[bucket/obj?versionId=v1-expected13] becomes test_parse[bucket/obj?versionId=v1-expected17]. Appending the new rows would preserve the existing selector. test_s3_path.py:33

Verification and disposition follow as replies in this thread.

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.

Verification and disposition of the independent review. Repairs are in 5f8c36c ("Repair the independent review findings…"), rebased on master 4f320bf (#1555, #1561, #1587 merged).

  1. Fixed (regression of this PR). On 28118e4, cat_file("s3://bucket//", start=-2, end=-1, version_id="v1") raised the new ValueError; the merge base raised FileNotFoundError. The sizing lookup used the stripped name whenever the path itself had no version.
    • A version given by version_id is now looked up as parsed, as a version in the path already was (s3.py, _cat_object). Both bucket// and dir/ are sized by the key as written, which matches the GetObject that reads them.
    • New test test_cat_file_range_version_argument_ending_in_slash. The two test_cat_file_version_id cases that pinned the lookup argument as the name string now expect the S3Path; the key and version are unchanged.
  2. Fixed (pre-existing; the merge base fails the same way). get_mapper("s3::") named the keys /bucket/key. Both get_mapper() overrides now pass the root through unstrip_protocol(). Tests: test_mapper_of_chained_root, sync and aio.
  3. Fixed (regression). _parent() with root_marker="/" returned //bucket/a. The parent is now joined to the marker once, as fsspec does. Tests: sync test_parent_of_subclass_root_marker, plus an assertion in the aio subclass test.
  4. Rejected.
    • S3Path.version_separators is on no release tag (git tag --contains 8a7cca5f is empty) and has no caller.
    • master is 5.0.0, and retiring that family of any-string helpers is approved for (a2) (item 5 of issuecomment-7258834035).
    • The PR's release notes mention the removal in case a 4.x release ships it first.
  5. Pre-existing; resolved by (a2) as decided. cat_ranges([path], …) with the default on_error="return" returns the ValueError of any invalid path for that range. On the merge base it does so for s3://bad bucket/k too.
    • Validating the paths before dispatch is item 4 of issuecomment-7258834035, which the maintainer assigned to (a2) on 2026-11-30, as the cat(on_error="return") ordering.
    • The docs now state the per-range result.
  6. Fixed. The Protocols section is limited to the filesystem's methods, and says that fsspec's own functions read :: as a chain separator.
  7. Fixed. The copy/mv ordering sentence is removed. The section now says that a method that reads a doubled path raises; mv(p, p) reads nothing.
  8. Fixed. lru_cache(maxsize=16).
  9. Fixed.
    • test_remove_protocol_doubled covers mixed prefixes (s3://s3a://, s3a::s3://).
    • test_doubled_protocol_destination (sync and aio) covers copy, mv, cp_file and pipe_file with a valid source and a doubled destination, and asserts that nothing is written.
  10. Fixed. test_parse also checks the groups of S3Path.PATTERN. The chained-protocol tests include tree(), comparing its result with the root line written as s3://.
  11. Partly.
    • The repeated S3Path("bucket", "/", "v1") assertion is removed.
    • The needs a key match is kept. It tells the version-without-key rejection apart from Invalid S3 path format, which info() of a bucket path could raise for another reason.
  12. Fixed. The s3:: cases of test_parse are appended, which keeps the existing IDs. The removed test_is_bucket case cannot be constructed any more, so the auto IDs after it shift.

Validation on 5f8c36c (base 4f320bf):

  • just lint passes; just docs lint passes.
  • just test offline: 4,842 passed, against 4,716 on the base.
  • Sphinx: 275 warnings, the same list as the base built in the same environment.
  • The differential check, base twice and branch twice: 0 problems.
  • The new tests fail on 28118e4 (findings 1, 2, 3) or on the merge base (s3::, doubled, mapper), as each should.

@laughingman7743
laughingman7743 force-pushed the fix/1491-protocol-remover branch from 28118e4 to 5f8c36c Compare November 30, 2026 13:47
laughingman7743 added a commit that referenced this pull request Nov 30, 2026
…ors (GH-1491)

From the first self-review of #1615:

- remove_protocol() built the prefixes of the protocols on every call, so
  _strip_protocol() took about 2.5 times as long as before. The prefixes are
  cached per protocols, which a class gives as a string or a tuple.
- S3Path.PATTERN is built from S3Path.PROTOCOLS, so the protocols are listed
  once.
- S3Path.version_separators() has no caller since _strip_protocol() uses
  strip_protocol(); it was not released.
- info() and with_version_id() state the ValueError of a version ID given
  with a bucket path.
- The Protocols section states that copy() and mv() look their sources up
  before they read the destinations, and that unstrip_protocol() does not
  check the path.
- The _strip_protocol() docstrings refer to S3Path.strip_protocol() instead
  of repeating it, and the doubled-protocol tests of both filesystems use
  the same local directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread pyathena/filesystem/s3.py
# A version of the path, also one given by version_id, is
# looked up as parsed, also one that ends in a slash,
# which the name would drop.
name if name is not None and not version_id else path,

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Self-review of the repair, both perspectives (5f8c36c over 4f320bf; the range-diff from 79b0f8e..28118e4 adds the repair commit, and the rebase reapplied the earlier commits unchanged).

  • Behavior.
    • _cat_object now takes the parsed path whenever any version is given. version_id already combines the path's version, version_id and VersionId, so an empty VersionId still sizes by the name, as before.
    • get_mapper(root) passes unstrip_protocol(root). FSMap strips it again, so "", bucket/dir and s3a://bucket give the same root as before. An S3Path root fails as it did on the base (stringify_path keeps the object).
    • _parent strips a leading root marker before joining it again. With the default root_marker="", lstrip("") is a no-op.
  • Upstream changes since the last review. Run the aio batch operations with the sync failure policy (GH-1456) #1555, Evict a missing bucket's cached entries, check mkdir() uncached, and keep max_paths entries (GH-1492) #1561 and Share the single-object copy and copy every annotation of a committed destination (GH-1520) #1587 add no new way to parse a path. Their new _strip_protocol calls go through the shared remover. The matrix on the new base shows no case outside the rules.
  • Claims. The commit message and the PR body name the observed behaviors. The tests that pin each repair fail on 28118e4. test_cat_file_version_id changed only the form of the lookup argument, from the name string to the S3Path; the key and version are the same.
  • Evidence. just lint, just docs lint and just test offline (4,842 passed) pass; Sphinx is identical to the base; the differential check, base twice and branch twice, has 0 problems.

Result: CLEAN for the repair.

Comment thread pyathena/filesystem/s3.py Outdated
"""
return super().get_mapper(
stringify_path(root),
self.unstrip_protocol(root),

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent follow-up review (relayed): Codex CLI codex exec -s read-only (model gpt-6.2-astra; session 01a22cd7-2410-7483-b835-a5c67fe0646a). Run with the serena and context7 MCP servers disabled, in a memory-capped scope, after two WSL restarts stopped earlier attempts.

Scope:

  • Head 5f8c36c, merge base 4f320bf.
  • The bounded package was the patch-series comparison git range-diff 79b0f8ef..28118e41 4f320bf0..5f8c36c5, the repair commit, and the upstream filesystem changes brought in by the rebase.
  • The snapshot was unchanged afterwards.
  • This is a static review.

Result: FINDINGS. The reviewer's report, verbatim:

Codex report

Static follow-up review of 5f8c36c5 on merge base 4f320bf0, using the checkout and installed fsspec 2026.9.0. No builds or tests were run.

Surfaces covered

  • Traced negative and empty cat_file() ranges through _cat_object(), _info_entry(), and their callers. An explicit version now preserves / and dir/ for HeadObject and any subsequent GetObject.
  • Traced sync and aio get_mapper() through fsspec’s FSMap for empty, relative, s3::, s3a://, and os.PathLike roots, including check=True and create=True. The bare s3:: mapper now addresses bucket/key correctly.
  • Checked _parent() with both "" and "/" root markers, the 16-entry prefix cache, the protocol documentation, and the changed tests. The appended parse cases preserve the existing IDs, and the versioned / key remains covered after removing the duplicate assertion.
  • Compared the patch series and traced the rebased aio batch handling, missing-bucket cache eviction, and shared copy implementation. I found no additional rebase-specific regression in those callers.

FINDINGS

  1. Medium — get_mapper() breaks relative roots for subclasses with a custom protocol. With protocol = ("other", "s3", "s3a"), fs.get_mapper("bucket", check=True) previously worked on a writable bucket. It now passes other://bucket into FSMap. The sync probe calls touch("other://bucket/<uuid>"), whose parser rejects other://. The aio variant fails earlier because its underlying S3FileSystem.exists() rejects that scheme, including with create=True. Restricting the rewrite to roots that already carry a :: prefix preserves relative roots. s3.py:2043, s3_async.py:1788

  2. Low — the protocol documentation omits the cat_ranges() error policy. A doubled-prefix path produces a ValueError in its result slot with the default on_error="return". With on_error="raise", the call raises and returns no list. The new paragraph promises a per-range result unconditionally. filesystem.md:777

  3. Low — the tree comparison masks an unstrip_protocol() regression. The test rewrites every string result beginning with s3::. If fs.unstrip_protocol("s3::bucket/key") incorrectly returns its input, the test converts it to the expected s3://bucket/key and passes. Limit this handling to the tree() case and check its displayed root explicitly. test_s3.py:3648, test_s3_async.py:917

  4. Low — the mapper tests accept a read of the wrong object. Their fake returns b"aa" for every GetObject. A mapper that reads bucket/bucket/key would pass the equality check even though the store contains only bucket/key. Checking the recorded Bucket and Key would establish the mapping. test_s3.py:3682, test_s3_async.py:950

  5. Low — the versioned range test expects two bytes for a one-byte slice. For its two-byte object, [-2:-1] requests bytes=0-0 and yields b"a". The fake returns b"aa" even if GetObject omits Range, and the request assertion checks only the key and version. The neighboring version-precedence test also pins the private _info_entry() argument shape, so passing an already-versioned S3Path would fail despite identical S3 requests. Both contracts can be checked at HeadObject and GetObject. test_s3.py:8392, test_s3.py:8351

  6. Low — the new doubled-prefix tests require undocumented exception text. Changing the diagnostic while preserving ValueError would fail these tests. For the destination cases, checking the recorded requests for writes would also catch an overwrite of the existing source followed by ValueError, which the final key-set comparison misses. test_s3.py:3671, test_s3_async.py:939, test_s3_path.py:172

Verification and disposition follow as a reply in this thread.

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.

Verification and disposition of the follow-up review. Repairs are in aa7a802 ("Rewrite only a chained root of a mapper, and tighten the protocol tests").

  1. Fixed (regression of 5f8c36c). get_mapper() now rewrites only a root that starts with a :: protocol; any other root is passed as it is.
    • Before, a subclass with protocol = ("other", "s3", "s3a") passed other://bucket/dir to FSMap's check, whose touch() could not parse it.
    • New test test_mapper_of_relative_root_in_subclass (with check=True). It fails on 5f8c36c.
  2. Fixed. The docs say "with the default on_error="return"".
  3. Fixed. Both chained-protocol tests rewrite only the root line of tree(), which they assert to be s3::bucket/dir. An unstrip_protocol() that returned its input would now fail the unstrip_protocol case.
  4. Fixed. The mapper tests assert the request targets: [("get_object", "key", None)].
  5. Fixed.
    • The ranged test asserts Range="bytes=0-0" together with the key and version of HeadObject and GetObject.
    • test_cat_file_version_id now checks the HeadObject and GetObject requests instead of the arguments of _info_entry(). Its parameters keep their shape, so the test IDs are unchanged.
  6. Partly.
    • The destination tests now also assert that no request other than HeadObject is sent, so an overwrite before the ValueError fails them.
    • The Invalid S3 path format match is kept: it is the message every parse test of the repository matches (test_parse_invalid and others), and it tells the parse rejection apart from other ValueErrors of the same calls.

Validation on aa7a802 (base 4f320bf):

  • just lint and just docs lint pass.
  • just test offline: 4,843 passed, against 4,716 on the base.
  • Sphinx: 281 warnings, the same list as the base built in the same run.
  • The differential check, base twice and branch twice: 0 problems.
    • The harness was rebuilt after the WSL restart, with the same 27 spellings × 50 operations.
    • One more schedule-dependent cell was seen between two base runs: aio get -r of s3::bucket, the same bucket-root case as R6. It is now in R6's list.

Comment thread pyathena/filesystem/s3.py Outdated
The ``fsspec.mapping.FSMap`` of the root.
"""
root = stringify_path(root)
if "::" in root.partition("/")[0]:

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Self-review of the repair aa7a802, both perspectives

Range: 5f8c36c..aa7a802, one commit; the base is unchanged (4f320bf).

  • Behavior. The root is rewritten only when its first segment contains ::.
    • "", bucket/dir, s3://bucket, s3a://bucket and an os.PathLike (through stringify_path first) reach FSMap as on the merge base.
    • s3:: and s3::bucket/dir reach it as s3://….
    • A subclass's relative root keeps working with check=True; the new test fails on 5f8c36c.
    • The aio override is the same code.
  • Tests.
    • The tree() root line is now asserted, not normalized away. A mutated unstrip_protocol() returning its input fails the unstrip_protocol case.
    • The mapper and range tests assert request targets, Range included.
    • test_cat_file_version_id keeps its parameter shape and IDs, and checks requests instead of private arguments.
  • Claims. The commit message, PR body and docs sentence match the code: cat_ranges() returns the error only with the default on_error="return".
  • Evidence. just lint and just docs lint pass; just test offline: 4,843 passed; Sphinx is identical to the base; the differential check, base twice and branch twice: 0 problems.

Result: CLEAN for the repair.

Comment thread tests/pyathena/filesystem/test_s3.py Outdated
with pytest.raises(ValueError, match="Invalid S3 path format"):
call(fs, dst)
assert sorted(store) == ["key"]
assert [t for t in s3_request_targets(requests) if t[0] != "head_object"] == []

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent follow-up review 2 (relayed): Codex CLI codex exec -s read-only (model gpt-6.2-astra; session 01a22d00-1feb-71a2-96e0-85e0bd0849bf). MCP servers disabled, memory-capped scope.

Scope:

  • The commit 5f8c36c..aa7a802, in a detached snapshot of aa7a802. The snapshot was unchanged afterwards.
  • This is a static review.

Result: FINDINGS. The reviewer's report, verbatim:

Codex report

Static review coverage for 5f8c36c5..aa7a8029, using the installed fsspec 2026.9.0 source.

  • Traced both get_mapper() implementations through FSMap key construction, check=True, and create=True. The reported ("other", "s3", "s3a") subclass now accepts a relative root. Empty roots, s3://, s3a://, and os.PathLike[str] retain their behavior. PyAthena’s S3Path was already unsupported as a mapper root.
  • A bucketless s3:: mapper can read ["bucket/key"]. create=True recognizes the filesystem root as existing. check=True still raises ValueError because its temporary object has no bucket.
  • The cat_ranges() documentation matches both implementations. The chained-path tests now normalize only the asserted tree() root line. The ranged cat_file() tests preserve their parameter IDs and check the expected HeadObject, GetObject, version, and byte range.

FINDINGS

  1. Medium — The mapper still rewrites unrecognized :: prefixes. The guard accepts any :: before the first slash. On an aio subclass declaring protocol = "s3a", get_mapper("s3::bucket/dir", create=True) passes s3a://s3::bucket/dir to the backing filesystem’s exists(). It raises ValueError before looking up a prefix it accepts under the original spelling. The synchronous implementation has the same guard, and its check=True probe encounters the doubled prefix at touch(). Match the class’s declared protocol + "::" prefixes explicitly. s3.py:2044 · s3_async.py:1789

  2. Low — The subclass regression test exercises only the synchronous implementation. Reverting just the aio mapper to unconditional unstrip_protocol() would leave its tests passing while get_mapper("bucket/dir", check=True) again fails on the reported subclass. Parametrize the existing case over both classes. test_s3.py:3687

  3. Low — The read assertions omit the S3 bucket. A GetObject for other-bucket/key passes both chained-root mapper tests. The ranged test likewise accepts a HeadObject against the wrong bucket because its fake returns the same size for every request. Assert Bucket alongside Key on the recorded reads. test_s3.py:3685 · test_s3_async.py:953 · test_s3.py:8360

  4. Low — The doubled-destination tests can miss an attempted delete. s3_request_targets() emits one entry per object in DeleteObjects. If a failing move sends an empty delete batch before raising ValueError, the fake store stays unchanged and both assertions pass. Check the raw recorded operation names for writes and deletes. test_s3.py:3675 · test_s3_async.py:943

Disposition (repaired in 47579f3):

  1. Fixed. Only a root that starts with <p>:: for a protocol p of the class is rewritten. The class's protocol is normalized from a string or a tuple.
  2. Fixed.
    • The subclass test exists for AioS3FileSystem too, as test_mapper_of_relative_root_in_subclass.
    • Both tests are parametrized over ("other", "s3", "s3a") and "s3a".
    • The tuple case fails on 5f8c36c for both classes.
    • Not pinned: get_mapper("s3::bucket/dir") on a class without s3. It works now only because the parse-as-given methods still use the default protocols, which (a2) changes.
  3. Fixed. The mapper and ranged cat_file() tests assert Bucket together with Key.
  4. Fixed. The doubled-destination tests assert that the raw request names are only HeadObject.

("get_object", "bucket", "key")
]

@pytest.mark.parametrize("protocol", [("other", "s3", "s3a"), "s3a"])

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent follow-up review 3 (relayed): Codex CLI codex exec -s read-only (model gpt-6.2-astra; session 01a22d0b-9951-7b61-85d3-504b99fa22ab). MCP servers disabled, memory-capped scope.

Scope:

  • The commit aa7a802..47579f3, in a detached snapshot of 47579f3. The snapshot was unchanged afterwards.
  • This is a static review.

Result: FINDINGS. The reviewer's report, verbatim:

Codex report

Surfaces covered in this static review of aa7a8029..47579f3a

  • Traced both get_mapper implementations through fsspec 2026.9.0. They rewrite only a declared <p>:: prefix and preserve the matched protocol. I checked string and tuple protocols, empty and relative roots, s3://, s3a://, and os.PathLike[str]. An S3Path mapper root already raised AttributeError in the parent.
  • Checked key joining, create=True, and check=True. At the declared root s3::, mapper["bucket/key"] addresses the correct object and create=True sees an existing root. With check=True, fsspec constructs the bucketless probe s3:///<uuid>, which raises ValueError in both revisions.
  • Reviewed the changed tests against docs/testing.md. The ranged cat_file test checks bucket, key, version, and range on both requests. Both doubled-destination tests now detect an empty DeleteObjects request.

FINDINGS

  1. Medium — The subclass tests miss the reported regression. All four cases use "bucket/dir", so restoring the parent’s broad :: guard would pass them all. With protocol = "s3a", exercise get_mapper("s3::bucket/dir", check=True) on both classes. The parent passes s3a://s3::bucket/dir to fsspec and the check raises ValueError. The repaired code should write its probe in bucket bucket under dir/. A read through get_mapper("s3a::")["bucket/key"] would also catch treating the string protocol as individual characters. test_s3.py:3689 · test_s3_async.py:957

  2. Low — The chained-root mapper tests dropped the version check. A GetObject for the expected bucket and key with VersionId="null" now satisfies both assertions. On a versioned bucket, that can return older data. Preserve the previous r.get("VersionId") is None check alongside the new bucket assertion. test_s3.py:3685 · test_s3_async.py:953

Disposition (915d13c, tests only):

  1. Partly. The suggested assertion would pin a behavior that the approved (a2) changes, so it is left out:
    • Suggested: get_mapper("s3::bucket/dir", check=True) succeeds on a class whose only protocol is s3a.
    • That holds today only because the methods that parse a path as given use the default protocols, which include s3.
    • (a2) makes those methods use the class's protocols, after which that root is rejected.
    • Added instead: both subclass tests read through a chained root with the class's own first protocol, get_mapper("s3a::") and get_mapper("other::").
    • This catches a string protocol split into its characters. A mutation that drops the str/tuple normalization fails both [s3a] cases.
  2. Fixed. Both chained-root mapper tests check VersionId again, together with the bucket and the key.

Validation:

  • On 47579f3: just lint passes; just test offline: 4,846 passed, against 4,716 on the base; Sphinx is identical to the base; the differential check, base twice and branch twice: 0 problems.
  • On 915d13c: just lint, just docs lint and just test offline (4,846 passed) pass. The differential check was not rerun, because the commit changes only tests.

Comment thread tests/pyathena/filesystem/test_s3.py Outdated
)
_, requests = serve_s3_keys(fs, {"key"})
fs.get_mapper("s3::")["bucket/key"]
assert [(name, r["Bucket"], r["Key"], r.get("VersionId")) for name, r in requests] == [

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent follow-up review 4 (relayed): Codex CLI codex exec -s read-only (model gpt-6.2-astra; session 01a22d1a-6990-70a2-b186-2b3ebbbd459d). MCP servers disabled, memory-capped scope.

Scope:

  • The commit 47579f3..915d13c, tests only, in a detached snapshot of 915d13c. The snapshot was unchanged afterwards.
  • This is a static review.

Result: FINDINGS (one, low). The reviewer's report, verbatim:

Codex report

Static review of 915d13c7. I covered these surfaces:

  • The sync and aio s3:: mapper reads through fsspec 2026.9.0’s FSMap. Both assertions catch a wrong bucket, key, or string version ID.
  • The subclass reads at other:: and s3a::. If either get_mapper iterates "s3a" as characters, it skips normalization. FSMap then constructs /bucket/key, which PyAthena rejects before GetObject. The other:: case catches hard-coded default protocols.
  • Test quality under the repository’s “Choose what to test” criteria. Sync and aio have separate get_mapper implementations, so each can regress independently. Clearing the request log isolates the subclass read from the preceding check=True probe. Testing guide

FINDINGS

  • Low severity. The default-root assertions accept an explicit VersionId=None because r.get("VersionId") also returns None for an absent field. The fake returns bytes for that request, while botocore rejects None for the string parameter. The subclass assertions also accept VersionId="v1", which could read an older version of the same key. Checking "VersionId" not in r alongside the operation, bucket, and key would close both false positives. Sync default · Aio default · Sync subclass · Aio subclass

Disposition: fixed in 2c823de.

  • The four mapper read assertions, sync and aio, default and subclass, now check "VersionId" in r is False.
  • just lint passes; just test offline: 4,846 passed.
  • The commit changes only tests, so the differential check was not rerun.

)
_, requests = serve_s3_keys(fs, {"key"})
fs.get_mapper("s3::")["bucket/key"]
assert [(name, r["Bucket"], r["Key"], "VersionId" in r) for name, r in requests] == [

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent follow-up review 5 (relayed): Codex CLI codex exec -s read-only (model gpt-6.2-astra; session 01a22d1f-051e-7981-bddf-349ce535bbcf). MCP servers disabled, memory-capped scope.

Scope:

  • The commit 915d13c..2c823de, tests only, in a detached snapshot of 2c823de. The snapshot was unchanged afterwards.
  • This is a static review.

Result: CLEAN.

Codex report

Static review of 2c823dee covered these surfaces.

  • Sync and aio mapper reads of bucket/key from the s3:: root. Sync assertion · Aio assertion
  • Sync and aio subclass reads from other:: and s3a::. Both tests clear the setup requests before checking the read. Sync assertion · Aio assertion
  • The fake S3 client records the keyword arguments it receives. All six cases require exactly one GetObject for bucket/key. Sending VersionId=None or any other value would make "VersionId" in r true and fail the assertion, even though the fake returns data. Request recorder

CLEAN

This closes the independent review of the series:

laughingman7743 and others added 9 commits December 1, 2026 00:44
…H-1491)

S3Path.remove_protocol() removes at most one protocol, written with "://"
or, as fsspec chains it, with "::", and raises ValueError when another
protocol follows it. S3Path.parse() uses it with the default protocols, so
the methods that parse a path as given accept "s3::bucket/key", which
raised ValueError there while the methods that strip the protocol first
accepted it.

_strip_protocol(), _parent() and unstrip_protocol() of S3FileSystem and
AioS3FileSystem pass the protocols of their class to S3Path.strip_protocol(),
S3Path.parent_name() and S3Path.unstrip_protocol(), which are written once.
fsspec's _strip_protocol() removed one prefix of each protocol, so
"s3://s3://bucket/key" reached the key "key" in the methods that strip
first, writes included; it now raises ValueError. unstrip_protocol() returns
"s3://bucket/key" for "s3::bucket/key" instead of "s3://s3::bucket/key".

The PathLike test calls are shared as PATH_CALLS, so that every method is
also run with the "s3::" and the doubled spellings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
touch("s3://bucket//") and the cp_file() destination "s3://bucket//" write
the key "/", as #1511 decided for every single-object write, while
pipe_file() and put_file() raise ValueError until #1511 changes them. The
docs said that every write to that spelling raises.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
S3Path("bucket", None, "v1") named the bucket, so info() of it, and
info("s3://bucket", version_id="v1"), returned the bucket and ignored the
version, while the string "bucket?versionId=v1" raised ValueError.
__post_init__() now raises ValueError for a version without a key, which
also covers with_version_id() of a bucket path. A version of the key "/"
(bucket//?versionId=v1) still names an object.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ors (GH-1491)

From the first self-review of #1615:

- remove_protocol() built the prefixes of the protocols on every call, so
  _strip_protocol() took about 2.5 times as long as before. The prefixes are
  cached per protocols, which a class gives as a string or a tuple.
- S3Path.PATTERN is built from S3Path.PROTOCOLS, so the protocols are listed
  once.
- S3Path.version_separators() has no caller since _strip_protocol() uses
  strip_protocol(); it was not released.
- info() and with_version_id() state the ValueError of a version ID given
  with a bucket path.
- The Protocols section states that copy() and mv() look their sources up
  before they read the destinations, and that unstrip_protocol() does not
  check the path.
- The _strip_protocol() docstrings refer to S3Path.strip_protocol() instead
  of repeating it, and the doubled-protocol tests of both filesystems use
  the same local directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
From Codex's review of 28118e4:

- cat_file() sized a negative or empty range of a version given by
  version_id with the name, which drops a trailing slash, so
  "s3://bucket//" with version_id raised the new ValueError of a bucket
  with a version, and "dir/" was sized by "dir". A version given by
  version_id is now looked up as parsed, as a version in the path already
  was, and both name the key as written.
- _parent() joined the parent to the root marker without removing the
  marker that the path already had, so a subclass with root_marker="/"
  returned "//bucket/a" for "/bucket/a/key". It is joined once, as fsspec
  does.
- get_mapper("s3::") named the keys "/bucket/key", because fsspec joins the
  root with "x" before it removes the protocol. The root is written with
  "s3://" first.
- The cache of the protocol prefixes is bounded.
- The Protocols section of the docs is limited to the methods of the
  filesystem: fsspec's own functions read "::" as a chain separator. It
  also states that cat_ranges() returns the error of such a path for its
  range, as for any invalid path, and drops the copy()/mv() ordering note.
- The tests also cover tree() with "s3::", a doubled destination after a
  valid source, mixed doubled prefixes in remove_protocol(), and the public
  PATTERN. The parse cases for "s3::" are appended, which keeps the IDs of
  the existing cases, and a duplicated assertion is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ts (GH-1491)

From Codex's follow-up review of 5f8c36c:

- get_mapper() wrote every root with a protocol of the class, so a
  subclass whose first protocol is not "s3" passed "other://bucket" to the
  check of FSMap, which touches the root as given and failed to parse it.
  Only a root that starts with a "::" protocol is rewritten; any other root
  is passed as it is.
- The docs say that cat_ranges() returns the error of a doubled path for
  its range with the default on_error="return".
- The chained-protocol tests rewrite only the root line of tree(), which
  they check, so that an unstrip_protocol() that returned "s3::" would
  fail them. The mapper tests check the key that is read, the destination
  tests check that no write is sent, and the ranged cat_file() tests check
  the HeadObject and GetObject requests, Range included, instead of the
  arguments of _info_entry().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
From Codex's second follow-up review of aa7a802:

- get_mapper() rewrote any root whose first segment contains "::", also a
  protocol that the class does not declare, so a subclass with
  protocol = "s3a" turned "s3::bucket/dir" into "s3a://s3::bucket/dir".
  Only a root that starts with "<protocol>::" for a protocol of the class
  is rewritten now.
- The subclass mapper test also runs for AioS3FileSystem, and for a class
  whose protocol is a single string.
- The mapper and ranged cat_file() tests check the bucket of the reads, and
  the doubled-destination tests check the names of all requests, so that an
  empty DeleteObjects request is not missed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…H-1491)

From Codex's third follow-up review of 47579f3:

- The mapper tests check again that the read names no version, which the
  bucket check had dropped.
- The subclass mapper tests also read through a root with the class's own
  first protocol, chained ("other::", "s3a::"), so that a protocol given as
  a string is not split into its characters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
From Codex's fourth follow-up review of 915d13c: r.get("VersionId") is
None both for a request without the parameter and for one that sends None
explicitly, and the subclass reads did not check the version at all. The
mapper tests now check that the GetObject request has no VersionId.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
return cls(match.group("bucket"), match.group("key"), match.group("version_id"))

@classmethod
def remove_protocol(cls, path: str, protocols: str | tuple[str, ...] = PROTOCOLS) -> str:

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Rebase record

@laughingman7743
laughingman7743 marked this pull request as ready for review November 30, 2026 16:08
@laughingman7743
laughingman7743 merged commit 3597987 into master Nov 30, 2026
16 checks passed
@laughingman7743
laughingman7743 deleted the fix/1491-protocol-remover branch November 30, 2026 16:22
laughingman7743 added a commit that referenced this pull request Dec 1, 2026
pipe_file(), put_file() and get_file() parse their argument once into
an S3Path with the protocol remover of #1615, keeping the trailing
slashes, and pass it to _open_path(). So s3://bucket/dir/ is the key
dir/ and s3://bucket// the key / on every path, as for cat_file(),
rm_file(), touch() and the other single-object methods. pipe_file() and
put_file() of bucket// write the key / instead of raising ValueError,
and get_file() of dir/ downloads the folder marker when it exists.
pipe_file() also accepts an S3Path.

A ranged cat_file() that needs the size of the object looks up the key
as written, so the range of a marker no longer raises FileNotFoundError.

The docs replace the paragraph on trailing slashes and the section on
bucket// with one table of the three groups of methods.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant