Skip to content

perf(sort-merge): cache current-row bytes in RowValues for SortPreservingMerge - #23990

Open
zhuqi-lucas wants to merge 2 commits into
apache:mainfrom
zhuqi-lucas:perf/spm-rowvalues-cache
Open

perf(sort-merge): cache current-row bytes in RowValues for SortPreservingMerge#23990
zhuqi-lucas wants to merge 2 commits into
apache:mainfrom
zhuqi-lucas:perf/spm-rowvalues-cache

Conversation

@zhuqi-lucas

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Part of the SortPreservingMerge cursor-cache work in #23840, split into smaller PRs for easier review (per @alamb / @rluvaton). This one carries the largest share of the win.

Rationale for this change

SortPreservingMerge compares cursor heads in a loser tree; every emitted row triggers log2(k) compare calls. For multi-column sort keys the key is serialized into arrow Rows and wrapped in RowValues, and each compare called Rows::row(idx) for both sides — walking Arc<Rows>offsets[idx] / offsets[idx+1] → buffer slice.

The offsets buffer (~65 KB per batch per partition, ×16 partitions) is far too large to stay cache-resident, so those lookups typically land in L2/L3 with a DRAM tail — and they are repeated for the same idx on every compare of a stable loser-tree head, even though the answer never changes until the cursor advances.

What changes are included in this PR?

