datafusion-ballista icon indicating copy to clipboard operation
datafusion-ballista copied to clipboard

Performance review: shuffle, executor, scheduler and client findings (tracking)

Open NoahKusaba opened this issue 2 months ago • 3 comments

A performance review of the shuffle data path, executor runtime, scheduler control plane and client result path, looking only for throughput, latency and memory wins. Findings were checked against the TPC-H SF1000 runs in #2499 and the per-stage plans and task metrics in #2419. Full write-up with plan excerpts: https://claude.ai/artifact/M1RdVxs9H9FgnYVsncomXF

[!NOTE] Rankings came from reading the code, not from profiles, and several looked smaller once measured (see @andygrove's review of A3 and the closed #2518 / #2522). Treat each open item as a lead to benchmark before building, not as a confirmed win.

Line numbers refer to 187e21fc. Impact is the expected effect on query time or peak memory for shuffle-heavy workloads on a multi-executor cluster. Effort: S = hours, M = days, L = weeks. Status last updated 2026-11-08.

Status

Fixed

# Finding Fixed by
A1 Remote shuffle blocks fully buffered before first batch #2659 (closes #2656)
A11 Small filtered build sides don't stop the lineitem shuffle #2434; key pushdown into the probe scan continues in #1375 / #2700 (operators in #2701)
C16 Date-partitioned scans list every partition directory #2553 (benchmark registers Hive partition columns), #2558 (prune and rebalance file groups, closes #2551)
R1 Scheduler re-read every Parquet footer per job #2498 (closes #2497)

In progress

# Finding Impact Effort Open PR / issue
A6 Sort-shuffle layout forces a barrier and copies spilled data Medium L #2774 (#2578; groundwork merged in #2579), related #2318
A7 Broadcast build sides re-fetched and rebuilt per task Medium M #2807
A8 Results fetched after job end, serially, through Flight Medium M partly #2577 (result service, closes #2484) and #2696 (concurrent streaming, pipelined mode only)
A10 Task placement ignores shuffle data locality Low–Med M duplicate of #2319, PR #2430
C6 Sort-shuffle end-of-input encode doubles peak memory Medium M #2803 (reserves the encoded output)
C15 Probe side read as broadcast runs the join in one task Medium S #2454, PR #2501

Open

# Finding Impact Effort Related
A2 Coarse tasks hold every vcore until the slowest partition finishes High (measured) M #2445; measurement below
A4 Scheduler serialised through one event loop, uncoalesced revives High M
A5 Executor memory sliced statically per vcore Medium M
A12 Byte-range splits of large row groups leave one task doing the work Medium M
A9 Blocking I/O fans out to one OS thread per output partition Medium M duplicate of #2509
C1 Sort-shuffle spill and final write block tokio workers High S
C2 Flight do_get re-compresses with hard-coded LZ4 Medium S
C3 Client result fetch: new connection per partition, 64 KiB windows Medium S
C4 Shuffle index and schema header re-read per fetch Medium S
C7 Each revive clones the job map and write-locks every graph Medium S
C8 Sort-shuffle local reads use an unbuffered File Medium S
C9 Local shuffle files read one at a time inside poll_next Low–Med S
C10 Remote fetch spawns one tokio task per location up front Low–Med S
C11 Every PartitionLocation carries full executor metadata Low–Med S duplicate of #1851
A3 Full stage plan re-encoded per task ~~High~~ Low M review below
C17 Stage row metrics sum across operators and switch units Low S #2422
C12 ballista_config() clones and re-parses settings per call Low S
C14 Pull-mode client polls job status every 50 ms Low S

Dropped after measurement

# Finding Why
C5 Passthrough shuffle writer writes small batches as-is #2518 closed: on TPC-H SF10 passthrough files already average ~6.6k rows per batch, and no plan Ballista produces today feeds the writer small batches. #2517 closed.
C13 View columns garbage-collected unconditionally #2522 closed: view columns rarely reach the sort-shuffle writer by default (schema_force_view_types=false), and the real fix belongs in the arrow-rs IPC writer (apache/arrow-rs#7185). #2557 applies the same 2× sparsity check to the passthrough writers. #2521 closed.

Found later

Merged PRs from the same investigation that weren't on the original list:

PR Change
#2796 Count buffers shared by sliced batches once in shuffle buffering (q18's partial aggregate spilled 1,145× per input partition at SF100)
#2805 Default the shuffle codec to zstd (SF1000: 1702 s → 1318 s on the #2792 branch)
#2798 Disable Nagle on scheduler connections (~40 ms per pull-mode poll)
#2795 Reschedule tasks that don't fit in a poll response (job hang at high partition counts)
#2655 Pull-staged executors take one vcore permit per partition, not per task (closes #2650)

Still open from that work: #2793, #2794, #2797, #2799, #2804; benchmark results collect in #2792.

SF1000 context (at filing)

  • #2499: Ballista totalled 652.5 s, 0.72× of Spark 3.5 (909.6 s) and 1.45× of Spark + Comet (450.0 s). 100.2 s of that was planning (R1); without it Ballista was about 1.21× of Comet.
  • Largest gaps to Comet: q06 (11.5×, R1 then C16), q14 (4.2×, R1 + C16), q07 (3.8×, a 14.6 s max vs 1.4 s median task in stage 1), q20 (3.4×, two single-task stages, A12).
  • Outlier stages in #2419 (54.0.0, before #2434): q08 s1 (full lineitem sort-shuffle to join 1.3M parts; 14.2 / 62.5 / 131.1 s min/median/max task time on a 1.01× input spread: A11, A2, A6, C1), q08 s5 (80M probe rows in one task: C15), q02 s6, q10 s0, q16 s4 and q20 s5 (one task doing the whole scan: A12), q06 s0 (one-year filter over all 256 tasks: C16).

Open questions

  • q05, q07, q18 and q21 got slower between the Sep 8 build (DataFusion 55.0.0) and 32ceaf8 (55.1.0): +18%, +7%, +27% and +25%. Event-log plans from both builds would show whether stage shapes changed or only per-stage time. q21 is now tracked in #2662.
  • The lineitem writer tail (A6, C1, A5) has three candidate causes: spill-and-copy on the critical path, drains stalling behind a spill on a shared worker, or scan stages competing for disk and network. Per-task spill and write timings (C17) would separate them.
  • Rankings assume block transport for remote shuffle reads. On an N-executor cluster only ~1/N of reads are local, so C8 and C9 rank lower here than they would on a single node.

Details

Architectural (A1–A12)

A1. Remote shuffle blocks are fully buffered before the first batch ✅

Fixed by #2659. Each remote fetch did stream.try_collect::<Vec<_>>() before emitting anything, so transfer and compute never overlapped, and decoded batches (≈ compression ratio × max_bytes_in_flight) sat outside the MemoryPool. At SF1000 this OOM-killed executors on q5 (#2656: 86% of peak heap). #2659 streams fetches and also made the executor spill limit configurable and moved spills to --work-dir.

A2. Coarse tasks hold every vcore until the slowest partition finishes

Impact: High (measured) · Effort: M · Related: #2445; speculative execution was #863 (not planned)

bind_one packs up to budget.vcores partitions into one task, and max_partitions_per_task still defaults to 0 (unbounded), so a stage is usually one task per executor. Vcores are refunded only when the whole task finishes, so one slow partition keeps V−1 cores idle; a failure retries the whole slice.

Measured (comment): on Comet native executors over Ballista, max_partitions_per_task=1 took a scan-heavy query from 3.9 s to 1.5 s and a heavier one from 6.8 s to 2.4 s; sub-second queries barely changed (0.24 → 0.22 s).

Suggested change: default max_partitions_per_task to 1 (or refund each vcore as its partition drains), then add straggler detection and speculative relaunch.

Where: mod.rs:427-505, query_stage_scheduler.rs:483-498, config.rs:472-480

A3. Full stage plan re-encoded per task

Impact: ~~High~~ Low · Effort: M

Downgraded after @andygrove's review: restrict_plan_to_partitions already slices file groups and reader locations, so bytes across a stage's tasks are about 1× the plan; only broadcast readers repeat. Restrict + encode for 256 tasks over ~10k files took 378 ms in a debug build. The one superlinear piece is cloning the whole FileScanConfig per restrict (tasks × files). The per-stage cache was removed by #2038 because plans now differ per task, and #619 is done. Session config is encoded once per batch since #2358. If plans do grow too large (#2165, #2290), broadcast reader location lists are the first suspect.

A4. Scheduler work is serialised through one event loop with uncoalesced revives

Impact: High · Effort: M

Every TaskUpdating batch posts a ReviveOffers that runs in full: it snapshots all running jobs and holds the global available_vcores mutex while awaiting each graph's write lock. AQE replans inside the loop when a stage resolves. Delay grows with jobs × stages × task completions, and jobs are visited in HashMap order. (#2798 removed a separate ~40 ms per-poll network delay.)

Suggested change: coalesce revives with a dirty flag, track pending-task counts atomically, iterate jobs FIFO or fair-share, and move AQE replanning off the loop.

Where: event_loop.rs:78-92, query_stage_scheduler.rs:505-524, memory.rs:73, mod.rs:538-545, planner.rs:356-384

A5. Executor memory is sliced statically per vcore

Impact: Medium · Effort: M

Each task gets a FairSpillPool of per_vcore × vcores_consumed and spills when its slice fills, even if the executor is otherwise idle. Collapse stages (final sort, SPM, global aggregate) run as one task with vcores_consumed = 1, so they get 1/V of executor memory. (#2655 fixed pull-staged executors overcommitting this budget.)

Suggested change: one executor-wide pool with a guaranteed minimum per task and borrowable headroom, or size collapse tasks by the memory they need.

Where: executor_process.rs:224-245, mod.rs:462-468

A6. Sort-shuffle file layout forces a barrier and a second copy of spilled data

Impact: Medium · Effort: L · In progress: #2774 (#2578), related #2318

The coordinator writes nothing until all M input drains finish, so the final write is serial and on the critical path. Spilled bytes are written twice (spill file, then copied into data.arrow), and each (input × partition × spill) segment is a separate IPC stream repeating the schema.

Suggested change: let the index point at a list of segments per partition so it references spill files instead of copying them, or emit one IPC stream per partition. Either removes the M-input barrier.

Where: writer.rs:1117-1186, writer.rs:823-905, multi_stream_reader.rs:95-108

A7. Broadcast build sides are re-fetched and rebuilt per task

Impact: Medium · Effort: M · In progress: #2807

Each task on an executor fetches the whole broadcast build side and builds its own hash table. #2807 adds an executor-wide BroadcastReadCache; on SF100 q2 at 128 partitions one broadcast stage made 16,384 fetches and decoded the same table 16 times.

Where: shuffle_reader.rs:168-190, shuffle_reader.rs:374

A8. Results are fetched only after the job ends, serially, through Flight

Impact: Medium · Effort: M · Partly addressed: #2577, #2696

The staged-mode client waits for Successful, then reads partitions one at a time via stream::iter(partitions).flatten(), each over a new BallistaClient (C3) and the Flight re-encode path (C2). #2577 moved result serving into its own service (#2484) and #2696 streams all partitions concurrently, but only for pipelined jobs.

Suggested change: for staged jobs, read final-stage partitions with bounded concurrency over pooled connections, and serve raw file bytes via block transport.

Where: distributed_query.rs:586-640, distributed_query.rs:856-905

A9. Blocking I/O fans out to one OS thread per output partition

Duplicate of #2509, which has measurements and a design. write_stream_to_disk holds a spawn_blocking thread per output stream and encodes/compresses there, outside the vcore-sized pool.

A10. Task placement ignores where shuffle data lives

Duplicate of #2319, PR #2430. Binding sorts executors by free vcores only, though every input location's num_bytes is known at bind time.

A11. Small filtered build sides don't stop the full lineitem shuffle ✅

Fixed by #2434, which stages the filtered build side first and promotes the join to broadcast (q08: 164 s → 37.1 s). Pushing the build side's keys into the probe scan continues in #1375 and the runtime filter roadmap #2700 (operators merged in #2701).

A12. Byte-range splits of large row groups leave one task doing all the work

Impact: Medium · Effort: M

A row group is read only by the byte range containing its midpoint, so with ~512 MiB row groups and 256 ranges most ranges read nothing. Supplier stages put all 10M rows in one task (q02 s6, q15 s0, q16 s4, q20 s5). The A2 measurement shows the same shape: 13 row groups over 190 splits left 177 empty. #2558 rebalances files after pruning but doesn't split inside a file.

Suggested change: split scans on row-group boundaries using the footer metadata the scheduler already reads, capping groups at the row-group count.

Where: #2419 q02.md s6, q10.md s0, q15.md s0, q16.md s4, q20.md s5

Code (C1–C17)

C1. Sort-shuffle spill and final write block tokio worker threads

Impact: High · Effort: S

spill_all_partitions runs inline in the async drain loop (interleave, encode, compress, write), and write_task_consolidated copies every spill file into data.arrow inside the coordinator future, pinning a runtime worker for the duration.

Suggested change: run both in spawn_blocking (or the I/O pool from #2509).

Where: writer.rs:672-679, writer.rs:1176-1186, spill.rs:114-140

C2. Flight do_get decodes and re-compresses with hard-coded LZ4

Impact: Medium · Effort: S

Still true on main: do_get re-encodes every batch with LZ4_FRAME regardless of ballista.shuffle.compression.codec. Since #2805 made zstd the default, every Flight read now transcodes zstd → LZ4. The sort-shuffle branch also polls MultiStreamPartitionStream directly on the gRPC runtime.

Suggested change: route client fetches to block transport; where Flight stays, use the configured codec and the spawn_blocking + channel pattern.

Where: flight_service.rs:134-156, flight_service.rs:199-206

C3. Client result fetch opens a new connection per partition with 64 KiB windows

Impact: Medium · Effort: S

fetch_partition calls BallistaClient::try_new(…, 0, 0) per partition: a fresh handshake each time and a ~64 KiB-per-RTT flow-control window. The cheap part of A8.

Suggested change: reuse one client per executor, pass the configured window sizes, and replace flatten() with buffered(n).

Where: distributed_query.rs:624-640, distributed_query.rs:881-892

C4. Shuffle index and schema header are re-read on every partition fetch

Impact: Medium · Effort: S

Each partition request stats and parses the whole data.arrow.index; local reads and do_get also open the data file twice to decode the schema. With K reducers over M task files, each index is parsed K × M times.

Suggested change: an executor-side LRU of parsed (ShuffleIndex, SchemaRef) per path, invalidated on job cleanup.

Where: flight_service.rs:498-506, reader.rs:36-66, shuffle_reader.rs:1267-1290

C5. Passthrough shuffle writer writes small batches as-is ✖️

Dropped. #2518 coalesced batches before writing, but TPC-H SF10 showed no difference: passthrough files already average ~6.6k rows per batch, and the motivating plan shape isn't produced by any current rule. Per-partition coalescers also don't bound memory at high partition counts.

C6. Sort-shuffle end-of-input encode doubles peak memory

Impact: Medium · Effort: M · In progress: #2803

encode_buffered_partitions encodes every partition while the source batches are still alive, and the encoded buffers stay uncharged to the pool until every other input finishes. #2803 reserves the encoded bytes (measured 287 MiB held vs 205 MiB reserved before); #2774's split-on-arrival layout removes most of the overlap.

Where: writer.rs:40-80, writer.rs:750-764

C7. Each revive clones the job map and write-locks every graph

Impact: Medium · Effort: S

get_running_job_cache rebuilds a HashMap of running jobs on every revive, binders take each graph's write lock even with nothing pending, and bind_one re-walks the plan for stage_has_input_collapse per task. The cheap subset of A4.

Suggested change: check available_tasks() under a read lock first, and compute is_collapse and the partition cap once per RunningStage.

Where: task_manager.rs:395-409, mod.rs:433-444, mod.rs:591-598

C8. Sort-shuffle local reads go through an unbuffered File

Impact: Medium · Effort: S

MultiStreamPartitionStream builds StreamReader<File> directly, so each of arrow's small read_exact calls is a syscall. Other shuffle formats already use a 256 KiB BufReader.

Suggested change: wrap in a BufReader sized min(256 KiB, segment length) over .take(end - start).

Where: multi_stream_reader.rs:100-107, reader.rs:66

C9. Local shuffle files are read one at a time, inside poll_next

Impact: Low–Med · Effort: S

The blocking side only opens files; read, decompress and decode happen in LocalShuffleStream::poll_next on the task runtime, one stream at a time through try_flatten.

Suggested change: do the whole read on the blocking side with bounded concurrency (2–4 files).

Where: shuffle_reader.rs:828-841, shuffle_reader.rs:583-592

C10. Remote fetch spawns one tokio task per location up front

Impact: Low–Med · Effort: S

Every remote location gets a SpawnedTask immediately, most parked on semaphores, each acquisition locking a Mutex<HashMap>. 10k locations means 10k tasks before any data moves.

Suggested change: stream::iter(locations).buffer_unordered(max_reqs) with a pre-built address → semaphore map.

Where: shuffle_reader.rs:861-933

C11. Every PartitionLocation carries full executor metadata

Duplicate of #1851. Each of the M × K locations embeds a full ExecutorMetadata plus a job_id string.

C12. ballista_config() clones and re-parses settings on every call

Impact: Low · Effort: S

Clones the settings HashMap and re-parses string values per getter, per execute() and per partition. Suggested change: return Arc<BallistaConfig> with typed fields parsed once.

Where: extension.rs:484-490, config.rs:899-935

C13. View columns garbage-collected unconditionally ✖️

Dropped. #2522 gated gc() on a 2× sparsity check (−11.5% on dense batches), but view columns rarely reach the sort-shuffle writer with schema_force_view_types=false, and the root cause is the arrow-rs IPC writer serialising unreferenced buffers (apache/arrow-rs#7185). #2557 uses the same 2× check for the passthrough writers.

C14. Pull-mode client polls job status every 50 ms

Impact: Low · Effort: S

With ballista.client.pull=true, ~25 ms average added latency per query and 20 RPCs/s per waiting client. Suggested change: exponential backoff from ~5 ms to 250 ms, or remove pull mode.

Where: distributed_query.rs:543-583

C15. A probe side read as broadcast runs the whole join in one task

Impact: Medium · Effort: S · In progress: #2454, PR #2501

In q08 s5, AQE produced a CollectLeft join whose probe child was a broadcast ShuffleReaderExec, so one task pushed 80M probe rows through the join (7.4 s).

C16. Date-partitioned scans list every partition directory ✅

Fixed. Ballista already pruned Hive partitions when they were declared; the TPC-H runner didn't declare them. #2553 registers the partition columns, and #2558 prunes files by statistics and rebalances the remaining file groups (#2551).

C17. Stage row metrics sum across operators and switch units

Impact: Low · Effort: S · Related: #2422

Not a slowdown, but it makes the rest hard to measure. Stage output_rows sums every operator (q08 s1 reports exactly 2× its input), source-stage input_rows sometimes counts batches, and JobEnd has no task count or per-task spill/write/fetch times.

Suggested change: report the terminal operator's output_rows and leaf rows as stage input, and add per-task timing percentiles to JobEnd.

NoahKusaba avatar Oct 01 '26 20:10 NoahKusaba

I checked A3 against main and the picture is smaller than the table suggests.

  • The stage plan is not shipped whole to every task. restrict_plan_to_partitions slices scan file groups and shuffle reader locations first, so the bytes summed across a stage's tasks are about 1x the plan. Only broadcast readers, which stay intact by design, are repeated per task.
  • I timed restrict plus encode in a debug build on a synthetic filter over a scan or reader, for a 256-partition stage. A scan with about 10k files took 378 ms for 256 tasks and 57 ms for 32 tasks. A reader with 256 partitions and 34 locations each took 56 ms and 41 ms. Release builds should be several times faster.
  • The one superlinear piece is that each restrict clones the whole FileScanConfig, so cost is tasks times files. It only matters at much larger file counts than this.
  • The per-stage cache was removed by #2038 because plans now differ per task. #619 is the same idea and is already done.

I'd drop A3 from the High list. If a plan does get too big, the broadcast reader's location list could be a cause, which may be related to #2290 and #2165 but I haven't confirmed that.

andygrove avatar Oct 08 '26 14:10 andygrove

Thanks for checking @andygrove I'm realizing that alot of these findings are not as impactful as advertised once properly benchmarked, or just not the correct way to address the issue. I think the proper way to do AI performance evaluation isn't to ask AI to go find things to potentially speed up, it's to ask it to prove every speedup finding with a real benchmark run and compile this report as a starting point to begin investigating. Unfortunately my computer is extremely slow 😆 .

I'll update the list regardless with current findings.

NoahKusaba avatar Oct 08 '26 15:10 NoahKusaba

A data point for A2, from Comet Native Executors (apache/datafusion-comet#7288), which run Comet's plans on Ballista's scheduler and executors. One executor with 4 vcores, blocking mode, aggregates over a Parquet table of 13 files with one row group each (384 MB), read as 190 byte-range splits of 2 MiB. A split only gets the row groups that start in it, so 13 splits hold all the rows and 177 are empty.

With the default (max_partitions_per_task unbounded), bind_one packed 4 consecutive splits into each task. Nearly every task held one of the 13 non-empty splits and three empty ones, and kept all 4 vcores until it finished, so the 13 non-empty splits ran one at a time, about 270 ms each: the scan stage took 3.7 s of the query's 3.9 s. With ballista.scheduler.max_partitions_per_task=1 they ran 4 at a time and the query took 1.5 s. A heavier query went from 6.8 s to 2.4 s, and queries of a few hundred milliseconds barely changed (0.24 s to 0.22 s), so at this scale the extra tasks cost less than the idle vcores did.

andygrove avatar Nov 08 '26 17:11 andygrove