← Back to Pull requests

perf: combine small input batches before a native sort that merges them #7696

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Nov 19, 2026 21:39 UTC
Author

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, SortExec took 16,778 s of elapsed_compute for 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:

  • When it spills, sort_and_spill_in_mem_batches calls in_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.

  • For every output batch, BatchBuilder calls arrow interleave over every live input batch, for each column and each struct child. The cost per output batch grows with the number of streams.

  • Without spilling, DataFusion combines runs only for single-key sorts. Multi-key sorts merge one stream per batch either way.
  • #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 extra CoalesceBatchesExec was 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 native SortExec:

  • - Gate: batches pass through unchanged until a task's sort input reaches the sort's in-place threshold, counted the way the sort counts it. Small sorts, the case that regressed in #5686, are unaffected.
    - Combining: after the gate, batches with fewer rows than half of spark.comet.batchSize and fewer than 512 are combined in arrival order. A combined batch holds at most spark.comet.batchSize rows 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.
    - Memory: it reserves exactly what it holds, in a consumer that cannot spill: the batches it keeps alive, and the combined copy, which counts a buffer once per column that uses it, so columns that share a buffer cannot make the copy outgrow the cap. It releases the reservation before the combined batch reaches the sort, so it holds nothing while the sort reserves. If the pool refuses, it hands the group and the batch to the sort and passes the next 64 small batches through before asking again. Errors other than ResourcesExhausted are returned.
    - Never combined: batches with a different schema start a new group. Batches with small dictionary keys or small run-end types, at any nesting depth, pass through, since concatenating them can overflow the key type. A small slice of a large batch counts as large and passes through.
    - Metrics: coalesced_input_batches and coalesced_output_batches are reported under the sort. The operator's time is part of the sort's time.
  • Planner: the Sort arm adds the coalescer only when Sort.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.

  • Config: spark.comet.exec.sort.coalesceInput.enabled, off by default for now (see below). CometSortExec sets the proto field from it and declares the two metrics.

  • Docs:

  • - metrics.md gets a CometSort section.
    - memory_management.md describes the reservation and the limitation below.
  • Benchmark: 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.rs pins 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:

  • apache/datafusion#26931 combines small batches into runs inside the sorter, keeping the original batches if a run cannot be admitted. Once it is available in Comet's DataFusion, this operator may be unnecessary, or can be enabled by default. The two-key in-memory numbers below are relevant there: DataFusion 55.2 keeps multi-key sorts at one run per batch, and sort_small_batches shows combining is faster for tiny batches.

  • Hold the input before the gate without copying it, so the start of each task's input is combined too.
  • How are these changes tested?

  • Rust unit tests in sort_input_coalesce.rs (25):

  • - Gate and grouping: pass-through below the gate without a copy; the gate's byte counting; the row target, byte cap and 512-row limit; large batches flushing the group first; empty, zero-row and zero-column batches.
    - Memory: the reservation covers exactly the held batches and the copy, and is released; a copy of columns that share one buffer is reserved per column and capped; small slices of separate large buffers are capped by what they keep alive; nothing is held while the sort receives a batch; a refused reservation flushes the held group first, then backoff and resumption; combining when the pool fits the group but not a full one.
    - Errors and early drop: an input error reaches the sort and releases memory; dropping the stream while it holds a group releases the reservation.
    - Batches never combined: schema changes; small dictionary keys at the top level, in a struct and in a list; slices of large batches.
    - Metrics: a rebuilt node reports through the original's metrics.
    - Types: a nested map, list and struct mix, decimal(38,10) at its limits, years 1 and 9999, a time zone, CJK and other non-ASCII strings, and dictionaries.
    - Spilling sorts: single-key and multi-key spilling SortExecs give identical output with and without the coalescer.
  • CometFairMemoryPool tests (fair_pool.rs): a sort whose fair share is halved by a second active spillable consumer spills and finishes with combined input; 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.

  • Planner tests (4): only a full sort over unordered input is wrapped, with the session's batch size and threshold; a sort with only a skip is 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.

  • - The data covers nested structs, maps and arrays of structs, decimal bounds, dates, timestamps and timestamp_ntz from year 1 to 9999, and non-ASCII strings.
    - Sort keys include a single string key, multiple keys with both null orderings, and a struct field.
    - One configuration, with a non-UTC session time zone. CometTaskMetricsSuite covers 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.

  • Micro-benchmark 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:
  • | Rows per input batch | In memory, 1 key | In memory, 2 keys | Spilling, 1 key | Spilling, 2 keys |
    | --- | --- | --- | --- | --- |
    | 16 | 86.3 -> 51.9 | 345.9 -> 71.0 | 256.2 -> 79.3 | 257.0 -> 87.0 |
    | 64 | 38.8 -> 31.9 | 116.6 -> 43.1 | 102.0 -> 58.6 | 105.5 -> 65.1 |
    | 256 | 32.1 -> 29.7 | 47.7 -> 31.3 | 64.2 -> 57.4 | 59.0 -> 52.8 |
    | 384 | 31.2 -> 28.3 | 39.6 -> 29.2 | 58.0 -> 57.0 | 56.0 -> 49.7 |
    | 1024 (passed through) | 27.0 -> 27.2 | 32.0 -> 32.1 | 40.1 -> 42.7 | 48.2 -> 49.6 |

    Keys already in order (two keys sort by a contiguous group and then the key, checked outside the timed loop):

    | Rows per input batch | In memory, 1 key | In memory, 2 keys | Spilling, 1 key | Spilling, 2 keys |
    | --- | --- | --- | --- | --- |
    | 16 | 66.2 -> 38.3 | 268.5 -> 55.2 | 221.0 -> 68.3 | 236.5 -> 94.2 |
    | 64 | 29.2 -> 22.1 | 67.6 -> 27.2 | 76.6 -> 47.4 | 112.4 -> 65.2 |
    | 256 | 19.7 -> 18.1 | 24.2 -> 19.4 | 44.7 -> 42.5 | 49.1 -> 51.0 |
    | 1024 (passed through) | 16.9 -> 17.1 | 16.0 -> 16.0 | 34.5 -> 34.3 | 49.6 -> 49.0 |

    When 512-row batches were combined, a spilling single-key sort got slower (51.4 -> 54.0 ms), so the limit is fewer than 512 rows. 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 stage timings, flag off vs on (spark.range data, sortWithinPartitions after 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):
  • | Workload | Spill | Runs | Sort stage, median (s) | Change |
    | --- | --- | --- | --- | --- |
    | #5686's case: 1 M rows (long, double, string), 128 map tasks x 128 partitions, 16g | none | 5 | 1.30 -> 1.22 | none measurable (runs overlap) |
    | 40 M wide rows, 2000 x 400, 1g: past the gate, in memory | none | 5 | 16.51 -> 19.09 | +16% |
    | 80 M wide rows, 4000 x 100 (blocks of ~200 rows), 512m | ~4.6 GB | 9 | 15.85 -> 14.84 | -6% (mean -5%; faster in 5 of 9 pairs) |
    | 40 M wide rows, 8000 x 100 (blocks of ~50 rows), 256m | ~2.3 GB | 7 | 24.96 -> 22.81 | -9% (faster in 6 of 7 pairs; stage wall -7%) |

    - Below the gate there is no cost; this is the case where #5686's earlier attempt was 11.6% slower.
    - Past the gate, a single-key sort that stays in memory pays for the extra copy: DataFusion already combines its runs, so the coalescer's copy is wasted. This is the second reason the flag is opt-in.
    - 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). #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 ExternalSorterMerge under 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.enabled off and on, spark.sql.shuffle.partitions=2000 and AQE partition coalescing off, at 16g and at 2g off-heap. Three iterations each; times are the average.
  • | Off-heap | Off (s) | On (s) | Change | Failed tasks, on |
    | --- | --- | --- | --- | --- |
    | 16g | 1148.3 | 1144.9 | -0.3% | 0 |
    | 2g | 1257.7 | 1234.8 | -1.8% | 0 |

    - The coalescer combined batches in q3, q4, q9, q10 and q21, including about 8.4 M small batches in q9 and 5.2 M in q10. Those queries changed by 1% or less: their sorts did not spill and are not where the time goes. TPC-H does not reach the spill-heavy sort over tiny blocks that #5686 describes, so this run shows that the change costs nothing on a standard workload, not the speed-up.
    - No query failed with the coalescer on, and spill counts did not change. The only failures were in the run with it off: an executor was lost during one q5 iteration (256.8 s against about 87 s for the others), which is left out of the 16g "off" total above (1204.9 s with it).
    - q11 (about 3 s or 25 s per iteration whatever the setting) and q12 (82 to 112 s) vary too much between iterations to compare. q7 was about 10% slower with the coalescer on at 16g, though nothing was combined there. That could be the cost of the extra operator described above, or noise; three iterations do not separate the two.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: sunchao Review duration: 16147m
    All Vouch review confidence checks passed
    Residual risk 0.28 = Change Risk (0.52) × (1 − Review Confidence (0.47)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    46%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #7696"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 46.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 46.7% · Lower = rushed or shallow review
    46.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 27.7% · Safe to merge
    27.7%