Skip to content

perf: keep first_value/last_value group orderings in the arrow row format - #27047

Open
akupchinskiy wants to merge 3 commits into
apache:mainfrom
akupchinskiy:first-last-tz-ordering-contention
Open

akupchinskiy wants to merge 3 commits into
apache:mainfrom
akupchinskiy:first-last-tz-ordering-contention

Conversation

@akupchinskiy

@akupchinskiy akupchinskiy commented Nov 3, 2026 •

Copy link
Copy Markdown

Which issue does this PR close?

Rationale for this change

FirstLastGroupsAccumulator keeps each group's winning ordering values as Vec<ScalarValue>. Every updated group builds, clones and compares ScalarValues, and for a time zone aware timestamp every clone also touches the time zone's shared Arc<str>, which is why that case got slower with more partitions. As suggested in review, this PR fixes the storage instead of the time zone symptom.

What changes are included in this PR?

In datafusion/functions-aggregate/src/first_last.rs:

  • New GroupOrderings with two implementations:
    • OrderingRows: orderings in the arrow row format, compared as bytes. Fixed-width ordering types share one buffer with the rows back to back; variable-width types use one reusable buffer per group. Groups without a winner store the encoding of all-null orderings.
    • ScalarOrderings: the previous ScalarValue storage, kept for ordering types whose row encoding does not order like compare_rows (nested and union types) or does not decode back to the planned type (checked once with a round trip in try_new).
  • row_comparable decides the path per ordering type: flat types and dictionaries of them use rows.
  • evaluate does not decode orderings; state decodes them and casts dictionaries back, so the intermediate state schema is unchanged. EmitTo::First drains in place; when more than half of the fixed-width rows are taken, the kept rows move to a right-sized buffer, and shrink_to_fit shrinks the ordering storage, so emitted groups release their memory.
  • A dictionary ordering column is compacted after take when it has more than MAX_DICTIONARY_VALUES_PER_ROW values per selected row (as map_dictionary_values does), so a batch with a few candidates does not encode the whole dictionary.
  • size() accounts for the row buffers (cached for the ScalarValue path).

The non-grouped accumulators are unchanged.

Are these changes tested?

  • New unit tests: test_group_orderings_storage_by_type (which path each type takes), test_group_acc_row_orderings_time_zone (time zone aware orderings, state emitted in parts and merged), test_group_acc_string_and_dictionary_orderings, test_row_orderings_compare_like_scalars (for every type on the row path and all four sort options, with nulls and ties, the winner, state and merge match compare_rows over ScalarValues), test_scalar_orderings_fallbacks (union DESC, dictionaries of boolean / duration / interval, lists with nulls), test_group_acc_shrink_after_partial_emit, test_group_acc_shrink_var_rows, test_scalar_orderings_size_counts_headers_once, test_row_orderings_sparse_dictionary.
  • aggregate.slt (kept from the first version of this PR): first_value / last_value ordered by a Timestamp(µs, "+05:00") column over a UNION ALL of two tables (partial states merged), with NULL orderings, ties broken by a second key, the time zone aware column as the second key, DESC, and the time zone aware value as the result.
  • All datafusion-functions-aggregate tests, datafusion-physical-plan aggregate tests, clippy, and the sqllogictest files that use first_value / last_value / DISTINCT ON (aggregate, group_by, distinct_on, first_last_, window, joins and others) pass.
  • Benchmark first_last_orderings (added in this PR; Q05 and Q06 are new in this version): benchmark_runner first_last_orderings -n <partitions> -i 5, main and this branch interleaved over 3 rounds, median ms, MacBook M2 Pro:
