Skip to content
Open
14 changes: 11 additions & 3 deletions docs/api/filesystem.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
---------
Expand Down
58 changes: 54 additions & 4 deletions docs/filesystem.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -1086,14 +1086,64 @@ 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:
if size >= 5 * 2**20:

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Self-review round one (implementation behavior; /code-review high and /simplify), base 06d48025, reviewed head e0e50e61, repairs in 54c5e715. FINDINGS, repaired: the example started a multipart upload for any stream, so an empty stream sent a completion without parts. It now writes a short stream with PutObject, as the S3WriteSession docstring example does.

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, 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.
`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, 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.

### Multipart requests

`create_multipart_upload()`, `upload_part()`, `upload_part_copy()`,
Expand Down
Loading