Skip to content

Spill groups of sorted runs whose merge keys fit - #27724

Open
brancz wants to merge 1 commit into
apache:mainfrom
dash0hq:sort-spill-alloc-fallback
Open

brancz wants to merge 1 commit into
apache:mainfrom
dash0hq:sort-spill-alloc-fallback

Conversation

@brancz

@brancz brancz commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

Rationale for this change

When a sort runs out of memory, it spills its buffered batches to disk. Before writing anything, the spill merges all buffered sorted runs into one file, and the row-format merge converts the sort keys of every run's first batch at once. Dictionary keys, including run-end-encoded and struct-wrapped ones, are decoded into their values in the row format, so these keys can be many times larger than the buffered data. The spill then fails with ResourcesExhausted before it has released any input, so a sort that should spill fails instead.

#27043 avoided the merge for selected spills by predicting which keys might expand. Predictions miss some cases, such as nested dictionaries, and also catch cases that would have fit, such as short strings or low-expansion dictionaries. Those spills then pay for extra spill files, extra disk usage and lost parallel preparation.

What changes are included in this PR?

Convert the keys of each run's first batch one run at a time instead. When the pool refuses a run, merge and spill the runs added so far, which releases their memory, then continue with the refused run. A run whose keys do not fit alone is spilled unmerged. When all keys fit, the spill writes one file as before, so sorts that succeeded on main write the same spill files.

What is the testing strategy for this PR?

Unit tests.

Are there any user-facing changes?

No, just enhanced spill behavior.

@alamb @kosiew

A spill of several buffered runs merges them into one file. Before
writing anything, the row-format merge converts the keys of the first
batch of every run. Dictionary keys, including run-end-encoded and
struct-wrapped ones, can expand far beyond the pool, so the spill
fails with ResourcesExhausted before it releases any input.

Convert the keys of each run's first batch one run at a time instead.
When the pool refuses a run, merge and spill the runs added so far,
which releases their memory, then continue with the refused run. A run
whose keys do not fit alone is spilled unmerged. When all keys fit,
the spill writes one file as before, so sorts that succeeded on main
write the same spill files.

Co-authored-by: Amp <amp@ampcode.com>
@github-actions github-actions Bot added the physical-plan Changes to the physical-plan crate label Nov 24, 2026
@kosiew

kosiew commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

run benchmark sort_tpch

env:
  DATAFUSION_EXECUTION_TARGET_PARTITIONS: "1"
  DATAFUSION_RUNTIME_MEMORY_LIMIT: "128M"

@adriangbot

Copy link
Copy Markdown

🤖 Benchmark running (GKE) | trigger
Instance: c4a-highmem-16 (12 vCPU / 65 GiB) | Linux bench-c7186944697-5753-8l2dp 6.12.105+ #1 SMP Sat Sep 19 07:55:25 UTC 2026 aarch64 GNU/Linux

CPU Details (lscpu)
Architecture:                            aarch64
CPU op-mode(s):                          64-bit
Byte Order:                              Little Endian
CPU(s):                                  16
On-line CPU(s) list:                     0-15
Vendor ID:                               ARM
Model name:                              Neoverse-V2
Model:                                   1
Thread(s) per core:                      1
Core(s) per cluster:                     16
Socket(s):                               -
Cluster(s):                              1
Stepping:                                r0p1
BogoMIPS:                                2000.00
Flags:                                   fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache:                               1 MiB (16 instances)
L1i cache:                               1 MiB (16 instances)
L2 cache:                                32 MiB (16 instances)
L3 cache:                                80 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-15
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; CSV2, BHB
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected

Comparing sort-spill-alloc-fallback (e16c63a) to 9d894e1 (merge-base) diff

Run configuration
run benchmark sort_tpch
env:
  DATAFUSION_EXECUTION_TARGET_PARTITIONS: "1"
  DATAFUSION_RUNTIME_MEMORY_LIMIT: "128M"

Results will be posted here when complete


File an issue against this benchmark runner

@adriangbot

Copy link
Copy Markdown

🤖 Benchmark completed (GKE) | trigger

Instance: c4a-highmem-16 (12 vCPU / 65 GiB)

Comparing sort-spill-alloc-fallback (e16c63a) to 9d894e1 (merge-base) diff

Run configuration
run benchmark sort_tpch
env:
  DATAFUSION_EXECUTION_TARGET_PARTITIONS: "1"
  DATAFUSION_RUNTIME_MEMORY_LIMIT: "128M"
