-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
mod.rs
2158 lines (1961 loc) · 75.7 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, get_window_mode, PartitionSearchMode,
};
use crate::{
DisplayFormatType, Distribution, ExecutionPlan, 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::{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,
expressions::{Column, Max, Min, UnKnownColumn},
physical_exprs_contains, reverse_order_bys, AggregateExpr, EquivalenceProperties,
LexOrdering, LexRequirement, PhysicalExpr, PhysicalSortExpr, PhysicalSortRequirement,
};
use itertools::{izip, Itertools};
mod group_values;
mod no_grouping;
mod order;
mod row_hash;
mod topk;
mod topk_stream;
pub use datafusion_expr::AggregateFunction;
use datafusion_physical_expr::equivalence::ProjectionMapping;
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,
}
}
}
/// Group By expression modes
///
/// `PartiallyOrdered` and `FullyOrdered` are used to reason about
/// when certain group by keys will never again be seen (and thus can
/// be emitted by the grouping operator).
///
/// Specifically, each distinct combination of the relevant columns
/// are contiguous in the input, and once a new combination is seen
/// previous combinations are guaranteed never to appear again
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GroupByOrderMode {
/// The input is known to be ordered by a preset (prefix but
/// possibly reordered) of the expressions in the `GROUP BY` clause.
///
/// For example, if the input is ordered by `a, b, c` and we group
/// by `b, a, d`, `PartiallyOrdered` means a subset of group `b,
/// a, d` defines a preset for the existing ordering, in this case
/// `a, b`.
PartiallyOrdered,
/// The input is known to be ordered by *all* the expressions in the
/// `GROUP BY` clause.
///
/// For example, if the input is ordered by `a, b, c, d` and we group by b, a,
/// `Ordered` means that all of the of group by expressions appear
/// as a preset for the existing ordering, in this case `a, b`.
FullyOrdered,
}
/// 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>>>,
/// (ORDER BY clause) expression for each aggregate expression
order_by_expr: Vec<Option<LexOrdering>>,
/// 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>,
partition_search_mode: PartitionSearchMode,
output_ordering: Option<LexOrdering>,
}
/// This function returns the ordering requirement of the first non-reversible
/// order-sensitive aggregate function such as ARRAY_AGG. This requirement serves
/// as the initial requirement while calculating the finest requirement among all
/// aggregate functions. If this function returns `None`, it means there is no
/// hard ordering requirement for the aggregate functions (in terms of direction).
/// Then, we can generate two alternative requirements with opposite directions.
fn get_init_req(
aggr_expr: &[Arc<dyn AggregateExpr>],
order_by_expr: &[Option<LexOrdering>],
) -> Option<LexOrdering> {
for (aggr_expr, fn_reqs) in aggr_expr.iter().zip(order_by_expr.iter()) {
// If the aggregation function is a non-reversible order-sensitive function
// and there is a hard requirement, choose first such requirement:
if is_order_sensitive(aggr_expr)
&& aggr_expr.reverse_expr().is_none()
&& fn_reqs.is_some()
{
return fn_reqs.clone();
}
}
None
}
/// This function gets the finest ordering requirement among all the aggregation
/// functions. If requirements are conflicting, (i.e. we can not compute the
/// aggregations in a single [`AggregateExec`]), the function returns an error.
fn get_finest_requirement(
aggr_expr: &mut [Arc<dyn AggregateExpr>],
order_by_expr: &mut [Option<LexOrdering>],
eq_properties: &EquivalenceProperties,
) -> Result<Option<LexOrdering>> {
// First, we check if all the requirements are satisfied by the existing
// ordering. If so, we return `None` to indicate this.
let mut all_satisfied = true;
for (aggr_expr, fn_req) in aggr_expr.iter_mut().zip(order_by_expr.iter_mut()) {
if eq_properties.ordering_satisfy(fn_req.as_deref().unwrap_or(&[])) {
continue;
}
if let Some(reverse) = aggr_expr.reverse_expr() {
let reverse_req = fn_req.as_ref().map(|item| reverse_order_bys(item));
if eq_properties.ordering_satisfy(reverse_req.as_deref().unwrap_or(&[])) {
// We need to update `aggr_expr` with its reverse since only its
// reverse requirement is compatible with the existing requirements:
*aggr_expr = reverse;
*fn_req = reverse_req;
continue;
}
}
// Requirement is not satisfied:
all_satisfied = false;
}
if all_satisfied {
// All of the requirements are already satisfied.
return Ok(None);
}
let mut finest_req = get_init_req(aggr_expr, order_by_expr);
for (aggr_expr, fn_req) in aggr_expr.iter_mut().zip(order_by_expr.iter_mut()) {
let Some(fn_req) = fn_req else {
continue;
};
if let Some(finest_req) = &mut finest_req {
if let Some(finer) = eq_properties.get_finer_ordering(finest_req, fn_req) {
*finest_req = finer;
continue;
}
// If an aggregate function is reversible, analyze whether its reverse
// direction is compatible with existing requirements:
if let Some(reverse) = aggr_expr.reverse_expr() {
let fn_req_reverse = reverse_order_bys(fn_req);
if let Some(finer) =
eq_properties.get_finer_ordering(finest_req, &fn_req_reverse)
{
// We need to update `aggr_expr` with its reverse, since only its
// reverse requirement is compatible with existing requirements:
*aggr_expr = reverse;
*finest_req = finer;
*fn_req = fn_req_reverse;
continue;
}
}
// If neither of the requirements satisfy the other, this means
// requirements are conflicting. Currently, we do not support
// conflicting requirements.
return not_impl_err!(
"Conflicting ordering requirements in aggregate functions is not supported"
);
} else {
finest_req = Some(fn_req.clone());
}
}
Ok(finest_req)
}
/// Calculates search_mode for the aggregation
fn get_aggregate_search_mode(
group_by: &PhysicalGroupBy,
input: &Arc<dyn ExecutionPlan>,
aggr_expr: &mut [Arc<dyn AggregateExpr>],
order_by_expr: &mut [Option<LexOrdering>],
ordering_req: &mut Vec<PhysicalSortExpr>,
) -> PartitionSearchMode {
let groupby_exprs = group_by
.expr
.iter()
.map(|(item, _)| item.clone())
.collect::<Vec<_>>();
let mut partition_search_mode = PartitionSearchMode::Linear;
if !group_by.is_single() || groupby_exprs.is_empty() {
return partition_search_mode;
}
if let Some((should_reverse, mode)) =
get_window_mode(&groupby_exprs, ordering_req, input)
{
let all_reversible = aggr_expr
.iter()
.all(|expr| !is_order_sensitive(expr) || expr.reverse_expr().is_some());
if should_reverse && all_reversible {
izip!(aggr_expr.iter_mut(), order_by_expr.iter_mut()).for_each(
|(aggr, order_by)| {
if let Some(reverse) = aggr.reverse_expr() {
*aggr = reverse;
} else {
unreachable!();
}
*order_by = order_by.as_ref().map(|ob| reverse_order_bys(ob));
},
);
*ordering_req = reverse_order_bys(ordering_req);
}
partition_search_mode = mode;
}
partition_search_mode
}
/// Check whether group by expression contains all of the expression inside `requirement`
// As an example Group By (c,b,a) contains all of the expressions in the `requirement`: (a ASC, b DESC)
fn group_by_contains_all_requirements(
group_by: &PhysicalGroupBy,
requirement: &LexOrdering,
) -> bool {
let physical_exprs = group_by.input_exprs();
// When we have multiple groups (grouping set)
// since group by may be calculated on the subset of the group_by.expr()
// it is not guaranteed to have all of the requirements among group by expressions.
// Hence do the analysis: whether group by contains all requirements in the single group case.
group_by.is_single()
&& requirement
.iter()
.all(|req| physical_exprs_contains(&physical_exprs, &req.expr))
}
impl AggregateExec {
/// Create a new hash aggregate execution plan
pub fn try_new(
mode: AggregateMode,
group_by: PhysicalGroupBy,
mut aggr_expr: Vec<Arc<dyn AggregateExpr>>,
filter_expr: Vec<Option<Arc<dyn PhysicalExpr>>>,
// Ordering requirement of each aggregate expression
mut order_by_expr: Vec<Option<LexOrdering>>,
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);
// Reset ordering requirement to `None` if aggregator is not order-sensitive
order_by_expr = aggr_expr
.iter()
.zip(order_by_expr)
.map(|(aggr_expr, fn_reqs)| {
// If
// - aggregation function is order-sensitive and
// - aggregation is performing a "first stage" calculation, and
// - at least one of the aggregate function requirement is not inside group by expression
// keep the ordering requirement as is; otherwise ignore the ordering requirement.
// 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.
fn_reqs.filter(|req| {
is_order_sensitive(aggr_expr)
&& mode.is_first_stage()
&& !group_by_contains_all_requirements(&group_by, req)
})
})
.collect::<Vec<_>>();
let requirement = get_finest_requirement(
&mut aggr_expr,
&mut order_by_expr,
&input.equivalence_properties(),
)?;
let mut ordering_req = requirement.unwrap_or(vec![]);
let partition_search_mode = get_aggregate_search_mode(
&group_by,
&input,
&mut aggr_expr,
&mut order_by_expr,
&mut ordering_req,
);
// 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
.into_iter()
.map(|idx| PhysicalSortRequirement {
expr: groupby_exprs[idx].clone(),
options: None,
})
.collect::<Vec<_>>();
// Postfix ordering requirement of the aggregation to the requirement.
let req = PhysicalSortRequirement::from_sort_exprs(&ordering_req);
new_requirement.extend(req);
new_requirement = collapse_lex_req(new_requirement);
// 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
.equivalence_properties()
.project(&projection_mapping, schema.clone());
let output_ordering = aggregate_eqs.oeq_class().output_ordering();
Ok(AggregateExec {
mode,
group_by,
aggr_expr,
filter_expr,
order_by_expr,
input,
schema,
input_schema,
projection_mapping,
metrics: ExecutionPlanMetricsSet::new(),
required_input_ordering,
limit: None,
partition_search_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
}
/// ORDER BY clause expression for each aggregate expression
pub fn order_by_expr(&self) -> &[Option<LexOrdering>] {
&self.order_by_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.order_by_expr().iter().any(|e| e.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.partition_search_mode != PartitionSearchMode::Linear {
write!(f, ", ordering_mode={:?}", self.partition_search_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.partition_search_mode == PartitionSearchMode::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(
self.mode,
self.group_by.clone(),
self.aggr_expr.clone(),
self.filter_expr.clone(),
self.order_by_expr.clone(),
children[0].clone(),
self.input_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))
}
/// returns physical expressions for arguments to evaluate against a batch
/// The expressions are different depending on `mode`:
/// * Partial: AggregateExpr::expressions
/// * Final: columns of `AggregateExpr::state_fields()`
fn aggregate_expressions(
aggr_expr: &[Arc<dyn AggregateExpr>],
mode: &AggregateMode,
col_idx_base: usize,
) -> Result<Vec<Vec<Arc<dyn PhysicalExpr>>>> {
match mode {
AggregateMode::Partial
| AggregateMode::Single
| AggregateMode::SinglePartitioned => Ok(aggr_expr
.iter()
.map(|agg| {
let mut result = agg.expressions().clone();
// In partial mode, append ordering requirements to expressions' results.
// Ordering requirements are used by subsequent executors to satisfy the required
// ordering for `AggregateMode::FinalPartitioned`/`AggregateMode::Final` modes.
if matches!(mode, AggregateMode::Partial) {