Repository navigation
fix(storage): close the upload file handle when the request fails - #1575
tushardev-365 wants to merge 1 commit into
Conversation
When a caller passes a path rather than an open file, _upload_or_update and upload_to_signed_url open the handle themselves and hand it to _request inside the files dict. The close lived after the except HTTPStatusError block, so it only ran when the request succeeded: any non-2xx raised StorageApiError straight past it and the handle was left open, with no way for the caller to reach it. It leaks whenever the exception is retained (logging with exc_info, collecting failures in a batch upload loop, an error reporter), because the traceback keeps the frame holding the reader alive. Python also emits ResourceWarning: unclosed file on that path. Move the close into a finally so it runs on both paths. The condition is unchanged, so only handles storage3 opened itself are closed and a caller-supplied stream is still left alone.
|
Closing this in favour of #1586, which carries the same Two things this PR did better, and I've asked over there to fold them in:
For the record: the analysis in this PR — the fd-count table, the note that the traceback keeps the frame holding the reader alive, and spotting that One heads-up for future PRs: |
`_request` closed the uploaded file handle after the `except HTTPStatusError` block, so the close only ran when the request succeeded. Any non-2xx raised `StorageApiError` straight past it and the handle stayed open. Since the handle only ever existed inside the local `files` mapping, the caller had no way to close it either. Python reports it as `ResourceWarning: unclosed file`. The close also lived in the wrong place. `_request` sees only a `BufferedReader` and cannot tell one that storage3 opened from one the caller passed in, so it closed both. A caller who supplies their own stream had it closed under them on the success path. Move the close to the two functions that open the file, `_upload_or_update` and `upload_to_signed_url`, which know whether they own the handle. A handle storage3 opened is closed on both paths; a caller-supplied stream is left alone on both paths. Supersedes #1575 and #1586, which both fixed the leak by wrapping `_request` in `try/finally`. That closes the leak but keeps the close in the frame that cannot tell the two cases apart, and extends the closing of caller-owned streams to the error path as well. Co-authored-by: Tushar Pagar <240662211+tushardev-365@users.noreply.github.com> Co-authored-by: chengwudi1 <chengwudi1@users.noreply.github.com>
…1607) Supersedes #1586 and the closed #1575. ## The leak `_request` closed the uploaded file handle *after* the `except HTTPStatusError` block, so the close only ran on success. Any non-2xx raised `StorageApiError` straight past it and the handle stayed open. The handle only ever existed inside the local `files` mapping, so the caller had no way to close it either — Python reports it as `ResourceWarning: unclosed file`. Both `upload()` / `update()` (via `_upload_or_update`) and `upload_to_signed_url()` are affected. Credit for the diagnosis goes to @tushardev-365 in #1575, including the fd-count reproduction and the note that a retained traceback keeps the frame holding the reader alive. ## Why not just `try/finally` around `_request` That is what both #1575 and #1586 did, and it does close the leak. But it leaves the close in a frame that cannot tell the two cases apart: ```python if files and "file" in files and isinstance(files["file"][1], BufferedReader): files["file"][1].close() ``` `_request` sees only a `BufferedReader`. A handle storage3 opened from a path and a stream the caller passed in are both `BufferedReader`, so it closes both. On `main` that already bites callers who supply their own stream — it is closed under them on the success path. Wrapping `_request` in `try/finally` extends that to the error path too, which breaks retry-after-failure: ```python with open("big.bin", "rb") as f: try: client.storage.from_("bucket").upload("big.bin", f) except StorageApiError: f.seek(0) # ValueError: I/O operation on closed file client.storage.from_("bucket").upload("big.bin", f) ``` ## This change Move the close into the two functions that open the file — `_upload_or_update` and `upload_to_signed_url` — which know whether they own the handle: ```python if isinstance(file, BufferedReader) or isinstance(file, bytes) or isinstance(file, FileIO): # bytes or byte-stream-like object received -- the caller owns it opened = None files = {"file": (filename, file, content_type)} else: # str or pathlib.path received -- we own the handle, so we close it opened = open(file, "rb") files = {"file": (filename, opened, content_type)} try: response = await self._request(...) finally: if opened is not None: opened.close() ``` `_request` no longer touches the handle at all. Result: a handle storage3 opened is closed on both paths; a caller-supplied stream is left alone on both paths. ## Tests `tests/_async/test_file_api.py` and its generated `_sync` twin, 4 tests each: - `test_upload_closes_file_handle_on_error` - `test_upload_closes_file_handle_on_success` (regression) - `test_update_closes_file_handle_on_error` — `update()` shares `_upload_or_update` - `test_caller_supplied_handle_is_left_open` — asserts on both paths They assert on the real handle's `.closed` (captured from the `files` mapping the client received) rather than patching `builtins.open` and asserting on a mock. That approach is from #1575. Reverting only the source change turns 6 of the 8 red, including the caller-supplied guard on the success path, which fails on `main` today. ## Note for reviewers `run-unasync.py` cannot regenerate the existing storage test files: it emits `from unittest.mock import SyncMock` (no such name) wherever a test uses `AsyncMock`, so `tests/_sync/test_bucket.py` and `tests/_sync/test_client.py` are hand-corrected and running the script today breaks them. The new test file avoids `AsyncMock` entirely, so its `_sync` copy is genuinely generated and round-trips. Worth a separate issue. ## Verification - 74 storage unit tests pass - `ruff check` and `ruff format --check` clean - `mypy` shows only the pre-existing `pyiceberg` import-not-found errors in `analytics.py`, untouched here --------- Co-authored-by: Tushar Pagar <240662211+tushardev-365@users.noreply.github.com> Co-authored-by: chengwudi1 <chengwudi1@users.noreply.github.com> Co-authored-by: Lukas Klingsbo <lukas.klingsbo@gmail.com>
What
When a caller passes a path instead of an already-open file, storage3 opens the handle itself:
_requestthen closed it after theexcept HTTPStatusErrorblock, so the close only ran when the request succeeded. Any non-2xx raisedStorageApiErrorstraight past it and the handle stayed open — and since it only ever existed inside_request's localfilesdict, the caller has no way to close it either.It leaks whenever the exception is retained: logging with
exc_info, collecting failures in a batch-upload loop,raise ... from, an error reporter. The traceback keeps the frame holding the reader alive. Python also emitsResourceWarning: unclosed fileon that path.Counting open fds against a mock transport returning 409 (the most common upload failure), with the error retained each time:
Both
upload()/update()(via_upload_or_update) andupload_to_signed_url()are affected.Fix
Move the close into a
finallyso it runs on both paths. The condition is unchanged — still onlyBufferedReader, i.e. only handles storage3 opened itself, so a caller-supplied stream is still left alone to close as they see fit.Tests
test_upload_closes_file_handle_on_error(async + sync): mock the transport into an error, then assert the handle storage3 opened is closed. Reverting only the source change fails it on.closed is False.Note
The diff on
file_api.pylooks larger than it is — wrapping the body intryreindents it. The only behavioural change is where the close happens._syncis generated, so the change was made in_asyncand regenerated withmake build-sync; unrelated regenerated files are excluded.This does not touch the
resp.textline a few lines above (#1563), which has PRs open already — different defect, different code path.