Skip to content

Commit bdad988

Browse files
authored
fix: Error if both group_by and aggr is empty in AggregateExec::try_new() (#25786)
## Which issue does this PR close? <!-- We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123. --> - Closes #. ## Rationale for this change <!-- Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed. Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes. Please explain the problem you are trying to solve in terms of the user-visible behavior, rather than the implementation. For example, "The code in `foo.rs` doesn't handle nulls" is a symptom of the implementation. "COUNT(DISTINCT) returns wrong results when the column contains nulls" is the user-visible problem. --> If both group by expression and aggregate expression is empty, such aggregate is not valid. ``` AggregateExec { group_by_expr: vec![], aggr_expr: vec![], .... } ``` Now `AggregateExec::try_new()` with such invalid input would succeed, this PR adds a validation for it. (this case is not possible from SQL interface, but it can be built through raw `AggregateExec` API) ## What changes are included in this PR? <!-- There is no need to duplicate the description in the issue here, but it is sometimes worth providing a summary of the individual changes in this PR. --> 1. Error for this case 2. Update several optimizer UTs to avoid building such plan ## What is the testing strategy for this PR? <!-- We typically require tests for all PRs in order to: 1. Prevent the code from being accidentally broken by subsequent changes 3. Serve as another way to document the expected behavior of the code Briefly describe how this PR is tested, and point to the specific tests you added. For example: 'This new feature is covered by the `sqllogictest` cases added in `foo.slt`'. If this PR does not add tests, explain why. For example, if the change is already covered by existing tests, please mention it. You should also check the `codecov` bot reply on this PR to confirm the changed code is exercised. --> UT (this case it not able to test from SQL) ## Are there any user-facing changes? <!-- If there are user-facing changes then we may require documentation to be updated before approving the PR. If there are any breaking changes to public APIs, please add the `api change` label. --> no
1 parent f029e2b commit bdad988

5 files changed

Lines changed: 57 additions & 13 deletions

File tree

‎datafusion/core/tests/physical_optimizer/enforce_sorting.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2095,7 +2095,7 @@ async fn test_remove_unnecessary_sort3() -> Result<()> {
20952095
EnforceSortingTest::new(physical_plan.clone()).with_repartition_sorts(true);
20962096
assert_snapshot!(test.run(), @r"
20972097
Input Plan:
2098-
AggregateExec: mode=Final, gby=[], aggr=[]
2098+
AggregateExec: mode=Single, gby=[], aggr=[COUNT(*)]
20992099
SortPreservingMergeExec: [nullable_col@0 ASC, non_nullable_col@1 ASC]
21002100
SortExec: expr=[nullable_col@0 ASC, non_nullable_col@1 ASC], preserve_partitioning=[true]
21012101
RepartitionExec: partitioning=RoundRobinBatch(10), input_partitions=1, maintains_sort_order=true
@@ -2104,7 +2104,7 @@ async fn test_remove_unnecessary_sort3() -> Result<()> {
21042104
DataSourceExec: partitions=1, partition_sizes=[0]
21052105
21062106
Optimized Plan:
2107-
AggregateExec: mode=Final, gby=[], aggr=[]
2107+
AggregateExec: mode=Single, gby=[], aggr=[COUNT(*)]
21082108
DataSourceExec: partitions=1, partition_sizes=[0]
21092109
");
21102110

‎datafusion/core/tests/physical_optimizer/limited_distinct_aggregation.rs‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -532,14 +532,14 @@ fn test_no_group_by() -> Result<()> {
532532
let source = mock_data()?;
533533
let schema = source.schema();
534534

535-
// `SELECT <aggregate with no expressions> FROM DataSourceExec LIMIT 10;`, Single AggregateExec
535+
// `SELECT COUNT(*) FROM DataSourceExec LIMIT 10;`, Single AggregateExec
536536
let single_agg = AggregateExec::try_new(
537537
AggregateMode::Single,
538538
build_group_by(&schema, vec![]),
539-
vec![], /* aggr_expr */
540-
vec![], /* filter_expr */
541-
source, /* input */
542-
schema, /* input_schema */
539+
vec![Arc::new(TestAggregate::CountStar.count_expr(&schema))],
540+
vec![None],
541+
source,
542+
schema,
543543
)?;
544544
let limit_exec = LocalLimitExec::new(
545545
Arc::new(single_agg),
@@ -553,7 +553,7 @@ fn test_no_group_by() -> Result<()> {
553553
actual,
554554
@r"
555555
LocalLimitExec: fetch=10
556-
AggregateExec: mode=Single, gby=[], aggr=[]
556+
AggregateExec: mode=Single, gby=[], aggr=[COUNT(*)]
557557
DataSourceExec: partitions=1, partition_sizes=[1]
558558
"
559559
);

‎datafusion/core/tests/physical_optimizer/test_utils.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -378,10 +378,10 @@ pub fn aggregate_exec(input: Arc<dyn ExecutionPlan>) -> Arc<dyn ExecutionPlan> {
378378
let schema = input.schema();
379379
Arc::new(
380380
AggregateExec::try_new(
381-
AggregateMode::Final,
381+
AggregateMode::Single,
382382
PhysicalGroupBy::default(),
383-
vec![],
384-
vec![],
383+
vec![Arc::new(TestAggregate::CountStar.count_expr(&schema))],
384+
vec![None],
385385
input,
386386
schema,
387387
)

‎datafusion/physical-plan/src/aggregates/mod.rs‎

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -979,7 +979,14 @@ impl AggregateExec {
979979
&self.cache
980980
}
981981

982-
/// Create a new hash aggregate execution plan
982+
/// Create a new hash aggregate execution plan.
983+
///
984+
/// # Errors
985+
///
986+
/// Returns an internal error if the provided args can't build a valid aggregation:
987+
///
988+
/// - Both grouping and aggregate expressions are empty, without grouping sets.
989+
/// - The numbers of aggregate expressions and filter expressions differ.
983990
pub fn try_new(
984991
mode: AggregateMode,
985992
group_by: impl Into<Arc<PhysicalGroupBy>>,
@@ -1023,6 +1030,12 @@ impl AggregateExec {
10231030
let group_by = group_by.into();
10241031
let filter_expr = filter_expr.into();
10251032

1033+
if group_by.is_true_no_grouping() && aggr_expr.is_empty() {
1034+
return internal_err!(
1035+
"Grouping expressions and aggregate expressions cannot both be empty"
1036+
);
1037+
}
1038+
10261039
// Make sure arguments are consistent in size
10271040
assert_eq_or_internal_err!(
10281041
aggr_expr.len(),
@@ -3350,7 +3363,7 @@ mod tests {
33503363
use arrow::compute::{SortOptions, concat_batches};
33513364
use arrow::datatypes::{Int32Type, Int64Type};
33523365
use datafusion_common::test_util::{batches_to_sort_string, batches_to_string};
3353-
use datafusion_common::{DataFusionError, internal_err};
3366+
use datafusion_common::{DataFusionError, assert_contains, internal_err};
33543367
use datafusion_execution::config::SessionConfig;
33553368
use datafusion_execution::memory_pool::{
33563369
FairSpillPool, MemoryPool, PeakRecordingPool,
@@ -3414,6 +3427,31 @@ mod tests {
34143427
Ok(schema)
34153428
}
34163429

3430+
/// If both group_by and aggr is empty, return error since it's not a valid aggregate
3431+
#[test]
3432+
fn test_try_new_rejects_empty_aggregate() -> Result<()> {
3433+
let schema = create_test_schema()?;
3434+
for group_by in [
3435+
PhysicalGroupBy::default(),
3436+
PhysicalGroupBy::new_single(vec![]),
3437+
] {
3438+
let err = AggregateExec::try_new(
3439+
AggregateMode::Single,
3440+
group_by,
3441+
vec![],
3442+
vec![],
3443+
Arc::new(EmptyExec::new(Arc::clone(&schema))),
3444+
Arc::clone(&schema),
3445+
)
3446+
.unwrap_err();
3447+
assert_contains!(
3448+
err.to_string(),
3449+
"Grouping expressions and aggregate expressions cannot both be empty"
3450+
);
3451+
}
3452+
Ok(())
3453+
}
3454+
34173455
/// some mock data to aggregates
34183456
fn some_data() -> (Arc<Schema>, Vec<RecordBatch>) {
34193457
// define a schema.

‎datafusion/sqllogictest/test_files/grouping.slt‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,12 @@ SELECT COUNT(*) FROM test GROUP BY GROUPING SETS (());
310310
----
311311
2
312312

313+
# An empty grouping set is valid even without aggregate expressions.
314+
query I
315+
SELECT 1 FROM test GROUP BY GROUPING SETS (());
316+
----
317+
1
318+
313319
# grouping_sets_with_empty_set
314320
query I
315321
SELECT SUM(v1) FROM generate_series(10) AS t1(v1) GROUP BY GROUPING SETS(())

0 commit comments

Comments
 (0)