Repository navigation
Remove one protocol, s3:: included, from the paths of every method, and reject an S3Path version without a key (GH-1491) - #1615
Conversation
…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: |
There was a problem hiding this comment.
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:
remove_protocol()built the prefixes on every call. Measured:_strip_protocoltook 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.S3Path.PATTERNlisted the protocols again. It is now built fromPROTOCOLS.S3Path.version_separators()had no caller left. It is removed: it is on no release tag, and only on unreleased4.xthrough the Keep the slashes that end a version ID in path strings (GH-1469) #1481 backport.info()andwith_version_id()did not state the newValueError. They now do.- The Protocols section claimed that every method raises. It now states the
copy()/mv()source lookup before a doubled destination raises (R4), and thatunstrip_protocol()does not check. - The aio
_strip_protocoldocstring repeated the sync one; both now refer toS3Path.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 whilecat_file()of the same arguments reads versionv1of the key/. The lookups stripbucket//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_bucketpins the lookup side.- A subclass with other protocols can still pass a doubled prefix such as
myfs://s3://b/kthrough 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=())). AttributeErrorinstead ofTypeErrorfor anS3Pathpassed 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.PROTOCOLSon the filesystems: small gains, left as they are.
Evidence on 28118e4:
just lintpasses.just test offline: 4,627 passed.just docs lintpasses.- 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.
|
|
||
| ## Path addressing | ||
|
|
||
| ### Protocols |
There was a problem hiding this comment.
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, thecopy/mv/cp_filedestinations,cp_file, tags,getxattr/setxattr,list_multipart_uploads,metadata,object_version_info,put_file,rm,rm_file,sign,touchandunstrip_protocol. Correction: the PR body omittedput_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, throughcopy,copy -r,mvandpipe_file. Confirmed. - Doubled prefixes now raise before any request. E2 holds, except R3 (
isfilereturnsFalse) and R4 (copy/mvsend 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". Onlyinfo()returned the bucket. Reworded. - The docs on
bucket//("touch()and the destination ofcp_file()write the key/;pipe_file()andput_file()raise"). Matrix on 28118e4, sync, aio and aio coroutines:touchsendsPutObject Key=/, andcp_file_tosendsCopyObject Key=/.pipe_fileraisesCannot write to a bucket.andput_fileraisesThe path does not contain a key.Confirmed. S3Path.PATTERN. It still matches whatparse()returns for the valid spellings oftest_parse, includings3::,bucket//?versionId=v1and newline keys. It does not match the doubled spellings. Docs line 847 ("useS3Path.PATTERN") still holds.- "
version_separatorsis unreleased."git tag --contains 8a7cca5fis empty.origin/4.xhas it through 6c78870. The release note now says to mention the removal only if a4.xrelease 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;protocolsis a new keyword with a default.PATTERNonly gainss3::/s3a::.- Breaking changes for 5.0.0, listed in the release notes:
S3Path(bucket, None, v)raises; doubled prefixes raise;_strip_protocolraises for a doubled prefix inside fsspec helpers such asfsspec.open("s3://s3://b/k"). - Pickled
S3Pathobjects 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_pathskeeps 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( |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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
S3Pathparsing, 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.PathLikeinputs, transfers, and traversal. - Installed fsspec 2026.9.0 paths through
open_files,FSMap,_parent, expansion,walk,glob, andfind. - Filesystem documentation and all added, moved, or removed test cases. The named
PathLikecases survive the reorganization. The removed keyless-version case has constructor-rejection coverage.
FINDINGS
-
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 raisesValueError. Its size lookup strips the slashes and appliesv1to a keyless path. The merge base raisedFileNotFoundError, 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 -
Medium — A mapper rooted at
s3::cannot read an existing key.fs.get_mapper("s3::")["bucket/key"]passes/bucket/keytocat()and raisesValueError.fs.get_mapper("s3://")["bucket/key"]readsbucket/key. Both filesystem classes pass the raw root toFSMap, which joins it with"x"before stripping the protocol. That join inserts a slash afters3::. s3.py:2025 · s3_async.py:1858 · fsspec/mapping.py:46 -
Medium —
_parent()doubles a subclass’s root marker. Withroot_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 -
Medium — The change removes a public method.
S3Path.version_separators("bucket/key?versionId=v1//")returned"//"at the merge base and now raisesAttributeError. The API reference includesS3Path’s public members. Retaining this method is compatible with the new stripping implementation. s3_path.py:331, deletion site · API reference:93 -
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 aValueErroron both filesystems. Parsing happens inside the per-range read, where the defaulton_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 -
Medium — The protocol documentation overstates where the spellings are interchangeable. With PyAthena registered,
fsspec.open_files("s3::bucket/key")[0].pathis"". Likewise,fsspec.get_mapper("s3::bucket/prefix").rootis"". fsspec splits::into two URL-chain components before PyAthena sees the path. Scope the equivalence to paths passed directly to the filesystem and shows3://for these module-level APIs. filesystem.md:751 · fsspec/core.py:345 -
Low — The documented source-lookup order has exceptions. For
p = "s3://s3://bucket/key",fs.mv(p, p)returnsNonebefore any lookup. Conversely,fs.copy(["bucket/missing"], [p])raises the destinationValueErrorbefore 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 -
Low — The protocol cache retains arbitrary caller input indefinitely. A long-lived caller passing successive
protocols=f"tenant{i}"values toS3Path.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
-
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-prefixparse()tests would still pass because the bucket regex rejects the leftover colon. Yetpipe_file("s3://s3a://bucket/key", b"x")could strip one prefix at each layer and writebucket/key. The filesystem matrix uses onlys3://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 -
Low — Two directly observable results bypass the new tests. Removing
::fromS3Path.PATTERNwould makePATTERN.fullmatch("s3::bucket/key")returnNonewhile every parser test still passes, sinceparse()now uses_NAME_PATTERN. Both positive filesystem matrices also excludetree(), sotree("s3::bucket/dir")could lose its descendants undetected. Its echoed root and its descendants can be checked separately in one sync test because the aiotree()delegates to it. s3_path.py:93 · test_s3.py:3103 · test_s3_async.py:1057 -
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 andinfo()tests. The positive assertion aboutS3Path("bucket", "/", "v1")also runs identically for bothkeyparameters. 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 -
Low — Inserting the parser cases renumbers existing pytest selectors. For example,
test_parse[bucket/obj?versionId=v1-expected13]becomestest_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.
There was a problem hiding this comment.
Verification and disposition of the independent review. Repairs are in 5f8c36c ("Repair the independent review findings…"), rebased on master 4f320bf (#1555, #1561, #1587 merged).
- Fixed (regression of this PR). On 28118e4,
cat_file("s3://bucket//", start=-2, end=-1, version_id="v1")raised the newValueError; the merge base raisedFileNotFoundError. The sizing lookup used the stripped name whenever the path itself had no version.- A version given by
version_idis now looked up as parsed, as a version in the path already was (s3.py,_cat_object). Bothbucket//anddir/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 twotest_cat_file_version_idcases that pinned the lookup argument as the name string now expect theS3Path; the key and version are unchanged.
- A version given by
- Fixed (pre-existing; the merge base fails the same way).
get_mapper("s3::")named the keys/bucket/key. Bothget_mapper()overrides now pass the root throughunstrip_protocol(). Tests:test_mapper_of_chained_root, sync and aio. - Fixed (regression).
_parent()withroot_marker="/"returned//bucket/a. The parent is now joined to the marker once, as fsspec does. Tests: synctest_parent_of_subclass_root_marker, plus an assertion in the aio subclass test. - Rejected.
S3Path.version_separatorsis on no release tag (git tag --contains 8a7cca5fis 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.xrelease ships it first.
- Pre-existing; resolved by (a2) as decided.
cat_ranges([path], …)with the defaulton_error="return"returns theValueErrorof any invalid path for that range. On the merge base it does so fors3://bad bucket/ktoo.- 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.
- Validating the paths before dispatch is item 4 of issuecomment-7258834035, which the maintainer assigned to (a2) on 2026-11-30, as the
- Fixed. The Protocols section is limited to the filesystem's methods, and says that fsspec's own functions read
::as a chain separator. - 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. - Fixed.
lru_cache(maxsize=16). - Fixed.
test_remove_protocol_doubledcovers 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.
- Fixed.
test_parsealso checks the groups ofS3Path.PATTERN. The chained-protocol tests includetree(), comparing its result with the root line written ass3://. - Partly.
- The repeated
S3Path("bucket", "/", "v1")assertion is removed. - The
needs a keymatch is kept. It tells the version-without-key rejection apart fromInvalid S3 path format, whichinfo()of a bucket path could raise for another reason.
- The repeated
- Fixed. The
s3::cases oftest_parseare appended, which keeps the existing IDs. The removedtest_is_bucketcase cannot be constructed any more, so the auto IDs after it shift.
Validation on 5f8c36c (base 4f320bf):
just lintpasses;just docs lintpasses.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.
- Since Run the aio batch operations with the sync failure policy (GH-1456) #1555, two base runs also differ in the requests of failing aio
cat -rcells, the fail-fast schedule. R6 now excludes only the requests of every failingcat_reccell; their exceptions, store and local files are still compared.
- Since Run the aio batch operations with the sync failure policy (GH-1456) #1555, two base runs also differ in the requests of failing aio
- The new tests fail on 28118e4 (findings 1, 2, 3) or on the merge base (
s3::, doubled, mapper), as each should.
28118e4 to
5f8c36c
Compare
…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>
| # 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, |
There was a problem hiding this comment.
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_objectnow takes the parsed path whenever any version is given.version_idalready combines the path's version,version_idandVersionId, so an emptyVersionIdstill sizes by the name, as before.get_mapper(root)passesunstrip_protocol(root). FSMap strips it again, so"",bucket/dirands3a://bucketgive the samerootas before. AnS3Pathroot fails as it did on the base (stringify_pathkeeps the object)._parentstrips a leading root marker before joining it again. With the defaultroot_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_protocolcalls 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_idchanged only the form of the lookup argument, from the name string to theS3Path; the key and version are the same. - Evidence.
just lint,just docs lintandjust 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.
| """ | ||
| return super().get_mapper( | ||
| stringify_path(root), | ||
| self.unstrip_protocol(root), |
There was a problem hiding this comment.
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/anddir/for HeadObject and any subsequent GetObject. - Traced sync and aio
get_mapper()through fsspec’sFSMapfor empty, relative,s3::,s3a://, andos.PathLikeroots, includingcheck=Trueandcreate=True. The bares3::mapper now addressesbucket/keycorrectly. - 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
-
Medium —
get_mapper()breaks relative roots for subclasses with a custom protocol. Withprotocol = ("other", "s3", "s3a"),fs.get_mapper("bucket", check=True)previously worked on a writable bucket. It now passesother://bucketintoFSMap. The sync probe callstouch("other://bucket/<uuid>"), whose parser rejectsother://. The aio variant fails earlier because its underlyingS3FileSystem.exists()rejects that scheme, including withcreate=True. Restricting the rewrite to roots that already carry a::prefix preserves relative roots. s3.py:2043, s3_async.py:1788 -
Low — the protocol documentation omits the
cat_ranges()error policy. A doubled-prefix path produces aValueErrorin its result slot with the defaulton_error="return". Withon_error="raise", the call raises and returns no list. The new paragraph promises a per-range result unconditionally. filesystem.md:777 -
Low — the tree comparison masks an
unstrip_protocol()regression. The test rewrites every string result beginning withs3::. Iffs.unstrip_protocol("s3::bucket/key")incorrectly returns its input, the test converts it to the expecteds3://bucket/keyand passes. Limit this handling to thetree()case and check its displayed root explicitly. test_s3.py:3648, test_s3_async.py:917 -
Low — the mapper tests accept a read of the wrong object. Their fake returns
b"aa"for every GetObject. A mapper that readsbucket/bucket/keywould pass the equality check even though the store contains onlybucket/key. Checking the recordedBucketandKeywould establish the mapping. test_s3.py:3682, test_s3_async.py:950 -
Low — the versioned range test expects two bytes for a one-byte slice. For its two-byte object,
[-2:-1]requestsbytes=0-0and yieldsb"a". The fake returnsb"aa"even if GetObject omitsRange, 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-versionedS3Pathwould fail despite identical S3 requests. Both contracts can be checked at HeadObject and GetObject. test_s3.py:8392, test_s3.py:8351 -
Low — the new doubled-prefix tests require undocumented exception text. Changing the diagnostic while preserving
ValueErrorwould fail these tests. For the destination cases, checking the recorded requests for writes would also catch an overwrite of the existing source followed byValueError, 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.
There was a problem hiding this comment.
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").
- 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")passedother://bucket/dirto FSMap's check, whosetouch()could not parse it. - New test
test_mapper_of_relative_root_in_subclass(withcheck=True). It fails on 5f8c36c.
- Before, a subclass with
- Fixed. The docs say "with the default
on_error="return"". - Fixed. Both chained-protocol tests rewrite only the root line of
tree(), which they assert to bes3::bucket/dir. Anunstrip_protocol()that returned its input would now fail theunstrip_protocolcase. - Fixed. The mapper tests assert the request targets:
[("get_object", "key", None)]. - Fixed.
- The ranged test asserts
Range="bytes=0-0"together with the key and version of HeadObject and GetObject. test_cat_file_version_idnow checks the HeadObject and GetObject requests instead of the arguments of_info_entry(). Its parameters keep their shape, so the test IDs are unchanged.
- The ranged test asserts
- Partly.
- The destination tests now also assert that no request other than HeadObject is sent, so an overwrite before the
ValueErrorfails them. - The
Invalid S3 path formatmatch is kept: it is the message every parse test of the repository matches (test_parse_invalidand others), and it tells the parse rejection apart from otherValueErrors of the same calls.
- The destination tests now also assert that no request other than HeadObject is sent, so an overwrite before the
Validation on aa7a802 (base 4f320bf):
just lintandjust docs lintpass.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 -rofs3::bucket, the same bucket-root case as R6. It is now in R6's list.
| The ``fsspec.mapping.FSMap`` of the root. | ||
| """ | ||
| root = stringify_path(root) | ||
| if "::" in root.partition("/")[0]: |
There was a problem hiding this comment.
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://bucketand anos.PathLike(throughstringify_pathfirst) reach FSMap as on the merge base.s3::ands3::bucket/dirreach it ass3://….- 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 mutatedunstrip_protocol()returning its input fails theunstrip_protocolcase. - The mapper and range tests assert request targets, Range included.
test_cat_file_version_idkeeps its parameter shape and IDs, and checks requests instead of private arguments.
- The
- Claims. The commit message, PR body and docs sentence match the code:
cat_ranges()returns the error only with the defaulton_error="return". - Evidence.
just lintandjust docs lintpass;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.
| 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"] == [] |
There was a problem hiding this comment.
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 throughFSMapkey construction,check=True, andcreate=True. The reported("other", "s3", "s3a")subclass now accepts a relative root. Empty roots,s3://,s3a://, andos.PathLike[str]retain their behavior. PyAthena’sS3Pathwas already unsupported as a mapper root. - A bucketless
s3::mapper can read["bucket/key"].create=Truerecognizes the filesystem root as existing.check=Truestill raisesValueErrorbecause its temporary object has no bucket. - The
cat_ranges()documentation matches both implementations. The chained-path tests now normalize only the assertedtree()root line. The rangedcat_file()tests preserve their parameter IDs and check the expectedHeadObject,GetObject, version, and byte range.
FINDINGS
-
Medium — The mapper still rewrites unrecognized
::prefixes. The guard accepts any::before the first slash. On an aio subclass declaringprotocol = "s3a",get_mapper("s3::bucket/dir", create=True)passess3a://s3::bucket/dirto the backing filesystem’sexists(). It raisesValueErrorbefore looking up a prefix it accepts under the original spelling. The synchronous implementation has the same guard, and itscheck=Trueprobe encounters the doubled prefix attouch(). Match the class’s declaredprotocol + "::"prefixes explicitly. s3.py:2044 · s3_async.py:1789 -
Low — The subclass regression test exercises only the synchronous implementation. Reverting just the aio mapper to unconditional
unstrip_protocol()would leave its tests passing whileget_mapper("bucket/dir", check=True)again fails on the reported subclass. Parametrize the existing case over both classes. test_s3.py:3687 -
Low — The read assertions omit the S3 bucket. A
GetObjectforother-bucket/keypasses both chained-root mapper tests. The ranged test likewise accepts aHeadObjectagainst the wrong bucket because its fake returns the same size for every request. AssertBucketalongsideKeyon the recorded reads. test_s3.py:3685 · test_s3_async.py:953 · test_s3.py:8360 -
Low — The doubled-destination tests can miss an attempted delete.
s3_request_targets()emits one entry per object inDeleteObjects. If a failing move sends an empty delete batch before raisingValueError, 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):
- Fixed. Only a root that starts with
<p>::for a protocolpof the class is rewritten. The class'sprotocolis normalized from a string or a tuple. - Fixed.
- The subclass test exists for
AioS3FileSystemtoo, astest_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 withouts3. It works now only because the parse-as-given methods still use the default protocols, which (a2) changes.
- The subclass test exists for
- Fixed. The mapper and ranged
cat_file()tests assertBuckettogether withKey. - 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"]) |
There was a problem hiding this comment.
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_mapperimplementations 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://, andos.PathLike[str]. AnS3Pathmapper root already raisedAttributeErrorin the parent. - Checked key joining,
create=True, andcheck=True. At the declared roots3::,mapper["bucket/key"]addresses the correct object andcreate=Truesees an existing root. Withcheck=True, fsspec constructs the bucketless probes3:///<uuid>, which raisesValueErrorin both revisions. - Reviewed the changed tests against
docs/testing.md. The rangedcat_filetest checks bucket, key, version, and range on both requests. Both doubled-destination tests now detect an emptyDeleteObjectsrequest.
FINDINGS
-
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. Withprotocol = "s3a", exerciseget_mapper("s3::bucket/dir", check=True)on both classes. The parent passess3a://s3::bucket/dirto fsspec and the check raisesValueError. The repaired code should write its probe in bucketbucketunderdir/. A read throughget_mapper("s3a::")["bucket/key"]would also catch treating the string protocol as individual characters. test_s3.py:3689 · test_s3_async.py:957 -
Low — The chained-root mapper tests dropped the version check. A
GetObjectfor the expected bucket and key withVersionId="null"now satisfies both assertions. On a versioned bucket, that can return older data. Preserve the previousr.get("VersionId") is Nonecheck alongside the new bucket assertion. test_s3.py:3685 · test_s3_async.py:953
Disposition (915d13c, tests only):
- 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 iss3a. - 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::")andget_mapper("other::"). - This catches a string protocol split into its characters. A mutation that drops the str/tuple normalization fails both
[s3a]cases.
- Suggested:
- Fixed. Both chained-root mapper tests check
VersionIdagain, together with the bucket and the key.
Validation:
- On 47579f3:
just lintpasses;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 lintandjust test offline(4,846 passed) pass. The differential check was not rerun, because the commit changes only tests.
| ) | ||
| _, 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] == [ |
There was a problem hiding this comment.
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’sFSMap. Both assertions catch a wrong bucket, key, or string version ID. - The subclass reads at
other::ands3a::. If eitherget_mapperiterates"s3a"as characters, it skips normalization.FSMapthen constructs/bucket/key, which PyAthena rejects beforeGetObject. Theother::case catches hard-coded default protocols. - Test quality under the repository’s “Choose what to test” criteria. Sync and aio have separate
get_mapperimplementations, so each can regress independently. Clearing the request log isolates the subclass read from the precedingcheck=Trueprobe. Testing guide
FINDINGS
- Low severity. The default-root assertions accept an explicit
VersionId=Nonebecauser.get("VersionId")also returnsNonefor an absent field. The fake returns bytes for that request, while botocore rejectsNonefor the string parameter. The subclass assertions also acceptVersionId="v1", which could read an older version of the same key. Checking"VersionId" not in ralongside 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 ris False. just lintpasses;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] == [ |
There was a problem hiding this comment.
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/keyfrom thes3::root. Sync assertion · Aio assertion - Sync and aio subclass reads from
other::ands3a::. 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
GetObjectforbucket/key. SendingVersionId=Noneor any other value would make"VersionId" in rtrue and fail the assertion, even though the fake returns data. Request recorder
CLEAN
This closes the independent review of the series:
…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>
2c823de to
f735c12
Compare
| 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: |
There was a problem hiding this comment.
Rebase record
- The branch was rebased from 4f320bf..2c823de onto master 06d4802 as 06d4802..f735c12. Master had merged Quote the names and literals of the Hive DDL that to_sql() and generate_ddl() write (GH-1474) #1602 (SQL only) and Name explicit versions in info() and record HeadObject's VersionId (GH-1529) #1618 (Settle the S3Object entries and response models for 5.0.0 #1529:
info()names explicit versions,S3Object.from_metadatarecords HeadObject's VersionId). git range-diff: every commit is identical except the context of one test hunk in "Reject an S3Path with a version but no key". Upstream changed the expected name intest_info_looks_up_path_as_it_is, which sits next to the addedtest_info_version_of_bucket.- Upstream contracts checked against the series:
from_metadatabuilds entries frommetadata.path, which always has a key, so the newS3Pathinvariant does not reject it.- The
cat_file()sizing lookup comparesinfo.keyand the entry type, which the new naming does not change.
- Rerun on f735c12:
just lintandjust docs lintpass;just test offline: 4,875 passed, against 4,745 on the base; Sphinx is identical to the base; the differential check, base twice and branch twice: 0 problems, and the base-vs-base differences are inside R6.
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>
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 raisesValueErrorwhen another of the protocols follows the one removed.S3Path.parse()uses it (new optionalprotocolsargument, default("s3", "s3a")).s3::bucket/keyands3a::bucket/key, which raisedInvalid S3 path formatthere:cat_file,rm_file,rm,touch,cp_file, thecopy/mvdestinations, the key check ofput_file,sign,metadata, xattrs, tags,chmod,list_multipart_uploadsandobject_version_info._strip_protocol()is not slower than before._strip_protocol(),_parent()andunstrip_protocol()ofS3FileSystemandAioS3FileSystemwere verbatim copies over fsspec's implementations. Each is now one line that passes the class'sprotocoltoS3Path.strip_protocol(),S3Path.parent_name()orS3Path.unstrip_protocol()._strip_protocol()removed one prefix per protocol, sos3://s3://bucket/k,s3::s3://bucket/k,s3a://s3://bucket/kands3://s3a://bucket/kreached the keykin the strip-first methods, writes included (pipe_file,copy,mv). They now raiseValueErrorbefore any request.isfile()still returnsFalsefor them, because fsspec'sisfilecatchesException.copy()/mv()raise only after looking up the source, because they parse a destination after that lookup.unstrip_protocol("s3::bucket/k")returnss3://bucket/k(wass3://s3::bucket/k). A://alias such ass3a://is kept.get_mapper("s3::")readsbucket/keyasget_mapper("s3://")does. Before, fsspec joined that root with the keys as/bucket/key. Bothget_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'sroot_markeronce, 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")andinfo("s3://bucket", version_id="v1")raiseValueError. The first two built a bucket path with a version, whichinfo()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 byversion_idby the key as written, as it already did for a version in the path. Before, it sized the name without its trailing slash: fors3://bucket//that became the newValueErrorof a bucket with a version, and fors3://bucket/dir/it sized the version ofdir.docs/filesystem.md:touch()and thecp_file()destination write the key/, whilepipe_file()andput_file()raise. It said that every write raises. Address the key as written in the single-object methods, pipe_file, put_file and get_file included #1511 changes those two methods and rewrites the section.S3Path.PATTERNstays a public regular expression for the default protocols, now includings3::ands3a::. It is built fromS3Path.PROTOCOLS.parse()matches the protocol-free part afterremove_protocol().S3Path.version_separators()is removed. It has no caller since_strip_protocol()usesS3Path.strip_protocol(). It is on no release tag;4.xhas it through the Keep the slashes that end a version ID in path strings (GH-1469) #1481 backport.parse()takesprotocols, 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:
S3Pathpassed inward and accepted everywhere;isfile()catching onlyOSError;S3Path;expand_path();cat_ranges()returns theValueErrorof 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):
s3::ands3a::paths.s3://s3://bucket/key, raisesValueErrorinstead of namingbucket/keyin some methods.unstrip_protocol("s3::bucket/key")returnss3://bucket/key.S3Pathwith a version but no key raisesValueError, also throughwith_version_id()andinfo(bucket_path, version_id=...).S3Path.remove_protocol,strip_protocol,parent_name,unstrip_protocol, and theprotocolsargument ofS3Path.parse.S3Path.version_separatorsis removed; mention it only if a4.xrelease 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:s3::and doubled-prefix runs of the sharedPATH_CALLS(sync and aio);S3Path, mapper (including a subclass with other protocols),_parentand rangedcat_filecases. No live AWS run; no AWS request or response changes, only which spellings reach them.uv run sphinx-build -b html docs <out>): 281 warnings, the same list as 06d4802 built in the same run._parentroot marker, and the doubled-destination cases of the methods that already raised. Everys3::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), theremove_protocol/unstrip_protocolcases,test_version_without_keyandtest_info_version_of_bucket. The doubled-prefix cases of the parse-as-given methods pass on both, because they already raised.test_is_bucketis removed:S3Path("bucket", None, "v1")can no longer be constructed, andtest_version_without_keychecks 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 decoykeyXversionId=,dir/,dir/a,dir/b,x/y,/@s1, and one pending upload ofkey. 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.s3://bucket/k,s3a://bucket/k,bucket/k, anos.PathLike,s3::bucket/k, the doubleds3://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)ands3://bad bucket/k.reopen(the file's__reduce__reopen) andunstrip_protocol.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).s3::Xcell equals the merge-base cell ofs3://X.ValueErrorwith no request and no change, exceptunstrip_protocol, which formats and does not validate (s3::s3://bucket/k→s3://s3://bucket/k).S3Path(bucket, None, v1)cell raisesValueErrorat construction.s3::….mv()returns early only for equal strings, so a move ofs3://bucket/kontos3::bucket/ksends the HeadObject that thes3a://alias already sends.isfile()of a doubled prefix returnsFalse.copy()/mv()to a doubled destination raise after the HeadObject of the source, with no write.S3Pathpassed to a method that does not take one yet (rm_file,touch, tags,chmod,list_multipart_uploads,object_version_info) fails withAttributeErrorinstead ofTypeError.get -rof the bucket root (any spelling), and every recursivecat()that raises. Their results, exceptions, store and local files are still compared.copy,copy -r,mvandpipe_file.s3::, the extra ones being R6 cells.S3Path(bucket, None, v1).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