Repository navigation
perf: keep first_value/last_value group orderings in the arrow row format - #27047
akupchinskiy wants to merge 3 commits into
Conversation
There was a problem hiding this comment.
@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) { |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
0ede219 to
97d4414
Compare
|
Thanks for the review! I rebased onto main and added the reproducer as a new SQL suite, Since #27303, the original single-key Both suggestions are applied: an empty merge state now returns the The suite isn't in |
|
run benchmark sql env:
BENCH_NAME: "first_last_tz"
BENCH_FILTER: "first_last_tz"
baseline:
ref: a07bd3e430 |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing first-last-tz-ordering-contention (97d4414) to a07bd3e diff Run configurationrun 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 |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing first-last-tz-ordering-contention (97d4414) to a07bd3e diff Run configurationrun benchmark sql
env:
BENCH_FILTER: "first_last_tz"
BENCH_NAME: "first_last_tz"
baseline:
ref: "a07bd3e430"CPU Details (lscpu)Details
Resource Usagesql — base (merge-base)
sql — branch
File an issue against this benchmark runner |
kosiew
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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.
|
Thanks @alamb, that's a fair point. The time zone case is just where the cost shows up most (the shared I'll rework this PR so the accumulator stores the orderings without |
@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.
97d4414 to
97f6f80
Compare
…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.
|
@alamb reworked as you suggested: group orderings are now stored in the arrow row format and compared as bytes. The old 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. |
|
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 Sorry for the confusion, I should have mentioned the rename in my update. |
|
run benchmark sql env:
BENCH_NAME: "first_last_orderings"
BENCH_FILTER: "first_last_orderings"
baseline:
ref: d98afae21e |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing first-last-tz-ordering-contention (3fe7584) to d98afae diff Run configurationrun benchmark sql
env:
BENCH_FILTER: "first_last_orderings"
BENCH_NAME: "first_last_orderings"
baseline:
ref: "d98afae21e"Trigger commentResults will be posted here when complete File an issue against this benchmark runner |
Which issue does this PR close?
Rationale for this change
FirstLastGroupsAccumulatorkeeps each group's winning ordering values asVec<ScalarValue>. Every updated group builds, clones and comparesScalarValues, and for a time zone aware timestamp every clone also touches the time zone's sharedArc<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:GroupOrderingswith 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 previousScalarValuestorage, kept for ordering types whose row encoding does not order likecompare_rows(nested and union types) or does not decode back to the planned type (checked once with a round trip intry_new).row_comparabledecides the path per ordering type: flat types and dictionaries of them use rows.evaluatedoes not decode orderings;statedecodes them and casts dictionaries back, so the intermediate state schema is unchanged.EmitTo::Firstdrains in place; when more than half of the fixed-width rows are taken, the kept rows move to a right-sized buffer, andshrink_to_fitshrinks the ordering storage, so emitted groups release their memory.takewhen it has more thanMAX_DICTIONARY_VALUES_PER_ROWvalues per selected row (asmap_dictionary_valuesdoes), so a batch with a few candidates does not encode the whole dictionary.size()accounts for the row buffers (cached for theScalarValuepath).The non-grouped accumulators are unchanged.
Are these changes tested?
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 matchcompare_rowsoverScalarValues),test_scalar_orderings_fallbacks(unionDESC, 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_valueordered by aTimestamp(µs, "+05:00")column over aUNION ALLof 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.datafusion-functions-aggregatetests,datafusion-physical-planaggregate tests, clippy, and the sqllogictest files that usefirst_value/last_value/DISTINCT ON(aggregate, group_by, distinct_on, first_last_, window, joins and others) pass.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: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
ScalarValuepath, 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
ScalarOrderingsthat 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.