Repository navigation
perf: combine small input batches before a native sort that merges them - #7696
parthchandra wants to merge 10 commits into
Conversation
comphead
left a comment
There was a problem hiding this comment.
I checked the operator against DataFusion 55.2's ExternalSorter. It reserves before it holds a batch and frees before the sort reserves, and the planner wraps only full sorts over unordered input. One fair_pool.rs test no longer tests what it says once merged with #7630, and a few tests repeat others. For the DataFusion follow-up, the two-key in-memory numbers are worth including: in_mem_sort_stream in 55.2 and 56.0 keeps multi-column sorts at one run per batch, on the grounds that merging many small runs is faster, and sort_small_batches shows the opposite for tiny batches.
| // Another consumer that can spill, such as a second sort in the task, halves the share. | ||
| let _other_sort = spillable("ExternalSorter[1]", &pool); |
There was a problem hiding this comment.
Since #7630 landed on main, CometFairMemoryPool splits the share only among consumers that can spill and are active. A sort that has not started takes no share from another sort (is_sort and unstarted_sorts in try_grow). This ExternalSorter[1] registers but never reserves. So after a merge with main, I expect the sort under test to get the whole 3 MiB share, and the test stops covering the halved share it describes. It should still pass, because the plain sort spills either way, so CI will not flag it. hold(&other_sort, 2) from memory_pools/testing.rs makes it active, as the tests added in #7630 do. The final pool.reserved() check then has to allow for those 2 bytes. Untested.
There was a problem hiding this comment.
Good catch, thanks. After rebasing on main with #7630, the second sort now calls hold(&other_sort, 2), so it is active and halves the share, and the final check allows for its 2 bytes. I checked that the test still guards what it says: with the earlier 1 MiB group cap it fails with "fair limit is 1540096 bytes" (half of the 3 MiB share), and it passes with the current cap.
| #[test] | ||
| fn a_refused_reservation_flushes_the_held_group_first() { | ||
| let input = ten_row_batches(4); | ||
| let one = get_record_batch_memory_size(&input[0]); | ||
| // Room for two batches and their copy. The third is refused, so the first two go out | ||
| // combined and the third passes through. The fourth starts a new group. | ||
| let output = run_in_pool(input.clone(), 1000, 2 * 2 * one); | ||
| assert_eq!(row_counts(&output), [20, 10, 10]); | ||
| same_rows(&output, &input); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn holds_no_memory_while_the_sort_takes_a_batch() { | ||
| let input = ten_row_batches(10); | ||
| let schema = input[0].schema(); | ||
| let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1 << 30)); | ||
| let runtime = RuntimeEnvBuilder::new() | ||
| .with_memory_pool(Arc::clone(&pool)) | ||
| .build_arc() | ||
| .unwrap(); | ||
| let ctx = SessionContext::new_with_config_rt(SessionConfig::new(), runtime); | ||
| let source = MemorySourceConfig::try_new_exec(&[input], schema, None).unwrap(); | ||
| // A 25-row target makes every third batch overflow the group. | ||
| let exec = SortInputCoalesceExec::new(source, 25, 0); | ||
| let mut stream = exec.execute(0, ctx.task_ctx()).unwrap(); | ||
| let mut rows = vec![]; | ||
| while let Some(batch) = stream.try_next().await.unwrap() { | ||
| assert_eq!(pool.reserved(), 0, "held memory while handing on a batch"); | ||
| rows.push(batch.num_rows()); | ||
| } | ||
| assert_eq!(rows, [20, 20, 20, 20, 20]); | ||
| } | ||
|
|
||
| #[test] | ||
| fn after_a_refusal_the_next_batches_pass_through() { | ||
| let input = ten_row_batches(6); | ||
| let one = get_record_batch_memory_size(&input[0]); | ||
| // Room for two batches and their copy, so the third is refused. The ones after it pass | ||
| // through without asking the pool again. | ||
| let output = run_in_pool(input.clone(), 1000, 2 * 2 * one); | ||
| assert_eq!(row_counts(&output), [20, 10, 10, 10, 10]); | ||
| same_rows(&output, &input); | ||
| } |
There was a problem hiding this comment.
These two tests use the same pool size and target as combining_resumes_after_the_backoff below. Their expected outputs, [20, 10, 10] and [20, 10, 10, 10, 10], are prefixes of its output, so that test alone covers all three. Also, the comment in the first one is off: the fourth batch passes through under the backoff and does not start a new group. The three dictionary tests at lines 767 to 816 differ only in how the column wraps the Int8 dictionary. One test that loops over the three columns would cover them.
There was a problem hiding this comment.
Agreed. I removed the two refusal tests, since combining_resumes_after_the_backoff covers both outputs, and rewrote its comment to spell out each step: the held group goes out first, then 64 batches pass through, then combining resumes. The three dictionary tests are now one test that loops over the plain, struct and list wrappers.
| /// A sort in a fair pool so tight that it spills about every 50 KiB. It failed with combined | ||
| /// input when the coalescer still held memory while the sort reserved a combined batch. | ||
| async fn sort_in_tight_fair_pool( | ||
| input: Vec<RecordBatch>, | ||
| coalesce: bool, | ||
| ) -> Result<MetricsSet> { | ||
| use datafusion::execution::memory_pool::FairSpillPool; | ||
| use datafusion::physical_expr::expressions::col; | ||
| use datafusion::physical_expr::{LexOrdering, PhysicalSortExpr}; | ||
| use datafusion::physical_plan::sorts::sort::SortExec; | ||
|
|
||
| let schema = input[0].schema(); | ||
| let runtime = RuntimeEnvBuilder::new() | ||
| .with_memory_pool(Arc::new(FairSpillPool::new(2560 * 1024))) | ||
| .build_arc() | ||
| .unwrap(); | ||
| let config = SessionConfig::new().with_sort_spill_reservation_bytes(64 * 1024); | ||
| let gate = config.options().execution.sort_in_place_threshold_bytes; | ||
| let ctx = SessionContext::new_with_config_rt(config, runtime); | ||
| let source = MemorySourceConfig::try_new_exec(&[input], Arc::clone(&schema), None).unwrap(); | ||
| let coalescer = Arc::new(SortInputCoalesceExec::new( | ||
| Arc::clone(&source) as _, | ||
| 8192, | ||
| gate, | ||
| )); | ||
| let sort_input: Arc<dyn ExecutionPlan> = if coalesce { | ||
| Arc::clone(&coalescer) as _ | ||
| } else { | ||
| source | ||
| }; | ||
| let ordering = LexOrdering::new(vec![PhysicalSortExpr::new( | ||
| col("id", &schema).unwrap(), | ||
| Default::default(), | ||
| )]) | ||
| .unwrap(); | ||
| let sort = Arc::new(SortExec::new(ordering, sort_input)); | ||
| collect(sort.execute(0, ctx.task_ctx())?).await?; | ||
| Ok(coalescer.metrics().unwrap()) | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn combined_input_does_not_fail_a_sort_in_a_tight_fair_pool() { | ||
| let input: Vec<_> = (0..4000) | ||
| .map(|b| { | ||
| let ids: Vec<i64> = (0..50) | ||
| .map(|i| ((b * 50 + i) * 7919 % 200_000) as i64) | ||
| .collect(); | ||
| let text = ids.iter().map(|i| format!("value-{i:010}-padding-padding")); | ||
| RecordBatch::try_from_iter([ | ||
| ("id", Arc::new(Int64Array::from(ids.clone())) as ArrayRef), | ||
| ( | ||
| "s", | ||
| Arc::new(StringArray::from_iter_values(text)) as ArrayRef, | ||
| ), | ||
| ]) | ||
| .unwrap() | ||
| }) | ||
| .collect(); | ||
| sort_in_tight_fair_pool(input.clone(), false) | ||
| .await | ||
| .expect("the plain sort fits"); | ||
| let metrics = sort_in_tight_fair_pool(input, true) | ||
| .await | ||
| .expect("the sort over combined batches fits too"); | ||
| assert!(metric(&metrics, "coalesced_input_batches") > 0); | ||
| } |
There was a problem hiding this comment.
This runs the same scenario as a_sort_fits_its_share_with_combined_input_where_it_fits_without in fair_pool.rs: a sort over small batches in a tight fair pool, with and without the coalescer. The difference is that it uses DataFusion's FairSpillPool, which Comet does not use outside tests. The failure it describes, the coalescer holding memory while the sort reserves, is the invariant that holds_no_memory_while_the_sort_takes_a_batch checks directly. I think this test and sort_in_tight_fair_pool can be removed.
There was a problem hiding this comment.
Agreed, removed combined_input_does_not_fail_a_sort_in_a_tight_fair_pool and sort_in_tight_fair_pool. The CometFairMemoryPool test in fair_pool.rs covers the scenario on Comet's real pool, and holds_no_memory_while_the_sort_takes_a_batch checks the invariant directly.
A shuffle from many map tasks gives each reduce task one tiny batch per block. DataFusion's sort merges one stream per buffered batch when it spills, so such sorts become very slow. Add SortInputCoalesceExec in front of a full native sort over unordered input. It passes batches through until the input reaches the sort's in-place threshold, then combines small batches into batches of at most spark.comet.batchSize rows and half that threshold in bytes. It reserves exactly what it holds and holds nothing while the sort takes a batch. Controlled by spark.comet.exec.sort.coalesceInput.enabled (default true). Closes apache#5686.
sunchao
left a comment
There was a problem hiding this comment.
I'd keep spark.comet.exec.sort.coalesceInput.enabled opt-in for now. I traced two independent memory problems through DataFusion 55.2 and Arrow 59.3.2. A group can fit the coalescer's budget and still fail the sort's retry after a spill. Shared input columns can also expand during concatenation and exceed the group's byte cap. I've left concrete inputs for both inline. There's an open upstream PR that forms runs inside the sorter and retains the original batches if the replacement fails admission. That seems like a good place to exercise the same inputs. DataFusion #26931
Before enabling this by default, could we get paired Spark stage timings with the flag off and on for the spilling small-block workload and for the 128-writer/128-reducer case from #5686? The TPC-H sorts that combined blocks stayed in memory. On the small-reducer path, each batch now goes through a second size calculation until the gate opens. Those two measurements would show the gain on the target stage and the cost below the gate. Prior Spark measurements
| context: Arc<TaskContext>, | ||
| ) -> Result<SendableRecordBatchStream> { | ||
| let mut input = self.input.execute(partition, Arc::clone(&context))?; | ||
| let reservation = MemoryConsumer::new(format!("SortInputCoalesceExec[{partition}]")) |
There was a problem hiding this comment.
The pool can grant this unspillable consumer a group that exceeds ExternalSorter’s fair share. That can fail a task even when 24 raw batches fit at once. Fair-pool checks · Sort retry
A regression case for the new fair-pool test would be an 11.5 MiB pool, a second active spillable consumer, and the default 10 MiB merge reservation, 1 MiB threshold and 8,192-row target. Feed it 64 batches of 256 rows with eight separately allocated, non-null Int64 columns. Each batch holds 16 KiB and costs the sort 32 KiB. Tracing the reservations through 55.2 gives the following sequence.
- With coalescing off, the 768 KiB sort share admits runs of 24, 24 and 16 batches. Their spill files fit in the merge workspace.
- With coalescing on, the gate opens after batch 32. The sort holds 256 KiB at that point. The pool grants the coalescer 1 MiB for batches 33–64 and their copy. Once emitted, that single 512 KiB batch costs the sort 1 MiB. The sort spills its 256 KiB and retries with an empty buffer, where the limit is still 768 KiB.
The backoff only sees refusals on the coalescer's reservation. Could we add this case and keep the feature opt-in until an oversized group can fall back to the original batches under the sort's own reservation?
There was a problem hiding this comment.
Reproduced exactly as you traced it. I added your case as a_combined_batch_can_exceed_a_share_the_raw_batches_fit in fair_pool.rs: the plain sort fits, and the coalesced sort fails with the external-sort error. It pins the limitation until the sort can fall back to the original batches, and the feature is now opt-in.
| self.backoff -= 1; | ||
| None | ||
| } else { | ||
| Some(get_record_batch_memory_size(batch)) |
There was a problem hiding this comment.
Could we budget retained input and materialized output separately here? get_record_batch_memory_size counts each buffer address once. A projection such as named_struct('a', s, 'b', s, ...) can reuse the same string array for several fields. Arrow concatenates each field into a separate array. Struct evaluation · Input accounting · Arrow concatenation
For example, after the gate, take two 256-row batches, each with a 128 KiB string buffer shared by eight fields. Together the inputs fit the 512 KiB cap. We reserve about 512 KiB, then allocate 2 MiB for the strings alone while retaining the inputs. The sort then needs about 4 MiB to admit the result. Counting the output per field before concatenating would let us cap the copy and reserve for both allocations. A test with repeated Arc::clones of one StringArray would catch this.
There was a problem hiding this comment.
Fixed. The coalescer now tracks what it keeps alive and what the copy writes, counting a shared buffer once per column for the copy. It caps the group by the copy and reserves both. a_copy_of_shared_columns_is_reserved_and_capped uses Arc::clones of one StringArray across 8 fields.
| if needed <= size { | ||
| return Ok(true); | ||
| } | ||
| match self.reservation.try_grow(needed - size) { |
There was a problem hiding this comment.
This request can spill a JVM operator before we know whether there is a second batch to combine. With fair_unified and the sort at its share, the original sort request hits the local limit and triggers a native spill. The unspillable coalescer goes straight to Spark, which can spill a resident UnsafeExternalSorter to grant the request. That disk write has already happened even if the next batch forces a one-batch flush. We measured this behavior with a temporary reservation in #7190. Prior spill measurement
Could we apply the same resident-memory guard used for semi-join reduction, or charge this request against the sort's remaining share before calling Spark? The existing admission test could exercise this with small blocks and a sibling that counts spill calls. Planner guard · Spark test
There was a problem hiding this comment.
Applied the same guard. The check is now a shared helper in join.rs, used by both the semi-join reduction and the sort, so the coalescer is skipped when another Spark consumer holds execution memory.
| }; | ||
| let input = sort.input(); | ||
| // The reducer packs its own output, so it replaces any input coalescer. | ||
| let input = SortInputCoalesceExec::unwrap_input(sort.input()); |
There was a problem hiding this comment.
Could we keep the coalescer between the reducer and the sort when both options are enabled? The reducer only packs the output of a successful reduction. For the 62-row shuffle blocks described in the PR, every block is below its 1,024-row minimum, so the reducer forwards each one separately. Enabling right-key reduction on an eligible left-semi join would therefore restore the original merge fan-in on the right sort. A test with both flags and a long stream of short blocks could check that bypassed rows still reach the sort in combined batches. Reducer decision and forwarding
There was a problem hiding this comment.
Good point. The reducer now goes below the coalescer (sort -> coalescer -> reducer), so bypassed short blocks still get combined. The planner test checks this.
| columns.push(( | ||
| "g".into(), | ||
| Arc::new(Int64Array::from_iter_values( | ||
| ids.iter().map(|&i| (i % 64) as i64), |
There was a problem hiding this comment.
The two_keys/in_order case sorts by (g, key), so the leading key wraps from 63 to 0 at i = 64. At 64 rows per batch every run spans all 64 groups, and at 1,024 rows even a single batch wraps repeatedly. The reported 18% slowdown therefore measures a cyclic leading key. Could we generate contiguous groups with i * 64 / ROWS, check lexicographic order across batch boundaries outside the timed loop, and refresh the two-key numbers?
There was a problem hiding this comment.
You're right, the key wrapped. g is now i * 64 / ROWS, with an order check outside the timed loop. The 1024-row in-order case is now 49.6 -> 49.0 ms, and I refreshed the two-key numbers in the description.
| grouper.prepare(&batch)? | ||
| }; | ||
| if let Some(batch) = flushed { | ||
| baseline.record_output(batch.num_rows()); |
There was a problem hiding this comment.
Could we record the emitted batch with (&batch).record_output(&baseline) on all three emission paths, as ExplodeExec does? Passing the row count updates only output_rows. The native plan then reports zero output_batches and output_bytes even when coalesced_output_batches is positive. The total batch count is particularly useful here because it includes the blocks passed through before the gate and tells us how many batches actually reached the sort. DataFusion counters · Comet example
There was a problem hiding this comment.
Done. All three emit points use (&batch).record_output(&baseline).
| let exec = SortInputCoalesceExec::new(source, 40, 0); | ||
| let mut stream = exec.execute(0, ctx.task_ctx()).unwrap(); | ||
| // The first group is out and the second is being held. | ||
| assert_eq!(stream.try_next().await.unwrap().unwrap().num_rows(), 40); |
There was a problem hiding this comment.
At this point flush() has freed the first group's reservation and the stream is suspended in emit().await, before it has pulled the next group. The pool is already at zero before drop(stream). Could we have the input yield two short batches and then return Poll::Pending? Polling the coalescer once and asserting pool.reserved() > 0 before dropping it would exercise cancellation with a live reservation.
There was a problem hiding this comment.
Rewritten. The input yields two short batches and then stays pending. The test checks that memory is held, drops the stream, and checks that the reservation is back to 0.
| -- The second run gives the sort a tiny memory pool and merge reservation so that it spills. | ||
| -- Config: spark.comet.datafusion.execution.sort_spill_reservation_bytes=65536 | ||
| -- ConfigMatrix: spark.comet.exec.memoryPool.fraction=1.0,0.002 | ||
| -- ConfigMatrix: spark.sql.session.timeZone=UTC,America/Los_Angeles |
There was a problem hiding this comment.
Could we keep this file focused on Spark parity for nested values with one configuration and a smaller input? The three matrix dimensions rerun the 200-file setup and six queries eight times. The test durations on this commit sum to 5m58s on Spark 4.1 and 26m56s across the five profiles. Spark 4.1 timings · Other profiles
The new CometTaskMetricsSuite test already verifies that the sort combines batches after the default gate, spills, and honors the toggle. Setting the threshold to zero here would let a handful of small files exercise concatenation from the first block. One time zone and one pool size should cover the nested copy. Metrics test
There was a problem hiding this comment.
Reduced to one configuration, with threshold 0 and one time zone, over 20 files. The metrics test keeps covering the gate, spill and toggle.
|
@comphead Thanks for checking it against |
|
@sunchao Thanks. I made the config opt-in, and here are paired Spark stage timings, flag off vs on (sort stage median, alternating runs in one application):
Below the gate there's no measurable cost. Past the gate, a single-key sort that stays in memory pays for the extra copy, since DataFusion combines its runs anyway. That's another reason to keep this opt-in until something like apache/datafusion#26931 lands. With spilling, the gain grows as blocks shrink. The failed tasks in the spilling runs were |
d1819fd to
aaed42f
Compare
…-read # Conflicts: # docs/source/user-guide/latest/metrics.md
…-read # Conflicts: # native/core/src/execution/planner/join.rs
andygrove
left a comment
There was a problem hiding this comment.
Thanks for making this opt-in and for the paired stage timings. I went through the coalescer against DataFusion's ExternalSorter and the fair pool, and the reservation handling looks right to me. It only uses try_grow, it turns ResourcesExhausted into a flush and a backoff, and it holds nothing while the sort reserves. The shared-column accounting and the guard for other Spark consumers also close the concerns from the earlier round.
One thing I would like in the .doc string for spark.comet.exec.sort.coalesceInput.enabled. It names the memory failure, but not the one shape that gets slower, which is a single-key sort that stays in memory past the gate. Your timings show about 16 percent there (16.51 s to 19.09 s), because the sort pays for a copy that DataFusion's own run combining makes unnecessary. Could the text say that, so someone deciding whether to turn this on sees the cost next to the memory warning? configs.md is generated from that string, so this is the only place it needs to go.
In docs/source/user-guide/latest/metrics.md, the new CometSort section starts with "Native sorts report these additional metrics". Could that say "CometSort reports these additional metrics"? The style guide avoids "native" on its own (T3).
I would also like to see sunchao's re-review of the opt-in change before this merges, since the open memory questions were theirs.
Done |
@sunchao if you could take another look. |
sunchao
left a comment
There was a problem hiding this comment.
Thanks for the opt-in gate and the fair-pool coverage. There is a separate retention case in the grouping logic, even before the pool starts refusing reservations.
| Some(size) => { | ||
| // A batch with another schema starts a new group, since the concat needs one. | ||
| let fits = rows <= self.target_rows - self.rows | ||
| && size.copy <= self.max_bytes - self.copy |
There was a problem hiding this comment.
fits caps the cumulative copy bytes, but checks held bytes only per input. With a 512 KiB cap I fed it 16 one-row Int32 slices from distinct 256 KiB buffers. One pending group held 4,194,304 bytes for 64 bytes of rows and reserved 4,194,368 bytes. This is a non-spillable reservation, so it reduces the fair share available to upstream spillable operators until a flush or refusal. Could we check size.held <= self.max_bytes - self.held here too, and test that a third such slice flushes the first two? The current per-input check accepts all three.
I tried that extra condition locally with the locked dependencies. Peak reservation on the 16-slice input fell from 4,194,368 to 524,296 bytes (512 KiB held plus 8 bytes copied), with all 24 existing coalescer tests passing.
There was a problem hiding this comment.
Thanks, good catch. I added size.held <= self.max_bytes - self.held to the fit check, and the group now also flushes when its held bytes reach the cap. slices_of_separate_buffers_are_capped_by_what_they_hold feeds 16 one-row slices from separate 256 KiB buffers with a 512 KiB cap: they now go out in groups of 2, and without the extra condition all 16 land in one group.
|
@sunchao any more comments? |
andygrove
left a comment
There was a problem hiding this comment.
Thanks for the updates. The .doc string for spark.comet.exec.sort.coalesceInput.enabled now names the single-key in-memory slowdown next to the memory warning, and the metrics.md wording is fixed. I also traced the new size.held <= self.max_bytes - self.held check and the flush at held == max_bytes. self.held never exceeds the cap, so the subtraction cannot underflow, and slices_of_separate_buffers_are_capped_by_what_they_hold pins the behavior.
I have nothing further. The only open item from my last review is sunchao's re-review of the retention fix.
mbutrovich
left a comment
There was a problem hiding this comment.
Thanks @parthchandra, and thanks for working through the memory cases from the earlier rounds. In apache/datafusion#21543 (summary), coalescing paid off when it cut merge fan-in from thousands of runs and lost on multi-column string sorts once runs grew to 32K rows, and the 512 KiB group cap here keeps combined batches near the size of a default 8192-row batch, on the side of that line where DataFusion's per-batch sort already works well.
The description lists two follow-ups (re-evaluating this operator and its default once apache/datafusion#26931 is in Comet's DataFusion, and holding pre-gate input without copying it), but neither has an issue. Could you file one for each before this merges and link them from the description? The re-evaluation issue should name what decides between removing the operator and enabling it by default, for example rerunning sort_small_batches and the spilling stage timings from this PR against the new sorter. Without an issue, the opt-in config and the extra operator will outlive the reason for them.
| /// In `sort_small_batches`, combining 512-row batches made a spilling single-key sort slower, | ||
| /// while 384 rows or fewer was never slower. | ||
| const MAX_SMALL_BATCH_ROWS: usize = 512; |
There was a problem hiding this comment.
This comment states a crossover that the numbers in the description don't show. Combining 512-row batches in a spilling single-key sort went from 51.4 to 54.0 ms (5%), and the description puts laptop noise at 10% to 20%. The 1024-row spilling single-key case, where both sides pass the batches through unchanged, differs by more (40.1 to 42.7 ms). The "never slower" half doesn't hold either: the in-order two-key spilling case at 256 rows went from 49.1 to 51.0 ms.
The limit matters because blocks of 512 to 4095 rows still produce one merge stream each, and #5686 measured 1.49x from coalescing 1024-row batches. Could the 512 and 1024 cases, run with combining on a server CPU (x86_64 with AVX2, which Comet builds for), go in the re-evaluation issue? For this PR, the comment can say what the data supports:
| /// In `sort_small_batches`, combining 512-row batches made a spilling single-key sort slower, | |
| /// while 384 rows or fewer was never slower. | |
| const MAX_SMALL_BATCH_ROWS: usize = 512; | |
| /// The gain shrinks as batches grow. In `sort_small_batches` the differences at 512 rows were | |
| /// within the run's noise, so this limit is a conservative choice rather than a measured | |
| /// crossover. | |
| const MAX_SMALL_BATCH_ROWS: usize = 512; |
There was a problem hiding this comment.
Agreed, the numbers don't show a crossover. I applied your wording, and the description now says the 512-row limit is a conservative choice. The 512 and 1024 cases with combining on, on an x86_64 server, are in #7852.
| "slower, about 16% in one measurement, because DataFusion already combines its runs " + | ||
| "in memory, so the copy is extra work. It helps most when a sort spills over many " + |
There was a problem hiding this comment.
The 16% belongs here, but I don't think the copy is the cause. As I read DataFusion 55.2, without the coalescer ExternalSorter concatenates the raw batches of a single-key sort into runs of up to sort_in_place_threshold_bytes of reserved memory, which is 2x the data (in_mem_sort_stream, coalesce_in_mem_batches_into_runs). That is about 512 KiB of data per run at the default 1 MiB threshold. With the coalescer, each combined batch holds up to 512 KiB and reserves up to 1 MiB, so it fills a run by itself and the sort skips its own concat. Both paths copy each row once into runs of about the same size.
Could we drop the cause from the doc string for now, and put a profile of that stage with the flag off and on in the re-evaluation issue? If the time goes somewhere else, the cost may be avoidable.
| "slower, about 16% in one measurement, because DataFusion already combines its runs " + | |
| "in memory, so the copy is extra work. It helps most when a sort spills over many " + | |
| "slower, about 16% in one measurement. It helps most when a sort spills over many " + |
There was a problem hiding this comment.
Good point. I dropped the cause from the doc string with your wording. The description now says the cause isn't settled, and that both paths copy each row once. A profile of that stage with the flag off and on is item 3 in #7852.
comphead
left a comment
There was a problem hiding this comment.
A second pass, mostly on test reuse, plus one doc sentence and the new metric declarations. The follow-up issues mbutrovich asked for cover the removal question I had.
| "coalesced_input_batches" -> SQLMetrics.createMetric( | ||
| sparkContext, | ||
| "number of small input batches combined into larger ones"), | ||
| "coalesced_output_batches" -> SQLMetrics.createMetric( | ||
| sparkContext, | ||
| "number of batches produced by combining small input batches")) |
There was a problem hiding this comment.
These two are declared on every CometSort, including with the config off, which is the default and leaves them at zero. Other opt-in features declare theirs only when the serialized operator enables them, as CometSortMergeJoinExec does with getRightKeyReductionEnabled and CometHashJoinExec with getDynamicFilterEnabled. Could these be added only when nativeOp.getSort.getCoalesceInput is set? The CometSort section in metrics.md would then say that the last two rows appear only with spark.comet.exec.sort.coalesceInput.enabled=true.
There was a problem hiding this comment.
Done. CometSortExec now declares the two metrics only when nativeOp.getSort.getCoalesceInput is set, like the join operators. metrics.md says they appear only with the config on. With the config off, the CometTaskMetricsSuite test now checks that they are not declared.
| buffers. The coalescer that can sit in front of a native sort also reserves the batches it holds, | ||
| at twice their size to cover the combined copy. So an imported batch that a sort, a join or that |
There was a problem hiding this comment.
"At twice their size" does not match what the coalescer reserves. It reserves what the held batches keep alive plus the copy counted per column, so a batch whose columns share a buffer reserves more than twice its size, and a small slice of a larger buffer less. Could this say it reserves the batches it holds and their combined copy, as the new bullet under "The unified pools" does?
There was a problem hiding this comment.
Fixed. It now says the coalescer reserves the batches it holds plus their combined copy.
| /// Sorts 3000 batches of 60 wide rows in `pool`, optionally combining them first. Returns | ||
| /// how many rows came out, how many times the sort spilled, and how many input batches were | ||
| /// combined. | ||
| async fn sort_small_batches( |
There was a problem hiding this comment.
sort_small_batches and sort_int_batches rebuild what sort_on and try_collect_with in this test module already do, and most of their local use lines repeat the module's imports. Could one helper on top of those two take the input, the config and the coalesce flag, and return the sorted batches with the spill and combine counts? The share test could then also compare the combined output with the plain one. That would cover what a_spilling_sort_gives_the_same_result_from_combined_input and its multi-key twin check in sort_input_coalesce.rs, on Comet's pool instead of DataFusion's GreedyMemoryPool, so those two and their spilling_sort and check_spilling_sort helpers could go. The second sort key does not change what the coalescer does.
There was a problem hiding this comment.
Done. sort_in_pool, built on sort_on and try_collect_with, replaces both helpers. It returns the sorted output with the spill and combine counts. The share test now also checks that the combined output equals the plain one. I removed the two spilling-sort tests and their spilling_sort and check_spilling_sort helpers from sort_input_coalesce.rs.
| } | ||
|
|
||
| #[test] | ||
| fn combines_when_the_pool_holds_the_group_but_not_a_full_one() { |
There was a problem hiding this comment.
This pins what reservation_covers_a_group_and_is_released_after_it already checks after every push, and what the last two asserts of a_copy_of_shared_columns_is_reserved_and_capped check at the exact boundary (held plus copy combines, one byte less does not). Could it go? Also, six places in this module build the same pool, runtime and SessionContext. run_in_pool already covers the body of passes_through_when_memory_is_short, a max_bytes argument would let it replace run_capped, and a small context helper would cover the three stream tests.
There was a problem hiding this comment.
Removed. run_in_pool now takes max_bytes, so it replaces run_capped and the body of passes_through_when_memory_is_short. A context helper builds the pool's SessionContext for the three stream tests.
|
Thanks @mbutrovich. I filed #7852 to re-evaluate the operator once apache/datafusion#26931 is in Comet's DataFusion. It names the runs that decide between removing it and enabling it by default. #7853 covers holding the input before the gate without copying it. Both are linked from the description. |
|
@sunchao can I get another look? (FWIW, ci has passed in the fork but gh is not showing it, I will trigger another re-run) |
Which issue does this PR close?
Closes #5686.
Rationale for this change
A shuffle written by many map tasks into many partitions gives each reduce task one tiny Arrow batch per shuffle block. On a production job, about 330,000 map tasks write to 16,000 partitions, so each reduce task reads about 330,000 blocks of about 62 rows. When the native sort over that input spills, it is extremely slow. In one task,
SortExectook 16,778 s ofelapsed_computefor 19.7 M rows and 5 spills, about 97% of the task. The shuffle read took 33 s.The cause is DataFusion 55.2's
ExternalSorter:sort_and_spill_in_mem_batchescallsin_mem_sort_stream(false, false), which does not combine buffered batches into runs. Every buffered batch becomes its own merge stream, so a spill of about 4 M rows merges about 66,000 streams.BatchBuildercalls arrowinterleaveover every live input batch, for each column and each struct child. The cost per output batch grows with the number of streams.#5686 found the same problem and measured a large native gain. It was set aside after an end-to-end run regressed by 11%. In that run each partition held about 7,800 rows, under the 1 MiB
sort_in_place_threshold_bytes, so the sort never merged: it concatenated in place, and the extraCoalesceBatchesExecwas pure overhead. The issue also pointed out that the coalescer's buffers were not charged to a memory pool. This PR follows the analysis in #5686 and addresses both points.What changes are included in this PR?
SortInputCoalesceExec(native/operators/src/sort_input_coalesce.rs), a new operator in front of a nativeSortExec:spark.comet.batchSizeand fewer than 512 are combined in arrival order. A combined batch holds at mostspark.comet.batchSizerows and half the in-place threshold in bytes, 512 KiB by default, kept between 64 KiB and 4 MiB. The sort then reserves no more for a combined batch than its own in-place threshold. Input batches are never split.ResourcesExhaustedare returned.coalesced_input_batchesandcoalesced_output_batchesare reported under the sort. The operator's time is part of the sort's time.Sortarm adds the coalescer only whenSort.coalesce_input(a new proto field) is set, the sort has no fetch (TopK never merges), the input does not already satisfy the ordering (the sort passes such input through), and no other Spark consumer in the task holds execution memory, using the same check as the semi-join key reduction, since Spark could spill that consumer to grant the coalescer's reservation. When the semi-join key reduction also applies, it goes below the coalescer, because it forwards short blocks it cannot reduce unchanged.spark.comet.exec.sort.coalesceInput.enabled, off by default for now (see below).CometSortExecsets the proto field from it, and declares the two metrics only when it is on.metrics.mdgets aCometSortsection.memory_management.mddescribes the reservation and the limitation below.native/operators/benches/sort_small_batches.rs.Why it is opt-in. A combined batch is larger than the blocks it replaces. The coalescer cannot spill, so the pool checks it only against its size, and it can build a batch larger than the sort may hold. A sort whose share fits the original batches can then fail with "Not enough memory to continue external sort". A test in
fair_pool.rspins a concrete case: with a 768 KiB sort share, the raw batches fit in runs of 24, 24 and 16, but a 512 KiB combined batch costs the sort 1 MiB. Fixing this needs the sort to fall back to the original batches when the combined one does not fit, which apache/datafusion#26931 does by forming runs inside the sorter. Until then this stays opt-in, for workloads like #5686's where the gain is large.Follow-ups, not in this PR:
How are these changes tested?
sort_input_coalesce.rs(22):CometFairMemoryPooltests (fair_pool.rs): a sort whose fair share is halved by a second active spillable consumer spills, finishes with combined input, and gives the same output as without it; it failed with an earlier 1 MiB cap. A second test pins the limitation above: the raw batches fit the sort's share, and the combined batch fails it.skipis wrapped; the semi-join key reduction goes below the coalescer.sql-tests/operators/sort_coalesce_input.sql: compared with Spark, with combining from the first block (in-place threshold 0). Each sort task reads blocks of about 12 rows.CometTaskMetricsSuitecovers the default gate, spilling and the toggle.CometTaskMetricsSuite: a sort over 80 map tasks' small blocks spills and matches Spark. With the config on it combines batches; with it off it does not. The test checks metrics, which a SQL file cannot.sort_small_batches: 200,000 wide rows (fixed-length string key, 8 longs, a struct, no nulls), one or two sort keys, in memory and with a memory limit that forces spills, with keys scattered so every batch spans the whole key range (poorly predicted) and with keys already in order (the most predictable merge). Times in ms, raw -> combined, on a laptop with about +/-10% run-to-run noise. Scattered keys:Keys already in order (two keys sort by a contiguous group and then the key, checked outside the timed loop):
The gain shrinks as batches grow. When 512-row batches were combined, a spilling single-key sort went from 51.4 to 54.0 ms, which is within this laptop's noise, so the 512-row limit is a conservative choice rather than a measured crossover. #7852 asks for the 512 and 1024 cases with combining on, on an x86_64 server. Multi-key sorts gain the most, even in memory, where DataFusion does not combine runs itself.
Cost: batches the coalescer passes through are unchanged. The cases that pass through are within noise, which on this laptop is up to about 20% between back-to-back runs: for example, raw 384-row in-order spilling runs alone ranged from 52 to 75 ms. An earlier two-key in-order run showed an 18% slowdown at 1024 rows, but its group key wrapped around, so the input was not in order; with contiguous groups it is 49.6 -> 49.0 ms. Below the gate, every batch is measured once more than before, which the TPC-H runs below include.
spark.rangedata,sortWithinPartitionsafter a hash repartition, 2 executors x 8 cores, AQE off; one warm-up per setting, then alternating off/on runs in one application; the sort stage is the stage that reads the shuffle):Below the gate there is no cost; this is the case where perf: coalesce small shuffle-read batches before native sort #5686's earlier attempt was 11.6% slower.
Past the gate, a single-key sort that stays in memory is about 16% slower. This is the second reason the flag is opt-in. The cause is not settled. Without the coalescer, DataFusion 55.2 concatenates a single-key sort's batches into runs of about the same size, so both paths copy each row once. Re-evaluate SortInputCoalesceExec once DataFusion's sorter combines small batches #7852 asks for a profile of this stage with the flag off and on.
With spilling, the gain grows as blocks get smaller: about 5% and not consistent with ~200-row blocks, about 9% and consistent with ~50-row blocks. These rows are narrow (a long key, eight longs, a short string). perf: coalesce small shuffle-read batches before native sort #5686's job had 62-row blocks of much wider rows and about 66,000 merge streams per spill, and the microbenchmark is 3.3x faster when spilling at 16 rows per batch.
The spilling runs had failed tasks with both settings (32 and 32 at 512m, 20 off and 12 on at 256m), all
Additional allocation failed for ExternalSorterMergeunder the small pools; retries succeeded.End-to-end: TPC-H SF100 on one machine (Spark 4.0 standalone, 2 executors x 8 cores), with
spark.comet.exec.sort.coalesceInput.enabledoff and on,spark.sql.shuffle.partitions=2000and AQE partition coalescing off, at 16g and at 2g off-heap. Three iterations each; times are the average.