Skip to content

Fix the defects that the 4.x backport reviews found in master (get() checks, concurrent close, docs, tests) #1565

Backlog

Description

@laughingman7743

Problem

The independent reviews of the 4.x backports (#1552, #1553, #1560) found defects in the master changes themselves. The backports keep master's code, so the fixes go to master first and are then backported. Each item below is on master at abe633c. Items marked verified were checked against the code or reproduced; the others are static review findings that the fixing PR has to confirm first.

1. get() destination check (#1516)

  1. An existing local directory skips the check of its source (verified by reading the code). S3FileSystem._check_local_destinations() skips a destination that is an existing directory (pyathena/filesystem/s3.py:3302) before it asks whether its S3 source is a file. With out/k already a directory, get(["bucket/k/child", "bucket/k"], ["out/k/child", "out/k"], batch_size=1) downloads child and then raises IsADirectoryError from get_file() for k, instead of ValueError before any download. Not a regression: before Reject get() files that other destinations lie below and keep folder markers as directories (GH-1487) #1516 the same call also ended in IsADirectoryError.
  2. bytes and str spellings of one path are not compared. os.path.realpath() keeps the type of its argument (s3.py:3305), so [b"/tmp/out/k", "/tmp/out/k/child"] passes the ancestor check: k is written, and the child's parent directory then fails.
  3. A listed source must be hashable. rp in directories (s3.py:3347) raises TypeError for a str subclass with __hash__ = None, even when the set is empty; such a source downloaded before Reject get() files that other destinations lie below and keep folder markers as directories (GH-1487) #1516.

2. invalidate_cache() docstring (#1481)

Verified. The docstring says that a path ending in slashes is invalidated with and without them (s3.py:4933). Since #1481, the slashes after a version ID belong to it: invalidating bucket/key?versionId=v1/ evicts the version v1/ and keeps v1, as test_s3.py checks. The docstring needs that exception.

3. S3Path pickles with an empty version ID (#1534)

Verified (the dataclass state is restored without __post_init__). S3Path.__post_init__() (pyathena/filesystem/s3_path.py:79) stores an empty version ID as None, but unpickling does not call it. An S3Path("bucket", "k", "") pickled by v4.3.0 keeps version_id="" when it is loaded, so it compares unequal to S3Path("bucket", "k"), and move_pairs() can accept two sources whose destinations are that one object.

4. Concurrent close() of AioS3StreamedFile (#1541)

Two tasks close a file opened for writing. The first close is cancelled while its PutObject runs, and S3 then answers AccessDenied. The first task waits for the request and raises its cancellation, but _close_once() (pyathena/filesystem/s3_async.py:2889) hands None to the second task, which returns as if the object had been written.

5. Docs and docstrings of the read path (#1541)

  1. docs/filesystem.md:184 says that a write() that takes nothing fails the download with OSError. A non-blocking raw stream whose write() returns None is not supported (S3File._write_all(), s3.py:6499, counts None as all of the data), which Fix the read path of S3 files (GH-1517) #1541 states but the guide does not.
  2. The S3File.__reduce__ docstring says that the reopened file reads the same object (s3.py:5658). With version awareness off, a literal key that looks like a version, such as S3Path("bucket", "x?versionId=null"), is reparsed on reopen as the null version of x. The filesystem guide already documents this; the docstring does not.

6. Tests

  1. test_batch_conflicting_pairs (test_s3.py): the upload collision pair s3://bucket/a and bucket/a is already equal after the protocol is stripped. A pair that is equal only once parsed, such as s3::s3://bucket/a and bucket/a, is not covered, so a comparison of strings would pass the test (Pair tuples as lists and align put() progress with _put() (GH-1482) #1498).
  2. test_get_file_with_destinations_below_it (sync and aio) and test_writer_invalid_block_size (test_s3_writer.py) match exception messages that are not documented; the exception type and the absence of writes are the contract (Reject get() files that other destinations lie below and keep folder markers as directories (GH-1487) #1516, Move the filesystem helpers to the objects they operate on (GH-1453) #1480). See docs/testing.md "Choose what to test".
  3. test_read_in_stopped_scope (test_s3_async.py): with three ranges and two workers, the executor already rejects the third range before the file's read, so the test passes without the per-request check that Fix the read path of S3 files (GH-1517) #1541 added.
  4. test_open_s3_additional_kwargs_none (test_s3_async.py): checks the stored encryption setting without an upload, so a wb open that drops it would pass.
  5. test_read_non_positive_block_size (aio) and test_open_read_non_positive_block_size (sync): a reintroduced endless range split hangs or exhausts the worker instead of failing; they need a bound.

Reproduction

Items 1.1 and 3 are reproducible offline: item 1.1 with a local directory out/k and a fake S3 holding k and k/child; item 3 by pickling an S3Path whose version_id is set to "" through object.__setattr__ and loading it. The other items come from reading the code and need a reproduction in the fixing PR.

Environment

master abe633c; also on 4.x after the backports #1552, #1553 and #1560.

Proposed fix (optional)

One PR on master that confirms each item, fixes the confirmed ones (or records why one is not changed), and is then backported to 4.x with the other fixes. Item 4 is the only one that can report success for a failed write; it comes first.

Activity

  1. laughingman7743 commented on Nov 30, 2026

    @laughingman7743
    MemberAuthor

    One more item, from the independent follow-up review of #1560 (static; not yet confirmed):

    5.3. pipe_file() docstring on transactions

    The S3FileSystem.pipe_file() docstring (master pyathena/filesystem/s3.py:3709) says that writes inside an fsspec transaction go through the buffered path, "which uploads the data as a parallel multipart upload". With the default block size, a one-byte pipe_file() inside fs.transaction stays buffered until the commit, which sends a single PutObject.

  2. laughingman7743 commented on Nov 30, 2026

    @laughingman7743
    MemberAuthor

    One more item, from the independent review of the 4.x backport #1568 (static; not yet confirmed):

    6.6. placeholder_connection() docstring

    The test helper placeholder_connection() (tests/pyathena/util.py, its **kwargs from 4062ca1, #1544) says "Building it sends no request to AWS." That holds for the default arguments, but it forwards connection arguments: placeholder_connection(role_arn="arn:aws:iam::123456789012:role/test") attempts AssumeRole while the connection is built. The docstring should limit the guarantee to arguments that make no request.

  3. laughingman7743 commented on Nov 30, 2026

    @laughingman7743
    MemberAuthor

    More items, from the independent review of the 4.x backport #1578 (static; not yet confirmed). The code, docs and tests are the same on master.

    6.7. SQLAlchemy 2.1 in the compliance suite (#1566)

    tests/sqlalchemy/test_suite.py (the quantifier test, (True, False, True, False)) expects SQLAlchemy 2.0's result for ~(any_(flags) == True). SQLAlchemy 2.1 negates the whole any_match, which gives (True, False, False, False) for flags = [True, False]. #1566 updated the compile-only test for this difference, but not the live compliance test.

    6.8. fsspec.open_files() and bucket versions (#1551)

    docs/filesystem.md (master line 779) lists fsspec.open_files() among the compositions that raise ValueError for a bucket path with a version. Its default expansion globs ?, so with only XversionId=v1 in the bucket, fsspec.open_files(["s3://bucket/?versionId=v1"]) returns a reader for that object.

    6.9. Engine option coverage (#1567)

    The consolidated engine test in tests/pyathena/sqlalchemy/test_base.py no longer checks that duration_seconds and verify reach the DB-API connection; the removed test_conn_str_duration_seconds and test_conn_str_verify did. A connection that dropped duration_seconds=1800 after the URL conversion would pass the replacement tests.

    6.10. Exception wording in #1551's tests

    tests/pyathena/filesystem/test_s3.py and test_s3_path_pairing.py (the bucket-version cases) match undocumented exception messages; the type and the absence of requests are the contract.

  4. laughingman7743 commented on Nov 30, 2026

    @laughingman7743
    MemberAuthor

    Two more items, from the independent follow-up review of the 4.x backport #1578, which now includes a8afdaa (#1538 item 1). Both are on master too.

    7. cp_file() of a directory path depends on the listing cache (a8afdaa)

    Verified offline with serve_s3_keys(fs, {"dir/child"}): cp_file("s3://bucket/dir/", "s3://bucket/dst") skips the directory on a cold cache (HeadObject, ListObjectsV2), but after fs.ls("s3://bucket/dir") it raises FileNotFoundError: bucket/dir/ without a request: the cached listing holds dir/child and no entry for dir/, and the lookup of the parsed source answers from it before the prefix check. Before a8afdaa, both calls skipped the directory. Same on master 0255e1f and on the current master; the async copy shares the lookup.

    8. bucket// writes (docs)

    docs/filesystem.md ("Bucket paths with a trailing double slash", master line 794) says that a write to s3://YOUR_S3_BUCKET//, "such as pipe_file()", raises ValueError. cp_file("s3://bucket/src", "s3://bucket//") sends CopyObject with the destination key /; only the writes that strip the trailing slashes, such as pipe_file(), raise.

  5. laughingman7743 commented on Nov 30, 2026

    @laughingman7743
    MemberAuthor

    More items, from the independent review of the 4.x backport #1591 (the discard() part of #1539; static, not yet confirmed). S3File.discard(), the write() docstring, the guide's paragraph and the tests are the same on master.

    9. An interrupted discard() can commit an empty object (#1539)

    discard() drops the buffer and marks the file closed before _abort_write() changes the write session. For a closed autocommit=False file that holds b"abc" for a deferred commit, an interrupt (Ctrl-C) on entry to _abort_write() leaves the session IDLE without the data; if the caller catches it and the transaction then commits, commit() sends an empty PutObject. The session should refuse the commit before the buffer is released.

    10. discard() with a pool executor of the calling thread (#1539)

    A worker of an S3ThreadPool(1) that uses that pool as an S3File's executor, writes inside with and calls discard(): discard() shuts the pool down with wait=False, and the with exit's _close() calls shutdown(wait=True), so the worker joins itself and raises RuntimeError.

    11. discard() docs (#1539)

    1. The S3File.write() docstring lists S3MultipartStateError only after flush(force=True), but after an explicit commit() of an open file the next write() raises it too; with autocommit=False, a flush(force=True) alone leaves the file open and uncommitted, and the next write() raises ValueError.
    2. The guide says that discard() makes a later close() commit nothing; a write that flush(force=True) already committed (autocommit, multipart) stays committed, and discard() sends no abort. "an uncommitted write" would say it.

    12. discard() tests (#1539)

    1. The forked-child test calls _close_without_commit() and then close() on the same handle, so a regression in either path is masked by the other.
    2. The post-discard() write() test matches fsspec's message ("not in write mode"); the exception type is the contract.
  6. laughingman7743 commented on Nov 30, 2026

    @laughingman7743
    MemberAuthor

    Item 9 is verified offline (serve_s3_keys; fs.open(..., "wb", autocommit=False), write(b"abc"), close(), then discard() with an interrupt raised on entry to the abort, then commit()):

    So #1539's discard() turns this interrupted case from committing the written data into committing an empty object. It is the first item to fix; the 4.x backport of discard() (#1591) waits for that fix.

  7. laughingman7743 commented on Nov 30, 2026

    @laughingman7743
    MemberAuthor

    More items, from the independent review of the 4.x adaptation of #1559 (#1594; static, not yet confirmed). Master's AthenaDialect.connect()/initialize() (#1559) has the same code.

    13. Connection arguments of #1559 (pyathena/sqlalchemy/base.py)

    1. connect() keeps the cparams dict of each connection, whose nested dicts (tblproperties, serdeproperties, cursor_kwargs) are shared with the arguments of later connections. A do_connect handler of a later connection that changes cparams["cursor_kwargs"]["s3_staging_dir"] in place changes the options that DDL takes from the first connection.
    2. A call of create_connect_args() outside the pool, concurrent with the first connection, can see _connected false and replace the options right after initialize() set them.
    3. weakref.ref(connection, ...) raises TypeError for a DB-API connection that cannot be weakly referenced, such as a proxy with __slots__ and no __weakref__ returned by a module passed with create_engine(module=...), so the first connection fails even if no DDL is compiled.
  8. laughingman7743 commented on Nov 30, 2026

    @laughingman7743
    MemberAuthor

    One more item, from the independent follow-up review of #1594 (static, not yet confirmed):

    13.4. test_create_table_takes_arguments_of_initializing_connection (#1559)

    The test closes the second connection, created in a first_connect listener, before the dialect is initialized, so its weak-reference callback removes its pending entry; an implementation that takes the latest pending arguments (popitem()) also passes. It also relies on first_connect running before Dialect.initialize(). Keeping the second connection open until the checkout ends (for example from a do_connect handler that creates both and returns the first) would distinguish them.

  9. added this to the 5.0.0 milestone on Nov 30, 2026
  10. laughingman7743 commented on Nov 30, 2026

    @laughingman7743
    MemberAuthor

    Items 9 to 12 (the discard() findings of #1539) move to #1628, which is in the 5.0.0 milestone: item 9 is a master-only regression against 4.4.0 and blocks 5.0.0. The remaining items stay here for 5.0.1; the 4.x backport #1591 now waits for #1628.

  11. modified the milestones: 5.0.0, 5.0.1 on Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions