Repository navigation
Closed
Labels
Description
Part of #1327 (design problem 1 of the audit report). Related to #1322 and #1323, which need a decision here.
Summary
Consolidate the filesystem's executors into one thread-pool type with one sizing and ownership policy, and one batch primitive, before #1322 adds concurrency to the batch operations.
Current state (766d79d)
- Four mechanisms.
S3ThreadPoolExecutor(aThreadPoolExecutorwrapper),S3AioThreadPool(a superset: lazy threads,release(), after-fork reset,run/run_shielded),S3AioExecutor(anS3AioThreadPoolreached throughrun_coroutine_threadsafeon fsspec's loop), andReadAheadStream's ownThreadPoolExecutor. - The loop hop of
S3AioExecutoradds failure modes and no function: it needs a running loop, hangs after a fork (Make files usable after fork with either filesystem #1336), a blocking wait on the loop thread never completes, and futures stay pending when the loop stops, while the write session waits on them; every call is wrapped in two_S3WorkItems.AioS3Fileoverrides nothing and exists for this executor. - Pools per call. The synchronous filesystem creates a pool per open file and per
rm, recursivechmod,clear_multipart_uploadsand multipart copy; the asyncio filesystem has one pool plus one peropen()and peropen_async(). Total threads are unbounded across concurrent files. A file shuts down an executor that its caller passed in, so pools cannot be shared. - Sizing.
max_workersdefaults tocpu_count() * 5inS3FileSystem,S3FileandS3AioExecutor, and tomin(32, cpu + 4)inS3AioThreadPoolandAioS3FileSystem; neither is reconciled with botocore'smax_pool_connectionsof 10 (Run the batch operations of S3FileSystem concurrently #1322 question 5). - Nesting.
AioS3FileSystem's delegatedput_file/pipe_file/get_filerun in a filesystem thread and open a file with its own pool: up tomax_workers ** 2parts in flight (16 concurrent UploadPart and 22 threads atmax_workers=4). A call in anS3AioThreadPoolthread that waits for work submitted to the same pool starves once every thread waits (max_workers=1: 0 of 2 done after 2 s). Run the batch operations of S3FileSystem concurrently #1322 must avoid both. - Fan-out by hand. Track-before-schedule, cancel-before-stop and
clear_framesare written at five sites (S3File._fetch_range, recursivechmod,AioS3StreamedFile._fetch_range, the asyncio annotation copies, the write session's_stop_requests), with different failure semantics;rmandclear_multipart_uploadswait for everything and stop nothing.
Proposal (for decision)
- One thread pool type (merge
S3ThreadPoolExecutorintoS3AioThreadPoolunder a neutral name, with aliases), used directly by both file classes; deprecateS3AioExecutor; keepAioS3Fileas a plain subclass. File work would then run to its end when fsspec's loop stops instead of being cancelled with it. - One bounded pool per filesystem, shared by its files and batch operations, with
max_workersas a per-call cap; files stop owning or shutting down executors. Size the pool against the client'smax_pool_connections, or set the latter frommax_workerswhen the filesystem builds the client. - One batch primitive (for example
map(fn, items, *, fail_fast)with an asyncio counterpart) that implements the fan-out rules once, for Run the batch operations of S3FileSystem concurrently #1322's batch operations and the five sites above. - A range reader shared by both file classes and a pipelined
get_file(Download in parallel ranges in get_file() #1323), with the range splitter onS3Core(merging the short tail, aspart_rangesdoes).
Risks: S3AioExecutor and S3ThreadPoolExecutor are public and documented; head-of-line blocking between files sharing a pool; error order of batch operations.
Activity
laughingman7743 commentedon Nov 3, 2026
Design decision for this issue together with #1322, after consulting Codex and Claude Fable on two options (a shared request pool, and a filesystem-wide request semaphore) at 766d79d.
The first implementation of #1322 (#1344, per-call batch pools over unchanged per-file pools) is paused: it multiplied requests to
batch_size * max_workersthrough a 10-connection pool, andbatch_size=-1started one thread per object.Decisions
A pool does not bound every request, because composite calls send some requests in their own thread: small PutObject, a single-range GetObject, HeadObject, CopyObject, and CompleteMultipartUpload/AbortMultipartUpload.
A semaphore around
S3Core.call()would bound requests but not threads or memory, and its waiters cannot be stopped.Exceeding urllib3's pool opens and discards connections (extra handshakes), but does not block.
The S3 client is also shared with the result sets, so no filesystem-level budget can be exact.
The documented bound is approximate: the request pool, plus
batch_sizeper-object calls, plus the caller's thread.It runs leaf requests only: ranges, parts, part copies, ACLs, DeleteObjects batches, and aborts.
Code that runs in it never submits to it or waits on it.
The per-object composite calls of a batch run in separate task threads: a per-call pool of at most
batch_sizethreads inS3FileSystem, and the existingS3AioThreadPoolinAioS3FileSystem.They wait only on the request pool, so no tier waits on itself.
Orchestration (for example, aio
mv()planning) stays out of the task pool.The request pool defaults to the client's
max_pool_connections(10 withconnection=); an explicitmax_workersis used as given.A client that the filesystem builds sets
max_pool_connectionsfrommax_workersunlessconfig_kwargssets it.Inside a batch, the per-file window of parts and ranges defaults to
max(1, pool // batch_size), so parts in memory do not multiply.The order is FIFO without fairness machinery; a window of at most the pool size bounds head-of-line delay.
batch_size(per call and in the constructor of both filesystems, as fsspec/s3fs storage options) counts objects in flight.Its default is the request pool size, and
-1means the request pool size, never one thread per object.rmtakesbatch_size;rm(max_workers=)remains as a deprecated alias for one minor release.Scheduling keywords are stripped explicitly, and S3 parameters keep their validation.
_run_batchand the five hand-written sites (S3File._fetch_range, recursivechmod,AioS3StreamedFile._fetch_range, the aio annotation copies, and the write session's_stop_requests):mvcopies everything before it deletes anything;on_erroras in fsspec.S3ThreadPoolExecutorandS3AioThreadPoolmerge into one fork-safe pool type, which keeps the FIFO start order that the aio_abortrelies on.S3ThreadPoolExecutorandS3AioExecutorremain as aliases (theloopargument is ignored with a warning),_create_executorreturns the filesystem's pool, andS3File(executor=)is still accepted.Files stop shutting down a shared pool but still drain their own requests on close, including inside a transaction.
Shutdown drains coordinators and cleanup before the request pool stops.
After a fork, newly opened files work; open files inherited from the parent are rejected rather than promised.
get_file(Download in parallel ranges in get_file() #1323), which build on 2 to 5 but are decided there.Order of PRs
batch_size/rmarguments (decisions 4, 5).mvandcat_ranges(Run the batch operations of S3FileSystem concurrently #1322, rebuilt from Run the batch operations of S3FileSystem concurrently (GH-1322) #1344), and the Align AioS3FileSystem with S3FileSystem for cancellation, recursive put, expand_path, and arguments #1337 items.Each step validates cancellation, transactions, shutdown, memory bounds, and performance for what it changes.
laughingman7743 commentedon Nov 3, 2026
Step 1 (#1336) is done in #1353. Implementation decisions for step 2 of the design:
S3AioThreadPoolbecomesS3ThreadPool, a neutral name;S3ThreadPoolExecutorandS3AioThreadPoolremain as aliases, andS3AioExecutorremains as a subclass whoseloopargument is ignored with a warning, without the loop hop.AioS3FileSystemfiles use the pool directly.S3FileSystemgetsclose()andwithsupport, asAioS3FileSystemhas: they release the idle threads of the request pool, and the filesystem stays usable. Without them, the threads stay until the filesystem is garbage collected.read/write/flush/commit/discardof a file opened in the parent raiseRuntimeError;close(), including at garbage collection, only marks the file closed, without flushing, committing, or aborting, since the upload belongs to the parent. This also covers write sessions with parts in flight at the fork (found in the Make files usable after fork with either filesystem (GH-1336) #1353 review).Correct the fork docs and drop the AioS3FileSystem executor override (G…
Describe _create_executor as the executor source of files and operati…
Narrow the fork and ordering docs and drop a duplicate test (GH-1332)
State the queue order in the S3ThreadPool.submit() docstring (GH-1332)
Merge pull request #1357 from pyathena-dev/refactor/1332-one-pool-type
Hand scope places on in the pool thread, bound aio rm, release on clo…
Run the annotation copies through a scope and document raising parall…
Count a scope's call once the pool has accepted it (GH-1332)
Settle a call interrupted after the pool accepted it through its work…
laughingman7743 commentedon Nov 4, 2026
Specification: the executors, pools, and fan-out of the S3 filesystems (steps 2–4)
This comment states what the executors and their users must guarantee. The remaining steps of the design are implemented and reviewed against it.
It covers:
Each invariant has an ID, which the failure matrix, the tests, and the reviews use. Code references are to #1359 at ddc302b. Codex reviewed three earlier versions against that code (14, 7, and 2 findings), and all of them are folded in.
1. Policy for interrupts and failures
KeyboardInterruptarrives in the main thread at any bytecode boundary, or inside a blocking C call such asLock.acquire()orFuture.result(). Every component follows one rule:I1. No interrupt, cancellation, or failure makes a call or a wait block forever, or lets a call run after its owner has returned. "Owner" means the file, the operation, or the fan-out.
I2. If an interrupt makes a component lose track of the exact state, it errs toward running calls rather than toward blocking, within two bounds:
release()does not end them (P3 is then not met).Nothing else is allowed.
I3. A call that the pool or a scope has accepted may still run after its submitter was interrupted, as with
ThreadPoolExecutor. A caller that must be able to cancel it tracks its own future before scheduling (submit_to(), Fix interrupted multipart creation scheduling and flaky SIGINT tests #1113), and cancels that future.Done callbacks must not raise
BaseException.concurrent.futureslogs anExceptionraised by a callback and propagates anything else. PyAthena's callbacks only update state under a lock.2. Components and tiers
S3ThreadPool, request poolS3FileSystemS3ThreadPool, task pool (AioS3FileSystem._thread_pool)AioS3FileSystemS3FileSystemcp_file,get_file,put_file,pipe_file,cat_file), at mostbatch_size_S3PoolScopemax_workersof them in the request pool_S3WorkItemsubmit_to()or a scope submitsS3File,AioS3File,AioS3StreamedFile_S3WriteSessionA leaf request sends one request (with its retries), or a fixed sequence of requests, and never waits for a future of any pool. A composite call waits for leaf requests.
_abortwaits for a started completion (s3_async.py:684) under this rule.ReadAheadStream,ParquetChunkReader, the pandas footer pool, and fsspec's"background"cache, and the event loop throughasyncio.to_thread.3. Invariants
_S3WorkItem(W)States:
NEW → CLAIMED by run → SETTLED, orNEW → CLAIMED by settle → SETTLED.PENDINGexactly once: running, cancelled and notified, or failed. Only the work item callsset_running_or_notify_cancel()on it.run()raises nothing from the callable; the callable's failure is set on the future. A done callback that raisesBaseExceptionpropagates (§1).run()after the future was cancelled runs nothing and only notifies.S3ThreadPool(P)States of the pool:
IDLE(no threads)→ ACTIVE → RELEASING → IDLE, andSHUTDOWNfrom any state. States of a call:QUEUED → RUNNING → DONE, orQUEUED → CANCELLED.P1. Calls are dequeued in submission order (one queue).
P2. At most
max_workerscalls run at once.P3.
release()ends the threads once no call is queued or running, counting the calls submitted after it. The pool stays usable, and a later call starts new threads. An interrupt ofsubmit()may suspend P3 until shutdown or collection (I2).P4. After
shutdown(),submit()raisesRuntimeError, and the queued calls still run.P5. At interpreter exit, the queued calls still run, and new submissions raise.
P6. An interrupt of
submit()keeps P2 and P3 within I2 (s3_executor.py:364-367):ThreadPoolExecutor.submit()returns and before_futures.add(), the call is untracked. Arelease()can then detach the executor while the call runs, but only when no tracked call remains, so the new executor runs at most one call more thanmax_workers(I2)._futures.add()and beforeadd_done_callback(), the future stays in the set, so arelease()issued before the call ends keeps the idle threads until shutdown or collection (I2).Neither is tested yet.
P6c (dependency limit). An interrupt inside
ThreadPoolExecutor.submit()after it queues the call and before it starts a worker (concurrent/futures/thread.py,_adjust_thread_count) leaves a queued call without a worker until the next submission. With no next submission, the call never runs, andshutdown(wait=True)does not wait for it. This is inside CPython, and the pool cannot repair it without private APIs. The docs and tests record it as a limit of I1.P7. In a forked child, the copy of the pool has no threads, queued calls, or held locks, and new calls start new threads.
_S3PoolScope(S)States of a call:
WAITING → ENTERED → ENDED,WAITING → CANCELLED, orENTERED → ENDEDdirectly.max_workerscalls areENTERED, plus at most one per interrupt under I2.ENTEREDcall frees its place exactly once, when it ends.s3_executor.py:605-611):_next()frees the place before it takes the next waiting call under a second lock acquisition, so a new submitter can take the place ahead of an older waiting call. The place must pass to the oldest waiting call under one lock.shutdown(wait=True)returns once every call that will run has ended, and never waits for a call that will never run.submit()follows I1–I3. An interrupt inside itstrycancels the call unless it has started, and one that has started runs to its end. An interrupt at its finalreturn(s3_executor.py:562) leaves an accepted call that the caller cannot reach. The call then runs (I3), which is acceptable only because callers that cancel usesubmit_to(). Gap: no test asserts either behavior at that point.Files (F)
F1. The requests that a file runs in parallel are at most its
max_workers, in the request pool of its filesystem when the filesystem created its executor. ForS3FileandAioS3File, a range that needs one request runs in the caller's thread. ForAioS3StreamedFile, every range goes through its scope, so a one-byte read waits behind a saturated pool. An executor that a caller passes toS3File(executor=)is used as given.F2. Closing, committing, or discarding a file waits for its own requests and for its scheduled commit or abort, also inside a transaction, and leaves the pool running. Gaps in a streamed file's
close(), which shuts its scope down without waiting (s3_async.py:1497):GetObjectruns, followed byclose(), returns while the request runs (s3_async.py:1754);close(), returns while the commit runs in the task pool (s3_async.py:1660).Both violate I1.
close()must await, without blocking the event loop, its scope's calls and a scheduled commit or abort.F3. A commit passes three stages: reserved (
begin_complete()), scheduled (in a pool), and started.s3_async.py:1657).s3_async.py:714). One that has started runs to its end, and the upload is aborted only if it fails.F4. In a forked child, a file that the parent opened raises
RuntimeErrorfrom every public read, write, flush,commit(), anddiscard(). Itsclose(), also at garbage collection, only marks it closed.F5. The data of a failed or cancelled read is freed once its requests end (Free failed part bodies without the GC and abort an async copy's upload created during loop shutdown #1186). An interrupt of the waiting thread after
wait()returns (s3.py:3454) holds the completed bodies through the traceback until the caller drops it. Gap: this must be cleared as on failure.Filesystem lifecycle and sizing (L)
max_workersthreads, which default to the client'smax_pool_connections.max_pool_connections = max_workersunlessconfig_kwargssets it.close()andwithrelease the idle threads (P3), and the filesystem stays usable.Fan-out primitive, step 3 (B)
B1. At most the window's items are in flight. The next one starts when one ends. Items are tracked before they are scheduled.
B2. On the first failure that stops the batch:
stop_retries_on);B3. An interrupt or a cancellation of the waiting thread or task behaves as B2 and is re-raised. A repeated interrupt or cancellation does not stop the drain of the running items; it is re-raised after the drain.
B4. A DeleteObjects error embedded in a response counts as a failure. Aborts are not stopped.
B5.
on_errorfollows each operation's existing contract:cat:raise,omit,return;cat_ranges:return, or anything else to raise;copy:raise, orignorefor a missing source, withignoreas the default whenrecursive.Which failures stop the batch is stated per operation.
B6. Nothing that the primitive started runs after it returns or raises. This also holds for its asyncio counterpart when the event loop shuts down. Gap until step 3 (
s3_async.py:773): a cancellation of the annotation copies of an aio multipart copy returns fromgather()without waiting for the running annotation requests. APutObjectAnnotationcan then run after the copy has raisedCancelledError. Step 3 replaces this fan-out with the primitive.Batch operations, step 4 (O)
batch_size, per call and per filesystem, counts the per-object calls in flight. Its default, and-1, mean the request pool size. The per-object composite calls run in per-call task threads (§2), never in the request pool (T1).max(1, pool // batch_size).mvcopies everything before it deletes anything.rm(max_workers=N)keeps counting DeleteObjects requests of up to 1,000 keys each, so it does not become an alias of an object count.rm(batch_size=)counts the same requests, andmax_workersstays a deprecated alias of it for one minor release.4. Failure matrix
Status:
5. Consumers
From an inventory of
pyathena/,benchmarks/, and the test helpers:max_workersS3FileSystem/AioS3FileSystemthat users createclose(),with, collection)pandas/result_set.py:921)s3_max_workers, defaultcpu_count() * 5close()of the result setpolars/result_set.py:1239,:874)s3_max_workersskip_instance_cache=True, collectedstorage_options(pandas/result_set.py:1748)s3fs/result_set.py:145)close()of the result set"background"cache of the pandas CSV reads (pandas/result_set.py:1835)benchmarks/pyathena_bench/filesystem.py:240)to_sql6. Verification
Opcode-level interrupt injection. A test helper traces a target frame with
sys.settraceandframe.f_trace_opcodes = True. It raisesKeyboardInterruptat the n-th opcode, for every n until the target returns without one. Targets:S3ThreadPool.submitand_S3PoolScope.submit;S3Executor.submit_toand_S3WriteSession._submit;S3File._fetch_range;After each run, the helper checks:
release()ends the threads;Deterministic barrier cases for what tracing cannot reach:
Lock.acquire(),Future.result(),wait()), delivered with a realSIGINTto the main thread while a barrier holds it there;Stub matrix. For each ◐ or ✘ cell that a change touches, one AWS-free test per branch of the cell, not per cell. Each must fail when its invariant is broken (mutation check).
Reviews. Each step's reviews check the diff against these IDs and report the cells that it changes.
Limits: the injection covers Python frames of the targets, not C extensions (botocore, urllib3), which the barrier cases sample at their blocking points only.
7. Decisions needed
Sizing of the cursors' filesystems.
s3_max_workersdefaults tocpu_count() * 5in the pandas and polars cursors and in their async and aio variants.max_pool_connectionsof the connection'ss3_config. An explicit value is kept as given.max_pool_connections, as the footer pool does (pandas/result_set.py:1030).Recommended: (a), which follows decision 3.
P6. P6 holds within I2, so the pool needs no change. Recommended: add tests that assert the I2 bounds at both windows (one extra call at most; idle threads kept until shutdown). Keeping the executor's futures to the pool behind a wrapper, as the scope does, would make P3 hold through interrupts, at the cost of a second work item per call. Not recommended now.
Scope of Share one request pool per filesystem among its files and operations (GH-1332) #1359. Recommended: Share one request pool per filesystem among its files and operations (GH-1332) #1359 also covers:
Repeated cancellation (B3) and the annotation copies (B6) are handled with the primitive in step 3, and the per-call task threads (O1) with the batch operations in step 4. P6c is recorded as a limit.
laughingman7743 commentedon Nov 5, 2026
Decisions on the specification, as recommended:
s3_max_workersdefaults to None, so the request pool takes the client's connection pool; an explicit value is used as given.22 remaining items
Count failures that the executor reports in a map (GH-1332)
Correct the asyncio docs on how the fan-outs run (GH-1332)
Record executor failures when their futures settle (GH-1332)
Close the remaining gaps in failure recording of a map (GH-1332)
Wait for one future that ends a map (GH-1332)
Resume the end of a map's wait after an interrupt in its signal (GH-1332
Merge pull request #1367 from pyathena-dev/feat/1332-fan-out
laughingman7743 commentedon Nov 7, 2026
Step 4: the batch operations
This comment fixes the design of step 4 of the design against the specification (O1–O4, B2, B5, T1–T2) and the amended I1. It builds on the primitive of step 3 (design, #1367). Code references are to master at 7fcbcc6.
1. Split
S3FileSystem, the per-call task threads (O1), the window of a file inside a batch (O2),mv(O3),rm(batch_size=)(O4), and the cooperative writer stop of B2. Closes Run the batch operations of S3FileSystem concurrently #1322.AioS3FileSystem. Its defect 1 (a cancelled_put_file/_pipe_file/_get_filekeeps sending parts and commits) needs two parts: the cooperative stop of 4a, whichS3AioThreadPool.runalready triggers through its stop event, and a drain:runre-raises the cancellation at once (s3_executor.py:535), so the cancelled coroutine must keep the submitted future and await the running call, its abort included, before it re-raises, asmap_asyncdoes (B6). The batch coroutines_get,_put,_pipe, and_catcome from fsspec, whose chunk runner awaitsasyncio.wait()with no cancellation cleanup (fsspec/asyn.py:380): a cancelled batch leaves its child tasks running, so their stops and drains never start. 4b overrides them, and_copyand_cat_ranges, which use the same runner (s3_async.py:523,fsspec/asyn.py:653), to cancel the children and await them before re-raising. A child that is already cancelling (Task.cancelling()) is not cancelled again:asyncio.run()cancels every task at shutdown (asyncio/runners.py:204), so a child can be draining before its parent handles its own cancellation, and a second cancellation from the parent would end that drain (amended I1 allows that escape for a repeated cancellation, not for one shutdown). The same drain applies to every coroutine that runs a blocking call throughrun:_cat_fileand both simple-copy paths (s3_async.py:203,:619) as well as the three of defect 1, with the future tracked before it is scheduled. Defects 2–4 align the arguments and the recursiveput; defect 5 (max_workers=None) was fixed by Share one request pool per filesystem among its files and operations (GH-1332) #1359 (s3.py:239-242) and needs only a test.#1344 is rebuilt in place (force-push with lease), so that its review history stays with the change. Its pairing of
copy,get, andputand itson_errorhandling are kept;_run_batch, its own refill loop, and itsbatch_sizerules are replaced.2. Sites (4a)
cat(on_error="raise")cat_filecat(on_error="omit" | "return")cat_fileExceptioncat_ranges(on_error="return")cat_file(path, start, end)Exceptioncat_ranges(other)cat_file(path, start, end)getget_file, with a branch of the callbackputput_file, with a branch of the callbackpipe(dict)pipe_filecopy(on_error="raise")cp_filecopy(on_error="ignore")cp_fileFileNotFoundError(counts)mv_copy_file, then_delete_objectsrm_delete_batch(unchanged, step 3)A single path of
cat,pipe(str), and a batch of one item run the call in the calling thread, without a pool."No
Exception" isstop_on_failure=Truewith acountsthat discounts everyException, notstop_on_failure=False: aBaseExceptionof a call (KeyboardInterrupt,SystemExit) is counted whatevercountssays (_S3Batch._record) and stops the batch, as fsspec and #1344 catchExceptiononly.catbuilds its dict in a loop in its own frame, not a comprehension, whose frame would keep the current body on Python 3.11, and on any exception drops the outcomes, the partial dict, and the loop variable before it re-raises, so that an interrupt during the assembly keeps no body in the traceback (F5 at the wrapper; the primitive's cleanup ends whenmapreturns).3. Per-call task threads (O1, T1, T2)
Each batch operation maps its per-object calls over an
S3ThreadPool(max_workers=batch_size)that it creates, withS3Executor.map()(step 3), and shuts it down withwait=Falsein afinally, as_map()does with its scope. The per-object calls wait for their requests in the request pool; nothing in the task threads maps on the task pool, so the bare-pool limit ofmapdoes not apply. The request pool runs leaf requests only (T1).mapgives the batch its stop, gate, latch, drain, and F5 cleanup: on the first failure that stops the batch, no queued call starts, the retries of the running calls stop, the running calls are waited for, and the failure is raised (B2). An interrupt does the same (B3); a second one stops the wait and the running calls end in their threads (amended I1).mapsubmits every item at once to the task pool's FIFO queue. #1344's refill loop, which kept at mostbatch_sizefutures, is not needed: a queued future holds afunctools.partialof the paths and arguments only.4.
batch_size(O1)batch_sizeparameter ofS3FileSystem.__init__and of each batch operation, asAsyncFileSystemhas. A per-call value overrides the filesystem's.None(default) and-1mean the size of the request pool,self.max_workers. Run the batch operations of S3FileSystem concurrently (GH-1322) #1344's cap bymax_pool_connectionsis no longer needed: since Share one request pool per filesystem among its files and operations (GH-1332) #1359, the request pool and the client's connection pool have the same size by default (s3.py:320-321,:239-242).-1differs from fsspec's "every call at once" (decided). The request pool bounds the requests that go through it (ranges, parts, part copies), not every request:cat_fileand a smallpipe_filesend theirs from the task thread (s3.py:2008), so abatch_sizeabove the pool raises the number of concurrent requests tobatch_size.ValueError. A value larger than the request pool is used as given.5. The window of a file in a batch (O2)
Each per-object call that opens a file or a scope gets
max_workers=max(1, self.max_workers // n), wheren = min(batch_size, number of pairs)is the number of calls that can run at once: a batch of two pairs keeps a window ofpool // 2, notpool // batch_size. A call that runs inline (one pair) gets no window and keeps the filesystem's, as now (s3.py:1802,:2065,:2742). Amax_workersthat the caller passed in**kwargsis resolved first (Noneand0, which some callers read as the default,s3.py:1802, become the window) and then capped at the window, so O2 holds with no exception; a smaller positive one is kept. With the defaults and a full batch, each object runs one request at a time, and a batch keeps at mostself.max_workersrequests in the request pool. The window is passed as the existingmax_workerskeyword ofput_file,pipe_file(multipart for large values, and buffered in a transaction),open()(get_file), andcp_file(s3.py:1733,:1910,:2065,:2742).cat_filesends one request and takes no window.6. The cooperative writer stop (B2)
A write that a stop scope has stopped sends no further part and does not commit:
session.start()(s3.py:3282,:1827), so a stoppedput_filesends no CreateMultipartUpload and AbortMultipartUpload pair._S3WriteSession._submit(s3_writer.py:827) checks the enclosing stop scopes before it tracks a part (before:852; a check after the tracking and outside thetryat:854would leave a tracked request that never settles, andabort()and_complete_partswould wait for it forever), and the submitted part checks again when it starts (:855), since a part queued behind a full request pool would otherwise send its first attempt after the stop. The part's context carries the scopes, as for its retries._writer.complete()(:930), inside the failure handling of_commit, so that a stop during the wait is seen and the session becomesFAILED, whichabort()aborts. For the callers ofbegin_complete()(s3_async.py:738,:1690), a check before_commitwould leave the sessionCOMPLETING, andabort()would then return without aborting (:758).unstoppable_retries(), as now.S3File,pipe_file, and both CopyObject paths ofcp_file, including the fallback after the multipart planning (s3.py:1808).S3File._fetch_range(the requests thatremote.read()sends, possibly several per read), andget_filechecks again before writing a block locally (s3.py:2130), so a stopped download reads no further range and writes nothing more; a block read when the stop came is dropped. Every range read is a first attempt, which the retry stop does not reach. The prefetch threads of fsspec's"background"cache carry no context: agetwith that cache type may finish one prefetch after the stop (documented limit).s3.py:1851) are not stopped, and run underunstoppable_retries(), as the abort does: the object is committed, and a stopped loop or a stopped retry would leave it with part of its S3 annotations (GetObjectAnnotation/PutObjectAnnotation,s3_core.py:1441). They finish after the batch stops.pyathena.util.retries_stopped()returns whether an event of the enclosingstop_retries_on()scopes is set;retry_api_callandwait_with_retry_stopuse the same test.concurrent.futures.CancelledError. In a batch the latched failure is raised instead; under an interrupt, the interrupt.The check is not placed in
retry_api_call, where it would stop every first attempt in a stopped scope, including reads and the requests of the cursors that use these scopes.7.
rm(O4)rm(path, recursive=False, maxdepth=None, batch_size=None, **kwargs):batch_sizecounts DeleteObjects requests of up to 1,000 keys, asmax_workersdoes now.max_workersstays an alias for one minor release and emits aDeprecationWarning; both together raiseTypeError.rmkeeps its scope on the request pool (step 3), not task threads: a DeleteObjects call is a leaf request.8. Callbacks
getandputset the size of the callback to the number of pairs, and create and update each file's branch in the task thread that transfers it, asAioS3FileSystemdoes. Every use of the parent callback and of the children thatbranched()returns (branched(),set_size,relative_update,close) runs under one lock of the operation, through a proxy that the per-object call receives: fsspec does not make the children distinct (fsspec/callbacks.py:69), so a user's callback may share state between them. The parent's relative update by one runs in the task thread, sincemapreturns only at the end. The calls stay inside the mapped callable, so that a failure of the user's callback is a failure of that call. (AioS3FileSystemcreates the branches in the event-loop thread, which serializes them.)9. Changes that callers observe (4a)
cat,cat_ranges,get,put,pipe(dict),copy, andmvrun their per-object calls concurrently and acceptbatch_size. After a failure, at mostbatch_size - 1other calls are still running, and each finishes its current request (and a committed copy its annotations); a multipart write sends no further part and does not commit, and a download reads no further block. Objects that other threads completed before the failure stay written: their number is not bounded bybatch_size, since a slow failure lets the other threads complete any number of objects that the sequential loop would not have reached.stop_retries_on()scope now also stops before its next part and its commit. Inside PyAthena these scopes are the step 3 primitive, the aio task pool, andrun_in_thread,create_in_thread, andrun_in_thread_or_closeofpyathena/aio/util.py(:67,:192,:266;open_asyncusescreate_in_thread,s3_async.py:924). None of them encloses a part or a commit today except the aio task pool, which is Align AioS3FileSystem with S3FileSystem for cancellation, recursive put, expand_path, and arguments #1337 defect 1;to_parquetwrites with boto3 directly (pandas/util.py:190).getaccepts anos.PathLikedestination for any source;copyno longer passes its copy parameters toexpand_path()(from Run the batch operations of S3FileSystem concurrently (GH-1322) #1344).rm(max_workers=)emits aDeprecationWarning.ValueErrorbefore any transfer, asmvdoes (s3_path_pairing.py:226): two pairs ofget,put,copy, orpipe(dict)with the same destination after normalization (pipe({"s3://b/k": x, "b/k": y})), and acopydestination that is another pair's source (copy(["b/a", "b/b"], ["b/b", "b/c"])). Run concurrently, the first can mix or reorder the writes, and the second can copy the old contents. Local destinations ofgetalso conflict when they are the same existing file (os.path.samefile, such as hard links) or the same file-like object (get([a, b], [stream, stream])).copyrule is its own, notmove_pairs: a pair whose source is its destination is kept (an in-place rewrite withMetadataDirective="REPLACE"), and a source that is a prefix-only directory, which_copy_fileskips (s3.py:1742), is excluded with theconflict_candidateslookups of_move_pairs(s3.py:1572-1578), socopy(["b/dir", "b/x"], ["b/x", "b/y"])withb/dira bare prefix stays a skip and a copy.copy("b/d/", "b/d/sub/", recursive=True)raises whenb/d/sub/already holds objects, since a destination is then another pair's source.get(..., outfile=stream)with several sources writes them into the one stream one after another in input order, without task threads.10. Verification
batch_sizeat once;None,-1, explicit, and invalidbatch_size; the window of O2 reaches the per-object call; an explicitmax_workersabove the window is capped, and one below it is kept.on_errorofcat,cat_ranges, andcopy(B5), with a failure that does and one that does not stop the batch.put: the running upload sends no further UploadPart, including a part queued behind a full pool, and no CompleteMultipartUpload, and is aborted; a stop during the wait for the parts aborts as well; a queuedput_filedoes not start.get: the running download reads no further block.samefileand stream destinations; a self-copy and a skipped prefix-only source do not conflict;get(outfile=)runs in order.pool // 2; a single pair keeps the filesystem's window;max_workersof0,None, above, and below the window.put_filesends no CreateMultipartUpload; the annotation copies of a committed copy retry after the stop.get_filedrops the block whose read was in flight.catkeeps no body (Python 3.11 and the latest).SIGINTwhile a batch waits (real signal, bounded); a second one during the drain.mv: nothing deleted after a failed copy, including when another copy ends after the failure (O3).rm(max_workers=)warns and counts requests;rm(batch_size=)the same without the warning.just benchmark test.The in-region measurement of #1344 ("Not run yet") is step 5.
11. Review record
Codex (static, against 7fcbcc6 and e669525), 11 findings, folded in: the drain of a cancelled aio call (4b), part checks at start and the completion check after the wait, the download stop, duplicate destinations, the window of
pipe_file, the cap of an explicitmax_workers,BaseExceptionin non-stopping batches, callback locking, the bound of §9, and F5 of thecatassembly. Second round, 7 findings, folded in: cancellation of fsspec's batch coroutines (4b), source/destination overlap ofcopy, normalized destinations ofpipe,get(outfile=), the block in flight of a stopped download, the annotations of a committed copy (documented, not stopped), and the cap test. Third round, Claude Fable 5.1 and Codex in parallel against this version (7 and 8 findings), folded in: the window of a batch smaller thanbatch_sizeand of an inline call, the retries of the annotation copies, thecopyconflict rule and its directory skips, the place of the_submitcheck against the tracking, the creation of an upload, the inventory of stop scopes, theCOMPLETINGcase ofbegin_complete()callers only (Fable); the cancellation of_copy,_cat_ranges,_cat_file, and the simple copies, no second cancellation of a draining child at loop shutdown, the range-request check and the background cache,max_workersof0andNone, locking of the children,samefileand stream destinations, the request bound of a largebatch_size(Codex). Not taken: one interrupt during the wait after a failure stops that wait. Step 3 decided this (design §3–4, #1367), and the batch operations inherit it.12. Decisions
Decided by the maintainer:
-1is the request pool size (spec O1); the stop raisesconcurrent.futures.CancelledError, with no new exception type; conflicting pairs raiseValueError, asmvdoes.Ordering with #1362 (
copysource lookups), #1369, and the recursivechmodfix of #1335, which touch the same methods: 4a rebases after whichever merges first.Run the batch operations of S3FileSystem concurrently (GH-1322)
Run the batch operations of S3FileSystem concurrently (GH-1322)
Attribute the 16 KiB reads to the HTTP connection (GH-1332)
Correct the block size, ranges, and limits of the entry (GH-1332)
Describe the body of a when_required part as read in blocks too (GH-1332
Merge pull request #1420 from pyathena-dev/docs/1332-filesystem-remea…