924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r1010277591


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/PullUpPredicates.java:
##########
@@ -0,0 +1,141 @@
+// 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.
+
+package org.apache.doris.nereids.rules.rewrite.logical;
+
+import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.NamedExpression;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import 
org.apache.doris.nereids.trees.expressions.functions.agg.AggregateFunction;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalJoin;
+import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
+import org.apache.doris.nereids.trees.plans.visitor.PlanVisitor;
+import org.apache.doris.nereids.util.ExpressionUtils;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * poll up effective predicates from operator's children.
+ */
+public class PullUpPredicates extends PlanVisitor<Set<Expression>, Void> {
+
+    PredicatePropagation propagation = new PredicatePropagation();
+
+    @Override
+    public Set<Expression> visit(Plan plan, Void context) {
+        if (plan.arity() == 1) {
+            return plan.child(0).accept(this, context);
+        }
+        return Sets.newHashSet();
+    }
+
+    @Override
+    public Set<Expression> visitLogicalFilter(LogicalFilter<? extends Plan> 
filter, Void context) {
+        List<Expression> predicates = 
Lists.newArrayList(filter.getConjuncts());
+        predicates.addAll(filter.child().accept(this, context));
+        return getAvailableExpressions(Sets.newHashSet(predicates), filter);
+    }
+
+    @Override
+    public Set<Expression> visitLogicalJoin(LogicalJoin<? extends Plan, ? 
extends Plan> join, Void context) {
+        Set<Expression> predicates = Sets.newHashSet();
+        Set<Expression> leftPredicates = join.left().accept(this, context);
+        Set<Expression> rightPredicates = join.right().accept(this, context);
+        switch (join.getJoinType()) {
+            case INNER_JOIN:
+            case CROSS_JOIN:
+                predicates.addAll(leftPredicates);
+                predicates.addAll(rightPredicates);
+                join.getOnClauseCondition().map(on -> 
predicates.addAll(ExpressionUtils.extractConjunction(on)));
+                break;
+            case LEFT_SEMI_JOIN:
+                predicates.addAll(leftPredicates);
+                join.getOnClauseCondition().map(on -> 
predicates.addAll(ExpressionUtils.extractConjunction(on)));
+                break;
+            case RIGHT_SEMI_JOIN:
+                predicates.addAll(rightPredicates);
+                join.getOnClauseCondition().map(on -> 
predicates.addAll(ExpressionUtils.extractConjunction(on)));
+                break;
+            case LEFT_OUTER_JOIN:
+            case LEFT_ANTI_JOIN:
+                predicates.addAll(leftPredicates);
+                break;
+            case RIGHT_OUTER_JOIN:
+            case RIGHT_ANTI_JOIN:
+                predicates.addAll(rightPredicates);
+                break;
+            default:
+        }
+        return getAvailableExpressions(predicates, join);
+    }
+
+    @Override
+    public Set<Expression> visitLogicalProject(LogicalProject<? extends Plan> 
project, Void context) {
+        Set<Expression> childPredicates = project.child().accept(this, 
context);
+        Map<Expression, Slot> expressionSlotMap = project.getAliasToProducer()
+                .entrySet()
+                .stream()
+                .collect(Collectors.toMap(Entry::getValue, Entry::getKey));
+        Expression expression = 
ExpressionUtils.replace(ExpressionUtils.and(Lists.newArrayList(childPredicates)),
+                expressionSlotMap);
+        Set<Expression> predicates = 
Sets.newHashSet(ExpressionUtils.extractConjunction(expression));
+        return getAvailableExpressions(predicates, project);
+    }
+
+    @Override
+    public Set<Expression> visitLogicalAggregate(LogicalAggregate<? extends 
Plan> aggregate, Void context) {
+        Set<Expression> childPredicates = aggregate.child().accept(this, 
context);
+        Map<Expression, Slot> expressionSlotMap = 
aggregate.getOutputExpressions()
+                .stream()
+                .filter(this::hasAgg)
+                .collect(Collectors.toMap(
+                        namedExpr -> {
+                            if (namedExpr instanceof Alias) {
+                                return ((Alias) namedExpr).child();
+                            } else {
+                                return namedExpr;
+                            }
+                        }, NamedExpression::toSlot)
+                );
+        Expression expression = 
ExpressionUtils.replace(ExpressionUtils.and(Lists.newArrayList(childPredicates)),
+                expressionSlotMap);
+        Set<Expression> predicates = 
Sets.newHashSet(ExpressionUtils.extractConjunction(expression));
+        return getAvailableExpressions(predicates, aggregate);
+    }
+
+    public Set<Expression> getAvailableExpressions(Set<Expression> predicates, 
Plan plan) {
+        predicates.addAll(propagation.infer(predicates));
+        return predicates.stream()
+                .filter(p -> 
plan.getOutputSet().containsAll(p.getInputSlots()))
+                .collect(Collectors.toSet());
+    }
+
+    private boolean hasAgg(Expression expression) {
+        return expression.anyMatch(AggregateFunction.class::isInstance);
+    }

Review Comment:
   change to private method



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/InferPredicates.java:
##########
@@ -0,0 +1,137 @@
+// 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.
+
+package org.apache.doris.nereids.rules.rewrite.logical;
+
+import org.apache.doris.nereids.pattern.MatchingContext;
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.rules.rewrite.RewriteRuleFactory;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalJoin;
+import org.apache.doris.nereids.util.ExpressionUtils;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * infer additional predicates for `LogicalFilter` and `LogicalJoin`.
+ */
+public class InferPredicates implements RewriteRuleFactory {
+    PredicatePropagation propagation = new PredicatePropagation();
+    PullUpPredicates pollUpPredicates = new PullUpPredicates();
+
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                inferWhere(),
+                inferOn()
+        );
+    }
+
+    /**
+     * reference `inferOn`
+     */
+    private Rule inferWhere() {
+        return logicalFilter(any()).thenApply(ctx -> {
+            LogicalFilter<Plan> root = ctx.root;
+            Plan filter = getOriginalPlan(ctx, root);
+            Set<Expression> filterPredicates = filter.accept(pollUpPredicates, 
null);
+            Set<Expression> filterChildPredicates = 
filter.child(0).accept(pollUpPredicates, null);
+            filterPredicates.removeAll(filterChildPredicates);
+            root.getConjuncts().forEach(filterPredicates::remove);
+            if (!filterPredicates.isEmpty()) {
+                filterPredicates.addAll(root.getConjuncts());
+                return new 
LogicalFilter<>(ExpressionUtils.and(Lists.newArrayList(filterPredicates)), 
root.child());
+            }
+            return root;
+        }).toRule(RuleType.INFER_PREDICATES_FOR_WHERE);
+    }
+
+    /**
+     * The logic is as follows:
+     * 1. poll up bottom predicate then infer additional predicates
+     *   for example:
+     *   select * from (select * from t1 where t1.id = 1) t join t2 on t.id = 
t2.id
+     *   1. poll up bottom predicate
+     *      select * from (select * from t1 where t1.id = 1) t join t2 on t.id 
= t2.id and t.id = 1
+     *   2. infer
+     *      select * from (select * from t1 where t1.id = 1) t join t2 on t.id 
= t2.id and t.id = 1 and t2.id = 1
+     *   finally transformed sql:
+     *      select * from (select * from t1 where t1.id = 1) t join t2 on t.id 
= t2.id and t2.id = 1
+     * 2. put these predicates into `otherJoinConjuncts` , these predicates 
are processed in the next
+     *   round of predicate push-down
+     */
+    private Rule inferOn() {
+        return logicalJoin(any(), any()).thenApply(ctx -> {
+            LogicalJoin<Plan, Plan> root = ctx.root;
+            Plan left = getOriginalPlan(ctx, root.left());
+            Plan right = getOriginalPlan(ctx, root.right());
+            Set<Expression> expressions = getAllExpressions(left, right, 
root.getOnClauseCondition());
+            List<Expression> otherJoinConjuncts = 
Lists.newArrayList(root.getOtherJoinConjuncts());
+            switch (root.getJoinType()) {
+                case INNER_JOIN:
+                case CROSS_JOIN:
+                case LEFT_SEMI_JOIN:
+                case RIGHT_SEMI_JOIN:
+                    otherJoinConjuncts.addAll(inferNewPredicate(left, 
expressions));
+                    otherJoinConjuncts.addAll(inferNewPredicate(right, 
expressions));
+                    break;
+                case LEFT_OUTER_JOIN:
+                case LEFT_ANTI_JOIN:
+                    otherJoinConjuncts.addAll(inferNewPredicate(right, 
expressions));
+                    break;
+                case RIGHT_OUTER_JOIN:
+                case RIGHT_ANTI_JOIN:
+                    otherJoinConjuncts.addAll(inferNewPredicate(left, 
expressions));
+                    break;
+                default:
+                    return root;
+            }
+            return root.withOtherJoinConjuncts(otherJoinConjuncts);
+        }).toRule(RuleType.INFER_PREDICATES_FOR_ON);
+    }
+
+    private Plan getOriginalPlan(MatchingContext context, Plan patternPlan) {
+        patternPlan.getGroupExpression().orElseThrow(() -> new 
IllegalArgumentException("GroupExpression not exists."));
+        return 
context.cascadesContext.getMemo().copyOut(patternPlan.getGroupExpression().get(),
 false);
+    }

Review Comment:
   This copy out inefficiency, every filter/join will copy out every child plan 
tree, there are a lot of duplicate copies.
   How about copy out the root group once, and do bottom up rewrite, then copy 
into the memo



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/PredicatePropagation.java:
##########
@@ -0,0 +1,85 @@
+// 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.
+
+package org.apache.doris.nereids.rules.rewrite.logical;
+
+import org.apache.doris.nereids.trees.expressions.EqualTo;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import 
org.apache.doris.nereids.trees.expressions.visitor.DefaultExpressionRewriter;
+
+import com.google.common.collect.Sets;
+
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * derive additional predicates.
+ * for example:
+ * a = b and a = 1 => b = 1
+ */
+public class PredicatePropagation {
+
+    /**
+     * infer additional predicates.
+     */
+    public Set<Expression> infer(Set<Expression> predicates) {
+        Set<Expression> inferred = Sets.newHashSet();
+        for (Expression predicate : predicates) {
+            if (canEquivalentInfer(predicate)) {
+                List<Expression> newInferred = predicates.stream()
+                        .filter(p -> !p.equals(predicate))
+                        .map(p -> doInfer(predicate, p))
+                        .collect(Collectors.toList());
+                inferred.addAll(newInferred);
+            }
+        }
+        inferred.removeAll(predicates);
+        return inferred;
+    }
+
+    /**
+     * Use the left or right child of `leftSlotEqualToRightSlot` to replace 
the left or right child of `expression`
+     */
+    private Expression doInfer(Expression leftSlotEqualToRightSlot, Expression 
expression) {
+        return expression.accept(new DefaultExpressionRewriter<Void>() {
+            @Override
+            public Expression visit(Expression expr, Void context) {
+                expr = super.visit(expr, context);
+
+                // flip leftSlot and rightSlot
+                if (expr.equals(leftSlotEqualToRightSlot.child(0))) {
+                    return leftSlotEqualToRightSlot.child(1);
+                } else if (expr.equals(leftSlotEqualToRightSlot.child(1))) {
+                    return leftSlotEqualToRightSlot.child(0);
+                } else {
+                    return expr;
+                }
+            }
+        }, null);
+    }
+
+    /**
+     * Currently only equivalence derivation is supported
+     * and requires that the left and right sides of an expression must be slot
+     */
+    private boolean canEquivalentInfer(Expression predicate) {
+        return predicate instanceof EqualTo && 
predicate.children().stream().allMatch(e -> e instanceof SlotReference);

Review Comment:
   This condition has an implicit conditions: this rule must invoke after 
TypeCoercion. Because we can not infer filter when the type is not equals:
   
   for example:
   a.id is int , b.id is string, the filter `a.id = b.id and concat(a.id, '0') 
= '10'`
   we can not infer a new filter `concat(b.id, '0') = '10'`,
   because the row a.id = 1 and b.id = '1.0' can join and through the join 
`a.id = b.id` and filter `concat(a.id, '0') = '10'`, but can not through the 
filter `concat(b.id, '0') = '10'`.
   
   I think you can add the implicit conditions to here:
   ```java
   return predicate instanceof EqualTo
           && predicate.children().stream().allMatch(e -> e instanceof 
SlotReference)
           && 
predicate.child(0).getDataType().equals(predicate.child(1).getDataType();
   ```
   
   
   Another case is the filter `a.id = b.id and a.id = c.id`,  infer `b.id = 
c.id` maybe useless have some executing overhead, so maybe we should add some 
rule to delete some useless expression.
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscr...@doris.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscr...@doris.apache.org
For additional commands, e-mail: commits-h...@doris.apache.org

Reply via email to