From 5a252d37be55aa59ac186ff5b1c6b1e3736ce5c5 Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Mon, 30 Nov 2026 23:23:08 +0900 Subject: [PATCH 1/8] Make the write session public and share the file drivers (GH-1455) Publish S3WriteSession and S3WriteState in s3_writer.py. The states take plain names (COMMITTING and COMMITTED replace COMPLETING and COMPLETED), and the error messages describe them separately. One commit(body=None) sends PutObject or completes the multipart upload, chosen by whether the write started one, and rejects a non-empty body for a multipart upload; put() and complete() become private. begin_complete()/withdraw_complete() become reserve_commit()/withdraw_commit(). settled(), which no caller uses, is removed. abort_or_log() logs a failed or interrupted abort with the upload ID and replaces the abort-failure log sites of both files and of the multipart copy. Prepared parameters of an operation replace the session's request_kwargs for that operation. S3MultipartStateError becomes S3WriteStateError; the former name refers to the same class. S3File and AioS3StreamedFile keep their S3FileTarget, which builds the session and holds the shared append copies, commit, and abort; the blocking and awaited waits, the buffering, and the finalizers stay on each file. Co-Authored-By: Claude Opus 5.5 --- docs/api/filesystem.rst | 14 +- docs/filesystem.md | 55 ++- pyathena/filesystem/s3.py | 248 ++++++----- pyathena/filesystem/s3_async.py | 114 ++--- pyathena/filesystem/s3_writer.py | 466 +++++++++++--------- tests/pyathena/filesystem/test_s3.py | 77 ++-- tests/pyathena/filesystem/test_s3_async.py | 17 +- tests/pyathena/filesystem/test_s3_writer.py | 205 +++++++-- 8 files changed, 734 insertions(+), 462 deletions(-) diff --git a/docs/api/filesystem.rst b/docs/api/filesystem.rst index 638cfa5cd..adf09afab 100644 --- a/docs/api/filesystem.rst +++ b/docs/api/filesystem.rst @@ -186,13 +186,21 @@ S3 Requests .. autoclass:: pyathena.filesystem.s3_object.S3DeleteBatch :members: -Multipart Writer ----------------- +Multipart Writer and Write Session +---------------------------------- .. autoclass:: pyathena.filesystem.s3_writer.S3MultipartWriter :members: -.. autoclass:: pyathena.filesystem.s3_writer.S3MultipartStateError +.. autoclass:: pyathena.filesystem.s3_writer.S3WriteSession + :members: + +.. autoclass:: pyathena.filesystem.s3_writer.S3WriteState + :members: + +.. autoclass:: pyathena.filesystem.s3_writer.S3WriteStateError + +.. autodata:: pyathena.filesystem.s3_writer.S3MultipartStateError S3 Errors --------- diff --git a/docs/filesystem.md b/docs/filesystem.md index 58faf151e..29ab2649d 100644 --- a/docs/filesystem.md +++ b/docs/filesystem.md @@ -313,7 +313,7 @@ and a multipart upload can be left incomplete. `clear_multipart_uploads` removes uploads. A file returned by `open` whose write or commit has failed, or which has been -discarded, cannot be committed: its `commit()` raises `S3MultipartStateError`. Inside a +discarded, cannot be committed: its `commit()` raises `S3WriteStateError`. Inside a transaction, a write error that the caller catches therefore makes the transaction fail when it commits, and fsspec discards the files of the transaction that are not committed yet. @@ -1044,7 +1044,7 @@ treated as not passed. To create a directory bucket, pass its `Location` and `Bu ### Multipart writer `S3MultipartWriter` provides synchronous multipart requests and part planning without fsspec. -It plans the parts of the write session of `S3File` and `AioS3StreamedFile`, which sends them through `S3Core`; applications can also construct it on an `S3Core`. +It plans the parts of the write session (`S3WriteSession`, see [Write session](filesystem-write-session)) of `S3File` and `AioS3StreamedFile`, which sends them through `S3Core`; applications can also construct it on an `S3Core`. The constructor validates the destination and block size without sending a request. The caller owns the buffer and executor, collects part results in number order, and waits for running requests before completing or aborting. Serialize initiation and finalization; part requests can run in parallel after initiation. @@ -1086,14 +1086,61 @@ The caller can therefore retry a failed abort. The writer does not invalidate the filesystem cache; call `fs.invalidate_cache()` after a direct write. When an `S3File` wait for multipart creation is interrupted, it waits for any creation that has already started and recovers the successful response before aborting. -It drops the buffer and closes the file before waiting, so a later close cannot upload the interrupted write, and a deferred commit raises `S3MultipartStateError`. +It drops the buffer and closes the file before waiting, so a later close cannot upload the interrupted write, and a deferred commit raises `S3WriteStateError`. A Ctrl-C during the blocking recovery wait does not stop it; it is raised once the upload is aborted, and otherwise the original error is re-raised. An additional interruption outside that wait can stop cleanup; once the upload identity is known, `discard()` can retry the abort. An abort failure retains the upload identity for `discard()` to retry. An abort answered with `NoSuchUpload` discards the write, since the upload no longer exists; after a completion that took effect although it failed, such as one whose response was lost, the object holds the written data. -A failed `commit()` also closes the file without its buffered data and aborts the multipart upload, if any; a later `commit()` raises `S3MultipartStateError`. +A failed `commit()` also closes the file without its buffered data and aborts the multipart upload, if any; a later `commit()` raises `S3WriteStateError`. Cancelling a `write()` of a file from `open_async()` while it waits to submit a part closes the file without committing and aborts its multipart upload after the running part requests finish; a commit that `close()` or `flush(force=True)` has already queued still completes. +(filesystem-write-session)= + +### Write session + +`S3WriteSession` in `pyathena.filesystem.s3_writer` sends the requests of one write of an object and keeps its state; `S3File`, `AioS3StreamedFile`, and the multipart copies of `S3FileSystem` write through it. +It commits a write with a single PutObject request, or with a multipart upload whose parts it uploads or copies on an `S3Executor`, at most `max_workers` at once. +The constructor sends no request. + +```python +from pyathena.filesystem.s3_executor import S3ThreadPool +from pyathena.filesystem.s3_writer import S3WriteSession + +with S3ThreadPool(max_workers=4) as executor: + session = S3WriteSession( + core, + S3Path("YOUR_S3_BUCKET", "path/to/object"), + executor, + block_size=5 * 2**20, + max_workers=4, + ) + try: + session.start() + for number, body in session.iter_parts(stream): + session.wait_ready() + session.submit_part(number, body) + result = session.commit() + except BaseException: + session.abort_or_log() + raise +``` + +`start()` creates the multipart upload; without it, `commit(body)` writes `body` with PutObject, and `None` or empty bytes write an empty object. +After `start()`, `commit()` completes the upload once its parts have been uploaded, and rejects a non-empty `body`. +A successful commit returns its result again without another request. +`ready()` returns a future, and `wait_ready()` blocks, until another part may be submitted. +`check()` raises the first failure of a request; after it, the operations that the failure prevents raise `S3WriteStateError`, which is also available under its former name `S3MultipartStateError`. +`state` returns an `S3WriteState`, such as `ACTIVE`, `COMMITTING`, `COMMITTED`, or `ABORT_FAILED`. + +`abort()` cancels the part requests that have not started, waits for the running ones, and aborts the upload; it raises a failure of the abort and keeps the upload, so that a later `abort()` retries. +`abort_or_log()` logs such a failure, with the upload ID, instead of raising it, for a caller that raises the error that ended the write. +A driver that cannot block reserves the commit with `reserve_commit()` before it queues the call to `commit()`, withdraws the reservation with `withdraw_commit()` if that call never runs, and begins an abort with `begin_abort()`. +`commit_attempts` counts the commit requests that have started to be sent, including failed ones, which may have committed the object. + +The `request_kwargs` of the session are added to each request whose operation accepts them. +`prepared_params` gives the parameters of the requests of an operation by client method name, such as `create_multipart_upload`; they are sent as given and replace the `request_kwargs` of the session for that operation. +The session does not invalidate the filesystem cache; call `fs.invalidate_cache()` after a direct write. + ### Multipart requests `create_multipart_upload()`, `upload_part()`, `upload_part_copy()`, diff --git a/pyathena/filesystem/s3.py b/pyathena/filesystem/s3.py index 1acf9d4f8..a2f3e2379 100644 --- a/pyathena/filesystem/s3.py +++ b/pyathena/filesystem/s3.py @@ -14,7 +14,7 @@ import sys import threading import warnings -from collections.abc import Callable, Generator, Iterable, Mapping +from collections.abc import Callable, Generator, Iterable, Iterator, Mapping from concurrent.futures import CancelledError from copy import deepcopy from dataclasses import dataclass, field @@ -69,7 +69,7 @@ raise_if_stopped, unstoppable_retries, ) -from pyathena.filesystem.s3_writer import _S3WriteSession, _S3WriteState +from pyathena.filesystem.s3_writer import S3WriteSession, S3WriteState from pyathena.filesystem.util import override, user_agent_extra if TYPE_CHECKING: @@ -3805,7 +3805,7 @@ def _copy_object_with_multipart_upload( # for its requests, unless a further interrupt stopped that wait. executor = self._create_executor(max_workers=max_workers) try: - session = _S3WriteSession( + session = S3WriteSession( core, plan.destination, executor, @@ -3827,25 +3827,11 @@ def _copy_object_with_multipart_upload( for part_number, range_ in enumerate(plan.ranges, 1): session.wait_ready() session.submit_copy(part_number, plan.source, range_) - completed = session.complete() + completed = cast(S3CompleteMultipartUpload, session.commit()) except BaseException: - try: - session.abort() - except KeyboardInterrupt: - if (upload := session.upload) is not None: - _logger.warning( - f"Interrupted the abort of multipart upload {upload.upload_id} " - f"to s3://{upload.bucket}/{upload.key}." - ) - raise - except Exception: - # Logged instead of raised, so that the error that made - # the copy fail is raised. - upload = cast(S3MultipartUpload, session.upload) - _logger.exception( - f"Failed to abort multipart upload {upload.upload_id} " - f"to s3://{upload.bucket}/{upload.key}." - ) + # The error that made the copy fail is raised, not a failure + # of the abort. + session.abort_or_log() raise finally: executor.shutdown(wait=False) @@ -5643,6 +5629,9 @@ class S3FileTarget: appended: S3Object | None = None append_data: bytes | None = field(default=None, repr=False) if_match_from_lookup: bool = False + # The commit requests of the write session counted when the cache of the + # path was last invalidated after a commit (see commit()). + _invalidated_commit_attempts: int = field(default=0, init=False, repr=False, compare=False) @classmethod def resolve( @@ -5901,6 +5890,114 @@ def read_range(self, fs: S3FileSystem, core: S3Core, range_: tuple[int, int], /) with fs._evicting_stale(path, self.if_match_from_lookup): return core.get_object(path, range_) + def write_session( + self, fs: S3FileSystem, executor: S3Executor, *, block_size: int, max_workers: int + ) -> S3WriteSession: + """Create the session of a write of the object, without sending any request. + + Args: + fs: The filesystem, whose core sends the requests. + executor: The executor of the creation and part requests. + block_size: The block size of the file. + max_workers: The number of part requests of the file in flight. + + Returns: + The session, whose requests inherit ``request_kwargs``, read + when each request is sent; a mapping assigned to the attribute + later is not read. + """ + return S3WriteSession( + fs.core, + S3Path(self.bucket, self.key), + executor, + block_size=block_size, + max_workers=max_workers, + request_kwargs=self.request_kwargs, + ) + + def iter_append_copies( + self, fs: S3FileSystem, session: S3WriteSession + ) -> Iterator[tuple[int, tuple[int, int] | None]]: + """Plan the part copies of the appended object, which lead the multipart upload. + + Args: + fs: The filesystem, whose core limits the parts. + session: The session of the write, which numbers the parts. + + Yields: + The part number and the source range of each copy, with an + exclusive end, or None to copy an object that fits in one part + whole. Nothing if no object is appended. + """ + size = self.appended.get("size", 0) if self.appended is not None else 0 + whole_source = size <= fs.core.MULTIPART_UPLOAD_MAX_PART_SIZE + for part_number, range_ in session.iter_copy_parts(size): + yield part_number, None if whole_source else range_ + + def commit(self, fs: S3FileSystem, session: S3WriteSession, buffer: BytesIO | None) -> None: + """Commit a write of the object whose final flush has prepared its data. + + Sends the buffered data with PutObject if the write started no + multipart upload, and otherwise completes the upload (see + :meth:`S3WriteSession.commit`). A failure that shows a cached entry + to be stale evicts it. Once a commit request has started to be sent + since the last invalidation, the cache of the path is invalidated, + also when the request fails, since a request whose response is lost + may have committed the object, and a rejected conditional write + shows that an object exists. + + Args: + fs: The filesystem, which caches the object. + session: The session of the write. + buffer: The written data that no part has uploaded, or None. + The data of a multipart upload is in its parts. + """ + path = S3Path(self.bucket, self.key) + body = None + if buffer is not None and not session.multipart: + # None without data, which writes an empty object as well. + body = buffer.getvalue() or None + try: + with fs._evicting_stale(path): + session.commit(body) + finally: + if session.commit_attempts != self._invalidated_commit_attempts: + # A commit refused, stopped, or ended by a failed part before + # its request leaves the object as it was. Recorded after the + # invalidation, so that a later commit invalidates again if + # an interrupt stopped it. + fs._invalidate(path) + self._invalidated_commit_attempts = session.commit_attempts + + def abort(self, fs: S3FileSystem, session: S3WriteSession, abort: Callable[[], None]) -> None: + """Abort a write of the object, and invalidate the cached listings that the abort changes. + + A failure of the abort that reaches this method, and that shows a + cached entry to be stale, evicts it. The listings above a multipart + upload of a directory bucket are invalidated unless the write was + already discarded or is committed instead, as the abort then sends + nothing. + + Args: + fs: The filesystem, which caches the object. + session: The session of the write. + abort: The abort of the session to run: + :meth:`S3WriteSession.abort`, or + :meth:`S3WriteSession.abort_or_log`. + """ + path = S3Path(self.bucket, self.key) + discarded = session.state is S3WriteState.ABORTED + try: + with fs._evicting_stale(path): + abort() + finally: + if ( + session.multipart + and not discarded + and session.state not in (S3WriteState.COMMITTING, S3WriteState.COMMITTED) + ): + fs._invalidate_upload_listings(path) + class S3File(AbstractBufferedFile): """A buffered file object for reading and writing an S3 object. @@ -5908,10 +6005,6 @@ class S3File(AbstractBufferedFile): Instances are returned by ``S3FileSystem.open()``. """ - #: The commit requests of the write session counted when the cache of - #: the path was last invalidated after a commit. - _invalidated_commit_attempts = 0 - fs: S3FileSystem buffer: BytesIO | None @@ -6029,23 +6122,16 @@ def __init__( self.version_id: str | None = target.version_id self.s3_additional_kwargs: dict[str, Any] = target.request_kwargs self._details: S3Object | dict[str, Any] = target.details - # The object that is read, which splits and sends the range reads; - # None when writing. - self._target: S3FileTarget | None = target if mode == "rb" else None + # The object that the file reads or writes, which splits and sends + # the range reads, and commits and aborts the write. + self._target = target self._executor: S3Executor = executor or fs._create_executor(max_workers=max_workers) # The requests and the state of the write; None when reading. - self._session: _S3WriteSession | None = None + self._session: S3WriteSession | None = None if mode != "rb": - self._session = _S3WriteSession( - fs.core, - S3Path(target.bucket, target.key), - self._executor, - block_size=block_size, - max_workers=max_workers, - # The mapping itself, which the requests read when they are - # sent, as before; a mapping assigned later is not read. - request_kwargs=self.s3_additional_kwargs, + self._session = target.write_session( + fs, self._executor, block_size=block_size, max_workers=max_workers ) negative_read_block = mode == "rb" and isinstance(block_size, int) and block_size < 0 super().__init__( @@ -6072,15 +6158,13 @@ def __init__( self.blocksize = block_size self.append_block = False - # The size of the appended object, as looked up when opening. - self._append_size = 0 if target.appended is not None: if target.append_data is not None: self.write(target.append_data) else: # Copied with UploadPartCopy as the leading part(s). self.append_block = True - self._append_size = self.loc = target.appended.get("size", 0) + self.loc = target.appended.get("size", 0) @property def _s3_path(self) -> S3Path: @@ -6480,7 +6564,7 @@ def write(self, data: bytes | bytearray | memoryview) -> int: committing it. RuntimeError: In a forked child process of the process that opened the file. - S3MultipartStateError: If the write was committed after + S3WriteStateError: If the write was committed after ``flush(force=True)``. ValueError: If the file is not open for writing, also after :meth:`discard`. @@ -6520,17 +6604,15 @@ def _close_without_commit(self) -> None: if self._wait_for_close_later(): # The abort of discard(); the file is closed above, and its # executor shut down below. - if self._session is not None: - self._abort_write() + if (session := self._session) is not None: + # Logged outside the eviction, which the failure reaches + # first. + with session._logging_abort_failure(): + self._target.abort(self.fs, session, session.abort) else: # The handed-over close, which cannot be waited for here, # discards the write once it ends. self._discard_later = True - except Exception: - upload_id = cast(S3MultipartUpload, self.multipart_upload).upload_id - _logger.exception( - f"Failed to abort multipart upload {upload_id} to s3://{self.bucket}/{self.key}." - ) finally: self._executor.shutdown() @@ -6587,7 +6669,7 @@ def _initiate_upload(self) -> None: if not self.append_block and self.tell() < self.blocksize: return - session = cast(_S3WriteSession, self._session) + session = cast(S3WriteSession, self._session) path = S3Path(self.bucket, self.key) try: with self.fs._evicting_stale(path): @@ -6597,15 +6679,13 @@ def _initiate_upload(self) -> None: session.check() self.fs._invalidate_upload_listings(path) if self.append_block: - # The size of the object looked up when opening, which the - # part copies are conditional on. - size = self._append_size - whole_source = size <= self.fs.core.MULTIPART_UPLOAD_MAX_PART_SIZE - for part_number, range_ in session.iter_copy_parts(size): + # Copies the object looked up when opening, on which the + # part copies are conditional. + for part_number, range_ in self._target.iter_append_copies(self.fs, session): # The part copies count toward max_workers, as the # parts do. session.wait_ready() - session.submit_copy(part_number, path, None if whole_source else range_) + session.submit_copy(part_number, path, range_) except BaseException: # A creation that has started may still create an upload, which # the abort waits for. @@ -6651,7 +6731,7 @@ def _upload_chunk(self, final: bool = False) -> bool: self._commit() return not final - session = cast(_S3WriteSession, self._session) + session = cast(S3WriteSession, self._session) # fsspec's flush() never calls this on a closed file, whose buffer # may have been dropped. buffer = cast(BytesIO, self.buffer) @@ -6703,7 +6783,7 @@ def commit(self) -> None: opened the file, or if a close of the file that was handed over to another thread runs and this is called during a garbage collection or in a thread of an :class:`S3ThreadPool`. - S3MultipartStateError: If the write was discarded, or the write + S3WriteStateError: If the write was discarded, or the write or an earlier commit failed. """ self._check_process() @@ -6734,35 +6814,14 @@ def _commit(self) -> None: The part of :meth:`commit` that the final flush of an ``autocommit`` file also runs. See :meth:`commit`. """ - session = cast(_S3WriteSession, self._session) try: - with self.fs._evicting_stale(S3Path(self.bucket, self.key)): - if not session.multipart: - body = None - if self.buffer is not None and self.tell(): - self.buffer.seek(0) - body = self.buffer.read() - # None writes an empty object. - session.put(body) - else: - session.complete() + self._target.commit(self.fs, cast(S3WriteSession, self._session), self.buffer) except BaseException: # Closed without the buffer, which a failed write cannot commit # again; for a multipart upload, it holds only the data of the # last part. self._close_without_commit() raise - finally: - if session.commit_attempts != self._invalidated_commit_attempts: - # Once a commit request has started to be sent since the - # last invalidation, also after a failure, which may have - # committed the object, and after a 412, which shows that an - # object exists. A commit refused, stopped, or ended by a - # failed part before its request leaves the object as it - # was. Recorded after the invalidation, so that a later - # commit invalidates again if an interrupt stopped it. - self.fs._invalidate(S3Path(self.bucket, self.key)) - self._invalidated_commit_attempts = session.commit_attempts def discard(self) -> None: """Discard the written data, close the file, and abort the multipart upload, if any. @@ -6774,7 +6833,7 @@ def discard(self) -> None: abort, whose own retries are not stopped. If the abort fails or is interrupted, the upload is kept, and calling this again retries the abort. Afterwards, :meth:`commit` raises - :class:`~pyathena.filesystem.s3_writer.S3MultipartStateError`. A + :class:`~pyathena.filesystem.s3_writer.S3WriteStateError`. A committed file is only closed, and a file opened for reading is left unchanged. Waits first for a close of the file that was handed over to another thread (see :meth:`close`). @@ -6792,33 +6851,12 @@ def discard(self) -> None: self.buffer = None self.closed = True try: - self._abort_write() + self._target.abort(self.fs, self._session, self._session.abort) finally: # The abort has waited for the running parts, unless an interrupt # stopped that wait, which this does not repeat. self._executor.shutdown(wait=False) - def _abort_write(self) -> None: - """Abort the write, and invalidate the cached listings that the abort changes. - - The abort of :meth:`discard`, which :meth:`_close_without_commit` - also runs for a file that it has closed itself. - """ - session = cast(_S3WriteSession, self._session) - discarded = session.state is _S3WriteState.ABORTED - try: - with self.fs._evicting_stale(S3Path(self.bucket, self.key)): - session.abort() - finally: - # Unless the write was already discarded, or is committed - # instead, as the abort then sends nothing. - if ( - session.multipart - and not discarded - and session.state not in (_S3WriteState.COMPLETING, _S3WriteState.COMPLETED) - ): - self.fs._invalidate_upload_listings(S3Path(self.bucket, self.key)) - def _lookup_kwargs(self) -> dict[str, Any]: """Select the parameters of the file on which the access to its object depends. @@ -6952,7 +6990,7 @@ def _fetch_range(self, start: int, end: int) -> bytes: concurrent.futures.CancelledError: If an enclosing stop scope has been stopped. """ - target = cast(S3FileTarget, self._target) + target = self._target ranges = target.read_ranges(start, end, self.blocksize, self.max_workers) if not ranges: return b"" @@ -6997,7 +7035,7 @@ def _download(self, outfile: Any, callback: Callback) -> None: been stopped. OSError: If ``outfile`` writes no byte of a body. """ - target = cast(S3FileTarget, self._target) + target = self._target size = cast(int, self.size) # A positive block for the arithmetic of the waves; read_ranges() # reads a non-positive block size in one range as well. diff --git a/pyathena/filesystem/s3_async.py b/pyathena/filesystem/s3_async.py index 2d5dcca50..beaf36267 100644 --- a/pyathena/filesystem/s3_async.py +++ b/pyathena/filesystem/s3_async.py @@ -48,7 +48,7 @@ ) from pyathena.filesystem.s3_path import S3Path from pyathena.filesystem.s3_retry import retries_stopped -from pyathena.filesystem.s3_writer import _S3WriteSession, _S3WriteState +from pyathena.filesystem.s3_writer import S3WriteSession, S3WriteState from pyathena.filesystem.util import create_in_thread, override if TYPE_CHECKING: @@ -2550,8 +2550,6 @@ class AioS3StreamedFile(AbstractAsyncStreamedFile): ``ResourceWarning``. """ - #: See :attr:`S3File._invalidated_commit_attempts`. - _invalidated_commit_attempts = 0 #: Whether a close waits for the final phase in progress, which then #: closes the file before it ends; see :meth:`_close_once`. _close_requested = False @@ -2649,9 +2647,9 @@ def __init__( self.version_id = target.version_id self.s3_additional_kwargs: dict[str, Any] = target.request_kwargs self._details: S3Object | dict[str, Any] = target.details - # The object that is read, which splits and sends the range reads; - # None when writing. - self._target: S3FileTarget | None = target if mode == "rb" else None + # The object that the file reads or writes, which splits and sends + # the range reads, and commits and aborts the write. + self._target = target super().__init__( fs=fs, path=target.path, @@ -2665,18 +2663,11 @@ def __init__( ) self.append_block = False - # The size of the appended object, as looked up when opening. - self._append_size = 0 # The requests and the state of the write; None when reading. - self._session: _S3WriteSession | None = None + self._session: S3WriteSession | None = None if mode != "rb": - self._session = _S3WriteSession( - fs.core, - S3Path(self.bucket, self.key), - self._requests, - block_size=block_size, - max_workers=self.max_workers, - request_kwargs=self.s3_additional_kwargs, + self._session = target.write_session( + fs._sync_fs, self._requests, block_size=block_size, max_workers=self.max_workers ) if target.appended is not None: if target.append_data is not None: @@ -2684,7 +2675,7 @@ def __init__( else: # Copied with UploadPartCopy as the leading part(s). self.append_block = True - self._append_size = self.loc = target.appended.get("size", 0) + self.loc = target.appended.get("size", 0) def __del__(self) -> None: # close() is a coroutine, which garbage collection cannot await, so @@ -2698,7 +2689,7 @@ def __del__(self) -> None: if ( not getattr(self, "closed", True) and session is not None - and session.state not in (_S3WriteState.COMPLETING, _S3WriteState.COMPLETED) + and session.state not in (S3WriteState.COMMITTING, S3WriteState.COMMITTED) # A submitted commit aborts the upload itself if it fails. and not self._commit_submitted() ): @@ -2799,7 +2790,7 @@ async def write(self, data: bytes) -> int: try: # See S3File.write. with self.fs._evicting_stale(S3Path(self.bucket, self.key)): - cast(_S3WriteSession, self._session).check() + cast(S3WriteSession, self._session).check() except BaseException as e: await self._close_without_commit_after(e) raise @@ -3179,7 +3170,7 @@ def _begin_close_without_commit(self) -> bool: Returns: Whether the caller has to discard the write; see - :meth:`_S3WriteSession.begin_abort`. False for a file without a + :meth:`S3WriteSession.begin_abort`. False for a file without a write session, and once the commit has been submitted (see :meth:`_commit_submitted`). """ @@ -3225,14 +3216,14 @@ def _seal(self) -> None: if ( session is not None and not self._commit_submitted() - and session.state in (_S3WriteState.IDLE, _S3WriteState.CREATING, _S3WriteState.ACTIVE) + and session.state in (S3WriteState.IDLE, S3WriteState.CREATING, S3WriteState.ACTIVE) ): session.begin_abort() async def _initiate_upload(self) -> None: if not self.append_block and self.tell() < self.blocksize: return - session = cast(_S3WriteSession, self._session) + session = cast(S3WriteSession, self._session) path = S3Path(self.bucket, self.key) try: # See S3File._initiate_upload. @@ -3243,13 +3234,13 @@ async def _initiate_upload(self) -> None: session.check() self.fs._invalidate_upload_listings(path) if self.append_block: - size = self._append_size - whole_source = size <= self.fs.core.MULTIPART_UPLOAD_MAX_PART_SIZE - for part_number, range_ in session.iter_copy_parts(size): + for part_number, range_ in self._target.iter_append_copies( + self.fs._sync_fs, session + ): # The part copies count toward max_workers, as the # parts do. await self._wait_ready() - session.submit_copy(part_number, path, None if whole_source else range_) + session.submit_copy(part_number, path, range_) except BaseException as e: # A creation that has started may still create an upload, which # the abort waits for. @@ -3280,7 +3271,7 @@ async def _upload_chunk(self, final: bool = False) -> bool: if final: await self._commit() return not final - session = cast(_S3WriteSession, self._session) + session = cast(S3WriteSession, self._session) buffer = cast(BytesIO, self.buffer) buffer.seek(0) try: @@ -3301,9 +3292,9 @@ async def _wait_ready(self) -> None: """Wait until another part may be submitted, without blocking the event loop. A cancellation of the waiting task cancels only its own wait. See - :meth:`_S3WriteSession.ready`. + :meth:`S3WriteSession.ready`. """ - waiter = cast(_S3WriteSession, self._session).ready() + waiter = cast(S3WriteSession, self._session).ready() if not waiter.done(): await asyncio.wrap_future(waiter) @@ -3323,15 +3314,15 @@ async def _commit(self) -> None: queuing of the commit, after which the file is closed without committing it. """ - session = cast(_S3WriteSession, self._session) + session = cast(S3WriteSession, self._session) # Tracked before it is queued, so that close() also waits for a # commit that an interrupt of the queuing has let start. commit: Future[None] = Future() self._commit_future = commit try: - # The failure of a part that begin_complete() raises. + # The failure of a part that reserve_commit() raises. with self.fs._evicting_stale(S3Path(self.bucket, self.key)): - session.begin_complete() + session.reserve_commit() # Passed, as closing the file without committing it drops the buffer. self.fs._thread_pool.submit_to( commit, self._complete_upload, cast(BytesIO, self.buffer) @@ -3341,7 +3332,7 @@ async def _commit(self) -> None: if commit.cancel(): # Not started, and now never: a commit that was queued by a # submission that an interrupt stopped finds itself cancelled. - session.withdraw_complete() + session.withdraw_commit() await self._close_without_commit_after(e) raise await self.fs._thread_pool.wait_shielded(commit) @@ -3364,55 +3355,24 @@ def _complete_upload(self, buffer: BytesIO) -> None: FileExistsError: If an object was created at the path after the file was opened in exclusive-create mode. """ - session = cast(_S3WriteSession, self._session) - path = S3Path(self.bucket, self.key) - # See S3File.commit. + session = cast(S3WriteSession, self._session) try: - with self.fs._evicting_stale(path): - if not session.multipart: - body = None - if self.tell(): - buffer.seek(0) - body = buffer.read() - # None writes an empty object. - session.put(body) - else: - try: - session.complete() - except BaseException: - self._discard() - raise - finally: - if session.commit_attempts != self._invalidated_commit_attempts: - # See S3File._commit. - self.fs._invalidate(path) - self._invalidated_commit_attempts = session.commit_attempts + self._target.commit(self.fs._sync_fs, session, buffer) + except BaseException: + if session.multipart: + self._discard() + raise def _discard(self) -> None: """Discard the write, and abort its multipart upload, if any; blocks. - Runs in a thread. See :meth:`_S3WriteSession.abort`. A failure is - logged instead of raised, so that it does not mask the error that the - caller is handling, also when no task waits for the abort any more. + Runs in a thread. See :meth:`S3WriteSession.abort_or_log`: a failure + is logged instead of raised, so that it does not mask the error that + the caller is handling, also when no task waits for the abort any + more. """ - session = cast(_S3WriteSession, self._session) - discarded = session.state is _S3WriteState.ABORTED - try: - session.abort() - except Exception: - upload_id = cast(S3MultipartUpload, session.upload).upload_id - _logger.exception( - f"Failed to abort multipart upload {upload_id} to s3://{self.bucket}/{self.key}." - ) - finally: - # Unless the write was already discarded, or is committed - # instead, as the abort then sends nothing. - if ( - session.multipart - and not discarded - and session.state not in (_S3WriteState.COMPLETING, _S3WriteState.COMPLETED) - ): - self.fs._invalidate_upload_listings(S3Path(self.bucket, self.key)) + session = cast(S3WriteSession, self._session) + self._target.abort(self.fs._sync_fs, session, session.abort_or_log) async def _fetch_range(self, start: int, end: int) -> bytes: """Read a byte range of the object with parallel range requests. @@ -3441,7 +3401,7 @@ async def _fetch_range(self, start: int, end: int) -> bytes: been stopped. """ self._check_process() - target = cast(S3FileTarget, self._target) + target = self._target ranges = target.read_ranges(start, end, self.blocksize, self.max_workers) if not ranges: return b"" diff --git a/pyathena/filesystem/s3_writer.py b/pyathena/filesystem/s3_writer.py index 1e8bff661..73e4f3091 100644 --- a/pyathena/filesystem/s3_writer.py +++ b/pyathena/filesystem/s3_writer.py @@ -9,7 +9,9 @@ from __future__ import annotations +import contextlib import enum +import logging import threading from collections.abc import Callable, Iterator, Mapping, Sequence from concurrent.futures import CancelledError, Future, wait @@ -29,6 +31,8 @@ T = TypeVar("T") +_logger = logging.getLogger(__name__) + class S3MultipartWriter: """Plan parts and send the requests of a multipart write. @@ -293,7 +297,7 @@ def abort(self, **params: Any) -> None: self.upload = None -class S3MultipartStateError(RuntimeError): +class S3WriteStateError(RuntimeError): """An operation that the state of a write no longer allows. For example, committing a file whose upload was discarded, or whose @@ -301,27 +305,47 @@ class S3MultipartStateError(RuntimeError): """ -class _S3WriteState(enum.Enum): - """The states of a :class:`_S3WriteSession`.""" +#: The former name of :class:`S3WriteStateError`, which refers to the same class. +S3MultipartStateError = S3WriteStateError + + +class S3WriteState(enum.Enum): + """The states of an :class:`S3WriteSession`.""" #: No request has been sent. - IDLE = "has not started a multipart upload" + IDLE = "IDLE" #: The multipart upload is being created. - CREATING = "is creating its multipart upload" + CREATING = "CREATING" #: Parts may be submitted. - ACTIVE = "is uploading parts" - #: The write is being committed. - COMPLETING = "is being committed" + ACTIVE = "ACTIVE" + #: The write is being committed, with PutObject or by completing its + #: multipart upload, or its commit has been reserved + #: (see :meth:`S3WriteSession.reserve_commit`). + COMMITTING = "COMMITTING" #: The write has been committed. - COMPLETED = "has been committed" + COMMITTED = "COMMITTED" #: A request has failed; the write cannot be committed. - FAILED = "has failed" + FAILED = "FAILED" #: The multipart upload is being aborted. - ABORTING = "is being aborted" + ABORTING = "ABORTING" #: The write has been discarded, and its multipart upload, if any, aborted. - ABORTED = "has been discarded" + ABORTED = "ABORTED" #: The abort failed or was interrupted; the upload is kept for a retry. - ABORT_FAILED = "failed to abort its multipart upload" + ABORT_FAILED = "ABORT_FAILED" + + +#: How the messages of :class:`S3WriteStateError` describe each state. +_STATE_DESCRIPTIONS = { + S3WriteState.IDLE: "has not started a multipart upload", + S3WriteState.CREATING: "is creating its multipart upload", + S3WriteState.ACTIVE: "is uploading parts", + S3WriteState.COMMITTING: "is being committed", + S3WriteState.COMMITTED: "has been committed", + S3WriteState.FAILED: "has failed", + S3WriteState.ABORTING: "is being aborted", + S3WriteState.ABORTED: "has been discarded", + S3WriteState.ABORT_FAILED: "failed to abort its multipart upload", +} #: The seconds after which a wait of the session checks the requests again, @@ -330,10 +354,10 @@ class _S3WriteState(enum.Enum): _RECHECK_INTERVAL = 1.0 #: The states in which the caller may still write data. -_WRITABLE_STATES = frozenset({_S3WriteState.IDLE, _S3WriteState.CREATING, _S3WriteState.ACTIVE}) +_WRITABLE_STATES = frozenset({S3WriteState.IDLE, S3WriteState.CREATING, S3WriteState.ACTIVE}) -class _S3WriteSession: +class S3WriteSession: """Own the requests of one write of an object, and its state. A write is committed either with a single PutObject request, or as a @@ -351,8 +375,33 @@ class _S3WriteSession: metadata, and a failure is recorded, and the future is dropped. The first failure is raised once, by the next operation that the caller performs; afterwards, the operations that the failure prohibits raise - :class:`S3MultipartStateError`. A failed write is never committed; the - caller aborts it with :meth:`abort`. + :class:`S3WriteStateError`. A failed write is never committed; the + caller aborts it with :meth:`abort`, or with :meth:`abort_or_log` while + it handles the error that ended the write. + + The write is committed with :meth:`commit`, which sends PutObject if no + multipart upload was started, and otherwise completes the upload. A + driver that cannot block, such as one in an event loop, reserves the + commit with :meth:`reserve_commit` before it queues the call that + commits, and begins an abort with :meth:`begin_abort`; the blocking + :meth:`commit` and :meth:`abort` then run in another thread. + + Example: + A blocking write of the data of a stream:: + + session = S3WriteSession(core, path, executor, block_size=block_size, max_workers=4) + try: + if size >= block_size: + session.start() + for part_number, body in session.iter_parts(stream): + session.wait_ready() + session.submit_part(part_number, body) + session.commit() + else: + session.commit(stream.read()) + except BaseException: + session.abort_or_log() + raise """ def __init__( @@ -380,10 +429,13 @@ def __init__( (see :meth:`S3Core.with_request_kwargs`). The mapping is read when each request is sent, so later changes to it apply to the requests that follow. - prepared_params: The explicit parameters of the requests of some + prepared_params: The parameters of the requests of some operations, by client method name, such as - ``create_multipart_upload``. They are sent as given, so that - botocore rejects one that the operation does not accept. + ``create_multipart_upload``, which are sent as given for that + operation, so that botocore rejects one that the operation + does not accept. They replace ``request_kwargs`` for that + operation, whose requests still receive the + ``request_kwargs`` of the core that the operation accepts. Raises: ValueError: If the destination, the block size, or @@ -405,7 +457,7 @@ def __init__( self._lock = threading.Lock() # Notified whenever a request settles or the state changes. self._changed = threading.Condition(self._lock) - self._state = _S3WriteState.IDLE + self._state = S3WriteState.IDLE self._multipart = False self._creation: Future[S3MultipartUpload] | None = None # The part requests that have not settled, which may not have been @@ -413,9 +465,8 @@ def __init__( self._requests: set[Future[S3MultipartUploadPart]] = set() self._next_part_number = 1 self._parts: dict[int, S3MultipartUploadPart] = {} - # The waiters of ready() and settled(), each with the number of part - # requests in flight below which it resolves. - self._waiters: list[tuple[Future[None], int]] = [] + # The waiters of ready(). + self._waiters: list[Future[None]] = [] # Set by abort(), so that the creation and the running part requests # make no further attempt before the upload is aborted. self._stop = threading.Event() @@ -424,10 +475,10 @@ def __init__( # A description of the first failure, kept after it is raised. self._failure_summary: str | None = None self._result: S3PutObject | S3CompleteMultipartUpload | None = None - # The state that begin_complete() reserved the commit from, IDLE for - # PutObject or ACTIVE for the completion, until put() or complete() - # takes the reservation. - self._reservation: _S3WriteState | None = None + # The state that reserve_commit() reserved the commit from, IDLE for + # PutObject or ACTIVE for the completion, until commit() takes the + # reservation. + self._reservation: S3WriteState | None = None # Set by begin_abort() until abort() takes over the abort that it began. self._abort_pending = False # The commit requests that have started to be sent. @@ -437,7 +488,7 @@ def __init__( self._abort_owner: threading.Thread | None = None @property - def state(self) -> _S3WriteState: + def state(self) -> S3WriteState: """The current state.""" return self._state @@ -455,14 +506,16 @@ def upload(self) -> S3MultipartUpload | None: def commit_attempts(self) -> int: """The number of the commit requests that have started to be sent. - A request is the PutObject of :meth:`put` or the - CompleteMultipartUpload of :meth:`complete`, counted right before the - call that sends it, whatever its outcome: a failed or interrupted - request may still have committed the write, and one that botocore - rejects before sending it is counted too. A commit that is refused, - stopped, or ended by a failed part before its request is not - counted, nor one that returns the result of an earlier successful - commit. + A request is the PutObject or the CompleteMultipartUpload of + :meth:`commit`, counted once right before the call that sends it, + whatever its outcome and however many times it is retried: a failed + or interrupted request may still have committed the write, and one + that botocore rejects before sending it is counted too. A commit that + is refused, stopped, or ended by a failed part before its request is + not counted, nor one that returns the result of an earlier successful + commit. A driver that caches what it writes compares the count before + and after a commit, also a failed one, to tell whether the object may + have changed. """ return self._commit_attempts @@ -506,7 +559,7 @@ def start(self) -> None: for it. Raises: - S3MultipartStateError: If a request has already been sent. + S3WriteStateError: If a request has already been sent. concurrent.futures.CancelledError: If an enclosing stop scope has been stopped (see :func:`~pyathena.filesystem.s3_retry.raise_if_stopped`). """ @@ -514,8 +567,8 @@ def start(self) -> None: creation: Future[S3MultipartUpload] = Future() creation.add_done_callback(self._on_created) with self._lock: - self._refuse_unless(_S3WriteState.IDLE, operation="start a multipart upload") - self._state = _S3WriteState.CREATING + self._refuse_unless(S3WriteState.IDLE, operation="start a multipart upload") + self._state = S3WriteState.CREATING self._multipart = True self._creation = creation try: @@ -545,20 +598,18 @@ def ready(self) -> Future[None]: Returns: A future whose result is None. """ - return self._waiter(self._max_workers) - - def settled(self) -> Future[None]: - """Return a future that resolves when no part request is in flight. - - It resolves once the upload is created and its part requests have - settled, or, as for :meth:`ready`, when the write can no longer submit - parts, such as after a failure, which the next operation raises. Each - call returns a new future, which the caller may cancel. - - Returns: - A future whose result is None. - """ - return self._waiter(1) + waiter: Future[None] = Future() + with self._lock: + self._consume_finished() + self._drop_cancelled_waiters() + ready = self._is_ready() + if not ready: + self._waiters.append(waiter) + waiters = self._publish() + self._notify(waiters) + if ready: + waiter.set_result(None) + return waiter def wait_ready(self) -> None: """Block until another part may be submitted; see :meth:`ready`. @@ -588,7 +639,7 @@ def check(self) -> None: Raises: BaseException: The first failure of a request, if it has not been raised yet. - S3MultipartStateError: If the write failed earlier, or has been + S3WriteStateError: If the write failed earlier, or has been committed or discarded. """ if self._failure_summary is None and self._state in _WRITABLE_STATES: @@ -608,7 +659,7 @@ def submit_part(self, part_number: int, body: bytes) -> None: Raises: BaseException: The first failure of a request, if it has not been raised yet. - S3MultipartStateError: If the upload is not active. + S3WriteStateError: If the upload is not active. RuntimeError: If ``max_workers`` part requests are in flight; :meth:`ready` waits for one of them. ValueError: If the part number is not the next one. @@ -632,7 +683,7 @@ def submit_copy(self, part_number: int, source: S3Path, range_: tuple[int, int] Raises: BaseException: The first failure of a request, if it has not been raised yet. - S3MultipartStateError: If the upload is not active. + S3WriteStateError: If the upload is not active. RuntimeError: If ``max_workers`` part requests are in flight; :meth:`ready` waits for one of them. ValueError: If the part number is not the next one. @@ -645,91 +696,90 @@ def submit_copy(self, part_number: int, source: S3Path, range_: tuple[int, int] **self._params("upload_part_copy"), ) - def put(self, body: bytes | None) -> S3PutObject: - """Commit the write with a single PutObject request. + def commit(self, body: bytes | None = None) -> S3PutObject | S3CompleteMultipartUpload: + """Commit the write. - Committing again after a successful request returns its result - without another request. + A write that started no multipart upload is committed with a single + PutObject request of ``body``; None or empty bytes write an empty + object. A write that started one is committed by completing it, once + its part requests have settled: the first failure among them is + raised without waiting for the others. A failed or interrupted + commit leaves the write failed, and the caller aborts it. Committing + again after a successful commit returns its result without another + request. Args: - body: The data of the object, or None for an empty object. - - Returns: - The result of the request. - - Raises: - S3MultipartStateError: If the write started a multipart upload, - failed, or has been discarded. - concurrent.futures.CancelledError: If an enclosing stop scope has - been stopped before the request (see - :func:`~pyathena.filesystem.s3_retry.raise_if_stopped`); the write fails then. - """ - return self._commit(_S3WriteState.IDLE, lambda: self._put_object(body)) - - def complete(self) -> S3CompleteMultipartUpload: - """Commit the write by completing its multipart upload. - - Waits for the part requests, and raises the first failure among them - without waiting for the others. A failed or interrupted completion - leaves the session failed, and the caller aborts the upload. - Completing again after a successful completion returns its result - without another request. + body: The data of the object, for a write that started no + multipart upload. A write that started one has uploaded its + data as parts. Returns: - The result of the completion. + The result of the PutObject request + (:class:`~pyathena.filesystem.s3_object.S3PutObject`), or of the + completion + (:class:`~pyathena.filesystem.s3_object.S3CompleteMultipartUpload`). Raises: BaseException: The first failure of a request, if it has not been - raised yet, or the failure of the completion. - S3MultipartStateError: If no upload is active, or the write failed - earlier or has been discarded. + raised yet, or the failure of the commit request. + S3WriteStateError: If the write is being created or aborted, or + failed earlier, or has been discarded. + ValueError: If ``body`` is not empty for a write that started a + multipart upload. concurrent.futures.CancelledError: If an enclosing stop scope has been stopped before the request (see :func:`~pyathena.filesystem.s3_retry.raise_if_stopped`); the write fails then. """ - return self._commit(_S3WriteState.ACTIVE, self._complete_parts) + if not self._multipart: + return self._commit(S3WriteState.IDLE, lambda: self._put_object(body)) + if body: + raise ValueError( + f"Cannot commit a body to {self._path.uri}: the write uploads its data as " + "parts of a multipart upload." + ) + return self._commit(S3WriteState.ACTIVE, self._complete_parts) - def begin_complete(self) -> None: + def reserve_commit(self) -> None: """Reserve the commit before the call that sends it is queued. Does not block. Afterwards, :meth:`abort` leaves the write to the - commit, and the next :meth:`put` or :meth:`complete`, whichever the - write allows, sends it, unless :meth:`withdraw_complete` withdraws the - reservation first. Does nothing for a committed write. + commit, and the next :meth:`commit` sends it, unless + :meth:`withdraw_commit` withdraws the reservation first, before the + call that commits is dispatched. Does nothing for a committed write. Raises: BaseException: The first failure of a request, if it has not been raised yet. - S3MultipartStateError: If the write failed earlier, or has been + S3WriteStateError: If the write failed earlier, or has been discarded. """ with self._lock: - if self._state is _S3WriteState.COMPLETED: + if self._state is S3WriteState.COMMITTED: return - state = _S3WriteState.ACTIVE if self._multipart else _S3WriteState.IDLE + state = S3WriteState.ACTIVE if self._multipart else S3WriteState.IDLE self._refuse_unless(state, operation="commit") # Set first, so that a COMPLETING state that this sets always has # its reservation for the commit to take. self._reservation = state - self._state = _S3WriteState.COMPLETING + self._state = S3WriteState.COMMITTING - def withdraw_complete(self) -> None: - """Withdraw the commit reserved by :meth:`begin_complete`, unless it has been taken. + def withdraw_commit(self) -> None: + """Withdraw the commit reserved by :meth:`reserve_commit`, unless it has been taken. Does not block. For a caller whose call that sends the commit does not run, such as one that an interrupt kept from being queued, or one - cancelled before it started. The write then fails: :meth:`put` and - :meth:`complete` refuse it, and :meth:`abort` discards it. Does - nothing if no commit is reserved, or once :meth:`put` or - :meth:`complete` has taken the reservation, whose commit runs on. + cancelled before it started. The write then fails: :meth:`commit` + refuses it, and :meth:`abort` discards it. Does nothing if no commit + is reserved, or once :meth:`commit` has taken the reservation, whose + commit runs on. """ with self._lock: - if self._state is _S3WriteState.COMPLETING and self._reservation is not None: + if self._state is S3WriteState.COMMITTING and self._reservation is not None: # Failed first, so that an interrupt in between never leaves # a COMPLETING state without its reservation, which abort() # leaves to a commit that nothing sends. self._fail( - S3MultipartStateError( + S3WriteStateError( f"The commit of the write to {self._path.uri} was withdrawn." ), raised=True, @@ -754,20 +804,20 @@ def begin_abort(self) -> bool: committed, has been discarded, or never sent a request. """ with self._lock: - if self._state is _S3WriteState.IDLE: - self._state = _S3WriteState.ABORTED + if self._state is S3WriteState.IDLE: + self._state = S3WriteState.ABORTED if self._state in ( - _S3WriteState.COMPLETING, - _S3WriteState.COMPLETED, - _S3WriteState.ABORTED, + S3WriteState.COMMITTING, + S3WriteState.COMMITTED, + S3WriteState.ABORTED, ): return False - if self._state is _S3WriteState.ABORTING: + if self._state is S3WriteState.ABORTING: return True # Set first, so that an ABORTING state that this sets is always # left for abort() to take over, even after an interrupt. self._abort_pending = True - self._state = _S3WriteState.ABORTING + self._state = S3WriteState.ABORTING waiters = self._take_waiters() self._notify(waiters) self._stop_requests() @@ -806,7 +856,7 @@ def abort(self) -> None: interrupt: KeyboardInterrupt | None = None try: with self._lock: - while self._state is _S3WriteState.ABORTING and not self._abort_pending: + while self._state is S3WriteState.ABORTING and not self._abort_pending: owner = self._abort_owner if owner is None or owner is threading.current_thread() or not owner.is_alive(): # Not inside the call, which has ended. @@ -815,13 +865,13 @@ def abort(self) -> None: return self._changed.wait(_RECHECK_INTERVAL) if self._state in ( - _S3WriteState.COMPLETING, - _S3WriteState.COMPLETED, - _S3WriteState.ABORTED, + S3WriteState.COMMITTING, + S3WriteState.COMMITTED, + S3WriteState.ABORTED, ): return - if self._state is _S3WriteState.IDLE: - self._state = _S3WriteState.ABORTED + if self._state is S3WriteState.IDLE: + self._state = S3WriteState.ABORTED return # Set first, so that an interrupt anywhere after the state # changes leaves the write ABORT_FAILED, not ABORTING, which @@ -829,7 +879,7 @@ def abort(self) -> None: owned = True self._abort_pending = False self._abort_owner = threading.current_thread() - self._state = _S3WriteState.ABORTING + self._state = S3WriteState.ABORTING waiters = self._take_waiters() self._notify(waiters) # Again after begin_abort(), which an interrupt may have stopped. @@ -842,7 +892,7 @@ def abort(self) -> None: self._consume_finished() try: if self._upload is not None: - self._request_core().abort_multipart_upload( + self._request_core("abort_multipart_upload").abort_multipart_upload( self._upload, **self._params("abort_multipart_upload") ) except FileNotFoundError as e: @@ -851,16 +901,61 @@ def abort(self) -> None: # Cleared after a successful abort, or after S3 reported that the # upload no longer exists; a failed abort retains it to retry. self._upload = None - self._end_abort(_S3WriteState.ABORTED) + self._end_abort(S3WriteState.ABORTED) except BaseException: if owned: - self._end_abort(_S3WriteState.ABORT_FAILED) + self._end_abort(S3WriteState.ABORT_FAILED) # A failed abort raises its failure, which stops the caller as - # the interrupt would, and which the callers log with the upload. + # the interrupt would; abort_or_log() logs it with the upload. raise if interrupt is not None: raise interrupt + def abort_or_log(self) -> None: + """Abort the write as :meth:`abort` does, logging a failure instead of raising it. + + For a caller that handles the error that ended the write, which it + raises itself: a failed abort does not replace that error. The + failure is logged with the ID of the upload, which is kept so that a + later :meth:`abort` can retry. An interrupt, such as + ``KeyboardInterrupt``, is logged with the ID and raised. + + Raises: + KeyboardInterrupt: An interrupt of the abort. + """ + with self._logging_abort_failure(): + self.abort() + + @contextlib.contextmanager + def _logging_abort_failure(self) -> Iterator[None]: + """Log a failure of the abort in the block instead of raising it; see :meth:`abort_or_log`. + + Also for a caller whose abort runs inside another context manager + that the failure has to reach first. + + Yields: + None. + + Raises: + KeyboardInterrupt: An interrupt of the block. + """ + try: + yield + except KeyboardInterrupt: + if (upload := self._upload) is not None: + _logger.warning( + f"Interrupted the abort of multipart upload {upload.upload_id} " + f"to {self._path.uri}." + ) + raise + except Exception: + if (upload := self._upload) is not None: + _logger.exception( + f"Failed to abort multipart upload {upload.upload_id} to {self._path.uri}." + ) + else: + _logger.exception(f"Failed to abort the write to {self._path.uri}.") + def _params(self, method: str) -> dict[str, Any]: """Return the explicit parameters of a request of an S3 operation. @@ -872,15 +967,21 @@ def _params(self, method: str) -> dict[str, Any]: """ return dict(self._prepared_params.get(method) or {}) - def _request_core(self) -> S3Core: + def _request_core(self, method: str) -> S3Core: """Return the core that sends a request with the inherited parameters as they are now. + Args: + method: The name of the client method of the request, such as + ``upload_part``. + Returns: The core, with the inherited parameters added to its - ``request_kwargs``, so that they yield to the fields of the - request, or the core itself if there are none. + ``request_kwargs``, so that the core filters them by the + operation and they yield to the fields of the request; the core + itself if there are none, or if the operation has prepared + parameters, which replace them. """ - if not self._request_kwargs: + if not self._request_kwargs or method in self._prepared_params: return self._core return self._core.with_request_kwargs({**self._core.request_kwargs, **self._request_kwargs}) @@ -902,7 +1003,9 @@ def _initiate(self, params: Mapping[str, Any]) -> S3MultipartUpload: been stopped. """ raise_if_stopped(f"create a multipart upload to {self._path.uri}") - self._upload = self._request_core().create_multipart_upload(self._path, **params) + self._upload = self._request_core("create_multipart_upload").create_multipart_upload( + self._path, **params + ) return self._upload def _submit(self, method: str, **kwargs: Any) -> None: @@ -926,7 +1029,7 @@ def _submit(self, method: str, **kwargs: Any) -> None: request.add_done_callback(self._on_part_done) with self._lock: self._consume_finished() - self._refuse_unless(_S3WriteState.ACTIVE, operation="upload a part") + self._refuse_unless(S3WriteState.ACTIVE, operation="upload a part") if len(self._requests) >= self._max_workers: raise RuntimeError( f"{self._max_workers} part requests are in flight; wait for ready() first." @@ -976,11 +1079,11 @@ def _send_part(self, method: str, **kwargs: Any) -> S3MultipartUploadPart: raise_if_stopped(f"upload part {kwargs['part_number']} to {self._path.uri}") self._writer._check_part_number(kwargs["part_number"]) # The upload is read when the request runs, after the creation set it. - send = getattr(self._request_core(), method) + send = getattr(self._request_core(method), method) return cast(S3MultipartUploadPart, send(upload=self._upload, **kwargs)) def _put_object(self, body: bytes | None) -> S3PutObject: - """Send the PutObject request of :meth:`put` unless the write has been stopped. + """Send the PutObject request of :meth:`commit` unless the write has been stopped. Args: body: The data of the object, or None for an empty object. @@ -994,9 +1097,11 @@ def _put_object(self, body: bytes | None) -> S3PutObject: """ raise_if_stopped(f"put {self._path.uri}") self._commit_attempts += 1 - return self._request_core().put_object(self._path, body, **self._params("put_object")) + return self._request_core("put_object").put_object( + self._path, body, **self._params("put_object") + ) - def _commit(self, state: _S3WriteState, send: Callable[[], T]) -> T: + def _commit(self, state: S3WriteState, send: Callable[[], T]) -> T: """Reserve the commit, send its request, and record the outcome. Args: @@ -1010,12 +1115,10 @@ def _commit(self, state: _S3WriteState, send: Callable[[], T]) -> T: reserved = False try: with self._lock: - if self._state is _S3WriteState.COMPLETED and self._multipart is ( - state is _S3WriteState.ACTIVE - ): + if self._state is S3WriteState.COMMITTED: return cast(T, self._result) - if self._state is _S3WriteState.COMPLETING and self._reservation is state: - # Reserved by begin_complete(). + if self._state is S3WriteState.COMMITTING and self._reservation is state: + # Reserved by reserve_commit(). reserved = True self._reservation = None else: @@ -1024,16 +1127,16 @@ def _commit(self, state: _S3WriteState, send: Callable[[], T]) -> T: # changes leaves the write failed, for the caller to # abort, rather than being committed. reserved = True - self._state = _S3WriteState.COMPLETING + self._state = S3WriteState.COMMITTING result = send() with self._lock: # The result first, as the state publishes it. self._result = cast(S3PutObject | S3CompleteMultipartUpload, result) - self._state = _S3WriteState.COMPLETED + self._state = S3WriteState.COMMITTED waiters = self._publish() self._notify(waiters) except BaseException as e: - if reserved and self._state is not _S3WriteState.COMPLETED: + if reserved and self._state is not S3WriteState.COMMITTED: with self._lock: self._fail(e, raised=True) waiters = self._publish() @@ -1065,7 +1168,7 @@ def _complete_parts(self) -> S3CompleteMultipartUpload: raise_if_stopped(f"complete the multipart upload to {self._path.uri}") self._changed.wait(_RECHECK_INTERVAL) self._consume_finished() - self._refuse_unless(_S3WriteState.COMPLETING, operation="commit") + self._refuse_unless(S3WriteState.COMMITTING, operation="commit") parts = [self._parts[number] for number in sorted(self._parts)] if len(parts) != self._next_part_number - 1: # Every finished request has been consumed, so this guards the @@ -1078,7 +1181,7 @@ def _complete_parts(self) -> S3CompleteMultipartUpload: raise_if_stopped(f"complete the multipart upload to {self._path.uri}") self._commit_attempts += 1 with unstoppable_retries(): - return self._request_core().complete_multipart_upload( + return self._request_core("complete_multipart_upload").complete_multipart_upload( cast(S3MultipartUpload, self._upload), parts, **self._params("complete_multipart_upload"), @@ -1126,7 +1229,7 @@ def _consume_creation(self, creation: Future[S3MultipartUpload]) -> None: """ if self._creation is not creation: return - if self._state is _S3WriteState.CREATING: + if self._state is S3WriteState.CREATING: if creation.cancelled(): # Such as by an executor passed to the file that cancels its # queued calls as it shuts down. @@ -1134,7 +1237,7 @@ def _consume_creation(self, creation: Future[S3MultipartUpload]) -> None: elif (error := creation.exception()) is not None: self._fail(error) else: - self._state = _S3WriteState.ACTIVE + self._state = S3WriteState.ACTIVE # Cleared after the outcome is recorded, so that a callback stopped # in between leaves the creation for the next consumption. self._creation = None @@ -1163,7 +1266,7 @@ def _consume(self, request: Future[S3MultipartUploadPart]) -> None: if error is None: part = request.result() self._parts[part.part_number] = part - elif self._state not in (_S3WriteState.ABORTING, _S3WriteState.ABORT_FAILED): + elif self._state not in (S3WriteState.ABORTING, S3WriteState.ABORT_FAILED): self._fail(error) self._requests.discard(request) @@ -1185,8 +1288,8 @@ def _fail(self, error: BaseException, *, raised: bool = False) -> None: if not raised: self._failure = error self._failure_summary = f"{type(error).__name__}: {error}" - if self._state in _WRITABLE_STATES or (raised and self._state is _S3WriteState.COMPLETING): - self._state = _S3WriteState.FAILED + if self._state in _WRITABLE_STATES or (raised and self._state is S3WriteState.COMMITTING): + self._state = S3WriteState.FAILED def _publish(self) -> list[Future[None]]: """Notify the waits of a change; called with the lock held. @@ -1204,7 +1307,7 @@ def _publish(self) -> list[Future[None]]: self._changed.notify_all() return self._take_waiters() - def _refuse_unless(self, *states: _S3WriteState, operation: str) -> None: + def _refuse_unless(self, *states: S3WriteState, operation: str) -> None: """Raise unless the write is in one of the states without a failure. Called with the lock held. The first failure is raised only once, and @@ -1217,17 +1320,20 @@ def _refuse_unless(self, *states: _S3WriteState, operation: str) -> None: Raises: BaseException: The first failure, if it has not been raised yet. - S3MultipartStateError: Otherwise, if the write is not in one of + S3WriteStateError: Otherwise, if the write is not in one of the states or has failed. """ if self._state in states and self._failure_summary is None: return error, self._failure = self._failure, None if error is None: - message = f"Cannot {operation}: the write to {self._path.uri} {self._state.value}." + message = ( + f"Cannot {operation}: the write to {self._path.uri} " + f"{_STATE_DESCRIPTIONS[self._state]}." + ) if self._failure_summary is not None: message += f" The first failure: {self._failure_summary}" - error = S3MultipartStateError(message) + error = S3WriteStateError(message) try: raise error finally: @@ -1259,7 +1365,7 @@ def _settle_creation(self) -> KeyboardInterrupt | None: if interrupt is None: interrupt = e - def _end_abort(self, state: _S3WriteState) -> None: + def _end_abort(self, state: S3WriteState) -> None: """Record the outcome of the abort that this call owns, and notify the waits. Args: @@ -1269,7 +1375,7 @@ def _end_abort(self, state: _S3WriteState) -> None: with self._lock: self._state = state self._abort_owner = None - if state is _S3WriteState.ABORTED: + if state is S3WriteState.ABORTED: # A discarded write reports its state, not a failure that it # was discarded after. self._failure = None @@ -1294,45 +1400,16 @@ def _stop_requests(self) -> None: request.cancel() self._stop.set() - def _waiter(self, limit: int) -> Future[None]: - """Return a future that resolves when fewer than ``limit`` part requests are in flight. - - See :meth:`ready`. - - Args: - limit: The number of part requests in flight below which the - future resolves. - - Returns: - A future whose result is None. - """ - waiter: Future[None] = Future() - with self._lock: - self._consume_finished() - self._drop_cancelled_waiters() - ready = self._is_ready(limit) - if not ready: - self._waiters.append((waiter, limit)) - waiters = self._publish() - self._notify(waiters) - if ready: - waiter.set_result(None) - return waiter - - def _is_ready(self, limit: int) -> bool: - """Whether a waiter resolves; called with the lock held. - - Args: - limit: The number of part requests in flight below which the - waiter resolves while the upload is active. + def _is_ready(self) -> bool: + """Whether a waiter of :meth:`ready` resolves; called with the lock held. Returns: Whether the waiter resolves. """ - if self._state is _S3WriteState.CREATING: + if self._state is S3WriteState.CREATING: return False - if self._state is _S3WriteState.ACTIVE and self._failure_summary is None: - return len(self._requests) < limit + if self._state is S3WriteState.ACTIVE and self._failure_summary is None: + return len(self._requests) < self._max_workers return True def _take_waiters(self) -> list[Future[None]]: @@ -1342,14 +1419,9 @@ def _take_waiters(self) -> list[Future[None]]: The waiters that resolve in the current state. """ # Taken, so that each waiter is resolved by one thread only. - taken: list[Future[None]] = [] - waiting: list[tuple[Future[None], int]] = [] - for waiter, limit in self._waiters: - if self._is_ready(limit): - taken.append(waiter) - else: - waiting.append((waiter, limit)) - self._waiters = waiting + if not self._waiters or not self._is_ready(): + return [] + taken, self._waiters = self._waiters, [] return taken def _drop_cancelled_waiters(self) -> None: @@ -1359,11 +1431,11 @@ def _drop_cancelled_waiters(self) -> None: future, so that ``concurrent.futures.wait()`` counts them as done. """ waiting = [] - for waiter, limit in self._waiters: + for waiter in self._waiters: if waiter.cancelled(): waiter.set_running_or_notify_cancel() else: - waiting.append((waiter, limit)) + waiting.append(waiter) self._waiters = waiting @staticmethod diff --git a/tests/pyathena/filesystem/test_s3.py b/tests/pyathena/filesystem/test_s3.py index 5d10543d6..6f6a34378 100644 --- a/tests/pyathena/filesystem/test_s3.py +++ b/tests/pyathena/filesystem/test_s3.py @@ -64,7 +64,7 @@ from pyathena.filesystem.s3_object import S3MultipartUpload, S3Object, S3ObjectType, S3StorageClass from pyathena.filesystem.s3_path import S3Path from pyathena.filesystem.s3_retry import raise_if_stopped -from pyathena.filesystem.s3_writer import S3MultipartStateError, _S3WriteSession, _S3WriteState +from pyathena.filesystem.s3_writer import S3WriteSession, S3WriteState, S3WriteStateError from pyathena.fs import s3_filesystem from pyathena.util import RetryConfig, stop_retries_on from tests import ENV @@ -1106,7 +1106,7 @@ def _discard_file(fs, path): finally: with mock.patch.object(fs.core, "call", return_value={}): f.discard() - with contextlib.suppress(S3MultipartStateError): + with contextlib.suppress(S3WriteStateError): f.close() @staticmethod @@ -1184,8 +1184,8 @@ def test_failed_write_invalidates_cache(self, write, requests_kwargs): ("part_failed", PermissionError), ("stopped", CancelledError), ("stopped_multipart", CancelledError), - ("refused", S3MultipartStateError), - ("refused_retry", S3MultipartStateError), + ("refused", S3WriteStateError), + ("refused_retry", S3WriteStateError), ], ) def test_unsent_commit_keeps_cache(self, case, error): @@ -4515,7 +4515,7 @@ def test_failed_commit_inside_with(self): # as an exclusive write whose object was created since the file was # opened, raises its error and closes the file, whose exit returns # quietly. The exit used to commit again and raise - # S3MultipartStateError over the error of the commit. + # S3WriteStateError over the error of the commit. fs, objects, _ = self._make_storing_fs() def write(): @@ -6465,7 +6465,7 @@ def upload_part_copy(part_number, **kwargs): fs.core.upload_part_copy = upload_part_copy try: with ( - mock.patch.object(_S3WriteSession, "abort", side_effect=KeyboardInterrupt), + mock.patch.object(S3WriteSession, "abort", side_effect=KeyboardInterrupt), pytest.raises(KeyboardInterrupt), ): call_bounded( @@ -6993,7 +6993,7 @@ def test_pipe_file_failed_write(self, intrans): with ( mock.patch.object(S3File, "write", side_effect=RuntimeError("write failed")), - pytest.raises(S3MultipartStateError) if intrans else contextlib.nullcontext(), + pytest.raises(S3WriteStateError) if intrans else contextlib.nullcontext(), fs.transaction if intrans else contextlib.nullcontext(), pytest.raises(RuntimeError, match="write failed"), ): @@ -7102,7 +7102,7 @@ def test_pipe_file_compression_failed_write(self, intrans): with ( mock.patch.object(S3File, "write", side_effect=RuntimeError("write failed")), - pytest.raises(S3MultipartStateError) if intrans else contextlib.nullcontext(), + pytest.raises(S3WriteStateError) if intrans else contextlib.nullcontext(), fs.transaction if intrans else contextlib.nullcontext(), pytest.raises(RuntimeError, match="write failed"), ): @@ -7158,7 +7158,7 @@ def test_put_file_failed_write(self, tmp_path, intrans, error): callback.relative_update = mock.MagicMock(side_effect=error("callback failed")) with ( - pytest.raises(S3MultipartStateError) + pytest.raises(S3WriteStateError) if intrans and error is not PermissionError else contextlib.nullcontext(), fs.transaction if intrans else contextlib.nullcontext(), @@ -7191,7 +7191,7 @@ def test_put_file_failed_write_aborts_multipart_upload(self, tmp_path, intrans): lpath.write_bytes(b"a" * (2 * S3FileSystem.DEFAULT_BLOCK_SIZE + 1)) with ( - pytest.raises(S3MultipartStateError) if intrans else contextlib.nullcontext(), + pytest.raises(S3WriteStateError) if intrans else contextlib.nullcontext(), fs.transaction if intrans else contextlib.nullcontext(), pytest.raises(RuntimeError, match="callback failed"), ): @@ -9724,7 +9724,7 @@ def create_multipart_upload(*args, **kw): # The HeadObject of the source. fs.core.call.return_value = {"ContentLength": 2 * S3Core.MULTIPART_UPLOAD_MAX_PART_SIZE} fs.core.abort_multipart_upload = mock.MagicMock() - ready = _S3WriteSession.ready + ready = S3WriteSession.ready def wait_for_ready(session): # The interrupt is sent once the copy waits for the creation. @@ -9733,7 +9733,7 @@ def wait_for_ready(session): return waiter with ( - mock.patch.object(_S3WriteSession, "ready", wait_for_ready), + mock.patch.object(S3WriteSession, "ready", wait_for_ready), # Sent only while the creation is running and the copy waits for # it, which the creation cannot stop doing before the interrupt. sigint_when(lambda: started.is_set() and waiting.is_set()) as signals, @@ -9812,7 +9812,7 @@ def upload_part_copy(**kwargs): logged_while_running.append(logged.wait(EVENT_TIMEOUT)) return SimpleNamespace(etag='"e"', part_number=kwargs["part_number"]) - init = _S3WriteSession.__init__ + init = S3WriteSession.__init__ def init_with_interrupt(session, *args, **kwargs): init(session, *args, **kwargs) @@ -9820,7 +9820,7 @@ def init_with_interrupt(session, *args, **kwargs): class InterruptedCondition(threading.Condition): def wait(self, timeout=None): # The first wait of the abort, for the running part copy. - if session.state is _S3WriteState.ABORTING and not interrupts: + if session.state is S3WriteState.ABORTING and not interrupts: interrupts.append(part_2_started.is_set() and not logged.is_set()) raise KeyboardInterrupt return super().wait(timeout) @@ -9840,7 +9840,7 @@ def wait(self, timeout=None): try: with ( caplog.at_level(logging.WARNING, logger="pyathena.filesystem.s3"), - mock.patch.object(_S3WriteSession, "__init__", init_with_interrupt), + mock.patch.object(S3WriteSession, "__init__", init_with_interrupt), pytest.raises(KeyboardInterrupt), ): call_bounded( @@ -10922,7 +10922,7 @@ def write_then_fail(): # The multipart upload, if any, was aborted, and GH-1211: the # discarded write cannot be committed afterwards. assert not fs.list_multipart_uploads(path) - with pytest.raises(S3MultipartStateError, match="has been discarded"): + with pytest.raises(S3WriteStateError, match="has been discarded"): files[0].commit() assert not fs.exists(path) @@ -12315,7 +12315,7 @@ def create(*args, **kwargs): fs.core.create_multipart_upload.side_effect = create executor = S3ThreadPool(max_workers=1) - ready = _S3WriteSession.ready + ready = S3WriteSession.ready def interrupt_ready(session): # The wait of the write for the creation is interrupted. @@ -12344,7 +12344,7 @@ def interrupt_recovery(futures): try: with ( - mock.patch.object(_S3WriteSession, "ready", interrupt_ready), + mock.patch.object(S3WriteSession, "ready", interrupt_ready), mock.patch("pyathena.filesystem.s3_writer.wait", side_effect=interrupt_recovery), pytest.raises(KeyboardInterrupt) as info, ): @@ -12366,7 +12366,7 @@ def interrupt_recovery(futures): ) file.close() # GH-1211: the discarded write is not committed. - with pytest.raises(S3MultipartStateError): + with pytest.raises(S3WriteStateError): file.commit() fs.core.call.assert_called_once() fs.core.upload_part.assert_not_called() @@ -12379,7 +12379,7 @@ def test_creation_cancelled_before_start(self): executor = mock.MagicMock() file = S3File(fs, "s3://bucket/key.txt", mode="wb", block_size=4, executor=executor) - ready = _S3WriteSession.ready + ready = S3WriteSession.ready def interrupt_ready(session): # The creation is never started, and the wait for it is interrupted. @@ -12388,7 +12388,7 @@ def interrupt_ready(session): return waiter with ( - mock.patch.object(_S3WriteSession, "ready", interrupt_ready), + mock.patch.object(S3WriteSession, "ready", interrupt_ready), pytest.raises(KeyboardInterrupt), ): file.write(b"x" * 8) @@ -12401,7 +12401,7 @@ def interrupt_ready(session): executor.shutdown.assert_called_once() fs.core.create_multipart_upload.assert_not_called() fs.core.call.assert_not_called() - with pytest.raises(S3MultipartStateError): + with pytest.raises(S3WriteStateError): file.commit() fs.core.put_object.assert_not_called() @@ -12484,7 +12484,7 @@ def wait_for_creation(futures): assert file.closed assert file.buffer is None assert file.multipart_upload is None - with pytest.raises(S3MultipartStateError): + with pytest.raises(S3WriteStateError): file.commit() fs.core.complete_multipart_upload.assert_not_called() fs.core.put_object.assert_not_called() @@ -12501,7 +12501,7 @@ def test_creation_failure(self): assert file.buffer is None assert file.multipart_upload is None fs.core.call.assert_not_called() - with pytest.raises(S3MultipartStateError, match="The first failure: PermissionError"): + with pytest.raises(S3WriteStateError, match="The first failure: PermissionError"): file.commit() fs.core.put_object.assert_not_called() @@ -12601,12 +12601,11 @@ def _make_write_file(data: bytes, autocommit: bool, *, block_size=None, executor if block_size is not None: file.fs.core.MULTIPART_UPLOAD_MIN_PART_SIZE = block_size file.fs.core.MULTIPART_UPLOAD_MAX_PART_SIZE = 2 * block_size - file._session = _S3WriteSession( - file.fs.core, - S3Path("bucket", "key.txt"), - file._executor, - block_size=file.blocksize, - max_workers=file.max_workers, + file._target = S3FileTarget( + path=file.path, bucket=file.bucket, key=file.key, version_id=None, request_kwargs={} + ) + file._session = file._target.write_session( + file.fs, file._executor, block_size=file.blocksize, max_workers=file.max_workers ) return file @@ -12959,7 +12958,7 @@ def test_write_exceeding_max_parts(self, existing, mode, writes, closing, autoco # The upload is aborted, and committing a deferred write afterwards # raises instead of uploading anything. if not autocommit: - with pytest.raises(S3MultipartStateError): + with pytest.raises(S3WriteStateError): f.commit() assert [n for n, _ in self._parts(fs, existing) if n > 3] == [] fs.core.call.assert_called_once_with( @@ -13081,7 +13080,7 @@ def upload_part(**kwargs): assert f.multipart_upload is None assert f.completed_parts == () f.close() - with pytest.raises(S3MultipartStateError): + with pytest.raises(S3WriteStateError): f.commit() fs.core.call.assert_called_once() fs.core.complete_multipart_upload.assert_not_called() @@ -13389,7 +13388,7 @@ def test_discard(self, multipart): assert file.completed_parts == () # GH-1211: a discarded write is not committed afterwards. The buffered # data used to be uploaded with PutObject. - with pytest.raises(S3MultipartStateError, match="has been discarded"): + with pytest.raises(S3WriteStateError, match="has been discarded"): file.commit() file.fs.core.put_object.assert_not_called() file.fs.core.complete_multipart_upload.assert_not_called() @@ -13465,7 +13464,7 @@ def test_failed_put_closes_file(self): file.commit() assert file.closed assert file.buffer is None - with pytest.raises(S3MultipartStateError): + with pytest.raises(S3WriteStateError): file.commit() fs.core.put_object.assert_called_once() @@ -13474,7 +13473,7 @@ def test_failed_put_closes_file(self): ) def test_discard_open_file(self, data): # GH-1518: discard() left the file open, so that its close, also at the - # end of a with block, raised S3MultipartStateError. It closes the file + # end of a with block, raised S3WriteStateError. It closes the file # now, and the close commits nothing. fs = self._make_append_fs(b"") with S3File(fs, "s3://bucket/key.txt", mode="wb", block_size=4) as file: @@ -13534,7 +13533,7 @@ def test_commit_failure_and_discard(self, abort_fails): # completing the upload or uploading that data alone with PutObject. assert file.closed assert file.buffer is None - with pytest.raises(S3MultipartStateError): + with pytest.raises(S3WriteStateError): file.commit() file.fs.core.complete_multipart_upload.assert_called_once() file.fs.core.put_object.assert_not_called() @@ -13615,7 +13614,7 @@ def test_commit_failure_and_interrupted_abort(self): assert file.completed_parts with pytest.raises(RuntimeError): executor.submit(lambda: None) - with pytest.raises(S3MultipartStateError): + with pytest.raises(S3WriteStateError): file.commit() file.fs.core.complete_multipart_upload.assert_called_once() file.discard() @@ -13665,7 +13664,7 @@ def test_interrupted_creation_stops_retries(self): operation, RetryConfig(attempt=2, multiplier=EVENT_TIMEOUT) ) executor = S3ThreadPool(max_workers=1) - ready = _S3WriteSession.ready + ready = S3WriteSession.ready def interrupt_ready(session): # The wait of the write for the creation is interrupted. @@ -13683,7 +13682,7 @@ def interrupted(timeout=None): file = S3File(fs, "s3://bucket/key", mode="wb", block_size=block_size, executor=executor) started = time.monotonic() with ( - mock.patch.object(_S3WriteSession, "ready", interrupt_ready), + mock.patch.object(S3WriteSession, "ready", interrupt_ready), pytest.raises(KeyboardInterrupt), ): file.write(b"x" * block_size) diff --git a/tests/pyathena/filesystem/test_s3_async.py b/tests/pyathena/filesystem/test_s3_async.py index 5e52e068a..adc475d6f 100644 --- a/tests/pyathena/filesystem/test_s3_async.py +++ b/tests/pyathena/filesystem/test_s3_async.py @@ -49,7 +49,7 @@ ) from pyathena.filesystem.s3_path import S3Path from pyathena.filesystem.s3_retry import raise_if_stopped, retries_stopped -from pyathena.filesystem.s3_writer import S3MultipartStateError +from pyathena.filesystem.s3_writer import S3WriteStateError from pyathena.fs import s3_filesystem from pyathena.util import RetryConfig, stop_retries_on from tests import ENV @@ -2625,7 +2625,7 @@ def write_in_transaction(): fs.pipe_file("s3://bucket/k1", b"data") fs.pipe_file("s3://bucket/k2", b"data") - with pytest.raises(S3MultipartStateError): + with pytest.raises(S3WriteStateError): write_in_transaction() put_object.assert_not_called() @@ -2668,7 +2668,7 @@ def write_in_transaction(): write_in_transaction() assert [(c.args[0].key, c.args[1]) for c in put_object.call_args_list] == [("k2", b"a")] else: - with pytest.raises(S3MultipartStateError): + with pytest.raises(S3WriteStateError): write_in_transaction() put_object.assert_not_called() @@ -5762,7 +5762,7 @@ async def fail(): with pytest.raises(ValueError, match="failed"): await await_bounded(exit_) # The close fails to submit the last byte of the aborted upload. - with pytest.raises(S3MultipartStateError): + with pytest.raises(S3WriteStateError): await await_bounded(close) finally: release.set() @@ -6079,7 +6079,7 @@ def upload_part(**kwargs): with pytest.raises(asyncio.CancelledError) as e: await await_bounded(close) assert e.value.args == ("first",) - with pytest.raises(S3MultipartStateError): + with pytest.raises(S3WriteStateError): await await_bounded(write) finally: release.set() @@ -6114,7 +6114,7 @@ def upload_part(**kwargs): release.set() with pytest.raises(asyncio.CancelledError): await await_bounded(write) - with pytest.raises(S3MultipartStateError): + with pytest.raises(S3WriteStateError): await await_bounded(close) finally: release.set() @@ -6162,9 +6162,10 @@ async def flush(self, force=False): await asyncio.Event().wait() await super().flush(force=force) - f = SlowFile(fs, "bucket/key", "wb", block_size=block_size) + f = SlowFile(fs, "bucket/key", "wb", block_size=block_size, max_workers=1) await f.write(b"a" * block_size * 2) - await asyncio.wrap_future(f._session.settled()) + # With one worker, ready() resolves once no part is in flight. + await await_bounded(asyncio.wrap_future(f._session.ready())) close = asyncio.ensure_future(f.close()) await await_bounded(entered.wait()) close.cancel() diff --git a/tests/pyathena/filesystem/test_s3_writer.py b/tests/pyathena/filesystem/test_s3_writer.py index 5f0409770..6875daa16 100644 --- a/tests/pyathena/filesystem/test_s3_writer.py +++ b/tests/pyathena/filesystem/test_s3_writer.py @@ -26,13 +26,15 @@ S3CompleteMultipartUpload, S3MultipartUpload, S3MultipartUploadPart, + S3PutObject, ) from pyathena.filesystem.s3_path import S3Path from pyathena.filesystem.s3_writer import ( S3MultipartStateError, S3MultipartWriter, - _S3WriteSession, - _S3WriteState, + S3WriteSession, + S3WriteState, + S3WriteStateError, ) from pyathena.util import RetryConfig, stop_retries_on from tests.pyathena.util import ( @@ -324,7 +326,8 @@ def _make_session( Returns: The session and its recorded requests: ``created``, ``parts`` (the numbers of the part requests sent), ``completed`` (the part numbers - of each completion), and ``aborts``. + of each completion), ``puts`` (the body of each PutObject), and + ``aborts``. """ client = boto3.client( "s3", region_name="us-east-1", aws_access_key_id="dummy", aws_secret_access_key="dummy" @@ -334,7 +337,7 @@ def _make_session( core.MULTIPART_UPLOAD_MAX_PART_SIZE = 8 errors = dict(part_errors or {}) abort_errors = list(abort_errors) - requests = SimpleNamespace(created=0, parts=[], completed=[], aborts=0) + requests = SimpleNamespace(created=0, parts=[], completed=[], puts=[], aborts=0) def create(path, **params): requests.created += 1 @@ -356,6 +359,10 @@ def complete_stub(upload, parts, **params): raise complete_error return complete() if complete is not None else None + def put_object(path, body=None, **params): + requests.puts.append(body) + return S3PutObject({"ETag": '"e"'}) + def abort(upload, **params): if on_abort is not None: on_abort() @@ -367,7 +374,8 @@ def abort(upload, **params): core.upload_part = upload_part # type: ignore[method-assign] core.complete_multipart_upload = complete_stub # type: ignore[method-assign] core.abort_multipart_upload = abort # type: ignore[method-assign] - session = _S3WriteSession( + core.put_object = put_object # type: ignore[method-assign] + session = S3WriteSession( core, S3Path("bucket", "key"), executor, block_size=4, max_workers=max_workers ) return session, requests @@ -444,7 +452,7 @@ def test_stopped_write_sends_nothing_more(self, stopped): else: threading.Timer(0.2, lambda: (stop.set(), gate.set())).start() with pytest.raises(CancelledError): - session.complete() + session.commit() session.abort() expected_parts = [1] if stopped in ("queued", "completion") else [] assert (requests.parts, requests.completed) == (expected_parts, []) @@ -478,7 +486,7 @@ def wait_for_parts(timeout=None): threading.Thread(target=lambda: (waiting.wait(5), stop.set()), daemon=True).start() try: with pytest.raises(CancelledError): - session.complete() + session.commit() assert not gate.is_set() finally: gate.set() @@ -508,7 +516,7 @@ def stop_during_completion(): _start(session) session.submit_part(1, b"abcd") threading.Thread(target=stop_during_completion, daemon=True).start() - assert session.complete() == "success" + assert session.commit() == "success" assert operation.calls == 2 assert requests.completed == [[1]] @@ -546,11 +554,9 @@ class AccessDeniedError(PermissionError): for operation in ( session.check, lambda: session.submit_part(2, b"abcd"), - session.complete, + session.commit, ): - with pytest.raises( - S3MultipartStateError, match="The first failure: AccessDeniedError" - ): + with pytest.raises(S3WriteStateError, match="The first failure: AccessDeniedError"): operation() session.abort() finally: @@ -573,7 +579,7 @@ def test_dropped_request_fails_the_write(self, dropped): session.check() session.submit_part(1, b"abcd") with pytest.raises(CancelledError): - session.complete() + session.commit() session.abort() assert requests.completed == [] @@ -620,12 +626,12 @@ def defer(future): assert session.ready().result(5) is None session.submit_part(2, b"efgh") assert called.acquire(timeout=5) - session.complete() + session.commit() elif operation == "complete": gate.set() session.submit_part(1, b"abcd") assert called.acquire(timeout=5) - session.complete() + session.commit() elif operation == "abort": session.submit_part(1, b"abcd") session.submit_part(2, b"efgh") @@ -634,15 +640,15 @@ def defer(future): assert called.acquire(timeout=5) session.abort() else: - session.complete() + session.commit() # Every deferred callback runs after the operation. for future in deferred: (on_created if operation == "creation" else on_part_done)(future) if operation == "abort": assert requests.completed == [] assert session.completed_parts == () - with pytest.raises(S3MultipartStateError, match="has been discarded"): - session.complete() + with pytest.raises(S3WriteStateError, match="has been discarded"): + session.commit() else: expected = {"creation": [], "ready": [1, 2], "complete": [1]}[operation] assert requests.completed == [expected] @@ -671,7 +677,7 @@ def test_cancelled_waiter(self, dropped_by): for waiter in waiters: assert waiter.result(5) is None assert wait([first], timeout=5).done == {first} - session.complete() + session.commit() assert requests.completed == [[1]] @pytest.mark.parametrize( @@ -691,16 +697,16 @@ def test_abort_finds_upload_gone(self, error, aborted): ) _start(session) with pytest.raises(OSError, match="PreconditionFailed"): - session.complete() + session.commit() if aborted: session.abort() else: with pytest.raises(FileNotFoundError, match="NoSuchBucket"): session.abort() - assert session.state is _S3WriteState.ABORT_FAILED + assert session.state is S3WriteState.ABORT_FAILED assert session.upload is not None session.abort() - assert session.state is _S3WriteState.ABORTED + assert session.state is S3WriteState.ABORTED assert session.upload is None assert requests.aborts == (1 if aborted else 2) @@ -746,7 +752,7 @@ def interrupted_wait(futures): def interrupted_done(): # Interrupted as the check returns that it is running. result = done() - if not result and session.state is _S3WriteState.ABORTING: + if not result and session.state is S3WriteState.ABORTING: interrupt_once() return result @@ -760,11 +766,11 @@ def interrupted_done(): assert interrupted == [True] assert requests.aborts == 1 if abort_fails: - assert session.state is _S3WriteState.ABORT_FAILED + assert session.state is S3WriteState.ABORT_FAILED assert session.upload is not None else: assert str(info.value) == "interrupt" - assert session.state is _S3WriteState.ABORTED + assert session.state is S3WriteState.ABORTED assert session.upload is None # The code whose interrupt points take the second interrupt. @@ -780,7 +786,7 @@ def test_abort_after_two_interrupts(self, retried_in, target): # first, such as a close handed over by a garbage collection, while # the interrupted main thread lives on, does not wait forever either. attempts = [] - code = getattr(_S3WriteSession, target) + code = getattr(S3WriteSession, target) def case(interrupter): gate = threading.Event() @@ -794,7 +800,7 @@ def case(interrupter): class InterruptedCondition(threading.Condition): def wait(self, timeout=None): - if session.state is _S3WriteState.ABORTING and first_call[0]: + if session.state is S3WriteState.ABORTING and first_call[0]: first_call[0] = False raise KeyboardInterrupt return super().wait(timeout) @@ -813,7 +819,7 @@ def wait(self, timeout=None): call_bounded(session.abort) session.abort() attempts.append(interrupted_twice) - assert session.state is _S3WriteState.ABORTED + assert session.state is S3WriteState.ABORTED assert session.upload is None assert requests.aborts == 1 @@ -845,4 +851,145 @@ def abort_in_another_thread(): session.abort() assert nested == [None] assert requests.aborts == 1 - assert session.state is _S3WriteState.ABORTED + assert session.state is S3WriteState.ABORTED + + @pytest.mark.parametrize( + ("multipart", "body", "puts", "completed"), + [ + (False, None, [None], []), + (False, b"", [b""], []), + (False, b"data", [b"data"], []), + (True, None, [], [[1]]), + (True, b"", [], [[1]]), + ], + ) + def test_commit_follows_the_state(self, multipart, body, puts, completed): + # GH-1455: commit() sends PutObject for a write that started no + # multipart upload, also with an empty body, and completes the upload + # of one that did. A repeated commit returns the recorded result + # without another request. + with S3ThreadPool(max_workers=1) as executor: + session, requests = _make_session( + executor, complete=lambda: S3CompleteMultipartUpload({"ETag": '"c"'}) + ) + if multipart: + _start(session) + session.submit_part(1, b"abcd") + result = session.commit(body) + assert session.commit(body) is result + assert isinstance(result, S3CompleteMultipartUpload if multipart else S3PutObject) + assert session.state is S3WriteState.COMMITTED + assert session.commit_attempts == 1 + assert (requests.puts, requests.completed) == (puts, completed) + + def test_commit_rejects_a_body_of_a_multipart_upload(self): + # GH-1455: the data of a multipart upload is in its parts; a body + # given to its commit is rejected before any request, and the write + # can still be committed. + with S3ThreadPool(max_workers=1) as executor: + session, requests = _make_session(executor) + _start(session) + session.submit_part(1, b"abcd") + with pytest.raises(ValueError, match="Cannot commit a body"): + session.commit(b"efgh") + assert (session.state, session.commit_attempts) == (S3WriteState.ACTIVE, 0) + session.commit() + assert (requests.puts, requests.completed) == ([], [[1]]) + + @pytest.mark.parametrize("multipart", [False, True]) + @pytest.mark.parametrize("withdrawn", [False, True]) + def test_reserved_commit(self, multipart, withdrawn): + # GH-1455: a reserved commit leaves the write to the commit, which + # the next commit() sends; abort() meanwhile does nothing. A + # withdrawn reservation fails the write: commit() refuses it, and + # abort() discards it. + with S3ThreadPool(max_workers=1) as executor: + session, requests = _make_session(executor) + if multipart: + _start(session) + session.submit_part(1, b"abcd") + session.reserve_commit() + assert session.state is S3WriteState.COMMITTING + session.abort() + assert session.state is S3WriteState.COMMITTING + if withdrawn: + session.withdraw_commit() + assert session.state is S3WriteState.FAILED + with pytest.raises(S3WriteStateError, match="was withdrawn"): + session.commit() + session.abort() + assert session.state is S3WriteState.ABORTED + else: + session.commit() + # Taken by the commit, so the withdrawal does nothing. + session.withdraw_commit() + assert session.state is S3WriteState.COMMITTED + sent = [] if withdrawn else ([[1]] if multipart else [None]) + assert (requests.completed if multipart else requests.puts) == sent + assert requests.aborts == (1 if multipart and withdrawn else 0) + + @pytest.mark.parametrize("interrupted", [False, True]) + def test_abort_or_log(self, interrupted, caplog): + # GH-1455: abort_or_log() logs a failed abort with the upload ID + # instead of raising it, and raises an interrupt after logging it; + # the upload is kept, so that a later abort retries. + error = KeyboardInterrupt() if interrupted else PermissionError("denied") + with S3ThreadPool(max_workers=1) as executor: + session, requests = _make_session(executor, abort_errors=[error]) + _start(session) + with caplog.at_level("WARNING", logger="pyathena.filesystem.s3_writer"): + with pytest.raises(KeyboardInterrupt) if interrupted else contextlib.nullcontext(): + session.abort_or_log() + assert session.state is S3WriteState.ABORT_FAILED + assert session.upload is not None + session.abort_or_log() + verb = "Interrupted the abort of" if interrupted else "Failed to abort" + assert caplog.messages == [f"{verb} multipart upload uploadid to s3://bucket/key."] + assert session.state is S3WriteState.ABORTED + assert requests.aborts == 2 + + def test_prepared_params_replace_request_kwargs(self): + # GH-1455: the prepared parameters of an operation are sent as given + # in place of the session's request_kwargs, which the requests of the + # other operations receive where the operation accepts them. + client = boto3.client( + "s3", region_name="us-east-1", aws_access_key_id="dummy", aws_secret_access_key="dummy" + ) + core = S3Core(client, retry_config=RetryConfig(attempt=1)) + core.MULTIPART_UPLOAD_MIN_PART_SIZE = 4 + core.MULTIPART_UPLOAD_MAX_PART_SIZE = 8 + target = {"Bucket": "bucket", "Key": "key"} + upload = {**target, "UploadId": "u", "RequestPayer": "requester"} + with Stubber(client) as stubber, S3ThreadPool(max_workers=1) as executor: + stubber.add_response( + "create_multipart_upload", + {**target, "UploadId": "u"}, + {**target, "ContentType": "image/png"}, + ) + stubber.add_response( + "upload_part", {"ETag": '"e"'}, {**upload, "PartNumber": 1, "Body": b"abcd"} + ) + stubber.add_response( + "complete_multipart_upload", + {**target, "ETag": '"c"'}, + {**upload, "MultipartUpload": {"Parts": [{"ETag": '"e"', "PartNumber": 1}]}}, + ) + session = S3WriteSession( + core, + S3Path("bucket", "key"), + executor, + block_size=4, + max_workers=1, + request_kwargs={"ContentType": "text/plain", "RequestPayer": "requester"}, + prepared_params={"create_multipart_upload": {"ContentType": "image/png"}}, + ) + _start(session) + session.submit_part(1, b"abcd") + session.commit() + stubber.assert_no_pending_responses() + + +def test_multipart_state_error_is_the_write_state_error(): + # GH-1455: the former name refers to the same class, so that code that + # catches it keeps catching the errors of a write. + assert S3MultipartStateError is S3WriteStateError From 9a218d11e8b91d4dcd13f0d2080bf7801b5c3f87 Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Tue, 1 Dec 2026 00:27:50 +0900 Subject: [PATCH 2/8] Check the commit body after the state, and release appended data (GH-1455) commit(body) on a multipart write returned ValueError before it looked at the state, so a commit after a success did not return the recorded result, and a failed or discarded write did not raise its state error. The body is now checked once the state allows the commit. A write-mode file keeps its S3FileTarget, which held the data of a small appended object after the file had written it into its buffer; the target drops it there. The interrupted-copy test listens on the session's logger, which now logs the upload ID, and checks the record. The documentation example writes a short stream with PutObject, the commit docstring names the refusal of a concurrent commit, and stale comments name the COMMITTING state. Co-Authored-By: Claude Opus 5.5 --- docs/filesystem.md | 15 +-- pyathena/filesystem/s3.py | 15 ++- pyathena/filesystem/s3_async.py | 2 + pyathena/filesystem/s3_writer.py | 105 +++++++++----------- tests/pyathena/filesystem/test_s3.py | 8 +- tests/pyathena/filesystem/test_s3_writer.py | 16 ++- 6 files changed, 87 insertions(+), 74 deletions(-) diff --git a/docs/filesystem.md b/docs/filesystem.md index 29ab2649d..b47e95fb5 100644 --- a/docs/filesystem.md +++ b/docs/filesystem.md @@ -1115,17 +1115,20 @@ with S3ThreadPool(max_workers=4) as executor: max_workers=4, ) try: - session.start() - for number, body in session.iter_parts(stream): - session.wait_ready() - session.submit_part(number, body) - result = session.commit() + if size >= 5 * 2**20: + session.start() + for part_number, body in session.iter_parts(stream): + session.wait_ready() + session.submit_part(part_number, body) + result = session.commit() + else: + result = session.commit(stream.read()) except BaseException: session.abort_or_log() raise ``` -`start()` creates the multipart upload; without it, `commit(body)` writes `body` with PutObject, and `None` or empty bytes write an empty object. +`start()` creates the multipart upload, which needs at least one part before `commit()`; without it, `commit(body)` writes `body` with PutObject, and `None` or empty bytes write an empty object. After `start()`, `commit()` completes the upload once its parts have been uploaded, and rejects a non-empty `body`. A successful commit returns its result again without another request. `ready()` returns a future, and `wait_ready()` blocks, until another part may be submitted. diff --git a/pyathena/filesystem/s3.py b/pyathena/filesystem/s3.py index a2f3e2379..4db3878a2 100644 --- a/pyathena/filesystem/s3.py +++ b/pyathena/filesystem/s3.py @@ -5609,7 +5609,8 @@ class S3FileTarget: size: The size of the object that is read, if known. appended: The existing object in append mode, if any. append_data: The data of an appended object that the file rewrites - from its buffer, if any. + from its buffer, if any, until the file has written it into its + buffer. if_match_from_lookup: Whether the reads are conditioned with ``IfMatch`` on the ETag of the object looked up for reading, possibly in the listing cache, rather than on the caller's @@ -5895,6 +5896,10 @@ def write_session( ) -> S3WriteSession: """Create the session of a write of the object, without sending any request. + A target creates the session of one file: :meth:`commit` and + :meth:`abort` take that session, and the target records which of its + commits have invalidated the cache. + Args: fs: The filesystem, whose core sends the requests. executor: The executor of the creation and part requests. @@ -5902,9 +5907,9 @@ def write_session( max_workers: The number of part requests of the file in flight. Returns: - The session, whose requests inherit ``request_kwargs``, read - when each request is sent; a mapping assigned to the attribute - later is not read. + The session, whose requests inherit the mapping of + ``request_kwargs``, read when each request is sent; a mapping + assigned to ``request_kwargs`` later is not read. """ return S3WriteSession( fs.core, @@ -6161,6 +6166,8 @@ def __init__( if target.appended is not None: if target.append_data is not None: self.write(target.append_data) + # Not kept twice while the file is open: the target is. + target.append_data = None else: # Copied with UploadPartCopy as the leading part(s). self.append_block = True diff --git a/pyathena/filesystem/s3_async.py b/pyathena/filesystem/s3_async.py index beaf36267..89e06db01 100644 --- a/pyathena/filesystem/s3_async.py +++ b/pyathena/filesystem/s3_async.py @@ -2672,6 +2672,8 @@ def __init__( if target.appended is not None: if target.append_data is not None: cast(BytesIO, self.buffer).write(target.append_data) + # Not kept twice while the file is open: the target is. + target.append_data = None else: # Copied with UploadPartCopy as the leading part(s). self.append_block = True diff --git a/pyathena/filesystem/s3_writer.py b/pyathena/filesystem/s3_writer.py index 73e4f3091..824da8ec9 100644 --- a/pyathena/filesystem/s3_writer.py +++ b/pyathena/filesystem/s3_writer.py @@ -13,9 +13,9 @@ import enum import logging import threading -from collections.abc import Callable, Iterator, Mapping, Sequence +from collections.abc import Iterator, Mapping, Sequence from concurrent.futures import CancelledError, Future, wait -from typing import Any, BinaryIO, TypeVar, cast +from typing import Any, BinaryIO, cast from pyathena.filesystem.s3_core import S3Core from pyathena.filesystem.s3_errors import S3ClientError @@ -29,8 +29,6 @@ from pyathena.filesystem.s3_path import S3Path from pyathena.filesystem.s3_retry import raise_if_stopped, stop_retries_on, unstoppable_retries -T = TypeVar("T") - _logger = logging.getLogger(__name__) @@ -722,22 +720,54 @@ def commit(self, body: bytes | None = None) -> S3PutObject | S3CompleteMultipart Raises: BaseException: The first failure of a request, if it has not been raised yet, or the failure of the commit request. - S3WriteStateError: If the write is being created or aborted, or - failed earlier, or has been discarded. + S3WriteStateError: If the multipart upload is being created, the + write is being committed by another call or aborted, or the + write failed earlier or has been discarded. ValueError: If ``body`` is not empty for a write that started a multipart upload. concurrent.futures.CancelledError: If an enclosing stop scope has been stopped before the request (see :func:`~pyathena.filesystem.s3_retry.raise_if_stopped`); the write fails then. """ - if not self._multipart: - return self._commit(S3WriteState.IDLE, lambda: self._put_object(body)) - if body: - raise ValueError( - f"Cannot commit a body to {self._path.uri}: the write uploads its data as " - "parts of a multipart upload." - ) - return self._commit(S3WriteState.ACTIVE, self._complete_parts) + reserved = False + try: + with self._lock: + if self._state is S3WriteState.COMMITTED: + return cast(S3PutObject | S3CompleteMultipartUpload, self._result) + # IDLE for PutObject, or ACTIVE for the completion. + state = S3WriteState.ACTIVE if self._multipart else S3WriteState.IDLE + taken = self._state is S3WriteState.COMMITTING and self._reservation is state + if not taken: + self._refuse_unless(state, operation="commit") + if body and self._multipart: + raise ValueError( + f"Cannot commit a body to {self._path.uri}: the write uploads its " + "data as parts of a multipart upload." + ) + # Set first, so that an interrupt right after the state + # changes leaves the write failed, for the caller to abort, + # rather than being committed. + reserved = True + if taken: + # Reserved by reserve_commit(). + self._reservation = None + else: + self._state = S3WriteState.COMMITTING + result = self._complete_parts() if self._multipart else self._put_object(body) + with self._lock: + # The result first, as the state publishes it. + self._result = result + self._state = S3WriteState.COMMITTED + waiters = self._publish() + self._notify(waiters) + except BaseException as e: + if reserved and self._state is not S3WriteState.COMMITTED: + with self._lock: + self._fail(e, raised=True) + waiters = self._publish() + self._notify(waiters) + raise + return result def reserve_commit(self) -> None: """Reserve the commit before the call that sends it is queued. @@ -758,7 +788,7 @@ def reserve_commit(self) -> None: return state = S3WriteState.ACTIVE if self._multipart else S3WriteState.IDLE self._refuse_unless(state, operation="commit") - # Set first, so that a COMPLETING state that this sets always has + # Set first, so that a COMMITTING state that this sets always has # its reservation for the commit to take. self._reservation = state self._state = S3WriteState.COMMITTING @@ -776,7 +806,7 @@ def withdraw_commit(self) -> None: with self._lock: if self._state is S3WriteState.COMMITTING and self._reservation is not None: # Failed first, so that an interrupt in between never leaves - # a COMPLETING state without its reservation, which abort() + # a COMMITTING state without its reservation, which abort() # leaves to a commit that nothing sends. self._fail( S3WriteStateError( @@ -1101,49 +1131,6 @@ def _put_object(self, body: bytes | None) -> S3PutObject: self._path, body, **self._params("put_object") ) - def _commit(self, state: S3WriteState, send: Callable[[], T]) -> T: - """Reserve the commit, send its request, and record the outcome. - - Args: - state: The state that allows the commit: IDLE for PutObject, or - ACTIVE for the completion of the multipart upload. - send: Sends the request and returns its result. - - Returns: - The result of the request, or of the earlier successful commit. - """ - reserved = False - try: - with self._lock: - if self._state is S3WriteState.COMMITTED: - return cast(T, self._result) - if self._state is S3WriteState.COMMITTING and self._reservation is state: - # Reserved by reserve_commit(). - reserved = True - self._reservation = None - else: - self._refuse_unless(state, operation="commit") - # Set first, so that an interrupt right after the state - # changes leaves the write failed, for the caller to - # abort, rather than being committed. - reserved = True - self._state = S3WriteState.COMMITTING - result = send() - with self._lock: - # The result first, as the state publishes it. - self._result = cast(S3PutObject | S3CompleteMultipartUpload, result) - self._state = S3WriteState.COMMITTED - waiters = self._publish() - self._notify(waiters) - except BaseException as e: - if reserved and self._state is not S3WriteState.COMMITTED: - with self._lock: - self._fail(e, raised=True) - waiters = self._publish() - self._notify(waiters) - raise - return result - def _complete_parts(self) -> S3CompleteMultipartUpload: """Complete the upload once its part requests have settled. diff --git a/tests/pyathena/filesystem/test_s3.py b/tests/pyathena/filesystem/test_s3.py index 6f6a34378..2f1fee407 100644 --- a/tests/pyathena/filesystem/test_s3.py +++ b/tests/pyathena/filesystem/test_s3.py @@ -9834,12 +9834,13 @@ def wait(self, timeout=None): fs.core.call.return_value = {"ContentLength": 2 * S3Core.MULTIPART_UPLOAD_MAX_PART_SIZE} fs.core.abort_multipart_upload = mock.MagicMock() handler = UploadIdLogged() - logger = logging.getLogger("pyathena.filesystem.s3") + # The logger of the session, whose abort_or_log() logs the upload ID. + logger = logging.getLogger("pyathena.filesystem.s3_writer") logger.addHandler(handler) try: with ( - caplog.at_level(logging.WARNING, logger="pyathena.filesystem.s3"), + caplog.at_level(logging.WARNING, logger="pyathena.filesystem.s3_writer"), mock.patch.object(S3WriteSession, "__init__", init_with_interrupt), pytest.raises(KeyboardInterrupt), ): @@ -9858,6 +9859,9 @@ def wait(self, timeout=None): assert interrupts == [True] assert logged_while_running == [True] + assert caplog.messages == [ + "Interrupted the abort of multipart upload uploadid to s3://bucket/dst." + ] fs.core.abort_multipart_upload.assert_not_called() @pytest.mark.parametrize( diff --git a/tests/pyathena/filesystem/test_s3_writer.py b/tests/pyathena/filesystem/test_s3_writer.py index 6875daa16..7e73c54bf 100644 --- a/tests/pyathena/filesystem/test_s3_writer.py +++ b/tests/pyathena/filesystem/test_s3_writer.py @@ -885,15 +885,25 @@ def test_commit_follows_the_state(self, multipart, body, puts, completed): def test_commit_rejects_a_body_of_a_multipart_upload(self): # GH-1455: the data of a multipart upload is in its parts; a body # given to its commit is rejected before any request, and the write - # can still be committed. + # can still be committed. Once committed, a commit with the body + # returns the recorded result, and a discarded write refuses it with + # its state rather than the body. with S3ThreadPool(max_workers=1) as executor: - session, requests = _make_session(executor) + session, requests = _make_session( + executor, complete=lambda: S3CompleteMultipartUpload({"ETag": '"c"'}) + ) _start(session) session.submit_part(1, b"abcd") with pytest.raises(ValueError, match="Cannot commit a body"): session.commit(b"efgh") assert (session.state, session.commit_attempts) == (S3WriteState.ACTIVE, 0) - session.commit() + result = session.commit() + assert session.commit(b"efgh") is result + discarded, _ = _make_session(executor) + _start(discarded) + discarded.abort() + with pytest.raises(S3WriteStateError, match="has been discarded"): + discarded.commit(b"efgh") assert (requests.puts, requests.completed) == ([], [[1]]) @pytest.mark.parametrize("multipart", [False, True]) From 6971bc258bd5da81a590d2061ae8911558fe5444 Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Tue, 1 Dec 2026 00:55:33 +0900 Subject: [PATCH 3/8] Clean up a failed commit before invalidating, and close session gaps (GH-1455) The shared commit of S3FileTarget invalidated the cache of the path before the file aborted the failed upload, and an interrupt of the invalidation after a successful commit closed a sync file without its buffer. The file's cleanup now runs inside the commit, before the invalidation, as before the drivers were shared. The session takes a reserved commit before it checks the body, so that a rejected body fails the write and abort() aborts the upload, and it resolves the waits of ready() when the write starts to be committed. write_session() keeps the version of the target, which the session refuses, and starts the invalidation record over; the append plan yields no copy for an object that the file rewrites from its buffer. The docstrings and docs name the fields that S3Core sets itself and when an interrupted abort is logged; the log tests check the level and the upload ID instead of the wording. Co-Authored-By: Claude Opus 5.5 --- docs/filesystem.md | 4 +- pyathena/filesystem/s3.py | 61 ++++++++++----- pyathena/filesystem/s3_async.py | 13 ++-- pyathena/filesystem/s3_writer.py | 55 ++++++++----- tests/pyathena/filesystem/test_s3.py | 70 ++++++++++++++++- tests/pyathena/filesystem/test_s3_async.py | 22 ++++++ tests/pyathena/filesystem/test_s3_writer.py | 85 ++++++++++++++++++++- 7 files changed, 258 insertions(+), 52 deletions(-) diff --git a/docs/filesystem.md b/docs/filesystem.md index b47e95fb5..ddc3d860b 100644 --- a/docs/filesystem.md +++ b/docs/filesystem.md @@ -1128,7 +1128,7 @@ with S3ThreadPool(max_workers=4) as executor: raise ``` -`start()` creates the multipart upload, which needs at least one part before `commit()`; without it, `commit(body)` writes `body` with PutObject, and `None` or empty bytes write an empty object. +`start()` creates the multipart upload, which needs at least one part before `commit()`; without it, `commit(body)` writes `body` with PutObject, and `None` or empty bytes send no body, as with `S3Core.put_object()`. After `start()`, `commit()` completes the upload once its parts have been uploaded, and rejects a non-empty `body`. A successful commit returns its result again without another request. `ready()` returns a future, and `wait_ready()` blocks, until another part may be submitted. @@ -1141,7 +1141,7 @@ A driver that cannot block reserves the commit with `reserve_commit()` before it `commit_attempts` counts the commit requests that have started to be sent, including failed ones, which may have committed the object. The `request_kwargs` of the session are added to each request whose operation accepts them. -`prepared_params` gives the parameters of the requests of an operation by client method name, such as `create_multipart_upload`; they are sent as given and replace the `request_kwargs` of the session for that operation. +`prepared_params` gives the parameters of the requests of an operation by client method name, such as `create_multipart_upload`; they are sent as given, except for the fields that `S3Core` sets itself, such as the checksum algorithm of the upload, and replace the `request_kwargs` of the session for that operation. The session does not invalidate the filesystem cache; call `fs.invalidate_cache()` after a direct write. ### Multipart requests diff --git a/pyathena/filesystem/s3.py b/pyathena/filesystem/s3.py index 4db3878a2..4af2435fe 100644 --- a/pyathena/filesystem/s3.py +++ b/pyathena/filesystem/s3.py @@ -5898,7 +5898,7 @@ def write_session( A target creates the session of one file: :meth:`commit` and :meth:`abort` take that session, and the target records which of its - commits have invalidated the cache. + commits have invalidated the cache, which a new session starts over. Args: fs: The filesystem, whose core sends the requests. @@ -5910,10 +5910,15 @@ def write_session( The session, whose requests inherit the mapping of ``request_kwargs``, read when each request is sent; a mapping assigned to ``request_kwargs`` later is not read. + + Raises: + ValueError: If the target names a version, which a write cannot + replace, or the block size is invalid. """ + self._invalidated_commit_attempts = 0 return S3WriteSession( fs.core, - S3Path(self.bucket, self.key), + S3Path(self.bucket, self.key, self.version_id), executor, block_size=block_size, max_workers=max_workers, @@ -5932,30 +5937,42 @@ def iter_append_copies( Yields: The part number and the source range of each copy, with an exclusive end, or None to copy an object that fits in one part - whole. Nothing if no object is appended. + whole. Nothing if no object is appended, or if the appended + object is smaller than ``S3Core.MULTIPART_UPLOAD_MIN_PART_SIZE``, + which the file rewrites from its buffer (see ``append_data``). """ size = self.appended.get("size", 0) if self.appended is not None else 0 + if size < fs.core.MULTIPART_UPLOAD_MIN_PART_SIZE: + return whole_source = size <= fs.core.MULTIPART_UPLOAD_MAX_PART_SIZE for part_number, range_ in session.iter_copy_parts(size): yield part_number, None if whole_source else range_ - def commit(self, fs: S3FileSystem, session: S3WriteSession, buffer: BytesIO | None) -> None: + def commit( + self, + fs: S3FileSystem, + session: S3WriteSession, + buffer: BytesIO | None, + on_failure: Callable[[], None] | None = None, + ) -> None: """Commit a write of the object whose final flush has prepared its data. Sends the buffered data with PutObject if the write started no multipart upload, and otherwise completes the upload (see :meth:`S3WriteSession.commit`). A failure that shows a cached entry - to be stale evicts it. Once a commit request has started to be sent - since the last invalidation, the cache of the path is invalidated, - also when the request fails, since a request whose response is lost - may have committed the object, and a rejected conditional write - shows that an object exists. + to be stale evicts it, and then runs ``on_failure``. Once a commit + request has started to be sent since the last invalidation, the + cache of the path is invalidated last, also when the request fails, + since a request whose response is lost may have committed the + object, and a rejected conditional write shows that an object exists. Args: fs: The filesystem, which caches the object. session: The session of the write. buffer: The written data that no part has uploaded, or None. The data of a multipart upload is in its parts. + on_failure: Run after a failure of the commit, before the error + is raised, such as the abort of the multipart upload. """ path = S3Path(self.bucket, self.key) body = None @@ -5963,8 +5980,13 @@ def commit(self, fs: S3FileSystem, session: S3WriteSession, buffer: BytesIO | No # None without data, which writes an empty object as well. body = buffer.getvalue() or None try: - with fs._evicting_stale(path): - session.commit(body) + try: + with fs._evicting_stale(path): + session.commit(body) + except BaseException: + if on_failure is not None: + on_failure() + raise finally: if session.commit_attempts != self._invalidated_commit_attempts: # A commit refused, stopped, or ended by a failed part before @@ -6821,14 +6843,15 @@ def _commit(self) -> None: The part of :meth:`commit` that the final flush of an ``autocommit`` file also runs. See :meth:`commit`. """ - try: - self._target.commit(self.fs, cast(S3WriteSession, self._session), self.buffer) - except BaseException: - # Closed without the buffer, which a failed write cannot commit - # again; for a multipart upload, it holds only the data of the - # last part. - self._close_without_commit() - raise + # A failed commit closes the file without the buffer, which a failed + # write cannot commit again; for a multipart upload, it holds only + # the data of the last part. + self._target.commit( + self.fs, + cast(S3WriteSession, self._session), + self.buffer, + on_failure=self._close_without_commit, + ) def discard(self) -> None: """Discard the written data, close the file, and abort the multipart upload, if any. diff --git a/pyathena/filesystem/s3_async.py b/pyathena/filesystem/s3_async.py index 89e06db01..3274bfca7 100644 --- a/pyathena/filesystem/s3_async.py +++ b/pyathena/filesystem/s3_async.py @@ -3358,12 +3358,13 @@ def _complete_upload(self, buffer: BytesIO) -> None: file was opened in exclusive-create mode. """ session = cast(S3WriteSession, self._session) - try: - self._target.commit(self.fs._sync_fs, session, buffer) - except BaseException: - if session.multipart: - self._discard() - raise + # A failed completion aborts the multipart upload. + self._target.commit( + self.fs._sync_fs, + session, + buffer, + on_failure=self._discard if session.multipart else None, + ) def _discard(self) -> None: """Discard the write, and abort its multipart upload, if any; blocks. diff --git a/pyathena/filesystem/s3_writer.py b/pyathena/filesystem/s3_writer.py index 824da8ec9..265a628d2 100644 --- a/pyathena/filesystem/s3_writer.py +++ b/pyathena/filesystem/s3_writer.py @@ -431,9 +431,11 @@ def __init__( operations, by client method name, such as ``create_multipart_upload``, which are sent as given for that operation, so that botocore rejects one that the operation - does not accept. They replace ``request_kwargs`` for that - operation, whose requests still receive the - ``request_kwargs`` of the core that the operation accepts. + does not accept, under the fields that the core sets itself, + such as the checksum algorithm of the upload. They replace + ``request_kwargs`` for that operation, whose requests still + receive the ``request_kwargs`` of the core that the operation + accepts. Raises: ValueError: If the destination, the block size, or @@ -698,13 +700,13 @@ def commit(self, body: bytes | None = None) -> S3PutObject | S3CompleteMultipart """Commit the write. A write that started no multipart upload is committed with a single - PutObject request of ``body``; None or empty bytes write an empty - object. A write that started one is committed by completing it, once - its part requests have settled: the first failure among them is - raised without waiting for the others. A failed or interrupted - commit leaves the write failed, and the caller aborts it. Committing - again after a successful commit returns its result without another - request. + PutObject request of ``body``; None or empty bytes send no body, so + an empty object is written, as :meth:`S3Core.put_object` writes it. + A write that started one is committed by completing it, once its + part requests have settled: the first failure among them is raised + without waiting for the others. A failed or interrupted commit leaves + the write failed, and the caller aborts it. Committing again after a + successful commit returns its result without another request. Args: body: The data of the object, for a write that started no @@ -736,23 +738,29 @@ def commit(self, body: bytes | None = None) -> S3PutObject | S3CompleteMultipart return cast(S3PutObject | S3CompleteMultipartUpload, self._result) # IDLE for PutObject, or ACTIVE for the completion. state = S3WriteState.ACTIVE if self._multipart else S3WriteState.IDLE - taken = self._state is S3WriteState.COMMITTING and self._reservation is state - if not taken: + waiters: list[Future[None]] = [] + if self._state is S3WriteState.COMMITTING and self._reservation is state: + # Reserved by reserve_commit(), and taken before the body + # is checked, so that a rejected body fails the write, + # which abort() then discards. + reserved = True + self._reservation = None + else: self._refuse_unless(state, operation="commit") if body and self._multipart: raise ValueError( f"Cannot commit a body to {self._path.uri}: the write uploads its " "data as parts of a multipart upload." ) - # Set first, so that an interrupt right after the state - # changes leaves the write failed, for the caller to abort, - # rather than being committed. - reserved = True - if taken: - # Reserved by reserve_commit(). - self._reservation = None - else: + if not reserved: + # Set first, so that an interrupt right after the state + # changes leaves the write failed, for the caller to + # abort, rather than being committed. + reserved = True self._state = S3WriteState.COMMITTING + # The waits of ready() end, as no part can be submitted. + waiters = self._publish() + self._notify(waiters) result = self._complete_parts() if self._multipart else self._put_object(body) with self._lock: # The result first, as the state publishes it. @@ -792,6 +800,9 @@ def reserve_commit(self) -> None: # its reservation for the commit to take. self._reservation = state self._state = S3WriteState.COMMITTING + # The waits of ready() end, as no part can be submitted. + waiters = self._publish() + self._notify(waiters) def withdraw_commit(self) -> None: """Withdraw the commit reserved by :meth:`reserve_commit`, unless it has been taken. @@ -948,7 +959,9 @@ def abort_or_log(self) -> None: raises itself: a failed abort does not replace that error. The failure is logged with the ID of the upload, which is kept so that a later :meth:`abort` can retry. An interrupt, such as - ``KeyboardInterrupt``, is logged with the ID and raised. + ``KeyboardInterrupt``, is raised, and logged with the ID of the upload + if the interrupted abort keeps it; an interrupt of the wait for the + creation is raised once the upload is aborted (see :meth:`abort`). Raises: KeyboardInterrupt: An interrupt of the abort. diff --git a/tests/pyathena/filesystem/test_s3.py b/tests/pyathena/filesystem/test_s3.py index 2f1fee407..bc1d7e3e2 100644 --- a/tests/pyathena/filesystem/test_s3.py +++ b/tests/pyathena/filesystem/test_s3.py @@ -9859,8 +9859,8 @@ def wait(self, timeout=None): assert interrupts == [True] assert logged_while_running == [True] - assert caplog.messages == [ - "Interrupted the abort of multipart upload uploadid to s3://bucket/dst." + assert [(r.levelno, "uploadid" in r.getMessage()) for r in caplog.records] == [ + (logging.WARNING, True) ] fs.core.abort_multipart_upload.assert_not_called() @@ -12197,6 +12197,53 @@ def _target(size=None): size=size, ) + def test_write_session_refuses_a_version(self): + # GH-1455: a write session of a target that names a version is + # refused before any request, as a write cannot replace a version. + fs = S3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + target = S3FileTarget( + path="bucket/key?versionId=v1", + bucket="bucket", + key="key", + version_id="v1", + request_kwargs={}, + ) + with pytest.raises(ValueError, match="Cannot write to a version"): + target.write_session( + fs, + mock.MagicMock(), + block_size=S3Core.MULTIPART_UPLOAD_MIN_PART_SIZE, + max_workers=1, + ) + + @pytest.mark.parametrize(("size", "copies"), [(3, []), (4, [(1, None)]), (8, [(1, None)])]) + def test_iter_append_copies(self, size, copies): + # GH-1455: an appended object smaller than the minimum part size is + # rewritten from the buffer of the file, so it has no part copy; a + # larger one that fits in a part is copied whole. + fs = S3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + fs.core.MULTIPART_UPLOAD_MIN_PART_SIZE = 4 + fs.core.MULTIPART_UPLOAD_MAX_PART_SIZE = 8 + target = S3FileTarget( + path="bucket/key", + bucket="bucket", + key="key", + version_id=None, + request_kwargs={}, + appended=S3Object( + init={"ContentLength": size}, + type=S3ObjectType.S3_OBJECT_TYPE_FILE, + bucket="bucket", + key="key", + ), + ) + session = target.write_session(fs, mock.MagicMock(), block_size=4, max_workers=1) + assert list(target.iter_append_copies(fs, session)) == copies + @pytest.mark.parametrize( ("start", "end", "block_size", "max_workers", "size", "ranges"), [ @@ -13554,6 +13601,25 @@ def test_commit_failure_and_discard(self, abort_fails): assert file.multipart_upload is None assert file.completed_parts == () + def test_failed_commit_invalidates_after_the_abort(self): + # GH-1455: a commit whose completion fails invalidates the cache of + # the path after the abort of the upload, so that an entry cached + # while the abort runs, which a completion that took effect despite + # its failure makes stale, does not survive the commit. + file = self._make_multipart_write_file(b"x" * 16, autocommit=False) + file._upload_chunk(final=True) + order = [] + file.fs.core.complete_multipart_upload.side_effect = RuntimeError("complete failed") + file.fs.core.call.side_effect = lambda *args, **kwargs: order.append("abort") + with ( + mock.patch.object( + file.fs, "_invalidate", side_effect=lambda path: order.append("invalidate") + ), + pytest.raises(RuntimeError, match="complete failed"), + ): + file.commit() + assert order == ["abort", "invalidate"] + def test_commit_stops_at_failed_part(self): # GH-1178: commit() raises a failed part without waiting for the parts # before it, so that the parts queued after it, such as the part diff --git a/tests/pyathena/filesystem/test_s3_async.py b/tests/pyathena/filesystem/test_s3_async.py index adc475d6f..271895e81 100644 --- a/tests/pyathena/filesystem/test_s3_async.py +++ b/tests/pyathena/filesystem/test_s3_async.py @@ -6147,6 +6147,28 @@ async def flush(self, force=False): assert calls == [True] assert put == [b"datatrailer"] + @pytest.mark.asyncio + async def test_failed_completion_invalidates_after_the_abort(self, fs): + # GH-1455: as TestS3File.test_failed_commit_invalidates_after_the_abort, + # a failed completion aborts the upload before the cache of the path + # is invalidated. + block_size = S3Core.MULTIPART_UPLOAD_MIN_PART_SIZE + order = [] + fs.core.complete_multipart_upload = mock.MagicMock(side_effect=OSError("complete failed")) + fs.core.abort_multipart_upload = mock.MagicMock( + side_effect=lambda *args, **kwargs: order.append("abort") + ) + f = await fs.open_async("s3://bucket/key", "wb", block_size=block_size) + await f.write(b"a" * block_size * 2) + with ( + mock.patch.object( + fs._sync_fs, "_invalidate", side_effect=lambda path: order.append("invalidate") + ), + pytest.raises(OSError, match="complete failed"), + ): + await await_bounded(f.close()) + assert order == ["abort", "invalidate"] + @pytest.mark.asyncio async def test_close_cancelled_before_final_flush_aborts(self, fs): # GH-1546: a close whose final flush ends before it begins, here in an diff --git a/tests/pyathena/filesystem/test_s3_writer.py b/tests/pyathena/filesystem/test_s3_writer.py index 7e73c54bf..66bdf2f47 100644 --- a/tests/pyathena/filesystem/test_s3_writer.py +++ b/tests/pyathena/filesystem/test_s3_writer.py @@ -8,6 +8,7 @@ import contextlib import gc import io +import logging import threading import weakref from concurrent.futures import CancelledError, wait @@ -953,8 +954,10 @@ def test_abort_or_log(self, interrupted, caplog): assert session.state is S3WriteState.ABORT_FAILED assert session.upload is not None session.abort_or_log() - verb = "Interrupted the abort of" if interrupted else "Failed to abort" - assert caplog.messages == [f"{verb} multipart upload uploadid to s3://bucket/key."] + level = logging.WARNING if interrupted else logging.ERROR + assert [(r.levelno, "uploadid" in r.getMessage()) for r in caplog.records] == [ + (level, True) + ] assert session.state is S3WriteState.ABORTED assert requests.aborts == 2 @@ -998,6 +1001,84 @@ def test_prepared_params_replace_request_kwargs(self): session.commit() stubber.assert_no_pending_responses() + def test_rejected_body_of_a_reserved_commit_fails_the_write(self): + # GH-1455: a body rejected by the commit that takes a reservation + # fails the write, so that abort() aborts the upload instead of + # leaving it to a commit that nothing sends. + with S3ThreadPool(max_workers=1) as executor: + session, requests = _make_session(executor) + _start(session) + session.submit_part(1, b"abcd") + session.reserve_commit() + with pytest.raises(ValueError, match="Cannot commit a body"): + session.commit(b"efgh") + assert session.state is S3WriteState.FAILED + session.abort() + assert session.state is S3WriteState.ABORTED + assert (requests.completed, requests.aborts) == ([], 1) + + @pytest.mark.parametrize("reserved", [False, True]) + def test_commit_ends_the_waits_of_ready(self, reserved): + # GH-1455: once the write is being committed, no part can be + # submitted, so a pending ready() resolves without waiting for the + # parts in flight, whether the commit is reserved or sent directly. + gate = threading.Event() + with S3ThreadPool(max_workers=1) as executor: + session, requests = _make_session(executor, gate=gate) + _start(session) + session.submit_part(1, b"abcd") + poll_until(lambda: requests.parts == [1], "part 1 did not start") + waiter = session.ready() + assert not waiter.done() + committer = threading.Thread(target=session.commit, daemon=True) + try: + if reserved: + session.reserve_commit() + else: + # Waits for part 1, which the gate holds. + committer.start() + assert waiter.result(5) is None + finally: + gate.set() + if reserved: + session.commit() + else: + committer.join(5) + assert session.state is S3WriteState.COMMITTED + assert requests.completed == [[1]] + + def test_withdrawal_leaves_a_running_commit(self): + # GH-1455: a withdrawal after the commit has taken its reservation, + # such as one of a commit call that is already sending its request, + # leaves that commit to run on and succeed. + started, release = threading.Event(), threading.Event() + results = [] + + def complete(): + started.set() + assert release.wait(5) + return S3CompleteMultipartUpload({"ETag": '"c"'}) + + with S3ThreadPool(max_workers=1) as executor: + session, requests = _make_session(executor, complete=complete) + _start(session) + session.submit_part(1, b"abcd") + session.reserve_commit() + committer = threading.Thread( + target=lambda: results.append(session.commit()), daemon=True + ) + committer.start() + try: + assert started.wait(5) + session.withdraw_commit() + assert session.state is S3WriteState.COMMITTING + finally: + release.set() + committer.join(5) + assert session.state is S3WriteState.COMMITTED + assert [type(result) for result in results] == [S3CompleteMultipartUpload] + assert requests.aborts == 0 + def test_multipart_state_error_is_the_write_state_error(): # GH-1455: the former name refers to the same class, so that code that From 3d20335a1699943a577435211e77f48f444ee514 Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Tue, 1 Dec 2026 01:45:25 +0900 Subject: [PATCH 4/8] Read the body and clean up inside the commit's eviction (GH-1455) The shared commit read the buffer before the block whose failure runs the file's cleanup, and evicted stale entries before that cleanup. The body is now read inside that block, and the cleanup runs inside the eviction, so that an entry cached while the upload is aborted is evicted too, as the async file did before the drivers were shared. The sync file passes no buffer to a multipart commit, which would keep it in the error's traceback. A reserved commit raises a failed part before it rejects its body. The docs say which fields prepared parameters must not give and that a Body of request_kwargs is sent when the commit has no body of its own. The order tests observe the cache of a filesystem instead of the calls, and a test covers an interrupt of the invalidation after a successful commit. Co-Authored-By: Claude Opus 5.5 --- docs/filesystem.md | 4 +- pyathena/filesystem/s3.py | 31 ++++--- pyathena/filesystem/s3_writer.py | 16 +++- tests/pyathena/filesystem/test_s3.py | 92 +++++++++++++++++---- tests/pyathena/filesystem/test_s3_async.py | 22 +++-- tests/pyathena/filesystem/test_s3_writer.py | 33 ++++++-- 6 files changed, 148 insertions(+), 50 deletions(-) diff --git a/docs/filesystem.md b/docs/filesystem.md index ddc3d860b..0ff88463e 100644 --- a/docs/filesystem.md +++ b/docs/filesystem.md @@ -1128,7 +1128,7 @@ with S3ThreadPool(max_workers=4) as executor: raise ``` -`start()` creates the multipart upload, which needs at least one part before `commit()`; without it, `commit(body)` writes `body` with PutObject, and `None` or empty bytes send no body, as with `S3Core.put_object()`. +`start()` creates the multipart upload, which needs at least one part before `commit()`; without it, `commit(body)` writes `body` with PutObject, and `None` or empty bytes send no body of their own, as with `S3Core.put_object()`. After `start()`, `commit()` completes the upload once its parts have been uploaded, and rejects a non-empty `body`. A successful commit returns its result again without another request. `ready()` returns a future, and `wait_ready()` blocks, until another part may be submitted. @@ -1141,7 +1141,7 @@ A driver that cannot block reserves the commit with `reserve_commit()` before it `commit_attempts` counts the commit requests that have started to be sent, including failed ones, which may have committed the object. The `request_kwargs` of the session are added to each request whose operation accepts them. -`prepared_params` gives the parameters of the requests of an operation by client method name, such as `create_multipart_upload`; they are sent as given, except for the fields that `S3Core` sets itself, such as the checksum algorithm of the upload, and replace the `request_kwargs` of the session for that operation. +`prepared_params` gives the parameters of the requests of an operation by client method name, such as `create_multipart_upload`; they are sent as given, must not give the fields that `S3Core` sets from the path, the upload, and the part, such as `Bucket` or `UploadId`, yield to those that it sets from the upload, such as its checksum algorithm, and replace the `request_kwargs` of the session for that operation. The session does not invalidate the filesystem cache; call `fs.invalidate_cache()` after a direct write. ### Multipart requests diff --git a/pyathena/filesystem/s3.py b/pyathena/filesystem/s3.py index 4af2435fe..2a634192a 100644 --- a/pyathena/filesystem/s3.py +++ b/pyathena/filesystem/s3.py @@ -5960,7 +5960,7 @@ def commit( Sends the buffered data with PutObject if the write started no multipart upload, and otherwise completes the upload (see :meth:`S3WriteSession.commit`). A failure that shows a cached entry - to be stale evicts it, and then runs ``on_failure``. Once a commit + to be stale evicts it once ``on_failure`` has run. Once a commit request has started to be sent since the last invalidation, the cache of the path is invalidated last, also when the request fails, since a request whose response is lost may have committed the @@ -5975,18 +5975,20 @@ def commit( is raised, such as the abort of the multipart upload. """ path = S3Path(self.bucket, self.key) - body = None - if buffer is not None and not session.multipart: - # None without data, which writes an empty object as well. - body = buffer.getvalue() or None try: - try: - with fs._evicting_stale(path): + # The eviction after the cleanup, so that an entry cached while + # the cleanup runs is evicted too. + with fs._evicting_stale(path): + try: + body = None + if buffer is not None and not session.multipart: + # None without data, which writes an empty object as well. + body = buffer.getvalue() or None session.commit(body) - except BaseException: - if on_failure is not None: - on_failure() - raise + except BaseException: + if on_failure is not None: + on_failure() + raise finally: if session.commit_attempts != self._invalidated_commit_attempts: # A commit refused, stopped, or ended by a failed part before @@ -6846,10 +6848,13 @@ def _commit(self) -> None: # A failed commit closes the file without the buffer, which a failed # write cannot commit again; for a multipart upload, it holds only # the data of the last part. + session = cast(S3WriteSession, self._session) self._target.commit( self.fs, - cast(S3WriteSession, self._session), - self.buffer, + session, + # A multipart upload has its data in its parts; the buffer, which + # the error of a failed commit would keep, is not passed. + None if session.multipart else self.buffer, on_failure=self._close_without_commit, ) diff --git a/pyathena/filesystem/s3_writer.py b/pyathena/filesystem/s3_writer.py index 265a628d2..646955684 100644 --- a/pyathena/filesystem/s3_writer.py +++ b/pyathena/filesystem/s3_writer.py @@ -431,8 +431,11 @@ def __init__( operations, by client method name, such as ``create_multipart_upload``, which are sent as given for that operation, so that botocore rejects one that the operation - does not accept, under the fields that the core sets itself, - such as the checksum algorithm of the upload. They replace + does not accept. They must not give the fields that the core + sets from the path, the upload and the part, such as + ``Bucket``, ``Key``, ``UploadId`` or ``PartNumber``, and + yield to those that it sets from the upload, such as its + checksum algorithm. They replace ``request_kwargs`` for that operation, whose requests still receive the ``request_kwargs`` of the core that the operation accepts. @@ -700,8 +703,9 @@ def commit(self, body: bytes | None = None) -> S3PutObject | S3CompleteMultipart """Commit the write. A write that started no multipart upload is committed with a single - PutObject request of ``body``; None or empty bytes send no body, so - an empty object is written, as :meth:`S3Core.put_object` writes it. + PutObject request of ``body``; None or empty bytes send no body of + their own, as with :meth:`S3Core.put_object`, which writes an empty + object unless the inherited parameters have ``Body``. A write that started one is committed by completing it, once its part requests have settled: the first failure among them is raised without waiting for the others. A failed or interrupted commit leaves @@ -748,6 +752,10 @@ def commit(self, body: bytes | None = None) -> S3PutObject | S3CompleteMultipart else: self._refuse_unless(state, operation="commit") if body and self._multipart: + if reserved: + # The first failure of a request, if any, before the + # error of the caller. + self._refuse_unless(S3WriteState.COMMITTING, operation="commit") raise ValueError( f"Cannot commit a body to {self._path.uri}: the write uploads its " "data as parts of a multipart upload." diff --git a/tests/pyathena/filesystem/test_s3.py b/tests/pyathena/filesystem/test_s3.py index bc1d7e3e2..a4627ad6f 100644 --- a/tests/pyathena/filesystem/test_s3.py +++ b/tests/pyathena/filesystem/test_s3.py @@ -61,7 +61,13 @@ from pyathena.filesystem.s3_core import S3Core, S3DeleteBatch, S3MultipartCopyPlan from pyathena.filesystem.s3_errors import S3ClientError from pyathena.filesystem.s3_executor import S3Executor, S3ThreadPool, _S3Batch, _S3PoolScope -from pyathena.filesystem.s3_object import S3MultipartUpload, S3Object, S3ObjectType, S3StorageClass +from pyathena.filesystem.s3_object import ( + S3MultipartUpload, + S3MultipartUploadPart, + S3Object, + S3ObjectType, + S3StorageClass, +) from pyathena.filesystem.s3_path import S3Path from pyathena.filesystem.s3_retry import raise_if_stopped from pyathena.filesystem.s3_writer import S3WriteSession, S3WriteState, S3WriteStateError @@ -9859,9 +9865,11 @@ def wait(self, timeout=None): assert interrupts == [True] assert logged_while_running == [True] - assert [(r.levelno, "uploadid" in r.getMessage()) for r in caplog.records] == [ - (logging.WARNING, True) - ] + assert [ + r.levelno + for r in caplog.records + if r.name == "pyathena.filesystem.s3_writer" and "uploadid" in r.getMessage() + ] == [logging.WARNING] fs.core.abort_multipart_upload.assert_not_called() @pytest.mark.parametrize( @@ -12210,7 +12218,7 @@ def test_write_session_refuses_a_version(self): version_id="v1", request_kwargs={}, ) - with pytest.raises(ValueError, match="Cannot write to a version"): + with pytest.raises(ValueError, match="version"): target.write_session( fs, mock.MagicMock(), @@ -13601,24 +13609,74 @@ def test_commit_failure_and_discard(self, abort_fails): assert file.multipart_upload is None assert file.completed_parts == () + @staticmethod + def _offline_write_fs(): + # A filesystem with its own cache whose write requests are mocked. + fs = S3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + fs.core.create_multipart_upload = mock.MagicMock( + return_value=S3MultipartUpload( + {"Bucket": "bucket", "Key": "key", "UploadId": "uploadid"} + ) + ) + fs.core.upload_part = mock.MagicMock( + side_effect=lambda **kw: S3MultipartUploadPart(kw["part_number"], {"ETag": '"e"'}) + ) + fs.core.complete_multipart_upload = mock.MagicMock() + fs.core.abort_multipart_upload = mock.MagicMock() + fs.core.put_object = mock.MagicMock() + return fs + def test_failed_commit_invalidates_after_the_abort(self): # GH-1455: a commit whose completion fails invalidates the cache of # the path after the abort of the upload, so that an entry cached # while the abort runs, which a completion that took effect despite # its failure makes stale, does not survive the commit. - file = self._make_multipart_write_file(b"x" * 16, autocommit=False) - file._upload_chunk(final=True) - order = [] - file.fs.core.complete_multipart_upload.side_effect = RuntimeError("complete failed") - file.fs.core.call.side_effect = lambda *args, **kwargs: order.append("abort") - with ( - mock.patch.object( - file.fs, "_invalidate", side_effect=lambda path: order.append("invalidate") - ), - pytest.raises(RuntimeError, match="complete failed"), - ): + fs = self._offline_write_fs() + path = S3Path("bucket", "key") + cached = S3Object( + init={"ContentLength": 1}, + type=S3ObjectType.S3_OBJECT_TYPE_FILE, + bucket="bucket", + key="key", + ) + fs.core.complete_multipart_upload.side_effect = RuntimeError("complete failed") + # A lookup that caches the object while the abort runs. + fs.core.abort_multipart_upload.side_effect = lambda *args, **kwargs: ( + fs._listing_cache.put_lookup(path, {}, cached) + ) + block_size = S3Core.MULTIPART_UPLOAD_MIN_PART_SIZE + file = fs.open("s3://bucket/key", "wb", block_size=block_size) + file.write(b"x" * block_size * 2) + with pytest.raises(RuntimeError, match="complete failed"): + file.close() + fs.core.abort_multipart_upload.assert_called_once() + assert fs._listing_cache.get_lookup(path, {}) is None + + def test_interrupted_invalidation_keeps_a_committed_file_open(self): + # GH-1455: an interrupt while the cache is invalidated after a + # successful commit of a force-flushed file is raised without closing + # the file, and a later commit sends no other request. + fs = self._offline_write_fs() + file = fs.open("s3://bucket/key", "wb", autocommit=False) + file.write(b"data") + file.flush(force=True) + invalidate = fs._invalidate + interrupts = [KeyboardInterrupt()] + + def interrupted_invalidate(path): + if interrupts: + raise interrupts.pop() + invalidate(path) + + with mock.patch.object(fs, "_invalidate", side_effect=interrupted_invalidate): + with pytest.raises(KeyboardInterrupt): + file.commit() + assert not file.closed file.commit() - assert order == ["abort", "invalidate"] + file.close() + fs.core.put_object.assert_called_once() def test_commit_stops_at_failed_part(self): # GH-1178: commit() raises a failed part without waiting for the parts diff --git a/tests/pyathena/filesystem/test_s3_async.py b/tests/pyathena/filesystem/test_s3_async.py index 271895e81..fe81667f4 100644 --- a/tests/pyathena/filesystem/test_s3_async.py +++ b/tests/pyathena/filesystem/test_s3_async.py @@ -6153,21 +6153,25 @@ async def test_failed_completion_invalidates_after_the_abort(self, fs): # a failed completion aborts the upload before the cache of the path # is invalidated. block_size = S3Core.MULTIPART_UPLOAD_MIN_PART_SIZE - order = [] + cache = fs._sync_fs._listing_cache + path = S3Path("bucket", "key") + cached = S3Object( + init={"ContentLength": 1}, + type=S3ObjectType.S3_OBJECT_TYPE_FILE, + bucket="bucket", + key="key", + ) fs.core.complete_multipart_upload = mock.MagicMock(side_effect=OSError("complete failed")) + # A lookup that caches the object while the abort runs. fs.core.abort_multipart_upload = mock.MagicMock( - side_effect=lambda *args, **kwargs: order.append("abort") + side_effect=lambda *args, **kwargs: cache.put_lookup(path, {}, cached) ) f = await fs.open_async("s3://bucket/key", "wb", block_size=block_size) await f.write(b"a" * block_size * 2) - with ( - mock.patch.object( - fs._sync_fs, "_invalidate", side_effect=lambda path: order.append("invalidate") - ), - pytest.raises(OSError, match="complete failed"), - ): + with pytest.raises(OSError, match="complete failed"): await await_bounded(f.close()) - assert order == ["abort", "invalidate"] + fs.core.abort_multipart_upload.assert_called_once() + assert cache.get_lookup(path, {}) is None @pytest.mark.asyncio async def test_close_cancelled_before_final_flush_aborts(self, fs): diff --git a/tests/pyathena/filesystem/test_s3_writer.py b/tests/pyathena/filesystem/test_s3_writer.py index 66bdf2f47..90245caa2 100644 --- a/tests/pyathena/filesystem/test_s3_writer.py +++ b/tests/pyathena/filesystem/test_s3_writer.py @@ -895,7 +895,7 @@ def test_commit_rejects_a_body_of_a_multipart_upload(self): ) _start(session) session.submit_part(1, b"abcd") - with pytest.raises(ValueError, match="Cannot commit a body"): + with pytest.raises(ValueError, match="body"): session.commit(b"efgh") assert (session.state, session.commit_attempts) == (S3WriteState.ACTIVE, 0) result = session.commit() @@ -955,9 +955,11 @@ def test_abort_or_log(self, interrupted, caplog): assert session.upload is not None session.abort_or_log() level = logging.WARNING if interrupted else logging.ERROR - assert [(r.levelno, "uploadid" in r.getMessage()) for r in caplog.records] == [ - (level, True) - ] + assert [ + r.levelno + for r in caplog.records + if r.name == "pyathena.filesystem.s3_writer" and "uploadid" in r.getMessage() + ] == [level] assert session.state is S3WriteState.ABORTED assert requests.aborts == 2 @@ -1010,13 +1012,34 @@ def test_rejected_body_of_a_reserved_commit_fails_the_write(self): _start(session) session.submit_part(1, b"abcd") session.reserve_commit() - with pytest.raises(ValueError, match="Cannot commit a body"): + with pytest.raises(ValueError, match="body"): session.commit(b"efgh") assert session.state is S3WriteState.FAILED session.abort() assert session.state is S3WriteState.ABORTED assert (requests.completed, requests.aborts) == ([], 1) + def test_rejected_body_of_a_reserved_commit_raises_a_failed_part(self): + # GH-1455: a part that failed after the commit was reserved is raised + # by the commit that takes the reservation, before the rejection of + # its body, as the completion would raise it. + gate = threading.Event() + executor = S3ThreadPool(max_workers=1) + session, requests = _make_session( + executor, gate=gate, part_errors={1: PermissionError("denied")} + ) + _start(session) + session.submit_part(1, b"abcd") + session.reserve_commit() + gate.set() + # Waits for the part, and the record of its failure, to end. + call_bounded(executor.shutdown) + with pytest.raises(PermissionError, match="denied"): + session.commit(b"efgh") + assert session.state is S3WriteState.FAILED + session.abort() + assert (requests.completed, requests.aborts) == ([], 1) + @pytest.mark.parametrize("reserved", [False, True]) def test_commit_ends_the_waits_of_ready(self, reserved): # GH-1455: once the write is being committed, no part can be From 8695cc585f198c994e1c246966edae4a8cc1b771 Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Tue, 1 Dec 2026 02:10:53 +0900 Subject: [PATCH 5/8] Evict around the cleanup, and pass the effective core (GH-1455) A failed commit evicts the entries that its error shows to be stale before the cleanup, which an interrupt may end, and again after it, for an entry cached while the upload was aborted. A commit that fails before the session takes its reservation, such as on a closed buffer, withdraws the reservation. A reserved commit consumes finished part requests before it rejects a body, so that a part failure whose callback has not run is raised first. S3FileTarget.write_session() and iter_append_copies() take the core of the file's filesystem, so that the async file sends through the core of AioS3FileSystem, as before the drivers were shared. The docs name the payload parameters that only PutObject inherits and the Body that a commit without a body sends. Co-Authored-By: Claude Opus 5.5 --- docs/filesystem.md | 4 +- pyathena/filesystem/s3.py | 42 ++++++++------ pyathena/filesystem/s3_async.py | 4 +- pyathena/filesystem/s3_writer.py | 14 +++-- tests/pyathena/filesystem/test_s3.py | 64 +++++++++++++++++++-- tests/pyathena/filesystem/test_s3_writer.py | 41 +++++++------ 6 files changed, 123 insertions(+), 46 deletions(-) diff --git a/docs/filesystem.md b/docs/filesystem.md index 0ff88463e..630586a23 100644 --- a/docs/filesystem.md +++ b/docs/filesystem.md @@ -1128,7 +1128,7 @@ with S3ThreadPool(max_workers=4) as executor: raise ``` -`start()` creates the multipart upload, which needs at least one part before `commit()`; without it, `commit(body)` writes `body` with PutObject, and `None` or empty bytes send no body of their own, as with `S3Core.put_object()`. +`start()` creates the multipart upload, which needs at least one part before `commit()`; without it, `commit(body)` writes `body` with PutObject, and `None` or empty bytes send no body of their own, as with `S3Core.put_object()`, so a `Body` in `request_kwargs` or in the prepared parameters of `put_object` is sent instead. After `start()`, `commit()` completes the upload once its parts have been uploaded, and rejects a non-empty `body`. A successful commit returns its result again without another request. `ready()` returns a future, and `wait_ready()` blocks, until another part may be submitted. @@ -1140,7 +1140,7 @@ A successful commit returns its result again without another request. A driver that cannot block reserves the commit with `reserve_commit()` before it queues the call to `commit()`, withdraws the reservation with `withdraw_commit()` if that call never runs, and begins an abort with `begin_abort()`. `commit_attempts` counts the commit requests that have started to be sent, including failed ones, which may have committed the object. -The `request_kwargs` of the session are added to each request whose operation accepts them. +The `request_kwargs` of the session are added to each request whose operation accepts them, except those that describe the payload of the object, such as `ContentMD5`, which `S3Core` sends with PutObject only (see `S3Core.call()`). `prepared_params` gives the parameters of the requests of an operation by client method name, such as `create_multipart_upload`; they are sent as given, must not give the fields that `S3Core` sets from the path, the upload, and the part, such as `Bucket` or `UploadId`, yield to those that it sets from the upload, such as its checksum algorithm, and replace the `request_kwargs` of the session for that operation. The session does not invalidate the filesystem cache; call `fs.invalidate_cache()` after a direct write. diff --git a/pyathena/filesystem/s3.py b/pyathena/filesystem/s3.py index 2a634192a..56f94f1f1 100644 --- a/pyathena/filesystem/s3.py +++ b/pyathena/filesystem/s3.py @@ -5892,7 +5892,7 @@ def read_range(self, fs: S3FileSystem, core: S3Core, range_: tuple[int, int], /) return core.get_object(path, range_) def write_session( - self, fs: S3FileSystem, executor: S3Executor, *, block_size: int, max_workers: int + self, core: S3Core, executor: S3Executor, *, block_size: int, max_workers: int ) -> S3WriteSession: """Create the session of a write of the object, without sending any request. @@ -5901,7 +5901,7 @@ def write_session( commits have invalidated the cache, which a new session starts over. Args: - fs: The filesystem, whose core sends the requests. + core: The core of the filesystem, which sends the requests. executor: The executor of the creation and part requests. block_size: The block size of the file. max_workers: The number of part requests of the file in flight. @@ -5917,7 +5917,7 @@ def write_session( """ self._invalidated_commit_attempts = 0 return S3WriteSession( - fs.core, + core, S3Path(self.bucket, self.key, self.version_id), executor, block_size=block_size, @@ -5926,12 +5926,12 @@ def write_session( ) def iter_append_copies( - self, fs: S3FileSystem, session: S3WriteSession + self, core: S3Core, session: S3WriteSession ) -> Iterator[tuple[int, tuple[int, int] | None]]: """Plan the part copies of the appended object, which lead the multipart upload. Args: - fs: The filesystem, whose core limits the parts. + core: The core of the filesystem, which limits the parts. session: The session of the write, which numbers the parts. Yields: @@ -5942,9 +5942,9 @@ def iter_append_copies( which the file rewrites from its buffer (see ``append_data``). """ size = self.appended.get("size", 0) if self.appended is not None else 0 - if size < fs.core.MULTIPART_UPLOAD_MIN_PART_SIZE: + if size < core.MULTIPART_UPLOAD_MIN_PART_SIZE: return - whole_source = size <= fs.core.MULTIPART_UPLOAD_MAX_PART_SIZE + whole_source = size <= core.MULTIPART_UPLOAD_MAX_PART_SIZE for part_number, range_ in session.iter_copy_parts(size): yield part_number, None if whole_source else range_ @@ -5960,7 +5960,11 @@ def commit( Sends the buffered data with PutObject if the write started no multipart upload, and otherwise completes the upload (see :meth:`S3WriteSession.commit`). A failure that shows a cached entry - to be stale evicts it once ``on_failure`` has run. Once a commit + to be stale evicts it before ``on_failure`` runs, and again once it + has run, for an entry cached meanwhile. A commit reserved with + :meth:`S3WriteSession.reserve_commit` that the failure kept from + taking its reservation, such as a failed read of the buffer, is + withdrawn. Once a commit request has started to be sent since the last invalidation, the cache of the path is invalidated last, also when the request fails, since a request whose response is lost may have committed the @@ -5976,16 +5980,18 @@ def commit( """ path = S3Path(self.bucket, self.key) try: - # The eviction after the cleanup, so that an entry cached while - # the cleanup runs is evicted too. + # Evicts again after the cleanup, for an entry cached meanwhile. with fs._evicting_stale(path): try: - body = None - if buffer is not None and not session.multipart: - # None without data, which writes an empty object as well. - body = buffer.getvalue() or None - session.commit(body) + # Evicts before the cleanup, which an interrupt may end. + with fs._evicting_stale(path): + body = None + if buffer is not None and not session.multipart: + # None without data, which writes an empty object as well. + body = buffer.getvalue() or None + session.commit(body) except BaseException: + session.withdraw_commit() if on_failure is not None: on_failure() raise @@ -6160,7 +6166,7 @@ def __init__( self._session: S3WriteSession | None = None if mode != "rb": self._session = target.write_session( - fs, self._executor, block_size=block_size, max_workers=max_workers + fs.core, self._executor, block_size=block_size, max_workers=max_workers ) negative_read_block = mode == "rb" and isinstance(block_size, int) and block_size < 0 super().__init__( @@ -6712,7 +6718,9 @@ def _initiate_upload(self) -> None: if self.append_block: # Copies the object looked up when opening, on which the # part copies are conditional. - for part_number, range_ in self._target.iter_append_copies(self.fs, session): + for part_number, range_ in self._target.iter_append_copies( + self.fs.core, session + ): # The part copies count toward max_workers, as the # parts do. session.wait_ready() diff --git a/pyathena/filesystem/s3_async.py b/pyathena/filesystem/s3_async.py index 3274bfca7..673a46c6f 100644 --- a/pyathena/filesystem/s3_async.py +++ b/pyathena/filesystem/s3_async.py @@ -2667,7 +2667,7 @@ def __init__( self._session: S3WriteSession | None = None if mode != "rb": self._session = target.write_session( - fs._sync_fs, self._requests, block_size=block_size, max_workers=self.max_workers + fs.core, self._requests, block_size=block_size, max_workers=self.max_workers ) if target.appended is not None: if target.append_data is not None: @@ -3237,7 +3237,7 @@ async def _initiate_upload(self) -> None: self.fs._invalidate_upload_listings(path) if self.append_block: for part_number, range_ in self._target.iter_append_copies( - self.fs._sync_fs, session + self.fs.core, session ): # The part copies count toward max_workers, as the # parts do. diff --git a/pyathena/filesystem/s3_writer.py b/pyathena/filesystem/s3_writer.py index 646955684..013a58750 100644 --- a/pyathena/filesystem/s3_writer.py +++ b/pyathena/filesystem/s3_writer.py @@ -424,7 +424,10 @@ def __init__( :meth:`ready` waits for one of them to finish. request_kwargs: Parameters inherited by each request that accepts them, which the core adds under the fields of the request - (see :meth:`S3Core.with_request_kwargs`). The mapping is read + (see :meth:`S3Core.with_request_kwargs`), except those that + describe the payload of the object, such as ``ContentMD5``, + which it sends with PutObject only (see :meth:`S3Core.call`). + The mapping is read when each request is sent, so later changes to it apply to the requests that follow. prepared_params: The parameters of the requests of some @@ -705,7 +708,8 @@ def commit(self, body: bytes | None = None) -> S3PutObject | S3CompleteMultipart A write that started no multipart upload is committed with a single PutObject request of ``body``; None or empty bytes send no body of their own, as with :meth:`S3Core.put_object`, which writes an empty - object unless the inherited parameters have ``Body``. + object unless ``request_kwargs`` or the prepared parameters of + ``put_object`` give ``Body``. A write that started one is committed by completing it, once its part requests have settled: the first failure among them is raised without waiting for the others. A failed or interrupted commit leaves @@ -753,8 +757,10 @@ def commit(self, body: bytes | None = None) -> S3PutObject | S3CompleteMultipart self._refuse_unless(state, operation="commit") if body and self._multipart: if reserved: - # The first failure of a request, if any, before the - # error of the caller. + # The first failure of a request, if any, also of one + # whose callback has not run yet, before the error of + # the caller. + self._consume_finished() self._refuse_unless(S3WriteState.COMMITTING, operation="commit") raise ValueError( f"Cannot commit a body to {self._path.uri}: the write uploads its " diff --git a/tests/pyathena/filesystem/test_s3.py b/tests/pyathena/filesystem/test_s3.py index a4627ad6f..477d35b3d 100644 --- a/tests/pyathena/filesystem/test_s3.py +++ b/tests/pyathena/filesystem/test_s3.py @@ -12220,12 +12220,34 @@ def test_write_session_refuses_a_version(self): ) with pytest.raises(ValueError, match="version"): target.write_session( - fs, + fs.core, mock.MagicMock(), block_size=S3Core.MULTIPART_UPLOAD_MIN_PART_SIZE, max_workers=1, ) + def test_commit_withdraws_a_reservation_that_it_did_not_take(self): + # GH-1455: a commit that fails before the session takes the reserved + # commit, such as on a closed buffer, withdraws the reservation, so + # that the write fails instead of waiting for a commit that nothing + # sends. + fs = S3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + target = self._target() + session = target.write_session( + fs.core, + mock.MagicMock(), + block_size=S3Core.MULTIPART_UPLOAD_MIN_PART_SIZE, + max_workers=1, + ) + session.reserve_commit() + buffer = io.BytesIO(b"data") + buffer.close() + with pytest.raises(ValueError, match="closed"): + target.commit(fs, session, buffer) + assert session.state is S3WriteState.FAILED + @pytest.mark.parametrize(("size", "copies"), [(3, []), (4, [(1, None)]), (8, [(1, None)])]) def test_iter_append_copies(self, size, copies): # GH-1455: an appended object smaller than the minimum part size is @@ -12249,8 +12271,8 @@ def test_iter_append_copies(self, size, copies): key="key", ), ) - session = target.write_session(fs, mock.MagicMock(), block_size=4, max_workers=1) - assert list(target.iter_append_copies(fs, session)) == copies + session = target.write_session(fs.core, mock.MagicMock(), block_size=4, max_workers=1) + assert list(target.iter_append_copies(fs.core, session)) == copies @pytest.mark.parametrize( ("start", "end", "block_size", "max_workers", "size", "ranges"), @@ -12664,7 +12686,7 @@ def _make_write_file(data: bytes, autocommit: bool, *, block_size=None, executor path=file.path, bucket=file.bucket, key=file.key, version_id=None, request_kwargs={} ) file._session = file._target.write_session( - file.fs, file._executor, block_size=file.blocksize, max_workers=file.max_workers + file.fs.core, file._executor, block_size=file.blocksize, max_workers=file.max_workers ) return file @@ -13654,6 +13676,40 @@ def test_failed_commit_invalidates_after_the_abort(self): fs.core.abort_multipart_upload.assert_called_once() assert fs._listing_cache.get_lookup(path, {}) is None + @pytest.mark.parametrize("cached", ["before the commit", "during the abort"]) + def test_missing_bucket_of_a_failed_commit_is_evicted(self, cached): + # GH-1455: a completion that finds the bucket missing evicts the + # bucket's entries before the cleanup aborts the upload, also when an + # interrupt ends that abort, and again once the abort has run, for an + # entry cached meanwhile. + fs = self._offline_write_fs() + sibling = S3Path("bucket", "other") + entry = S3Object( + init={"ContentLength": 1}, + type=S3ObjectType.S3_OBJECT_TYPE_FILE, + bucket="bucket", + key="other", + ) + fs.core.complete_multipart_upload.side_effect = s3_client_error( + "NoSuchBucket", 404, bucket_name="bucket" + ) + if cached == "before the commit": + fs._listing_cache.put_lookup(sibling, {}, entry) + fs.core.abort_multipart_upload.side_effect = KeyboardInterrupt + raised = KeyboardInterrupt + else: + fs.core.abort_multipart_upload.side_effect = lambda *args, **kwargs: ( + fs._listing_cache.put_lookup(sibling, {}, entry) + ) + raised = FileNotFoundError + block_size = S3Core.MULTIPART_UPLOAD_MIN_PART_SIZE + file = fs.open("s3://bucket/key", "wb", block_size=block_size) + file.write(b"x" * block_size * 2) + with pytest.raises(raised): + file.close() + fs.core.abort_multipart_upload.assert_called_once() + assert fs._listing_cache.get_lookup(sibling, {}) is None + def test_interrupted_invalidation_keeps_a_committed_file_open(self): # GH-1455: an interrupt while the cache is invalidated after a # successful commit of a force-flushed file is raised without closing diff --git a/tests/pyathena/filesystem/test_s3_writer.py b/tests/pyathena/filesystem/test_s3_writer.py index 90245caa2..5e5df6572 100644 --- a/tests/pyathena/filesystem/test_s3_writer.py +++ b/tests/pyathena/filesystem/test_s3_writer.py @@ -858,7 +858,7 @@ def abort_in_another_thread(): ("multipart", "body", "puts", "completed"), [ (False, None, [None], []), - (False, b"", [b""], []), + (False, b"", [None], []), (False, b"data", [b"data"], []), (True, None, [], [[1]]), (True, b"", [], [[1]]), @@ -881,7 +881,8 @@ def test_commit_follows_the_state(self, multipart, body, puts, completed): assert isinstance(result, S3CompleteMultipartUpload if multipart else S3PutObject) assert session.state is S3WriteState.COMMITTED assert session.commit_attempts == 1 - assert (requests.puts, requests.completed) == (puts, completed) + # Empty bytes and None send the same request. + assert ([body or None for body in requests.puts], requests.completed) == (puts, completed) def test_commit_rejects_a_body_of_a_multipart_upload(self): # GH-1455: the data of a multipart upload is in its parts; a body @@ -1022,22 +1023,28 @@ def test_rejected_body_of_a_reserved_commit_fails_the_write(self): def test_rejected_body_of_a_reserved_commit_raises_a_failed_part(self): # GH-1455: a part that failed after the commit was reserved is raised # by the commit that takes the reservation, before the rejection of - # its body, as the completion would raise it. + # its body, as the completion would raise it, also before the + # callback of the part has recorded the failure. gate = threading.Event() - executor = S3ThreadPool(max_workers=1) - session, requests = _make_session( - executor, gate=gate, part_errors={1: PermissionError("denied")} - ) - _start(session) - session.submit_part(1, b"abcd") - session.reserve_commit() - gate.set() - # Waits for the part, and the record of its failure, to end. - call_bounded(executor.shutdown) - with pytest.raises(PermissionError, match="denied"): - session.commit(b"efgh") - assert session.state is S3WriteState.FAILED - session.abort() + called = threading.Semaphore(0) + with S3ThreadPool(max_workers=1) as executor: + session, requests = _make_session( + executor, gate=gate, part_errors={1: PermissionError("denied")} + ) + _start(session) + # The callback of the part is deferred, so that only the commit + # can find the failure. + with mock.patch.object( + session, "_on_part_done", side_effect=lambda request: called.release() + ): + session.submit_part(1, b"abcd") + session.reserve_commit() + gate.set() + assert called.acquire(timeout=5) + with pytest.raises(PermissionError, match="denied"): + session.commit(b"efgh") + assert session.state is S3WriteState.FAILED + session.abort() assert (requests.completed, requests.aborts) == ([], 1) @pytest.mark.parametrize("reserved", [False, True]) From 91dd6bd91ddc432de39775a1add1391ee49ef525 Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Tue, 1 Dec 2026 02:31:17 +0900 Subject: [PATCH 6/8] Plan append copies as resolved, and raise failed parts first (GH-1455) iter_append_copies() decided with the limits of the core it was given whether an appended object is rewritten from the buffer, which resolve() had decided with the limits of the filesystem; with different limits, an appended object could be neither copied nor rewritten. It now plans the copies of the appended object, for one that resolve() did not read into append_data, as the files call it. Any commit, reserved or not, consumes finished part requests and raises a failed part before it rejects a body. The docs name the checksums that the completion of a FULL_OBJECT upload inherits and the parameters from which a PutObject without a body takes its Body. Co-Authored-By: Claude Opus 5.5 --- docs/filesystem.md | 4 ++-- pyathena/filesystem/s3.py | 10 ++++---- pyathena/filesystem/s3_writer.py | 22 ++++++++++------- tests/pyathena/filesystem/test_s3.py | 26 --------------------- tests/pyathena/filesystem/test_s3_writer.py | 14 ++++++----- 5 files changed, 28 insertions(+), 48 deletions(-) diff --git a/docs/filesystem.md b/docs/filesystem.md index 630586a23..529517417 100644 --- a/docs/filesystem.md +++ b/docs/filesystem.md @@ -1128,7 +1128,7 @@ with S3ThreadPool(max_workers=4) as executor: raise ``` -`start()` creates the multipart upload, which needs at least one part before `commit()`; without it, `commit(body)` writes `body` with PutObject, and `None` or empty bytes send no body of their own, as with `S3Core.put_object()`, so a `Body` in `request_kwargs` or in the prepared parameters of `put_object` is sent instead. +`start()` creates the multipart upload, which needs at least one part before `commit()`; without it, `commit(body)` writes `body` with PutObject, and `None` or empty bytes send no body of their own, as with `S3Core.put_object()`, so a `Body` among the parameters of that PutObject request is sent instead: the prepared parameters of `put_object`, if any, or else the `request_kwargs` of the session, and those of the core. After `start()`, `commit()` completes the upload once its parts have been uploaded, and rejects a non-empty `body`. A successful commit returns its result again without another request. `ready()` returns a future, and `wait_ready()` blocks, until another part may be submitted. @@ -1140,7 +1140,7 @@ A successful commit returns its result again without another request. A driver that cannot block reserves the commit with `reserve_commit()` before it queues the call to `commit()`, withdraws the reservation with `withdraw_commit()` if that call never runs, and begins an abort with `begin_abort()`. `commit_attempts` counts the commit requests that have started to be sent, including failed ones, which may have committed the object. -The `request_kwargs` of the session are added to each request whose operation accepts them, except those that describe the payload of the object, such as `ContentMD5`, which `S3Core` sends with PutObject only (see `S3Core.call()`). +The `request_kwargs` of the session are added to each request whose operation accepts them, except those that describe the payload of the object, such as `ContentMD5`, which `S3Core` sends with PutObject only, and, as the checksums of a `FULL_OBJECT` upload, with its completion (see `S3Core.call()`). `prepared_params` gives the parameters of the requests of an operation by client method name, such as `create_multipart_upload`; they are sent as given, must not give the fields that `S3Core` sets from the path, the upload, and the part, such as `Bucket` or `UploadId`, yield to those that it sets from the upload, such as its checksum algorithm, and replace the `request_kwargs` of the session for that operation. The session does not invalidate the filesystem cache; call `fs.invalidate_cache()` after a direct write. diff --git a/pyathena/filesystem/s3.py b/pyathena/filesystem/s3.py index 56f94f1f1..13ba5205a 100644 --- a/pyathena/filesystem/s3.py +++ b/pyathena/filesystem/s3.py @@ -5930,6 +5930,10 @@ def iter_append_copies( ) -> Iterator[tuple[int, tuple[int, int] | None]]: """Plan the part copies of the appended object, which lead the multipart upload. + For an appended object that the file copies, which :meth:`resolve` + leaves without ``append_data``; one that it reads into + ``append_data`` is rewritten from the buffer of the file instead. + Args: core: The core of the filesystem, which limits the parts. session: The session of the write, which numbers the parts. @@ -5937,13 +5941,9 @@ def iter_append_copies( Yields: The part number and the source range of each copy, with an exclusive end, or None to copy an object that fits in one part - whole. Nothing if no object is appended, or if the appended - object is smaller than ``S3Core.MULTIPART_UPLOAD_MIN_PART_SIZE``, - which the file rewrites from its buffer (see ``append_data``). + whole. Nothing if no object is appended. """ size = self.appended.get("size", 0) if self.appended is not None else 0 - if size < core.MULTIPART_UPLOAD_MIN_PART_SIZE: - return whole_source = size <= core.MULTIPART_UPLOAD_MAX_PART_SIZE for part_number, range_ in session.iter_copy_parts(size): yield part_number, None if whole_source else range_ diff --git a/pyathena/filesystem/s3_writer.py b/pyathena/filesystem/s3_writer.py index 013a58750..6d978a65a 100644 --- a/pyathena/filesystem/s3_writer.py +++ b/pyathena/filesystem/s3_writer.py @@ -426,7 +426,9 @@ def __init__( them, which the core adds under the fields of the request (see :meth:`S3Core.with_request_kwargs`), except those that describe the payload of the object, such as ``ContentMD5``, - which it sends with PutObject only (see :meth:`S3Core.call`). + which it sends with PutObject only, and, for the checksums of + a ``FULL_OBJECT`` upload, with its completion (see + :meth:`S3Core.call`). The mapping is read when each request is sent, so later changes to it apply to the requests that follow. @@ -708,8 +710,9 @@ def commit(self, body: bytes | None = None) -> S3PutObject | S3CompleteMultipart A write that started no multipart upload is committed with a single PutObject request of ``body``; None or empty bytes send no body of their own, as with :meth:`S3Core.put_object`, which writes an empty - object unless ``request_kwargs`` or the prepared parameters of - ``put_object`` give ``Body``. + object unless the parameters of the PutObject request give ``Body``: + the prepared parameters of ``put_object``, if any, or else + ``request_kwargs``, and the ``request_kwargs`` of the core. A write that started one is committed by completing it, once its part requests have settled: the first failure among them is raised without waiting for the others. A failed or interrupted commit leaves @@ -756,12 +759,13 @@ def commit(self, body: bytes | None = None) -> S3PutObject | S3CompleteMultipart else: self._refuse_unless(state, operation="commit") if body and self._multipart: - if reserved: - # The first failure of a request, if any, also of one - # whose callback has not run yet, before the error of - # the caller. - self._consume_finished() - self._refuse_unless(S3WriteState.COMMITTING, operation="commit") + # The first failure of a request, if any, also of one + # whose callback has not run yet, before the error of the + # caller. + self._consume_finished() + self._refuse_unless( + S3WriteState.COMMITTING if reserved else state, operation="commit" + ) raise ValueError( f"Cannot commit a body to {self._path.uri}: the write uploads its " "data as parts of a multipart upload." diff --git a/tests/pyathena/filesystem/test_s3.py b/tests/pyathena/filesystem/test_s3.py index 477d35b3d..36074b2f9 100644 --- a/tests/pyathena/filesystem/test_s3.py +++ b/tests/pyathena/filesystem/test_s3.py @@ -12248,32 +12248,6 @@ def test_commit_withdraws_a_reservation_that_it_did_not_take(self): target.commit(fs, session, buffer) assert session.state is S3WriteState.FAILED - @pytest.mark.parametrize(("size", "copies"), [(3, []), (4, [(1, None)]), (8, [(1, None)])]) - def test_iter_append_copies(self, size, copies): - # GH-1455: an appended object smaller than the minimum part size is - # rewritten from the buffer of the file, so it has no part copy; a - # larger one that fits in a part is copied whole. - fs = S3FileSystem( - key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True - ) - fs.core.MULTIPART_UPLOAD_MIN_PART_SIZE = 4 - fs.core.MULTIPART_UPLOAD_MAX_PART_SIZE = 8 - target = S3FileTarget( - path="bucket/key", - bucket="bucket", - key="key", - version_id=None, - request_kwargs={}, - appended=S3Object( - init={"ContentLength": size}, - type=S3ObjectType.S3_OBJECT_TYPE_FILE, - bucket="bucket", - key="key", - ), - ) - session = target.write_session(fs.core, mock.MagicMock(), block_size=4, max_workers=1) - assert list(target.iter_append_copies(fs.core, session)) == copies - @pytest.mark.parametrize( ("start", "end", "block_size", "max_workers", "size", "ranges"), [ diff --git a/tests/pyathena/filesystem/test_s3_writer.py b/tests/pyathena/filesystem/test_s3_writer.py index 5e5df6572..d3b4405a2 100644 --- a/tests/pyathena/filesystem/test_s3_writer.py +++ b/tests/pyathena/filesystem/test_s3_writer.py @@ -1020,11 +1020,12 @@ def test_rejected_body_of_a_reserved_commit_fails_the_write(self): assert session.state is S3WriteState.ABORTED assert (requests.completed, requests.aborts) == ([], 1) - def test_rejected_body_of_a_reserved_commit_raises_a_failed_part(self): - # GH-1455: a part that failed after the commit was reserved is raised - # by the commit that takes the reservation, before the rejection of - # its body, as the completion would raise it, also before the - # callback of the part has recorded the failure. + @pytest.mark.parametrize("reserved", [False, True]) + def test_rejected_body_raises_a_failed_part(self, reserved): + # GH-1455: a failed part is raised by a commit, also one that takes a + # reservation, before the rejection of its body, as the completion + # would raise it, also before the callback of the part has recorded + # the failure. gate = threading.Event() called = threading.Semaphore(0) with S3ThreadPool(max_workers=1) as executor: @@ -1038,7 +1039,8 @@ def test_rejected_body_of_a_reserved_commit_raises_a_failed_part(self): session, "_on_part_done", side_effect=lambda request: called.release() ): session.submit_part(1, b"abcd") - session.reserve_commit() + if reserved: + session.reserve_commit() gate.set() assert called.acquire(timeout=5) with pytest.raises(PermissionError, match="denied"): From ba0c127eea582928fd254ab278c194c443b6b0e3 Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Tue, 1 Dec 2026 02:51:04 +0900 Subject: [PATCH 7/8] Plan whole append copies from the session's ranges (GH-1455) iter_append_copies() took the core whose maximum part size decided whether the appended object is copied whole, apart from the session that plans the ranges; with different limits, every range was copied whole. It now takes only the session, and copies the object whole when the session plans it as one part. A test covers the boundary at the maximum part size. The docs say that prepared parameters of put_object replace the session's request_kwargs also as an empty mapping. Co-Authored-By: Claude Opus 5.5 --- docs/filesystem.md | 2 +- pyathena/filesystem/s3.py | 16 ++++++------- pyathena/filesystem/s3_async.py | 4 +--- pyathena/filesystem/s3_writer.py | 5 ++-- tests/pyathena/filesystem/test_s3.py | 35 ++++++++++++++++++++++++++++ 5 files changed, 48 insertions(+), 14 deletions(-) diff --git a/docs/filesystem.md b/docs/filesystem.md index 529517417..af78c6fa8 100644 --- a/docs/filesystem.md +++ b/docs/filesystem.md @@ -1128,7 +1128,7 @@ with S3ThreadPool(max_workers=4) as executor: raise ``` -`start()` creates the multipart upload, which needs at least one part before `commit()`; without it, `commit(body)` writes `body` with PutObject, and `None` or empty bytes send no body of their own, as with `S3Core.put_object()`, so a `Body` among the parameters of that PutObject request is sent instead: the prepared parameters of `put_object`, if any, or else the `request_kwargs` of the session, and those of the core. +`start()` creates the multipart upload, which needs at least one part before `commit()`; without it, `commit(body)` writes `body` with PutObject, and `None` or empty bytes send no body of their own, as with `S3Core.put_object()`, so a `Body` among the parameters of that PutObject request is sent instead: the prepared parameters of `put_object`, which replace the `request_kwargs` of the session when the session has them, also as an empty mapping, and the `request_kwargs` of the core. After `start()`, `commit()` completes the upload once its parts have been uploaded, and rejects a non-empty `body`. A successful commit returns its result again without another request. `ready()` returns a future, and `wait_ready()` blocks, until another part may be submitted. diff --git a/pyathena/filesystem/s3.py b/pyathena/filesystem/s3.py index 13ba5205a..72ac34b63 100644 --- a/pyathena/filesystem/s3.py +++ b/pyathena/filesystem/s3.py @@ -5926,7 +5926,7 @@ def write_session( ) def iter_append_copies( - self, core: S3Core, session: S3WriteSession + self, session: S3WriteSession ) -> Iterator[tuple[int, tuple[int, int] | None]]: """Plan the part copies of the appended object, which lead the multipart upload. @@ -5935,8 +5935,8 @@ def iter_append_copies( ``append_data`` is rewritten from the buffer of the file instead. Args: - core: The core of the filesystem, which limits the parts. - session: The session of the write, which numbers the parts. + session: The session of the write, which plans and numbers the + parts. Yields: The part number and the source range of each copy, with an @@ -5944,8 +5944,10 @@ def iter_append_copies( whole. Nothing if no object is appended. """ size = self.appended.get("size", 0) if self.appended is not None else 0 - whole_source = size <= core.MULTIPART_UPLOAD_MAX_PART_SIZE - for part_number, range_ in session.iter_copy_parts(size): + parts = list(session.iter_copy_parts(size)) + # An object planned as one part is copied whole. + whole_source = len(parts) == 1 + for part_number, range_ in parts: yield part_number, None if whole_source else range_ def commit( @@ -6718,9 +6720,7 @@ def _initiate_upload(self) -> None: if self.append_block: # Copies the object looked up when opening, on which the # part copies are conditional. - for part_number, range_ in self._target.iter_append_copies( - self.fs.core, session - ): + for part_number, range_ in self._target.iter_append_copies(session): # The part copies count toward max_workers, as the # parts do. session.wait_ready() diff --git a/pyathena/filesystem/s3_async.py b/pyathena/filesystem/s3_async.py index 673a46c6f..c08d6dc3e 100644 --- a/pyathena/filesystem/s3_async.py +++ b/pyathena/filesystem/s3_async.py @@ -3236,9 +3236,7 @@ async def _initiate_upload(self) -> None: session.check() self.fs._invalidate_upload_listings(path) if self.append_block: - for part_number, range_ in self._target.iter_append_copies( - self.fs.core, session - ): + for part_number, range_ in self._target.iter_append_copies(session): # The part copies count toward max_workers, as the # parts do. await self._wait_ready() diff --git a/pyathena/filesystem/s3_writer.py b/pyathena/filesystem/s3_writer.py index 6d978a65a..cb998fe78 100644 --- a/pyathena/filesystem/s3_writer.py +++ b/pyathena/filesystem/s3_writer.py @@ -711,8 +711,9 @@ def commit(self, body: bytes | None = None) -> S3PutObject | S3CompleteMultipart PutObject request of ``body``; None or empty bytes send no body of their own, as with :meth:`S3Core.put_object`, which writes an empty object unless the parameters of the PutObject request give ``Body``: - the prepared parameters of ``put_object``, if any, or else - ``request_kwargs``, and the ``request_kwargs`` of the core. + the prepared parameters of ``put_object``, which, if the session has + them, also as an empty mapping, replace ``request_kwargs``, and the + ``request_kwargs`` of the core. A write that started one is committed by completing it, once its part requests have settled: the first failure among them is raised without waiting for the others. A failed or interrupted commit leaves diff --git a/tests/pyathena/filesystem/test_s3.py b/tests/pyathena/filesystem/test_s3.py index 36074b2f9..f27706a9e 100644 --- a/tests/pyathena/filesystem/test_s3.py +++ b/tests/pyathena/filesystem/test_s3.py @@ -12226,6 +12226,41 @@ def test_write_session_refuses_a_version(self): max_workers=1, ) + @pytest.mark.parametrize(("size", "whole"), [(4, True), (8, True), (9, False)]) + def test_iter_append_copies(self, size, whole): + # GH-1455: an appended object up to the maximum part size is copied + # whole, without a range; a larger one is copied in ranges that + # cover it. + fs = S3FileSystem( + key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True + ) + fs.core.MULTIPART_UPLOAD_MIN_PART_SIZE = 4 + fs.core.MULTIPART_UPLOAD_MAX_PART_SIZE = 8 + target = S3FileTarget( + path="bucket/key", + bucket="bucket", + key="key", + version_id=None, + request_kwargs={}, + appended=S3Object( + init={"ContentLength": size}, + type=S3ObjectType.S3_OBJECT_TYPE_FILE, + bucket="bucket", + key="key", + ), + ) + session = target.write_session(fs.core, mock.MagicMock(), block_size=4, max_workers=1) + copies = list(target.iter_append_copies(session)) + if whole: + assert copies == [(1, None)] + else: + assert [number for number, _ in copies] == list(range(1, len(copies) + 1)) + assert len(copies) > 1 + ranges = [range_ for _, range_ in copies] + assert ranges[0][0] == 0 + assert ranges[-1][1] == size + assert all(a[1] == b[0] for a, b in itertools.pairwise(ranges)) + def test_commit_withdraws_a_reservation_that_it_did_not_take(self): # GH-1455: a commit that fails before the session takes the reserved # commit, such as on a closed buffer, withdraws the reservation, so From c8ca53f2dc3e55b37e642c07dd8bba1bf58d3f4c Mon Sep 17 00:00:00 2001 From: laughingman7743 Date: Tue, 1 Dec 2026 03:02:20 +0900 Subject: [PATCH 8/8] Drop the duplicate minimum-size case of the append plan test (GH-1455) The async append test already requires a whole copy at the minimum part size; the target test keeps the boundary at the maximum. Co-Authored-By: Claude Opus 5.5 --- tests/pyathena/filesystem/test_s3.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/pyathena/filesystem/test_s3.py b/tests/pyathena/filesystem/test_s3.py index f27706a9e..ffdf121a3 100644 --- a/tests/pyathena/filesystem/test_s3.py +++ b/tests/pyathena/filesystem/test_s3.py @@ -12226,11 +12226,11 @@ def test_write_session_refuses_a_version(self): max_workers=1, ) - @pytest.mark.parametrize(("size", "whole"), [(4, True), (8, True), (9, False)]) + @pytest.mark.parametrize(("size", "whole"), [(8, True), (9, False)]) def test_iter_append_copies(self, size, whole): - # GH-1455: an appended object up to the maximum part size is copied - # whole, without a range; a larger one is copied in ranges that - # cover it. + # GH-1455: an appended object of exactly the maximum part size is + # copied whole, without a range; a larger one is copied in ranges + # that cover it. fs = S3FileSystem( key="dummy", secret="dummy", region_name="us-east-1", skip_instance_cache=True )