Cache the current row's (ptr, len) once per Cursor::advance (via the existing CursorValues::set_offset hook) and read it in compare, so the hot path resolves to two plain field loads plus a memcmp instead of two Arc-chased offset walks.

  • The pointer is into the Arc-owned buffer heap and stays valid across struct moves (a cursor is written into a Vec<Option<Cursor<..>>> slot), so Send/Sync are implemented by hand with a SAFETY note.
  • eq / eq_to_previous take arbitrary cross-batch indices and continue to index Rows directly (the cache only holds the current offset).
  • compare keeps a debug-only assert that the cache invariant holds (indices equal the cursors' current offsets).

Only datafusion/physical-plan/src/sorts/cursor.rs changes. Follow-up PRs will apply the same pattern to the single-column string cursors (ByteArrayValues, StringViewArray) and add a null-wrapper fast path.

Are these changes tested?

Yes:

  • test_row_values_cache_matches_rows_index drives the cache across every offset of a multi-row batch and asserts identical ordering to per-row Rows indexing, plus the cross-batch eq path.
  • test_row_values_single_row_batch covers the up-front row-0 cache and the length snapshot.
  • Verified red/green: breaking set_offset (skip the refresh) makes the first test fail as expected.
  • Existing sorts::* merge tests (83) pass.

Are there any user-facing changes?

No API changes. The sort_tpch10 benchmark from the combined series (#23840) showed the multi-column queries driven by this cache: Q4 +1.23x, Q9 +1.15x, Q8 +1.13x, Q5 / Q6 / Q11 ~+1.12x; no regressions. CI benchmark to confirm on this split.

…vingMerge

Multi-column sorts serialize the sort key into arrow `Rows` and wrap it in
`RowValues`. Every loser-tree comparison called `Rows::row(idx)` for each
side, and each call walks `Arc<Rows>` -> offsets[idx] / offsets[idx+1] ->
buffer slice. The offsets buffer is far too large to stay cache-resident,
so those lookups typically cost an L2/L3 hit with a DRAM tail — repeated
for the same idx on every compare of a stable loser-tree head.

Cache the current row's `(ptr, len)` once per `Cursor::advance` (via the
existing `CursorValues::set_offset` hook) and read it in `compare`, so the
hot path resolves to two plain field loads plus a memcmp. The pointer is
into the Arc-owned buffer heap and stays valid across struct moves (the
cursor is written into a `Vec<Option<Cursor<..>>>` slot), so `Send`/`Sync`
are implemented by hand with a SAFETY note. `eq` / `eq_to_previous` take
arbitrary cross-batch indices and continue to index `Rows` directly.

This is the first of a series splitting apart the SPM cursor-cache work
for easier review; it carries the largest share of the win (multi-column
sort-tpch). Follow-ups add the same pattern to the single-column string
cursors and a null-wrapper fast path.

sort_tpch10 benchmark on the full series showed the multi-column queries
(Q4 +1.23x, Q8 +1.13x, Q9 +1.15x, Q5/Q6/Q11 ~+1.12x) driven by this cache.

Tests: `test_row_values_cache_matches_rows_index` checks the cached
ordering against per-row `Rows` indexing across every offset of a batch,
including the cross-batch `eq` path; `test_row_values_single_row_batch`
covers the up-front row-0 cache. Existing `sorts::*` merge tests (83)
pass.
Copilot AI review requested due to automatic review settings July 30, 2026 07:49

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@codecov-commenter

codecov-commenter commented Jul 30, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 80.85%. Comparing base (2e3626e) to head (5fbe9bf).
⚠️ Report is 20 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #23990      +/-   ##
==========================================
+ Coverage   80.75%   80.85%   +0.09%     
==========================================
  Files        1096     1099       +3     
  Lines      373588   374361     +773     
  Branches   373588   374361     +773     
==========================================
+ Hits       301691   302686     +995     
+ Misses      53896    53615     -281     
- Partials    18001    18060      +59     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@zhuqi-lucas

Copy link
Copy Markdown
Contributor Author

run benchmark sort_tpch10

@adriangbot

Copy link
Copy Markdown

🤖 Benchmark running (GKE) | trigger
Instance: c4a-highmem-16 (12 vCPU / 65 GiB) | Linux bench-c5138910480-1316-7j2vh 6.12.85+ #1 SMP Mon May 11 08:17:35 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 perf/spm-rowvalues-cache (5fbe9bf) to 2e3626e (merge-base) diff using: sort_tpch10
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)

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 perf_spm-rowvalues-cache
--------------------
Benchmark sort_tpch10.json
--------------------
┏━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓
┃ Query ┃                                   HEAD ┃               perf_spm-rowvalues-cache ┃        Change ┃
┡━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩
│ Q1    │   1672.16 / 1674.68 ±1.57 / 1676.47 ms │   1694.16 / 1706.26 ±7.46 / 1716.21 ms │     no change │
│ Q2    │  1487.46 / 1528.62 ±36.62 / 1593.04 ms │  1449.72 / 1488.04 ±27.82 / 1527.19 ms │     no change │
│ Q3    │  8679.26 / 8763.78 ±52.94 / 8822.65 ms │  8727.02 / 8797.48 ±41.24 / 8839.28 ms │     no change │
│ Q4    │  2893.02 / 2928.22 ±20.11 / 2954.84 ms │  2353.71 / 2389.91 ±28.48 / 2435.56 ms │ +1.23x faster │
│ Q5    │  2647.61 / 2666.26 ±14.09 / 2686.96 ms │  2467.76 / 2487.99 ±12.43 / 2501.97 ms │ +1.07x faster │
│ Q6    │   2817.12 / 2823.40 ±6.38 / 2831.64 ms │  2606.12 / 2624.04 ±14.18 / 2645.42 ms │ +1.08x faster │
│ Q7    │  5590.97 / 5621.97 ±29.22 / 5675.82 ms │  5331.17 / 5376.25 ±34.36 / 5432.28 ms │     no change │
│ Q8    │  4084.66 / 4199.36 ±64.61 / 4264.69 ms │ 3544.91 / 3724.45 ±102.35 / 3825.96 ms │ +1.13x faster │
│ Q9    │  4537.55 / 4594.72 ±61.80 / 4689.50 ms │ 3954.48 / 4061.63 ±104.11 / 4189.65 ms │ +1.13x faster │
│ Q10   │ 7130.17 / 7325.03 ±135.51 / 7505.43 ms │ 6418.37 / 6756.10 ±179.65 / 6919.42 ms │ +1.08x faster │
│ Q11   │  3566.59 / 3603.52 ±58.02 / 3719.08 ms │ 3542.86 / 3620.18 ±119.63 / 3857.81 ms │     no change │
└───────┴────────────────────────────────────────┴────────────────────────────────────────┴───────────────┘
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┓
┃ Benchmark Summary                       ┃            ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━┩
│ Total Time (HEAD)                       │ 45729.56ms │
│ Total Time (perf_spm-rowvalues-cache)   │ 43032.32ms │
│ Average Time (HEAD)                     │  4157.23ms │
│ Average Time (perf_spm-rowvalues-cache) │  3912.03ms │
│ Queries Faster                          │          6 │
│ Queries Slower                          │          0 │
│ Queries with No Change                  │          5 │
│ Queries with Failure                    │          0 │
└─────────────────────────────────────────┴────────────┘

Resource Usage

sort_tpch10 — base (merge-base)

Metric Value
Wall time 230.1s
Peak memory 19.3 GiB
Avg memory 7.5 GiB
CPU user 890.2s
CPU sys 78.1s
Peak spill 0 B

sort_tpch10 — branch

Metric Value
Wall time 220.1s
Peak memory 19.5 GiB
Avg memory 7.5 GiB
CPU user 845.9s
CPU sys 76.3s
Peak spill 0 B

File an issue against this benchmark runner

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.

4 participants