CPU Details (lscpu)
Architecture:                            aarch64
CPU op-mode(s):                          64-bit
Byte Order:                              Little Endian
CPU(s):                                  16
On-line CPU(s) list:                     0-15
Vendor ID:                               ARM
Model name:                              Neoverse-V2
Model:                                   1
Thread(s) per core:                      1
Core(s) per cluster:                     16
Socket(s):                               -
Cluster(s):                              1
Stepping:                                r0p1
BogoMIPS:                                2000.00
Flags:                                   fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache:                               1 MiB (16 instances)
L1i cache:                               1 MiB (16 instances)
L2 cache:                                32 MiB (16 instances)
L3 cache:                                80 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-15
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; CSV2, BHB
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected
Details

Comparing HEAD and sort-spill-alloc-fallback
--------------------
Benchmark sort_tpch1.json
--------------------
┏━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━┓
┃ Query ┃       HEAD ┃ sort-spill-alloc-fallback ┃    Change ┃
┡━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━┩
│ Q1    │  339.17 ms │                 344.41 ms │ no change │
│ Q2    │  336.83 ms │                 335.57 ms │ no change │
│ Q3    │ 1745.65 ms │                1748.04 ms │ no change │
│ Q4    │  454.80 ms │                 452.36 ms │ no change │
│ Q5    │  985.73 ms │                 988.88 ms │ no change │
│ Q6    │ 1069.52 ms │                1074.89 ms │ no change │
│ Q7    │ 1770.82 ms │                1770.27 ms │ no change │
│ Q8    │ 1078.28 ms │                1075.96 ms │ no change │
│ Q9    │ 1191.23 ms │                1184.06 ms │ no change │
│ Q10   │ 2682.51 ms │                2687.82 ms │ no change │
│ Q11   │  925.17 ms │                 930.03 ms │ no change │
└───────┴────────────┴───────────────────────────┴───────────┘
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┓
┃ Benchmark Summary                        ┃            ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━┩
│ Total Time (HEAD)                        │ 12579.71ms │
│ Total Time (sort-spill-alloc-fallback)   │ 12592.30ms │
│ Average Time (HEAD)                      │  1143.61ms │
│ Average Time (sort-spill-alloc-fallback) │  1144.75ms │
│ Queries Faster                           │          0 │
│ Queries Slower                           │          0 │
│ Queries with No Change                   │         11 │
│ Queries with Failure                     │          0 │
└──────────────────────────────────────────┴────────────┘

Distribution per query (min / mean ±stddev / max):

Comparing HEAD and sort-spill-alloc-fallback
--------------------
Benchmark sort_tpch1.json
--------------------
┏━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━┓
┃ Query ┃                                  HEAD ┃             sort-spill-alloc-fallback ┃    Change ┃
┡━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━┩
│ Q1    │     339.17 / 347.68 ±8.44 / 363.38 ms │     344.41 / 347.95 ±5.36 / 358.31 ms │ no change │
│ Q2    │     336.83 / 341.92 ±5.88 / 350.70 ms │     335.57 / 344.61 ±7.25 / 354.01 ms │ no change │
│ Q3    │  1745.65 / 1753.42 ±6.45 / 1764.33 ms │  1748.04 / 1754.16 ±4.64 / 1760.46 ms │ no change │
│ Q4    │     454.80 / 464.66 ±7.96 / 475.71 ms │     452.36 / 461.05 ±5.60 / 468.04 ms │ no change │
│ Q5    │     985.73 / 988.05 ±2.22 / 992.09 ms │    988.88 / 994.39 ±6.91 / 1007.70 ms │ no change │
│ Q6    │  1069.52 / 1082.90 ±8.48 / 1093.82 ms │  1074.89 / 1081.60 ±4.71 / 1088.10 ms │ no change │
│ Q7    │ 1770.82 / 1789.27 ±21.26 / 1829.65 ms │  1770.27 / 1779.72 ±7.42 / 1788.87 ms │ no change │
│ Q8    │  1078.28 / 1084.73 ±5.50 / 1092.52 ms │  1075.96 / 1079.29 ±3.07 / 1084.79 ms │ no change │
│ Q9    │  1191.23 / 1199.43 ±5.24 / 1204.24 ms │  1184.06 / 1186.90 ±3.09 / 1192.27 ms │ no change │
│ Q10   │ 2682.51 / 2704.89 ±17.05 / 2734.53 ms │ 2687.82 / 2705.05 ±12.49 / 2725.64 ms │ no change │
│ Q11   │     925.17 / 935.55 ±8.00 / 948.95 ms │     930.03 / 932.69 ±2.33 / 935.93 ms │ no change │
└───────┴───────────────────────────────────────┴───────────────────────────────────────┴───────────┘
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┓
┃ Benchmark Summary                        ┃            ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━┩
│ Total Time (HEAD)                        │ 12692.50ms │
│ Total Time (sort-spill-alloc-fallback)   │ 12667.41ms │
│ Average Time (HEAD)                      │  1153.86ms │
│ Average Time (sort-spill-alloc-fallback) │  1151.58ms │
│ Queries Faster                           │          0 │
│ Queries Slower                           │          0 │
│ Queries with No Change                   │         11 │
│ Queries with Failure                     │          0 │
└──────────────────────────────────────────┴────────────┘

Memory Pool Peaks

Peak MemoryPool reservation per query — what DataFusion's accounting believes it reserved. Recorded only for benchmarks that write a results JSON (the dfbench suites, and the suites bench.sh runs through the Criterion SQL harness since #25644), and only under a memory limit: DATAFUSION_RUNTIME_MEMORY_LIMIT, or one the suite sets itself.

Base: 9d894e1 (merge-base) | Changed: sort-spill-alloc-fallback

sort_tpch — sort_tpch1

Query Base Changed Change
1 128.1 MiB 128.1 MiB +0.0%
2 127.8 MiB 127.8 MiB +0.0%
3 141.8 MiB 141.8 MiB +0.0%
4 128.0 MiB 128.0 MiB +0.0%
5 128.0 MiB 128.0 MiB +0.0%
6 127.8 MiB 127.8 MiB +0.0%
7 127.2 MiB 127.2 MiB +0.0%
8 128.0 MiB 128.0 MiB +0.0%
9 127.7 MiB 127.7 MiB +0.0%
10 127.7 MiB 127.7 MiB +0.0%
11 132.3 MiB 132.3 MiB +0.0%

Pool accounting vs. process RSS

Max pool peak is the largest reservation any single query in the run reached; peak RSS covers the whole invocation, including data loading and allocator retention, and the two high-water marks need not coincide in time. The gap is therefore an upper bound on what the pool did not account for, not a measurement of it.

Benchmark Side Max pool peak Peak RSS Gap RSS / pool
sort_tpch base (9d894e1 (merge-base)) 141.8 MiB 1021.0 MiB 879.2 MiB 7.2×
sort_tpch changed (sort-spill-alloc-fallback) 141.8 MiB 902.8 MiB 761.0 MiB 6.4×
Resource Usage

sort_tpch — base (merge-base)

Metric Value
Wall time 65.0s
Peak memory 1021.0 MiB
Avg memory 717.9 MiB
CPU user 70.4s
CPU sys 22.1s
Peak spill 1.2 GiB

sort_tpch — branch

Metric Value
Wall time 65.0s
Peak memory 902.8 MiB
Avg memory 671.7 MiB
CPU user 70.4s
CPU sys 21.9s
Peak spill 1.2 GiB

File an issue against this benchmark runner

@kosiew kosiew left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@brancz,

Thanks for addressing the row-format expansion problem. Grouping runs based on actual memory availability is preferable to predicting key expansion and preserves parallel run preparation.

However, successful first-batch admission does not guarantee that a merge can finish spilling. We need to address this remaining failure path before merging.

break;
}
}
let sorted_stream = if cursors.partitions() > 0 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

First-batch admission cannot prevent refill failures. Spill singletons directly, preserving primed batches, and ensure multi-run merges can finish or safely fall back without losing or duplicating rows. Add a SortExec ingestion-spill regression with within-run key expansion, including multi-run refill if supported.

async fn test_ingestion_spill_groups_cleanup(#[case] fail: bool) -> Result<()> {
let keys = EncodedKeys::new(KeyShape::Dictionary, |_| 64);
let files = Arc::new(GatedFiles {
// The fourth file of the first ingestion spill

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we track finish() calls and gate the write after an earlier group completes within the same ingestion spill, rather than relying on a fixed file index? Retain the abort and resource cleanup assertions.

Comment on lines 594 to 595
/// Sorts the in-memory batches and merges them into a single sorted run, then writes
/// the result to spill files.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we update this documentation to reflect that one ingestion spill can produce multiple sorted files? Please also update spill_runs documentation to reflect the final admission and fallback policy.

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

Labels

physical-plan Changes to the physical-plan crate

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants