Skip to content

Consolidate the filesystem executors before parallel batch operations #1332

Closed

Description

@laughingman7743

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)

  1. Four mechanisms. S3ThreadPoolExecutor (a ThreadPoolExecutor wrapper), S3AioThreadPool (a superset: lazy threads, release(), after-fork reset, run/run_shielded), S3AioExecutor (an S3AioThreadPool reached through run_coroutine_threadsafe on fsspec's loop), and ReadAheadStream's own ThreadPoolExecutor.
  2. The loop hop of S3AioExecutor adds 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. AioS3File overrides nothing and exists for this executor.
  3. Pools per call. The synchronous filesystem creates a pool per open file and per rm, recursive chmod, clear_multipart_uploads and multipart copy; the asyncio filesystem has one pool plus one per open() and per open_async(). Total threads are unbounded across concurrent files. A file shuts down an executor that its caller passed in, so pools cannot be shared.
  4. Sizing. max_workers defaults to cpu_count() * 5 in S3FileSystem, S3File and S3AioExecutor, and to min(32, cpu + 4) in S3AioThreadPool and AioS3FileSystem; neither is reconciled with botocore's max_pool_connections of 10 (Run the batch operations of S3FileSystem concurrently #1322 question 5).
  5. Nesting. AioS3FileSystem's delegated put_file/pipe_file/get_file run in a filesystem thread and open a file with its own pool: up to max_workers ** 2 parts in flight (16 concurrent UploadPart and 22 threads at max_workers=4). A call in an S3AioThreadPool thread 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.
  6. Fan-out by hand. Track-before-schedule, cancel-before-stop and clear_frames are written at five sites (S3File._fetch_range, recursive chmod, AioS3StreamedFile._fetch_range, the asyncio annotation copies, the write session's _stop_requests), with different failure semantics; rm and clear_multipart_uploads wait for everything and stop nothing.

Proposal (for decision)

  1. One thread pool type (merge S3ThreadPoolExecutor into S3AioThreadPool under a neutral name, with aliases), used directly by both file classes; deprecate S3AioExecutor; keep AioS3File as a plain subclass. File work would then run to its end when fsspec's loop stops instead of being cancelled with it.
  2. One bounded pool per filesystem, shared by its files and batch operations, with max_workers as a per-call cap; files stop owning or shutting down executors. Size the pool against the client's max_pool_connections, or set the latter from max_workers when the filesystem builds the client.
  3. 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.
  4. 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 on S3Core (merging the short tail, as part_ranges does).

Risks: S3AioExecutor and S3ThreadPoolExecutor are public and documented; head-of-line blocking between files sharing a pool; error order of batch operations.

Activity

  1. laughingman7743 commented on Nov 3, 2026

    @laughingman7743
    MemberAuthor

    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_workers through a 10-connection pool, and batch_size=-1 started one thread per object.

    Decisions

    1. No strict request cap and no semaphore.
      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_size per-object calls, plus the caller's thread.
    2. One bounded request pool per filesystem, shared by its files and operations.
      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_size threads in S3FileSystem, and the existing S3AioThreadPool in AioS3FileSystem.
      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.
    3. Sizing.
      The request pool defaults to the client's max_pool_connections (10 with connection=); an explicit max_workers is used as given.
      A client that the filesystem builds sets max_pool_connections from max_workers unless config_kwargs sets 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.
    4. Arguments.
      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 -1 means the request pool size, never one thread per object.
      rm takes batch_size; rm(max_workers=) remains as a deprecated alias for one minor release.
      Scheduling keywords are stripped explicitly, and S3 parameters keep their validation.
    5. One fan-out primitive (sync, with an asyncio counterpart) replaces Run the batch operations of S3FileSystem concurrently (GH-1322) #1344's _run_batch and the five hand-written sites (S3File._fetch_range, recursive chmod, AioS3StreamedFile._fetch_range, the aio annotation copies, and the write session's _stop_requests):
      • bounded submission: the next call starts when one ends, and calls are tracked before they are scheduled;
      • on a stopping failure or an interrupt: start nothing new, cancel queued calls, stop retries, signal a cooperative stop that writers check before the next part and before commit (Align AioS3FileSystem with S3FileSystem for cancellation, recursive put, expand_path, and arguments #1337 item 1), wait for the running calls, and raise the failure that stopped the batch;
      • adapters for DeleteObjects errors embedded in the response, and for aborts, which are deliberately unstoppable;
      • mv copies everything before it deletes anything;
      • on_error as in fsspec.
    6. One pool type.
      S3ThreadPoolExecutor and S3AioThreadPool merge into one fork-safe pool type, which keeps the FIFO start order that the aio _abort relies on.
      S3ThreadPoolExecutor and S3AioExecutor remain as aliases (the loop argument is ignored with a warning), _create_executor returns the filesystem's pool, and S3File(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.
    7. Out of scope here: the shared range reader and parallel get_file (Download in parallel ranges in get_file() #1323), which build on 2 to 5 but are decided there.

    Order of PRs

    1. Make files usable after fork with either filesystem #1336: the fork and loop-hop fixes.
    2. The pool type and the filesystem-owned request pool, sized from the client pool, with behavior otherwise unchanged (decisions 2, 3, 6).
    3. The fan-out primitive, replacing the five sites, with the per-file window inside batches and the batch_size/rm arguments (decisions 4, 5).
    4. The batch operations of both filesystems, including mv and cat_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.
    5. Download in parallel ranges in get_file() #1323.
    6. One re-measurement of the Run the batch operations of S3FileSystem concurrently #1322 and Download in parallel ranges in get_file() #1323 validation cases, with the Run the batch operations of S3FileSystem concurrently #1322 question 4 probe.

    Each step validates cancellation, transactions, shutdown, memory bounds, and performance for what it changes.

  2. laughingman7743 commented on Nov 3, 2026

    @laughingman7743
    MemberAuthor

    Step 1 (#1336) is done in #1353. Implementation decisions for step 2 of the design:

    1. Two PRs.
      • 2a: one pool type. S3AioThreadPool becomes S3ThreadPool, a neutral name; S3ThreadPoolExecutor and S3AioThreadPool remain as aliases, and S3AioExecutor remains as a subclass whose loop argument is ignored with a warning, without the loop hop. AioS3FileSystem files use the pool directly.
      • 2b: the filesystem-owned request pool, its sizing (decision 3), files and operations that wait only for their own requests through a scoped handle on that pool, the asyncio filesystem's leaf requests moved to it, and the rejection of files inherited across a fork.
    2. Thread lifetime of the synchronous filesystem. S3FileSystem gets close() and with support, as AioS3FileSystem has: 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.
    3. Files inherited across a fork. In the child, read/write/flush/commit/discard of a file opened in the parent raise RuntimeError; 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).
  3. laughingman7743 commented on Nov 4, 2026

    @laughingman7743
    MemberAuthor

    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

    KeyboardInterrupt arrives in the main thread at any bytecode boundary, or inside a blocking C call such as Lock.acquire() or Future.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:

      • each interrupt may let at most one more call run at once, for as long as that call runs;
      • each interrupt may keep the idle threads of a pool until its shutdown or collection, so that a later 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.futures logs an Exception raised by a callback and propagates anything else. PyAthena's callbacks only update state under a lock.

    2. Components and tiers

    Component Owner Runs
    S3ThreadPool, request pool one per S3FileSystem leaf requests only
    S3ThreadPool, task pool (AioS3FileSystem._thread_pool) one per AioS3FileSystem blocking calls of the coroutines, which may wait on the request pool
    Per-call task threads (step 4) one batch call of S3FileSystem composite per-object calls of a batch (cp_file, get_file, put_file, pipe_file, cat_file), at most batch_size
    _S3PoolScope one per file, operation, or copy its calls, at most max_workers of them in the request pool
    _S3WorkItem one per call that submit_to() or a scope submits the callable; settles the caller's future exactly once
    S3File, AioS3File, AioS3StreamedFile the caller range reads and parts through a scope; commits and aborts in the caller's thread (sync) or in the task pool (streamed)
    _S3WriteSession a file or a multipart copy creation and parts through its executor; completion and abort in its caller

    A 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.

    • T1. No call in the request pool waits for a future of the request pool, directly or through a scope. Composite calls never run in the request pool.
    • T2. The tiers wait downward only: caller → task pool or per-call task threads → request pool. A call in the task pool may wait for another call of the task pool only when that call has already started and waits for nothing in the task pool. _abort waits for a started completion (s3_async.py:684) under this rule.
    • T3. Callers outside the pools may wait for any tier: user threads, cursor threads, the threads of ReadAheadStream, ParquetChunkReader, the pandas footer pool, and fsspec's "background" cache, and the event loop through asyncio.to_thread.

    3. Invariants

    _S3WorkItem (W)

    States: NEW → CLAIMED by run → SETTLED, or NEW → CLAIMED by settle → SETTLED.

    • W1. The caller's future leaves PENDING exactly once: running, cancelled and notified, or failed. Only the work item calls set_running_or_notify_cancel() on it.
    • W2. run() raises nothing from the callable; the callable's failure is set on the future. A done callback that raises BaseException propagates (§1).
    • W3. Once the future is settled, the item holds no reference to the future, the callable, or its arguments. While the callable runs, its arguments are referenced.
    • W4. run() after the future was cancelled runs nothing and only notifies.

    S3ThreadPool (P)

    States of the pool: IDLE (no threads) → ACTIVE → RELEASING → IDLE, and SHUTDOWN from any state. States of a call: QUEUED → RUNNING → DONE, or QUEUED → CANCELLED.

    • P1. Calls are dequeued in submission order (one queue).

    • P2. At most max_workers calls 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 of submit() may suspend P3 until shutdown or collection (I2).

    • P4. After shutdown(), submit() raises RuntimeError, 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):

      • (a) After ThreadPoolExecutor.submit() returns and before _futures.add(), the call is untracked. A release() 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 than max_workers (I2).
      • (b) After _futures.add() and before add_done_callback(), the future stays in the set, so a release() 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, and shutdown(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, or ENTERED → ENDED directly.

    • S1. At most max_workers calls are ENTERED, plus at most one per interrupt under I2.
    • S2. Every ENTERED call frees its place exactly once, when it ends.
    • S3. Calls enter in submission order, also with concurrent submitters. Gap (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.
    • S4. A call runs with the context variables of its submitter, also when it enters from another thread.
    • S5. shutdown(wait=True) returns once every call that will run has ended, and never waits for a call that will never run.
    • S6. A waiting call enters the pool before the call that frees its place ends there, so P3 waits for it.
    • S7. If the pool rejects a waiting call (P4, P5), the thread of the ending call runs it.
    • S8. A cancelled waiting call never runs, and its future is notified. Gap: its entry, which holds the arguments and the captured context, stays in the queue until a place frees. The entry must leave the queue when its future is cancelled.
    • S9. An interrupt of submit() follows I1–I3. An interrupt inside its try cancels the call unless it has started, and one that has started runs to its end. An interrupt at its final return (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 use submit_to(). Gap: no test asserts either behavior at that point.
    • S10. A scope that crosses a fork is unsupported. It belongs to a file, an operation, or a copy, and the file rejects use in the child (F4). An operation of a parent's filesystem in the child is unsupported (L6).

    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. For S3File and AioS3File, a range that needs one request runs in the caller's thread. For AioS3StreamedFile, every range goes through its scope, so a one-byte read waits behind a saturated pool. An executor that a caller passes to S3File(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):

      • a read cancelled while its GetObject runs, followed by close(), returns while the request runs (s3_async.py:1754);
      • a final flush cancelled after its commit was scheduled, followed by 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.

      • Before it is scheduled, a failure, interrupt, or cancellation withdraws the reservation and discards the write. Parts that have not started are cancelled, running ones are waited for, and the upload is aborted (s3_async.py:1657).
      • Once it is scheduled, a streamed file's commit completes even if the waiting task is cancelled (Give multipart writes a single owner of their parts and an explicit state #1211).
      • An aio copy's completion that is scheduled but has not started is cancelled by a cancellation, and the upload is aborted (s3_async.py:714). One that has started runs to its end, and the upload is aborted only if it fails.
      • A sync file commits in the caller's thread; an interrupt there fails the commit and aborts the upload (Move the AioS3FileSystem multipart copy onto the multipart write session #1230).
    • F4. In a forked child, a file that the parent opened raises RuntimeError from every public read, write, flush, commit(), and discard(). Its close(), 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)

    • L1. The request pool has max_workers threads, which default to the client's max_pool_connections.
    • L2. A client that the filesystem builds gets max_pool_connections = max_workers unless config_kwargs sets it.
    • L3. close() and with release the idle threads (P3), and the filesystem stays usable.
    • L4. A filesystem that nothing references ends its threads when it is collected.
    • L5. Every filesystem that PyAthena creates internally either has an owner that releases it (L3) when the owner closes, or is short-lived and collected (L4).
    • L6. In a forked child, a new filesystem works. The parent's filesystems keep the parent's boto3 client ("cannot be shared across processes", boto3 guide), so the docs say not to use them there.

    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:

      • start nothing new and cancel the queued items;
      • stop the retries of the running items (stop_retries_on);
      • signal a cooperative stop that writers check before their next part and before commit;
      • wait for the running items;
      • raise the failure that stopped the batch.
    • 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_error follows each operation's existing contract:

      • cat: raise, omit, return;
      • cat_ranges: return, or anything else to raise;
      • copy: raise, or ignore for a missing source, with ignore as the default when recursive.

      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 from gather() without waiting for the running annotation requests. A PutObjectAnnotation can then run after the copy has raised CancelledError. Step 3 replaces this fan-out with the primitive.

    Batch operations, step 4 (O)

    • O1. 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).
    • O2. Inside a batch, the window of a file is max(1, pool // batch_size).
    • O3. mv copies everything before it deletes anything.
    • O4. 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, and max_workers stays a deprecated alias of it for one minor release.

    4. Failure matrix

    Status:

    • ✔ holds, and a test fails without it;
    • ◐ holds by reading, untested;
    • ✘ gap;
    • — not applicable.
    Event Work item Pool Scope File read File write aio copy aio streamed fs operations Result sets
    Interrupt of the submitter ◐ W1 ◐ P6 (within I2); limit P6c ✔ S9 at two points; ✘ S9 return; ◐ others ◐ ✔ #1113 ✔ #1230 ✔ ◐ —
    Interrupt or cancellation of the waiting thread or task — — — ✘ F5 ◐ F3 ✔ parts and completion; ✘ B6 annotations; ✘ B3 repeated ✘ F2 (read) ◐ —
    Cancel by the caller ✔ W4 ✔ ✔ S8; ✘ S8 retention ✔ F5 ✔ F3 ✔ ✔ ◐ —
    Failure of a call ✔ W2 — ◐ ✔ ✔ ✔ ✔ ◐ (B2, step 3) —
    Concurrent submitters — ◐ P1 ✘ S3 ◐ ◐ — ◐ ◐ —
    Close or shutdown — ✔ P4 ✔ S5 ✔ F2 ✔ F2 ✔ ✘ F2 (read and commit) ✔ ◐ L5
    Release — ◐ P6b (within I2) ✔ S6 ◐ ◐ ◐ ◐ ◐ ◐
    Interpreter exit or event-loop shutdown — ◐ P5 ✔ S7 ◐ ◐ ✔ parts; ✘ B6 annotations ◐ ◐ —
    Fork — ✔ P7 — S10 ✔ F4 ✔ F4 — ✔ F4 — L6 ◐
    Garbage collection ◐ W3 ◐ L4 ◐ ◐ ◐ — ✔ — ◐ L4
    Transaction — — — — ✔ F2 — ✔ (rejected) — —

    5. Consumers

    From an inventory of pyathena/, benchmarks/, and the test helpers:

    Consumer max_workers Owner and release Status
    S3FileSystem / AioS3FileSystem that users create given, or the client's pool the user (close(), with, collection) L1–L4
    pandas result set (pandas/result_set.py:921) s3_max_workers, default cpu_count() * 5 close() of the result set ✘ sizing: 5 × CPUs threads against 10 connections
    polars chunked UNLOAD and CSV reads (polars/result_set.py:1239, :874) s3_max_workers one per read, skip_instance_cache=True, collected ◐ L4; ✘ sizing
    pandas reads with a given storage_options (pandas/result_set.py:1748) the user's options the user, through fsspec — (user-owned)
    s3fs result set (s3fs/result_set.py:145) default (the client's pool) close() of the result set L5
    fsspec "background" cache of the pandas CSV reads (pandas/result_set.py:1835) one thread per file, fsspec's the file T3
    benchmarks (benchmarks/pyathena_bench/filesystem.py:240) the case's never closed ◐ (the process ends)
    to_sql its own executors; no filesystem crosses processes — —

    6. Verification

    1. Opcode-level interrupt injection. A test helper traces a target frame with sys.settrace and frame.f_trace_opcodes = True. It raises KeyboardInterrupt at the n-th opcode, for every n until the target returns without one. Targets:

      • S3ThreadPool.submit and _S3PoolScope.submit;
      • S3Executor.submit_to and _S3WriteSession._submit;
      • the waiting code of S3File._fetch_range;
      • the fan-out primitive of step 3.

      After each run, the helper checks:

      • S1, S2, S5: no place or future is left;
      • the next call runs;
      • P2, and P3 unless I2 allows it to be suspended: release() ends the threads;
      • I1 and B6: nothing runs after the owner returns.
    2. Deterministic barrier cases for what tracing cannot reach:

      • interrupts inside blocking C calls (Lock.acquire(), Future.result(), wait()), delivered with a real SIGINT to the main thread while a barrier holds it there;
      • interleavings of concurrent submitters and ending calls (S3), forced with barriers;
      • repeated interrupts and cancellations during cleanup (B3).
    3. 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).

    4. 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

    1. Sizing of the cursors' filesystems. s3_max_workers defaults to cpu_count() * 5 in the pandas and polars cursors and in their async and aio variants.

      • (a) Default to None, so that the request pool takes the client's pool: 10, or the max_pool_connections of the connection's s3_config. An explicit value is kept as given.
      • (b) Keep the default, and cap the pool at the client's max_pool_connections, as the footer pool does (pandas/result_set.py:1030).

      Recommended: (a), which follows decision 3.

    2. 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.

    3. 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:

      • the ✘ cells of the scope and the files: S3, S8 retention, the S9 return tests, F2 for streamed files, F5;
      • the P6 tests of decision 2;
      • the sizing of the cursors (decision 1);
      • the injection helper and the barrier cases of §6.

      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.

  4. laughingman7743 commented on Nov 5, 2026

    @laughingman7743
    MemberAuthor

    Decisions on the specification, as recommended:

    1. The cursors' s3_max_workers defaults to None, so the request pool takes the client's connection pool; an explicit value is used as given.
    2. P6: no change to the pool; tests assert the I2 bounds at both windows.
    3. Share one request pool per filesystem among its files and operations (GH-1332) #1359 also covers S3, S8 retention, the S9 tests, F2 for streamed files, F5, the cursor default, the P6 tests, and the opcode-level interrupt injection and barrier cases of §6. B3 and B6 (annotation copies) go to step 3, O1 to step 4, and P6c is recorded as a limit.
  5. 22 remaining items

  6. laughingman7743 commented on Nov 7, 2026

    @laughingman7743
    MemberAuthor

    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

    • 4a (Run the batch operations of S3FileSystem concurrently (GH-1322) #1344, rebuilt on master): the batch operations of the synchronous 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.
    • 4b (Align AioS3FileSystem with S3FileSystem for cancellation, recursive put, expand_path, and arguments #1337): AioS3FileSystem. Its defect 1 (a cancelled _put_file/_pipe_file/_get_file keeps sending parts and commits) needs two parts: the cooperative stop of 4a, which S3AioThreadPool.run already triggers through its stop event, and a drain: run re-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, as map_async does (B6). The batch coroutines _get, _put, _pipe, and _cat come from fsspec, whose chunk runner awaits asyncio.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 _copy and _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 through run: _cat_file and 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 recursive put; 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, and put and its on_error handling are kept; _run_batch, its own refill loop, and its batch_size rules are replaced.

    2. Sites (4a)

    Operation Per-object call Stops the batch Outcome
    cat(on_error="raise") cat_file every failure dict, or the bytes of a single path
    cat(on_error="omit" | "return") cat_file no Exception failed paths left out, or their errors returned
    cat_ranges(on_error="return") cat_file(path, start, end) no Exception list, errors in place
    cat_ranges(other) cat_file(path, start, end) every failure list
    get get_file, with a branch of the callback every failure None
    put put_file, with a branch of the callback every failure None
    pipe(dict) pipe_file every failure None
    copy(on_error="raise") cp_file every failure None
    copy(on_error="ignore") cp_file every failure but FileNotFoundError (counts) None
    mv _copy_file, then _delete_objects every failure None; nothing deleted after a failed copy (O3)
    rm _delete_batch (unchanged, step 3) none (B4) as now

    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" is stop_on_failure=True with a counts that discounts every Exception, not stop_on_failure=False: a BaseException of a call (KeyboardInterrupt, SystemExit) is counted whatever counts says (_S3Batch._record) and stops the batch, as fsspec and #1344 catch Exception only.

    cat builds 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 when map returns).

    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, with S3Executor.map() (step 3), and shuts it down with wait=False in a finally, 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 of map does not apply. The request pool runs leaf requests only (T1).

    map gives 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).

    map submits every item at once to the task pool's FIFO queue. #1344's refill loop, which kept at most batch_size futures, is not needed: a queued future holds a functools.partial of the paths and arguments only.

    4. batch_size (O1)

    • New batch_size parameter of S3FileSystem.__init__ and of each batch operation, as AsyncFileSystem has. A per-call value overrides the filesystem's.
    • None (default) and -1 mean the size of the request pool, self.max_workers. Run the batch operations of S3FileSystem concurrently (GH-1322) #1344's cap by max_pool_connections is 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).
    • -1 differs 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_file and a small pipe_file send theirs from the task thread (s3.py:2008), so a batch_size above the pool raises the number of concurrent requests to batch_size.
    • Other values that are not positive raise 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), where n = min(batch_size, number of pairs) is the number of calls that can run at once: a batch of two pairs keeps a window of pool // 2, not pool // batch_size. A call that runs inline (one pair) gets no window and keeps the filesystem's, as now (s3.py:1802, :2065, :2742). A max_workers that the caller passed in **kwargs is resolved first (None and 0, 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 most self.max_workers requests in the request pool. The window is passed as the existing max_workers keyword of put_file, pipe_file (multipart for large values, and buffered in a transaction), open() (get_file), and cp_file (s3.py:1733, :1910, :2065, :2742). cat_file sends 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:

    • The creation of an upload checks before session.start() (s3.py:3282, :1827), so a stopped put_file sends 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 the try at :854 would leave a tracked request that never settles, and abort() and _complete_parts would 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.
    • The completion checks after the wait for the parts and immediately before _writer.complete() (:930), inside the failure handling of _commit, so that a stop during the wait is seen and the session becomes FAILED, which abort() aborts. For the callers of begin_complete() (s3_async.py:738, :1690), a check before _commit would leave the session COMPLETING, and abort() would then return without aborting (:758).
    • A stopped session raises, and its owner aborts as after any failure of a part; the abort runs under unstoppable_retries(), as now.
    • The single-request commits check before they send: the PutObject of a small S3File, pipe_file, and both CopyObject paths of cp_file, including the fallback after the multipart planning (s3.py:1808).
    • The range reads check when they start, in S3File._fetch_range (the requests that remote.read() sends, possibly several per read), and get_file checks 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: a get with that cache type may finish one prefetch after the stop (documented limit).
    • The annotation copies after a completed multipart copy (s3.py:1851) are not stopped, and run under unstoppable_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.
    • A new pyathena.util.retries_stopped() returns whether an event of the enclosing stop_retries_on() scopes is set; retry_api_call and wait_with_retry_stop use the same test.
    • The error is 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_size counts DeleteObjects requests of up to 1,000 keys, as max_workers does now. max_workers stays an alias for one minor release and emits a DeprecationWarning; both together raise TypeError. rm keeps its scope on the request pool (step 3), not task threads: a DeleteObjects call is a leaf request.

    8. Callbacks

    get and put set 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, as AioS3FileSystem does. Every use of the parent callback and of the children that branched() 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, since map returns 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. (AioS3FileSystem creates the branches in the event-loop thread, which serializes them.)

    9. Changes that callers observe (4a)

    • cat, cat_ranges, get, put, pipe(dict), copy, and mv run their per-object calls concurrently and accept batch_size. After a failure, at most batch_size - 1 other 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 by batch_size, since a slow failure lets the other threads complete any number of objects that the sequential loop would not have reached.
    • A writer in any 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, and run_in_thread, create_in_thread, and run_in_thread_or_close of pyathena/aio/util.py (:67, :192, :266; open_async uses create_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_parquet writes with boto3 directly (pandas/util.py:190).
    • get accepts an os.PathLike destination for any source; copy no longer passes its copy parameters to expand_path() (from Run the batch operations of S3FileSystem concurrently (GH-1322) #1344).
    • rm(max_workers=) emits a DeprecationWarning.
    • Conflicting pairs, which the sequential loop resolved by its order, raise ValueError before any transfer, as mv does (s3_path_pairing.py:226): two pairs of get, put, copy, or pipe(dict) with the same destination after normalization (pipe({"s3://b/k": x, "b/k": y})), and a copy destination 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 of get also 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])).
      • The copy rule is its own, not move_pairs: a pair whose source is its destination is kept (an in-place rewrite with MetadataDirective="REPLACE"), and a source that is a prefix-only directory, which _copy_file skips (s3.py:1742), is excluded with the conflict_candidates lookups of _move_pairs (s3.py:1572-1578), so copy(["b/dir", "b/x"], ["b/x", "b/y"]) with b/dir a bare prefix stays a skip and a copy.
      • Release note: copy("b/d/", "b/d/sub/", recursive=True) raises when b/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

    • Per operation: the calls run concurrently, at most batch_size at once; None, -1, explicit, and invalid batch_size; the window of O2 reaches the per-object call; an explicit max_workers above the window is capped, and one below it is kept.
    • on_error of cat, cat_ranges, and copy (B5), with a failure that does and one that does not stop the batch.
    • A failure in a batch of multipart 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 queued put_file does not start.
    • A failure in a batch of get: the running download reads no further block.
    • Each conflict of §9 raises before any transfer, including samefile and stream destinations; a self-copy and a skipped prefix-only source do not conflict; get(outfile=) runs in order.
    • A batch of two pairs gets a window of pool // 2; a single pair keeps the filesystem's window; max_workers of 0, None, above, and below the window.
    • A stopped put_file sends no CreateMultipartUpload; the annotation copies of a committed copy retry after the stop.
    • Callback calls of concurrent transfers never overlap, with a callback whose children share state.
    • A stopped get_file drops the block whose read was in flight.
    • An interrupt during the dict assembly of cat keeps no body (Python 3.11 and the latest).
    • A SIGINT while 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.
    • The existing AWS integration tests of each operation, and just benchmark test.
    • Each new stub test seen to fail without its change.

    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 explicit max_workers, BaseException in non-stopping batches, callback locking, the bound of §9, and F5 of the cat assembly. Second round, 7 findings, folded in: cancellation of fsspec's batch coroutines (4b), source/destination overlap of copy, normalized destinations of pipe, 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 than batch_size and of an inline call, the retries of the annotation copies, the copy conflict rule and its directory skips, the place of the _submit check against the tracking, the creation of an upload, the inventory of stop scopes, the COMPLETING case of begin_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_workers of 0 and None, locking of the children, samefile and stream destinations, the request bound of a large batch_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: -1 is the request pool size (spec O1); the stop raises concurrent.futures.CancelledError, with no new exception type; conflicting pairs raise ValueError, as mv does.

    Ordering with #1362 (copy source lookups), #1369, and the recursive chmod fix of #1335, which touch the same methods: 4a rebases after whichever merges first.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions