-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
AddExchanges.java
1145 lines (982 loc) · 57.4 KB
/
AddExchanges.java
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 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.
*/
package com.facebook.presto.sql.planner.optimizations;
import com.facebook.presto.Session;
import com.facebook.presto.SystemSessionProperties;
import com.facebook.presto.metadata.FunctionRegistry;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.metadata.TableLayoutResult;
import com.facebook.presto.operator.aggregation.InternalAggregationFunction;
import com.facebook.presto.spi.ColumnHandle;
import com.facebook.presto.spi.Constraint;
import com.facebook.presto.spi.GroupingProperty;
import com.facebook.presto.spi.LocalProperty;
import com.facebook.presto.spi.SortingProperty;
import com.facebook.presto.spi.predicate.NullableValue;
import com.facebook.presto.spi.predicate.TupleDomain;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.parser.SqlParser;
import com.facebook.presto.sql.planner.DomainTranslator;
import com.facebook.presto.sql.planner.ExpressionInterpreter;
import com.facebook.presto.sql.planner.LookupSymbolResolver;
import com.facebook.presto.sql.planner.PartitionFunctionBinding;
import com.facebook.presto.sql.planner.PlanNodeIdAllocator;
import com.facebook.presto.sql.planner.Symbol;
import com.facebook.presto.sql.planner.SymbolAllocator;
import com.facebook.presto.sql.planner.plan.AggregationNode;
import com.facebook.presto.sql.planner.plan.ChildReplacer;
import com.facebook.presto.sql.planner.plan.DeleteNode;
import com.facebook.presto.sql.planner.plan.DistinctLimitNode;
import com.facebook.presto.sql.planner.plan.ExchangeNode;
import com.facebook.presto.sql.planner.plan.FilterNode;
import com.facebook.presto.sql.planner.plan.IndexJoinNode;
import com.facebook.presto.sql.planner.plan.IndexSourceNode;
import com.facebook.presto.sql.planner.plan.JoinNode;
import com.facebook.presto.sql.planner.plan.LimitNode;
import com.facebook.presto.sql.planner.plan.MarkDistinctNode;
import com.facebook.presto.sql.planner.plan.OutputNode;
import com.facebook.presto.sql.planner.plan.PlanNode;
import com.facebook.presto.sql.planner.plan.PlanVisitor;
import com.facebook.presto.sql.planner.plan.ProjectNode;
import com.facebook.presto.sql.planner.plan.RowNumberNode;
import com.facebook.presto.sql.planner.plan.SemiJoinNode;
import com.facebook.presto.sql.planner.plan.SortNode;
import com.facebook.presto.sql.planner.plan.TableFinishNode;
import com.facebook.presto.sql.planner.plan.TableScanNode;
import com.facebook.presto.sql.planner.plan.TableWriterNode;
import com.facebook.presto.sql.planner.plan.TopNNode;
import com.facebook.presto.sql.planner.plan.TopNRowNumberNode;
import com.facebook.presto.sql.planner.plan.UnionNode;
import com.facebook.presto.sql.planner.plan.UnnestNode;
import com.facebook.presto.sql.planner.plan.ValuesNode;
import com.facebook.presto.sql.planner.plan.WindowNode;
import com.facebook.presto.sql.tree.BooleanLiteral;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.FunctionCall;
import com.facebook.presto.sql.tree.NullLiteral;
import com.facebook.presto.sql.tree.QualifiedName;
import com.facebook.presto.sql.tree.QualifiedNameReference;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import static com.facebook.presto.sql.ExpressionUtils.combineConjuncts;
import static com.facebook.presto.sql.ExpressionUtils.extractConjuncts;
import static com.facebook.presto.sql.ExpressionUtils.stripDeterministicConjuncts;
import static com.facebook.presto.sql.ExpressionUtils.stripNonDeterministicConjuncts;
import static com.facebook.presto.sql.analyzer.ExpressionAnalyzer.getExpressionTypes;
import static com.facebook.presto.sql.planner.PartitionFunctionHandle.HASH;
import static com.facebook.presto.sql.planner.PartitionFunctionHandle.ROUND_ROBIN;
import static com.facebook.presto.sql.planner.optimizations.LocalProperties.grouped;
import static com.facebook.presto.sql.planner.plan.AggregationNode.Step.FINAL;
import static com.facebook.presto.sql.planner.plan.AggregationNode.Step.PARTIAL;
import static com.facebook.presto.sql.planner.plan.ExchangeNode.gatheringExchange;
import static com.facebook.presto.sql.planner.plan.ExchangeNode.partitionedExchange;
import static com.facebook.presto.sql.planner.plan.ExchangeNode.replicatedExchange;
import static com.facebook.presto.sql.planner.plan.JoinNode.Type.FULL;
import static com.facebook.presto.sql.planner.plan.JoinNode.Type.INNER;
import static com.facebook.presto.sql.planner.plan.JoinNode.Type.RIGHT;
import static com.facebook.presto.util.ImmutableCollectors.toImmutableSet;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Iterables.getOnlyElement;
import static java.util.stream.Collectors.toList;
public class AddExchanges
extends PlanOptimizer
{
private final SqlParser parser;
private final Metadata metadata;
public AddExchanges(Metadata metadata, SqlParser parser)
{
this.metadata = metadata;
this.parser = parser;
}
@Override
public PlanNode optimize(PlanNode plan, Session session, Map<Symbol, Type> types, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator)
{
boolean distributedJoinEnabled = SystemSessionProperties.isDistributedJoinEnabled(session);
boolean distributedIndexJoinEnabled = SystemSessionProperties.isDistributedIndexJoinEnabled(session);
boolean redistributeWrites = SystemSessionProperties.isRedistributeWrites(session);
boolean preferStreamingOperators = SystemSessionProperties.preferStreamingOperators(session);
PlanWithProperties result = plan.accept(new Rewriter(symbolAllocator, idAllocator, symbolAllocator, session, distributedIndexJoinEnabled, distributedJoinEnabled, preferStreamingOperators, redistributeWrites), new Context(PreferredProperties.any(), false));
return result.getNode();
}
private static class Context
{
private PreferredProperties preferredProperties;
// For delete queries, the TableScan node that corresponds to the table being deleted on must be collocated with the Delete node.
// Care must be taken so that Exchange node is not introduced between the two. For now, only SemiJoin may introduce it.
private boolean downstreamIsDelete;
Context(PreferredProperties preferredProperties, boolean downstreamIsDelete)
{
this.preferredProperties = preferredProperties;
this.downstreamIsDelete = downstreamIsDelete;
}
Context withPreferredProperties(PreferredProperties preferredProperties)
{
return new Context(preferredProperties, downstreamIsDelete);
}
Context withHashPartitionedSemiJoinBanned(boolean hashPartitionedSemiJoinBanned)
{
return new Context(preferredProperties, hashPartitionedSemiJoinBanned);
}
PreferredProperties getPreferredProperties()
{
return preferredProperties;
}
boolean isDownstreamIsDelete()
{
return downstreamIsDelete;
}
}
private class Rewriter
extends PlanVisitor<Context, PlanWithProperties>
{
private final SymbolAllocator allocator;
private final PlanNodeIdAllocator idAllocator;
private final SymbolAllocator symbolAllocator;
private final Session session;
private final boolean distributedIndexJoins;
private final boolean distributedJoins;
private final boolean preferStreamingOperators;
private final boolean redistributeWrites;
public Rewriter(SymbolAllocator allocator, PlanNodeIdAllocator idAllocator, SymbolAllocator symbolAllocator, Session session, boolean distributedIndexJoins, boolean distributedJoins, boolean preferStreamingOperators, boolean redistributeWrites)
{
this.allocator = allocator;
this.idAllocator = idAllocator;
this.symbolAllocator = symbolAllocator;
this.session = session;
this.distributedIndexJoins = distributedIndexJoins;
this.distributedJoins = distributedJoins;
this.preferStreamingOperators = preferStreamingOperators;
this.redistributeWrites = redistributeWrites;
}
@Override
protected PlanWithProperties visitPlan(PlanNode node, Context context)
{
return rebaseAndDeriveProperties(node, planChild(node, context));
}
@Override
public PlanWithProperties visitDelete(DeleteNode node, Context context)
{
// Delete operator does not work unless it is co-located with the corresponding TableScan.
return rebaseAndDeriveProperties(node, planChild(node, context.withHashPartitionedSemiJoinBanned(true)));
}
@Override
public PlanWithProperties visitProject(ProjectNode node, Context context)
{
Map<Symbol, Symbol> identities = computeIdentityTranslations(node.getAssignments());
PreferredProperties translatedPreferred = context.getPreferredProperties().translate(symbol -> Optional.ofNullable(identities.get(symbol)));
return rebaseAndDeriveProperties(node, planChild(node, context.withPreferredProperties(translatedPreferred)));
}
@Override
public PlanWithProperties visitOutput(OutputNode node, Context context)
{
PlanWithProperties child = planChild(node, context.withPreferredProperties(PreferredProperties.any()));
if (child.getProperties().isDistributed()) {
child = withDerivedProperties(
gatheringExchange(idAllocator.getNextId(), child.getNode()),
child.getProperties());
}
return rebaseAndDeriveProperties(node, child);
}
@Override
public PlanWithProperties visitAggregation(AggregationNode node, Context context)
{
FunctionRegistry functionRegistry = metadata.getFunctionRegistry();
boolean decomposable = node.getFunctions()
.values().stream()
.map(functionRegistry::getAggregateFunctionImplementation)
.allMatch(InternalAggregationFunction::isDecomposable);
PreferredProperties preferredProperties = node.getGroupBy().isEmpty()
? PreferredProperties.any()
: PreferredProperties.derivePreferences(context.getPreferredProperties(), ImmutableSet.copyOf(node.getGroupBy()), Optional.of(node.getGroupBy()), grouped(node.getGroupBy()));
PlanWithProperties child = planChild(node, context.withPreferredProperties(preferredProperties));
if (!child.getProperties().isDistributed()) {
// If already unpartitioned, just drop the single aggregation back on
return rebaseAndDeriveProperties(node, child);
}
if (node.getGroupBy().isEmpty()) {
if (decomposable) {
return splitAggregation(node, child, partial -> gatheringExchange(idAllocator.getNextId(), partial));
}
else {
child = withDerivedProperties(
gatheringExchange(idAllocator.getNextId(), child.getNode()),
child.getProperties());
return rebaseAndDeriveProperties(node, child);
}
}
else {
if (child.getProperties().isPartitionedOn(node.getGroupBy())) {
return rebaseAndDeriveProperties(node, child);
}
else {
if (decomposable) {
return splitAggregation(
node,
child,
partial -> partitionedExchange(idAllocator.getNextId(), partial, new PartitionFunctionBinding(HASH, node.getGroupBy(), node.getHashSymbol())));
}
else {
child = withDerivedProperties(
partitionedExchange(idAllocator.getNextId(), child.getNode(), new PartitionFunctionBinding(HASH, node.getGroupBy(), node.getHashSymbol())),
child.getProperties());
return rebaseAndDeriveProperties(node, child);
}
}
}
}
@NotNull
private PlanWithProperties splitAggregation(AggregationNode node, PlanWithProperties newChild, Function<PlanNode, PlanNode> exchanger)
{
// otherwise, add a partial and final with an exchange in between
Map<Symbol, Symbol> masks = node.getMasks();
Map<Symbol, FunctionCall> finalCalls = new HashMap<>();
Map<Symbol, FunctionCall> intermediateCalls = new HashMap<>();
Map<Symbol, Signature> intermediateFunctions = new HashMap<>();
Map<Symbol, Symbol> intermediateMask = new HashMap<>();
for (Map.Entry<Symbol, FunctionCall> entry : node.getAggregations().entrySet()) {
Signature signature = node.getFunctions().get(entry.getKey());
InternalAggregationFunction function = metadata.getFunctionRegistry().getAggregateFunctionImplementation(signature);
Symbol intermediateSymbol = allocator.newSymbol(signature.getName(), function.getIntermediateType());
intermediateCalls.put(intermediateSymbol, entry.getValue());
intermediateFunctions.put(intermediateSymbol, signature);
if (masks.containsKey(entry.getKey())) {
intermediateMask.put(intermediateSymbol, masks.get(entry.getKey()));
}
// rewrite final aggregation in terms of intermediate function
finalCalls.put(entry.getKey(), new FunctionCall(QualifiedName.of(signature.getName()), ImmutableList.<Expression>of(new QualifiedNameReference(intermediateSymbol.toQualifiedName()))));
}
PlanWithProperties partial = withDerivedProperties(
new AggregationNode(
idAllocator.getNextId(),
newChild.getNode(),
node.getGroupBy(),
intermediateCalls,
intermediateFunctions,
intermediateMask,
PARTIAL,
node.getSampleWeight(),
node.getConfidence(),
node.getHashSymbol()),
newChild.getProperties());
PlanNode exchange = exchanger.apply(partial.getNode());
return withDerivedProperties(
new AggregationNode(
node.getId(),
exchange,
node.getGroupBy(),
finalCalls,
node.getFunctions(),
ImmutableMap.of(),
FINAL,
Optional.empty(),
node.getConfidence(),
node.getHashSymbol()),
deriveProperties(exchange, partial.getProperties()));
}
@Override
public PlanWithProperties visitMarkDistinct(MarkDistinctNode node, Context context)
{
PreferredProperties preferredChildProperties = PreferredProperties.derivePreferences(context.getPreferredProperties(), ImmutableSet.copyOf(node.getDistinctSymbols()), Optional.of(node.getDistinctSymbols()), grouped(node.getDistinctSymbols()));
PlanWithProperties child = node.getSource().accept(this, context.withPreferredProperties(preferredChildProperties));
if (!child.getProperties().isDistributed() ||
!child.getProperties().isPartitionedOn(node.getDistinctSymbols())) {
child = withDerivedProperties(
partitionedExchange(
idAllocator.getNextId(),
child.getNode(),
new PartitionFunctionBinding(HASH, node.getDistinctSymbols(), node.getHashSymbol())),
child.getProperties());
}
return rebaseAndDeriveProperties(node, child);
}
@Override
public PlanWithProperties visitWindow(WindowNode node, Context context)
{
List<LocalProperty<Symbol>> desiredProperties = new ArrayList<>();
if (!node.getPartitionBy().isEmpty()) {
desiredProperties.add(new GroupingProperty<>(node.getPartitionBy()));
}
for (Symbol symbol : node.getOrderBy()) {
desiredProperties.add(new SortingProperty<>(symbol, node.getOrderings().get(symbol)));
}
PlanWithProperties child = planChild(
node,
context.withPreferredProperties(PreferredProperties.derivePreferences(context.getPreferredProperties(), ImmutableSet.copyOf(node.getPartitionBy()), desiredProperties)));
if (!child.getProperties().isPartitionedOn(node.getPartitionBy())) {
if (node.getPartitionBy().isEmpty()) {
child = withDerivedProperties(
gatheringExchange(idAllocator.getNextId(), child.getNode()),
child.getProperties());
}
else {
child = withDerivedProperties(
partitionedExchange(idAllocator.getNextId(), child.getNode(), new PartitionFunctionBinding(HASH, node.getPartitionBy(), node.getHashSymbol())),
child.getProperties());
}
}
Iterator<Optional<LocalProperty<Symbol>>> matchIterator = LocalProperties.match(child.getProperties().getLocalProperties(), desiredProperties).iterator();
Set<Symbol> prePartitionedInputs = ImmutableSet.of();
if (!node.getPartitionBy().isEmpty()) {
Optional<LocalProperty<Symbol>> groupingRequirement = matchIterator.next();
Set<Symbol> unPartitionedInputs = groupingRequirement.map(LocalProperty::getColumns).orElse(ImmutableSet.of());
prePartitionedInputs = node.getPartitionBy().stream()
.filter(symbol -> !unPartitionedInputs.contains(symbol))
.collect(toImmutableSet());
}
int preSortedOrderPrefix = 0;
if (prePartitionedInputs.equals(ImmutableSet.copyOf(node.getPartitionBy()))) {
while (matchIterator.hasNext() && !matchIterator.next().isPresent()) {
preSortedOrderPrefix++;
}
}
return withDerivedProperties(
new WindowNode(
node.getId(),
child.getNode(),
node.getPartitionBy(),
node.getOrderBy(),
node.getOrderings(),
node.getFrame(),
node.getWindowFunctions(),
node.getSignatures(),
node.getHashSymbol(),
prePartitionedInputs,
preSortedOrderPrefix),
child.getProperties());
}
@Override
public PlanWithProperties visitRowNumber(RowNumberNode node, Context context)
{
if (node.getPartitionBy().isEmpty()) {
PlanWithProperties child = planChild(node, context.withPreferredProperties(PreferredProperties.undistributed()));
if (child.getProperties().isDistributed()) {
child = withDerivedProperties(
gatheringExchange(idAllocator.getNextId(), child.getNode()),
child.getProperties());
}
return rebaseAndDeriveProperties(node, child);
}
PlanWithProperties child = planChild(node, context.withPreferredProperties(PreferredProperties.derivePreferences(context.getPreferredProperties(), ImmutableSet.copyOf(node.getPartitionBy()), grouped(node.getPartitionBy()))));
// TODO: add config option/session property to force parallel plan if child is unpartitioned and window has a PARTITION BY clause
if (!child.getProperties().isPartitionedOn(node.getPartitionBy())) {
child = withDerivedProperties(
partitionedExchange(
idAllocator.getNextId(),
child.getNode(),
new PartitionFunctionBinding(HASH, node.getPartitionBy(), node.getHashSymbol())),
child.getProperties());
}
// TODO: streaming
return rebaseAndDeriveProperties(node, child);
}
@Override
public PlanWithProperties visitTopNRowNumber(TopNRowNumberNode node, Context context)
{
PreferredProperties preferredChildProperties;
Function<PlanNode, PlanNode> addExchange;
if (node.getPartitionBy().isEmpty()) {
preferredChildProperties = PreferredProperties.any();
addExchange = partial -> gatheringExchange(idAllocator.getNextId(), partial);
}
else {
preferredChildProperties = PreferredProperties.derivePreferences(context.getPreferredProperties(), ImmutableSet.copyOf(node.getPartitionBy()), grouped(node.getPartitionBy()));
addExchange = partial -> partitionedExchange(idAllocator.getNextId(), partial, new PartitionFunctionBinding(HASH, node.getPartitionBy(), node.getHashSymbol()));
}
PlanWithProperties child = planChild(node, context.withPreferredProperties(preferredChildProperties));
if (!child.getProperties().isPartitionedOn(node.getPartitionBy())) {
// add exchange + push function to child
child = withDerivedProperties(
new TopNRowNumberNode(
idAllocator.getNextId(),
child.getNode(),
node.getPartitionBy(),
node.getOrderBy(),
node.getOrderings(),
node.getRowNumberSymbol(),
node.getMaxRowCountPerPartition(),
true,
node.getHashSymbol()),
child.getProperties());
child = withDerivedProperties(addExchange.apply(child.getNode()), child.getProperties());
}
return rebaseAndDeriveProperties(node, child);
}
@Override
public PlanWithProperties visitTopN(TopNNode node, Context context)
{
PlanWithProperties child = planChild(node, context.withPreferredProperties(PreferredProperties.any()));
if (child.getProperties().isDistributed()) {
child = withDerivedProperties(
new TopNNode(idAllocator.getNextId(), child.getNode(), node.getCount(), node.getOrderBy(), node.getOrderings(), true),
child.getProperties());
child = withDerivedProperties(
gatheringExchange(idAllocator.getNextId(), child.getNode()),
child.getProperties());
}
return rebaseAndDeriveProperties(node, child);
}
@Override
public PlanWithProperties visitSort(SortNode node, Context context)
{
PlanWithProperties child = planChild(node, context.withPreferredProperties(PreferredProperties.undistributed()));
if (child.getProperties().isDistributed()) {
child = withDerivedProperties(
gatheringExchange(idAllocator.getNextId(), child.getNode()),
child.getProperties());
}
return rebaseAndDeriveProperties(node, child);
}
@Override
public PlanWithProperties visitLimit(LimitNode node, Context context)
{
PlanWithProperties child = planChild(node, context.withPreferredProperties(PreferredProperties.any()));
if (child.getProperties().isDistributed()) {
child = withDerivedProperties(
new LimitNode(idAllocator.getNextId(), child.getNode(), node.getCount()),
child.getProperties());
child = withDerivedProperties(
gatheringExchange(idAllocator.getNextId(), child.getNode()),
child.getProperties());
}
return rebaseAndDeriveProperties(node, child);
}
@Override
public PlanWithProperties visitDistinctLimit(DistinctLimitNode node, Context context)
{
PlanWithProperties child = planChild(node, context.withPreferredProperties(PreferredProperties.any()));
if (child.getProperties().isDistributed()) {
child = withDerivedProperties(
gatheringExchange(
idAllocator.getNextId(),
new DistinctLimitNode(idAllocator.getNextId(), child.getNode(), node.getLimit(), node.getHashSymbol())),
child.getProperties());
}
return rebaseAndDeriveProperties(node, child);
}
@Override
public PlanWithProperties visitFilter(FilterNode node, Context context)
{
if (node.getSource() instanceof TableScanNode) {
return planTableScan((TableScanNode) node.getSource(), node.getPredicate(), context);
}
return rebaseAndDeriveProperties(node, planChild(node, context));
}
@Override
public PlanWithProperties visitTableScan(TableScanNode node, Context context)
{
return planTableScan(node, BooleanLiteral.TRUE_LITERAL, context);
}
@Override
public PlanWithProperties visitTableWriter(TableWriterNode node, Context context)
{
PlanWithProperties source = node.getSource().accept(this, context);
if (redistributeWrites) {
source = withDerivedProperties(
partitionedExchange(idAllocator.getNextId(), source.getNode(), new PartitionFunctionBinding(ROUND_ROBIN, ImmutableList.of())),
source.getProperties()
);
}
return rebaseAndDeriveProperties(node, source);
}
private PlanWithProperties planTableScan(TableScanNode node, Expression predicate, Context context)
{
// don't include non-deterministic predicates
Expression deterministicPredicate = stripNonDeterministicConjuncts(predicate);
DomainTranslator.ExtractionResult decomposedPredicate = DomainTranslator.fromPredicate(
metadata,
session,
deterministicPredicate,
symbolAllocator.getTypes());
TupleDomain<ColumnHandle> simplifiedConstraint = decomposedPredicate.getTupleDomain()
.transform(node.getAssignments()::get)
.intersect(node.getCurrentConstraint());
Map<ColumnHandle, Symbol> assignments = ImmutableBiMap.copyOf(node.getAssignments()).inverse();
Expression constraint = combineConjuncts(
deterministicPredicate,
DomainTranslator.toPredicate(node.getCurrentConstraint().transform(assignments::get)));
// Layouts will be returned in order of the connector's preference
List<TableLayoutResult> layouts = metadata.getLayouts(
session, node.getTable(),
new Constraint<>(simplifiedConstraint, bindings -> !shouldPrune(constraint, node.getAssignments(), bindings)),
Optional.of(node.getOutputSymbols().stream()
.map(node.getAssignments()::get)
.collect(toImmutableSet())));
if (layouts.isEmpty()) {
return new PlanWithProperties(
new ValuesNode(idAllocator.getNextId(), node.getOutputSymbols(), ImmutableList.of()),
ActualProperties.undistributed());
}
// Filter out layouts that cannot supply all the required columns
layouts = layouts.stream()
.filter(layoutHasAllNeededOutputs(node))
.collect(toList());
checkState(!layouts.isEmpty(), "No usable layouts for %s", node);
List<PlanWithProperties> possiblePlans = layouts.stream()
.map(layout -> {
TableScanNode tableScan = new TableScanNode(
node.getId(),
node.getTable(),
node.getOutputSymbols(),
node.getAssignments(),
Optional.of(layout.getLayout().getHandle()),
simplifiedConstraint.intersect(layout.getLayout().getPredicate()),
Optional.ofNullable(node.getOriginalConstraint()).orElse(predicate));
PlanWithProperties result = new PlanWithProperties(tableScan, deriveProperties(tableScan, ImmutableList.of()));
Expression resultingPredicate = combineConjuncts(
DomainTranslator.toPredicate(layout.getUnenforcedConstraint().transform(assignments::get)),
stripDeterministicConjuncts(predicate),
decomposedPredicate.getRemainingExpression());
if (!BooleanLiteral.TRUE_LITERAL.equals(resultingPredicate)) {
return withDerivedProperties(
new FilterNode(idAllocator.getNextId(), result.getNode(), resultingPredicate),
deriveProperties(tableScan, ImmutableList.of()));
}
return result;
})
.collect(toList());
return pickPlan(possiblePlans, context);
}
private Predicate<TableLayoutResult> layoutHasAllNeededOutputs(TableScanNode node)
{
return layout -> !layout.getLayout().getColumns().isPresent()
|| layout.getLayout().getColumns().get().containsAll(Lists.transform(node.getOutputSymbols(), node.getAssignments()::get));
}
/**
* possiblePlans should be provided in layout preference order
*/
private PlanWithProperties pickPlan(List<PlanWithProperties> possiblePlans, Context context)
{
checkArgument(!possiblePlans.isEmpty());
if (preferStreamingOperators) {
possiblePlans = new ArrayList<>(possiblePlans);
Collections.sort(possiblePlans, Comparator.comparing(PlanWithProperties::getProperties, streamingExecutionPreference(context.getPreferredProperties()))); // stable sort; is Collections.min() guaranteed to be stable?
}
return possiblePlans.get(0);
}
private boolean shouldPrune(Expression predicate, Map<Symbol, ColumnHandle> assignments, Map<ColumnHandle, NullableValue> bindings)
{
List<Expression> conjuncts = extractConjuncts(predicate);
IdentityHashMap<Expression, Type> expressionTypes = getExpressionTypes(session, metadata, parser, symbolAllocator.getTypes(), predicate);
LookupSymbolResolver inputs = new LookupSymbolResolver(assignments, bindings);
// If any conjuncts evaluate to FALSE or null, then the whole predicate will never be true and so the partition should be pruned
for (Expression expression : conjuncts) {
ExpressionInterpreter optimizer = ExpressionInterpreter.expressionOptimizer(expression, metadata, session, expressionTypes);
Object optimized = optimizer.optimize(inputs);
if (Boolean.FALSE.equals(optimized) || optimized == null || optimized instanceof NullLiteral) {
return true;
}
}
return false;
}
@Override
public PlanWithProperties visitValues(ValuesNode node, Context context)
{
return new PlanWithProperties(node, ActualProperties.undistributed());
}
@Override
public PlanWithProperties visitTableFinish(TableFinishNode node, Context context)
{
PlanWithProperties child = planChild(node, context.withPreferredProperties(PreferredProperties.any()));
// if the child is already a gathering exchange, don't add another
if ((child.getNode() instanceof ExchangeNode) && ((ExchangeNode) child.getNode()).getType().equals(ExchangeNode.Type.GATHER)) {
return rebaseAndDeriveProperties(node, child);
}
if (child.getProperties().isDistributed() || !child.getProperties().isCoordinatorOnly()) {
child = withDerivedProperties(
gatheringExchange(idAllocator.getNextId(), child.getNode()),
child.getProperties());
}
return rebaseAndDeriveProperties(node, child);
}
@Override
public PlanWithProperties visitJoin(JoinNode node, Context context)
{
List<Symbol> leftSymbols = Lists.transform(node.getCriteria(), JoinNode.EquiJoinClause::getLeft);
List<Symbol> rightSymbols = Lists.transform(node.getCriteria(), JoinNode.EquiJoinClause::getRight);
PlanWithProperties left;
PlanWithProperties right;
if ((distributedJoins && !(node.getType() == INNER && leftSymbols.isEmpty())) || node.getType() == FULL || node.getType() == RIGHT) {
// The implementation of full outer join only works if the data is hash partitioned. See LookupJoinOperators#buildSideOuterJoinUnvisitedPositions
left = node.getLeft().accept(this, context.withPreferredProperties(PreferredProperties.hashPartitioned(leftSymbols)));
right = node.getRight().accept(this, context.withPreferredProperties(PreferredProperties.hashPartitioned(rightSymbols)));
// force partitioning
if (!left.getProperties().isHashPartitionedOn(leftSymbols)) {
left = withDerivedProperties(
partitionedExchange(idAllocator.getNextId(), left.getNode(), new PartitionFunctionBinding(HASH, leftSymbols, node.getLeftHashSymbol())),
left.getProperties());
}
if (!right.getProperties().isHashPartitionedOn(rightSymbols)) {
right = withDerivedProperties(
partitionedExchange(idAllocator.getNextId(), right.getNode(), new PartitionFunctionBinding(HASH, rightSymbols, node.getRightHashSymbol())),
right.getProperties());
}
}
else {
// It can only be INNER or LEFT here. Therefore, no flipping is necessary even though the below code assumes the node is not RIGHT.
left = node.getLeft().accept(this, context.withPreferredProperties(PreferredProperties.any()));
right = node.getRight().accept(this, context.withPreferredProperties(PreferredProperties.any()));
if (!left.getProperties().isDistributed() && right.getProperties().isDistributed()) {
// force single-node join
// TODO: if inner join, flip order and do a broadcast join
right = withDerivedProperties(
gatheringExchange(idAllocator.getNextId(), right.getNode()),
right.getProperties());
}
else if (left.getProperties().isDistributed() && !(left.getProperties().isHashPartitionedOn(leftSymbols) && right.getProperties().isHashPartitionedOn(rightSymbols))) {
right = withDerivedProperties(
replicatedExchange(idAllocator.getNextId(), right.getNode()),
right.getProperties());
}
}
JoinNode result = new JoinNode(node.getId(),
node.getType(),
left.getNode(),
right.getNode(),
node.getCriteria(),
node.getLeftHashSymbol(),
node.getRightHashSymbol());
return new PlanWithProperties(result, deriveProperties(result, ImmutableList.of(left.getProperties(), right.getProperties())));
}
@Override
public PlanWithProperties visitUnnest(UnnestNode node, Context context)
{
PreferredProperties translatedPreferred = context.getPreferredProperties().translate(symbol -> node.getReplicateSymbols().contains(symbol) ? Optional.of(symbol) : Optional.empty());
return rebaseAndDeriveProperties(node, planChild(node, context.withPreferredProperties(translatedPreferred)));
}
@Override
public PlanWithProperties visitSemiJoin(SemiJoinNode node, Context context)
{
PlanWithProperties source;
PlanWithProperties filteringSource;
if (distributedJoins && !context.isDownstreamIsDelete()) {
List<Symbol> sourceSymbols = ImmutableList.of(node.getSourceJoinSymbol());
List<Symbol> filteringSourceSymbols = ImmutableList.of(node.getFilteringSourceJoinSymbol());
source = node.getSource().accept(this, context.withPreferredProperties(PreferredProperties.hashPartitioned(sourceSymbols)));
// Child will not satisfy hash with null replicate anyways, and repartition is always necessary.
// Therefore, tell the filtering source pick whatever partition it likes.
filteringSource = node.getFilteringSource().accept(this, context.withPreferredProperties(PreferredProperties.any()));
// force partitioning if source isn't already partitioned on sourceSymbols
if (!source.getProperties().isHashPartitionedOn(sourceSymbols)) {
source = withDerivedProperties(
partitionedExchange(idAllocator.getNextId(), source.getNode(), new PartitionFunctionBinding(HASH, sourceSymbols, node.getSourceHashSymbol())),
source.getProperties());
}
// The following statements would normally be written as: if (condition) { filteringSource = ...; }
// However, the if-condition will always evaluate to true in this case because no externally-visible node produces partition with null replicate.
// As a result, it is written as checkState instead.
checkState(!filteringSource.getProperties().isHashPartitionedOn(filteringSourceSymbols) || !filteringSource.getProperties().isNullReplication());
filteringSource = withDerivedProperties(
partitionedExchange(
idAllocator.getNextId(),
filteringSource.getNode(),
new PartitionFunctionBinding(HASH, filteringSourceSymbols, node.getFilteringSourceHashSymbol(), true, OptionalInt.empty())),
filteringSource.getProperties());
}
else {
source = node.getSource().accept(this, context.withPreferredProperties(PreferredProperties.any()));
// Delete operator works fine even if TableScans on the filtering (right) side is not co-located with itself. It only cares about the corresponding TableScan,
// which is always on the source (left) side. Therefore, hash-partitioned semi-join is always allowed on the filtering side.
filteringSource = node.getFilteringSource().accept(this, context.withPreferredProperties(PreferredProperties.any()).withHashPartitionedSemiJoinBanned(false));
// make filtering source match requirements of source
if (source.getProperties().isDistributed()) {
filteringSource = withDerivedProperties(
replicatedExchange(idAllocator.getNextId(), filteringSource.getNode()),
filteringSource.getProperties());
}
else {
filteringSource = withDerivedProperties(
gatheringExchange(idAllocator.getNextId(), filteringSource.getNode()),
filteringSource.getProperties());
}
}
return rebaseAndDeriveProperties(node, ImmutableList.of(source, filteringSource));
}
@Override
public PlanWithProperties visitIndexJoin(IndexJoinNode node, Context context)
{
List<Symbol> joinColumns = Lists.transform(node.getCriteria(), IndexJoinNode.EquiJoinClause::getProbe);
// Only prefer grouping on join columns if no parent local property preferences
List<LocalProperty<Symbol>> desiredLocalProperties = context.getPreferredProperties().getLocalProperties().isEmpty() ? grouped(joinColumns) : ImmutableList.of();
PlanWithProperties probeSource = node.getProbeSource().accept(this, context.withPreferredProperties(PreferredProperties.derivePreferences(context.getPreferredProperties(), ImmutableSet.copyOf(joinColumns), desiredLocalProperties)));
ActualProperties probeProperties = probeSource.getProperties();
PlanWithProperties indexSource = node.getIndexSource().accept(this, context.withPreferredProperties(PreferredProperties.any()));
// TODO: allow repartitioning if unpartitioned to increase parallelism
if (shouldRepartitionForIndexJoin(joinColumns, context.getPreferredProperties(), probeProperties)) {
probeSource = withDerivedProperties(
partitionedExchange(idAllocator.getNextId(), probeSource.getNode(), new PartitionFunctionBinding(HASH, joinColumns, node.getProbeHashSymbol())),
probeProperties);
}
// TODO: if input is grouped, create streaming join
// index side is really a nested-loops plan, so don't add exchanges
PlanNode result = ChildReplacer.replaceChildren(node, ImmutableList.of(probeSource.getNode(), node.getIndexSource()));
return new PlanWithProperties(result, deriveProperties(result, ImmutableList.of(probeSource.getProperties(), indexSource.getProperties())));
}
private boolean shouldRepartitionForIndexJoin(List<Symbol> joinColumns, PreferredProperties parentPreferredProperties, ActualProperties probeProperties)
{
// See if distributed index joins are enabled
if (!distributedIndexJoins) {
return false;
}
// No point in repartitioning if the plan is not distributed
if (!probeProperties.isDistributed()) {
return false;
}
Optional<PreferredProperties.Partitioning> parentPartitioningPreferences = parentPreferredProperties.getGlobalProperties()
.flatMap(PreferredProperties.Global::getPartitioningProperties);
// Disable repartitioning if it would disrupt a parent's partitioning preference when streaming is enabled
boolean parentAlreadyPartitionedOnChild = parentPartitioningPreferences
.map(partitioning -> probeProperties.isPartitionedOn(partitioning.getPartitioningColumns()))
.orElse(false);
if (preferStreamingOperators && parentAlreadyPartitionedOnChild) {
return false;
}
// Otherwise, repartition if we need to align with the join columns
if (!probeProperties.isPartitionedOn(joinColumns)) {
return true;
}
// If we are already partitioned on the join columns because the data has been forced effectively into one stream,
// then we should repartition if that would make a difference (from the single stream state).
return probeProperties.isEffectivelySinglePartition() && probeProperties.isRepartitionEffective(joinColumns);
}
@Override
public PlanWithProperties visitIndexSource(IndexSourceNode node, Context context)
{
return new PlanWithProperties(node, ActualProperties.undistributed());
}
@Override
public PlanWithProperties visitUnion(UnionNode node, Context context)
{
if (!context.getPreferredProperties().getGlobalProperties().isPresent() || !context.getPreferredProperties().getGlobalProperties().get().isHashPartitioned()) {
// first, classify children into partitioned and unpartitioned
List<PlanNode> unpartitionedChildren = new ArrayList<>();
List<List<Symbol>> unpartitionedOutputLayouts = new ArrayList<>();
List<PlanNode> partitionedChildren = new ArrayList<>();
List<List<Symbol>> partitionedOutputLayouts = new ArrayList<>();
List<PlanNode> sources = node.getSources();
for (int i = 0; i < sources.size(); i++) {
PlanWithProperties child = sources.get(i).accept(this, context.withPreferredProperties(PreferredProperties.any()));
if (!child.getProperties().isDistributed()) {
unpartitionedChildren.add(child.getNode());
unpartitionedOutputLayouts.add(node.sourceOutputLayout(i));
}
else {
partitionedChildren.add(child.getNode());
partitionedOutputLayouts.add(node.sourceOutputLayout(i));
}
}
PlanNode result = null;
if (!partitionedChildren.isEmpty()) {
// add an exchange above partitioned inputs and fold it into the
// set of unpartitioned inputs
result = new ExchangeNode(
idAllocator.getNextId(),
ExchangeNode.Type.GATHER,
Optional.empty(),
partitionedChildren,
node.getOutputSymbols(),
partitionedOutputLayouts);
unpartitionedChildren.add(result);
unpartitionedOutputLayouts.add(result.getOutputSymbols());
}
// if there's at least one unpartitioned input (including the exchange that might have been added in the
// previous step), add a local union
if (unpartitionedChildren.size() > 1) {
ImmutableListMultimap.Builder<Symbol, Symbol> mappings = ImmutableListMultimap.builder();
for (int i = 0; i < node.getOutputSymbols().size(); i++) {
for (List<Symbol> outputLayout : unpartitionedOutputLayouts) {
mappings.put(node.getOutputSymbols().get(i), outputLayout.get(i));
}
}
result = new UnionNode(node.getId(), unpartitionedChildren, mappings.build());
}
return new PlanWithProperties(result, ActualProperties.undistributed());
}
// hash partition the sources
List<Symbol> hashingColumns = context.getPreferredProperties().getGlobalProperties().get().getPartitioningProperties().get().getHashingOrder().get();
ImmutableList.Builder<PlanNode> partitionedSources = ImmutableList.builder();
ImmutableListMultimap.Builder<Symbol, Symbol> outputToSourcesMapping = ImmutableListMultimap.builder();
for (int sourceIndex = 0; sourceIndex < node.getSources().size(); sourceIndex++) {
ImmutableList.Builder<Symbol> hashColumnsBuilder = ImmutableList.builder();
for (Symbol column : hashingColumns) {
hashColumnsBuilder.add(node.getSymbolMapping().get(column).get(sourceIndex));
}
List<Symbol> sourceHashColumns = hashColumnsBuilder.build();
PlanWithProperties source = node.getSources().get(sourceIndex).accept(this, context.withPreferredProperties(PreferredProperties.hashPartitioned(sourceHashColumns)));
if (!source.getProperties().isHashPartitionedOn(sourceHashColumns)) {
source = withDerivedProperties(
partitionedExchange(
idAllocator.getNextId(),
source.getNode(),
new PartitionFunctionBinding(HASH, sourceHashColumns, Optional.empty())),
source.getProperties());
}
partitionedSources.add(source.getNode());
for (int column = 0; column < node.getOutputSymbols().size(); column++) {
outputToSourcesMapping.put(node.getOutputSymbols().get(column), node.sourceOutputLayout(sourceIndex).get(column));
}
}
return new PlanWithProperties(new UnionNode(node.getId(), partitionedSources.build(), outputToSourcesMapping.build()), ActualProperties.hashPartitioned(hashingColumns));