Skip to content

Commit 658371b

Browse files
committed
[CALCITE-6846] Support basic dphyp join reorder algorithm
1 parent 5a1b15c commit 658371b

File tree

9 files changed

+1137
-0
lines changed

9 files changed

+1137
-0
lines changed

core/src/main/java/org/apache/calcite/rel/rules/CoreRules.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -816,4 +816,14 @@ private CoreRules() {}
816816
WINDOW_REDUCE_EXPRESSIONS =
817817
ReduceExpressionsRule.WindowReduceExpressionsRule.WindowReduceExpressionsRuleConfig
818818
.DEFAULT.toRule();
819+
/** Rule that flattens a tree of {@link LogicalJoin}s
820+
* into a single {@link HyperGraph} with N inputs. */
821+
public static final JoinToHyperGraphRule JOIN_TO_HYPER_GRAPH =
822+
JoinToHyperGraphRule.Config.DEFAULT.toRule();
823+
824+
/** Rule that re-orders a {@link Join} tree using dphyp algorithm.
825+
*
826+
* @see #JOIN_TO_HYPER_GRAPH */
827+
public static final DphypJoinReorderRule HYPER_GRAPH_OPTIMIZE =
828+
DphypJoinReorderRule.Config.DEFAULT.toRule();
819829
}
Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to you under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
package org.apache.calcite.rel.rules;
18+
19+
import org.apache.calcite.rel.RelNode;
20+
import org.apache.calcite.rel.core.JoinRelType;
21+
import org.apache.calcite.rel.metadata.RelMetadataQuery;
22+
import org.apache.calcite.rex.RexNode;
23+
import org.apache.calcite.tools.RelBuilder;
24+
25+
import org.checkerframework.checker.nullness.qual.Nullable;
26+
27+
import java.util.HashMap;
28+
import java.util.List;
29+
30+
import static com.google.common.base.Preconditions.checkArgument;
31+
32+
/**
33+
* The core process of dphyp enumeration algorithm.
34+
*/
35+
public class DpHyp {
36+
37+
private HyperGraph hyperGraph;
38+
39+
private HashMap<Long, RelNode> dpTable;
40+
41+
private RelBuilder builder;
42+
43+
private RelMetadataQuery mq;
44+
45+
public DpHyp(HyperGraph hyperGraph, RelBuilder builder, RelMetadataQuery relMetadataQuery) {
46+
this.hyperGraph = hyperGraph;
47+
this.dpTable = new HashMap<>();
48+
this.builder = builder;
49+
this.mq = relMetadataQuery;
50+
}
51+
52+
public void startEnumerateJoin() {
53+
int size = hyperGraph.getInputs().size();
54+
for (int i = 0; i < size; i++) {
55+
long singleNode = LongBitmap.newBitmap(i);
56+
dpTable.put(singleNode, hyperGraph.getInput(i));
57+
hyperGraph.initEdgeBitMap(singleNode);
58+
}
59+
60+
// start enumerating from the second to last
61+
for (int i = size - 2; i >= 0; i--) {
62+
long csg = LongBitmap.newBitmap(i);
63+
long forbidden = csg - 1;
64+
emitCsg(csg);
65+
enumerateCsgRec(csg, forbidden);
66+
}
67+
}
68+
69+
private void emitCsg(long csg) {
70+
long forbidden = csg | LongBitmap.getBvBitmap(csg);
71+
long neighbors = hyperGraph.getNeighborBitmap(csg, forbidden);
72+
73+
LongBitmap.ReverseIterator reverseIterator = new LongBitmap.ReverseIterator(neighbors);
74+
for (long cmp : reverseIterator) {
75+
List<HyperEdge> edges = hyperGraph.connectCsgCmp(csg, cmp);
76+
if (!edges.isEmpty()) {
77+
emitCsgCmp(csg, cmp, edges);
78+
}
79+
// forbidden the nodes that smaller than current cmp when extend cmp, e.g.
80+
// neighbors = {t1, t2}, t1 and t2 are connected.
81+
// when extented t2, we will get (t1, t2)
82+
// when extented t1, we will get (t1, t2) repeated
83+
long newForbidden =
84+
(cmp | LongBitmap.getBvBitmap(cmp)) & neighbors;
85+
newForbidden = newForbidden | forbidden;
86+
enumerateCmpRec(csg, cmp, newForbidden);
87+
}
88+
}
89+
90+
private void enumerateCsgRec(long csg, long forbidden) {
91+
long neighbors = hyperGraph.getNeighborBitmap(csg, forbidden);
92+
LongBitmap.SubsetIterator subsetIterator = new LongBitmap.SubsetIterator(neighbors);
93+
for (long subNeighbor : subsetIterator) {
94+
hyperGraph.updateEdgesForUnion(csg, subNeighbor);
95+
long newCsg = csg | subNeighbor;
96+
if (dpTable.containsKey(newCsg)) {
97+
emitCsg(newCsg);
98+
}
99+
}
100+
long newForbidden = forbidden | neighbors;
101+
subsetIterator.reset();
102+
for (long subNeighbor : subsetIterator) {
103+
long newCsg = csg | subNeighbor;
104+
enumerateCsgRec(newCsg, newForbidden);
105+
}
106+
}
107+
108+
private void enumerateCmpRec(long csg, long cmp, long forbidden) {
109+
long neighbors = hyperGraph.getNeighborBitmap(cmp, forbidden);
110+
LongBitmap.SubsetIterator subsetIterator = new LongBitmap.SubsetIterator(neighbors);
111+
for (long subNeighbor : subsetIterator) {
112+
long newCmp = cmp | subNeighbor;
113+
hyperGraph.updateEdgesForUnion(cmp, subNeighbor);
114+
if (dpTable.containsKey(newCmp)) {
115+
List<HyperEdge> edges = hyperGraph.connectCsgCmp(csg, newCmp);
116+
if (!edges.isEmpty()) {
117+
emitCsgCmp(csg, newCmp, edges);
118+
}
119+
}
120+
}
121+
long newForbidden = forbidden | neighbors;
122+
subsetIterator.reset();
123+
for (long subNeighbor : subsetIterator) {
124+
long newCmp = cmp | subNeighbor;
125+
enumerateCmpRec(csg, newCmp, newForbidden);
126+
}
127+
}
128+
129+
private void emitCsgCmp(long csg, long cmp, List<HyperEdge> edges) {
130+
checkArgument(dpTable.containsKey(csg));
131+
checkArgument(dpTable.containsKey(cmp));
132+
RelNode child1 = dpTable.get(csg);
133+
RelNode child2 = dpTable.get(cmp);
134+
135+
JoinRelType joinType = hyperGraph.extractJoinType(edges);
136+
if (joinType == null) {
137+
return;
138+
}
139+
RexNode joinCond1 = hyperGraph.extractJoinCond(child1, child2, edges);
140+
RelNode newPlan1 = builder
141+
.push(child1)
142+
.push(child2)
143+
.join(joinType, joinCond1)
144+
.build();
145+
146+
// swap left and right
147+
RexNode joinCond2 = hyperGraph.extractJoinCond(child2, child1, edges);
148+
RelNode newPlan2 = builder
149+
.push(child2)
150+
.push(child1)
151+
.join(joinType, joinCond2)
152+
.build();
153+
RelNode winPlan = mq.getCumulativeCost(newPlan1).isLt(mq.getCumulativeCost(newPlan2))
154+
? newPlan1
155+
: newPlan2;
156+
157+
if (!dpTable.containsKey(csg | cmp)) {
158+
dpTable.put(csg | cmp, winPlan);
159+
} else {
160+
RelNode oriPlan = dpTable.get(csg | cmp);
161+
if (mq.getCumulativeCost(winPlan).isLt(mq.getCumulativeCost(oriPlan))) {
162+
dpTable.put(csg | cmp, winPlan);
163+
}
164+
}
165+
}
166+
167+
public @Nullable RelNode getBestPlan() {
168+
int size = hyperGraph.getInputs().size();
169+
long wholeGraph = LongBitmap.newBitmapBetween(0, size);
170+
return dpTable.get(wholeGraph);
171+
}
172+
173+
}
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to you under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
package org.apache.calcite.rel.rules;
18+
19+
import org.apache.calcite.plan.RelOptRuleCall;
20+
import org.apache.calcite.plan.RelRule;
21+
import org.apache.calcite.rel.RelNode;
22+
import org.apache.calcite.rel.core.Join;
23+
import org.apache.calcite.rex.RexBuilder;
24+
import org.apache.calcite.rex.RexNode;
25+
import org.apache.calcite.tools.RelBuilder;
26+
27+
import org.immutables.value.Value;
28+
29+
import java.util.ArrayList;
30+
import java.util.List;
31+
32+
/** Rule that re-orders a {@link Join} tree using dphyp algorithm.
33+
*
34+
* @see CoreRules#HYPER_GRAPH_OPTIMIZE */
35+
@Value.Enclosing
36+
public class DphypJoinReorderRule
37+
extends RelRule<DphypJoinReorderRule.Config>
38+
implements TransformationRule {
39+
40+
protected DphypJoinReorderRule(Config config) {
41+
super(config);
42+
}
43+
44+
@Override public void onMatch(RelOptRuleCall call) {
45+
HyperGraph hyperGraph = call.rel(0);
46+
RelBuilder relBuilder = call.builder();
47+
// make all field name unique and convert the
48+
// HyperEdge condition from RexInputRef to RexInputFieldName
49+
hyperGraph.convertHyperEdgeCond();
50+
51+
// enumerate by Dphyp
52+
DpHyp dpHyp = new DpHyp(hyperGraph, relBuilder, call.getMetadataQuery());
53+
dpHyp.startEnumerateJoin();
54+
RelNode orderedJoin = dpHyp.getBestPlan();
55+
if (orderedJoin == null) {
56+
return;
57+
}
58+
59+
// permute field to origin order
60+
List<String> oriNames = hyperGraph.getRowType().getFieldNames();
61+
List<String> newNames = orderedJoin.getRowType().getFieldNames();
62+
List<RexNode> projects = new ArrayList<>();
63+
RexBuilder rexBuilder = hyperGraph.getCluster().getRexBuilder();
64+
for (String oriName : oriNames) {
65+
projects.add(rexBuilder.makeInputRef(orderedJoin, newNames.indexOf(oriName)));
66+
}
67+
68+
RelNode result = call.builder()
69+
.push(orderedJoin)
70+
.project(projects)
71+
.build();
72+
call.transformTo(result);
73+
}
74+
75+
/** Rule configuration. */
76+
@Value.Immutable
77+
public interface Config extends RelRule.Config {
78+
Config DEFAULT = ImmutableDphypJoinReorderRule.Config.of()
79+
.withOperandSupplier(b1 ->
80+
b1.operand(HyperGraph.class).anyInputs());
81+
82+
@Override default DphypJoinReorderRule toRule() {
83+
return new DphypJoinReorderRule(this);
84+
}
85+
}
86+
}
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to you under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
package org.apache.calcite.rel.rules;
18+
19+
import org.apache.calcite.rel.core.JoinRelType;
20+
import org.apache.calcite.rex.RexNode;
21+
22+
/**
23+
* Edge in HyperGraph, that represents a join predicate.
24+
*/
25+
public class HyperEdge {
26+
27+
private long leftNodeBits;
28+
29+
private long rightNodeBits;
30+
31+
private JoinRelType joinType;
32+
33+
private RexNode condition;
34+
35+
public HyperEdge(long leftNodeBits, long rightNodeBits, JoinRelType joinType, RexNode condition) {
36+
this.leftNodeBits = leftNodeBits;
37+
this.rightNodeBits = rightNodeBits;
38+
this.joinType = joinType;
39+
this.condition = condition;
40+
}
41+
42+
public long getNodeBitmap() {
43+
return leftNodeBits | rightNodeBits;
44+
}
45+
46+
public long getLeftNodeBitmap() {
47+
return leftNodeBits;
48+
}
49+
50+
public long getRightNodeBitmap() {
51+
return rightNodeBits;
52+
}
53+
54+
// hyperedge (u, v) is simple if |u| = |v| = 1
55+
public boolean isSimple() {
56+
boolean leftSimple = (leftNodeBits & (leftNodeBits - 1)) == 0;
57+
boolean rightSimple = (rightNodeBits & (rightNodeBits - 1)) == 0;
58+
return leftSimple && rightSimple;
59+
}
60+
61+
public JoinRelType getJoinType() {
62+
return joinType;
63+
}
64+
65+
public RexNode getCondition() {
66+
return condition;
67+
}
68+
69+
@Override public String toString() {
70+
StringBuilder sb = new StringBuilder();
71+
sb.append(LongBitmap.printBitmap(leftNodeBits))
72+
.append("——").append(joinType).append("——")
73+
.append(LongBitmap.printBitmap(rightNodeBits));
74+
return sb.toString();
75+
}
76+
77+
// before starting dphyp, replace RexInputRef to RexInputFieldName
78+
public void replaceCondition(RexNode fieldNameCond) {
79+
this.condition = fieldNameCond;
80+
}
81+
82+
}

0 commit comments

Comments
 (0)