forked from apache/datafusion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenforcement.rs
2179 lines (2037 loc) · 91.9 KB
/
enforcement.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.
//! Enforcement optimizer rules are used to make sure the plan's Distribution and Ordering
//! requirements are met by inserting necessary [[RepartitionExec]] and [[SortExec]].
//!
use crate::config::OPT_TOP_DOWN_JOIN_KEY_REORDERING;
use crate::error::Result;
use crate::physical_optimizer::PhysicalOptimizerRule;
use crate::physical_plan::aggregates::{AggregateExec, AggregateMode, PhysicalGroupBy};
use crate::physical_plan::coalesce_partitions::CoalescePartitionsExec;
use crate::physical_plan::joins::{
CrossJoinExec, HashJoinExec, PartitionMode, SortMergeJoinExec,
};
use crate::physical_plan::projection::ProjectionExec;
use crate::physical_plan::repartition::RepartitionExec;
use crate::physical_plan::rewrite::TreeNodeRewritable;
use crate::physical_plan::sorts::sort::SortExec;
use crate::physical_plan::sorts::sort::SortOptions;
use crate::physical_plan::windows::WindowAggExec;
use crate::physical_plan::Partitioning;
use crate::physical_plan::{with_new_children_if_necessary, Distribution, ExecutionPlan};
use crate::prelude::SessionConfig;
use arrow::datatypes::SchemaRef;
use datafusion_expr::logical_plan::JoinType;
use datafusion_physical_expr::equivalence::EquivalenceProperties;
use datafusion_physical_expr::expressions::Column;
use datafusion_physical_expr::expressions::NoOp;
use datafusion_physical_expr::{
expr_list_eq_strict_order, normalize_expr_with_equivalence_properties,
normalize_sort_expr_with_equivalence_properties, AggregateExpr, PhysicalExpr,
PhysicalSortExpr,
};
use std::collections::HashMap;
use std::sync::Arc;
/// BasicEnforcement rule, it ensures the Distribution and Ordering requirements are met
/// in the strictest way. It might add additional [[RepartitionExec]] to the plan tree
/// and give a non-optimal plan, but it can avoid the possible data skew in joins.
///
/// For example for a HashJoin with keys(a, b, c), the required Distribution(a, b, c) can be satisfied by
/// several alternative partitioning ways: [(a, b, c), (a, b), (a, c), (b, c), (a), (b), (c), ( )].
///
/// This rule only chooses the exactly match and satisfies the Distribution(a, b, c) by a HashPartition(a, b, c).
#[derive(Default)]
pub struct BasicEnforcement {}
impl BasicEnforcement {
#[allow(missing_docs)]
pub fn new() -> Self {
Self {}
}
}
impl PhysicalOptimizerRule for BasicEnforcement {
fn optimize(
&self,
plan: Arc<dyn ExecutionPlan>,
config: &SessionConfig,
) -> Result<Arc<dyn ExecutionPlan>> {
let target_partitions = config.target_partitions();
let top_down_join_key_reordering = config
.config_options()
.read()
.get_bool(OPT_TOP_DOWN_JOIN_KEY_REORDERING)
.unwrap_or_default();
let new_plan = if top_down_join_key_reordering {
// Run a top-down process to adjust input key ordering recursively
let plan_requirements = PlanWithKeyRequirements::new(plan);
let adjusted =
plan_requirements.transform_down(&adjust_input_keys_ordering)?;
adjusted.plan
} else {
plan
};
// Distribution and Ordering enforcement need to be applied bottom-up.
new_plan.transform_up(&{
|plan| {
let adjusted = if !top_down_join_key_reordering {
reorder_join_keys_to_inputs(plan)?
} else {
plan
};
Ok(Some(ensure_distribution_and_ordering(
adjusted,
target_partitions,
)?))
}
})
}
fn name(&self) -> &str {
"BasicEnforcement"
}
fn schema_check(&self) -> bool {
true
}
}
/// When the physical planner creates the Joins, the ordering of join keys is from the original query.
/// That might not match with the output partitioning of the join node's children
/// A Top-Down process will use this method to adjust children's output partitioning based on the parent key reordering requirements:
///
/// Example:
/// TopJoin on (a, b, c)
/// bottom left join on(b, a, c)
/// bottom right join on(c, b, a)
///
/// Will be adjusted to:
/// TopJoin on (a, b, c)
/// bottom left join on(a, b, c)
/// bottom right join on(a, b, c)
///
/// Example:
/// TopJoin on (a, b, c)
/// Agg1 group by (b, a, c)
/// Agg2 group by (c, b, a)
///
/// Will be adjusted to:
/// TopJoin on (a, b, c)
/// Projection(b, a, c)
/// Agg1 group by (a, b, c)
/// Projection(c, b, a)
/// Agg2 group by (a, b, c)
///
/// Following is the explanation of the reordering process:
///
/// 1) If the current plan is Partitioned HashJoin, SortMergeJoin, check whether the requirements can be satisfied by adjusting join keys ordering:
/// Requirements can not be satisfied, clear the current requirements, generate new requirements(to pushdown) based on the current join keys, return the unchanged plan.
/// Requirements is already satisfied, clear the current requirements, generate new requirements(to pushdown) based on the current join keys, return the unchanged plan.
/// Requirements can be satisfied by adjusting keys ordering, clear the current requiements, generate new requirements(to pushdown) based on the adjusted join keys, return the changed plan.
///
/// 2) If the current plan is Aggregation, check whether the requirements can be satisfied by adjusting group by keys ordering:
/// Requirements can not be satisfied, clear all the requirements, return the unchanged plan.
/// Requirements is already satisfied, clear all the requirements, return the unchanged plan.
/// Requirements can be satisfied by adjusting keys ordering, clear all the requirements, return the changed plan.
///
/// 3) If the current plan is RepartitionExec, CoalescePartitionsExec or WindowAggExec, clear all the requirements, return the unchanged plan
/// 4) If the current plan is Projection, transform the requirements to the columns before the Projection and push down requirements
/// 5) For other types of operators, by default, pushdown the parent requirements to children.
///
fn adjust_input_keys_ordering(
requirements: PlanWithKeyRequirements,
) -> Result<Option<PlanWithKeyRequirements>> {
let parent_required = requirements.required_key_ordering.clone();
let plan_any = requirements.plan.as_any();
if let Some(HashJoinExec {
left,
right,
on,
filter,
join_type,
mode,
null_equals_null,
..
}) = plan_any.downcast_ref::<HashJoinExec>()
{
match mode {
PartitionMode::Partitioned => {
let join_constructor =
|new_conditions: (Vec<(Column, Column)>, Vec<SortOptions>)| {
Ok(Arc::new(HashJoinExec::try_new(
left.clone(),
right.clone(),
new_conditions.0,
filter.clone(),
join_type,
PartitionMode::Partitioned,
null_equals_null,
)?) as Arc<dyn ExecutionPlan>)
};
Ok(Some(reorder_partitioned_join_keys(
requirements.plan.clone(),
&parent_required,
on,
vec![],
&join_constructor,
)?))
}
PartitionMode::CollectLeft => {
let new_right_request = match join_type {
JoinType::Inner | JoinType::Right => shift_right_required(
&parent_required,
left.schema().fields().len(),
),
JoinType::RightSemi | JoinType::RightAnti => {
Some(parent_required.clone())
}
JoinType::Left
| JoinType::LeftSemi
| JoinType::LeftAnti
| JoinType::Full => None,
};
// Push down requirements to the right side
Ok(Some(PlanWithKeyRequirements {
plan: requirements.plan.clone(),
required_key_ordering: vec![],
request_key_ordering: vec![None, new_right_request],
}))
}
PartitionMode::Auto => {
// Can not satisfy, clear the current requirements and generate new empty requirements
Ok(Some(PlanWithKeyRequirements::new(
requirements.plan.clone(),
)))
}
}
} else if let Some(CrossJoinExec { left, .. }) =
plan_any.downcast_ref::<CrossJoinExec>()
{
let left_columns_len = left.schema().fields().len();
// Push down requirements to the right side
Ok(Some(PlanWithKeyRequirements {
plan: requirements.plan.clone(),
required_key_ordering: vec![],
request_key_ordering: vec![
None,
shift_right_required(&parent_required, left_columns_len),
],
}))
} else if let Some(SortMergeJoinExec {
left,
right,
on,
join_type,
sort_options,
null_equals_null,
..
}) = plan_any.downcast_ref::<SortMergeJoinExec>()
{
let join_constructor =
|new_conditions: (Vec<(Column, Column)>, Vec<SortOptions>)| {
Ok(Arc::new(SortMergeJoinExec::try_new(
left.clone(),
right.clone(),
new_conditions.0,
*join_type,
new_conditions.1,
*null_equals_null,
)?) as Arc<dyn ExecutionPlan>)
};
Ok(Some(reorder_partitioned_join_keys(
requirements.plan.clone(),
&parent_required,
on,
sort_options.clone(),
&join_constructor,
)?))
} else if let Some(AggregateExec {
mode,
group_by,
aggr_expr,
input,
input_schema,
..
}) = plan_any.downcast_ref::<AggregateExec>()
{
if !parent_required.is_empty() {
match mode {
AggregateMode::FinalPartitioned => Ok(Some(reorder_aggregate_keys(
requirements.plan.clone(),
&parent_required,
group_by,
aggr_expr,
input.clone(),
input_schema,
)?)),
_ => Ok(Some(PlanWithKeyRequirements::new(
requirements.plan.clone(),
))),
}
} else {
// Keep everything unchanged
Ok(None)
}
} else if let Some(ProjectionExec { expr, .. }) =
plan_any.downcast_ref::<ProjectionExec>()
{
// For Projection, we need to transform the requirements to the columns before the Projection
// And then to push down the requirements
// Construct a mapping from new name to the the orginal Column
let new_required = map_columns_before_projection(&parent_required, expr);
if new_required.len() == parent_required.len() {
Ok(Some(PlanWithKeyRequirements {
plan: requirements.plan.clone(),
required_key_ordering: vec![],
request_key_ordering: vec![Some(new_required.clone())],
}))
} else {
// Can not satisfy, clear the current requirements and generate new empty requirements
Ok(Some(PlanWithKeyRequirements::new(
requirements.plan.clone(),
)))
}
} else if plan_any.downcast_ref::<RepartitionExec>().is_some()
|| plan_any.downcast_ref::<CoalescePartitionsExec>().is_some()
|| plan_any.downcast_ref::<WindowAggExec>().is_some()
{
Ok(Some(PlanWithKeyRequirements::new(
requirements.plan.clone(),
)))
} else {
// By default, push down the parent requirements to children
let children_len = requirements.plan.children().len();
Ok(Some(PlanWithKeyRequirements {
plan: requirements.plan.clone(),
required_key_ordering: vec![],
request_key_ordering: vec![Some(parent_required.clone()); children_len],
}))
}
}
fn reorder_partitioned_join_keys<F>(
join_plan: Arc<dyn ExecutionPlan>,
parent_required: &[Arc<dyn PhysicalExpr>],
on: &[(Column, Column)],
sort_options: Vec<SortOptions>,
join_constructor: &F,
) -> Result<PlanWithKeyRequirements>
where
F: Fn((Vec<(Column, Column)>, Vec<SortOptions>)) -> Result<Arc<dyn ExecutionPlan>>,
{
let join_key_pairs = extract_join_keys(on);
if let Some((
JoinKeyPairs {
left_keys,
right_keys,
},
new_positions,
)) = try_reorder(
join_key_pairs.clone(),
parent_required,
&join_plan.equivalence_properties(),
) {
if !new_positions.is_empty() {
let new_join_on = new_join_conditions(&left_keys, &right_keys);
let mut new_sort_options: Vec<SortOptions> = vec![];
for idx in 0..sort_options.len() {
new_sort_options.push(sort_options[new_positions[idx]])
}
Ok(PlanWithKeyRequirements {
plan: join_constructor((new_join_on, new_sort_options))?,
required_key_ordering: vec![],
request_key_ordering: vec![Some(left_keys), Some(right_keys)],
})
} else {
Ok(PlanWithKeyRequirements {
plan: join_plan,
required_key_ordering: vec![],
request_key_ordering: vec![Some(left_keys), Some(right_keys)],
})
}
} else {
Ok(PlanWithKeyRequirements {
plan: join_plan,
required_key_ordering: vec![],
request_key_ordering: vec![
Some(join_key_pairs.left_keys),
Some(join_key_pairs.right_keys),
],
})
}
}
fn reorder_aggregate_keys(
agg_plan: Arc<dyn ExecutionPlan>,
parent_required: &[Arc<dyn PhysicalExpr>],
group_by: &PhysicalGroupBy,
aggr_expr: &[Arc<dyn AggregateExpr>],
agg_input: Arc<dyn ExecutionPlan>,
input_schema: &SchemaRef,
) -> Result<PlanWithKeyRequirements> {
let out_put_columns = group_by
.expr()
.iter()
.enumerate()
.map(|(index, (_col, name))| Column::new(name, index))
.collect::<Vec<_>>();
let out_put_exprs = out_put_columns
.iter()
.map(|c| Arc::new(c.clone()) as Arc<dyn PhysicalExpr>)
.collect::<Vec<_>>();
if parent_required.len() != out_put_exprs.len()
|| !group_by.null_expr().is_empty()
|| expr_list_eq_strict_order(&out_put_exprs, parent_required)
{
Ok(PlanWithKeyRequirements::new(agg_plan))
} else {
let new_positions = expected_expr_positions(&out_put_exprs, parent_required);
match new_positions {
None => Ok(PlanWithKeyRequirements::new(agg_plan)),
Some(positions) => {
let new_partial_agg = if let Some(AggregateExec {
mode,
group_by,
aggr_expr,
input,
input_schema,
..
}) =
agg_input.as_any().downcast_ref::<AggregateExec>()
{
if matches!(mode, AggregateMode::Partial) {
let mut new_group_exprs = vec![];
for idx in positions.iter() {
new_group_exprs.push(group_by.expr()[*idx].clone());
}
let new_partial_group_by =
PhysicalGroupBy::new_single(new_group_exprs);
// new Partial AggregateExec
Some(Arc::new(AggregateExec::try_new(
AggregateMode::Partial,
new_partial_group_by,
aggr_expr.clone(),
input.clone(),
input_schema.clone(),
)?))
} else {
None
}
} else {
None
};
if let Some(partial_agg) = new_partial_agg {
let mut new_group_exprs = vec![];
for idx in positions.into_iter() {
new_group_exprs.push(group_by.expr()[idx].clone());
}
let new_group_by = PhysicalGroupBy::new_single(new_group_exprs);
let new_final_agg = Arc::new(AggregateExec::try_new(
AggregateMode::FinalPartitioned,
new_group_by,
aggr_expr.to_vec(),
partial_agg,
input_schema.clone(),
)?);
// Need to create a new projection to change the expr ordering back
let mut proj_exprs = out_put_columns
.iter()
.map(|col| {
(
Arc::new(Column::new(
col.name(),
new_final_agg.schema().index_of(col.name()).unwrap(),
))
as Arc<dyn PhysicalExpr>,
col.name().to_owned(),
)
})
.collect::<Vec<_>>();
let agg_schema = new_final_agg.schema();
let agg_fields = agg_schema.fields();
for (idx, field) in
agg_fields.iter().enumerate().skip(out_put_columns.len())
{
proj_exprs.push((
Arc::new(Column::new(field.name().as_str(), idx))
as Arc<dyn PhysicalExpr>,
field.name().clone(),
))
}
// TODO merge adjacent Projections if there are
Ok(PlanWithKeyRequirements::new(Arc::new(
ProjectionExec::try_new(proj_exprs, new_final_agg)?,
)))
} else {
Ok(PlanWithKeyRequirements::new(agg_plan))
}
}
}
}
}
fn map_columns_before_projection(
parent_required: &[Arc<dyn PhysicalExpr>],
proj_exprs: &[(Arc<dyn PhysicalExpr>, String)],
) -> Vec<Arc<dyn PhysicalExpr>> {
let mut column_mapping = HashMap::new();
for (expression, name) in proj_exprs.iter() {
if let Some(column) = expression.as_any().downcast_ref::<Column>() {
column_mapping.insert(name.clone(), column.clone());
};
}
let new_required: Vec<Arc<dyn PhysicalExpr>> = parent_required
.iter()
.filter_map(|r| {
if let Some(column) = r.as_any().downcast_ref::<Column>() {
column_mapping.get(column.name())
} else {
None
}
})
.map(|e| Arc::new(e.clone()) as Arc<dyn PhysicalExpr>)
.collect::<Vec<_>>();
new_required
}
fn shift_right_required(
parent_required: &[Arc<dyn PhysicalExpr>],
left_columns_len: usize,
) -> Option<Vec<Arc<dyn PhysicalExpr>>> {
let new_right_required: Vec<Arc<dyn PhysicalExpr>> = parent_required
.iter()
.filter_map(|r| {
if let Some(col) = r.as_any().downcast_ref::<Column>() {
if col.index() >= left_columns_len {
Some(
Arc::new(Column::new(col.name(), col.index() - left_columns_len))
as Arc<dyn PhysicalExpr>,
)
} else {
None
}
} else {
None
}
})
.collect::<Vec<_>>();
// if the parent required are all comming from the right side, the requirements can be pushdown
if new_right_required.len() != parent_required.len() {
None
} else {
Some(new_right_required)
}
}
/// When the physical planner creates the Joins, the ordering of join keys is from the original query.
/// That might not match with the output partitioning of the join node's children
/// This method will try to change the ordering of the join keys to match with the
/// partitioning of the join nodes' children. If it can not match with both sides, it will try to
/// match with one, either the left side or the right side.
///
/// Example:
/// TopJoin on (a, b, c)
/// bottom left join on(b, a, c)
/// bottom right join on(c, b, a)
///
/// Will be adjusted to:
/// TopJoin on (b, a, c)
/// bottom left join on(b, a, c)
/// bottom right join on(c, b, a)
///
/// Compared to the Top-Down reordering process, this Bottom-Up approach is much simpler, but might not reach a best result.
/// The Bottom-Up approach will be useful in future if we plan to support storage partition-wised Joins.
/// In that case, the datasources/tables might be pre-partitioned and we can't adjust the key ordering of the datasources
/// and then can't apply the Top-Down reordering process.
fn reorder_join_keys_to_inputs(
plan: Arc<dyn crate::physical_plan::ExecutionPlan>,
) -> Result<Arc<dyn crate::physical_plan::ExecutionPlan>> {
let plan_any = plan.as_any();
if let Some(HashJoinExec {
left,
right,
on,
filter,
join_type,
mode,
null_equals_null,
..
}) = plan_any.downcast_ref::<HashJoinExec>()
{
match mode {
PartitionMode::Partitioned => {
let join_key_pairs = extract_join_keys(on);
if let Some((
JoinKeyPairs {
left_keys,
right_keys,
},
new_positions,
)) = reorder_current_join_keys(
join_key_pairs,
Some(left.output_partitioning()),
Some(right.output_partitioning()),
&left.equivalence_properties(),
&right.equivalence_properties(),
) {
if !new_positions.is_empty() {
let new_join_on = new_join_conditions(&left_keys, &right_keys);
Ok(Arc::new(HashJoinExec::try_new(
left.clone(),
right.clone(),
new_join_on,
filter.clone(),
join_type,
PartitionMode::Partitioned,
null_equals_null,
)?))
} else {
Ok(plan)
}
} else {
Ok(plan)
}
}
_ => Ok(plan),
}
} else if let Some(SortMergeJoinExec {
left,
right,
on,
join_type,
sort_options,
null_equals_null,
..
}) = plan_any.downcast_ref::<SortMergeJoinExec>()
{
let join_key_pairs = extract_join_keys(on);
if let Some((
JoinKeyPairs {
left_keys,
right_keys,
},
new_positions,
)) = reorder_current_join_keys(
join_key_pairs,
Some(left.output_partitioning()),
Some(right.output_partitioning()),
&left.equivalence_properties(),
&right.equivalence_properties(),
) {
if !new_positions.is_empty() {
let new_join_on = new_join_conditions(&left_keys, &right_keys);
let mut new_sort_options = vec![];
for idx in 0..sort_options.len() {
new_sort_options.push(sort_options[new_positions[idx]])
}
Ok(Arc::new(SortMergeJoinExec::try_new(
left.clone(),
right.clone(),
new_join_on,
*join_type,
new_sort_options,
*null_equals_null,
)?))
} else {
Ok(plan)
}
} else {
Ok(plan)
}
} else {
Ok(plan)
}
}
/// Reorder the current join keys ordering based on either left partition or right partition
fn reorder_current_join_keys(
join_keys: JoinKeyPairs,
left_partition: Option<Partitioning>,
right_partition: Option<Partitioning>,
left_equivalence_properties: &EquivalenceProperties,
right_equivalence_properties: &EquivalenceProperties,
) -> Option<(JoinKeyPairs, Vec<usize>)> {
match (left_partition, right_partition.clone()) {
(Some(Partitioning::Hash(left_exprs, _)), _) => {
try_reorder(join_keys.clone(), &left_exprs, left_equivalence_properties)
.or_else(|| {
reorder_current_join_keys(
join_keys,
None,
right_partition,
left_equivalence_properties,
right_equivalence_properties,
)
})
}
(_, Some(Partitioning::Hash(right_exprs, _))) => {
try_reorder(join_keys, &right_exprs, right_equivalence_properties)
}
_ => None,
}
}
fn try_reorder(
join_keys: JoinKeyPairs,
expected: &[Arc<dyn PhysicalExpr>],
equivalence_properties: &EquivalenceProperties,
) -> Option<(JoinKeyPairs, Vec<usize>)> {
let mut normalized_expected = vec![];
let mut normalized_left_keys = vec![];
let mut normalized_right_keys = vec![];
if join_keys.left_keys.len() != expected.len() {
return None;
}
if expr_list_eq_strict_order(expected, &join_keys.left_keys)
|| expr_list_eq_strict_order(expected, &join_keys.right_keys)
{
return Some((join_keys, vec![]));
} else if !equivalence_properties.classes().is_empty() {
normalized_expected = expected
.iter()
.map(|e| {
normalize_expr_with_equivalence_properties(
e.clone(),
equivalence_properties.classes(),
)
})
.collect::<Vec<_>>();
assert_eq!(normalized_expected.len(), expected.len());
normalized_left_keys = join_keys
.left_keys
.iter()
.map(|e| {
normalize_expr_with_equivalence_properties(
e.clone(),
equivalence_properties.classes(),
)
})
.collect::<Vec<_>>();
assert_eq!(join_keys.left_keys.len(), normalized_left_keys.len());
normalized_right_keys = join_keys
.right_keys
.iter()
.map(|e| {
normalize_expr_with_equivalence_properties(
e.clone(),
equivalence_properties.classes(),
)
})
.collect::<Vec<_>>();
assert_eq!(join_keys.right_keys.len(), normalized_right_keys.len());
if expr_list_eq_strict_order(&normalized_expected, &normalized_left_keys)
|| expr_list_eq_strict_order(&normalized_expected, &normalized_right_keys)
{
return Some((join_keys, vec![]));
}
}
let new_positions = expected_expr_positions(&join_keys.left_keys, expected)
.or_else(|| expected_expr_positions(&join_keys.right_keys, expected))
.or_else(|| expected_expr_positions(&normalized_left_keys, &normalized_expected))
.or_else(|| {
expected_expr_positions(&normalized_right_keys, &normalized_expected)
});
if let Some(positions) = new_positions {
let mut new_left_keys = vec![];
let mut new_right_keys = vec![];
for pos in positions.iter() {
new_left_keys.push(join_keys.left_keys[*pos].clone());
new_right_keys.push(join_keys.right_keys[*pos].clone());
}
Some((
JoinKeyPairs {
left_keys: new_left_keys,
right_keys: new_right_keys,
},
positions,
))
} else {
None
}
}
/// Return the expected expressions positions.
/// For example, the current expressions are ['c', 'a', 'a', b'], the expected expressions are ['b', 'c', 'a', 'a'],
///
/// This method will return a Vec [3, 0, 1, 2]
fn expected_expr_positions(
current: &[Arc<dyn PhysicalExpr>],
expected: &[Arc<dyn PhysicalExpr>],
) -> Option<Vec<usize>> {
if current.is_empty() || expected.is_empty() {
return None;
}
let mut indexes: Vec<usize> = vec![];
let mut current = current.to_vec();
for expr in expected.iter() {
// Find the position of the expected expr in the current expressions
if let Some(expected_position) = current.iter().position(|e| e.eq(expr)) {
current[expected_position] = Arc::new(NoOp::new());
indexes.push(expected_position);
} else {
return None;
}
}
Some(indexes)
}
fn extract_join_keys(on: &[(Column, Column)]) -> JoinKeyPairs {
let (left_keys, right_keys) = on
.iter()
.map(|(l, r)| {
(
Arc::new(l.clone()) as Arc<dyn PhysicalExpr>,
Arc::new(r.clone()) as Arc<dyn PhysicalExpr>,
)
})
.unzip();
JoinKeyPairs {
left_keys,
right_keys,
}
}
fn new_join_conditions(
new_left_keys: &[Arc<dyn PhysicalExpr>],
new_right_keys: &[Arc<dyn PhysicalExpr>],
) -> Vec<(Column, Column)> {
let new_join_on = new_left_keys
.iter()
.zip(new_right_keys.iter())
.map(|(l_key, r_key)| {
(
l_key.as_any().downcast_ref::<Column>().unwrap().clone(),
r_key.as_any().downcast_ref::<Column>().unwrap().clone(),
)
})
.collect::<Vec<_>>();
new_join_on
}
fn ensure_distribution_and_ordering(
plan: Arc<dyn crate::physical_plan::ExecutionPlan>,
target_partitions: usize,
) -> Result<Arc<dyn crate::physical_plan::ExecutionPlan>> {
if plan.children().is_empty() {
return Ok(plan);
}
let required_input_distributions = plan.required_input_distribution();
let required_input_orderings = plan.required_input_ordering();
let children: Vec<Arc<dyn ExecutionPlan>> = plan.children();
assert_eq!(children.len(), required_input_distributions.len());
assert_eq!(children.len(), required_input_orderings.len());
// Add RepartitionExec to guarantee output partitioning
let children = children
.into_iter()
.zip(required_input_distributions.into_iter())
.map(|(child, required)| {
if child
.output_partitioning()
.satisfy(required.clone(), || child.equivalence_properties())
{
Ok(child)
} else {
let new_child: Result<Arc<dyn ExecutionPlan>> = match required {
Distribution::SinglePartition
if child.output_partitioning().partition_count() > 1 =>
{
Ok(Arc::new(CoalescePartitionsExec::new(child.clone())))
}
_ => {
let partition = required.create_partitioning(target_partitions);
Ok(Arc::new(RepartitionExec::try_new(child, partition)?))
}
};
new_child
}
});
// Add SortExec to guarantee output ordering
let new_children: Result<Vec<Arc<dyn ExecutionPlan>>> = children
.zip(required_input_orderings.into_iter())
.map(|(child_result, required)| {
let child = child_result?;
if ordering_satisfy(child.output_ordering(), required, || {
child.equivalence_properties()
}) {
Ok(child)
} else {
let sort_expr = required.unwrap().to_vec();
if child.output_partitioning().partition_count() > 1 {
Ok(Arc::new(SortExec::new_with_partitioning(
sort_expr, child, true, None,
)) as Arc<dyn ExecutionPlan>)
} else {
Ok(Arc::new(SortExec::try_new(sort_expr, child, None)?)
as Arc<dyn ExecutionPlan>)
}
}
})
.collect();
with_new_children_if_necessary(plan, new_children?)
}
/// Check the required ordering requirements are satisfied by the provided PhysicalSortExprs.
fn ordering_satisfy<F: FnOnce() -> EquivalenceProperties>(
provided: Option<&[PhysicalSortExpr]>,
required: Option<&[PhysicalSortExpr]>,
equal_properties: F,
) -> bool {
match (provided, required) {
(_, None) => true,
(None, Some(_)) => false,
(Some(provided), Some(required)) => {
if required.len() > provided.len() {
false
} else {
let fast_match = required
.iter()
.zip(provided.iter())
.all(|(order1, order2)| order1.eq(order2));
if !fast_match {
let eq_properties = equal_properties();
let eq_classes = eq_properties.classes();
if !eq_classes.is_empty() {
let normalized_required_exprs = required
.iter()
.map(|e| {
normalize_sort_expr_with_equivalence_properties(
e.clone(),
eq_classes,
)
})
.collect::<Vec<_>>();
let normalized_provided_exprs = provided
.iter()
.map(|e| {
normalize_sort_expr_with_equivalence_properties(
e.clone(),
eq_classes,
)
})
.collect::<Vec<_>>();
normalized_required_exprs
.iter()
.zip(normalized_provided_exprs.iter())
.all(|(order1, order2)| order1.eq(order2))
} else {
fast_match
}
} else {
fast_match
}
}
}
}
}
#[derive(Debug, Clone)]
struct JoinKeyPairs {
left_keys: Vec<Arc<dyn PhysicalExpr>>,
right_keys: Vec<Arc<dyn PhysicalExpr>>,
}
#[derive(Debug, Clone)]
struct PlanWithKeyRequirements {
plan: Arc<dyn ExecutionPlan>,
/// Parent required key ordering
required_key_ordering: Vec<Arc<dyn PhysicalExpr>>,
/// The request key ordering to children
request_key_ordering: Vec<Option<Vec<Arc<dyn PhysicalExpr>>>>,
}
impl PlanWithKeyRequirements {
pub fn new(plan: Arc<dyn ExecutionPlan>) -> Self {
let children_len = plan.children().len();
PlanWithKeyRequirements {
plan,
required_key_ordering: vec![],
request_key_ordering: vec![None; children_len],
}
}
pub fn children(&self) -> Vec<PlanWithKeyRequirements> {
let plan_children = self.plan.children();
assert_eq!(plan_children.len(), self.request_key_ordering.len());
plan_children
.into_iter()
.zip(self.request_key_ordering.clone().into_iter())
.map(|(child, required)| {
let from_parent = required.unwrap_or_default();
let length = child.children().len();
PlanWithKeyRequirements {
plan: child,
required_key_ordering: from_parent.clone(),
request_key_ordering: vec![None; length],
}
})
.collect()
}
}