From 81094b46618df479dee0477e0bbdfd5429274634 Mon Sep 17 00:00:00 2001 From: xavlee <52435309+xavlee@users.noreply.github.com> Date: Fri, 16 Oct 2026 09:30:27 +0000 Subject: [PATCH] refactor: use group clustering terminology in aggregate execution (#24697) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Which issue does this PR relate to? - Part of #24438. - Builds on the baseline test in #24737 (merged). ## Rationale for this change Aggregate execution currently uses `InputOrderMode` to select execution paths and recognize completed groups. A group can be completed incrementally when its rows form one contiguous run: once the run ends, that group cannot appear again in the same input partition. Sorted input supplies this guarantee, and unsorted input can supply it too: ```text AAABBBCCCC -> sorted; groups can be completed incrementally CCCAAABBB -> unsorted; groups can still be completed incrementally ``` This PR describes the input's _**clustering**_ guarantee with `GroupClusteringMode` and uses clustering terminology throughout the aggregate execution machinery. Aggregate construction derives the mode directly from the existing ordering analysis. The follow-up in #24497 will also derive it from grouped equivalence properties. ## What changes are included in this PR? - Replace the aggregate's `InputOrderMode` field with `GroupClusteringMode::{None, Partial, Full}`: - `None`: Groups have no apparent clustering guarantee. - `Partial(indices)`: rows are contiguous on a subset of grouping expressions; a change in that tuple completes all groups in the preceding run. - `Full`: rows are contiguous on the complete grouping tuple; a change in that tuple completes the preceding group. - Rename the stateful `GroupOrdering` tracker and its `Partial` and `Full` implementations to `GroupClustering`, `GroupClusteringPartial`, and `GroupClusteringFull`. - Rename the ordered aggregate streams, shared table, and adjacent-key group-values implementation to use clustered terminology, - Preserve actual sort expressions and options through equivalence properties and input-ordering requirements. - Display `group_clustering_mode` in aggregate plans and document the public API migration in the DataFusion 56 upgrade guide. ## Stack 1. [#24737 — test: cover unsorted contiguous groups in one partition](https://github.com/apache/datafusion/pull/24737) (merged) 2. [#24697 — refactor: use group clustering terminology in aggregate execution](https://github.com/apache/datafusion/pull/24697) ← **this PR** 3. [#24698 — feat: add Grouped equivalence properties](https://github.com/apache/datafusion/pull/24698) 4. [#24497 — feat: stream aggregates over grouped input](https://github.com/apache/datafusion/pull/24497) ## Are there any user-facing changes? Yes. This PR changes public Rust APIs: - `AggregateExec::input_order_mode()` is replaced by `AggregateExec::group_clustering_mode()`, returning the public `GroupClusteringMode` enum. - `AggregateExec::compute_properties` accepts `&GroupClusteringMode` in place of `&InputOrderMode`. - The public `GroupOrdering`, `GroupOrderingPartial`, and `GroupOrderingFull` types in `aggregates::order` are renamed to `GroupClustering`, `GroupClusteringPartial`, and `GroupClusteringFull`. - `GroupClustering::try_new` takes `&GroupClusteringMode`; `new_group_values` takes `&GroupClustering`. Aggregate plan output uses `group_clustering_mode=Full` and `group_clustering_mode=Partial(indices)` in place of `ordering_mode=Sorted` and `ordering_mode=PartiallySorted(indices)`. SQL results and aggregate execution-path selection retain their existing behavior. ## Review this layer [View this PR's diff](https://github.com/apache/datafusion/pull/24697/files) (cherry picked from commit d93699ce388af4153dd6e9f1a6a2c74855b42a5e) --- datafusion/core/tests/dataframe/mod.rs | 14 +- .../core/tests/fuzz_cases/aggregate_fuzz.rs | 12 +- .../aggregation_fuzzer/query_builder.rs | 4 +- .../enforce_distribution.rs | 8 +- .../physical_optimizer/filter_pushdown.rs | 14 +- .../limited_distinct_aggregation.rs | 2 +- .../tests/physical_optimizer/pushdown_sort.rs | 4 +- .../benches/dictionary_group_values.rs | 6 +- .../physical-plan/benches/partial_ordering.rs | 16 +- ...inal_table.rs => clustered_final_table.rs} | 16 +- ...al_table.rs => clustered_partial_table.rs} | 14 +- .../aggregates/aggregate_hash_table/common.rs | 4 +- ...{common_ordered.rs => common_clustered.rs} | 58 ++-- .../aggregates/aggregate_hash_table/mod.rs | 8 +- .../aggregate_hash_table/partial_table.rs | 4 +- ...al_stream.rs => clustered_final_stream.rs} | 202 +++++++------- ..._stream.rs => clustered_partial_stream.rs} | 43 +-- .../src/aggregates/group_values/mod.rs | 6 +- .../src/aggregates/grouped_hash_stream.rs | 51 ++-- .../src/aggregates/hash_stream.rs | 19 +- .../physical-plan/src/aggregates/mod.rs | 248 +++++++++++++----- .../src/aggregates/order/full.rs | 16 +- .../physical-plan/src/aggregates/order/mod.rs | 143 ++++++---- .../src/aggregates/order/partial.rs | 22 +- .../src/aggregates/partial_reduce_stream.rs | 5 +- .../src/aggregates/single_stream.rs | 19 +- .../physical-plan/src/recursive_query.rs | 4 +- .../test_files/agg_func_substitute.slt | 12 +- .../sqllogictest/test_files/aggregate.slt | 16 +- .../sqllogictest/test_files/array_agg.slt | 4 +- .../sqllogictest/test_files/group_by.slt | 58 ++-- datafusion/sqllogictest/test_files/joins.slt | 8 +- datafusion/sqllogictest/test_files/order.slt | 2 +- .../test_files/ordered_aggregate_spill.slt | 24 +- .../test_files/preserve_file_partitioning.slt | 12 +- .../push_down_filter_regression.slt | 4 +- .../repartition_subset_satisfaction.slt | 12 +- .../sqllogictest/test_files/sort_pushdown.slt | 10 +- datafusion/sqllogictest/test_files/union.slt | 4 +- datafusion/sqllogictest/test_files/unnest.slt | 4 +- datafusion/sqllogictest/test_files/window.slt | 4 +- .../library-user-guide/upgrading/55.0.0.md | 21 ++ 42 files changed, 672 insertions(+), 485 deletions(-) rename datafusion/physical-plan/src/aggregates/aggregate_hash_table/{ordered_final_table.rs => clustered_final_table.rs} (86%) rename datafusion/physical-plan/src/aggregates/aggregate_hash_table/{ordered_partial_table.rs => clustered_partial_table.rs} (88%) rename datafusion/physical-plan/src/aggregates/aggregate_hash_table/{common_ordered.rs => common_clustered.rs} (88%) rename datafusion/physical-plan/src/aggregates/{ordered_final_stream.rs => clustered_final_stream.rs} (81%) rename datafusion/physical-plan/src/aggregates/{ordered_partial_stream.rs => clustered_partial_stream.rs} (89%) diff --git a/datafusion/core/tests/dataframe/mod.rs b/datafusion/core/tests/dataframe/mod.rs index 4966c7aa9ae73..656562909dd17 100644 --- a/datafusion/core/tests/dataframe/mod.rs +++ b/datafusion/core/tests/dataframe/mod.rs @@ -893,7 +893,7 @@ async fn test_aggregate_with_pk2() -> Result<()> { assert_snapshot!( physical_plan_to_string(&df).await, @r" - AggregateExec: mode=Single, gby=[id@0 as id, name@1 as name], aggr=[], ordering_mode=Sorted + AggregateExec: mode=Single, gby=[id@0 as id, name@1 as name], aggr=[], group_clustering_mode=Full FilterExec: id@0 = 1 AND name@1 = a DataSourceExec: partitions=1, partition_sizes=[1] " @@ -941,7 +941,7 @@ async fn test_aggregate_with_pk3() -> Result<()> { assert_snapshot!( physical_plan_to_string(&df).await, @r" - AggregateExec: mode=Single, gby=[id@0 as id, name@1 as name], aggr=[], ordering_mode=PartiallySorted([0]) + AggregateExec: mode=Single, gby=[id@0 as id, name@1 as name], aggr=[], group_clustering_mode=Partial([0]) FilterExec: id@0 = 1 DataSourceExec: partitions=1, partition_sizes=[1] " @@ -991,7 +991,7 @@ async fn test_aggregate_with_pk4() -> Result<()> { assert_snapshot!( physical_plan_to_string(&df).await, @r" - AggregateExec: mode=Single, gby=[id@0 as id], aggr=[], ordering_mode=Sorted + AggregateExec: mode=Single, gby=[id@0 as id], aggr=[], group_clustering_mode=Full FilterExec: id@0 = 1 DataSourceExec: partitions=1, partition_sizes=[1] " @@ -3273,9 +3273,9 @@ async fn union_with_mix_of_presorted_and_explicitly_resorted_inputs_with_reparti assert_snapshot!( union_with_mix_of_presorted_and_explicitly_resorted_inputs_impl(false).await?, @r" - AggregateExec: mode=Final, gby=[id@0 as id], aggr=[], ordering_mode=Sorted + AggregateExec: mode=Final, gby=[id@0 as id], aggr=[], group_clustering_mode=Full SortPreservingMergeExec: [id@0 ASC NULLS LAST] - AggregateExec: mode=Partial, gby=[id@0 as id], aggr=[], ordering_mode=Sorted + AggregateExec: mode=Partial, gby=[id@0 as id], aggr=[], group_clustering_mode=Full UnionExec DataSourceExec: file_groups={1 group: [[{testdata}/alltypes_tiny_pages.parquet]]}, projection=[id], output_ordering=[id@0 ASC NULLS LAST], file_type=parquet SortExec: expr=[id@0 ASC NULLS LAST], preserve_partitioning=[false] @@ -3291,9 +3291,9 @@ async fn union_with_mix_of_presorted_and_explicitly_resorted_inputs_with_reparti assert_snapshot!( union_with_mix_of_presorted_and_explicitly_resorted_inputs_impl(true).await?, @r" - AggregateExec: mode=Final, gby=[id@0 as id], aggr=[], ordering_mode=Sorted + AggregateExec: mode=Final, gby=[id@0 as id], aggr=[], group_clustering_mode=Full SortPreservingMergeExec: [id@0 ASC NULLS LAST] - AggregateExec: mode=Partial, gby=[id@0 as id], aggr=[], ordering_mode=Sorted + AggregateExec: mode=Partial, gby=[id@0 as id], aggr=[], group_clustering_mode=Full UnionExec DataSourceExec: file_groups={1 group: [[{testdata}/alltypes_tiny_pages.parquet]]}, projection=[id], output_ordering=[id@0 ASC NULLS LAST], file_type=parquet SortExec: expr=[id@0 ASC NULLS LAST], preserve_partitioning=[false] diff --git a/datafusion/core/tests/fuzz_cases/aggregate_fuzz.rs b/datafusion/core/tests/fuzz_cases/aggregate_fuzz.rs index f9e7f2e10e789..a54e5cbf560cf 100644 --- a/datafusion/core/tests/fuzz_cases/aggregate_fuzz.rs +++ b/datafusion/core/tests/fuzz_cases/aggregate_fuzz.rs @@ -41,7 +41,7 @@ use datafusion_common_runtime::JoinSet; use datafusion_functions_aggregate::sum::sum_udaf; use datafusion_physical_expr::PhysicalSortExpr; use datafusion_physical_expr::expressions::{Column, col, lit}; -use datafusion_physical_plan::InputOrderMode; +use datafusion_physical_plan::aggregates::GroupClusteringMode; use test_utils::{StringBatchGenerator, add_empty_batches}; use datafusion_execution::TaskContext; @@ -352,8 +352,8 @@ async fn run_aggregate_test(input1: Vec, group_by_columns: Vec<&str .unwrap(), ); assert_ne!( - aggregate_exec_running.input_order_mode(), - &InputOrderMode::Linear, + aggregate_exec_running.group_clustering_mode(), + &GroupClusteringMode::None, "running aggregate should observe ordered input for group_by: {group_by:?}" ); @@ -555,11 +555,11 @@ async fn verify_ordered_aggregate(frame: &DataFrame, expected_sort: bool) { if let Some(exec) = node.downcast_ref::() { if self.expected_sort { assert!(matches!( - exec.input_order_mode(), - InputOrderMode::PartiallySorted(_) | InputOrderMode::Sorted + exec.group_clustering_mode(), + GroupClusteringMode::Partial(_) | GroupClusteringMode::Full )); } else { - assert_eq!(*exec.input_order_mode(), InputOrderMode::Linear); + assert_eq!(*exec.group_clustering_mode(), GroupClusteringMode::None); } } Ok(TreeNodeRecursion::Continue) diff --git a/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/query_builder.rs b/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/query_builder.rs index c517050b674ae..059e0db1b5481 100644 --- a/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/query_builder.rs +++ b/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/query_builder.rs @@ -92,9 +92,9 @@ pub struct QueryBuilder { /// ... /// ``` /// - /// More details can see [`GroupOrdering`]. + /// More details can see [`GroupClustering`]. /// - /// [`GroupOrdering`]: datafusion_physical_plan::aggregates::order::GroupOrdering + /// [`GroupClustering`]: datafusion_physical_plan::aggregates::order::GroupClustering dataset_sort_keys: Vec>, /// If we will also test the no grouping case like: diff --git a/datafusion/core/tests/physical_optimizer/enforce_distribution.rs b/datafusion/core/tests/physical_optimizer/enforce_distribution.rs index 2dbacf1d898ac..876d0dfb9d3ec 100644 --- a/datafusion/core/tests/physical_optimizer/enforce_distribution.rs +++ b/datafusion/core/tests/physical_optimizer/enforce_distribution.rs @@ -3954,9 +3954,9 @@ fn preserve_ordering_for_streaming_sorted_aggregate() -> Result<()> { let plan_distrib = test_config.to_plan(physical_plan.clone(), &DISTRIB_DISTRIB_SORT); assert_plan!(plan_distrib, @r" - AggregateExec: mode=FinalPartitioned, gby=[a@0 as a], aggr=[COUNT(b)], ordering_mode=Sorted + AggregateExec: mode=FinalPartitioned, gby=[a@0 as a], aggr=[COUNT(b)], group_clustering_mode=Full RepartitionExec: partitioning=Hash([a@0], 2), input_partitions=2, preserve_order=true, sort_exprs=a@0 ASC - AggregateExec: mode=Partial, gby=[a@0 as a], aggr=[COUNT(b)], ordering_mode=Sorted + AggregateExec: mode=Partial, gby=[a@0 as a], aggr=[COUNT(b)], group_clustering_mode=Full DataSourceExec: file_groups={2 groups: [[x], [y]]}, projection=[a, b, c, d, e], output_ordering=[a@0 ASC], file_type=parquet "); @@ -3988,9 +3988,9 @@ fn preserve_ordering_for_streaming_partially_sorted_aggregate() -> Result<()> { let plan_distrib = test_config.to_plan(physical_plan.clone(), &DISTRIB_DISTRIB_SORT); assert_plan!(plan_distrib, @r" - AggregateExec: mode=FinalPartitioned, gby=[a@0 as a, b@1 as b], aggr=[COUNT(c)], ordering_mode=PartiallySorted([0]) + AggregateExec: mode=FinalPartitioned, gby=[a@0 as a, b@1 as b], aggr=[COUNT(c)], group_clustering_mode=Partial([0]) RepartitionExec: partitioning=Hash([a@0, b@1], 2), input_partitions=2, preserve_order=true, sort_exprs=a@0 ASC - AggregateExec: mode=Partial, gby=[a@0 as a, b@1 as b], aggr=[COUNT(c)], ordering_mode=PartiallySorted([0]) + AggregateExec: mode=Partial, gby=[a@0 as a, b@1 as b], aggr=[COUNT(c)], group_clustering_mode=Partial([0]) DataSourceExec: file_groups={2 groups: [[x], [y]]}, projection=[a, b, c, d, e], output_ordering=[a@0 ASC], file_type=parquet "); diff --git a/datafusion/core/tests/physical_optimizer/filter_pushdown.rs b/datafusion/core/tests/physical_optimizer/filter_pushdown.rs index 8d6678ff7f621..303603f295ed0 100644 --- a/datafusion/core/tests/physical_optimizer/filter_pushdown.rs +++ b/datafusion/core/tests/physical_optimizer/filter_pushdown.rs @@ -737,12 +737,12 @@ fn test_pushdown_through_aggregates_on_grouping_columns() { OptimizationTest: input: - FilterExec: b@1 = bar - - AggregateExec: mode=Final, gby=[a@0 as a, b@1 as b], aggr=[cnt], ordering_mode=PartiallySorted([0]) + - AggregateExec: mode=Final, gby=[a@0 as a, b@1 as b], aggr=[cnt], group_clustering_mode=Partial([0]) - FilterExec: a@0 = foo - DataSourceExec: file_groups={1 group: [[test.parquet]]}, projection=[a, b, c], file_type=test, pushdown_supported=true output: Ok: - - AggregateExec: mode=Final, gby=[a@0 as a, b@1 as b], aggr=[cnt], ordering_mode=Sorted + - AggregateExec: mode=Final, gby=[a@0 as a, b@1 as b], aggr=[cnt], group_clustering_mode=Full - DataSourceExec: file_groups={1 group: [[test.parquet]]}, projection=[a, b, c], file_type=test, pushdown_supported=true, predicate=a@0 = foo AND b@1 = bar " ); @@ -801,7 +801,7 @@ fn test_pushdown_through_aggregates_preserves_parent_filter_order() { output: Ok: - FilterExec: cnt@2 = 1 - - AggregateExec: mode=Final, gby=[a@0 as a, b@1 as b], aggr=[cnt], ordering_mode=PartiallySorted([1]) + - AggregateExec: mode=Final, gby=[a@0 as a, b@1 as b], aggr=[cnt], group_clustering_mode=Partial([1]) - DataSourceExec: file_groups={1 group: [[test.parquet]]}, projection=[a, b, c], file_type=test, pushdown_supported=true, predicate=b@1 = bar " ); @@ -2493,7 +2493,7 @@ fn test_pushdown_filter_on_non_first_grouping_column() { - DataSourceExec: file_groups={1 group: [[test.parquet]]}, projection=[a, b, c], file_type=test, pushdown_supported=true output: Ok: - - AggregateExec: mode=Final, gby=[a@0 as a, b@1 as b], aggr=[cnt], ordering_mode=PartiallySorted([1]) + - AggregateExec: mode=Final, gby=[a@0 as a, b@1 as b], aggr=[cnt], group_clustering_mode=Partial([1]) - DataSourceExec: file_groups={1 group: [[test.parquet]]}, projection=[a, b, c], file_type=test, pushdown_supported=true, predicate=b@1 = bar " ); @@ -2632,7 +2632,7 @@ fn test_pushdown_grouping_sets_filter_on_common_column() { - DataSourceExec: file_groups={1 group: [[test.parquet]]}, projection=[a, b, c], file_type=test, pushdown_supported=true output: Ok: - - AggregateExec: mode=Final, gby=[(a@0 as a, b@1 as b), (NULL as a, b@1 as b)], aggr=[cnt], ordering_mode=PartiallySorted([1]) + - AggregateExec: mode=Final, gby=[(a@0 as a, b@1 as b), (NULL as a, b@1 as b)], aggr=[cnt], group_clustering_mode=Partial([1]) - DataSourceExec: file_groups={1 group: [[test.parquet]]}, projection=[a, b, c], file_type=test, pushdown_supported=true, predicate=b@1 = bar " ); @@ -2829,7 +2829,7 @@ fn test_pushdown_through_aggregate_with_reordered_input_columns() { - DataSourceExec: file_groups={1 group: [[test.parquet]]}, projection=[a, b, c], file_type=test, pushdown_supported=true output: Ok: - - AggregateExec: mode=Final, gby=[a@1 as a, b@2 as b], aggr=[cnt], ordering_mode=PartiallySorted([1]) + - AggregateExec: mode=Final, gby=[a@1 as a, b@2 as b], aggr=[cnt], group_clustering_mode=Partial([1]) - ProjectionExec: expr=[c@2 as c, a@0 as a, b@1 as b] - DataSourceExec: file_groups={1 group: [[test.parquet]]}, projection=[a, b, c], file_type=test, pushdown_supported=true, predicate=b@1 = bar " @@ -2918,7 +2918,7 @@ fn test_pushdown_through_aggregate_grouping_sets_with_reordered_input() { - DataSourceExec: file_groups={1 group: [[test.parquet]]}, projection=[a, b, c], file_type=test, pushdown_supported=true output: Ok: - - AggregateExec: mode=Final, gby=[(a@1 as a, b@2 as b), (NULL as a, b@2 as b)], aggr=[cnt], ordering_mode=PartiallySorted([1]) + - AggregateExec: mode=Final, gby=[(a@1 as a, b@2 as b), (NULL as a, b@2 as b)], aggr=[cnt], group_clustering_mode=Partial([1]) - ProjectionExec: expr=[c@2 as c, a@0 as a, b@1 as b] - DataSourceExec: file_groups={1 group: [[test.parquet]]}, projection=[a, b, c], file_type=test, pushdown_supported=true, predicate=b@1 = bar " diff --git a/datafusion/core/tests/physical_optimizer/limited_distinct_aggregation.rs b/datafusion/core/tests/physical_optimizer/limited_distinct_aggregation.rs index 323dfd6183306..3a07857fbfe91 100644 --- a/datafusion/core/tests/physical_optimizer/limited_distinct_aggregation.rs +++ b/datafusion/core/tests/physical_optimizer/limited_distinct_aggregation.rs @@ -401,7 +401,7 @@ fn test_has_order_by() -> Result<()> { actual, @r" LocalLimitExec: fetch=10 - AggregateExec: mode=Single, gby=[a@0 as a], aggr=[], ordering_mode=Sorted + AggregateExec: mode=Single, gby=[a@0 as a], aggr=[], group_clustering_mode=Full DataSourceExec: file_groups={1 group: [[x]]}, projection=[a, b, c, d, e], output_ordering=[a@0 ASC], file_type=parquet " ); diff --git a/datafusion/core/tests/physical_optimizer/pushdown_sort.rs b/datafusion/core/tests/physical_optimizer/pushdown_sort.rs index b72563a942ae3..6cf05ecfd8fc4 100644 --- a/datafusion/core/tests/physical_optimizer/pushdown_sort.rs +++ b/datafusion/core/tests/physical_optimizer/pushdown_sort.rs @@ -731,13 +731,13 @@ fn test_pushdown_through_blocking_node() { OptimizationTest: input: - SortExec: expr=[a@0 ASC], preserve_partitioning=[false] - - AggregateExec: mode=Final, gby=[a@0 as a], aggr=[COUNT(b)], ordering_mode=Sorted + - AggregateExec: mode=Final, gby=[a@0 as a], aggr=[COUNT(b)], group_clustering_mode=Full - SortExec: expr=[a@0 DESC NULLS LAST], preserve_partitioning=[false] - DataSourceExec: file_groups={1 group: [[x]]}, projection=[a, b, c, d, e], output_ordering=[a@0 ASC], file_type=parquet output: Ok: - SortExec: expr=[a@0 ASC], preserve_partitioning=[false] - - AggregateExec: mode=Final, gby=[a@0 as a], aggr=[COUNT(b)], ordering_mode=Sorted + - AggregateExec: mode=Final, gby=[a@0 as a], aggr=[COUNT(b)], group_clustering_mode=Full - SortExec: expr=[a@0 DESC NULLS LAST], preserve_partitioning=[false] - DataSourceExec: file_groups={1 group: [[x]]}, projection=[a, b, c, d, e], file_type=parquet, sort_order_for_reorder=[a@0 DESC NULLS LAST], reverse_row_groups=true " diff --git a/datafusion/physical-plan/benches/dictionary_group_values.rs b/datafusion/physical-plan/benches/dictionary_group_values.rs index ded52aebd1100..2338f619773c4 100644 --- a/datafusion/physical-plan/benches/dictionary_group_values.rs +++ b/datafusion/physical-plan/benches/dictionary_group_values.rs @@ -29,7 +29,7 @@ use criterion::{ }; use datafusion_expr::EmitTo; use datafusion_physical_plan::aggregates::group_values::new_group_values; -use datafusion_physical_plan::aggregates::order::GroupOrdering; +use datafusion_physical_plan::aggregates::order::GroupClustering; use rand::rngs::StdRng; use rand::seq::SliceRandom; use rand::{Rng, SeedableRng}; @@ -106,7 +106,7 @@ fn bench_intern_emit(c: &mut Criterion) { b.iter_batched_ref( || { ( - new_group_values(schema.clone(), &GroupOrdering::None) + new_group_values(schema.clone(), &GroupClustering::None) .unwrap(), Vec::::with_capacity(size), ) @@ -151,7 +151,7 @@ fn bench_repeated_intern_emit(c: &mut Criterion) { b.iter_batched_ref( || { ( - new_group_values(schema.clone(), &GroupOrdering::None) + new_group_values(schema.clone(), &GroupClustering::None) .unwrap(), Vec::::with_capacity(size), ) diff --git a/datafusion/physical-plan/benches/partial_ordering.rs b/datafusion/physical-plan/benches/partial_ordering.rs index bdadd6274b75e..967e84d78a88b 100644 --- a/datafusion/physical-plan/benches/partial_ordering.rs +++ b/datafusion/physical-plan/benches/partial_ordering.rs @@ -18,7 +18,7 @@ use std::sync::Arc; use arrow::array::{ArrayRef, Int32Array}; -use datafusion_physical_plan::aggregates::order::GroupOrderingPartial; +use datafusion_physical_plan::aggregates::order::GroupClusteringPartial; use criterion::{Criterion, criterion_group, criterion_main}; @@ -34,20 +34,20 @@ fn create_test_arrays(num_columns: usize) -> Vec { .collect() } fn bench_new_groups(c: &mut Criterion) { - let mut group = c.benchmark_group("group_ordering_partial"); + let mut group = c.benchmark_group("group_clustering_partial"); - // Test with 1, 2, 4, and 8 order indices + // Test with 1, 2, 4, and 8 grouping indices for num_columns in [1, 2, 4, 8] { - let order_indices: Vec = (0..num_columns).collect(); + let grouping_indices: Vec = (0..num_columns).collect(); - group.bench_function(format!("order_indices_{num_columns}"), |b| { + group.bench_function(format!("grouping_indices_{num_columns}"), |b| { let batch_group_values = create_test_arrays(num_columns); let group_indices: Vec = (0..BATCH_SIZE).collect(); b.iter(|| { - let mut ordering = - GroupOrderingPartial::try_new(order_indices.clone()).unwrap(); - ordering + let mut clustering = + GroupClusteringPartial::try_new(grouping_indices.clone()).unwrap(); + clustering .new_groups(&batch_group_values, &group_indices, BATCH_SIZE) .unwrap(); }); diff --git a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/ordered_final_table.rs b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/clustered_final_table.rs similarity index 86% rename from datafusion/physical-plan/src/aggregates/aggregate_hash_table/ordered_final_table.rs rename to datafusion/physical-plan/src/aggregates/aggregate_hash_table/clustered_final_table.rs index fd064ebffec12..11afac986bd2f 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/ordered_final_table.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/clustered_final_table.rs @@ -17,7 +17,7 @@ //! Aggregate table for final aggregation when partial-state input is ordered. //! -//! See comments in [`super::ordered_partial_table`] for details. +//! See comments in [`super::clustered_partial_table`] for details. use std::sync::Arc; @@ -25,12 +25,12 @@ use arrow::datatypes::SchemaRef; use arrow::record_batch::RecordBatch; use datafusion_common::Result; -use crate::InputOrderMode; +use crate::aggregates::GroupClusteringMode; use crate::aggregates::aggregate_hash_table::FinalMarker; use crate::aggregates::group_values::GroupByMetrics; use crate::aggregates::{AggregateExec, AggregateMode}; -use super::common_ordered::OrderedAggregateTable; +use super::common_clustered::ClusteredAggregateTable; /// Implementation specific to final aggregation, where the table stores partial /// aggregate states and the input rows are also partial states. @@ -40,14 +40,14 @@ use super::common_ordered::OrderedAggregateTable; /// - Aggregate table stores: `k, sum(x), count(x)` /// - Input rows: `k, sum(x), count(x)` /// -/// See comments at [`OrderedAggregateTable`] for details. -impl OrderedAggregateTable { +/// See comments at [`ClusteredAggregateTable`] for details. +impl ClusteredAggregateTable { pub(in crate::aggregates) fn new_with_input_order( agg: &AggregateExec, input_schema: &SchemaRef, output_schema: SchemaRef, batch_size: usize, - input_order_mode: &InputOrderMode, + group_clustering_mode: &GroupClusteringMode, group_by_metrics: GroupByMetrics, ) -> Result { Self::new_for_mode( @@ -56,7 +56,7 @@ impl OrderedAggregateTable { output_schema, Arc::clone(input_schema), batch_size, - input_order_mode, + group_clustering_mode, &AggregateMode::Final, vec![None; agg.aggr_expr.len()], group_by_metrics, @@ -76,7 +76,7 @@ impl OrderedAggregateTable { self.aggregate_evaluated_batch(&evaluated_batch, true) } - /// See comments in `ordered_partial_stream::next_output_batch` + /// See comments in `clustered_partial_stream::next_output_batch` pub(in crate::aggregates) fn next_output_batch( &mut self, ) -> Result> { diff --git a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/ordered_partial_table.rs b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/clustered_partial_table.rs similarity index 88% rename from datafusion/physical-plan/src/aggregates/aggregate_hash_table/ordered_partial_table.rs rename to datafusion/physical-plan/src/aggregates/aggregate_hash_table/clustered_partial_table.rs index a04e4dda8fb39..50fe74572b96f 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/ordered_partial_table.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/clustered_partial_table.rs @@ -17,7 +17,7 @@ //! Aggregate table for partial aggregation when input is ordered by group keys. //! -//! See the [`super::common_ordered`] comments for the high-level ideas. +//! See the [`super::common_clustered`] comments for the high-level ideas. //! //! This operator handles input that is ordered by group keys: //! - Fully ordered: `GROUP BY a, b`, input is `ORDER BY a, b` @@ -40,7 +40,7 @@ use crate::aggregates::{ group_values::GroupByMetrics, }; -use super::common_ordered::OrderedAggregateTable; +use super::common_clustered::ClusteredAggregateTable; /// Implementation specific to partial aggregation, where the table stores /// partial aggregate states and the input rows are raw rows. @@ -50,8 +50,8 @@ use super::common_ordered::OrderedAggregateTable; /// - Aggregate table stores: `k, sum(x), count(x)` /// - Input rows: `k, x` /// -/// See comments at [`OrderedAggregateTable`] for details. -impl OrderedAggregateTable { +/// See comments at [`ClusteredAggregateTable`] for details. +impl ClusteredAggregateTable { pub(in crate::aggregates) fn new( agg: &AggregateExec, partition: usize, @@ -67,7 +67,7 @@ impl OrderedAggregateTable { output_schema, state_schema, batch_size, - &agg.input_order_mode, + &agg.group_clustering_mode, &AggregateMode::Partial, agg.filter_expr.iter().cloned().collect(), group_by_metrics, @@ -92,8 +92,8 @@ impl OrderedAggregateTable { /// are complete and safe to emit. /// /// Key steps: - /// 1. Ask `group_ordering` to decide how many groups can be emitted eagerly. - /// 2. Remove the emitted groups from `group_ordering`, `GroupValues`, and + /// 1. Ask `group_clustering` to decide how many groups can be emitted eagerly. + /// 2. Remove the emitted groups from `group_clustering`, `GroupValues`, and /// all `GroupsAccumulator`s. /// /// This may output small batches. Avoiding tiny batches is left to future diff --git a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs index 91e9d6555c3e7..c9f8dc45e36de 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs @@ -29,7 +29,7 @@ use datafusion_physical_expr::aggregate::AggregateFunctionExpr; use crate::PhysicalExpr; use crate::aggregates::group_values::{GroupByMetrics, GroupValues, new_group_values}; use crate::aggregates::grouped_hash_stream::create_group_accumulator; -use crate::aggregates::order::GroupOrdering; +use crate::aggregates::order::GroupClustering; use crate::aggregates::{ AggregateExec, PhysicalGroupBy, aggregate_expressions, evaluate_group_by, }; @@ -132,7 +132,7 @@ impl AggregateHashTable { .collect::>()?; let group_schema = agg.group_by.group_schema(&input_schema)?; - let group_values = new_group_values(group_schema, &GroupOrdering::None)?; + let group_values = new_group_values(group_schema, &GroupClustering::None)?; Ok(Self { group_by_metrics: GroupByMetrics::new(&agg.metrics, partition), diff --git a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common_ordered.rs b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common_clustered.rs similarity index 88% rename from datafusion/physical-plan/src/aggregates/aggregate_hash_table/common_ordered.rs rename to datafusion/physical-plan/src/aggregates/aggregate_hash_table/common_clustered.rs index 2293e7b1b8e89..9c5c926de2370 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common_ordered.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common_clustered.rs @@ -28,11 +28,11 @@ use datafusion_common::assert_or_internal_err; use datafusion_execution::memory_pool::proxy::VecAllocExt; use datafusion_expr::EmitTo; -use crate::InputOrderMode; use crate::PhysicalExpr; +use crate::aggregates::GroupClusteringMode; use crate::aggregates::group_values::{GroupByMetrics, GroupValues, new_group_values}; use crate::aggregates::grouped_hash_stream::create_group_accumulator; -use crate::aggregates::order::GroupOrdering; +use crate::aggregates::order::GroupClustering; use crate::aggregates::{ AggregateExec, AggregateMode, PhysicalGroupBy, aggregate_expressions, evaluate_group_by, @@ -44,7 +44,7 @@ use super::common::{AggregateAccumulator, EvaluatedAggregateBatch}; /// /// # Ordering optimization /// -/// The table consumes input batches while `GroupOrdering` tracks which groups +/// The table consumes input batches while `GroupClustering` tracks which groups /// are proven complete. Completed groups can be emitted before the input stream /// ends, which keeps memory bounded by the active ordered key range. /// @@ -52,7 +52,7 @@ use super::common::{AggregateAccumulator, EvaluatedAggregateBatch}; /// /// The partial and final aggregate tables implement the two stages of grouped /// aggregation. See -/// [`OrderedPartialAggregateStream`](crate::aggregates::ordered_partial_stream::OrderedPartialAggregateStream) +/// [`ClusteredPartialAggregateStream`](crate::aggregates::clustered_partial_stream::ClusteredPartialAggregateStream) /// for the high-level plan shape. /// /// Example: `AVG(v) FILTER (WHERE v>0) GROUP BY k` @@ -70,14 +70,14 @@ use super::common::{AggregateAccumulator, EvaluatedAggregateBatch}; /// # Marker Type /// /// `OrderedAggrMode` selects the aggregate semantics. For example, -/// `OrderedAggregateTable::::new(...)` consumes raw rows +/// `ClusteredAggregateTable::::new(...)` consumes raw rows /// and emits partial states, while -/// `OrderedAggregateTable::::new_with_input_order(...)` +/// `ClusteredAggregateTable::::new_with_input_order(...)` /// consumes partial states and emits final values. /// /// Shared methods live on `impl`; partial/final behavior lives on /// marker-specific impls. -pub(in crate::aggregates) struct OrderedAggregateTable { +pub(in crate::aggregates) struct ClusteredAggregateTable { /// Output schema: group columns followed by aggregate state or final values. pub(super) output_schema: SchemaRef, @@ -92,7 +92,7 @@ pub(in crate::aggregates) struct OrderedAggregateTable { pub(super) group_by_metrics: GroupByMetrics, /// Group keys, ordering state, and accumulator states. - pub(super) buffer: OrderedAggregateTableBuffer, + pub(super) buffer: ClusteredAggregateTableBuffer, _mode: PhantomData, } @@ -102,15 +102,15 @@ pub(in crate::aggregates) struct OrderedAggregateTable { /// It accumulates input during aggregation and emits output rows as soon as the /// input ordering proves those groups are complete. /// -/// [`GroupOrdering`] tracks when and how to do early emit. +/// [`GroupClustering`] tracks when and how to do early emit. /// [`GroupValues`] stores the physical group-key layout, while /// [`datafusion_expr::GroupsAccumulator`] stores per-group aggregate state. -pub(super) struct OrderedAggregateTableBuffer { +pub(super) struct ClusteredAggregateTableBuffer { /// GROUP BY expressions evaluated against input batches. pub(super) group_by: Arc, /// Tracks how far ordered input allows this table to drain safely. - pub(super) group_ordering: GroupOrdering, + pub(super) group_clustering: GroupClustering, /// Interned group keys, in the same group-id order used by accumulators. pub(super) group_values: Box, @@ -126,7 +126,7 @@ pub(super) struct OrderedAggregateTableBuffer { } /// Methods shared by all aggregate modes -impl OrderedAggregateTable { +impl ClusteredAggregateTable { #[expect( clippy::too_many_arguments, reason = "keeps ordered partial and final table construction explicit" @@ -137,19 +137,19 @@ impl OrderedAggregateTable { output_schema: SchemaRef, state_schema: SchemaRef, batch_size: usize, - input_order_mode: &InputOrderMode, + group_clustering_mode: &GroupClusteringMode, aggregate_mode: &AggregateMode, filters: Vec>>, group_by_metrics: GroupByMetrics, ) -> Result { assert_or_internal_err!( batch_size > 0, - "OrderedAggregateTable requires config batch_size >= 1" + "ClusteredAggregateTable requires config batch_size >= 1" ); - let group_ordering = GroupOrdering::try_new(input_order_mode)?; + let group_clustering = GroupClustering::try_new(group_clustering_mode)?; let group_schema = agg.group_by.group_schema(input_schema)?; - let group_values = new_group_values(group_schema, &group_ordering)?; + let group_values = new_group_values(group_schema, &group_clustering)?; let aggregate_arguments = aggregate_expressions( &agg.aggr_expr, aggregate_mode, @@ -176,9 +176,9 @@ impl OrderedAggregateTable { state_schema, batch_size, group_by_metrics, - buffer: OrderedAggregateTableBuffer { + buffer: ClusteredAggregateTableBuffer { group_by: Arc::clone(&agg.group_by), - group_ordering, + group_clustering, group_values, group_indices: vec![], accumulators, @@ -217,15 +217,15 @@ impl OrderedAggregateTable { /// Called after the input stream is exhausted and the last batch has been /// aggregated. /// - /// Updates the internal `GroupOrdering` so it can continue emitting until + /// Updates the internal `GroupClustering` so it can continue emitting until /// the buffer is empty. pub(in crate::aggregates) fn input_done(&mut self) { - self.buffer.group_ordering.input_done(); + self.buffer.group_clustering.input_done(); } /// Returns the ordering state used to decide how memory pressure is handled. - pub(in crate::aggregates) fn group_ordering(&self) -> &GroupOrdering { - &self.buffer.group_ordering + pub(in crate::aggregates) fn group_clustering(&self) -> &GroupClustering { + &self.buffer.group_clustering } /// Number of groups currently buffered. @@ -246,7 +246,7 @@ impl OrderedAggregateTable { .map(|acc| acc.size()) .sum::() + self.buffer.group_values.size() - + self.buffer.group_ordering.size() + + self.buffer.group_clustering.size() + self.buffer.group_indices.allocated_size() } @@ -282,7 +282,7 @@ impl OrderedAggregateTable { self.buffer.group_values.clear_shrink(0); self.buffer.group_indices.clear(); self.buffer.group_indices.shrink_to_fit(); - self.buffer.group_ordering.reset(); + self.buffer.group_clustering.reset(); Ok(Some(batch)) } @@ -291,7 +291,7 @@ impl OrderedAggregateTable { /// /// Returns `(emit_to, should_remove_groups)`, where `emit_to` is the number /// of groups to emit from `GroupValues` / accumulators, and - /// `should_remove_groups` indicates whether `GroupOrdering` must also shift + /// `should_remove_groups` indicates whether `GroupClustering` must also shift /// its tracked indexes. pub(super) fn clamp_emit_to( &self, @@ -324,7 +324,7 @@ impl OrderedAggregateTable { .intern(group_values, &mut self.buffer.group_indices)?; let total_num_groups = self.buffer.group_values.len(); if total_num_groups > starting_num_groups { - self.buffer.group_ordering.new_groups( + self.buffer.group_clustering.new_groups( group_values, &self.buffer.group_indices, total_num_groups, @@ -358,7 +358,7 @@ impl OrderedAggregateTable { Ok(()) } - /// Emits groups allowed by `GroupOrdering`, leaving only the current + /// Emits groups allowed by `GroupClustering`, leaving only the current /// unfinished ordered-key range buffered. /// /// This common utility is used by ordered partial and ordered final aggregation. @@ -375,7 +375,7 @@ impl OrderedAggregateTable { return Ok(None); } - let Some(emit_to) = self.buffer.group_ordering.emit_to() else { + let Some(emit_to) = self.buffer.group_clustering.emit_to() else { return Ok(None); }; let (emit_to, should_remove_groups) = @@ -385,7 +385,7 @@ impl OrderedAggregateTable { let mut output = self.buffer.group_values.emit(emit_to)?; if should_remove_groups { match emit_to { - EmitTo::First(n) => self.buffer.group_ordering.remove_groups(n), + EmitTo::First(n) => self.buffer.group_clustering.remove_groups(n), // `EmitTo::All` is only used after `input_done`, when all // buffered groups are known complete and the ordering state is // no longer needed. diff --git a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/mod.rs b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/mod.rs index 2c7ec01654a63..aa98c4c12b7cb 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/mod.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/mod.rs @@ -15,11 +15,11 @@ // specific language governing permissions and limitations // under the License. +mod clustered_final_table; +mod clustered_partial_table; mod common; -mod common_ordered; +mod common_clustered; mod final_table; -mod ordered_final_table; -mod ordered_partial_table; mod partial_reduce_table; mod partial_table; mod single_table; @@ -28,4 +28,4 @@ pub(super) use common::{ AggregateHashTable, FinalMarker, PartialMarker, PartialReduceMarker, PartialSkipMarker, SingleMarker, }; -pub(super) use common_ordered::OrderedAggregateTable; +pub(super) use common_clustered::ClusteredAggregateTable; diff --git a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/partial_table.rs b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/partial_table.rs index a64fd32536eeb..2345663209513 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/partial_table.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/partial_table.rs @@ -25,7 +25,7 @@ use arrow::record_batch::RecordBatch; use datafusion_common::{Result, assert_eq_or_internal_err}; use crate::aggregates::group_values::new_group_values; -use crate::aggregates::order::GroupOrdering; +use crate::aggregates::order::GroupClustering; use crate::aggregates::{AggregateExec, group_id_array, max_duplicate_ordinal}; use super::common::{ @@ -77,7 +77,7 @@ impl AggregateHashTable { ) -> Result> { let state = self.state.building(); let group_schema = state.group_by.group_schema(&self.input_schema)?; - let group_values = new_group_values(group_schema, &GroupOrdering::None)?; + let group_values = new_group_values(group_schema, &GroupClustering::None)?; let accumulators = state .accumulators .iter() diff --git a/datafusion/physical-plan/src/aggregates/ordered_final_stream.rs b/datafusion/physical-plan/src/aggregates/clustered_final_stream.rs similarity index 81% rename from datafusion/physical-plan/src/aggregates/ordered_final_stream.rs rename to datafusion/physical-plan/src/aggregates/clustered_final_stream.rs index 19deedc258c46..e2400c97d6223 100644 --- a/datafusion/physical-plan/src/aggregates/ordered_final_stream.rs +++ b/datafusion/physical-plan/src/aggregates/clustered_final_stream.rs @@ -32,24 +32,25 @@ use datafusion_physical_expr_common::sort_expr::LexOrdering; use futures::stream::{Stream, StreamExt}; use super::AggregateExec; -use super::aggregate_hash_table::{FinalMarker, OrderedAggregateTable}; +use super::aggregate_hash_table::{ClusteredAggregateTable, FinalMarker}; use super::group_values::GroupByMetrics; use crate::aggregates::AggregateMode; +use crate::aggregates::GroupClusteringMode; use crate::metrics::{BaselineMetrics, RecordOutput, SpillMetrics}; use crate::sorts::IncrementalSortIterator; use crate::sorts::streaming_merge::{SortedSpillFile, StreamingMergeBuilder}; use crate::spill::spill_manager::SpillManager; use crate::stream::EmptyRecordBatchStream; -use crate::{InputOrderMode, RecordBatchStream, SendableRecordBatchStream}; +use crate::{RecordBatchStream, SendableRecordBatchStream}; -/// Final aggregate stream for `InputOrderMode::Sorted` and -/// `InputOrderMode::PartiallySorted`. +/// Final aggregate stream for `GroupClusteringMode::Full` and +/// `GroupClusteringMode::Partial`. /// -/// See comments at [`super::ordered_partial_stream::OrderedPartialAggregateStream`] for details. +/// See comments at [`super::clustered_partial_stream::ClusteredPartialAggregateStream`] for details. /// /// # Spilling /// -/// This section is only for implementation notes, for background, see [`super::ordered_partial_stream::OrderedPartialAggregateStream`] +/// This section is only for implementation notes, for background, see [`super::clustered_partial_stream::ClusteredPartialAggregateStream`] /// /// For partially sorted input, spilling works as follows: /// @@ -61,12 +62,12 @@ use crate::{InputOrderMode, RecordBatchStream, SendableRecordBatchStream}; /// batch and full index remain live until the run is written. /// - After input ends, merge the sorted runs and replay them through a fully /// ordered final aggregate stream. -pub(crate) struct OrderedFinalAggregateStream { +pub(crate) struct ClusteredFinalAggregateStream { schema: SchemaRef, input: SendableRecordBatchStream, reservation: MemoryReservation, baseline_metrics: BaselineMetrics, - state: Option, + state: Option, } /// Spill configuration and accumulated runs for partially ordered final @@ -94,23 +95,23 @@ struct OrderedFinalSpillContext { } /// See comments at `poll_next()` for details. -enum OrderedFinalAggregateState { +enum ClusteredFinalAggregateState { ReadingInput { - table: OrderedAggregateTable, + table: ClusteredAggregateTable, /// None if either /// - Disk Manager doesn't enable temporary file creation /// - The group keys are fully ordered, it's expected to use bounded memory spill_context: Option>, }, Spilling { - table: OrderedAggregateTable, + table: ClusteredAggregateTable, spill_context: Box, }, ProducingOutput { - table: OrderedAggregateTable, + table: ClusteredAggregateTable, }, PreparingMergeInput { - table: OrderedAggregateTable, + table: ClusteredAggregateTable, spill_context: Box, }, MergingSpills { @@ -119,10 +120,10 @@ enum OrderedFinalAggregateState { Done, } -type OrderedFinalAggregatePoll = Poll>>; -type OrderedFinalAggregateStateTransition = ControlFlow< - (OrderedFinalAggregatePoll, OrderedFinalAggregateState), - OrderedFinalAggregateState, +type ClusteredFinalAggregatePoll = Poll>>; +type ClusteredFinalAggregateStateTransition = ControlFlow< + (ClusteredFinalAggregatePoll, ClusteredFinalAggregateState), + ClusteredFinalAggregateState, >; impl OrderedFinalSpillContext { @@ -131,13 +132,13 @@ impl OrderedFinalSpillContext { context: &Arc, partition: usize, batch_size: usize, - input_order_mode: &InputOrderMode, + group_clustering_mode: &GroupClusteringMode, spill_schema: &SchemaRef, spill_metrics: SpillMetrics, ) -> Result { let group_schema = agg.group_by.group_schema(spill_schema)?; let output_ordering = agg.cache.output_ordering(); - let InputOrderMode::PartiallySorted(order_indices) = input_order_mode else { + let GroupClusteringMode::Partial(order_indices) = group_clustering_mode else { return internal_err!("Ordered final spill requires partially ordered input"); }; let spill_indices = order_indices.iter().copied().chain( @@ -182,10 +183,10 @@ impl OrderedFinalSpillContext { /// /// Individual spill files are ordered by the `group by` keys. /// - /// See [`OrderedFinalAggregateStream`] for spilling details. + /// See [`ClusteredFinalAggregateStream`] for spilling details. fn spill_table( &mut self, - table: &mut OrderedAggregateTable, + table: &mut ClusteredAggregateTable, ) -> Result<()> { let Some(batch) = table.take_state_batch()? else { return Ok(()); @@ -197,7 +198,7 @@ impl OrderedFinalSpillContext { .spill_manager .spill_record_batch_iter_and_return_max_batch_memory( sorted_iter, - "OrderedFinalAggregateSpill", + "ClusteredFinalAggregateSpill", )?; let Some((file, max_record_batch_memory)) = spill_file else { @@ -243,12 +244,12 @@ impl OrderedFinalSpillContext { .with_batch_size(batch_size) .with_reservation(merge_reservation) .build()?; - let replay = OrderedFinalAggregateStream::new_with_input_and_metrics( + let replay = ClusteredFinalAggregateStream::new_with_input_and_metrics( &agg, &context, partition, merged, - &InputOrderMode::Sorted, + &GroupClusteringMode::Full, baseline_metrics.clone(), group_by_metrics, None, @@ -258,7 +259,7 @@ impl OrderedFinalSpillContext { } } -impl OrderedFinalAggregateStream { +impl ClusteredFinalAggregateStream { pub fn new( agg: &AggregateExec, context: &Arc, @@ -268,10 +269,10 @@ impl OrderedFinalAggregateStream { agg.mode, AggregateMode::Final | AggregateMode::FinalPartitioned )); - debug_assert_ne!(agg.input_order_mode, InputOrderMode::Linear); + debug_assert_ne!(agg.group_clustering_mode, GroupClusteringMode::None); let input = agg.input.execute(partition, Arc::clone(context))?; - Self::new_with_input(agg, context, partition, input, &agg.input_order_mode) + Self::new_with_input(agg, context, partition, input, &agg.group_clustering_mode) } pub(in crate::aggregates) fn new_with_input( @@ -279,13 +280,13 @@ impl OrderedFinalAggregateStream { context: &Arc, partition: usize, input: SendableRecordBatchStream, - input_order_mode: &InputOrderMode, + group_clustering_mode: &GroupClusteringMode, ) -> Result { let baseline_metrics = BaselineMetrics::new(&agg.metrics, partition); let group_by_metrics = GroupByMetrics::new(&agg.metrics, partition); let spill_metrics = SpillMetrics::new(&agg.metrics, partition); let reservation = - MemoryConsumer::new(format!("OrderedFinalAggregateStream[{partition}]")) + MemoryConsumer::new(format!("ClusteredFinalAggregateStream[{partition}]")) // HACK: Technically, fully ordered aggregate is a non-spillable // consumer, since it uses bounded memory. There is a known race // condition bug, and we set it to spillable to let it have larger @@ -298,7 +299,7 @@ impl OrderedFinalAggregateStream { context, partition, input, - input_order_mode, + group_clustering_mode, baseline_metrics, group_by_metrics, Some(spill_metrics), @@ -318,7 +319,7 @@ impl OrderedFinalAggregateStream { context: &Arc, partition: usize, input: SendableRecordBatchStream, - input_order_mode: &InputOrderMode, + group_clustering_mode: &GroupClusteringMode, baseline_metrics: BaselineMetrics, group_by_metrics: GroupByMetrics, spill_metrics: Option, @@ -328,13 +329,13 @@ impl OrderedFinalAggregateStream { agg.mode, AggregateMode::Final | AggregateMode::FinalPartitioned )); - debug_assert_ne!(*input_order_mode, InputOrderMode::Linear); + debug_assert_ne!(*group_clustering_mode, GroupClusteringMode::None); let schema = Arc::clone(&agg.schema); let input_schema = input.schema(); let batch_size = context.session_config().batch_size(); - let can_spill = matches!(input_order_mode, InputOrderMode::PartiallySorted(_)) + let can_spill = matches!(group_clustering_mode, GroupClusteringMode::Partial(_)) && context.runtime_env().disk_manager.tmp_files_enabled(); let spill_context = if can_spill { let Some(spill_metrics) = spill_metrics else { @@ -345,7 +346,7 @@ impl OrderedFinalAggregateStream { context, partition, batch_size, - input_order_mode, + group_clustering_mode, &input_schema, spill_metrics, )?)) @@ -353,12 +354,12 @@ impl OrderedFinalAggregateStream { None }; - let table = OrderedAggregateTable::::new_with_input_order( + let table = ClusteredAggregateTable::::new_with_input_order( agg, &input_schema, Arc::clone(&schema), batch_size, - input_order_mode, + group_clustering_mode, group_by_metrics, )?; Ok(Self { @@ -366,7 +367,7 @@ impl OrderedFinalAggregateStream { input, reservation, baseline_metrics, - state: Some(OrderedFinalAggregateState::ReadingInput { + state: Some(ClusteredFinalAggregateState::ReadingInput { table, spill_context, }), @@ -378,21 +379,21 @@ impl OrderedFinalAggregateStream { self.input = Box::pin(EmptyRecordBatchStream::new(input_schema)); } - fn break_with_internal_err(message: &str) -> OrderedFinalAggregateStateTransition { + fn break_with_internal_err(message: &str) -> ClusteredFinalAggregateStateTransition { ControlFlow::Break(( Poll::Ready(Some(internal_err!("{message}"))), - OrderedFinalAggregateState::Done, + ClusteredFinalAggregateState::Done, )) } /// Reserve memory for the current aggregate table. fn reservation_size_for_table( - table: &OrderedAggregateTable, + table: &ClusteredAggregateTable, spill_context: Option<&OrderedFinalSpillContext>, ) -> usize { let table_size = table.memory_size(); if spill_context.is_some() { - // See `OrderedFinalAggregateStream` comments for how is it estimated + // See `ClusteredFinalAggregateStream` comments for how is it estimated table_size.saturating_add(table.num_groups().saturating_mul(size_of::())) } else { table_size @@ -408,9 +409,9 @@ impl OrderedFinalAggregateStream { fn handle_reading_input( &mut self, cx: &mut Context<'_>, - original_state: OrderedFinalAggregateState, - ) -> OrderedFinalAggregateStateTransition { - let OrderedFinalAggregateState::ReadingInput { + original_state: ClusteredFinalAggregateState, + ) -> ClusteredFinalAggregateStateTransition { + let ClusteredFinalAggregateState::ReadingInput { mut table, spill_context, } = original_state @@ -423,7 +424,7 @@ impl OrderedFinalAggregateStream { match self.input.poll_next_unpin(cx) { Poll::Pending => ControlFlow::Break(( Poll::Pending, - OrderedFinalAggregateState::ReadingInput { + ClusteredFinalAggregateState::ReadingInput { table, spill_context, }, @@ -437,7 +438,7 @@ impl OrderedFinalAggregateStream { if let Err(e) = result { return ControlFlow::Break(( Poll::Ready(Some(Err(e))), - OrderedFinalAggregateState::ReadingInput { + ClusteredFinalAggregateState::ReadingInput { table, spill_context, }, @@ -458,20 +459,20 @@ impl OrderedFinalAggregateStream { Err(e @ DataFusionError::ResourcesExhausted(_)) => { let Some(spill_context) = spill_context else { // `None` means spilling is not supported, see comments - // at `OrderedFinalAggregateState` for details. + // at `ClusteredFinalAggregateState` for details. return ControlFlow::Break(( Poll::Ready(Some(Err(e))), - OrderedFinalAggregateState::Done, + ClusteredFinalAggregateState::Done, )); }; if table.is_empty() { return ControlFlow::Break(( Poll::Ready(Some(Err(e))), - OrderedFinalAggregateState::Done, + ClusteredFinalAggregateState::Done, )); } return ControlFlow::Continue( - OrderedFinalAggregateState::Spilling { + ClusteredFinalAggregateState::Spilling { table, spill_context, }, @@ -480,7 +481,7 @@ impl OrderedFinalAggregateStream { Err(e) => { return ControlFlow::Break(( Poll::Ready(Some(Err(e))), - OrderedFinalAggregateState::Done, + ClusteredFinalAggregateState::Done, )); } } @@ -512,10 +513,10 @@ impl OrderedFinalAggregateStream { { return ControlFlow::Break(( Poll::Ready(Some(Err(e))), - OrderedFinalAggregateState::Done, + ClusteredFinalAggregateState::Done, )); } - let next_state = OrderedFinalAggregateState::ReadingInput { + let next_state = ClusteredFinalAggregateState::ReadingInput { table, spill_context, }; @@ -528,15 +529,15 @@ impl OrderedFinalAggregateStream { )) } // Can't do early emit, continue aggregating. - Ok(None) => { - ControlFlow::Continue(OrderedFinalAggregateState::ReadingInput { + Ok(None) => ControlFlow::Continue( + ClusteredFinalAggregateState::ReadingInput { table, spill_context, - }) - } + }, + ), Err(e) => ControlFlow::Break(( Poll::Ready(Some(Err(e))), - OrderedFinalAggregateState::ReadingInput { + ClusteredFinalAggregateState::ReadingInput { table, spill_context, }, @@ -545,7 +546,7 @@ impl OrderedFinalAggregateStream { } Poll::Ready(Some(Err(e))) => ControlFlow::Break(( Poll::Ready(Some(Err(e))), - OrderedFinalAggregateState::ReadingInput { + ClusteredFinalAggregateState::ReadingInput { table, spill_context, }, @@ -555,7 +556,7 @@ impl OrderedFinalAggregateStream { match spill_context { Some(spill_context) if spill_context.has_spills() => { ControlFlow::Continue( - OrderedFinalAggregateState::PreparingMergeInput { + ClusteredFinalAggregateState::PreparingMergeInput { table, spill_context, }, @@ -564,7 +565,7 @@ impl OrderedFinalAggregateStream { _ => { table.input_done(); ControlFlow::Continue( - OrderedFinalAggregateState::ProducingOutput { table }, + ClusteredFinalAggregateState::ProducingOutput { table }, ) } } @@ -579,9 +580,9 @@ impl OrderedFinalAggregateStream { /// Returns the next operator state with control flow decision. fn handle_spilling( &mut self, - original_state: OrderedFinalAggregateState, - ) -> OrderedFinalAggregateStateTransition { - let OrderedFinalAggregateState::Spilling { + original_state: ClusteredFinalAggregateState, + ) -> ClusteredFinalAggregateStateTransition { + let ClusteredFinalAggregateState::Spilling { mut table, mut spill_context, } = original_state @@ -597,7 +598,7 @@ impl OrderedFinalAggregateStream { Poll::Ready(Some(internal_err!( "Ordered final aggregation entered Spilling with an empty table" ))), - OrderedFinalAggregateState::Done, + ClusteredFinalAggregateState::Done, )); } @@ -616,13 +617,13 @@ impl OrderedFinalAggregateStream { match result { // Finished spilling the aggregate table, continue aggregating from input - Ok(()) => ControlFlow::Continue(OrderedFinalAggregateState::ReadingInput { + Ok(()) => ControlFlow::Continue(ClusteredFinalAggregateState::ReadingInput { table, spill_context: Some(spill_context), }), Err(e) => ControlFlow::Break(( Poll::Ready(Some(Err(e))), - OrderedFinalAggregateState::Done, + ClusteredFinalAggregateState::Done, )), } } @@ -638,9 +639,9 @@ impl OrderedFinalAggregateStream { /// Returns the next operator state with control flow decision. fn handle_preparing_merge_input( &mut self, - original_state: OrderedFinalAggregateState, - ) -> OrderedFinalAggregateStateTransition { - let OrderedFinalAggregateState::PreparingMergeInput { + original_state: ClusteredFinalAggregateState, + ) -> ClusteredFinalAggregateStateTransition { + let ClusteredFinalAggregateState::PreparingMergeInput { mut table, mut spill_context, } = original_state @@ -671,13 +672,13 @@ impl OrderedFinalAggregateStream { match replay { Ok(stream) => { - ControlFlow::Continue(OrderedFinalAggregateState::MergingSpills { + ControlFlow::Continue(ClusteredFinalAggregateState::MergingSpills { stream, }) } Err(e) => ControlFlow::Break(( Poll::Ready(Some(Err(e))), - OrderedFinalAggregateState::Done, + ClusteredFinalAggregateState::Done, )), } } @@ -691,9 +692,9 @@ impl OrderedFinalAggregateStream { fn handle_merging_spills( &mut self, cx: &mut Context<'_>, - original_state: OrderedFinalAggregateState, - ) -> OrderedFinalAggregateStateTransition { - let OrderedFinalAggregateState::MergingSpills { mut stream } = original_state + original_state: ClusteredFinalAggregateState, + ) -> ClusteredFinalAggregateStateTransition { + let ClusteredFinalAggregateState::MergingSpills { mut stream } = original_state else { return Self::break_with_internal_err( "Ordered final aggregate stream expected MergingSpills state", @@ -703,17 +704,19 @@ impl OrderedFinalAggregateStream { match stream.poll_next_unpin(cx) { Poll::Pending => ControlFlow::Break(( Poll::Pending, - OrderedFinalAggregateState::MergingSpills { stream }, + ClusteredFinalAggregateState::MergingSpills { stream }, )), Poll::Ready(Some(Ok(batch))) => ControlFlow::Break(( Poll::Ready(Some(Ok(batch))), - OrderedFinalAggregateState::MergingSpills { stream }, + ClusteredFinalAggregateState::MergingSpills { stream }, )), Poll::Ready(Some(Err(e))) => ControlFlow::Break(( Poll::Ready(Some(Err(e))), - OrderedFinalAggregateState::Done, + ClusteredFinalAggregateState::Done, )), - Poll::Ready(None) => ControlFlow::Continue(OrderedFinalAggregateState::Done), + Poll::Ready(None) => { + ControlFlow::Continue(ClusteredFinalAggregateState::Done) + } } } @@ -727,9 +730,10 @@ impl OrderedFinalAggregateStream { /// Returns the next operator state with control flow decision. fn handle_producing_output( &mut self, - original_state: OrderedFinalAggregateState, - ) -> OrderedFinalAggregateStateTransition { - let OrderedFinalAggregateState::ProducingOutput { table } = original_state else { + original_state: ClusteredFinalAggregateState, + ) -> ClusteredFinalAggregateStateTransition { + let ClusteredFinalAggregateState::ProducingOutput { table } = original_state + else { return Self::break_with_internal_err( "Ordered final aggregate stream expected ProducingOutput state", ); @@ -748,18 +752,18 @@ impl OrderedFinalAggregateStream { if let Err(e) = self.reservation.try_resize(0) { return ControlFlow::Break(( Poll::Ready(Some(Err(e))), - OrderedFinalAggregateState::Done, + ClusteredFinalAggregateState::Done, )); } - OrderedFinalAggregateState::Done + ClusteredFinalAggregateState::Done } else { if let Err(e) = self.reservation.try_resize(table.memory_size()) { return ControlFlow::Break(( Poll::Ready(Some(Err(e))), - OrderedFinalAggregateState::ProducingOutput { table }, + ClusteredFinalAggregateState::ProducingOutput { table }, )); } - OrderedFinalAggregateState::ProducingOutput { table } + ClusteredFinalAggregateState::ProducingOutput { table } }; ControlFlow::Break(( @@ -769,11 +773,11 @@ impl OrderedFinalAggregateStream { } Err(e) => ControlFlow::Break(( Poll::Ready(Some(Err(e))), - OrderedFinalAggregateState::ProducingOutput { table }, + ClusteredFinalAggregateState::ProducingOutput { table }, )), Ok(None) => { drop(table); - let next_state = OrderedFinalAggregateState::Done; + let next_state = ClusteredFinalAggregateState::Done; if let Err(e) = self.reservation.try_resize(0) { return ControlFlow::Break((Poll::Ready(Some(Err(e))), next_state)); } @@ -783,12 +787,12 @@ impl OrderedFinalAggregateStream { } } -impl Stream for OrderedFinalAggregateStream { +impl Stream for ClusteredFinalAggregateStream { type Item = Result; /// Entry point for the ordered final aggregate state machine. /// - /// See comments in [`OrderedFinalAggregateStream`] for high-level ideas. + /// See comments in [`ClusteredFinalAggregateStream`] for high-level ideas. /// /// State transition graph: /// @@ -847,25 +851,25 @@ impl Stream for OrderedFinalAggregateStream { let cur_state = self .state .take() - .expect("OrderedFinalAggregateStream state should not be None"); + .expect("ClusteredFinalAggregateStream state should not be None"); let next_state = match cur_state { - state @ OrderedFinalAggregateState::ReadingInput { .. } => { + state @ ClusteredFinalAggregateState::ReadingInput { .. } => { self.handle_reading_input(cx, state) } - state @ OrderedFinalAggregateState::Spilling { .. } => { + state @ ClusteredFinalAggregateState::Spilling { .. } => { self.handle_spilling(state) } - state @ OrderedFinalAggregateState::PreparingMergeInput { .. } => { + state @ ClusteredFinalAggregateState::PreparingMergeInput { .. } => { self.handle_preparing_merge_input(state) } - state @ OrderedFinalAggregateState::MergingSpills { .. } => { + state @ ClusteredFinalAggregateState::MergingSpills { .. } => { self.handle_merging_spills(cx, state) } - state @ OrderedFinalAggregateState::ProducingOutput { .. } => { + state @ ClusteredFinalAggregateState::ProducingOutput { .. } => { self.handle_producing_output(state) } - state @ OrderedFinalAggregateState::Done => { + state @ ClusteredFinalAggregateState::Done => { let _ = self.reservation.try_resize(0); self.state = Some(state); return Poll::Ready(None); @@ -883,7 +887,7 @@ impl Stream for OrderedFinalAggregateStream { drop(next_state); self.close_input(); self.reservation.free(); - self.state = Some(OrderedFinalAggregateState::Done); + self.state = Some(ClusteredFinalAggregateState::Done); return Poll::Ready(Some(Err(e))); } ControlFlow::Break((poll, next_state)) => { @@ -895,7 +899,7 @@ impl Stream for OrderedFinalAggregateStream { } } -impl RecordBatchStream for OrderedFinalAggregateStream { +impl RecordBatchStream for ClusteredFinalAggregateStream { fn schema(&self) -> SchemaRef { Arc::clone(&self.schema) } diff --git a/datafusion/physical-plan/src/aggregates/ordered_partial_stream.rs b/datafusion/physical-plan/src/aggregates/clustered_partial_stream.rs similarity index 89% rename from datafusion/physical-plan/src/aggregates/ordered_partial_stream.rs rename to datafusion/physical-plan/src/aggregates/clustered_partial_stream.rs index 9e93a111a6466..c8324add260e4 100644 --- a/datafusion/physical-plan/src/aggregates/ordered_partial_stream.rs +++ b/datafusion/physical-plan/src/aggregates/clustered_partial_stream.rs @@ -27,15 +27,16 @@ use datafusion_execution::{TaskContext, TryEmitter, async_try_stream}; use futures::stream::{Stream, StreamExt}; use super::AggregateExec; -use super::aggregate_hash_table::{OrderedAggregateTable, PartialMarker}; +use super::aggregate_hash_table::{ClusteredAggregateTable, PartialMarker}; use crate::aggregates::AggregateMode; -use crate::aggregates::order::GroupOrdering; +use crate::aggregates::GroupClusteringMode; +use crate::aggregates::order::GroupClustering; use crate::metrics::{BaselineMetrics, MetricBuilder, SpillMetrics}; use crate::stream::{EmptyRecordBatchStream, ObservedStream, RecordBatchStreamAdapter}; -use crate::{InputOrderMode, SendableRecordBatchStream, metrics}; +use crate::{SendableRecordBatchStream, metrics}; -/// Partial aggregate stream for `InputOrderMode::Sorted` and -/// `InputOrderMode::PartiallySorted`. +/// Partial aggregate stream for `GroupClusteringMode::Full` and +/// `GroupClusteringMode::Partial`. /// /// # Example /// @@ -94,10 +95,10 @@ use crate::{InputOrderMode, SendableRecordBatchStream, metrics}; /// If one `a` value contains many distinct `b` values, the table may accumulate /// enough groups to exceed the memory limit. /// -/// - `OrderedPartialAggregateStream`: On reservation failure, it emits all current +/// - `ClusteredPartialAggregateStream`: On reservation failure, it emits all current /// intermediate states downstream and resets the table. The final stage can /// merge repeated `(a, b)` state rows, so no disk spill is required. -/// - `OrderedFinalAggregateStream`: It cannot emit incomplete final results. On +/// - `ClusteredFinalAggregateStream`: It cannot emit incomplete final results. On /// reservation failure, it sorts the current intermediate states by the complete /// group key and spills them as one run. After the input ends, it spills any /// remaining states, performs a sort-preserving merge of all runs, and feeds the @@ -110,23 +111,23 @@ use crate::{InputOrderMode, SendableRecordBatchStream, metrics}; /// /// See issue for details: /// -pub(crate) struct OrderedPartialAggregateStream { +pub(crate) struct ClusteredPartialAggregateStream { schema: SchemaRef, input: SendableRecordBatchStream, reservation: MemoryReservation, baseline_metrics: BaselineMetrics, reduction_factor: metrics::RatioMetrics, - table: Option>, + table: Option>, } -impl OrderedPartialAggregateStream { +impl ClusteredPartialAggregateStream { pub fn new( agg: &AggregateExec, context: &Arc, partition: usize, ) -> Result { debug_assert_eq!(agg.mode, AggregateMode::Partial); - debug_assert_ne!(agg.input_order_mode, InputOrderMode::Linear); + debug_assert_ne!(agg.group_clustering_mode, GroupClusteringMode::None); let schema = Arc::clone(&agg.schema); let input = agg.input.execute(partition, Arc::clone(context))?; @@ -139,17 +140,17 @@ impl OrderedPartialAggregateStream { .with_type(metrics::MetricType::Summary) .ratio_metrics("reduction_factor", partition); - let table = OrderedAggregateTable::::new( + let table = ClusteredAggregateTable::::new( agg, partition, Arc::clone(&schema), batch_size, )?; let reservation = - MemoryConsumer::new(format!("OrderedPartialAggregateStream[{partition}]")) + MemoryConsumer::new(format!("ClusteredPartialAggregateStream[{partition}]")) .with_can_spill(matches!( - table.group_ordering(), - GroupOrdering::Partial(_) + table.group_clustering(), + GroupClustering::Partial(_) )) .register(context.memory_pool()); @@ -177,7 +178,7 @@ impl OrderedPartialAggregateStream { /// Entry point for the ordered partial aggregate state machine. /// - /// See comments in [`OrderedPartialAggregateStream`] for high-level ideas. + /// See comments in [`ClusteredPartialAggregateStream`] for high-level ideas. /// /// State transitions are implemented using the generator pattern; see the comments in [`async_try_stream`]. /// @@ -213,7 +214,7 @@ impl OrderedPartialAggregateStream { let mut table = self .table .take() - .expect("OrderedPartialAggregateStream state should not be None"); + .expect("ClusteredPartialAggregateStream state should not be None"); self.handle_reading_input(&mut table, &mut emitter).await?; @@ -238,7 +239,7 @@ impl OrderedPartialAggregateStream { /// See comments at [`Self::create_stream`] for details. async fn handle_reading_input( &mut self, - table: &mut OrderedAggregateTable, + table: &mut ClusteredAggregateTable, emitter: &mut TryEmitter, ) -> Result<()> { let elapsed_compute = self.baseline_metrics.elapsed_compute().clone(); @@ -291,7 +292,7 @@ impl OrderedPartialAggregateStream { /// Issue: fn resize_or_take_state_batch( &mut self, - table: &mut OrderedAggregateTable, + table: &mut ClusteredAggregateTable, ) -> Result> { let oom = match self.reservation.try_resize(table.memory_size()) { Ok(()) => return Ok(None), @@ -299,7 +300,7 @@ impl OrderedPartialAggregateStream { Err(e) => return Err(e), }; - if matches!(table.group_ordering(), GroupOrdering::Full(_)) { + if matches!(table.group_clustering(), GroupClustering::Full(_)) { return Err(oom); } @@ -319,7 +320,7 @@ impl OrderedPartialAggregateStream { /// async fn handle_draining_final( &mut self, - mut table: OrderedAggregateTable, + mut table: ClusteredAggregateTable, emitter: &mut TryEmitter, ) -> Result<()> { let elapsed_compute = self.baseline_metrics.elapsed_compute().clone(); diff --git a/datafusion/physical-plan/src/aggregates/group_values/mod.rs b/datafusion/physical-plan/src/aggregates/group_values/mod.rs index 1101d535311e4..92880dad291a6 100644 --- a/datafusion/physical-plan/src/aggregates/group_values/mod.rs +++ b/datafusion/physical-plan/src/aggregates/group_values/mod.rs @@ -43,7 +43,7 @@ use crate::aggregates::{ boolean::GroupValuesBoolean, bytes::GroupValuesBytes, bytes_view::GroupValuesBytesView, primitive::GroupValuesPrimitive, }, - order::GroupOrdering, + order::GroupClustering, }; mod metrics; @@ -135,7 +135,7 @@ pub trait GroupValues: Send { /// `GroupValuesRows`: crate::aggregates::group_values::GroupValuesRows pub fn new_group_values( schema: SchemaRef, - group_ordering: &GroupOrdering, + group_clustering: &GroupClustering, ) -> Result> { if schema.fields.len() == 1 { let d = schema.fields[0].data_type(); @@ -203,7 +203,7 @@ pub fn new_group_values( } if multi_group_by::supported_schema(schema.as_ref()) { - if matches!(group_ordering, GroupOrdering::None) { + if matches!(group_clustering, GroupClustering::None) { Ok(Box::new(GroupValuesColumn::::try_new(schema)?)) } else { Ok(Box::new(GroupValuesColumn::::try_new(schema)?)) diff --git a/datafusion/physical-plan/src/aggregates/grouped_hash_stream.rs b/datafusion/physical-plan/src/aggregates/grouped_hash_stream.rs index 99c101199459f..a1efbb41a264c 100644 --- a/datafusion/physical-plan/src/aggregates/grouped_hash_stream.rs +++ b/datafusion/physical-plan/src/aggregates/grouped_hash_stream.rs @@ -21,11 +21,11 @@ use std::sync::Arc; use std::task::{Context, Poll}; use std::vec; -use super::order::GroupOrdering; +use super::order::GroupClustering; use super::skip_partial::SkipAggregationProbe; use super::{AggregateExec, format_human_display}; use crate::aggregates::group_values::{GroupByMetrics, GroupValues, new_group_values}; -use crate::aggregates::order::GroupOrderingFull; +use crate::aggregates::order::GroupClusteringFull; use crate::aggregates::{ AggregateInputMode, AggregateMode, AggregateOutputMode, PhysicalGroupBy, create_schema, evaluate_group_by, evaluate_many, evaluate_optional, group_id_array, @@ -347,7 +347,7 @@ pub(crate) struct GroupedHashAggregateStream { /// Optional ordering information, that might allow groups to be /// emitted from the hash table prior to seeing the end of the /// input - group_ordering: GroupOrdering, + group_clustering: GroupClustering, /// The spill state object spill_state: SpillState, @@ -488,19 +488,19 @@ impl GroupedHashAggregateStream { .collect::>() .join(", "); let name = format!("GroupedHashAggregateStream[{partition}] ({agg_fn_names})"); - let group_ordering = GroupOrdering::try_new(&agg.input_order_mode)?; - let oom_mode = match (agg.mode, &group_ordering) { + let group_clustering = GroupClustering::try_new(&agg.group_clustering_mode)?; + let oom_mode = match (agg.mode, &group_clustering) { // In partial aggregation mode, always prefer to emit incomplete results early. (AggregateMode::Partial, _) => OutOfMemoryMode::EmitEarly, // For non-partial aggregation modes, emitting incomplete results is not an option. // Instead, use disk spilling to store sorted, incomplete results, and merge them // afterwards. - (_, GroupOrdering::None | GroupOrdering::Partial(_)) + (_, GroupClustering::None | GroupClustering::Partial(_)) if context.runtime_env().disk_manager.tmp_files_enabled() => { OutOfMemoryMode::Spill } - // For `GroupOrdering::Full`, the incoming stream is already sorted. This ensures the + // For `GroupClustering::Full`, the incoming stream is already sorted. This ensures the // number of incomplete groups can be kept small at all times. If we still hit // an out-of-memory condition, spilling to disk would not be beneficial since the same // situation is likely to reoccur when reading back the spilled data. @@ -510,7 +510,7 @@ impl GroupedHashAggregateStream { _ => OutOfMemoryMode::ReportError, }; - let group_values = new_group_values(group_schema, &group_ordering)?; + let group_values = new_group_values(group_schema, &group_clustering)?; let reservation = MemoryConsumer::new(name) // We interpret 'can spill' as 'can handle memory back pressure'. // This value needs to be set to true for the default memory pool implementations @@ -546,7 +546,7 @@ impl GroupedHashAggregateStream { // since Final mode expects unique group values as its input // - there is only one GROUP BY expressions set let skip_aggregation_probe = if agg.mode == AggregateMode::Partial - && matches!(group_ordering, GroupOrdering::None) + && matches!(group_clustering, GroupClustering::None) && agg_group_by.is_single() { let options = &context.session_config().options().execution; @@ -599,7 +599,7 @@ impl GroupedHashAggregateStream { baseline_metrics, group_by_metrics, batch_size, - group_ordering, + group_clustering, input_done: false, spill_state, group_values_soft_limit: agg.limit_options().map(|config| config.limit()), @@ -676,7 +676,7 @@ impl Stream for GroupedHashAggregateStream { // this might lead to incorrect output ordering if (self.spill_state.spills.is_empty() || self.spill_state.is_stream_merging) - && let Some(to_emit) = self.group_ordering.emit_to() + && let Some(to_emit) = self.group_clustering.emit_to() { timer.done(); if let Some(batch) = self.emit(to_emit, false)? { @@ -884,7 +884,7 @@ impl GroupedHashAggregateStream { // Update ordering information if necessary let total_num_groups = self.group_values.len(); if total_num_groups > starting_num_groups { - self.group_ordering.new_groups( + self.group_clustering.new_groups( group_values, group_indices, total_num_groups, @@ -967,7 +967,7 @@ impl GroupedHashAggregateStream { self.group_values.len() }; - if let Some(emit_to) = self.group_ordering.oom_emit_to(n) + if let Some(emit_to) = self.group_clustering.oom_emit_to(n) && let Some(batch) = self.emit(emit_to, false)? { return Ok(Some(ExecutionState::ProducingOutput(batch))); @@ -984,7 +984,7 @@ impl GroupedHashAggregateStream { let acc = self.accumulators.iter().map(|x| x.size()).sum::(); let groups_and_acc_size = acc + self.group_values.size() - + self.group_ordering.size() + + self.group_clustering.size() + self.current_group_indices.allocated_size(); // Reserve extra headroom for sorting during potential spill. @@ -1029,7 +1029,7 @@ impl GroupedHashAggregateStream { let timer = self.group_by_metrics.emitting_time.timer(); let mut output = self.group_values.emit(emit_to)?; if let EmitTo::First(n) = emit_to { - self.group_ordering.remove_groups(n); + self.group_clustering.remove_groups(n); } // Next output each aggregate value @@ -1101,7 +1101,7 @@ impl GroupedHashAggregateStream { .intern(&cols, &mut self.current_group_indices)?; let total_groups = self.group_values.len(); if total_groups > starting_groups { - self.group_ordering.new_groups( + self.group_clustering.new_groups( &cols, &self.current_group_indices, total_groups, @@ -1254,7 +1254,7 @@ impl GroupedHashAggregateStream { /// in case of disk spilling, the SPM stream have been drained. fn set_input_done_and_produce_output(&mut self) -> Result<()> { self.input_done = true; - self.group_ordering.input_done(); + self.group_clustering.input_done(); // Release the original input pipeline's resources now that we're done // reading from it. In the spill branch below, `self.input` is replaced // again with a stream that merges spill files. @@ -1298,12 +1298,12 @@ impl GroupedHashAggregateStream { // Reset the group values collectors. self.clear_all(); - // We can now use `GroupOrdering::Full` since the spill files are sorted + // We can now use `GroupClustering::Full` since the spill files are sorted // on the grouping columns. - self.group_ordering = GroupOrdering::Full(GroupOrderingFull::new()); + self.group_clustering = GroupClustering::Full(GroupClusteringFull::new()); // Recreate `group_values` for streaming merge so group ids are assigned - // in first-seen order, as required by `GroupOrderingFull`. + // in first-seen order, as required by `GroupClusteringFull`. // The pre-spill multi-column collector may use `vectorized_intern`, which // can assign new group ids out of input order under hash collisions. let group_schema = self @@ -1311,7 +1311,8 @@ impl GroupedHashAggregateStream { .merging_group_by .group_schema(&self.spill_state.spill_schema)?; if group_schema.fields().len() > 1 { - self.group_values = new_group_values(group_schema, &self.group_ordering)?; + self.group_values = + new_group_values(group_schema, &self.group_clustering)?; } // Use `OutOfMemoryMode::ReportError` from this point on @@ -1398,7 +1399,7 @@ impl GroupedHashAggregateStream { #[cfg(test)] mod tests { use super::*; - use crate::InputOrderMode; + use crate::aggregates::GroupClusteringMode; use crate::test::TestMemoryExec; use arrow::array::{Int32Array, Int64Array}; use arrow::datatypes::{DataType, Field, Schema}; @@ -1515,7 +1516,7 @@ mod tests { Ok(()) } - // Migrated to OrderedPartialAggregateStream coverage in aggregates/mod.rs; + // Migrated to ClusteredPartialAggregateStream coverage in aggregates/mod.rs; // kept here for the legacy GroupedHashAggregateStream implementation. #[tokio::test] async fn test_emit_early_with_partially_sorted() -> Result<()> { @@ -1583,8 +1584,8 @@ mod tests { Arc::clone(&schema), )?; assert!(matches!( - aggregate_exec.input_order_mode(), - InputOrderMode::PartiallySorted(_) + aggregate_exec.group_clustering_mode(), + GroupClusteringMode::Partial(_) )); // Must not panic with "assertion failed: *current_sort >= n" diff --git a/datafusion/physical-plan/src/aggregates/hash_stream.rs b/datafusion/physical-plan/src/aggregates/hash_stream.rs index f697e5a394f65..a1c24b4d7d782 100644 --- a/datafusion/physical-plan/src/aggregates/hash_stream.rs +++ b/datafusion/physical-plan/src/aggregates/hash_stream.rs @@ -44,9 +44,10 @@ use super::AggregateExec; use super::aggregate_hash_table::{ AggregateHashTable, FinalMarker, PartialMarker, PartialSkipMarker, }; +use super::clustered_final_stream::ClusteredFinalAggregateStream; use super::group_values::GroupByMetrics; -use super::ordered_final_stream::OrderedFinalAggregateStream; use super::skip_partial::SkipAggregationProbe; +use crate::aggregates::GroupClusteringMode; use crate::metrics::{ BaselineMetrics, MetricBuilder, MetricCategory, RecordOutput, SpillMetrics, }; @@ -54,7 +55,7 @@ use crate::sorts::IncrementalSortIterator; use crate::sorts::streaming_merge::{SortedSpillFile, StreamingMergeBuilder}; use crate::spill::spill_manager::SpillManager; use crate::stream::EmptyRecordBatchStream; -use crate::{InputOrderMode, RecordBatchStream, SendableRecordBatchStream, metrics}; +use crate::{RecordBatchStream, SendableRecordBatchStream, metrics}; /// Hash aggregation is implemented in two stages: partial and final. This /// stream implements the partial stage. @@ -137,7 +138,7 @@ use crate::{InputOrderMode, RecordBatchStream, SendableRecordBatchStream, metric /// 3. Perform a sort-preserving merge of all spill files and feed the merged output /// into an ordered streaming aggregation, which ensures bounded memory usage and /// evaluates the final result. -/// - [`OrderedFinalAggregateStream`] is reused for the streaming aggregation. +/// - [`ClusteredFinalAggregateStream`] is reused for the streaming aggregation. pub(crate) struct PartialHashAggregateStream { /// Output schema: group columns followed by partial aggregate state columns. schema: SchemaRef, @@ -325,7 +326,7 @@ impl FinalSpillContext { .with_compression_type(context.session_config().spill_compression()); let mut final_agg = agg.clone(); - final_agg.input_order_mode = InputOrderMode::Sorted; + final_agg.group_clustering_mode = GroupClusteringMode::Full; Ok(Self { final_agg, @@ -378,7 +379,7 @@ impl FinalSpillContext { } /// Merges every sorted run, and do the aggregate evaluation with - /// [`OrderedFinalAggregateStream`] + /// [`ClusteredFinalAggregateStream`] fn into_replay_stream( self, baseline_metrics: &BaselineMetrics, @@ -409,12 +410,12 @@ impl FinalSpillContext { .with_batch_size(batch_size) .with_reservation(merge_reservation) .build()?; - let replay = OrderedFinalAggregateStream::new_with_input_and_metrics( + let replay = ClusteredFinalAggregateStream::new_with_input_and_metrics( &final_agg, &context, partition, merged, - &InputOrderMode::Sorted, + &GroupClusteringMode::Full, baseline_metrics.clone(), group_by_metrics, None, @@ -431,7 +432,7 @@ impl PartialHashAggregateStream { partition: usize, ) -> Result { debug_assert_eq!(agg.mode, super::AggregateMode::Partial); - debug_assert_eq!(agg.input_order_mode, InputOrderMode::Linear); + debug_assert_eq!(agg.group_clustering_mode, GroupClusteringMode::None); let schema = Arc::clone(&agg.schema); let input = agg.input.execute(partition, Arc::clone(context))?; @@ -1017,7 +1018,7 @@ impl FinalHashAggregateStream { agg.mode, super::AggregateMode::Final | super::AggregateMode::FinalPartitioned )); - debug_assert_eq!(agg.input_order_mode, InputOrderMode::Linear); + debug_assert_eq!(agg.group_clustering_mode, GroupClusteringMode::None); let schema = Arc::clone(&agg.schema); let input = agg.input.execute(partition, Arc::clone(context))?; diff --git a/datafusion/physical-plan/src/aggregates/mod.rs b/datafusion/physical-plan/src/aggregates/mod.rs index de709ff7e5fef..8ca40ec0016bf 100644 --- a/datafusion/physical-plan/src/aggregates/mod.rs +++ b/datafusion/physical-plan/src/aggregates/mod.rs @@ -59,7 +59,7 @@ //! AggregateExec (partial, ordered) //! ``` //! -//! See [`OrderedPartialAggregateStream`] and [`OrderedFinalAggregateStream`] for +//! See [`ClusteredPartialAggregateStream`] and [`ClusteredFinalAggregateStream`] for //! details. //! //! Related configuration: @@ -148,11 +148,11 @@ use std::sync::Arc; use super::{DisplayAs, ExecutionPlanProperties, PlanProperties}; use crate::aggregates::{ aggregate_stream::AggregateStream, + clustered_final_stream::ClusteredFinalAggregateStream, + clustered_partial_stream::ClusteredPartialAggregateStream, grouped_hash_stream::GroupedHashAggregateStream, grouped_topk_stream::GroupedTopKAggregateStream, hash_stream::{FinalHashAggregateStream, PartialHashAggregateStream}, - ordered_final_stream::OrderedFinalAggregateStream, - ordered_partial_stream::OrderedPartialAggregateStream, partial_reduce_stream::PartialReduceHashAggregateStream, single_stream::SingleHashAggregateStream, }; @@ -168,7 +168,7 @@ use crate::statistics::{ChildStats, StatisticsArgs}; use crate::{ChildrenPropertiesMode, ReplaceChildrenOptions, validate_child_count}; use crate::{ DisplayFormatType, Distribution, ExecutionPlan, InputDistributionRequirements, - InputOrderMode, SendableRecordBatchStream, Statistics, + SendableRecordBatchStream, Statistics, }; use datafusion_common::config::ConfigOptions; use parking_lot::Mutex; @@ -206,13 +206,14 @@ use topk::heap::is_supported_heap_type; mod aggregate_hash_table; mod aggregate_stream; +mod clustered_final_stream; +mod clustered_partial_stream; pub mod group_values; mod grouped_hash_stream; mod grouped_topk_stream; mod hash_stream; pub mod order; -mod ordered_final_stream; -mod ordered_partial_stream; +pub use order::GroupClusteringMode; mod partial_reduce_stream; mod single_stream; mod skip_partial; @@ -673,15 +674,15 @@ enum StreamType { /// Input output scheme: initial input -> final result SingleHash(SingleHashAggregateStream), /// Partial stage of aggregation for ordered input. - OrderedPartialAggregate(OrderedPartialAggregateStream), + ClusteredPartialAggregate(ClusteredPartialAggregateStream), /// Final stage of aggregation for ordered input. - OrderedFinalAggregate(OrderedFinalAggregateStream), + ClusteredFinalAggregate(ClusteredFinalAggregateStream), /// Hash aggregation reused for multiple stages /// /// Note this is being incrementally migrated to dedicated streams like /// [`StreamType::PartialHash`], [`StreamType::FinalHash`], - /// [`StreamType::OrderedPartialAggregate`], and - /// [`StreamType::OrderedFinalAggregate`] + /// [`StreamType::ClusteredPartialAggregate`], and + /// [`StreamType::ClusteredFinalAggregate`] /// /// See issue for details: GroupedHash(GroupedHashAggregateStream), @@ -701,8 +702,8 @@ impl From for SendableRecordBatchStream { StreamType::PartialReduceHash(stream) => Box::pin(stream), StreamType::FinalHash(stream) => Box::pin(stream), StreamType::SingleHash(stream) => Box::pin(stream), - StreamType::OrderedPartialAggregate(stream) => stream.into_stream(), - StreamType::OrderedFinalAggregate(stream) => Box::pin(stream), + StreamType::ClusteredPartialAggregate(stream) => stream.into_stream(), + StreamType::ClusteredFinalAggregate(stream) => Box::pin(stream), StreamType::GroupedHash(stream) => Box::pin(stream), StreamType::GroupedPriorityQueue(stream) => Box::pin(stream), } @@ -857,8 +858,8 @@ pub struct AggregateExec { /// Execution metrics metrics: ExecutionPlanMetricsSet, required_input_ordering: Option, - /// Describes how the input is ordered relative to the group by columns - input_order_mode: InputOrderMode, + /// Describes which group keys are contiguous within each input partition. + group_clustering_mode: GroupClusteringMode, cache: Arc, /// During initialization, if the plan supports dynamic filtering (see [`AggrDynFilter`]), /// it is set to `Some(..)` regardless of whether it can be pushed down to a child node. @@ -882,7 +883,7 @@ impl AggregateExec { // clone the rest of the fields required_input_ordering: self.required_input_ordering.clone(), metrics: ExecutionPlanMetricsSet::new(), - input_order_mode: self.input_order_mode.clone(), + group_clustering_mode: self.group_clustering_mode.clone(), cache: Arc::clone(&self.cache), mode: self.mode, group_by: Arc::clone(&self.group_by), @@ -902,7 +903,7 @@ impl AggregateExec { // clone the rest of the fields required_input_ordering: self.required_input_ordering.clone(), metrics: ExecutionPlanMetricsSet::new(), - input_order_mode: self.input_order_mode.clone(), + group_clustering_mode: self.group_clustering_mode.clone(), cache: Arc::clone(&self.cache), mode: self.mode, group_by: Arc::clone(&self.group_by), @@ -1008,15 +1009,15 @@ impl AggregateExec { .filter(|idx| group_by.groups.iter().all(|group| !group[*idx])) .collect(); - let input_order_mode = if indices.len() == groupby_exprs.len() + let group_clustering_mode = if indices.len() == groupby_exprs.len() && !indices.is_empty() && group_by.groups.len() == 1 { - InputOrderMode::Sorted + GroupClusteringMode::Full } else if !indices.is_empty() { - InputOrderMode::PartiallySorted(indices) + GroupClusteringMode::Partial(indices) } else { - InputOrderMode::Linear + GroupClusteringMode::None }; // construct a map from the input expression to the output expression of the Aggregation group by @@ -1029,7 +1030,7 @@ impl AggregateExec { &group_expr_mapping, group_by.is_true_no_grouping(), &mode, - &input_order_mode, + &group_clustering_mode, aggr_expr.as_ref(), )?; @@ -1044,7 +1045,7 @@ impl AggregateExec { metrics: ExecutionPlanMetricsSet::new(), required_input_ordering, limit_options: None, - input_order_mode, + group_clustering_mode, cache: Arc::new(cache), dynamic_filter: None, }; @@ -1203,9 +1204,9 @@ impl AggregateExec { .execution .enable_migration_aggregate { - if self.should_use_ordered_partial_aggregate_stream(context) { - return Ok(StreamType::OrderedPartialAggregate( - OrderedPartialAggregateStream::new(self, context, partition)?, + if self.should_use_clustered_partial_aggregate_stream(context) { + return Ok(StreamType::ClusteredPartialAggregate( + ClusteredPartialAggregateStream::new(self, context, partition)?, )); } @@ -1221,9 +1222,9 @@ impl AggregateExec { )); } - if self.should_use_ordered_final_aggregate_stream(context) { - return Ok(StreamType::OrderedFinalAggregate( - OrderedFinalAggregateStream::new(self, context, partition)?, + if self.should_use_clustered_final_aggregate_stream(context) { + return Ok(StreamType::ClusteredFinalAggregate( + ClusteredFinalAggregateStream::new(self, context, partition)?, )); } @@ -1248,18 +1249,18 @@ impl AggregateExec { fn should_use_partial_hash_stream(&self, _context: &TaskContext) -> bool { self.mode == AggregateMode::Partial - && self.input_order_mode == InputOrderMode::Linear + && self.group_clustering_mode == GroupClusteringMode::None && !self.group_by.is_true_no_grouping() && self.group_by.is_single() && self.limit_options_supported_by_hash_stream() } - fn should_use_ordered_partial_aggregate_stream( + fn should_use_clustered_partial_aggregate_stream( &self, _context: &TaskContext, ) -> bool { self.mode == AggregateMode::Partial - && self.input_order_mode != InputOrderMode::Linear + && self.group_clustering_mode != GroupClusteringMode::None && !self.group_by.is_true_no_grouping() && self.group_by.is_single() && self.limit_options_supported_by_hash_stream() @@ -1270,7 +1271,7 @@ impl AggregateExec { self.mode, AggregateMode::Final | AggregateMode::FinalPartitioned ) && self.limit_options_supported_by_hash_stream() - && self.input_order_mode == InputOrderMode::Linear + && self.group_clustering_mode == GroupClusteringMode::None && !self.group_by.is_true_no_grouping() && self.group_by.is_single() } @@ -1283,7 +1284,7 @@ impl AggregateExec { self.mode == AggregateMode::PartialReduce && self.limit_options.is_none() - && self.input_order_mode == InputOrderMode::Linear + && self.group_clustering_mode == GroupClusteringMode::None && !self.group_by.is_true_no_grouping() && self.group_by.is_single() } @@ -1293,17 +1294,20 @@ impl AggregateExec { self.mode, AggregateMode::Single | AggregateMode::SinglePartitioned ) && self.limit_options.is_none() - && self.input_order_mode == InputOrderMode::Linear + && self.group_clustering_mode == GroupClusteringMode::None && !self.group_by.is_true_no_grouping() && self.group_by.is_single() } - fn should_use_ordered_final_aggregate_stream(&self, _context: &TaskContext) -> bool { + fn should_use_clustered_final_aggregate_stream( + &self, + _context: &TaskContext, + ) -> bool { matches!( self.mode, AggregateMode::Final | AggregateMode::FinalPartitioned ) && self.limit_options_supported_by_hash_stream() - && self.input_order_mode != InputOrderMode::Linear + && self.group_clustering_mode != GroupClusteringMode::None && !self.group_by.is_true_no_grouping() && self.group_by.is_single() } @@ -1366,7 +1370,7 @@ impl AggregateExec { group_expr_mapping: &ProjectionMapping, is_true_no_grouping: bool, mode: &AggregateMode, - input_order_mode: &InputOrderMode, + group_clustering_mode: &GroupClusteringMode, aggr_exprs: &[Arc], ) -> Result { // Construct equivalence properties: @@ -1418,7 +1422,7 @@ impl AggregateExec { }; // TODO: Emission type and boundedness information can be enhanced here - let emission_type = if *input_order_mode == InputOrderMode::Linear { + let emission_type = if *group_clustering_mode == GroupClusteringMode::None { EmissionType::Final } else { input.pipeline_behavior() @@ -1432,8 +1436,8 @@ impl AggregateExec { )) } - pub fn input_order_mode(&self) -> &InputOrderMode { - &self.input_order_mode + pub fn group_clustering_mode(&self) -> &GroupClusteringMode { + &self.group_clustering_mode } /// Estimates output statistics for this aggregate node. @@ -1912,8 +1916,12 @@ impl DisplayAs for AggregateExec { write!(f, ", lim=[{}]", config.limit)?; } - if self.input_order_mode != InputOrderMode::Linear { - write!(f, ", ordering_mode={:?}", self.input_order_mode)?; + if self.group_clustering_mode != GroupClusteringMode::None { + write!( + f, + ", group_clustering_mode={:?}", + self.group_clustering_mode + )?; } } DisplayFormatType::TreeRender => { @@ -2037,12 +2045,11 @@ impl ExecutionPlan for AggregateExec { /// rules yet, overriding the default implementation ensures that it /// accurately reflects the actual behavior. /// - /// If the [`InputOrderMode`] is `Linear`, the `group_by` columns don't have - /// an ordering, which means the results do not either. However, in the - /// `Ordered` and `PartiallyOrdered` cases, the `group_by` columns do have - /// an ordering, which is preserved in the output. + /// Clustered execution preserves existing sort order on the grouping keys. + /// Clustering alone does not establish a sort order; output properties are + /// projected from the input's actual ordering in `compute_properties`. fn maintains_input_order(&self) -> Vec { - vec![self.input_order_mode != InputOrderMode::Linear] + vec![self.group_clustering_mode != GroupClusteringMode::None] } fn children(&self) -> Vec<&Arc> { @@ -2300,8 +2307,8 @@ impl ExecutionPlan for AggregateExec { metrics: _, // Derived at construction from the input ordering and `group_by`. required_input_ordering: _, - // Derived at construction from the input ordering and `group_by`. - input_order_mode: _, + // Derived at construction from the input properties and `group_by`. + group_clustering_mode: _, // Derived at construction by `Self::compute_properties`. cache: _, dynamic_filter, @@ -4296,6 +4303,115 @@ mod tests { Ok(()) } + #[test] + fn group_clustering_is_recomputed_with_new_children() -> Result<()> { + let aggregate = Arc::new(single_test_aggregate()?); + let original_input = Arc::clone(aggregate.input()); + let schema = original_input.schema(); + let ordering = + LexOrdering::new([PhysicalSortExpr::new_default(col("a", &schema)?)]) + .unwrap(); + let sorted_input = TestMemoryExec::try_new(&[vec![]], schema, None)? + .try_with_sort_information(vec![ordering.clone()])?; + let sorted_input = + Arc::new(TestMemoryExec::update_cache(&Arc::new(sorted_input))); + + let sorted = aggregate.replace_children( + vec![sorted_input], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + )?; + let sorted_aggregate = sorted.downcast_ref::().unwrap(); + assert_eq!( + sorted_aggregate.group_clustering_mode(), + &GroupClusteringMode::Full + ); + assert_eq!(sorted.output_ordering(), Some(&ordering)); + assert_eq!(sorted.pipeline_behavior(), EmissionType::Incremental); + + let unordered = sorted.replace_children( + vec![original_input], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + )?; + let unordered_aggregate = unordered.downcast_ref::().unwrap(); + assert_eq!( + unordered_aggregate.group_clustering_mode(), + &GroupClusteringMode::None + ); + assert_eq!(unordered.maintains_input_order(), vec![false]); + assert!(unordered.output_ordering().is_none()); + assert_eq!(unordered.pipeline_behavior(), EmissionType::Final); + Ok(()) + } + + #[rstest::rstest] + #[case::full(true)] + #[case::partial(false)] + fn group_clustering_preserves_sort_options( + #[case] full: bool, + #[values(AggregateMode::Partial, AggregateMode::Single)] mode: AggregateMode, + #[values(false, true)] descending: bool, + #[values(false, true)] nulls_first: bool, + ) -> Result<()> { + let schema = Arc::new(Schema::new(vec![ + Field::new("a", DataType::Int32, true), + Field::new("b", DataType::Int32, true), + Field::new("value", DataType::Int64, true), + ])); + let options = SortOptions::new(descending, nulls_first); + let mut input_ordering = vec![PhysicalSortExpr::new(col("a", &schema)?, options)]; + let mut output_ordering = vec![PhysicalSortExpr::new( + Arc::new(Column::new("group_a", 1)), + options, + )]; + if full { + input_ordering.push(PhysicalSortExpr::new(col("b", &schema)?, options)); + output_ordering.push(PhysicalSortExpr::new( + Arc::new(Column::new("group_b", 0)), + options, + )); + } + let input_ordering = LexOrdering::new(input_ordering).unwrap(); + let input = TestMemoryExec::try_new(&[vec![]], Arc::clone(&schema), None)? + .try_with_sort_information(vec![input_ordering.clone()])?; + let aggregate = AggregateExec::try_new( + mode, + PhysicalGroupBy::new_single(vec![ + (col("b", &schema)?, "group_b".to_string()), + (col("a", &schema)?, "group_a".to_string()), + ]), + vec![Arc::new( + AggregateExprBuilder::new(sum_udaf(), vec![col("value", &schema)?]) + .schema(Arc::clone(&schema)) + .alias("SUM(value)") + .build()?, + )], + vec![None], + Arc::new(TestMemoryExec::update_cache(&Arc::new(input))), + schema, + )?; + + let expected_mode = if full { + GroupClusteringMode::Full + } else { + GroupClusteringMode::Partial(vec![1]) + }; + assert_eq!(aggregate.group_clustering_mode(), &expected_mode); + assert_eq!(aggregate.maintains_input_order(), vec![true]); + assert_eq!( + aggregate.properties().emission_type, + EmissionType::Incremental + ); + assert_eq!( + aggregate.properties().output_ordering(), + LexOrdering::new(output_ordering).as_ref() + ); + assert_eq!( + aggregate.required_input_ordering(), + vec![Some(OrderingRequirements::new_soft(input_ordering.into()))] + ); + Ok(()) + } + fn partial_reduce_test_aggregate() -> Result { let schema = Arc::new(Schema::new(vec![ Field::new("a", DataType::UInt32, false), @@ -4441,7 +4557,10 @@ mod tests { schema, )?; - assert_eq!(aggregate.input_order_mode(), &InputOrderMode::Linear); + assert_eq!( + aggregate.group_clustering_mode(), + &GroupClusteringMode::None + ); // This captures the behavior before #24438. When the source can declare // `(key, time_bin)` group-contiguous, the corresponding case can use // `EmissionType::Incremental`. @@ -4466,7 +4585,7 @@ mod tests { Ok(()) } - /// Ensures for ordered input, `OrderedPartialAggregateStream` is used. + /// Ensures for ordered input, `ClusteredPartialAggregateStream` is used. #[tokio::test] async fn ordered_partial_aggregate_planning() -> Result<()> { let schema = Arc::new(Schema::new(vec![ @@ -4520,13 +4639,13 @@ mod tests { Arc::clone(&schema), )?; assert!(matches!( - aggregate.input_order_mode(), - InputOrderMode::PartiallySorted(_) + aggregate.group_clustering_mode(), + GroupClusteringMode::Partial(_) )); let task_ctx = new_migrated_hash_ctx(2); let stream = aggregate.execute_typed(0, &task_ctx)?; - assert!(matches!(stream, StreamType::OrderedPartialAggregate(_))); + assert!(matches!(stream, StreamType::ClusteredPartialAggregate(_))); let stream: SendableRecordBatchStream = stream.into(); let output = collect(stream).await?; @@ -4544,12 +4663,12 @@ mod tests { // Ordered partial aggregation supports finite memory. let finite_memory_task_ctx = new_finite_memory_migrated_hash_ctx(2, 1024 * 1024)?; let stream = aggregate.execute_typed(0, &finite_memory_task_ctx)?; - assert!(matches!(stream, StreamType::OrderedPartialAggregate(_))); + assert!(matches!(stream, StreamType::ClusteredPartialAggregate(_))); Ok(()) } - /// Ensures for ordered input, `OrderedFinalAggregateStream` is used. + /// Ensures for ordered input, `ClusteredFinalAggregateStream` is used. #[tokio::test] async fn ordered_final_aggregate_planning() -> Result<()> { let schema = Arc::new(Schema::new(vec![ @@ -4600,11 +4719,14 @@ mod tests { final_input, Arc::clone(&schema), )?; - assert_eq!(final_aggregate.input_order_mode(), &InputOrderMode::Sorted); + assert_eq!( + final_aggregate.group_clustering_mode(), + &GroupClusteringMode::Full + ); let task_ctx = new_migrated_hash_ctx(2); let stream = final_aggregate.execute_typed(0, &task_ctx)?; - assert!(matches!(stream, StreamType::OrderedFinalAggregate(_))); + assert!(matches!(stream, StreamType::ClusteredFinalAggregate(_))); let stream: SendableRecordBatchStream = stream.into(); let output = collect(stream).await?; @@ -4621,7 +4743,7 @@ mod tests { // Ordered final aggregation supports finite memory. let finite_memory_task_ctx = new_finite_memory_migrated_hash_ctx(2, 1024 * 1024)?; let stream = final_aggregate.execute_typed(0, &finite_memory_task_ctx)?; - assert!(matches!(stream, StreamType::OrderedFinalAggregate(_))); + assert!(matches!(stream, StreamType::ClusteredFinalAggregate(_))); Ok(()) } @@ -4673,8 +4795,8 @@ mod tests { Arc::clone(&schema), )?; assert!(matches!( - aggregate.input_order_mode(), - InputOrderMode::PartiallySorted(_) + aggregate.group_clustering_mode(), + GroupClusteringMode::Partial(_) )); let runtime = RuntimeEnvBuilder::default() @@ -4691,7 +4813,7 @@ mod tests { ); let mut stream: SendableRecordBatchStream = - OrderedPartialAggregateStream::new(&aggregate, &task_ctx, 0)?.into_stream(); + ClusteredPartialAggregateStream::new(&aggregate, &task_ctx, 0)?.into_stream(); while let Some(result) = stream.next().await { if let Err(e) = result { @@ -4972,7 +5094,7 @@ mod tests { // // "AggregateExec: mode=Final, gby=[a@0 as a], aggr=[FIRST_VALUE(b)]", // " CoalescePartitionsExec", - // " AggregateExec: mode=Partial, gby=[a@0 as a], aggr=[FIRST_VALUE(b)], ordering_mode=None", + // " AggregateExec: mode=Partial, gby=[a@0 as a], aggr=[FIRST_VALUE(b)]", // " DataSourceExec: partitions=4, partition_sizes=[1, 1, 1, 1]", // // and checks whether the function `merge_batch` works correctly for diff --git a/datafusion/physical-plan/src/aggregates/order/full.rs b/datafusion/physical-plan/src/aggregates/order/full.rs index ca818d6a2d598..11bed6e533f3f 100644 --- a/datafusion/physical-plan/src/aggregates/order/full.rs +++ b/datafusion/physical-plan/src/aggregates/order/full.rs @@ -18,10 +18,10 @@ use datafusion_expr::EmitTo; use std::mem::size_of; -/// Tracks grouping state when the data is ordered entirely by its -/// group keys +/// Tracks group completion when rows are contiguous for the complete +/// grouping tuple. /// -/// When the group values are sorted, as soon as we see group `n+1` we +/// When groups are contiguous, as soon as we see group `n+1` we /// know we will never see any rows for group `n` again and thus they /// can be emitted. /// @@ -55,7 +55,7 @@ use std::mem::size_of; /// `0..12` can be emitted. Note that `13` can not yet be emitted as /// there may be more values in the next batch with the same group_id. #[derive(Debug)] -pub struct GroupOrderingFull { +pub struct GroupClusteringFull { state: State, } @@ -72,7 +72,7 @@ enum State { Complete, } -impl GroupOrderingFull { +impl GroupClusteringFull { pub fn new() -> Self { Self { state: State::Start, @@ -115,13 +115,13 @@ impl GroupOrderingFull { self.state = State::Complete; } - /// Starts tracking a new fully ordered input segment. + /// Starts tracking a new input segment with contiguous groups. pub fn reset(&mut self) { self.state = State::Start; } /// Called when new groups are added in a batch. See documentation - /// on [`super::GroupOrdering::new_groups`] + /// on [`super::GroupClustering::new_groups`] pub fn new_groups(&mut self, total_num_groups: usize) { assert_ne!(total_num_groups, 0); @@ -149,7 +149,7 @@ impl GroupOrderingFull { } } -impl Default for GroupOrderingFull { +impl Default for GroupClusteringFull { fn default() -> Self { Self::new() } diff --git a/datafusion/physical-plan/src/aggregates/order/mod.rs b/datafusion/physical-plan/src/aggregates/order/mod.rs index 259411b00b697..ffd7b24ff283a 100644 --- a/datafusion/physical-plan/src/aggregates/order/mod.rs +++ b/datafusion/physical-plan/src/aggregates/order/mod.rs @@ -24,41 +24,76 @@ use datafusion_expr::EmitTo; mod full; mod partial; -use crate::InputOrderMode; -pub use full::GroupOrderingFull; -pub use partial::GroupOrderingPartial; +pub use full::GroupClusteringFull; +pub use partial::GroupClusteringPartial; + +/// Describes how rows are clustered by grouping expressions within each input +/// partition. +/// +/// Input ordering is one way to establish clustering. Aggregate execution uses +/// these guarantees to determine when groups are complete and can be emitted. +/// This mode does not describe the sort order of the input or output. +/// +/// For example, when grouping by `key`, both inputs have fully contiguous +/// groups within the input partition: +/// +/// ```text +/// sorted: A A B B C C +/// not sorted: C C A A B B +/// ``` +/// +/// In both cases, once the key changes, the previous key will not appear again, +/// so its group is complete and can be emitted. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum GroupClusteringMode { + /// No clustering guarantee is available to complete groups before the input ends. + None, + /// Rows with the same values at these grouping-expression indices form one + /// contiguous range. When those values change, every group in the previous + /// range is complete and can be emitted. + /// + /// For example, with `GROUP BY (a, b)`, `Partial(vec![0])` means all rows + /// for each value of `a` are contiguous, while an `(a, b)` tuple may recur + /// within that range. + Partial(Vec), + /// Rows with the same complete grouping tuple form one contiguous range. + /// When the tuple changes, the previous group can be emitted. + Full, +} -/// Ordering information for each group in the hash table +/// Tracks when groups in the hash table are complete and can be emitted. #[derive(Debug)] -pub enum GroupOrdering { - /// Groups are not ordered +pub enum GroupClustering { + /// No guarantee identifies groups as complete before the input ends. None, - /// Groups are ordered by some pre-set of the group keys - Partial(GroupOrderingPartial), - /// Groups are entirely contiguous, - Full(GroupOrderingFull), + /// A subset of the group keys identifies contiguous ranges. + Partial(GroupClusteringPartial), + /// Each complete group occupies one contiguous range. + Full(GroupClusteringFull), } -impl GroupOrdering { - /// Create a `GroupOrdering` for the specified ordering - pub fn try_new(mode: &InputOrderMode) -> Result { +impl GroupClustering { + /// Create a tracker for the input's group-clustering guarantee. + pub fn try_new(mode: &GroupClusteringMode) -> Result { match mode { - InputOrderMode::Linear => Ok(GroupOrdering::None), - InputOrderMode::PartiallySorted(order_indices) => { - GroupOrderingPartial::try_new(order_indices.clone()) - .map(GroupOrdering::Partial) + GroupClusteringMode::None => Ok(GroupClustering::None), + GroupClusteringMode::Partial(order_indices) => { + GroupClusteringPartial::try_new(order_indices.clone()) + .map(GroupClustering::Partial) + } + GroupClusteringMode::Full => { + Ok(GroupClustering::Full(GroupClusteringFull::new())) } - InputOrderMode::Sorted => Ok(GroupOrdering::Full(GroupOrderingFull::new())), } } /// Returns how many groups can be emitted while respecting the current - /// ordering guarantees, or `None` if no data can be emitted. + /// clustering guarantees, or `None` if no data can be emitted. pub fn emit_to(&self) -> Option { match self { - GroupOrdering::None => None, - GroupOrdering::Partial(partial) => partial.emit_to(), - GroupOrdering::Full(full) => full.emit_to(), + GroupClustering::None => None, + GroupClustering::Partial(partial) => partial.emit_to(), + GroupClustering::Full(full) => full.emit_to(), } } @@ -74,8 +109,8 @@ impl GroupOrdering { } match self { - GroupOrdering::None => Some(EmitTo::First(n)), - GroupOrdering::Partial(_) | GroupOrdering::Full(_) => { + GroupClustering::None => Some(EmitTo::First(n)), + GroupClustering::Partial(_) | GroupClustering::Full(_) => { self.emit_to().map(|emit_to| match emit_to { EmitTo::First(max) => EmitTo::First(n.min(max)), EmitTo::All => EmitTo::First(n), @@ -87,9 +122,9 @@ impl GroupOrdering { /// Updates the state to indicate that the input is complete. pub fn input_done(&mut self) { match self { - GroupOrdering::None => {} - GroupOrdering::Partial(partial) => partial.input_done(), - GroupOrdering::Full(full) => full.input_done(), + GroupClustering::None => {} + GroupClustering::Partial(partial) => partial.input_done(), + GroupClustering::Full(full) => full.input_done(), } } @@ -101,9 +136,9 @@ impl GroupOrdering { /// input batch from a fresh ordering state. pub fn reset(&mut self) { match self { - GroupOrdering::None => {} - GroupOrdering::Partial(partial) => partial.reset(), - GroupOrdering::Full(full) => full.reset(), + GroupClustering::None => {} + GroupClustering::Partial(partial) => partial.reset(), + GroupClustering::Full(full) => full.reset(), } } @@ -111,9 +146,9 @@ impl GroupOrdering { /// existing indexes down by `n`. pub fn remove_groups(&mut self, n: usize) { match self { - GroupOrdering::None => {} - GroupOrdering::Partial(partial) => partial.remove_groups(n), - GroupOrdering::Full(full) => full.remove_groups(n), + GroupClustering::None => {} + GroupClustering::Partial(partial) => partial.remove_groups(n), + GroupClustering::Full(full) => full.remove_groups(n), } } @@ -132,15 +167,15 @@ impl GroupOrdering { total_num_groups: usize, ) -> Result<()> { match self { - GroupOrdering::None => {} - GroupOrdering::Partial(partial) => { + GroupClustering::None => {} + GroupClustering::Partial(partial) => { partial.new_groups( batch_group_values, group_indices, total_num_groups, )?; } - GroupOrdering::Full(full) => { + GroupClustering::Full(full) => { full.new_groups(total_num_groups); } }; @@ -151,9 +186,9 @@ impl GroupOrdering { pub fn size(&self) -> usize { size_of::() + match self { - GroupOrdering::None => 0, - GroupOrdering::Partial(partial) => partial.size(), - GroupOrdering::Full(full) => full.size(), + GroupClustering::None => 0, + GroupClustering::Partial(partial) => partial.size(), + GroupClustering::Full(full) => full.size(), } } } @@ -168,10 +203,10 @@ mod tests { #[test] fn test_oom_emit_to_none_ordering() { - let group_ordering = GroupOrdering::None; + let group_clustering = GroupClustering::None; - assert_eq!(group_ordering.oom_emit_to(0), None); - assert_eq!(group_ordering.oom_emit_to(5), Some(EmitTo::First(5))); + assert_eq!(group_clustering.oom_emit_to(0), None); + assert_eq!(group_clustering.oom_emit_to(5), Some(EmitTo::First(5))); } /// Creates a partially ordered grouping state with three groups. @@ -179,9 +214,9 @@ mod tests { /// `sort_key_values` controls whether a sort boundary exists in the batch: /// distinct values such as `[1, 2, 3]` create boundaries, while repeated /// values such as `[1, 1, 1]` do not. - fn partial_ordering(sort_key_values: Vec) -> Result { - let mut group_ordering = - GroupOrdering::Partial(GroupOrderingPartial::try_new(vec![0])?); + fn partial_ordering(sort_key_values: Vec) -> Result { + let mut group_clustering = + GroupClustering::Partial(GroupClusteringPartial::try_new(vec![0])?); let batch_group_values: Vec = vec![ Arc::new(Int32Array::from(sort_key_values)), @@ -189,30 +224,30 @@ mod tests { ]; let group_indices = vec![0, 1, 2]; - group_ordering.new_groups(&batch_group_values, &group_indices, 3)?; + group_clustering.new_groups(&batch_group_values, &group_indices, 3)?; - Ok(group_ordering) + Ok(group_clustering) } #[test] fn test_oom_emit_to_partial_clamps_to_boundary() -> Result<()> { - let group_ordering = partial_ordering(vec![1, 2, 3])?; + let group_clustering = partial_ordering(vec![1, 2, 3])?; // Can emit both `1` and `2` groups because we have seen `3` - assert_eq!(group_ordering.emit_to(), Some(EmitTo::First(2))); - assert_eq!(group_ordering.oom_emit_to(1), Some(EmitTo::First(1))); - assert_eq!(group_ordering.oom_emit_to(3), Some(EmitTo::First(2))); + assert_eq!(group_clustering.emit_to(), Some(EmitTo::First(2))); + assert_eq!(group_clustering.oom_emit_to(1), Some(EmitTo::First(1))); + assert_eq!(group_clustering.oom_emit_to(3), Some(EmitTo::First(2))); Ok(()) } #[test] fn test_oom_emit_to_partial_without_boundary() -> Result<()> { - let group_ordering = partial_ordering(vec![1, 1, 1])?; + let group_clustering = partial_ordering(vec![1, 1, 1])?; // Can't emit the last `1` group as it may have more values - assert_eq!(group_ordering.emit_to(), None); - assert_eq!(group_ordering.oom_emit_to(3), None); + assert_eq!(group_clustering.emit_to(), None); + assert_eq!(group_clustering.oom_emit_to(3), None); Ok(()) } diff --git a/datafusion/physical-plan/src/aggregates/order/partial.rs b/datafusion/physical-plan/src/aggregates/order/partial.rs index 1603bb6d079be..9bd128be90991 100644 --- a/datafusion/physical-plan/src/aggregates/order/partial.rs +++ b/datafusion/physical-plan/src/aggregates/order/partial.rs @@ -63,7 +63,7 @@ use datafusion_expr::EmitTo; /// order) recent group index /// ``` #[derive(Debug)] -pub struct GroupOrderingPartial { +pub struct GroupClusteringPartial { /// State machine state: State, @@ -115,7 +115,7 @@ impl State { } } -impl GroupOrderingPartial { +impl GroupClusteringPartial { /// TODO: Remove unnecessary `input_schema` parameter. pub fn try_new(order_indices: Vec) -> Result { debug_assert!(!order_indices.is_empty()); @@ -210,7 +210,7 @@ impl GroupOrderingPartial { } /// Called when new groups are added in a batch. See documentation - /// on [`super::GroupOrdering::new_groups`] + /// on [`super::GroupClustering::new_groups`] pub fn new_groups( &mut self, batch_group_values: &[ArrayRef], @@ -280,10 +280,10 @@ mod tests { use arrow::array::Int32Array; #[test] - fn test_group_ordering_partial() -> Result<()> { + fn test_group_clustering_partial() -> Result<()> { // Ordered on column a let order_indices = vec![0]; - let mut group_ordering = GroupOrderingPartial::try_new(order_indices)?; + let mut group_clustering = GroupClusteringPartial::try_new(order_indices)?; let batch_group_values: Vec = vec![ Arc::new(Int32Array::from(vec![1, 2, 3])), @@ -293,14 +293,14 @@ mod tests { let group_indices = vec![0, 1, 2]; let total_num_groups = 3; - group_ordering.new_groups( + group_clustering.new_groups( &batch_group_values, &group_indices, total_num_groups, )?; assert_eq!( - group_ordering.state, + group_clustering.state, State::InProgress { current_sort: 2, sort_key: vec![ScalarValue::Int32(Some(3))], @@ -316,14 +316,14 @@ mod tests { let group_indices = vec![3, 4, 5]; let total_num_groups = 6; - group_ordering.new_groups( + group_clustering.new_groups( &batch_group_values, &group_indices, total_num_groups, )?; assert_eq!( - group_ordering.state, + group_clustering.state, State::InProgress { current_sort: 2, sort_key: vec![ScalarValue::Int32(Some(3))], @@ -339,13 +339,13 @@ mod tests { let group_indices = vec![6, 7, 8]; let total_num_groups = 9; - group_ordering.new_groups( + group_clustering.new_groups( &batch_group_values, &group_indices, total_num_groups, )?; assert_eq!( - group_ordering.state, + group_clustering.state, State::InProgress { current_sort: 6, sort_key: vec![ScalarValue::Int32(Some(4))], diff --git a/datafusion/physical-plan/src/aggregates/partial_reduce_stream.rs b/datafusion/physical-plan/src/aggregates/partial_reduce_stream.rs index 2f4535e66f4ef..247ca0d151f21 100644 --- a/datafusion/physical-plan/src/aggregates/partial_reduce_stream.rs +++ b/datafusion/physical-plan/src/aggregates/partial_reduce_stream.rs @@ -35,9 +35,10 @@ use futures::stream::{Stream, StreamExt}; use super::AggregateExec; use super::aggregate_hash_table::{AggregateHashTable, PartialReduceMarker}; +use crate::aggregates::GroupClusteringMode; use crate::metrics::{BaselineMetrics, RecordOutput, SpillMetrics}; use crate::stream::EmptyRecordBatchStream; -use crate::{InputOrderMode, RecordBatchStream, SendableRecordBatchStream}; +use crate::{RecordBatchStream, SendableRecordBatchStream}; /// Hash aggregation can combine multiple partial stages before final /// evaluation. This stream implements the partial-reduce stage. @@ -154,7 +155,7 @@ impl PartialReduceHashAggregateStream { partition: usize, ) -> Result { debug_assert_eq!(agg.mode, super::AggregateMode::PartialReduce); - debug_assert_eq!(agg.input_order_mode, InputOrderMode::Linear); + debug_assert_eq!(agg.group_clustering_mode, GroupClusteringMode::None); let schema = Arc::clone(&agg.schema); let input = agg.input.execute(partition, Arc::clone(context))?; diff --git a/datafusion/physical-plan/src/aggregates/single_stream.rs b/datafusion/physical-plan/src/aggregates/single_stream.rs index c6f25dc2cf28b..854166636c663 100644 --- a/datafusion/physical-plan/src/aggregates/single_stream.rs +++ b/datafusion/physical-plan/src/aggregates/single_stream.rs @@ -37,16 +37,17 @@ use datafusion_physical_expr_common::sort_expr::LexOrdering; use futures::stream::{Stream, StreamExt}; use super::aggregate_hash_table::{AggregateHashTable, SingleMarker}; +use super::clustered_final_stream::ClusteredFinalAggregateStream; use super::group_values::GroupByMetrics; -use super::ordered_final_stream::OrderedFinalAggregateStream; use super::{AggregateExec, create_schema}; use crate::aggregates::AggregateMode; +use crate::aggregates::GroupClusteringMode; use crate::metrics::{BaselineMetrics, RecordOutput, SpillMetrics}; use crate::sorts::IncrementalSortIterator; use crate::sorts::streaming_merge::{SortedSpillFile, StreamingMergeBuilder}; use crate::spill::spill_manager::SpillManager; use crate::stream::EmptyRecordBatchStream; -use crate::{InputOrderMode, RecordBatchStream, SendableRecordBatchStream}; +use crate::{RecordBatchStream, SendableRecordBatchStream}; /// Hash aggregation can run the full logical aggregation in one operator. This /// stream implements the single stage for grouped hash aggregation. @@ -83,7 +84,7 @@ use crate::{InputOrderMode, RecordBatchStream, SendableRecordBatchStream}; /// 3. Perform a sort-preserving merge of all spill files and feed the merged output /// into an ordered streaming aggregation, which ensures bounded memory usage and /// evaluates the final result. -/// - [`OrderedFinalAggregateStream`] is reused for the streaming aggregation. +/// - [`ClusteredFinalAggregateStream`] is reused for the streaming aggregation. pub(crate) struct SingleHashAggregateStream { /// Output schema: group columns followed by final aggregate value columns. schema: SchemaRef, @@ -115,7 +116,7 @@ struct SingleSpillContext { /// and column-based group expressions rather than evaluating the raw input /// expressions a second time. After the spill files are merged into ordered /// input, this configuration is used to construct an - /// [`OrderedFinalAggregateStream`], and perform the final evaluation step. + /// [`ClusteredFinalAggregateStream`], and perform the final evaluation step. final_agg: AggregateExec, /// Task context. context: Arc, @@ -210,7 +211,7 @@ impl SingleSpillContext { } }; final_agg.group_by = Arc::new(agg.group_by.as_final()); - final_agg.input_order_mode = InputOrderMode::Sorted; + final_agg.group_clustering_mode = GroupClusteringMode::Full; Ok(Self { final_agg, @@ -263,7 +264,7 @@ impl SingleSpillContext { } /// Merges every sorted run, and do the aggregate evaluation with - /// [`OrderedFinalAggregateStream`] + /// [`ClusteredFinalAggregateStream`] fn into_replay_stream( self, baseline_metrics: &BaselineMetrics, @@ -294,12 +295,12 @@ impl SingleSpillContext { .with_batch_size(batch_size) .with_reservation(merge_reservation) .build()?; - let replay = OrderedFinalAggregateStream::new_with_input_and_metrics( + let replay = ClusteredFinalAggregateStream::new_with_input_and_metrics( &final_agg, &context, partition, merged, - &InputOrderMode::Sorted, + &GroupClusteringMode::Full, baseline_metrics.clone(), group_by_metrics, None, @@ -319,7 +320,7 @@ impl SingleHashAggregateStream { agg.mode, AggregateMode::Single | AggregateMode::SinglePartitioned )); - debug_assert_eq!(agg.input_order_mode, InputOrderMode::Linear); + debug_assert_eq!(agg.group_clustering_mode, GroupClusteringMode::None); let schema = Arc::clone(&agg.schema); let input = agg.input.execute(partition, Arc::clone(context))?; diff --git a/datafusion/physical-plan/src/recursive_query.rs b/datafusion/physical-plan/src/recursive_query.rs index 0a56488de84dd..494887f9068ef 100644 --- a/datafusion/physical-plan/src/recursive_query.rs +++ b/datafusion/physical-plan/src/recursive_query.rs @@ -23,7 +23,7 @@ use std::task::{Context, Poll}; use super::work_table::{ReservedBatches, WorkTable}; use crate::aggregates::group_values::{GroupValues, new_group_values}; -use crate::aggregates::order::GroupOrdering; +use crate::aggregates::order::GroupClustering; use crate::common::project_plan_to_schema; use crate::execution_plan::{Boundedness, EmissionType, reset_plan_states}; use crate::metrics::{ @@ -464,7 +464,7 @@ struct DistinctDeduplicator { impl DistinctDeduplicator { fn new(schema: SchemaRef, task_context: &TaskContext) -> Result { - let group_values = new_group_values(schema, &GroupOrdering::None)?; + let group_values = new_group_values(schema, &GroupClustering::None)?; let reservation = MemoryConsumer::new("RecursiveQueryHashTable") .register(task_context.memory_pool()); Ok(Self { diff --git a/datafusion/sqllogictest/test_files/agg_func_substitute.slt b/datafusion/sqllogictest/test_files/agg_func_substitute.slt index dd89e83492f6b..3e10271dd51d9 100644 --- a/datafusion/sqllogictest/test_files/agg_func_substitute.slt +++ b/datafusion/sqllogictest/test_files/agg_func_substitute.slt @@ -44,9 +44,9 @@ logical_plan 03)----TableScan: multiple_ordered_table projection=[a, c] physical_plan 01)ProjectionExec: expr=[a@0 as a, nth_value(multiple_ordered_table.c,Int64(1)) ORDER BY [multiple_ordered_table.c ASC NULLS LAST]@1 as result] -02)--AggregateExec: mode=FinalPartitioned, gby=[a@0 as a], aggr=[nth_value(multiple_ordered_table.c,Int64(1)) ORDER BY [multiple_ordered_table.c ASC NULLS LAST]], ordering_mode=Sorted +02)--AggregateExec: mode=FinalPartitioned, gby=[a@0 as a], aggr=[nth_value(multiple_ordered_table.c,Int64(1)) ORDER BY [multiple_ordered_table.c ASC NULLS LAST]], group_clustering_mode=Full 03)----RepartitionExec: partitioning=Hash([a@0], 4), input_partitions=4, preserve_order=true, sort_exprs=a@0 ASC NULLS LAST -04)------AggregateExec: mode=Partial, gby=[a@0 as a], aggr=[nth_value(multiple_ordered_table.c,Int64(1)) ORDER BY [multiple_ordered_table.c ASC NULLS LAST]], ordering_mode=Sorted +04)------AggregateExec: mode=Partial, gby=[a@0 as a], aggr=[nth_value(multiple_ordered_table.c,Int64(1)) ORDER BY [multiple_ordered_table.c ASC NULLS LAST]], group_clustering_mode=Full 05)--------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true 06)----------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[a, c], output_orderings=[[a@0 ASC NULLS LAST], [c@1 ASC NULLS LAST]], file_type=csv, has_header=true @@ -62,9 +62,9 @@ logical_plan 03)----TableScan: multiple_ordered_table projection=[a, c] physical_plan 01)ProjectionExec: expr=[a@0 as a, nth_value(multiple_ordered_table.c,Int64(1)) ORDER BY [multiple_ordered_table.c ASC NULLS LAST]@1 as result] -02)--AggregateExec: mode=FinalPartitioned, gby=[a@0 as a], aggr=[nth_value(multiple_ordered_table.c,Int64(1)) ORDER BY [multiple_ordered_table.c ASC NULLS LAST]], ordering_mode=Sorted +02)--AggregateExec: mode=FinalPartitioned, gby=[a@0 as a], aggr=[nth_value(multiple_ordered_table.c,Int64(1)) ORDER BY [multiple_ordered_table.c ASC NULLS LAST]], group_clustering_mode=Full 03)----RepartitionExec: partitioning=Hash([a@0], 4), input_partitions=4, preserve_order=true, sort_exprs=a@0 ASC NULLS LAST -04)------AggregateExec: mode=Partial, gby=[a@0 as a], aggr=[nth_value(multiple_ordered_table.c,Int64(1)) ORDER BY [multiple_ordered_table.c ASC NULLS LAST]], ordering_mode=Sorted +04)------AggregateExec: mode=Partial, gby=[a@0 as a], aggr=[nth_value(multiple_ordered_table.c,Int64(1)) ORDER BY [multiple_ordered_table.c ASC NULLS LAST]], group_clustering_mode=Full 05)--------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true 06)----------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[a, c], output_orderings=[[a@0 ASC NULLS LAST], [c@1 ASC NULLS LAST]], file_type=csv, has_header=true @@ -79,9 +79,9 @@ logical_plan 03)----TableScan: multiple_ordered_table projection=[a, c] physical_plan 01)ProjectionExec: expr=[a@0 as a, nth_value(multiple_ordered_table.c,Int64(1) + Int64(100)) ORDER BY [multiple_ordered_table.c ASC NULLS LAST]@1 as result] -02)--AggregateExec: mode=FinalPartitioned, gby=[a@0 as a], aggr=[nth_value(multiple_ordered_table.c, 101) ORDER BY [multiple_ordered_table.c ASC NULLS LAST] as nth_value(multiple_ordered_table.c,Int64(1) + Int64(100)) ORDER BY [multiple_ordered_table.c ASC NULLS LAST]], ordering_mode=Sorted +02)--AggregateExec: mode=FinalPartitioned, gby=[a@0 as a], aggr=[nth_value(multiple_ordered_table.c, 101) ORDER BY [multiple_ordered_table.c ASC NULLS LAST] as nth_value(multiple_ordered_table.c,Int64(1) + Int64(100)) ORDER BY [multiple_ordered_table.c ASC NULLS LAST]], group_clustering_mode=Full 03)----RepartitionExec: partitioning=Hash([a@0], 4), input_partitions=4, preserve_order=true, sort_exprs=a@0 ASC NULLS LAST -04)------AggregateExec: mode=Partial, gby=[a@0 as a], aggr=[nth_value(multiple_ordered_table.c, 101) ORDER BY [multiple_ordered_table.c ASC NULLS LAST] as nth_value(multiple_ordered_table.c,Int64(1) + Int64(100)) ORDER BY [multiple_ordered_table.c ASC NULLS LAST]], ordering_mode=Sorted +04)------AggregateExec: mode=Partial, gby=[a@0 as a], aggr=[nth_value(multiple_ordered_table.c, 101) ORDER BY [multiple_ordered_table.c ASC NULLS LAST] as nth_value(multiple_ordered_table.c,Int64(1) + Int64(100)) ORDER BY [multiple_ordered_table.c ASC NULLS LAST]], group_clustering_mode=Full 05)--------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true 06)----------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[a, c], output_orderings=[[a@0 ASC NULLS LAST], [c@1 ASC NULLS LAST]], file_type=csv, has_header=true diff --git a/datafusion/sqllogictest/test_files/aggregate.slt b/datafusion/sqllogictest/test_files/aggregate.slt index 067059c804d02..639aee9a25780 100644 --- a/datafusion/sqllogictest/test_files/aggregate.slt +++ b/datafusion/sqllogictest/test_files/aggregate.slt @@ -8577,9 +8577,9 @@ logical_plan 15)------------EmptyRelation: rows=1 physical_plan 01)ProjectionExec: expr=[last_value(a.foo) ORDER BY [a.foo ASC NULLS LAST]@1 as last_value(a.foo) ORDER BY [a.foo ASC NULLS LAST], sum(DISTINCT Int64(1))@2 as sum(DISTINCT Int64(1))] -02)--AggregateExec: mode=FinalPartitioned, gby=[id@0 as id], aggr=[last_value(a.foo) ORDER BY [a.foo ASC NULLS LAST], sum(DISTINCT Int64(1))], ordering_mode=Sorted +02)--AggregateExec: mode=FinalPartitioned, gby=[id@0 as id], aggr=[last_value(a.foo) ORDER BY [a.foo ASC NULLS LAST], sum(DISTINCT Int64(1))], group_clustering_mode=Full 03)----RepartitionExec: partitioning=Hash([id@0], 4), input_partitions=5 -04)------AggregateExec: mode=Partial, gby=[id@0 as id], aggr=[last_value(a.foo) ORDER BY [a.foo ASC NULLS LAST], sum(DISTINCT Int64(1))], ordering_mode=Sorted +04)------AggregateExec: mode=Partial, gby=[id@0 as id], aggr=[last_value(a.foo) ORDER BY [a.foo ASC NULLS LAST], sum(DISTINCT Int64(1))], group_clustering_mode=Full 05)--------UnionExec 06)----------ProjectionExec: expr=[1 as id, 2 as foo] 07)------------PlaceholderRowExec @@ -9245,7 +9245,7 @@ CREATE TABLE stream_test ( (3, 1.0, 1.0, 7, false, 'e'), (3, 2.0, 2.0, 8, false, 'f'); # Test comprehensive aggregates with streaming -# This verifies that CORR and other aggregates work together in a streaming plan (ordering_mode=Sorted) +# This verifies that CORR and other aggregates work together in a streaming plan (group_clustering_mode=Full) # Basic Aggregates query TT @@ -9284,7 +9284,7 @@ logical_plan 05)--------TableScan: stream_test projection=[g, x, y, i, b] physical_plan 01)ProjectionExec: expr=[g@0 as g, count(Int64(1))@1 as count(*), sum(stream_test.x)@2 as sum(stream_test.x), avg(stream_test.x)@3 as avg(stream_test.x), avg(stream_test.x)@3 as mean(stream_test.x), min(stream_test.x)@4 as min(stream_test.x), max(stream_test.y)@5 as max(stream_test.y), bit_and(stream_test.i)@6 as bit_and(stream_test.i), bit_or(stream_test.i)@7 as bit_or(stream_test.i), bit_xor(stream_test.i)@8 as bit_xor(stream_test.i), bool_and(stream_test.b)@9 as bool_and(stream_test.b), bool_or(stream_test.b)@10 as bool_or(stream_test.b), median(stream_test.x)@11 as median(stream_test.x), 0 as grouping(stream_test.g), var(stream_test.x)@12 as var(stream_test.x), var(stream_test.x)@12 as var_samp(stream_test.x), var_pop(stream_test.x)@13 as var_pop(stream_test.x), var(stream_test.x)@12 as var_sample(stream_test.x), var_pop(stream_test.x)@13 as var_population(stream_test.x), stddev(stream_test.x)@14 as stddev(stream_test.x), stddev(stream_test.x)@14 as stddev_samp(stream_test.x), stddev_pop(stream_test.x)@15 as stddev_pop(stream_test.x)] -02)--AggregateExec: mode=Single, gby=[g@0 as g], aggr=[count(Int64(1)), sum(stream_test.x), avg(stream_test.x), min(stream_test.x), max(stream_test.y), bit_and(stream_test.i), bit_or(stream_test.i), bit_xor(stream_test.i), bool_and(stream_test.b), bool_or(stream_test.b), median(stream_test.x), var(stream_test.x), var_pop(stream_test.x), stddev(stream_test.x), stddev_pop(stream_test.x)], ordering_mode=Sorted +02)--AggregateExec: mode=Single, gby=[g@0 as g], aggr=[count(Int64(1)), sum(stream_test.x), avg(stream_test.x), min(stream_test.x), max(stream_test.y), bit_and(stream_test.i), bit_or(stream_test.i), bit_xor(stream_test.i), bool_and(stream_test.b), bool_or(stream_test.b), median(stream_test.x), var(stream_test.x), var_pop(stream_test.x), stddev(stream_test.x), stddev_pop(stream_test.x)], group_clustering_mode=Full 03)----SortExec: TopK(fetch=10000), expr=[g@0 ASC NULLS LAST], preserve_partitioning=[false] 04)------DataSourceExec: partitions=1, partition_sizes=[1] @@ -9339,7 +9339,7 @@ logical_plan 03)----Sort: stream_test.g ASC NULLS LAST, fetch=10000 04)------TableScan: stream_test projection=[g, x] physical_plan -01)AggregateExec: mode=Single, gby=[g@0 as g], aggr=[array_agg(stream_test.x) ORDER BY [stream_test.x ASC NULLS LAST], array_agg(DISTINCT stream_test.x) ORDER BY [stream_test.x ASC NULLS LAST], first_value(stream_test.x) ORDER BY [stream_test.x ASC NULLS LAST], last_value(stream_test.x) ORDER BY [stream_test.x ASC NULLS LAST], nth_value(stream_test.x,Int64(1)) ORDER BY [stream_test.x ASC NULLS LAST]], ordering_mode=Sorted +01)AggregateExec: mode=Single, gby=[g@0 as g], aggr=[array_agg(stream_test.x) ORDER BY [stream_test.x ASC NULLS LAST], array_agg(DISTINCT stream_test.x) ORDER BY [stream_test.x ASC NULLS LAST], first_value(stream_test.x) ORDER BY [stream_test.x ASC NULLS LAST], last_value(stream_test.x) ORDER BY [stream_test.x ASC NULLS LAST], nth_value(stream_test.x,Int64(1)) ORDER BY [stream_test.x ASC NULLS LAST]], group_clustering_mode=Full 02)--SortExec: TopK(fetch=10000), expr=[g@0 ASC NULLS LAST, x@1 ASC NULLS LAST], preserve_partitioning=[false] 03)----DataSourceExec: partitions=1, partition_sizes=[1] @@ -9376,7 +9376,7 @@ logical_plan 03)----Sort: stream_test.g ASC NULLS LAST, fetch=10000 04)------TableScan: stream_test projection=[g, s] physical_plan -01)AggregateExec: mode=Single, gby=[g@0 as g], aggr=[array_agg(stream_test.s) ORDER BY [stream_test.s ASC NULLS LAST], string_agg(stream_test.s,Utf8("|")) ORDER BY [stream_test.s ASC NULLS LAST], string_agg(DISTINCT stream_test.s,Utf8("|")) ORDER BY [stream_test.s ASC NULLS LAST]], ordering_mode=Sorted +01)AggregateExec: mode=Single, gby=[g@0 as g], aggr=[array_agg(stream_test.s) ORDER BY [stream_test.s ASC NULLS LAST], string_agg(stream_test.s,Utf8("|")) ORDER BY [stream_test.s ASC NULLS LAST], string_agg(DISTINCT stream_test.s,Utf8("|")) ORDER BY [stream_test.s ASC NULLS LAST]], group_clustering_mode=Full 02)--SortExec: TopK(fetch=10000), expr=[g@0 ASC NULLS LAST, s@1 ASC NULLS LAST], preserve_partitioning=[false] 03)----DataSourceExec: partitions=1, partition_sizes=[1] @@ -9423,7 +9423,7 @@ logical_plan 05)--------TableScan: stream_test projection=[g, x, y] physical_plan 01)ProjectionExec: expr=[g@0 as g, corr(stream_test.x,stream_test.y)@1 as corr(stream_test.x,stream_test.y), covar_samp(stream_test.x,stream_test.y)@2 as covar(stream_test.x,stream_test.y), covar_samp(stream_test.x,stream_test.y)@2 as covar_samp(stream_test.x,stream_test.y), covar_pop(stream_test.x,stream_test.y)@3 as covar_pop(stream_test.x,stream_test.y), regr_sxx(stream_test.x,stream_test.y)@4 as regr_sxx(stream_test.x,stream_test.y), regr_sxy(stream_test.x,stream_test.y)@5 as regr_sxy(stream_test.x,stream_test.y), regr_syy(stream_test.x,stream_test.y)@6 as regr_syy(stream_test.x,stream_test.y), regr_avgx(stream_test.x,stream_test.y)@7 as regr_avgx(stream_test.x,stream_test.y), regr_avgy(stream_test.x,stream_test.y)@8 as regr_avgy(stream_test.x,stream_test.y), regr_count(stream_test.x,stream_test.y)@9 as regr_count(stream_test.x,stream_test.y), regr_slope(stream_test.x,stream_test.y)@10 as regr_slope(stream_test.x,stream_test.y), regr_intercept(stream_test.x,stream_test.y)@11 as regr_intercept(stream_test.x,stream_test.y), regr_r2(stream_test.x,stream_test.y)@12 as regr_r2(stream_test.x,stream_test.y)] -02)--AggregateExec: mode=Single, gby=[g@0 as g], aggr=[corr(stream_test.x,stream_test.y), covar_samp(stream_test.x,stream_test.y), covar_pop(stream_test.x,stream_test.y), regr_sxx(stream_test.x,stream_test.y), regr_sxy(stream_test.x,stream_test.y), regr_syy(stream_test.x,stream_test.y), regr_avgx(stream_test.x,stream_test.y), regr_avgy(stream_test.x,stream_test.y), regr_count(stream_test.x,stream_test.y), regr_slope(stream_test.x,stream_test.y), regr_intercept(stream_test.x,stream_test.y), regr_r2(stream_test.x,stream_test.y)], ordering_mode=Sorted +02)--AggregateExec: mode=Single, gby=[g@0 as g], aggr=[corr(stream_test.x,stream_test.y), covar_samp(stream_test.x,stream_test.y), covar_pop(stream_test.x,stream_test.y), regr_sxx(stream_test.x,stream_test.y), regr_sxy(stream_test.x,stream_test.y), regr_syy(stream_test.x,stream_test.y), regr_avgx(stream_test.x,stream_test.y), regr_avgy(stream_test.x,stream_test.y), regr_count(stream_test.x,stream_test.y), regr_slope(stream_test.x,stream_test.y), regr_intercept(stream_test.x,stream_test.y), regr_r2(stream_test.x,stream_test.y)], group_clustering_mode=Full 03)----SortExec: TopK(fetch=10000), expr=[g@0 ASC NULLS LAST], preserve_partitioning=[false] 04)------DataSourceExec: partitions=1, partition_sizes=[1] @@ -9476,7 +9476,7 @@ logical_plan 05)--------TableScan: stream_test projection=[g, x, i] physical_plan 01)ProjectionExec: expr=[g@0 as g, approx_distinct(stream_test.i)@1 as approx_distinct(stream_test.i), approx_median(stream_test.x)@2 as approx_median(stream_test.x), percentile_cont(Float64(0.5)) WITHIN GROUP [stream_test.x ASC NULLS LAST]@3 as percentile_cont(Float64(0.5)) WITHIN GROUP [stream_test.x ASC NULLS LAST], percentile_cont(Float64(0.5)) WITHIN GROUP [stream_test.x ASC NULLS LAST]@3 as quantile_cont(stream_test.x,Float64(0.5)), approx_percentile_cont(Float64(0.5)) WITHIN GROUP [stream_test.x ASC NULLS LAST]@4 as approx_percentile_cont(Float64(0.5)) WITHIN GROUP [stream_test.x ASC NULLS LAST], approx_percentile_cont_with_weight(Float64(1),Float64(0.5)) WITHIN GROUP [stream_test.x ASC NULLS LAST]@5 as approx_percentile_cont_with_weight(Float64(1),Float64(0.5)) WITHIN GROUP [stream_test.x ASC NULLS LAST], percentile_cont(stream_test.x,Float64(0.5))@6 as percentile_cont(stream_test.x,Float64(0.5)), approx_percentile_cont(stream_test.x,Float64(0.5))@7 as approx_percentile_cont(stream_test.x,Float64(0.5)), approx_percentile_cont_with_weight(stream_test.x,Float64(1),Float64(0.5))@8 as approx_percentile_cont_with_weight(stream_test.x,Float64(1),Float64(0.5))] -02)--AggregateExec: mode=Single, gby=[g@0 as g], aggr=[approx_distinct(stream_test.i), approx_median(stream_test.x), percentile_cont(Float64(0.5)) WITHIN GROUP [stream_test.x ASC NULLS LAST], approx_percentile_cont(Float64(0.5)) WITHIN GROUP [stream_test.x ASC NULLS LAST], approx_percentile_cont_with_weight(Float64(1),Float64(0.5)) WITHIN GROUP [stream_test.x ASC NULLS LAST], percentile_cont(stream_test.x,Float64(0.5)), approx_percentile_cont(stream_test.x,Float64(0.5)), approx_percentile_cont_with_weight(stream_test.x,Float64(1),Float64(0.5))], ordering_mode=Sorted +02)--AggregateExec: mode=Single, gby=[g@0 as g], aggr=[approx_distinct(stream_test.i), approx_median(stream_test.x), percentile_cont(Float64(0.5)) WITHIN GROUP [stream_test.x ASC NULLS LAST], approx_percentile_cont(Float64(0.5)) WITHIN GROUP [stream_test.x ASC NULLS LAST], approx_percentile_cont_with_weight(Float64(1),Float64(0.5)) WITHIN GROUP [stream_test.x ASC NULLS LAST], percentile_cont(stream_test.x,Float64(0.5)), approx_percentile_cont(stream_test.x,Float64(0.5)), approx_percentile_cont_with_weight(stream_test.x,Float64(1),Float64(0.5))], group_clustering_mode=Full 03)----SortExec: TopK(fetch=10000), expr=[g@0 ASC NULLS LAST], preserve_partitioning=[false] 04)------DataSourceExec: partitions=1, partition_sizes=[1] diff --git a/datafusion/sqllogictest/test_files/array_agg.slt b/datafusion/sqllogictest/test_files/array_agg.slt index d5aaf8cab17c1..47de0d24be254 100644 --- a/datafusion/sqllogictest/test_files/array_agg.slt +++ b/datafusion/sqllogictest/test_files/array_agg.slt @@ -530,9 +530,9 @@ logical_plan 15)------------EmptyRelation: rows=1 physical_plan 01)ProjectionExec: expr=[array_length(array_agg(DISTINCT a.foo)@1) as array_length(array_agg(DISTINCT a.foo)), sum(DISTINCT Int64(1))@2 as sum(DISTINCT Int64(1))] -02)--AggregateExec: mode=FinalPartitioned, gby=[id@0 as id], aggr=[array_agg(DISTINCT a.foo), sum(DISTINCT Int64(1))], ordering_mode=Sorted +02)--AggregateExec: mode=FinalPartitioned, gby=[id@0 as id], aggr=[array_agg(DISTINCT a.foo), sum(DISTINCT Int64(1))], group_clustering_mode=Full 03)----RepartitionExec: partitioning=Hash([id@0], 4), input_partitions=5 -04)------AggregateExec: mode=Partial, gby=[id@0 as id], aggr=[array_agg(DISTINCT a.foo), sum(DISTINCT Int64(1))], ordering_mode=Sorted +04)------AggregateExec: mode=Partial, gby=[id@0 as id], aggr=[array_agg(DISTINCT a.foo), sum(DISTINCT Int64(1))], group_clustering_mode=Full 05)--------UnionExec 06)----------ProjectionExec: expr=[1 as id, CAST(2 AS Int64) as foo] 07)------------PlaceholderRowExec diff --git a/datafusion/sqllogictest/test_files/group_by.slt b/datafusion/sqllogictest/test_files/group_by.slt index 38d1b7821451d..9ceb60c988bc9 100644 --- a/datafusion/sqllogictest/test_files/group_by.slt +++ b/datafusion/sqllogictest/test_files/group_by.slt @@ -2113,7 +2113,7 @@ logical_plan 03)----TableScan: annotated_data_infinite2 projection=[a, b, c] physical_plan 01)ProjectionExec: expr=[a@1 as a, b@0 as b, sum(annotated_data_infinite2.c)@2 as summation1] -02)--AggregateExec: mode=Single, gby=[b@1 as b, a@0 as a], aggr=[sum(annotated_data_infinite2.c)], ordering_mode=Sorted +02)--AggregateExec: mode=Single, gby=[b@1 as b, a@0 as a], aggr=[sum(annotated_data_infinite2.c)], group_clustering_mode=Full 03)----StreamingTableExec: partition_sizes=1, projection=[a, b, c], infinite_source=true, output_ordering=[a@0 ASC NULLS LAST, b@1 ASC NULLS LAST, c@2 ASC NULLS LAST] @@ -2144,7 +2144,7 @@ logical_plan 03)----TableScan: annotated_data_infinite2 projection=[a, c, d] physical_plan 01)ProjectionExec: expr=[a@1 as a, d@0 as d, sum(annotated_data_infinite2.c) ORDER BY [annotated_data_infinite2.a DESC NULLS FIRST]@2 as summation1] -02)--AggregateExec: mode=Single, gby=[d@2 as d, a@0 as a], aggr=[sum(annotated_data_infinite2.c) ORDER BY [annotated_data_infinite2.a DESC NULLS FIRST]], ordering_mode=PartiallySorted([1]) +02)--AggregateExec: mode=Single, gby=[d@2 as d, a@0 as a], aggr=[sum(annotated_data_infinite2.c) ORDER BY [annotated_data_infinite2.a DESC NULLS FIRST]], group_clustering_mode=Partial([1]) 03)----StreamingTableExec: partition_sizes=1, projection=[a, c, d], infinite_source=true, output_ordering=[a@0 ASC NULLS LAST] query III @@ -2177,7 +2177,7 @@ logical_plan 03)----TableScan: annotated_data_infinite2 projection=[a, b, c] physical_plan 01)ProjectionExec: expr=[a@0 as a, b@1 as b, first_value(annotated_data_infinite2.c) ORDER BY [annotated_data_infinite2.a DESC NULLS FIRST]@2 as first_c] -02)--AggregateExec: mode=Single, gby=[a@0 as a, b@1 as b], aggr=[first_value(annotated_data_infinite2.c) ORDER BY [annotated_data_infinite2.a DESC NULLS FIRST]], ordering_mode=Sorted +02)--AggregateExec: mode=Single, gby=[a@0 as a, b@1 as b], aggr=[first_value(annotated_data_infinite2.c) ORDER BY [annotated_data_infinite2.a DESC NULLS FIRST]], group_clustering_mode=Full 03)----StreamingTableExec: partition_sizes=1, projection=[a, b, c], infinite_source=true, output_ordering=[a@0 ASC NULLS LAST, b@1 ASC NULLS LAST, c@2 ASC NULLS LAST] query III @@ -2203,7 +2203,7 @@ logical_plan 03)----TableScan: annotated_data_infinite2 projection=[a, b, c] physical_plan 01)ProjectionExec: expr=[a@0 as a, b@1 as b, last_value(annotated_data_infinite2.c) ORDER BY [annotated_data_infinite2.a DESC NULLS FIRST]@2 as last_c] -02)--AggregateExec: mode=Single, gby=[a@0 as a, b@1 as b], aggr=[last_value(annotated_data_infinite2.c) ORDER BY [annotated_data_infinite2.a DESC NULLS FIRST]], ordering_mode=Sorted +02)--AggregateExec: mode=Single, gby=[a@0 as a, b@1 as b], aggr=[last_value(annotated_data_infinite2.c) ORDER BY [annotated_data_infinite2.a DESC NULLS FIRST]], group_clustering_mode=Full 03)----StreamingTableExec: partition_sizes=1, projection=[a, b, c], infinite_source=true, output_ordering=[a@0 ASC NULLS LAST, b@1 ASC NULLS LAST, c@2 ASC NULLS LAST] query III @@ -2230,7 +2230,7 @@ logical_plan 03)----TableScan: annotated_data_infinite2 projection=[a, b, c] physical_plan 01)ProjectionExec: expr=[a@0 as a, b@1 as b, last_value(annotated_data_infinite2.c)@2 as last_c] -02)--AggregateExec: mode=Single, gby=[a@0 as a, b@1 as b], aggr=[last_value(annotated_data_infinite2.c)], ordering_mode=Sorted +02)--AggregateExec: mode=Single, gby=[a@0 as a, b@1 as b], aggr=[last_value(annotated_data_infinite2.c)], group_clustering_mode=Full 03)----StreamingTableExec: partition_sizes=1, projection=[a, b, c], infinite_source=true, output_ordering=[a@0 ASC NULLS LAST, b@1 ASC NULLS LAST, c@2 ASC NULLS LAST] query III @@ -2289,7 +2289,7 @@ logical_plan 01)Aggregate: groupBy=[[annotated_data_infinite2.a, annotated_data_infinite2.b]], aggr=[[array_agg(annotated_data_infinite2.d) ORDER BY [annotated_data_infinite2.d ASC NULLS LAST]]] 02)--TableScan: annotated_data_infinite2 projection=[a, b, d] physical_plan -01)AggregateExec: mode=Single, gby=[a@0 as a, b@1 as b], aggr=[array_agg(annotated_data_infinite2.d) ORDER BY [annotated_data_infinite2.d ASC NULLS LAST]], ordering_mode=Sorted +01)AggregateExec: mode=Single, gby=[a@0 as a, b@1 as b], aggr=[array_agg(annotated_data_infinite2.d) ORDER BY [annotated_data_infinite2.d ASC NULLS LAST]], group_clustering_mode=Full 02)--PartialSortExec: expr=[a@0 ASC NULLS LAST, b@1 ASC NULLS LAST, d@2 ASC NULLS LAST], common_prefix_length=[2] 03)----StreamingTableExec: partition_sizes=1, projection=[a, b, d], infinite_source=true, output_ordering=[a@0 ASC NULLS LAST, b@1 ASC NULLS LAST] @@ -2540,7 +2540,7 @@ logical_plan 05)--------TableScan: sales_global projection=[country, amount] physical_plan 01)ProjectionExec: expr=[country@0 as country, array_agg(s.amount) ORDER BY [s.amount DESC NULLS FIRST]@1 as amounts, sum(s.amount)@2 as sum1] -02)--AggregateExec: mode=Single, gby=[country@0 as country], aggr=[array_agg(s.amount) ORDER BY [s.amount DESC NULLS FIRST], sum(s.amount)], ordering_mode=Sorted +02)--AggregateExec: mode=Single, gby=[country@0 as country], aggr=[array_agg(s.amount) ORDER BY [s.amount DESC NULLS FIRST], sum(s.amount)], group_clustering_mode=Full 03)----SortExec: TopK(fetch=10), expr=[country@0 ASC NULLS LAST, amount@1 DESC], preserve_partitioning=[false] 04)------DataSourceExec: partitions=1, partition_sizes=[1] @@ -2578,7 +2578,7 @@ logical_plan 05)--------TableScan: sales_global projection=[zip_code, country, amount] physical_plan 01)ProjectionExec: expr=[country@0 as country, zip_code@1 as zip_code, array_agg(s.amount) ORDER BY [s.amount DESC NULLS FIRST]@2 as amounts, sum(s.amount)@3 as sum1] -02)--AggregateExec: mode=Single, gby=[country@1 as country, zip_code@0 as zip_code], aggr=[array_agg(s.amount) ORDER BY [s.amount DESC NULLS FIRST], sum(s.amount)], ordering_mode=PartiallySorted([0]) +02)--AggregateExec: mode=Single, gby=[country@1 as country, zip_code@0 as zip_code], aggr=[array_agg(s.amount) ORDER BY [s.amount DESC NULLS FIRST], sum(s.amount)], group_clustering_mode=Partial([0]) 03)----SortExec: TopK(fetch=10), expr=[country@1 ASC NULLS LAST, amount@2 DESC], preserve_partitioning=[false] 04)------DataSourceExec: partitions=1, partition_sizes=[1] @@ -2615,7 +2615,7 @@ logical_plan 05)--------TableScan: sales_global projection=[country, amount] physical_plan 01)ProjectionExec: expr=[country@0 as country, array_agg(s.amount) ORDER BY [s.country DESC NULLS FIRST]@1 as amounts, sum(s.amount)@2 as sum1] -02)--AggregateExec: mode=Single, gby=[country@0 as country], aggr=[array_agg(s.amount) ORDER BY [s.country DESC NULLS FIRST], sum(s.amount)], ordering_mode=Sorted +02)--AggregateExec: mode=Single, gby=[country@0 as country], aggr=[array_agg(s.amount) ORDER BY [s.country DESC NULLS FIRST], sum(s.amount)], group_clustering_mode=Full 03)----SortExec: TopK(fetch=10), expr=[country@0 ASC NULLS LAST], preserve_partitioning=[false] 04)------DataSourceExec: partitions=1, partition_sizes=[1] @@ -2651,7 +2651,7 @@ logical_plan 05)--------TableScan: sales_global projection=[country, amount] physical_plan 01)ProjectionExec: expr=[country@0 as country, array_agg(s.amount) ORDER BY [s.country DESC NULLS FIRST, s.amount DESC NULLS FIRST]@1 as amounts, sum(s.amount)@2 as sum1] -02)--AggregateExec: mode=Single, gby=[country@0 as country], aggr=[array_agg(s.amount) ORDER BY [s.country DESC NULLS FIRST, s.amount DESC NULLS FIRST], sum(s.amount)], ordering_mode=Sorted +02)--AggregateExec: mode=Single, gby=[country@0 as country], aggr=[array_agg(s.amount) ORDER BY [s.country DESC NULLS FIRST, s.amount DESC NULLS FIRST], sum(s.amount)], group_clustering_mode=Full 03)----SortExec: TopK(fetch=10), expr=[country@0 ASC NULLS LAST, amount@1 DESC], preserve_partitioning=[false] 04)------DataSourceExec: partitions=1, partition_sizes=[1] @@ -3928,7 +3928,7 @@ logical_plan 12)------------------TableScan: multiple_ordered_table projection=[a, d] physical_plan 01)ProjectionExec: expr=[last_value(l.d) ORDER BY [l.a ASC NULLS LAST]@1 as amount_usd] -02)--AggregateExec: mode=Single, gby=[row_n@2 as row_n], aggr=[last_value(l.d) ORDER BY [l.a ASC NULLS LAST]], ordering_mode=Sorted +02)--AggregateExec: mode=Single, gby=[row_n@2 as row_n], aggr=[last_value(l.d) ORDER BY [l.a ASC NULLS LAST]], group_clustering_mode=Full 03)----HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(d@1, d@1)], filter=CAST(a@0 AS Int64) >= CAST(a@1 AS Int64) - 10, projection=[a@0, d@1, row_n@4] 04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[a, d], output_ordering=[a@0 ASC NULLS LAST], file_type=csv, has_header=true 05)------ProjectionExec: expr=[a@0 as a, d@1 as d, row_number() ORDER BY [r.a ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@2 as row_n] @@ -3968,9 +3968,9 @@ logical_plan 01)Aggregate: groupBy=[[multiple_ordered_table_with_pk.c, multiple_ordered_table_with_pk.b]], aggr=[[sum(CAST(multiple_ordered_table_with_pk.d AS Int64))]] 02)--TableScan: multiple_ordered_table_with_pk projection=[b, c, d] physical_plan -01)AggregateExec: mode=FinalPartitioned, gby=[c@0 as c, b@1 as b], aggr=[sum(multiple_ordered_table_with_pk.d)], ordering_mode=PartiallySorted([0]) +01)AggregateExec: mode=FinalPartitioned, gby=[c@0 as c, b@1 as b], aggr=[sum(multiple_ordered_table_with_pk.d)], group_clustering_mode=Partial([0]) 02)--RepartitionExec: partitioning=Hash([c@0, b@1], 8), input_partitions=8, preserve_order=true, sort_exprs=c@0 ASC NULLS LAST -03)----AggregateExec: mode=Partial, gby=[c@1 as c, b@0 as b], aggr=[sum(multiple_ordered_table_with_pk.d)], ordering_mode=PartiallySorted([0]) +03)----AggregateExec: mode=Partial, gby=[c@1 as c, b@0 as b], aggr=[sum(multiple_ordered_table_with_pk.d)], group_clustering_mode=Partial([0]) 04)------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1, maintains_sort_order=true 05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[b, c, d], output_ordering=[c@1 ASC NULLS LAST], constraints=[PrimaryKey([3])], file_type=csv, has_header=true @@ -4007,9 +4007,9 @@ logical_plan 01)Aggregate: groupBy=[[multiple_ordered_table_with_pk.c, multiple_ordered_table_with_pk.b]], aggr=[[sum(CAST(multiple_ordered_table_with_pk.d AS Int64))]] 02)--TableScan: multiple_ordered_table_with_pk projection=[b, c, d] physical_plan -01)AggregateExec: mode=FinalPartitioned, gby=[c@0 as c, b@1 as b], aggr=[sum(multiple_ordered_table_with_pk.d)], ordering_mode=PartiallySorted([0]) +01)AggregateExec: mode=FinalPartitioned, gby=[c@0 as c, b@1 as b], aggr=[sum(multiple_ordered_table_with_pk.d)], group_clustering_mode=Partial([0]) 02)--RepartitionExec: partitioning=Hash([c@0, b@1], 8), input_partitions=8, preserve_order=true, sort_exprs=c@0 ASC NULLS LAST -03)----AggregateExec: mode=Partial, gby=[c@1 as c, b@0 as b], aggr=[sum(multiple_ordered_table_with_pk.d)], ordering_mode=PartiallySorted([0]) +03)----AggregateExec: mode=Partial, gby=[c@1 as c, b@0 as b], aggr=[sum(multiple_ordered_table_with_pk.d)], group_clustering_mode=Partial([0]) 04)------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1, maintains_sort_order=true 05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[b, c, d], output_ordering=[c@1 ASC NULLS LAST], constraints=[PrimaryKey([3])], file_type=csv, has_header=true @@ -4030,9 +4030,9 @@ logical_plan 03)----Aggregate: groupBy=[[multiple_ordered_table_with_pk.c]], aggr=[[sum(CAST(multiple_ordered_table_with_pk.d AS Int64))]] 04)------TableScan: multiple_ordered_table_with_pk projection=[c, d] physical_plan -01)AggregateExec: mode=Single, gby=[c@0 as c, sum1@1 as sum1], aggr=[], ordering_mode=PartiallySorted([0]) +01)AggregateExec: mode=Single, gby=[c@0 as c, sum1@1 as sum1], aggr=[], group_clustering_mode=Partial([0]) 02)--ProjectionExec: expr=[c@0 as c, sum(multiple_ordered_table_with_pk.d)@1 as sum1] -03)----AggregateExec: mode=Single, gby=[c@0 as c], aggr=[sum(multiple_ordered_table_with_pk.d)], ordering_mode=Sorted +03)----AggregateExec: mode=Single, gby=[c@0 as c], aggr=[sum(multiple_ordered_table_with_pk.d)], group_clustering_mode=Full 04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[c, d], output_ordering=[c@0 ASC NULLS LAST], constraints=[PrimaryKey([3])], file_type=csv, has_header=true query TT @@ -4052,7 +4052,7 @@ physical_plan 01)ProjectionExec: expr=[c@0 as c, sum1@2 as sum1, sum(multiple_ordered_table_with_pk.b) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING@3 as sumb] 02)--WindowAggExec: wdw=[sum(multiple_ordered_table_with_pk.b) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING: Ok(Field { name: "sum(multiple_ordered_table_with_pk.b) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING", data_type: Int64, nullable: true }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(NULL)), is_causal: false }] 03)----ProjectionExec: expr=[c@0 as c, b@1 as b, sum(multiple_ordered_table_with_pk.d)@2 as sum1] -04)------AggregateExec: mode=Single, gby=[c@1 as c, b@0 as b], aggr=[sum(multiple_ordered_table_with_pk.d)], ordering_mode=PartiallySorted([0]) +04)------AggregateExec: mode=Single, gby=[c@1 as c, b@0 as b], aggr=[sum(multiple_ordered_table_with_pk.d)], group_clustering_mode=Partial([0]) 05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[b, c, d], output_ordering=[c@1 ASC NULLS LAST], constraints=[PrimaryKey([3])], file_type=csv, has_header=true query TT @@ -4081,10 +4081,10 @@ logical_plan physical_plan 01)HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(b@1, b@1)], projection=[c@0, c@3, sum1@2, sum1@5] 02)--ProjectionExec: expr=[c@0 as c, b@1 as b, sum(multiple_ordered_table_with_pk.d)@2 as sum1] -03)----AggregateExec: mode=Single, gby=[c@1 as c, b@0 as b], aggr=[sum(multiple_ordered_table_with_pk.d)], ordering_mode=PartiallySorted([0]) +03)----AggregateExec: mode=Single, gby=[c@1 as c, b@0 as b], aggr=[sum(multiple_ordered_table_with_pk.d)], group_clustering_mode=Partial([0]) 04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[b, c, d], output_ordering=[c@1 ASC NULLS LAST], constraints=[PrimaryKey([3])], file_type=csv, has_header=true 05)--ProjectionExec: expr=[c@0 as c, b@1 as b, sum(multiple_ordered_table_with_pk.d)@2 as sum1] -06)----AggregateExec: mode=Single, gby=[c@1 as c, b@0 as b], aggr=[sum(multiple_ordered_table_with_pk.d)], ordering_mode=PartiallySorted([0]) +06)----AggregateExec: mode=Single, gby=[c@1 as c, b@0 as b], aggr=[sum(multiple_ordered_table_with_pk.d)], group_clustering_mode=Partial([0]) 07)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[b, c, d], output_ordering=[c@1 ASC NULLS LAST], constraints=[PrimaryKey([3])], file_type=csv, has_header=true query TT @@ -4113,10 +4113,10 @@ physical_plan 01)ProjectionExec: expr=[c@0 as c, c@2 as c, sum1@1 as sum1, sum1@3 as sum1] 02)--CrossJoinExec 03)----ProjectionExec: expr=[c@0 as c, sum(multiple_ordered_table_with_pk.d)@1 as sum1] -04)------AggregateExec: mode=Single, gby=[c@0 as c], aggr=[sum(multiple_ordered_table_with_pk.d)], ordering_mode=Sorted +04)------AggregateExec: mode=Single, gby=[c@0 as c], aggr=[sum(multiple_ordered_table_with_pk.d)], group_clustering_mode=Full 05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[c, d], output_ordering=[c@0 ASC NULLS LAST], constraints=[PrimaryKey([3])], file_type=csv, has_header=true 06)----ProjectionExec: expr=[c@0 as c, sum(multiple_ordered_table_with_pk.d)@1 as sum1] -07)------AggregateExec: mode=Single, gby=[c@0 as c], aggr=[sum(multiple_ordered_table_with_pk.d)], ordering_mode=Sorted +07)------AggregateExec: mode=Single, gby=[c@0 as c], aggr=[sum(multiple_ordered_table_with_pk.d)], group_clustering_mode=Full 08)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[c, d], output_ordering=[c@0 ASC NULLS LAST], constraints=[PrimaryKey([3])], file_type=csv, has_header=true # we do not generate physical plan for Repartition yet (e.g Distribute By queries). @@ -4155,10 +4155,10 @@ logical_plan physical_plan 01)UnionExec 02)--ProjectionExec: expr=[c@0 as c, a@1 as a, sum(multiple_ordered_table_with_pk.d)@2 as sum1] -03)----AggregateExec: mode=Single, gby=[c@1 as c, a@0 as a], aggr=[sum(multiple_ordered_table_with_pk.d)], ordering_mode=Sorted +03)----AggregateExec: mode=Single, gby=[c@1 as c, a@0 as a], aggr=[sum(multiple_ordered_table_with_pk.d)], group_clustering_mode=Full 04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[a, c, d], output_orderings=[[a@0 ASC NULLS LAST], [c@1 ASC NULLS LAST]], constraints=[PrimaryKey([3])], file_type=csv, has_header=true 05)--ProjectionExec: expr=[c@0 as c, a@1 as a, sum(multiple_ordered_table_with_pk.d)@2 as sum1] -06)----AggregateExec: mode=Single, gby=[c@1 as c, a@0 as a], aggr=[sum(multiple_ordered_table_with_pk.d)], ordering_mode=Sorted +06)----AggregateExec: mode=Single, gby=[c@1 as c, a@0 as a], aggr=[sum(multiple_ordered_table_with_pk.d)], group_clustering_mode=Full 07)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[a, c, d], output_orderings=[[a@0 ASC NULLS LAST], [c@1 ASC NULLS LAST]], constraints=[PrimaryKey([3])], file_type=csv, has_header=true # table scan should be simplified. @@ -4173,7 +4173,7 @@ logical_plan 03)----TableScan: multiple_ordered_table_with_pk projection=[a, c, d] physical_plan 01)ProjectionExec: expr=[c@0 as c, a@1 as a, sum(multiple_ordered_table_with_pk.d)@2 as sum1] -02)--AggregateExec: mode=Single, gby=[c@1 as c, a@0 as a], aggr=[sum(multiple_ordered_table_with_pk.d)], ordering_mode=Sorted +02)--AggregateExec: mode=Single, gby=[c@1 as c, a@0 as a], aggr=[sum(multiple_ordered_table_with_pk.d)], group_clustering_mode=Full 03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[a, c, d], output_orderings=[[a@0 ASC NULLS LAST], [c@1 ASC NULLS LAST]], constraints=[PrimaryKey([3])], file_type=csv, has_header=true # limit should be simplified @@ -4192,7 +4192,7 @@ logical_plan physical_plan 01)ProjectionExec: expr=[c@0 as c, a@1 as a, sum(multiple_ordered_table_with_pk.d)@2 as sum1] 02)--GlobalLimitExec: skip=0, fetch=5 -03)----AggregateExec: mode=Single, gby=[c@1 as c, a@0 as a], aggr=[sum(multiple_ordered_table_with_pk.d)], ordering_mode=Sorted +03)----AggregateExec: mode=Single, gby=[c@1 as c, a@0 as a], aggr=[sum(multiple_ordered_table_with_pk.d)], group_clustering_mode=Full 04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[a, c, d], output_orderings=[[a@0 ASC NULLS LAST], [c@1 ASC NULLS LAST]], constraints=[PrimaryKey([3])], file_type=csv, has_header=true statement ok @@ -4275,9 +4275,9 @@ logical_plan physical_plan 01)SortPreservingMergeExec: [time_chunks@0 DESC], fetch=5 02)--ProjectionExec: expr=[date_bin(Utf8("15 minutes"),unbounded_csv_with_timestamps.ts)@0 as time_chunks] -03)----AggregateExec: mode=FinalPartitioned, gby=[date_bin(Utf8("15 minutes"),unbounded_csv_with_timestamps.ts)@0 as date_bin(Utf8("15 minutes"),unbounded_csv_with_timestamps.ts)], aggr=[], ordering_mode=Sorted +03)----AggregateExec: mode=FinalPartitioned, gby=[date_bin(Utf8("15 minutes"),unbounded_csv_with_timestamps.ts)@0 as date_bin(Utf8("15 minutes"),unbounded_csv_with_timestamps.ts)], aggr=[], group_clustering_mode=Full 04)------RepartitionExec: partitioning=Hash([date_bin(Utf8("15 minutes"),unbounded_csv_with_timestamps.ts)@0], 8), input_partitions=8, preserve_order=true, sort_exprs=date_bin(Utf8("15 minutes"),unbounded_csv_with_timestamps.ts)@0 DESC -05)--------AggregateExec: mode=Partial, gby=[date_bin(IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 900000000000 }, ts@0) as date_bin(Utf8("15 minutes"),unbounded_csv_with_timestamps.ts)], aggr=[], ordering_mode=Sorted +05)--------AggregateExec: mode=Partial, gby=[date_bin(IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 900000000000 }, ts@0) as date_bin(Utf8("15 minutes"),unbounded_csv_with_timestamps.ts)], aggr=[], group_clustering_mode=Full 06)----------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1, maintains_sort_order=true 07)------------StreamingTableExec: partition_sizes=1, projection=[ts], infinite_source=true, output_ordering=[ts@0 DESC] @@ -5000,7 +5000,7 @@ logical_plan 02)--Aggregate: groupBy=[[multiple_ordered_table.a, multiple_ordered_table.b]], aggr=[[array_agg(multiple_ordered_table.c) ORDER BY [multiple_ordered_table.c DESC NULLS FIRST]]] 03)----TableScan: multiple_ordered_table projection=[a, b, c] physical_plan -01)AggregateExec: mode=Single, gby=[a@0 as a, b@1 as b], aggr=[array_agg(multiple_ordered_table.c) ORDER BY [multiple_ordered_table.c DESC NULLS FIRST]], ordering_mode=Sorted +01)AggregateExec: mode=Single, gby=[a@0 as a, b@1 as b], aggr=[array_agg(multiple_ordered_table.c) ORDER BY [multiple_ordered_table.c DESC NULLS FIRST]], group_clustering_mode=Full 02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[a, b, c], output_orderings=[[a@0 ASC NULLS LAST, b@1 ASC NULLS LAST], [c@2 ASC NULLS LAST]], file_type=csv, has_header=true query II? diff --git a/datafusion/sqllogictest/test_files/joins.slt b/datafusion/sqllogictest/test_files/joins.slt index 54123002d0aa5..b5156104d9693 100644 --- a/datafusion/sqllogictest/test_files/joins.slt +++ b/datafusion/sqllogictest/test_files/joins.slt @@ -3432,7 +3432,7 @@ logical_plan 08)----------TableScan: annotated_data projection=[a, b] physical_plan 01)ProjectionExec: expr=[a@0 as a, last_value(r.b) ORDER BY [r.a ASC NULLS FIRST]@3 as last_col1] -02)--AggregateExec: mode=Single, gby=[a@0 as a, b@1 as b, c@2 as c], aggr=[last_value(r.b) ORDER BY [r.a ASC NULLS FIRST]], ordering_mode=PartiallySorted([0]) +02)--AggregateExec: mode=Single, gby=[a@0 as a, b@1 as b, c@2 as c], aggr=[last_value(r.b) ORDER BY [r.a ASC NULLS FIRST]], group_clustering_mode=Partial([0]) 03)----HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(a@0, a@0)] 04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[a, b, c], output_ordering=[a@0 ASC, b@1 ASC NULLS LAST, c@2 ASC NULLS LAST], file_type=csv, has_header=true 05)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[a, b], output_ordering=[a@0 ASC, b@1 ASC NULLS LAST], file_type=csv, has_header=true @@ -3479,7 +3479,7 @@ logical_plan 12)------------------TableScan: multiple_ordered_table projection=[a, d] physical_plan 01)ProjectionExec: expr=[last_value(l.d) ORDER BY [l.a ASC NULLS LAST]@1 as amount_usd] -02)--AggregateExec: mode=Single, gby=[row_n@2 as row_n], aggr=[last_value(l.d) ORDER BY [l.a ASC NULLS LAST]], ordering_mode=Sorted +02)--AggregateExec: mode=Single, gby=[row_n@2 as row_n], aggr=[last_value(l.d) ORDER BY [l.a ASC NULLS LAST]], group_clustering_mode=Full 03)----HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(d@1, d@1)], filter=CAST(a@0 AS Int64) >= CAST(a@1 AS Int64) - 10, projection=[a@0, d@1, row_n@4] 04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[a, d], output_ordering=[a@0 ASC NULLS LAST], file_type=csv, has_header=true 05)------ProjectionExec: expr=[a@0 as a, d@1 as d, row_number() ORDER BY [r.a ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@2 as row_n] @@ -3514,9 +3514,9 @@ logical_plan physical_plan 01)SortPreservingMergeExec: [a@0 ASC] 02)--ProjectionExec: expr=[a@0 as a, last_value(r.b) ORDER BY [r.a ASC NULLS FIRST]@3 as last_col1] -03)----AggregateExec: mode=FinalPartitioned, gby=[a@0 as a, b@1 as b, c@2 as c], aggr=[last_value(r.b) ORDER BY [r.a ASC NULLS FIRST]], ordering_mode=PartiallySorted([0]) +03)----AggregateExec: mode=FinalPartitioned, gby=[a@0 as a, b@1 as b, c@2 as c], aggr=[last_value(r.b) ORDER BY [r.a ASC NULLS FIRST]], group_clustering_mode=Partial([0]) 04)------RepartitionExec: partitioning=Hash([a@0, b@1, c@2], 2), input_partitions=2, preserve_order=true, sort_exprs=a@0 ASC -05)--------AggregateExec: mode=Partial, gby=[a@0 as a, b@1 as b, c@2 as c], aggr=[last_value(r.b) ORDER BY [r.a ASC NULLS FIRST]], ordering_mode=PartiallySorted([0]) +05)--------AggregateExec: mode=Partial, gby=[a@0 as a, b@1 as b, c@2 as c], aggr=[last_value(r.b) ORDER BY [r.a ASC NULLS FIRST]], group_clustering_mode=Partial([0]) 06)----------HashJoinExec: mode=Partitioned, join_type=Inner, on=[(a@0, a@0)] 07)------------RepartitionExec: partitioning=Hash([a@0], 2), input_partitions=1, maintains_sort_order=true 08)--------------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[a, b, c], output_ordering=[a@0 ASC, b@1 ASC NULLS LAST, c@2 ASC NULLS LAST], file_type=csv, has_header=true diff --git a/datafusion/sqllogictest/test_files/order.slt b/datafusion/sqllogictest/test_files/order.slt index 497966c95a387..7c4cc44e0e768 100644 --- a/datafusion/sqllogictest/test_files/order.slt +++ b/datafusion/sqllogictest/test_files/order.slt @@ -1708,7 +1708,7 @@ EXPLAIN SELECT c1, SUM(c2) as sum_c2 FROM table_with_ordered_not_null GROUP BY c ---- physical_plan 01)ProjectionExec: expr=[c1@0 as c1, sum(table_with_ordered_not_null.c2)@1 as sum_c2] -02)--AggregateExec: mode=Single, gby=[c1@0 as c1], aggr=[sum(table_with_ordered_not_null.c2)], ordering_mode=Sorted +02)--AggregateExec: mode=Single, gby=[c1@0 as c1], aggr=[sum(table_with_ordered_not_null.c2)], group_clustering_mode=Full 03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/aggregate_agg_multi_order.csv]]}, projection=[c1, c2], output_ordering=[c1@0 ASC NULLS LAST], file_type=csv, has_header=true statement ok diff --git a/datafusion/sqllogictest/test_files/ordered_aggregate_spill.slt b/datafusion/sqllogictest/test_files/ordered_aggregate_spill.slt index 2c53c94144eb3..db2c108f6a13f 100644 --- a/datafusion/sqllogictest/test_files/ordered_aggregate_spill.slt +++ b/datafusion/sqllogictest/test_files/ordered_aggregate_spill.slt @@ -50,9 +50,9 @@ FROM generate_series(20000) AS t1(v1) GROUP BY v1 ---- Plan with Metrics -01)AggregateExec: mode=FinalPartitioned,ordering_mode=Sorted, metrics=[spill_count=0,] +01)AggregateExec: mode=FinalPartitioned,group_clustering_mode=Full, metrics=[spill_count=0,] 02)--RepartitionExec:preserve_order=true -03)----AggregateExec: mode=Partial,ordering_mode=Sorted, metrics=[spill_count=0,] +03)----AggregateExec: mode=Partial,group_clustering_mode=Full, metrics=[spill_count=0,] query II rowsort @@ -95,9 +95,9 @@ FROM generate_series(20000) AS t1(v1) GROUP BY round(v1, -4), v1 % 5000 ---- Plan with Metrics -01)AggregateExec: mode=FinalPartitioned,aggr=[sum(t1.v1 * Int64(2))], ordering_mode=PartiallySorted([0]), metrics=[spill_count=0,] +01)AggregateExec: mode=FinalPartitioned,aggr=[sum(t1.v1 * Int64(2))], group_clustering_mode=Partial([0]), metrics=[spill_count=0,] 02)--RepartitionExec:input_partitions=1, maintains_sort_order=true -03)----AggregateExec: mode=Partial,ordering_mode=PartiallySorted([0]), metrics=[spill_count=0,] +03)----AggregateExec: mode=Partial,group_clustering_mode=Partial([0]), metrics=[spill_count=0,] # All rounds should have the same result hash @@ -119,9 +119,9 @@ FROM generate_series(20000) AS t1(v1) GROUP BY round(v1, -4), v1 % 5000 ---- Plan with Metrics -01)AggregateExec: mode=FinalPartitioned,aggr=[sum(t1.v1 * Int64(2))], ordering_mode=PartiallySorted([0]), metrics=[spilled_bytes= KB,] +01)AggregateExec: mode=FinalPartitioned,aggr=[sum(t1.v1 * Int64(2))], group_clustering_mode=Partial([0]), metrics=[spilled_bytes= KB,] 02)--RepartitionExec:input_partitions=1, maintains_sort_order=true -03)----AggregateExec: mode=Partial,ordering_mode=PartiallySorted([0]), metrics=[spill_count=0,] +03)----AggregateExec: mode=Partial,group_clustering_mode=Partial([0]), metrics=[spill_count=0,] # All rounds should have the same result hash @@ -143,9 +143,9 @@ FROM generate_series(20000) AS t1(v1) GROUP BY round(v1, -4), v1 % 5000 ---- Plan with Metrics -01)AggregateExec: mode=FinalPartitioned,aggr=[sum(t1.v1 * Int64(2))], ordering_mode=PartiallySorted([0]), metrics=[spilled_bytes= KB,] +01)AggregateExec: mode=FinalPartitioned,aggr=[sum(t1.v1 * Int64(2))], group_clustering_mode=Partial([0]), metrics=[spilled_bytes= KB,] 02)--RepartitionExec:input_partitions=1, maintains_sort_order=true -03)----AggregateExec: mode=Partial,ordering_mode=PartiallySorted([0]), metrics=[spill_count=0,] +03)----AggregateExec: mode=Partial,group_clustering_mode=Partial([0]), metrics=[spill_count=0,] # All rounds should have the same result hash @@ -171,9 +171,9 @@ FROM generate_series(20000) AS t1(v1) GROUP BY round(v1, -4), v1 % 5000 ---- Plan with Metrics -01)AggregateExec: mode=FinalPartitioned,aggr=[sum(t1.v1 * Int64(2)), min(t1.v1 % Int64(2))], ordering_mode=PartiallySorted([0]), metrics=[spilled_bytes=KB,] +01)AggregateExec: mode=FinalPartitioned,aggr=[sum(t1.v1 * Int64(2)), min(t1.v1 % Int64(2))], group_clustering_mode=Partial([0]), metrics=[spilled_bytes=KB,] 02)--RepartitionExec:input_partitions=1, maintains_sort_order=true -03)----AggregateExec: mode=Partial,aggr=[sum(t1.v1 * Int64(2)), min(t1.v1 % Int64(2))], ordering_mode=PartiallySorted([0]), metrics=[spill_count=0,] +03)----AggregateExec: mode=Partial,aggr=[sum(t1.v1 * Int64(2)), min(t1.v1 % Int64(2))], group_clustering_mode=Partial([0]), metrics=[spill_count=0,] # ================================================================================== @@ -196,7 +196,7 @@ FROM generate_series(20000) AS t1(v1) GROUP BY round(v1, -4), v1 % 5000 ---- Plan with Metrics -01)AggregateExec: mode=Single,aggr=[min(t1.v1 * Int64(2)), avg(t1.v1)], ordering_mode=PartiallySorted([0]), metrics=[spill_count=0,] +01)AggregateExec: mode=Single,aggr=[min(t1.v1 * Int64(2)), avg(t1.v1)], group_clustering_mode=Partial([0]), metrics=[spill_count=0,] query IIIR rowsort @@ -217,7 +217,7 @@ FROM generate_series(20000) AS t1(v1) GROUP BY round(v1, -4), v1 % 5000 ---- Plan with Metrics -01)AggregateExec: mode=Single,aggr=[min(t1.v1 * Int64(2)), avg(t1.v1)], ordering_mode=PartiallySorted([0]), metrics=[spilled_bytes= KB,] +01)AggregateExec: mode=Single,aggr=[min(t1.v1 * Int64(2)), avg(t1.v1)], group_clustering_mode=Partial([0]), metrics=[spilled_bytes= KB,] # Same result hash as the no-spill round above diff --git a/datafusion/sqllogictest/test_files/preserve_file_partitioning.slt b/datafusion/sqllogictest/test_files/preserve_file_partitioning.slt index e2dd22cc82bba..f4aab94ea627d 100644 --- a/datafusion/sqllogictest/test_files/preserve_file_partitioning.slt +++ b/datafusion/sqllogictest/test_files/preserve_file_partitioning.slt @@ -287,9 +287,9 @@ logical_plan physical_plan 01)SortPreservingMergeExec: [f_dkey@0 ASC NULLS LAST] 02)--ProjectionExec: expr=[f_dkey@0 as f_dkey, count(Int64(1))@1 as count(*), avg(fact_table_ordered.value)@2 as avg(fact_table_ordered.value)] -03)----AggregateExec: mode=FinalPartitioned, gby=[f_dkey@0 as f_dkey], aggr=[count(Int64(1)), avg(fact_table_ordered.value)], ordering_mode=Sorted +03)----AggregateExec: mode=FinalPartitioned, gby=[f_dkey@0 as f_dkey], aggr=[count(Int64(1)), avg(fact_table_ordered.value)], group_clustering_mode=Full 04)------RepartitionExec: partitioning=Hash([f_dkey@0], 3), input_partitions=3, preserve_order=true, sort_exprs=f_dkey@0 ASC NULLS LAST -05)--------AggregateExec: mode=Partial, gby=[f_dkey@1 as f_dkey], aggr=[count(Int64(1)), avg(fact_table_ordered.value)], ordering_mode=Sorted +05)--------AggregateExec: mode=Partial, gby=[f_dkey@1 as f_dkey], aggr=[count(Int64(1)), avg(fact_table_ordered.value)], group_clustering_mode=Full 06)----------DataSourceExec: file_groups={3 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/preserve_file_partitioning/fact/f_dkey=A/data.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/preserve_file_partitioning/fact/f_dkey=B/data.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/preserve_file_partitioning/fact/f_dkey=C/data.parquet]]}, projection=[value, f_dkey], output_ordering=[f_dkey@1 ASC NULLS LAST], file_type=parquet # Verify results without optimization @@ -319,7 +319,7 @@ logical_plan physical_plan 01)SortPreservingMergeExec: [f_dkey@0 ASC NULLS LAST] 02)--ProjectionExec: expr=[f_dkey@0 as f_dkey, count(Int64(1))@1 as count(*), avg(fact_table_ordered.value)@2 as avg(fact_table_ordered.value)] -03)----AggregateExec: mode=SinglePartitioned, gby=[f_dkey@1 as f_dkey], aggr=[count(Int64(1)), avg(fact_table_ordered.value)], ordering_mode=Sorted +03)----AggregateExec: mode=SinglePartitioned, gby=[f_dkey@1 as f_dkey], aggr=[count(Int64(1)), avg(fact_table_ordered.value)], group_clustering_mode=Full 04)------DataSourceExec: file_groups={3 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/preserve_file_partitioning/fact/f_dkey=A/data.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/preserve_file_partitioning/fact/f_dkey=B/data.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/preserve_file_partitioning/fact/f_dkey=C/data.parquet]]}, projection=[value, f_dkey], output_ordering=[f_dkey@1 ASC NULLS LAST], output_partitioning=Hash([f_dkey@1], 3), file_type=parquet query TIR @@ -359,9 +359,9 @@ logical_plan physical_plan 01)SortPreservingMergeExec: [f_dkey@0 ASC NULLS LAST] 02)--ProjectionExec: expr=[f_dkey@0 as f_dkey, max(d.env)@1 as max(d.env), max(d.service)@2 as max(d.service), count(Int64(1))@3 as count(*), sum(f.value)@4 as sum(f.value)] -03)----AggregateExec: mode=FinalPartitioned, gby=[f_dkey@0 as f_dkey], aggr=[max(d.env), max(d.service), count(Int64(1)), sum(f.value)], ordering_mode=Sorted +03)----AggregateExec: mode=FinalPartitioned, gby=[f_dkey@0 as f_dkey], aggr=[max(d.env), max(d.service), count(Int64(1)), sum(f.value)], group_clustering_mode=Full 04)------RepartitionExec: partitioning=Hash([f_dkey@0], 3), input_partitions=3, preserve_order=true, sort_exprs=f_dkey@0 ASC NULLS LAST -05)--------AggregateExec: mode=Partial, gby=[f_dkey@1 as f_dkey], aggr=[max(d.env), max(d.service), count(Int64(1)), sum(f.value)], ordering_mode=Sorted +05)--------AggregateExec: mode=Partial, gby=[f_dkey@1 as f_dkey], aggr=[max(d.env), max(d.service), count(Int64(1)), sum(f.value)], group_clustering_mode=Full 06)----------HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(d_dkey@0, f_dkey@1)], projection=[value@3, f_dkey@4, env@1, service@2] 07)------------CoalescePartitionsExec 08)--------------FilterExec: service@2 = log @@ -412,7 +412,7 @@ logical_plan physical_plan 01)SortPreservingMergeExec: [f_dkey@0 ASC NULLS LAST] 02)--ProjectionExec: expr=[f_dkey@0 as f_dkey, max(d.env)@1 as max(d.env), max(d.service)@2 as max(d.service), count(Int64(1))@3 as count(*), sum(f.value)@4 as sum(f.value)] -03)----AggregateExec: mode=SinglePartitioned, gby=[f_dkey@1 as f_dkey], aggr=[max(d.env), max(d.service), count(Int64(1)), sum(f.value)], ordering_mode=Sorted +03)----AggregateExec: mode=SinglePartitioned, gby=[f_dkey@1 as f_dkey], aggr=[max(d.env), max(d.service), count(Int64(1)), sum(f.value)], group_clustering_mode=Full 04)------HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(d_dkey@0, f_dkey@1)], projection=[value@3, f_dkey@4, env@1, service@2] 05)--------CoalescePartitionsExec 06)----------FilterExec: service@2 = log diff --git a/datafusion/sqllogictest/test_files/push_down_filter_regression.slt b/datafusion/sqllogictest/test_files/push_down_filter_regression.slt index 57509fd0395b9..1d8ab27f552e9 100644 --- a/datafusion/sqllogictest/test_files/push_down_filter_regression.slt +++ b/datafusion/sqllogictest/test_files/push_down_filter_regression.slt @@ -497,9 +497,9 @@ query TT EXPLAIN SELECT a, count(b) FROM agg_filter_pushdown WHERE a = 'x' GROUP BY a; ---- physical_plan -01)AggregateExec: mode=FinalPartitioned, gby=[a@0 as a], aggr=[count(agg_filter_pushdown.b)], ordering_mode=Sorted +01)AggregateExec: mode=FinalPartitioned, gby=[a@0 as a], aggr=[count(agg_filter_pushdown.b)], group_clustering_mode=Full 02)--RepartitionExec: partitioning=Hash([a@0], 4), input_partitions=4 -03)----AggregateExec: mode=Partial, gby=[a@0 as a], aggr=[count(agg_filter_pushdown.b)], ordering_mode=Sorted +03)----AggregateExec: mode=Partial, gby=[a@0 as a], aggr=[count(agg_filter_pushdown.b)], group_clustering_mode=Full 04)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/push_down_filter_regression/agg_filter_pushdown.parquet]]}, projection=[a, b], file_type=parquet, predicate=a@0 = x, pruning_predicate=a_null_count@2 != row_count@3 AND a_min@0 <= x AND x <= a_max@1, required_guarantees=[a in (x)] diff --git a/datafusion/sqllogictest/test_files/repartition_subset_satisfaction.slt b/datafusion/sqllogictest/test_files/repartition_subset_satisfaction.slt index 5371ca59beea1..09bf131e5e95f 100644 --- a/datafusion/sqllogictest/test_files/repartition_subset_satisfaction.slt +++ b/datafusion/sqllogictest/test_files/repartition_subset_satisfaction.slt @@ -161,9 +161,9 @@ logical_plan physical_plan 01)SortPreservingMergeExec: [f_dkey@0 ASC NULLS LAST, time_bin@1 ASC NULLS LAST] 02)--ProjectionExec: expr=[f_dkey@0 as f_dkey, date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),fact_table_ordered.timestamp)@1 as time_bin, count(Int64(1))@2 as count(*), avg(fact_table_ordered.value)@3 as avg(fact_table_ordered.value)] -03)----AggregateExec: mode=FinalPartitioned, gby=[f_dkey@0 as f_dkey, date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),fact_table_ordered.timestamp)@1 as date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),fact_table_ordered.timestamp)], aggr=[count(Int64(1)), avg(fact_table_ordered.value)], ordering_mode=Sorted +03)----AggregateExec: mode=FinalPartitioned, gby=[f_dkey@0 as f_dkey, date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),fact_table_ordered.timestamp)@1 as date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),fact_table_ordered.timestamp)], aggr=[count(Int64(1)), avg(fact_table_ordered.value)], group_clustering_mode=Full 04)------RepartitionExec: partitioning=Hash([f_dkey@0, date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),fact_table_ordered.timestamp)@1], 3), input_partitions=3, preserve_order=true, sort_exprs=f_dkey@0 ASC NULLS LAST, date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),fact_table_ordered.timestamp)@1 ASC NULLS LAST -05)--------AggregateExec: mode=Partial, gby=[f_dkey@2 as f_dkey, date_bin(IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }, timestamp@0) as date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),fact_table_ordered.timestamp)], aggr=[count(Int64(1)), avg(fact_table_ordered.value)], ordering_mode=Sorted +05)--------AggregateExec: mode=Partial, gby=[f_dkey@2 as f_dkey, date_bin(IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }, timestamp@0) as date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),fact_table_ordered.timestamp)], aggr=[count(Int64(1)), avg(fact_table_ordered.value)], group_clustering_mode=Full 06)----------DataSourceExec: file_groups={3 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_subset_satisfaction/fact/f_dkey=A/data.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_subset_satisfaction/fact/f_dkey=B/data.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_subset_satisfaction/fact/f_dkey=C/data.parquet]]}, projection=[timestamp, value, f_dkey], output_ordering=[f_dkey@2 ASC NULLS LAST, timestamp@0 ASC NULLS LAST], output_partitioning=Hash([f_dkey@2], 3), file_type=parquet # Verify results without subset satisfaction @@ -203,7 +203,7 @@ logical_plan physical_plan 01)SortPreservingMergeExec: [f_dkey@0 ASC NULLS LAST, time_bin@1 ASC NULLS LAST] 02)--ProjectionExec: expr=[f_dkey@0 as f_dkey, date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),fact_table_ordered.timestamp)@1 as time_bin, count(Int64(1))@2 as count(*), avg(fact_table_ordered.value)@3 as avg(fact_table_ordered.value)] -03)----AggregateExec: mode=SinglePartitioned, gby=[f_dkey@2 as f_dkey, date_bin(IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }, timestamp@0) as date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),fact_table_ordered.timestamp)], aggr=[count(Int64(1)), avg(fact_table_ordered.value)], ordering_mode=Sorted +03)----AggregateExec: mode=SinglePartitioned, gby=[f_dkey@2 as f_dkey, date_bin(IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }, timestamp@0) as date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),fact_table_ordered.timestamp)], aggr=[count(Int64(1)), avg(fact_table_ordered.value)], group_clustering_mode=Full 04)------DataSourceExec: file_groups={3 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_subset_satisfaction/fact/f_dkey=A/data.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_subset_satisfaction/fact/f_dkey=B/data.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_subset_satisfaction/fact/f_dkey=C/data.parquet]]}, projection=[timestamp, value, f_dkey], output_ordering=[f_dkey@2 ASC NULLS LAST, timestamp@0 ASC NULLS LAST], output_partitioning=Hash([f_dkey@2], 3), file_type=parquet # Verify results match with subset satisfaction @@ -373,9 +373,9 @@ physical_plan 05)--------RepartitionExec: partitioning=Hash([env@0, time_bin@1], 3), input_partitions=3 06)----------AggregateExec: mode=Partial, gby=[env@1 as env, time_bin@0 as time_bin], aggr=[avg(a.max_bin_value)] 07)------------ProjectionExec: expr=[date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),j.timestamp)@1 as time_bin, env@2 as env, max(j.value)@3 as max_bin_value] -08)--------------AggregateExec: mode=FinalPartitioned, gby=[f_dkey@0 as f_dkey, date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),j.timestamp)@1 as date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),j.timestamp), env@2 as env], aggr=[max(j.value)], ordering_mode=PartiallySorted([0, 1]) +08)--------------AggregateExec: mode=FinalPartitioned, gby=[f_dkey@0 as f_dkey, date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),j.timestamp)@1 as date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),j.timestamp), env@2 as env], aggr=[max(j.value)], group_clustering_mode=Partial([0, 1]) 09)----------------RepartitionExec: partitioning=Hash([f_dkey@0, date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),j.timestamp)@1, env@2], 3), input_partitions=3, preserve_order=true, sort_exprs=f_dkey@0 ASC NULLS LAST, date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),j.timestamp)@1 ASC NULLS LAST -10)------------------AggregateExec: mode=Partial, gby=[f_dkey@0 as f_dkey, date_bin(IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }, timestamp@2) as date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),j.timestamp), env@1 as env], aggr=[max(j.value)], ordering_mode=PartiallySorted([0, 1]) +10)------------------AggregateExec: mode=Partial, gby=[f_dkey@0 as f_dkey, date_bin(IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }, timestamp@2) as date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),j.timestamp), env@1 as env], aggr=[max(j.value)], group_clustering_mode=Partial([0, 1]) 11)--------------------HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(d_dkey@1, f_dkey@2)], projection=[f_dkey@4, env@0, timestamp@2, value@3] 12)----------------------CoalescePartitionsExec 13)------------------------FilterExec: service@1 = log, projection=[env@0, d_dkey@2] @@ -470,7 +470,7 @@ physical_plan 05)--------RepartitionExec: partitioning=Hash([env@0, time_bin@1], 3), input_partitions=3 06)----------AggregateExec: mode=Partial, gby=[env@1 as env, time_bin@0 as time_bin], aggr=[avg(a.max_bin_value)] 07)------------ProjectionExec: expr=[date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),j.timestamp)@1 as time_bin, env@2 as env, max(j.value)@3 as max_bin_value] -08)--------------AggregateExec: mode=SinglePartitioned, gby=[f_dkey@0 as f_dkey, date_bin(IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }, timestamp@2) as date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),j.timestamp), env@1 as env], aggr=[max(j.value)], ordering_mode=PartiallySorted([0, 1]) +08)--------------AggregateExec: mode=SinglePartitioned, gby=[f_dkey@0 as f_dkey, date_bin(IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }, timestamp@2) as date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 30000000000 }"),j.timestamp), env@1 as env], aggr=[max(j.value)], group_clustering_mode=Partial([0, 1]) 09)----------------HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(d_dkey@1, f_dkey@2)], projection=[f_dkey@4, env@0, timestamp@2, value@3] 10)------------------CoalescePartitionsExec 11)--------------------FilterExec: service@1 = log, projection=[env@0, d_dkey@2] diff --git a/datafusion/sqllogictest/test_files/sort_pushdown.slt b/datafusion/sqllogictest/test_files/sort_pushdown.slt index f2442762f3fd2..5ac7e8b2370a3 100644 --- a/datafusion/sqllogictest/test_files/sort_pushdown.slt +++ b/datafusion/sqllogictest/test_files/sort_pushdown.slt @@ -895,7 +895,7 @@ logical_plan 03)----TableScan: agg_expr_parquet projection=[x, y, v] physical_plan 01)SortExec: expr=[x@0 ASC NULLS LAST, agg_expr_parquet.y % Int64(2)@1 ASC NULLS LAST], preserve_partitioning=[false] -02)--AggregateExec: mode=Single, gby=[x@0 as x, CAST(y@1 AS Int64) % 2 as agg_expr_parquet.y % Int64(2)], aggr=[sum(agg_expr_parquet.v)], ordering_mode=PartiallySorted([0]) +02)--AggregateExec: mode=Single, gby=[x@0 as x, CAST(y@1 AS Int64) % 2 as agg_expr_parquet.y % Int64(2)], aggr=[sum(agg_expr_parquet.v)], group_clustering_mode=Partial([0]) 03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/sort_pushdown/agg_expr_sorted.parquet]]}, projection=[x, y, v], output_ordering=[x@0 ASC NULLS LAST, y@1 ASC NULLS LAST], file_type=parquet # Expected output pattern from ORDER BY [x, bucket]: @@ -929,7 +929,7 @@ logical_plan 02)--Aggregate: groupBy=[[agg_expr_parquet.x, CAST(agg_expr_parquet.y AS Int64)]], aggr=[[sum(CAST(agg_expr_parquet.v AS Int64))]] 03)----TableScan: agg_expr_parquet projection=[x, y, v] physical_plan -01)AggregateExec: mode=Single, gby=[x@0 as x, CAST(y@1 AS Int64) as agg_expr_parquet.y], aggr=[sum(agg_expr_parquet.v)], ordering_mode=Sorted +01)AggregateExec: mode=Single, gby=[x@0 as x, CAST(y@1 AS Int64) as agg_expr_parquet.y], aggr=[sum(agg_expr_parquet.v)], group_clustering_mode=Full 02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/sort_pushdown/agg_expr_sorted.parquet]]}, projection=[x, y, v], output_ordering=[x@0 ASC NULLS LAST, y@1 ASC NULLS LAST], file_type=parquet query III @@ -961,7 +961,7 @@ logical_plan 03)----TableScan: agg_expr_parquet projection=[x, v] physical_plan 01)SortExec: expr=[sum(agg_expr_parquet.v)@1 ASC NULLS LAST], preserve_partitioning=[false] -02)--AggregateExec: mode=Single, gby=[x@0 as x], aggr=[sum(agg_expr_parquet.v)], ordering_mode=Sorted +02)--AggregateExec: mode=Single, gby=[x@0 as x], aggr=[sum(agg_expr_parquet.v)], group_clustering_mode=Full 03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/sort_pushdown/agg_expr_sorted.parquet]]}, projection=[x, v], output_ordering=[x@0 ASC NULLS LAST], file_type=parquet query II @@ -1017,7 +1017,7 @@ logical_plan 03)----TableScan: agg_expr_parquet projection=[x, v] physical_plan 01)SortExec: expr=[CAST(x@0 AS Int64) + 1 DESC], preserve_partitioning=[false] -02)--AggregateExec: mode=Single, gby=[x@0 as x], aggr=[sum(agg_expr_parquet.v)], ordering_mode=Sorted +02)--AggregateExec: mode=Single, gby=[x@0 as x], aggr=[sum(agg_expr_parquet.v)], group_clustering_mode=Full 03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/sort_pushdown/agg_expr_sorted.parquet]]}, projection=[x, v], output_ordering=[x@0 ASC NULLS LAST], file_type=parquet query II @@ -1043,7 +1043,7 @@ logical_plan 03)----TableScan: agg_expr_parquet projection=[x, v] physical_plan 01)SortExec: expr=[2 * CAST(x@0 AS Int64) ASC NULLS LAST], preserve_partitioning=[false] -02)--AggregateExec: mode=Single, gby=[x@0 as x], aggr=[sum(agg_expr_parquet.v)], ordering_mode=Sorted +02)--AggregateExec: mode=Single, gby=[x@0 as x], aggr=[sum(agg_expr_parquet.v)], group_clustering_mode=Full 03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/sort_pushdown/agg_expr_sorted.parquet]]}, projection=[x, v], output_ordering=[x@0 ASC NULLS LAST], file_type=parquet query II diff --git a/datafusion/sqllogictest/test_files/union.slt b/datafusion/sqllogictest/test_files/union.slt index d4776dd0c0ddb..643494cfddec1 100644 --- a/datafusion/sqllogictest/test_files/union.slt +++ b/datafusion/sqllogictest/test_files/union.slt @@ -694,7 +694,7 @@ logical_plan physical_plan 01)UnionExec 02)--ProjectionExec: expr=[Int64(1)@0 as a] -03)----AggregateExec: mode=SinglePartitioned, gby=[1 as Int64(1)], aggr=[], ordering_mode=Sorted +03)----AggregateExec: mode=SinglePartitioned, gby=[1 as Int64(1)], aggr=[], group_clustering_mode=Full 04)------PlaceholderRowExec 05)--ProjectionExec: expr=[2 as a] 06)----PlaceholderRowExec @@ -722,7 +722,7 @@ logical_plan physical_plan 01)UnionExec 02)--ProjectionExec: expr=[count(Int64(1))@1 as count, CAST(n@0 AS Int64) as n] -03)----AggregateExec: mode=SinglePartitioned, gby=[n@0 as n], aggr=[count(Int64(1))], ordering_mode=Sorted +03)----AggregateExec: mode=SinglePartitioned, gby=[n@0 as n], aggr=[count(Int64(1))], group_clustering_mode=Full 04)------ProjectionExec: expr=[5 as n] 05)--------PlaceholderRowExec 06)--ProjectionExec: expr=[1 as count, max(Int64(10))@0 as n] diff --git a/datafusion/sqllogictest/test_files/unnest.slt b/datafusion/sqllogictest/test_files/unnest.slt index a3385b81d70d1..b6feeaea05c50 100644 --- a/datafusion/sqllogictest/test_files/unnest.slt +++ b/datafusion/sqllogictest/test_files/unnest.slt @@ -988,9 +988,9 @@ logical_plan 08)--------------TableScan: range() projection=[value] physical_plan 01)ProjectionExec: expr=[array_agg(unnested.ar)@1 as array_agg(unnested.ar)] -02)--AggregateExec: mode=FinalPartitioned, gby=[generated_id@0 as generated_id], aggr=[array_agg(unnested.ar)], ordering_mode=Sorted +02)--AggregateExec: mode=FinalPartitioned, gby=[generated_id@0 as generated_id], aggr=[array_agg(unnested.ar)], group_clustering_mode=Full 03)----RepartitionExec: partitioning=Hash([generated_id@0], 4), input_partitions=4, preserve_order=true, sort_exprs=generated_id@0 ASC NULLS LAST -04)------AggregateExec: mode=Partial, gby=[generated_id@0 as generated_id], aggr=[array_agg(unnested.ar)], ordering_mode=Sorted +04)------AggregateExec: mode=Partial, gby=[generated_id@0 as generated_id], aggr=[array_agg(unnested.ar)], group_clustering_mode=Full 05)--------ProjectionExec: expr=[generated_id@0 as generated_id, __unnest_placeholder(make_array(range().value),depth=1)@1 as ar] 06)----------UnnestExec 07)------------ProjectionExec: expr=[row_number() ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING@1 as generated_id, make_array(value@0) as __unnest_placeholder(make_array(range().value))] diff --git a/datafusion/sqllogictest/test_files/window.slt b/datafusion/sqllogictest/test_files/window.slt index 6374cbf4f4b80..dc6c4dd8ce40c 100644 --- a/datafusion/sqllogictest/test_files/window.slt +++ b/datafusion/sqllogictest/test_files/window.slt @@ -276,7 +276,7 @@ physical_plan 03)----SortExec: expr=[b@0 ASC NULLS LAST], preserve_partitioning=[true] 04)------AggregateExec: mode=FinalPartitioned, gby=[b@0 as b], aggr=[max(d.a)] 05)--------RepartitionExec: partitioning=Hash([b@0], 4), input_partitions=4 -06)----------AggregateExec: mode=Partial, gby=[b@1 as b], aggr=[max(d.a)], ordering_mode=Sorted +06)----------AggregateExec: mode=Partial, gby=[b@1 as b], aggr=[max(d.a)], group_clustering_mode=Full 07)------------UnionExec 08)--------------ProjectionExec: expr=[1 as a, aa as b] 09)----------------PlaceholderRowExec @@ -357,7 +357,7 @@ logical_plan physical_plan 01)SortPreservingMergeExec: [b@0 ASC NULLS LAST] 02)--ProjectionExec: expr=[b@0 as b, max(d.a)@1 as max_a, max(d.seq)@2 as max(d.seq)] -03)----AggregateExec: mode=SinglePartitioned, gby=[b@2 as b], aggr=[max(d.a), max(d.seq)], ordering_mode=Sorted +03)----AggregateExec: mode=SinglePartitioned, gby=[b@2 as b], aggr=[max(d.a), max(d.seq)], group_clustering_mode=Full 04)------ProjectionExec: expr=[row_number() PARTITION BY [s.b] ORDER BY [s.a ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@2 as seq, a@0 as a, b@1 as b] 05)--------BoundedWindowAggExec: wdw=[row_number() PARTITION BY [s.b] ORDER BY [s.a ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: Field { "row_number() PARTITION BY [s.b] ORDER BY [s.a ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW": UInt64 }, frame: RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW], mode=[Sorted] 06)----------SortExec: expr=[b@1 ASC NULLS LAST, a@0 ASC NULLS LAST], preserve_partitioning=[true] diff --git a/docs/source/library-user-guide/upgrading/55.0.0.md b/docs/source/library-user-guide/upgrading/55.0.0.md index 51e2850377d64..57fbe5be50653 100644 --- a/docs/source/library-user-guide/upgrading/55.0.0.md +++ b/docs/source/library-user-guide/upgrading/55.0.0.md @@ -25,6 +25,27 @@ in this section pertains to features and changes that have already been merged to the main branch and are awaiting release in this version. +### Aggregate group-clustering APIs (Datadog backport) + +`AggregateExec::input_order_mode()` has been replaced by +`AggregateExec::group_clustering_mode()`. It returns a `GroupClusteringMode`: +`None`, `Partial(indices)`, or `Full`, corresponding to the previous aggregate +modes `Linear`, `PartiallySorted(indices)`, and `Sorted`. +`AggregateExec::compute_properties` now accepts `&GroupClusteringMode` in place of +`&InputOrderMode`. + +`GroupClusteringMode` describes the input's group-clustering guarantees, which +determine when groups can be emitted during aggregation. + +In `datafusion_physical_plan::aggregates::order`, `GroupOrdering`, +`GroupOrderingPartial`, and `GroupOrderingFull` have been renamed to +`GroupClustering`, `GroupClusteringPartial`, and `GroupClusteringFull`. +`GroupClustering::try_new` accepts `&GroupClusteringMode`. + +Aggregate plans now display `group_clustering_mode=Full` or +`group_clustering_mode=Partial(indices)` instead of `ordering_mode=Sorted` or +`ordering_mode=PartiallySorted(indices)`. + ### `DataFrame::fill_null` now borrows its arguments `DataFrame::fill_null` previously took its arguments by value: