-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
mod.rs
2230 lines (2029 loc) · 77.9 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! Aggregates functionalities
use std::any::Any;
use std::sync::Arc;
use super::DisplayAs;
use crate::aggregates::{
no_grouping::AggregateStream, row_hash::GroupedHashAggregateStream,
topk_stream::GroupedTopKAggregateStream,
};
use crate::metrics::{ExecutionPlanMetricsSet, MetricsSet};
use crate::windows::get_ordered_partition_by_indices;
use crate::{
DisplayFormatType, Distribution, ExecutionPlan, InputOrderMode, Partitioning,
SendableRecordBatchStream, Statistics,
};
use arrow::array::ArrayRef;
use arrow::datatypes::{Field, Schema, SchemaRef};
use arrow::record_batch::RecordBatch;
use datafusion_common::stats::Precision;
use datafusion_common::{internal_err, not_impl_err, plan_err, DataFusionError, Result};
use datafusion_execution::TaskContext;
use datafusion_expr::Accumulator;
use datafusion_physical_expr::{
aggregate::is_order_sensitive,
equivalence::{collapse_lex_req, ProjectionMapping},
expressions::{Column, FirstValue, LastValue, Max, Min, UnKnownColumn},
physical_exprs_contains, reverse_order_bys, AggregateExpr, EquivalenceProperties,
LexOrdering, LexRequirement, PhysicalExpr, PhysicalSortExpr, PhysicalSortRequirement,
};
use itertools::Itertools;
mod group_values;
mod no_grouping;
mod order;
mod row_hash;
mod topk;
mod topk_stream;
pub use datafusion_expr::AggregateFunction;
pub use datafusion_physical_expr::expressions::create_aggregate_expr;
/// Hash aggregate modes
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum AggregateMode {
/// Partial aggregate that can be applied in parallel across input partitions
Partial,
/// Final aggregate that produces a single partition of output
Final,
/// Final aggregate that works on pre-partitioned data.
///
/// This requires the invariant that all rows with a particular
/// grouping key are in the same partitions, such as is the case
/// with Hash repartitioning on the group keys. If a group key is
/// duplicated, duplicate groups would be produced
FinalPartitioned,
/// Applies the entire logical aggregation operation in a single operator,
/// as opposed to Partial / Final modes which apply the logical aggregation using
/// two operators.
/// This mode requires tha the input is a single partition (like Final)
Single,
/// Applies the entire logical aggregation operation in a single operator,
/// as opposed to Partial / Final modes which apply the logical aggregation using
/// two operators.
/// This mode requires tha the input is partitioned by group key (like FinalPartitioned)
SinglePartitioned,
}
impl AggregateMode {
/// Checks whether this aggregation step describes a "first stage" calculation.
/// In other words, its input is not another aggregation result and the
/// `merge_batch` method will not be called for these modes.
pub fn is_first_stage(&self) -> bool {
match self {
AggregateMode::Partial
| AggregateMode::Single
| AggregateMode::SinglePartitioned => true,
AggregateMode::Final | AggregateMode::FinalPartitioned => false,
}
}
}
/// Represents `GROUP BY` clause in the plan (including the more general GROUPING SET)
/// In the case of a simple `GROUP BY a, b` clause, this will contain the expression [a, b]
/// and a single group [false, false].
/// In the case of `GROUP BY GROUPING SET/CUBE/ROLLUP` the planner will expand the expression
/// into multiple groups, using null expressions to align each group.
/// For example, with a group by clause `GROUP BY GROUPING SET ((a,b),(a),(b))` the planner should
/// create a `PhysicalGroupBy` like
/// ```text
/// PhysicalGroupBy {
/// expr: [(col(a), a), (col(b), b)],
/// null_expr: [(NULL, a), (NULL, b)],
/// groups: [
/// [false, false], // (a,b)
/// [false, true], // (a) <=> (a, NULL)
/// [true, false] // (b) <=> (NULL, b)
/// ]
/// }
/// ```
#[derive(Clone, Debug, Default)]
pub struct PhysicalGroupBy {
/// Distinct (Physical Expr, Alias) in the grouping set
expr: Vec<(Arc<dyn PhysicalExpr>, String)>,
/// Corresponding NULL expressions for expr
null_expr: Vec<(Arc<dyn PhysicalExpr>, String)>,
/// Null mask for each group in this grouping set. Each group is
/// composed of either one of the group expressions in expr or a null
/// expression in null_expr. If `groups[i][j]` is true, then the the
/// j-th expression in the i-th group is NULL, otherwise it is `expr[j]`.
groups: Vec<Vec<bool>>,
}
impl PhysicalGroupBy {
/// Create a new `PhysicalGroupBy`
pub fn new(
expr: Vec<(Arc<dyn PhysicalExpr>, String)>,
null_expr: Vec<(Arc<dyn PhysicalExpr>, String)>,
groups: Vec<Vec<bool>>,
) -> Self {
Self {
expr,
null_expr,
groups,
}
}
/// Create a GROUPING SET with only a single group. This is the "standard"
/// case when building a plan from an expression such as `GROUP BY a,b,c`
pub fn new_single(expr: Vec<(Arc<dyn PhysicalExpr>, String)>) -> Self {
let num_exprs = expr.len();
Self {
expr,
null_expr: vec![],
groups: vec![vec![false; num_exprs]],
}
}
/// Returns true if this GROUP BY contains NULL expressions
pub fn contains_null(&self) -> bool {
self.groups.iter().flatten().any(|is_null| *is_null)
}
/// Returns the group expressions
pub fn expr(&self) -> &[(Arc<dyn PhysicalExpr>, String)] {
&self.expr
}
/// Returns the null expressions
pub fn null_expr(&self) -> &[(Arc<dyn PhysicalExpr>, String)] {
&self.null_expr
}
/// Returns the group null masks
pub fn groups(&self) -> &[Vec<bool>] {
&self.groups
}
/// Returns true if this `PhysicalGroupBy` has no group expressions
pub fn is_empty(&self) -> bool {
self.expr.is_empty()
}
/// Check whether grouping set is single group
pub fn is_single(&self) -> bool {
self.null_expr.is_empty()
}
/// Calculate GROUP BY expressions according to input schema.
pub fn input_exprs(&self) -> Vec<Arc<dyn PhysicalExpr>> {
self.expr
.iter()
.map(|(expr, _alias)| expr.clone())
.collect()
}
/// Return grouping expressions as they occur in the output schema.
pub fn output_exprs(&self) -> Vec<Arc<dyn PhysicalExpr>> {
self.expr
.iter()
.enumerate()
.map(|(index, (_, name))| Arc::new(Column::new(name, index)) as _)
.collect()
}
}
impl PartialEq for PhysicalGroupBy {
fn eq(&self, other: &PhysicalGroupBy) -> bool {
self.expr.len() == other.expr.len()
&& self
.expr
.iter()
.zip(other.expr.iter())
.all(|((expr1, name1), (expr2, name2))| expr1.eq(expr2) && name1 == name2)
&& self.null_expr.len() == other.null_expr.len()
&& self
.null_expr
.iter()
.zip(other.null_expr.iter())
.all(|((expr1, name1), (expr2, name2))| expr1.eq(expr2) && name1 == name2)
&& self.groups == other.groups
}
}
enum StreamType {
AggregateStream(AggregateStream),
GroupedHash(GroupedHashAggregateStream),
GroupedPriorityQueue(GroupedTopKAggregateStream),
}
impl From<StreamType> for SendableRecordBatchStream {
fn from(stream: StreamType) -> Self {
match stream {
StreamType::AggregateStream(stream) => Box::pin(stream),
StreamType::GroupedHash(stream) => Box::pin(stream),
StreamType::GroupedPriorityQueue(stream) => Box::pin(stream),
}
}
}
/// Hash aggregate execution plan
#[derive(Debug)]
pub struct AggregateExec {
/// Aggregation mode (full, partial)
mode: AggregateMode,
/// Group by expressions
group_by: PhysicalGroupBy,
/// Aggregate expressions
aggr_expr: Vec<Arc<dyn AggregateExpr>>,
/// FILTER (WHERE clause) expression for each aggregate expression
filter_expr: Vec<Option<Arc<dyn PhysicalExpr>>>,
/// Set if the output of this aggregation is truncated by a upstream sort/limit clause
limit: Option<usize>,
/// Input plan, could be a partial aggregate or the input to the aggregate
pub input: Arc<dyn ExecutionPlan>,
/// Schema after the aggregate is applied
schema: SchemaRef,
/// Input schema before any aggregation is applied. For partial aggregate this will be the
/// same as input.schema() but for the final aggregate it will be the same as the input
/// to the partial aggregate, i.e., partial and final aggregates have same `input_schema`.
/// We need the input schema of partial aggregate to be able to deserialize aggregate
/// expressions from protobuf for final aggregate.
pub input_schema: SchemaRef,
/// The mapping used to normalize expressions like Partitioning and
/// PhysicalSortExpr that maps input to output
projection_mapping: ProjectionMapping,
/// Execution metrics
metrics: ExecutionPlanMetricsSet,
required_input_ordering: Option<LexRequirement>,
/// Describes how the input is ordered relative to the group by columns
input_order_mode: InputOrderMode,
/// Describe how the output is ordered
output_ordering: Option<LexOrdering>,
}
impl AggregateExec {
/// Create a new hash aggregate execution plan
pub fn try_new(
mode: AggregateMode,
group_by: PhysicalGroupBy,
aggr_expr: Vec<Arc<dyn AggregateExpr>>,
filter_expr: Vec<Option<Arc<dyn PhysicalExpr>>>,
input: Arc<dyn ExecutionPlan>,
input_schema: SchemaRef,
) -> Result<Self> {
let schema = create_schema(
&input.schema(),
&group_by.expr,
&aggr_expr,
group_by.contains_null(),
mode,
)?;
let schema = Arc::new(schema);
AggregateExec::try_new_with_schema(
mode,
group_by,
aggr_expr,
filter_expr,
input,
input_schema,
schema,
)
}
/// Create a new hash aggregate execution plan with the given schema.
/// This constructor isn't part of the public API, it is used internally
/// by Datafusion to enforce schema consistency during when re-creating
/// `AggregateExec`s inside optimization rules. Schema field names of an
/// `AggregateExec` depends on the names of aggregate expressions. Since
/// a rule may re-write aggregate expressions (e.g. reverse them) during
/// initialization, field names may change inadvertently if one re-creates
/// the schema in such cases.
#[allow(clippy::too_many_arguments)]
fn try_new_with_schema(
mode: AggregateMode,
group_by: PhysicalGroupBy,
mut aggr_expr: Vec<Arc<dyn AggregateExpr>>,
filter_expr: Vec<Option<Arc<dyn PhysicalExpr>>>,
input: Arc<dyn ExecutionPlan>,
input_schema: SchemaRef,
schema: SchemaRef,
) -> Result<Self> {
// Make sure arguments are consistent in size
if aggr_expr.len() != filter_expr.len() {
return internal_err!("Inconsistent aggregate expr: {:?} and filter expr: {:?} for AggregateExec, their size should match", aggr_expr, filter_expr);
}
let input_eq_properties = input.equivalence_properties();
// Get GROUP BY expressions:
let groupby_exprs = group_by.input_exprs();
// If existing ordering satisfies a prefix of the GROUP BY expressions,
// prefix requirements with this section. In this case, aggregation will
// work more efficiently.
let indices = get_ordered_partition_by_indices(&groupby_exprs, &input);
let mut new_requirement = indices
.iter()
.map(|&idx| PhysicalSortRequirement {
expr: groupby_exprs[idx].clone(),
options: None,
})
.collect::<Vec<_>>();
let req = get_aggregate_exprs_requirement(
&new_requirement,
&mut aggr_expr,
&group_by,
&input_eq_properties,
&mode,
)?;
new_requirement.extend(req);
new_requirement = collapse_lex_req(new_requirement);
let input_order_mode =
if indices.len() == groupby_exprs.len() && !indices.is_empty() {
InputOrderMode::Sorted
} else if !indices.is_empty() {
InputOrderMode::PartiallySorted(indices)
} else {
InputOrderMode::Linear
};
// construct a map from the input expression to the output expression of the Aggregation group by
let projection_mapping =
ProjectionMapping::try_new(&group_by.expr, &input.schema())?;
let required_input_ordering =
(!new_requirement.is_empty()).then_some(new_requirement);
let aggregate_eqs =
input_eq_properties.project(&projection_mapping, schema.clone());
let output_ordering = aggregate_eqs.oeq_class().output_ordering();
Ok(AggregateExec {
mode,
group_by,
aggr_expr,
filter_expr,
input,
schema,
input_schema,
projection_mapping,
metrics: ExecutionPlanMetricsSet::new(),
required_input_ordering,
limit: None,
input_order_mode,
output_ordering,
})
}
/// Aggregation mode (full, partial)
pub fn mode(&self) -> &AggregateMode {
&self.mode
}
/// Set the `limit` of this AggExec
pub fn with_limit(mut self, limit: Option<usize>) -> Self {
self.limit = limit;
self
}
/// Grouping expressions
pub fn group_expr(&self) -> &PhysicalGroupBy {
&self.group_by
}
/// Grouping expressions as they occur in the output schema
pub fn output_group_expr(&self) -> Vec<Arc<dyn PhysicalExpr>> {
self.group_by.output_exprs()
}
/// Aggregate expressions
pub fn aggr_expr(&self) -> &[Arc<dyn AggregateExpr>] {
&self.aggr_expr
}
/// FILTER (WHERE clause) expression for each aggregate expression
pub fn filter_expr(&self) -> &[Option<Arc<dyn PhysicalExpr>>] {
&self.filter_expr
}
/// Input plan
pub fn input(&self) -> &Arc<dyn ExecutionPlan> {
&self.input
}
/// Get the input schema before any aggregates are applied
pub fn input_schema(&self) -> SchemaRef {
self.input_schema.clone()
}
/// number of rows soft limit of the AggregateExec
pub fn limit(&self) -> Option<usize> {
self.limit
}
fn execute_typed(
&self,
partition: usize,
context: Arc<TaskContext>,
) -> Result<StreamType> {
// no group by at all
if self.group_by.expr.is_empty() {
return Ok(StreamType::AggregateStream(AggregateStream::new(
self, context, partition,
)?));
}
// grouping by an expression that has a sort/limit upstream
if let Some(limit) = self.limit {
if !self.is_unordered_unfiltered_group_by_distinct() {
return Ok(StreamType::GroupedPriorityQueue(
GroupedTopKAggregateStream::new(self, context, partition, limit)?,
));
}
}
// grouping by something else and we need to just materialize all results
Ok(StreamType::GroupedHash(GroupedHashAggregateStream::new(
self, context, partition,
)?))
}
/// Finds the DataType and SortDirection for this Aggregate, if there is one
pub fn get_minmax_desc(&self) -> Option<(Field, bool)> {
let agg_expr = self.aggr_expr.iter().exactly_one().ok()?;
if let Some(max) = agg_expr.as_any().downcast_ref::<Max>() {
Some((max.field().ok()?, true))
} else if let Some(min) = agg_expr.as_any().downcast_ref::<Min>() {
Some((min.field().ok()?, false))
} else {
None
}
}
pub fn group_by(&self) -> &PhysicalGroupBy {
&self.group_by
}
/// true, if this Aggregate has a group-by with no required or explicit ordering,
/// no filtering and no aggregate expressions
/// This method qualifies the use of the LimitedDistinctAggregation rewrite rule
/// on an AggregateExec.
pub fn is_unordered_unfiltered_group_by_distinct(&self) -> bool {
// ensure there is a group by
if self.group_by().is_empty() {
return false;
}
// ensure there are no aggregate expressions
if !self.aggr_expr().is_empty() {
return false;
}
// ensure there are no filters on aggregate expressions; the above check
// may preclude this case
if self.filter_expr().iter().any(|e| e.is_some()) {
return false;
}
// ensure there are no order by expressions
if self.aggr_expr().iter().any(|e| e.order_bys().is_some()) {
return false;
}
// ensure there is no output ordering; can this rule be relaxed?
if self.output_ordering().is_some() {
return false;
}
// ensure no ordering is required on the input
if self.required_input_ordering()[0].is_some() {
return false;
}
true
}
}
impl DisplayAs for AggregateExec {
fn fmt_as(
&self,
t: DisplayFormatType,
f: &mut std::fmt::Formatter,
) -> std::fmt::Result {
match t {
DisplayFormatType::Default | DisplayFormatType::Verbose => {
write!(f, "AggregateExec: mode={:?}", self.mode)?;
let g: Vec<String> = if self.group_by.is_single() {
self.group_by
.expr
.iter()
.map(|(e, alias)| {
let e = e.to_string();
if &e != alias {
format!("{e} as {alias}")
} else {
e
}
})
.collect()
} else {
self.group_by
.groups
.iter()
.map(|group| {
let terms = group
.iter()
.enumerate()
.map(|(idx, is_null)| {
if *is_null {
let (e, alias) = &self.group_by.null_expr[idx];
let e = e.to_string();
if &e != alias {
format!("{e} as {alias}")
} else {
e
}
} else {
let (e, alias) = &self.group_by.expr[idx];
let e = e.to_string();
if &e != alias {
format!("{e} as {alias}")
} else {
e
}
}
})
.collect::<Vec<String>>()
.join(", ");
format!("({terms})")
})
.collect()
};
write!(f, ", gby=[{}]", g.join(", "))?;
let a: Vec<String> = self
.aggr_expr
.iter()
.map(|agg| agg.name().to_string())
.collect();
write!(f, ", aggr=[{}]", a.join(", "))?;
if let Some(limit) = self.limit {
write!(f, ", lim=[{limit}]")?;
}
if self.input_order_mode != InputOrderMode::Linear {
write!(f, ", ordering_mode={:?}", self.input_order_mode)?;
}
}
}
Ok(())
}
}
impl ExecutionPlan for AggregateExec {
/// Return a reference to Any that can be used for down-casting
fn as_any(&self) -> &dyn Any {
self
}
fn schema(&self) -> SchemaRef {
self.schema.clone()
}
/// Get the output partitioning of this plan
fn output_partitioning(&self) -> Partitioning {
let input_partition = self.input.output_partitioning();
if self.mode.is_first_stage() {
// First stage aggregation will not change the output partitioning,
// but needs to respect aliases (e.g. mapping in the GROUP BY
// expression).
let input_eq_properties = self.input.equivalence_properties();
// First stage Aggregation will not change the output partitioning but need to respect the Alias
let input_partition = self.input.output_partitioning();
if let Partitioning::Hash(exprs, part) = input_partition {
let normalized_exprs = exprs
.into_iter()
.map(|expr| {
input_eq_properties
.project_expr(&expr, &self.projection_mapping)
.unwrap_or_else(|| {
Arc::new(UnKnownColumn::new(&expr.to_string()))
})
})
.collect();
return Partitioning::Hash(normalized_exprs, part);
}
}
// Final Aggregation's output partitioning is the same as its real input
input_partition
}
/// Specifies whether this plan generates an infinite stream of records.
/// If the plan does not support pipelining, but its input(s) are
/// infinite, returns an error to indicate this.
fn unbounded_output(&self, children: &[bool]) -> Result<bool> {
if children[0] {
if self.input_order_mode == InputOrderMode::Linear {
// Cannot run without breaking pipeline.
plan_err!(
"Aggregate Error: `GROUP BY` clauses with columns without ordering and GROUPING SETS are not supported for unbounded inputs."
)
} else {
Ok(true)
}
} else {
Ok(false)
}
}
fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {
self.output_ordering.as_deref()
}
fn required_input_distribution(&self) -> Vec<Distribution> {
match &self.mode {
AggregateMode::Partial => {
vec![Distribution::UnspecifiedDistribution]
}
AggregateMode::FinalPartitioned | AggregateMode::SinglePartitioned => {
vec![Distribution::HashPartitioned(self.output_group_expr())]
}
AggregateMode::Final | AggregateMode::Single => {
vec![Distribution::SinglePartition]
}
}
}
fn required_input_ordering(&self) -> Vec<Option<LexRequirement>> {
vec![self.required_input_ordering.clone()]
}
fn equivalence_properties(&self) -> EquivalenceProperties {
self.input
.equivalence_properties()
.project(&self.projection_mapping, self.schema())
}
fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
vec![self.input.clone()]
}
fn with_new_children(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
let mut me = AggregateExec::try_new_with_schema(
self.mode,
self.group_by.clone(),
self.aggr_expr.clone(),
self.filter_expr.clone(),
children[0].clone(),
self.input_schema.clone(),
self.schema.clone(),
//self.original_schema.clone(),
)?;
me.limit = self.limit;
Ok(Arc::new(me))
}
fn execute(
&self,
partition: usize,
context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
self.execute_typed(partition, context)
.map(|stream| stream.into())
}
fn metrics(&self) -> Option<MetricsSet> {
Some(self.metrics.clone_inner())
}
fn statistics(&self) -> Result<Statistics> {
// TODO stats: group expressions:
// - once expressions will be able to compute their own stats, use it here
// - case where we group by on a column for which with have the `distinct` stat
// TODO stats: aggr expression:
// - aggregations somtimes also preserve invariants such as min, max...
let column_statistics = Statistics::unknown_column(&self.schema());
match self.mode {
AggregateMode::Final | AggregateMode::FinalPartitioned
if self.group_by.expr.is_empty() =>
{
Ok(Statistics {
num_rows: Precision::Exact(1),
column_statistics,
total_byte_size: Precision::Absent,
})
}
_ => {
// When the input row count is 0 or 1, we can adopt that statistic keeping its reliability.
// When it is larger than 1, we degrade the precision since it may decrease after aggregation.
let num_rows = if let Some(value) =
self.input().statistics()?.num_rows.get_value()
{
if *value > 1 {
self.input().statistics()?.num_rows.to_inexact()
} else if *value == 0 {
// Aggregation on an empty table creates a null row.
self.input()
.statistics()?
.num_rows
.add(&Precision::Exact(1))
} else {
// num_rows = 1 case
self.input().statistics()?.num_rows
}
} else {
Precision::Absent
};
Ok(Statistics {
num_rows,
column_statistics,
total_byte_size: Precision::Absent,
})
}
}
}
}
fn create_schema(
input_schema: &Schema,
group_expr: &[(Arc<dyn PhysicalExpr>, String)],
aggr_expr: &[Arc<dyn AggregateExpr>],
contains_null_expr: bool,
mode: AggregateMode,
) -> Result<Schema> {
let mut fields = Vec::with_capacity(group_expr.len() + aggr_expr.len());
for (expr, name) in group_expr {
fields.push(Field::new(
name,
expr.data_type(input_schema)?,
// In cases where we have multiple grouping sets, we will use NULL expressions in
// order to align the grouping sets. So the field must be nullable even if the underlying
// schema field is not.
contains_null_expr || expr.nullable(input_schema)?,
))
}
match mode {
AggregateMode::Partial => {
// in partial mode, the fields of the accumulator's state
for expr in aggr_expr {
fields.extend(expr.state_fields()?.iter().cloned())
}
}
AggregateMode::Final
| AggregateMode::FinalPartitioned
| AggregateMode::Single
| AggregateMode::SinglePartitioned => {
// in final mode, the field with the final result of the accumulator
for expr in aggr_expr {
fields.push(expr.field()?)
}
}
}
Ok(Schema::new(fields))
}
fn group_schema(schema: &Schema, group_count: usize) -> SchemaRef {
let group_fields = schema.fields()[0..group_count].to_vec();
Arc::new(Schema::new(group_fields))
}
/// Determines the lexical ordering requirement for an aggregate expression.
///
/// # Parameters
///
/// - `aggr_expr`: A reference to an `Arc<dyn AggregateExpr>` representing the
/// aggregate expression.
/// - `group_by`: A reference to a `PhysicalGroupBy` instance representing the
/// physical GROUP BY expression.
/// - `agg_mode`: A reference to an `AggregateMode` instance representing the
/// mode of aggregation.
///
/// # Returns
///
/// A `LexOrdering` instance indicating the lexical ordering requirement for
/// the aggregate expression.
fn get_aggregate_expr_req(
aggr_expr: &Arc<dyn AggregateExpr>,
group_by: &PhysicalGroupBy,
agg_mode: &AggregateMode,
) -> LexOrdering {
// If the aggregation function is not order sensitive, or the aggregation
// is performing a "second stage" calculation, or all aggregate function
// requirements are inside the GROUP BY expression, then ignore the ordering
// requirement.
if !is_order_sensitive(aggr_expr) || !agg_mode.is_first_stage() {
return vec![];
}
let mut req = aggr_expr.order_bys().unwrap_or_default().to_vec();
// In non-first stage modes, we accumulate data (using `merge_batch`) from
// different partitions (i.e. merge partial results). During this merge, we
// consider the ordering of each partial result. Hence, we do not need to
// use the ordering requirement in such modes as long as partial results are
// generated with the correct ordering.
if group_by.is_single() {
// Remove all orderings that occur in the group by. These requirements
// will definitely be satisfied -- Each group by expression will have
// distinct values per group, hence all requirements are satisfied.
let physical_exprs = group_by.input_exprs();
req.retain(|sort_expr| {
!physical_exprs_contains(&physical_exprs, &sort_expr.expr)
});
}
req
}
/// Computes the finer ordering for between given existing ordering requirement
/// of aggregate expression.
///
/// # Parameters
///
/// * `existing_req` - The existing lexical ordering that needs refinement.
/// * `aggr_expr` - A reference to an aggregate expression trait object.
/// * `group_by` - Information about the physical grouping (e.g group by expression).
/// * `eq_properties` - Equivalence properties relevant to the computation.
/// * `agg_mode` - The mode of aggregation (e.g., Partial, Final, etc.).
///
/// # Returns
///
/// An `Option<LexOrdering>` representing the computed finer lexical ordering,
/// or `None` if there is no finer ordering; e.g. the existing requirement and
/// the aggregator requirement is incompatible.
fn finer_ordering(
existing_req: &LexOrdering,
aggr_expr: &Arc<dyn AggregateExpr>,
group_by: &PhysicalGroupBy,
eq_properties: &EquivalenceProperties,
agg_mode: &AggregateMode,
) -> Option<LexOrdering> {
let aggr_req = get_aggregate_expr_req(aggr_expr, group_by, agg_mode);
eq_properties.get_finer_ordering(existing_req, &aggr_req)
}
/// Concatenates the given slices.
fn concat_slices<T: Clone>(lhs: &[T], rhs: &[T]) -> Vec<T> {
[lhs, rhs].concat()
}
/// Get the common requirement that satisfies all the aggregate expressions.
///
/// # Parameters
///
/// - `aggr_exprs`: A slice of `Arc<dyn AggregateExpr>` containing all the
/// aggregate expressions.
/// - `group_by`: A reference to a `PhysicalGroupBy` instance representing the
/// physical GROUP BY expression.
/// - `eq_properties`: A reference to an `EquivalenceProperties` instance
/// representing equivalence properties for ordering.
/// - `agg_mode`: A reference to an `AggregateMode` instance representing the
/// mode of aggregation.
///
/// # Returns
///
/// A `LexRequirement` instance, which is the requirement that satisfies all the
/// aggregate requirements. Returns an error in case of conflicting requirements.
fn get_aggregate_exprs_requirement(
prefix_requirement: &[PhysicalSortRequirement],
aggr_exprs: &mut [Arc<dyn AggregateExpr>],
group_by: &PhysicalGroupBy,
eq_properties: &EquivalenceProperties,
agg_mode: &AggregateMode,
) -> Result<LexRequirement> {
let mut requirement = vec![];
for aggr_expr in aggr_exprs.iter_mut() {
let aggr_req = aggr_expr.order_bys().unwrap_or(&[]);
let reverse_aggr_req = reverse_order_bys(aggr_req);
let aggr_req = PhysicalSortRequirement::from_sort_exprs(aggr_req);
let reverse_aggr_req =
PhysicalSortRequirement::from_sort_exprs(&reverse_aggr_req);
if let Some(first_value) = aggr_expr.as_any().downcast_ref::<FirstValue>() {
let mut first_value = first_value.clone();
if eq_properties.ordering_satisfy_requirement(&concat_slices(
prefix_requirement,
&aggr_req,
)) {
first_value = first_value.with_requirement_satisfied(true);
*aggr_expr = Arc::new(first_value) as _;
} else if eq_properties.ordering_satisfy_requirement(&concat_slices(
prefix_requirement,
&reverse_aggr_req,
)) {
// Converting to LAST_VALUE enables more efficient execution
// given the existing ordering:
let mut last_value = first_value.convert_to_last();
last_value = last_value.with_requirement_satisfied(true);
*aggr_expr = Arc::new(last_value) as _;
} else {
// Requirement is not satisfied with existing ordering.
first_value = first_value.with_requirement_satisfied(false);
*aggr_expr = Arc::new(first_value) as _;
}
continue;
}
if let Some(last_value) = aggr_expr.as_any().downcast_ref::<LastValue>() {
let mut last_value = last_value.clone();
if eq_properties.ordering_satisfy_requirement(&concat_slices(
prefix_requirement,
&aggr_req,
)) {
last_value = last_value.with_requirement_satisfied(true);
*aggr_expr = Arc::new(last_value) as _;
} else if eq_properties.ordering_satisfy_requirement(&concat_slices(
prefix_requirement,
&reverse_aggr_req,
)) {
// Converting to FIRST_VALUE enables more efficient execution
// given the existing ordering:
let mut first_value = last_value.convert_to_first();
first_value = first_value.with_requirement_satisfied(true);
*aggr_expr = Arc::new(first_value) as _;
} else {
// Requirement is not satisfied with existing ordering.
last_value = last_value.with_requirement_satisfied(false);
*aggr_expr = Arc::new(last_value) as _;
}
continue;
}
if let Some(finer_ordering) =
finer_ordering(&requirement, aggr_expr, group_by, eq_properties, agg_mode)
{
if eq_properties.ordering_satisfy(&finer_ordering) {
// Requirement is satisfied by existing ordering
requirement = finer_ordering;
continue;
}
}
if let Some(reverse_aggr_expr) = aggr_expr.reverse_expr() {
if let Some(finer_ordering) = finer_ordering(
&requirement,
&reverse_aggr_expr,
group_by,
eq_properties,
agg_mode,
) {
if eq_properties.ordering_satisfy(&finer_ordering) {
// Reverse requirement is satisfied by exiting ordering.
// Hence reverse the aggregator
requirement = finer_ordering;
*aggr_expr = reverse_aggr_expr;
continue;
}
}
}
if let Some(finer_ordering) =
finer_ordering(&requirement, aggr_expr, group_by, eq_properties, agg_mode)
{
// There is a requirement that both satisfies existing requirement and current
// aggregate requirement. Use updated requirement
requirement = finer_ordering;
continue;
}
if let Some(reverse_aggr_expr) = aggr_expr.reverse_expr() {
if let Some(finer_ordering) = finer_ordering(
&requirement,
&reverse_aggr_expr,
group_by,
eq_properties,
agg_mode,