query partitions 1 / 4 / 10, main this PR
Q01 first_value ordered by (tz timestamp, int) 190 / 554 / 783 123 / 33 / 18
Q02 same, naive timestamp 189 / 72 / 42 124 / 33 / 18
Q03 DISTINCT ON, tz timestamp 219 / 597 / 831 132 / 37 / 21
Q04 DISTINCT ON, naive timestamp 218 / 91 / 55 133 / 38 / 20
Q05 first_value ordered by (int, int) 175 / 66 / 38 123 / 33 / 17
Q06 last_value ordered by (string, int) 210 / 86 / 52 155 / 56 / 31
  • Other shapes measured with ad hoc queries over the same data (not in the suite), 1 / 4 / 10 partitions: 100k groups x 20 rows ordered by (int, int) 111 / 47 / 33 -> 48 / 19 / 16; already ordered input where the winner never changes 99 / 39 -> 44 / 17 (1 / 4 partitions); a single int ordering, which takes the specialized accumulator, 34 / 18 / 11 -> 33 / 17 / 11 (unchanged); a list ordering, which stays on the ScalarValue path, 295 / 167 / 100 -> 298 / 170 / 104.

  • Sparse dictionary orderings (one parquet row group of 4.2M rows, a Dictionary(Int32, Utf8) ordering column with 16,384 values of about 125 bytes, so every batch carries the whole dictionary), median of 7 runs: 8 groups 96 ms on main and on this PR (180 ms without the compaction); 100k groups 234 -> 157 ms.

Not included: ordering by a struct is slow on main and on this branch (the ordering side does not compact struct slices). That is a one-line change in ScalarOrderings that I can do as a follow-up.

Are there any user-facing changes?

No.

This change was developed with the help of an AI assistant (Claude). I reviewed the code and ran the tests and benchmarks.

@github-actions github-actions Bot added sqllogictest SQL Logic Tests (.slt) functions Changes to functions implementation labels Nov 3, 2026
@akupchinskiy
akupchinskiy marked this pull request as ready for review November 3, 2026 09:18

@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.

@akupchinskiy, thanks for addressing the timezone reference-count contention. The approach preserves ordering semantics and intermediate-state types while removing shared Arc operations from group updates.

Please add the SQL reproducer in #27046 into a runnable benchmark under benchmarks/sql_benchmarks as part of this PR in a commit, then rebase it so that benchmark commit is the first commit in this PR. Then I can run benchmark like this.

In addition I have two non-blocking suggestions.

return Cow::Borrowed(columns);
}
let mut columns = columns.to_vec();
for (column, tz) in columns[1..].iter_mut().zip(&self.ordering_timezones) {

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 use columns.iter_mut().skip(1) instead of columns[1..].iter_mut()? Empty merge state currently panics instead of returning the existing Empty row in FIRST_VALUE error.

let first = partial.state(EmitTo::First(1))?;
let rest = partial.state(EmitTo::All)?;
assert_eq!(first[1].data_type(), &ts_type);
assert_eq!(rest[1].data_type(), &ts_type);

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 assert the emitted timestamp ticks in both state chunks? Expected values are [10] and [5] for FIRST_VALUE, and [30] and [15] for LAST_VALUE. This verifies timezone restoration preserves timestamp values.

@akupchinskiy
akupchinskiy force-pushed the first-last-tz-ordering-contention branch from 0ede219 to 97d4414 Compare November 20, 2026 12:13
@akupchinskiy

Copy link
Copy Markdown
Author

Thanks for the review! I rebased onto main and added the reproducer as a new SQL suite, first_last_tz, as the first commit (a07bd3e), so it gives a benchmark-only baseline.

Since #27303, the original single-key ORDER BY ts already takes the new primitive-key accumulator, so the suite orders by ts, o and uses DISTINCT ON, which still go through FirstLastGroupsAccumulator, with matching controls over a naive timestamp. Locally at 10 partitions Q01/Q03 go from 956/942 ms to 49/68 ms; the controls are 54/66 ms vs 50/67 ms. At 1 partition there is no material change.

Both suggestions are applied: an empty merge state now returns the Empty row in FIRST_VALUE error instead of panicking (confirmed it panicked before), and the test asserts the emitted timestamp ticks in both state chunks for FIRST_VALUE and LAST_VALUE.

The suite isn't in bench.sh on main yet, so it should run through the Criterion sql target:

run benchmark sql
```yaml
env:
  BENCH_NAME: "first_last_tz"
  BENCH_FILTER: "first_last_tz"
baseline:
  ref: "a07bd3e430588842f4c602f6b9a80b2a9509ee0c"
```

@kosiew

kosiew commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

run benchmark sql

env:
  BENCH_NAME: "first_last_tz"
  BENCH_FILTER: "first_last_tz"
baseline:
  ref: a07bd3e430

@adriangbot

Copy link
Copy Markdown

🤖 Benchmark running (GKE) | trigger
Instance: c4a-highmem-16 (12 vCPU / 65 GiB) | Linux bench-c7092856320-5620-7k668 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 first-last-tz-ordering-contention (97d4414) to a07bd3e diff

Run configuration
run benchmark sql
env:
  BENCH_FILTER: "first_last_tz"
  BENCH_NAME: "first_last_tz"
baseline:
  ref: "a07bd3e430"

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 first-last-tz-ordering-contention (97d4414) to a07bd3e diff

Run configuration
run benchmark sql
env:
  BENCH_FILTER: "first_last_tz"
  BENCH_NAME: "first_last_tz"
baseline:
  ref: "a07bd3e430"
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

group                HEAD                                   first-last-tz-ordering-contention
-----                ----                                   ---------------------------------
first_last_tz/Q01    8.27    285.2±4.07ms        ? ?/sec    1.00     34.5±0.36ms        ? ?/sec
first_last_tz/Q02    1.00     34.6±1.52ms        ? ?/sec    1.00     34.7±0.71ms        ? ?/sec
first_last_tz/Q03    8.42    382.7±3.12ms        ? ?/sec    1.00     45.5±1.64ms        ? ?/sec
first_last_tz/Q04    1.02     46.4±1.86ms        ? ?/sec    1.00     45.5±2.01ms        ? ?/sec

Resource Usage

sql — base (merge-base)

Metric Value
Wall time 720.3s
Peak memory 1.5 GiB
Avg memory 50.8 MiB
CPU user 512.7s
CPU sys 5.1s
Peak spill 0 B

sql — branch

Metric Value
Wall time 685.2s
Peak memory 1.3 GiB
Avg memory 48.2 MiB
CPU user 443.2s
CPU sys 4.2s
Peak spill 0 B

File an issue against this benchmark runner

kosiew
kosiew previously approved these changes Nov 24, 2026

@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.

@akupchinskiy,

Thanks for addressing all the review comments and adding the regression coverage.

The implementation preserves ordering semantics and intermediate state compatibility. The benchmarks confirm that it eliminates the approximately 8x performance penalty.

@alamb alamb 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.

Thanks for this PR @akupchinskiy and @kosiew but i think this is the wrong approach -- this is basically reporting high per-row overhead with ScalarValue but only fixing it for timestamps.

I think a better approch would be to figure out how to store values in the first/last value accumulator without using ScalarValuer

// The time zone of each ordering column that is a time zone aware
// timestamp, `None` for every other column.
//
// Such columns are stored in `orderings` without their time zone.

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.

This feels very much like fixing a symptom rather than the underlying problem

If the problem is high per-scalar value overhead I think we should be working on how to avoid using ScalarValue (e.g. use ArrayRef) rather than this hack of trying to remove a refcount.

@akupchinskiy

Copy link
Copy Markdown
Author

Thanks @alamb, that's a fair point. The time zone case is just where the cost shows up most (the shared Arc<str> refcount), but the underlying issue is the general FirstLastGroupsAccumulator keeping each group's ordering values as Vec<ScalarValue>.

I'll rework this PR so the accumulator stores the orderings without ScalarValue (for example in the arrow row format, compared as bytes). That should fix the time zone case and also help multi-column and string orderings. I'll update the PR with benchmark numbers once it's ready.

@kosiew
kosiew dismissed their stale review November 26, 2026 11:08

@alamb pointed out a better approach to fix root cause instead of symptom

…ue/last_value

Adds a data-free suite under benchmarks/sql_benchmarks for the general
FirstLastGroupsAccumulator (orderings with two keys, so the specialized single
primitive key path from apache#27303 is not taken):

- Q01/Q03: grouped first_value and DISTINCT ON ordered by a
  Timestamp(Microsecond, "UTC") column, the reproducer from apache#27046;
- Q02/Q04: the same queries over the same instants without a time zone;
- Q05: first_value ordered by (int, int);
- Q06: last_value ordered by (string, int).

Compare --partitions 1, 4 and 12. Size the input with FIRST_LAST_ROWS.
…rmat

FirstLastGroupsAccumulator kept each group's winning ordering values as
Vec<ScalarValue>, so every update built, cloned and compared ScalarValues per
group. For time zone aware timestamps this also bumped the shared Arc<str> of
the time zone from every thread.

Orderings are now stored as arrow rows (one fixed-width buffer when every
ordering type is fixed width, one reusable buffer per group otherwise) and
compared as bytes. Types whose row encoding does not order like compare_rows
(nested, union) or does not decode back to the planned type keep the
ScalarValue path. Intermediate state types and results are unchanged.
@akupchinskiy
akupchinskiy force-pushed the first-last-tz-ordering-contention branch from 97d4414 to 97f6f80 Compare November 26, 2026 15:59
@akupchinskiy akupchinskiy changed the title perf: avoid Arc<str> refcount contention in grouped first_value/last_value ordered by a time zone aware timestamp perf: keep first_value/last_value group orderings in the arrow row format Nov 26, 2026
…ictionaries

- shrink_to_fit also shrinks the ordering storage, and taking more than half
  of the fixed-width rows copies the kept rows into a right-sized buffer, so
  emitted groups release their memory (fixes the clustered partial aggregation
  test completed_groups_release_first_value_bitmap).
- ScalarOrderings::size counts each row's Vec header once.
- A dictionary ordering column is compacted after take when it has more than
  MAX_DICTIONARY_VALUES_PER_ROW values per selected row, so a batch with a few
  candidates does not encode the whole dictionary (8 groups over a 16k value
  dictionary: 0.18 s -> 0.096 s, same as main).
- Tests: byte order against compare_rows for every type on the row path and
  all sort options, the ScalarValue fallbacks (union DESC, dictionaries of
  boolean/duration/interval, lists with nulls), memory after partial emit,
  sparse dictionaries.
- Benchmark comment fixes.
@akupchinskiy

Copy link
Copy Markdown
Author

@alamb reworked as you suggested: group orderings are now stored in the arrow row format and compared as bytes. The old ScalarValue storage is only kept for nested and union ordering types. This fixes the time zone case (783 ms -> 18 ms at 10 partitions) and also speeds up other orderings, e.g. (int, int) 2.2x and (string, int) 1.7x. I added those two to the benchmark as Q05 and Q06.

The last commit fixes the CI failure (ordering memory wasn't released after emitting groups) and compacts sparse dictionaries before encoding, which was slower than main otherwise. Updated numbers are in the description.

@akupchinskiy

Copy link
Copy Markdown
Author

Thanks for running it! The benchmark was renamed in the rework (it now covers more than the time zone case), so the run failed with unknown benchmark 'first_last_tz'. The new name is first_last_orderings:

run benchmark sql
env:
  BENCH_NAME: "first_last_orderings"
  BENCH_FILTER: "first_last_orderings"
baseline:
  ref: d98afae21e

Sorry for the confusion, I should have mentioned the rename in my update.

@apache apache deleted a comment from adriangbot Nov 27, 2026
@apache apache deleted a comment from adriangbot Nov 27, 2026
@kosiew

kosiew commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

run benchmark sql

env:
  BENCH_NAME: "first_last_orderings"
  BENCH_FILTER: "first_last_orderings"
baseline:
  ref: d98afae21e

@adriangbot

Copy link
Copy Markdown

🤖 Benchmark running (GKE) | trigger
Instance: c4a-highmem-16 (12 vCPU / 65 GiB) | Linux bench-c7216530003-5793-mlndj 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 first-last-tz-ordering-contention (3fe7584) to d98afae diff

Run configuration
run benchmark sql
env:
  BENCH_FILTER: "first_last_orderings"
  BENCH_NAME: "first_last_orderings"
baseline:
  ref: "d98afae21e"
Trigger comment
run benchmark sql
```yaml
env:
  BENCH_NAME: "first_last_orderings"
  BENCH_FILTER: "first_last_orderings"
baseline:
  ref: d98afae21e
```

Results will be posted here when complete


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

functions Changes to functions implementation sqllogictest SQL Logic Tests (.slt)

Projects

None yet

4 participants