You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@doris.apache.org by GitBox <gi...@apache.org> on 2022/09/27 02:09:05 UTC

[GitHub] [doris] qzsee opened a new pull request, #12996: [Nereids][Improve] infer predicate when push down predicate

qzsee opened a new pull request, #12996:
URL: https://github.com/apache/doris/pull/12996

   # Proposed changes
   
   Issue Number: close #xxx
   
   ## Problem summary
   
   Describe your changes.
   
   ## Checklist(Required)
   
   1. Does it affect the original behavior: 
       - [ ] Yes
       - [ ] No
       - [ ] I don't know
   2. Has unit tests been added:
       - [ ] Yes
       - [ ] No
       - [ ] No Need
   3. Has document been added or modified:
       - [ ] Yes
       - [ ] No
       - [ ] No Need
   4. Does it need to update dependencies:
       - [ ] Yes
       - [ ] No
   5. Are there any changes that cannot be rolled back:
       - [ ] Yes (If Yes, please explain WHY)
       - [ ] No
   
   ## Further comments
   
   If this is a relatively large or complex change, kick off the discussion at [dev@doris.apache.org](mailto:dev@doris.apache.org) by explaining why you chose the solution you did and what alternatives you considered, etc...
   
   


-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] github-actions[bot] commented on pull request #12996: [Nereids][Improve] infer predicate after push down predicate

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on PR #12996:
URL: https://github.com/apache/doris/pull/12996#issuecomment-1307158469

   PR approved by at least one committer and no changes requested.


-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] hello-stephen commented on pull request #12996: [Nereids][Improve] infer predicate when push down predicate

Posted by GitBox <gi...@apache.org>.
hello-stephen commented on PR #12996:
URL: https://github.com/apache/doris/pull/12996#issuecomment-1279213441

   https://doris-community-test-1308700295.cos.ap-hongkong.myqcloud.com/tmp/20221015002223_clickbench_pr_29494.html


-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate after push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r1010421765


##########
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 condition: 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();
   ```
   
   The second implicit condition: this rule dependent the action: every non-deterministic in the same sql should equals. for example: `a.id = b.id and a.id=rand()`, if we can not ensure this condition and infer `b.id=()`, it will be wrong.
   
   
   Another case is the filter `a.id = b.id and a.id = c.id`,  infer `b.id = c.id` maybe useless and have some executing overhead, so maybe we should add some rule to delete some useless expression in the future, or just process this case: `column1 = column2 and anyExpressionJust compareTo anyExpressionNotContainsSlotReference`
   
   So maybe we should only process the case `a.id = b.id and a.id compareTo literal` for safety?



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate when push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r996606953


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/EffectivePredicatesExtractor.java:
##########
@@ -0,0 +1,157 @@
+// 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.SubqueryExpr;
+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.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * extract effective predicates.
+ */
+public class EffectivePredicatesExtractor extends PlanVisitor<Set<Expression>, Void> {
+
+    PredicatePropagation propagation = new PredicatePropagation();
+
+    @Override
+    public Set<Expression> visit(Plan plan, Void context) {
+        return Sets.newHashSet();
+    }
+
+    @Override
+    public Set<Expression> visitLogicalFilter(LogicalFilter<? extends Plan> filter, Void context) {
+        List<Expression> predicates = ExpressionUtils.extractConjunction(filter.getPredicates()).stream()
+                .filter(p -> {
+                    if (p instanceof SubqueryExpr) {
+                        SubqueryExpr subqueryExpr = (SubqueryExpr) p;
+                        return subqueryExpr.getCorrelateSlots().isEmpty();
+                    }

Review Comment:
   We should keep the logical orthogonality(don't handle the logic that other rules will handle
   )?
   SubqueryExpr will be replace to some join by UnnestSubquery rule.
   
   



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/EffectivePredicatesExtractor.java:
##########
@@ -0,0 +1,157 @@
+// 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.SubqueryExpr;
+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.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * extract effective predicates.
+ */
+public class EffectivePredicatesExtractor extends PlanVisitor<Set<Expression>, Void> {
+
+    PredicatePropagation propagation = new PredicatePropagation();
+
+    @Override
+    public Set<Expression> visit(Plan plan, Void context) {
+        return Sets.newHashSet();
+    }
+
+    @Override
+    public Set<Expression> visitLogicalFilter(LogicalFilter<? extends Plan> filter, Void context) {
+        List<Expression> predicates = ExpressionUtils.extractConjunction(filter.getPredicates()).stream()
+                .filter(p -> {
+                    if (p instanceof SubqueryExpr) {
+                        SubqueryExpr subqueryExpr = (SubqueryExpr) p;
+                        return subqueryExpr.getCorrelateSlots().isEmpty();
+                    }
+                    return true;
+                }).collect(Collectors.toList());
+        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();
+        predicates.addAll(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();
+        predicates.addAll(ExpressionUtils.extractConjunction(expression));
+        return getAvailableExpressions(predicates, aggregate);
+    }
+
+    public Set<Expression> getAvailableExpressions(Set<Expression> predicates, Plan plan) {
+        predicates.addAll(propagation.infer(Lists.newArrayList(predicates)));
+        return predicates.stream()
+                .filter(p -> new HashSet<>(plan.getOutput()).containsAll(p.getInputSlots()))
+                .collect(Collectors.toSet());
+    }
+
+    private boolean hasAgg(Expression expression) {
+        if (expression instanceof AggregateFunction) {
+            return true;
+        }
+        for (Expression child : expression.children()) {
+            if (hasAgg(child)) {
+                return true;
+            }
+        }
+        return false;
+    }

Review Comment:
   ```suggestion
       private boolean hasAgg(Expression expression) {
           return expression.anyMatch(AggregateFunction.class::isInstance);
       }
   ```



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/EffectivePredicatesExtractor.java:
##########
@@ -0,0 +1,157 @@
+// 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.SubqueryExpr;
+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.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * extract effective predicates.
+ */
+public class EffectivePredicatesExtractor extends PlanVisitor<Set<Expression>, Void> {
+
+    PredicatePropagation propagation = new PredicatePropagation();
+
+    @Override
+    public Set<Expression> visit(Plan plan, Void context) {
+        return Sets.newHashSet();
+    }
+
+    @Override
+    public Set<Expression> visitLogicalFilter(LogicalFilter<? extends Plan> filter, Void context) {
+        List<Expression> predicates = ExpressionUtils.extractConjunction(filter.getPredicates()).stream()
+                .filter(p -> {
+                    if (p instanceof SubqueryExpr) {
+                        SubqueryExpr subqueryExpr = (SubqueryExpr) p;
+                        return subqueryExpr.getCorrelateSlots().isEmpty();
+                    }
+                    return true;
+                }).collect(Collectors.toList());
+        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();
+        predicates.addAll(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();
+        predicates.addAll(ExpressionUtils.extractConjunction(expression));
+        return getAvailableExpressions(predicates, aggregate);
+    }
+
+    public Set<Expression> getAvailableExpressions(Set<Expression> predicates, Plan plan) {
+        predicates.addAll(propagation.infer(Lists.newArrayList(predicates)));
+        return predicates.stream()
+                .filter(p -> new HashSet<>(plan.getOutput()).containsAll(p.getInputSlots()))
+                .collect(Collectors.toSet());
+    }
+
+    private boolean hasAgg(Expression expression) {
+        if (expression instanceof AggregateFunction) {
+            return true;
+        }
+        for (Expression child : expression.children()) {
+            if (hasAgg(child)) {
+                return true;
+            }
+        }
+        return false;
+    }

Review Comment:
   don't repeat the common recursive traversal function(in TreeNode), if no any common traversal function meet your needs, and new function to TreeNode
   
   



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/InferPredicates.java:
##########
@@ -0,0 +1,123 @@
+// 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.rules.PlanRuleFactory;
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RulePromise;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.plans.JoinType;
+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.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * infer additional predicates for filter and join.
+ */
+public class InferPredicates implements PlanRuleFactory {
+    PredicatePropagation propagation = new PredicatePropagation();
+    EffectivePredicatesExtractor predicatesExtractor = new EffectivePredicatesExtractor();
+
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                inferWhere(),
+                inferOn()
+        );
+    }
+
+    private Rule inferWhere() {
+        return logicalFilter(any()).thenApply(ctx -> {
+            LogicalFilter<Plan> root = ctx.root;
+            Plan filter = ctx.cascadesContext.getMemo().copyOut(root.getGroupExpression().get(), false);
+            Set<Expression> filterPredicates = filter.accept(predicatesExtractor, null);
+            Set<Expression> filterChildPredicates = filter.child(0).accept(predicatesExtractor, null);
+            filterPredicates.removeAll(filterChildPredicates);
+            ExpressionUtils.extractConjunction(root.getPredicates()).forEach(filterPredicates::remove);

Review Comment:
   I think this rule should process the current predicate, and not need to remove the predicate which exist in the child, this is the responsibility of another rule.
   keep the logical orthogonality too, and this rule will become more clarity, so you not need to copy out from the memo in the EffectivePredicateExtractor.
   
   



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/PredicatePropagation.java:
##########
@@ -0,0 +1,100 @@
+// 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 com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * derive additional predicates.
+ * for example:
+ * a = b and a = 1 => b = 1
+ */
+public class PredicatePropagation {
+
+    /**
+     * infer additional predicates.
+     */
+    public Set<Expression> infer(List<Expression> predicates) {
+        Set<Expression> inferred = Sets.newHashSet();
+        for (Expression predicate : predicates) {
+            if (canEquivalentDeduce(predicate)) {
+                List<Expression> candidates = subtract(predicates, predicate);
+                candidates.forEach(candidate -> {
+                    inferred.add(transform(candidate, predicate.child(0), predicate.child(1)));
+                });
+            }
+        }
+        predicates.forEach(inferred::remove);
+        return inferred;
+    }
+
+    private Expression transform(Expression expression, Expression source, Expression target) {
+        Expression rewritten = replace(expression, source, target);
+        if (expression.equals(rewritten)) {
+            rewritten = mapChildren(expression, source, target);
+            if (expression.equals(rewritten)) {
+                return expression;
+            } else {
+                return rewritten;
+            }
+        } else {
+            return mapChildren(rewritten, source, target);
+        }
+    }
+
+    private Expression mapChildren(Expression expression, Expression source, Expression target) {
+        if (!expression.children().isEmpty()) {
+            List<Expression> children = Lists.newArrayList();
+            for (Expression child : expression.children()) {
+                children.add(transform(child, source, target));
+            }
+            return expression.withChildren(children);
+        } else {
+            return expression;
+        }
+    }
+
+    private Expression replace(Expression expression, Expression source, Expression target) {
+        if (expression.equals(source)) {
+            return target;
+        }
+        if (expression.equals(target)) {
+            return source;
+        }
+        return expression;
+    }
+
+    private boolean canEquivalentDeduce(Expression predicate) {
+        return predicate instanceof EqualTo && predicate.children().stream().allMatch(e -> e instanceof SlotReference);
+    }
+
+    private List<Expression> subtract(List<Expression> expressions, Expression target) {
+        ArrayList<Expression> cloneList = Lists.newArrayList(expressions);
+        cloneList.remove(target);
+        return cloneList;
+    }
+}

Review Comment:
   Do not recursively traverse/rewrite manually, too.
   
   Use DefaultExpressionRewriter:
   ```java
   class PredicatePropagation {
       public Set<Expression> infer(List<Expression> predicates) {
           Set<Expression> inferred = Sets.newHashSet();
           for (Expression predicate : predicates) {
               if (canEquivalentDeduce(predicate)) {
                   Expression leftSlotEqualToRightSlot = predicate;
   
                   List<Expression> newInferred = predicates.stream()
                           .filter(p -> !p.equals(leftSlotEqualToRightSlot))
                           .map(p -> doInfer(leftSlotEqualToRightSlot, p))
                           .collect(Collectors.toList());
                   inferred.addAll(newInferred);
               }
           }
           predicates.forEach(inferred::remove);
           return inferred;
       }
   
       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 expr.child(1);
                   } else if (expr.equals(leftSlotEqualToRightSlot.child(1))) {
                       return expr.child(0);
                   } else {
                       return expr;
                   }
               }
           }, null);
       }
   
       private boolean canEquivalentDeduce(Expression predicate) {
           return predicate instanceof EqualTo && predicate.children().stream().allMatch(e -> e instanceof SlotReference);
       }
   ```



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/InferPredicates.java:
##########
@@ -0,0 +1,123 @@
+// 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.rules.PlanRuleFactory;
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RulePromise;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.plans.JoinType;
+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.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * infer additional predicates for filter and join.
+ */
+public class InferPredicates implements PlanRuleFactory {
+    PredicatePropagation propagation = new PredicatePropagation();
+    EffectivePredicatesExtractor predicatesExtractor = new EffectivePredicatesExtractor();
+
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                inferWhere(),
+                inferOn()
+        );
+    }
+
+    private Rule inferWhere() {
+        return logicalFilter(any()).thenApply(ctx -> {
+            LogicalFilter<Plan> root = ctx.root;
+            Plan filter = ctx.cascadesContext.getMemo().copyOut(root.getGroupExpression().get(), false);
+            Set<Expression> filterPredicates = filter.accept(predicatesExtractor, null);
+            Set<Expression> filterChildPredicates = filter.child(0).accept(predicatesExtractor, null);
+            filterPredicates.removeAll(filterChildPredicates);
+            ExpressionUtils.extractConjunction(root.getPredicates()).forEach(filterPredicates::remove);
+            if (!filterPredicates.isEmpty()) {
+                filterPredicates.add(root.getPredicates());
+                return new LogicalFilter<>(ExpressionUtils.and(Lists.newArrayList(filterPredicates)), root.child());
+            }
+            return root;
+        }).toRule(RuleType.INFER_PREDICATES_FOR_WHERE);
+    }
+
+    private Rule inferOn() {
+        return logicalJoin(any(), any()).thenApply(ctx -> {
+            LogicalJoin<Plan, Plan> root = ctx.root;
+            JoinType joinType = root.getJoinType();
+            Plan left = root.left();
+            Plan right = root.right();
+            Plan originalLeft = ctx.cascadesContext.getMemo().copyOut(left.getGroupExpression().get(), false);
+            Plan originalRight = ctx.cascadesContext.getMemo().copyOut(right.getGroupExpression().get(), false);
+            Optional<Expression> condition = root.getOnClauseCondition();
+            Set<Expression> expressions = getAllExpressions(originalLeft, originalRight, condition);

Review Comment:
   ditto



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/EffectivePredicatesExtractor.java:
##########
@@ -0,0 +1,157 @@
+// 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.SubqueryExpr;
+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.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * extract effective predicates.

Review Comment:
   What does effective mean? Please add comment to sum up.
   
   



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] hello-stephen commented on pull request #12996: [Nereids][Improve] infer predicate when push down predicate

Posted by GitBox <gi...@apache.org>.
hello-stephen commented on PR #12996:
URL: https://github.com/apache/doris/pull/12996#issuecomment-1285290608

   TeamCity pipeline, clickbench performance test result:
    the sum of best hot time: 38.73 seconds
    load time: 585 seconds
    storage size: 17154562402 Bytes
    https://doris-community-test-1308700295.cos.ap-hongkong.myqcloud.com/tmp/20221020182035_clickbench_pr_31883.html


-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] wangshuo128 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate when push down predicate

Posted by GitBox <gi...@apache.org>.
wangshuo128 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r980704751


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/rewrite/InferPredicate.java:
##########
@@ -0,0 +1,225 @@
+// 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.expression.rewrite;
+
+import org.apache.doris.nereids.trees.expressions.ComparisonPredicate;
+import org.apache.doris.nereids.trees.expressions.EqualTo;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.InPredicate;
+import org.apache.doris.nereids.trees.expressions.IsNull;
+import org.apache.doris.nereids.trees.expressions.Not;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
+import org.apache.doris.nereids.util.ExpressionUtils;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class InferPredicate {
+
+    private final Map<Expression, Set<Expression>> equivalentMap = Maps.newHashMap();
+    private final Map<Expression, Set<Expression>> predicateMap = Maps.newHashMap();
+
+    private final Visitor visitor = new Visitor();
+
+    public List<Expression> inferEffectivePredicate(Expression predicate) {
+        List<Expression> infers = infer(predicate);
+        return infers.stream().filter(p -> p.getInputSlots().size() == 1).collect(Collectors.toList());
+    }
+
+
+    public List<Expression> infer(Expression predicate) {
+        List<Expression> splits = ExpressionUtils.extractConjunction(predicate);
+        splits.forEach(p -> p.accept(visitor, new InferContext()));
+        Set<Slot> inputSlots = predicate.getInputSlots();
+        Set<Expression> inferred = Sets.newLinkedHashSet();
+        inferred.addAll(splits);
+        for (Slot inputSlot : inputSlots) {
+            for (Expression search : equivalentSearch(inputSlot)) {
+                if (search instanceof EqualTo) {
+                    if (!inferred.contains(search) && !inferred.contains(((EqualTo) search).commute())) {
+                        inferred.add(search);
+                    }
+                    continue;
+                }
+                inferred.add(search);
+            }
+        }
+        splits.forEach(inferred::remove);
+        return ImmutableList.copyOf(inferred);
+    }
+
+    private static class InferContext {
+        Expression parent;
+
+        public Expression getParent() {
+            return parent;
+        }
+
+        public void setParent(Expression parent) {
+            this.parent = parent;
+        }
+    }
+
+    private class Visitor extends ExpressionVisitor<Void, InferContext> {
+
+        @Override
+        public Void visit(Expression expr, InferContext context) {
+            return null;
+        }
+
+        @Override
+        public Void visitEqualTo(EqualTo equalTo, InferContext context) {
+            Expression left = equalTo.left();
+            Expression right = equalTo.right();
+            if (left.isSlot() && right.isSlot()) {
+                Set<Expression> leftSet = equivalentMap.getOrDefault(left, Sets.newHashSet());
+                leftSet.add(right);
+                equivalentMap.putIfAbsent(left, leftSet);
+                Set<Expression> rightSet = equivalentMap.getOrDefault(right, Sets.newHashSet());
+                rightSet.add(left);
+                equivalentMap.putIfAbsent(right, rightSet);
+            }
+            visitComparisonPredicate(equalTo, context);
+            return null;
+        }
+
+        @Override
+        public Void visitComparisonPredicate(ComparisonPredicate cp, InferContext context) {
+            Optional<Expression> left = extractSlot(cp.left());
+            Optional<Expression> right = extractSlot(cp.right());
+            Expression target = null;
+            if (left.isPresent() && cp.right().isConstant()) {
+                target = left.get();
+            } else if (right.isPresent() && cp.left().isConstant()) {
+                target = right.get();
+            }
+            if (Objects.nonNull(target)) {
+                Set<Expression> targetSet = predicateMap.getOrDefault(target, Sets.newHashSet());
+                addPredicate(cp, targetSet, context);
+                predicateMap.putIfAbsent(target, targetSet);
+            }
+            return null;
+        }
+
+        @Override
+        public Void visitInPredicate(InPredicate inPredicate, InferContext context) {
+            Optional<Expression> cmp = extractSlot(inPredicate.getCompareExpr());
+            if (cmp.isPresent() && isAllConstant(inPredicate.getOptions())) {
+                Set<Expression> predicates = predicateMap.getOrDefault(cmp.get(), Sets.newHashSet());
+                addPredicate(inPredicate, predicates, context);
+                predicateMap.putIfAbsent(cmp.get(), predicates);
+            }
+            return null;
+        }
+
+        @Override
+        public Void visitIsNull(IsNull isNull, InferContext context) {
+            Optional<Expression> child = extractSlot(isNull.child());
+            if (child.isPresent()) {
+                Set<Expression> predicates = predicateMap.getOrDefault(child.get(), Sets.newHashSet());
+                addPredicate(isNull, predicates, context);
+                predicateMap.putIfAbsent(child.get(), predicates);
+            }
+            return null;
+        }
+
+        @Override
+        public Void visitNot(Not not, InferContext context) {
+            context.setParent(not);
+            not.child().accept(this, context);
+            return null;
+        }
+
+        private void addPredicate(Expression expr, Set<Expression> predicates, InferContext context) {
+            if (Objects.nonNull(context.getParent())) {
+                predicates.add(context.getParent());
+                return;
+            }
+            predicates.add(expr);
+        }
+
+        private boolean isAllConstant(List<Expression> expressions) {
+            return expressions.stream().allMatch(Expression::isConstant);
+        }
+
+        private Optional<Expression> extractSlot(Expression expression) {
+            Set<Slot> inputSlots = expression.getInputSlots();
+            if (inputSlots.size() == 1) {
+                for (Slot slot : inputSlots) {
+                    return Optional.of(slot);
+                }
+            }
+            return Optional.empty();
+        }
+
+    }
+
+    private Set<Expression> equivalentSearch(Expression slot) {

Review Comment:
   This method is a bit obscure, could we have some examples?



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/rewrite/InferPredicate.java:
##########
@@ -0,0 +1,225 @@
+// 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.expression.rewrite;
+
+import org.apache.doris.nereids.trees.expressions.ComparisonPredicate;
+import org.apache.doris.nereids.trees.expressions.EqualTo;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.InPredicate;
+import org.apache.doris.nereids.trees.expressions.IsNull;
+import org.apache.doris.nereids.trees.expressions.Not;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
+import org.apache.doris.nereids.util.ExpressionUtils;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class InferPredicate {

Review Comment:
   We should have some examples to explain how this class works.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/util/ReplaceSlot.java:
##########
@@ -0,0 +1,46 @@
+// 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.util;
+
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.expressions.visitor.DefaultExpressionRewriter;
+
+import java.util.Map;
+import java.util.Objects;
+
+public class ReplaceSlot extends DefaultExpressionRewriter<Map<Expression, Expression>> {

Review Comment:
   It seems this is duplicated with `ExpressionUtil.replace`?



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/PushDownJoinOtherCondition.java:
##########
@@ -62,7 +64,14 @@ public Rule build() {
             if (!join.getOtherJoinCondition().isPresent()) {
                 return null;
             }
+            InferPredicate inferPredicate = new InferPredicate();

Review Comment:
   Hmm. I'd suggest to adding a dedicated rule to infer predicates, rather than have side effects on predicates pushdonw rules.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/PushPredicatesThroughJoin.java:
##########
@@ -95,6 +97,12 @@ public Rule build() {
 
             Expression filterPredicates = filter.getPredicates();
 
+            InferPredicate inferPredicate = new InferPredicate();

Review Comment:
   ditto



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/rewrite/InferPredicate.java:
##########
@@ -0,0 +1,225 @@
+// 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.expression.rewrite;
+
+import org.apache.doris.nereids.trees.expressions.ComparisonPredicate;
+import org.apache.doris.nereids.trees.expressions.EqualTo;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.InPredicate;
+import org.apache.doris.nereids.trees.expressions.IsNull;
+import org.apache.doris.nereids.trees.expressions.Not;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
+import org.apache.doris.nereids.util.ExpressionUtils;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class InferPredicate {
+
+    private final Map<Expression, Set<Expression>> equivalentMap = Maps.newHashMap();

Review Comment:
   Please add some comments for these members.



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate after push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r1015094281


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/PredicatePropagation.java:
##########
@@ -0,0 +1,102 @@
+// 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.ComparisonPredicate;
+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`
+     * Now only support infer `ComparisonPredicate`.
+     * TODO: We should determine whether `expression` satisfies the condition for replacement
+     *       eg: Satisfy `expression` is non-deterministic
+     */
+    private Expression doInfer(Expression leftSlotEqualToRightSlot, Expression expression) {
+        return expression.accept(new DefaultExpressionRewriter<Void>() {
+
+            @Override
+            public Expression visit(Expression expr, Void context) {
+                return expr;
+            }
+
+            @Override
+            public Expression visitComparisonPredicate(ComparisonPredicate cp, Void context) {
+                if (!cp.left().isConstant() && !cp.right().isConstant()) {
+                    return cp;
+                }
+                return super.visit(cp, context);
+            }
+
+            @Override
+            public Expression visitSlotReference(SlotReference slotReference, Void context) {
+                if (slotReference.equals(leftSlotEqualToRightSlot.child(0))) {
+                    return leftSlotEqualToRightSlot.child(1);
+                } else if (slotReference.equals(leftSlotEqualToRightSlot.child(1))) {
+                    return leftSlotEqualToRightSlot.child(0);
+                } else {
+                    return slotReference;
+                }
+            }

Review Comment:
   Declare the shape in the visitComparisonPredicate will more clearer.
   ```java
   @Override
   public Expression visitComparisonPredicate(ComparisonPredicate cp, Void context) {
       if (cp.left().isSlot() && cp.right().isConstant()) {
           return swapSlot(cp);
       } else if (cp.left().isConstant() && cp.right().isSlot()) {
           return swapSlot(cp);
       }
       return super.visit(cp, context);
   }
   
   private Expression swapSlot(Expression expr) {
       return expr.rewriteUp(e -> {
           if (e.equals(leftSlotEqualToRightSlot.child(0)) {
               return leftSlotEqualToRightSlot.child(1);
           } else if (e.equals(leftSlotEqualToRightSlot.child(1)) {
               return leftSlotEqualToRightSlot.child(0);
           } else {
               return e;
           }
       });
   }
   ```



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate when push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r996612117


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/EffectivePredicatesExtractor.java:
##########
@@ -0,0 +1,157 @@
+// 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.SubqueryExpr;
+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.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * extract effective predicates.

Review Comment:
   What does effective mean? Please add comment to sum up.
   
   



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] qzsee commented on a diff in pull request #12996: [Nereids][Improve] infer predicate when push down predicate

Posted by GitBox <gi...@apache.org>.
qzsee commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r980709093


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/util/ReplaceSlot.java:
##########
@@ -0,0 +1,46 @@
+// 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.util;
+
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.expressions.visitor.DefaultExpressionRewriter;
+
+import java.util.Map;
+import java.util.Objects;
+
+public class ReplaceSlot extends DefaultExpressionRewriter<Map<Expression, Expression>> {

Review Comment:
   yes. I forget remove



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate after push down predicate

Posted by GitBox <gi...@apache.org>.
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] hello-stephen commented on pull request #12996: [Nereids][Improve] infer predicate when push down predicate

Posted by GitBox <gi...@apache.org>.
hello-stephen commented on PR #12996:
URL: https://github.com/apache/doris/pull/12996#issuecomment-1280487489

   https://doris-community-test-1308700295.cos.ap-hongkong.myqcloud.com/tmp/20221017163314_clickbench_pr_30045.html


-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] github-actions[bot] commented on pull request #12996: [Nereids][Improve] infer predicate after push down predicate

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on PR #12996:
URL: https://github.com/apache/doris/pull/12996#issuecomment-1307158520

   PR approved by anyone and no changes requested.


-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate when push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r996698062


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/PredicatePropagation.java:
##########
@@ -0,0 +1,100 @@
+// 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 com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * derive additional predicates.
+ * for example:
+ * a = b and a = 1 => b = 1
+ */
+public class PredicatePropagation {
+
+    /**
+     * infer additional predicates.
+     */
+    public Set<Expression> infer(List<Expression> predicates) {
+        Set<Expression> inferred = Sets.newHashSet();
+        for (Expression predicate : predicates) {
+            if (canEquivalentDeduce(predicate)) {
+                List<Expression> candidates = subtract(predicates, predicate);
+                candidates.forEach(candidate -> {
+                    inferred.add(transform(candidate, predicate.child(0), predicate.child(1)));
+                });
+            }
+        }
+        predicates.forEach(inferred::remove);
+        return inferred;
+    }
+
+    private Expression transform(Expression expression, Expression source, Expression target) {
+        Expression rewritten = replace(expression, source, target);
+        if (expression.equals(rewritten)) {
+            rewritten = mapChildren(expression, source, target);
+            if (expression.equals(rewritten)) {
+                return expression;
+            } else {
+                return rewritten;
+            }
+        } else {
+            return mapChildren(rewritten, source, target);
+        }
+    }
+
+    private Expression mapChildren(Expression expression, Expression source, Expression target) {
+        if (!expression.children().isEmpty()) {
+            List<Expression> children = Lists.newArrayList();
+            for (Expression child : expression.children()) {
+                children.add(transform(child, source, target));
+            }
+            return expression.withChildren(children);
+        } else {
+            return expression;
+        }
+    }
+
+    private Expression replace(Expression expression, Expression source, Expression target) {
+        if (expression.equals(source)) {
+            return target;
+        }
+        if (expression.equals(target)) {
+            return source;
+        }
+        return expression;
+    }
+
+    private boolean canEquivalentDeduce(Expression predicate) {
+        return predicate instanceof EqualTo && predicate.children().stream().allMatch(e -> e instanceof SlotReference);
+    }
+
+    private List<Expression> subtract(List<Expression> expressions, Expression target) {
+        ArrayList<Expression> cloneList = Lists.newArrayList(expressions);
+        cloneList.remove(target);
+        return cloneList;
+    }
+}

Review Comment:
   Do not recursively traverse/rewrite manually, too.
   
   Use DefaultExpressionRewriter:
   ```java
   class PredicatePropagation {
       public Set<Expression> infer(List<Expression> predicates) {
           Set<Expression> inferred = Sets.newHashSet();
           for (Expression predicate : predicates) {
               if (canEquivalentDeduce(predicate)) {
                   Expression leftSlotEqualToRightSlot = predicate;
   
                   List<Expression> newInferred = predicates.stream()
                           .filter(p -> !p.equals(leftSlotEqualToRightSlot))
                           .map(p -> doInfer(leftSlotEqualToRightSlot, p))
                           .collect(Collectors.toList());
                   inferred.addAll(newInferred);
               }
           }
           predicates.forEach(inferred::remove);
           return inferred;
       }
   
       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);
       }
   
       private boolean canEquivalentDeduce(Expression predicate) {
           return predicate instanceof EqualTo && predicate.children().stream().allMatch(e -> e instanceof SlotReference);
       }
   ```
   
   or you can add the common rewrite method to TreeNode:
   ```java
   /**
    * bottom-up rewrite.
    * @param rewriteFunction rewrite function.
    * @return rewritten result.
    */
   default NODE_TYPE rewriteUp(Function<NODE_TYPE, NODE_TYPE> rewriteFunction) {
       boolean changed = false;
       Builder<NODE_TYPE> newChildren = ImmutableList.builderWithExpectedSize(arity());
       for (NODE_TYPE child : children()) {
           NODE_TYPE newChild = child.rewriteUp(rewriteFunction);
           if (child != newChild) {
               changed = true;
           }
           newChildren.add(newChild);
       }
   
       NODE_TYPE rewrittenChildren = changed ? withChildren(newChildren.build()) : (NODE_TYPE) this;
       return rewriteFunction.apply(rewrittenChildren);
   }
   ```
   
   then
   
   ```java
   private Expression doInfer(Expression leftSlotEqualToRightSlot, Expression expression) {
       return expression.rewriteUp(expr -> {
           if (expr.equals(leftSlotEqualToRightSlot.child(0))) {
               return leftSlotEqualToRightSlot.child(1);
           } else if (expr.equals(leftSlotEqualToRightSlot.child(1))) {
               return leftSlotEqualToRightSlot.child(0);
           } else {
               return expr;
           }
       });
   }
   ``` 



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate when push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r996610488


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/EffectivePredicatesExtractor.java:
##########
@@ -0,0 +1,157 @@
+// 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.SubqueryExpr;
+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.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * extract effective predicates.
+ */
+public class EffectivePredicatesExtractor extends PlanVisitor<Set<Expression>, Void> {
+
+    PredicatePropagation propagation = new PredicatePropagation();
+
+    @Override
+    public Set<Expression> visit(Plan plan, Void context) {
+        return Sets.newHashSet();
+    }
+
+    @Override
+    public Set<Expression> visitLogicalFilter(LogicalFilter<? extends Plan> filter, Void context) {
+        List<Expression> predicates = ExpressionUtils.extractConjunction(filter.getPredicates()).stream()
+                .filter(p -> {
+                    if (p instanceof SubqueryExpr) {
+                        SubqueryExpr subqueryExpr = (SubqueryExpr) p;
+                        return subqueryExpr.getCorrelateSlots().isEmpty();
+                    }
+                    return true;
+                }).collect(Collectors.toList());
+        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();
+        predicates.addAll(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();
+        predicates.addAll(ExpressionUtils.extractConjunction(expression));
+        return getAvailableExpressions(predicates, aggregate);
+    }
+
+    public Set<Expression> getAvailableExpressions(Set<Expression> predicates, Plan plan) {
+        predicates.addAll(propagation.infer(Lists.newArrayList(predicates)));
+        return predicates.stream()
+                .filter(p -> new HashSet<>(plan.getOutput()).containsAll(p.getInputSlots()))
+                .collect(Collectors.toSet());
+    }
+
+    private boolean hasAgg(Expression expression) {
+        if (expression instanceof AggregateFunction) {
+            return true;
+        }
+        for (Expression child : expression.children()) {
+            if (hasAgg(child)) {
+                return true;
+            }
+        }
+        return false;
+    }

Review Comment:
   don't repeat the common recursive traversal function(in TreeNode), if no any common traversal function meet your needs, and new function to TreeNode
   ```suggestion
       private boolean hasAgg(Expression expression) {
           return expression.anyMatch(AggregateFunction.class::isInstance);
       }
   ```



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate when push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r996610488


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/EffectivePredicatesExtractor.java:
##########
@@ -0,0 +1,157 @@
+// 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.SubqueryExpr;
+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.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * extract effective predicates.
+ */
+public class EffectivePredicatesExtractor extends PlanVisitor<Set<Expression>, Void> {
+
+    PredicatePropagation propagation = new PredicatePropagation();
+
+    @Override
+    public Set<Expression> visit(Plan plan, Void context) {
+        return Sets.newHashSet();
+    }
+
+    @Override
+    public Set<Expression> visitLogicalFilter(LogicalFilter<? extends Plan> filter, Void context) {
+        List<Expression> predicates = ExpressionUtils.extractConjunction(filter.getPredicates()).stream()
+                .filter(p -> {
+                    if (p instanceof SubqueryExpr) {
+                        SubqueryExpr subqueryExpr = (SubqueryExpr) p;
+                        return subqueryExpr.getCorrelateSlots().isEmpty();
+                    }
+                    return true;
+                }).collect(Collectors.toList());
+        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();
+        predicates.addAll(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();
+        predicates.addAll(ExpressionUtils.extractConjunction(expression));
+        return getAvailableExpressions(predicates, aggregate);
+    }
+
+    public Set<Expression> getAvailableExpressions(Set<Expression> predicates, Plan plan) {
+        predicates.addAll(propagation.infer(Lists.newArrayList(predicates)));
+        return predicates.stream()
+                .filter(p -> new HashSet<>(plan.getOutput()).containsAll(p.getInputSlots()))
+                .collect(Collectors.toSet());
+    }
+
+    private boolean hasAgg(Expression expression) {
+        if (expression instanceof AggregateFunction) {
+            return true;
+        }
+        for (Expression child : expression.children()) {
+            if (hasAgg(child)) {
+                return true;
+            }
+        }
+        return false;
+    }

Review Comment:
   don't repeat the common recursive traversal function(in TreeNode), if no any common traversal function meet your needs, add new function to TreeNode
   ```suggestion
       private boolean hasAgg(Expression expression) {
           return expression.anyMatch(AggregateFunction.class::isInstance);
       }
   ```



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] hello-stephen commented on pull request #12996: [Nereids][Improve] infer predicate when push down predicate

Posted by GitBox <gi...@apache.org>.
hello-stephen commented on PR #12996:
URL: https://github.com/apache/doris/pull/12996#issuecomment-1284932911

   TeamCity pipeline, clickbench performance test result:
    the sum of best hot time: 39.5 seconds
    load time: 624 seconds
    storage size: 17154562266 Bytes
    https://doris-community-test-1308700295.cos.ap-hongkong.myqcloud.com/tmp/20221020130709_clickbench_pr_31811.html


-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate after push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r1010447576


##########
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 is very 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.
   Or create MemoBottomUpRewriter to traverse and rewrite in the memo?



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate after push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r1010421765


##########
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 condition: 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();
   ```
   
   The second implicit condition: this rule dependent the action: every non-deterministic in the same sql should equals. for example: `a.id = b.id and a.id=rand()`, if we can not ensure this condition and infer `b.id=()`, it will be wrong.
   
   
   Another case is the filter `a.id = b.id and a.id = c.id`,  infer `b.id = c.id` maybe useless and have some executing overhead, so maybe we should add some rule to delete some useless expression in the future, or just process this case: `column1 = column2 and anyExpression compareTo anyExpressionNotContainsSlotReference`
   
   So maybe we should only process the case `a.id = b.id and a.id compareTo literal` for safety?



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate when push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r996606953


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/EffectivePredicatesExtractor.java:
##########
@@ -0,0 +1,157 @@
+// 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.SubqueryExpr;
+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.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * extract effective predicates.
+ */
+public class EffectivePredicatesExtractor extends PlanVisitor<Set<Expression>, Void> {
+
+    PredicatePropagation propagation = new PredicatePropagation();
+
+    @Override
+    public Set<Expression> visit(Plan plan, Void context) {
+        return Sets.newHashSet();
+    }
+
+    @Override
+    public Set<Expression> visitLogicalFilter(LogicalFilter<? extends Plan> filter, Void context) {
+        List<Expression> predicates = ExpressionUtils.extractConjunction(filter.getPredicates()).stream()
+                .filter(p -> {
+                    if (p instanceof SubqueryExpr) {
+                        SubqueryExpr subqueryExpr = (SubqueryExpr) p;
+                        return subqueryExpr.getCorrelateSlots().isEmpty();
+                    }

Review Comment:
   We should keep the logical orthogonality(don't handle the logic that other rules will handle
   )?
   SubqueryExpr will be replace to some join by UnnestSubquery rule.
   
   



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate after push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r1010447576


##########
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 is very 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



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate after push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r1010421765


##########
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 and have some executing overhead, so maybe we should add some rule to delete some useless expression in the future, or just process this case: `column1 = column2 and column1 compareTo literal`
   
   



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate after push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r1015106069


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/InferPredicates.java:
##########
@@ -0,0 +1,118 @@
+// 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.jobs.JobContext;
+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.trees.plans.visitor.DefaultPlanRewriter;
+import org.apache.doris.nereids.util.ExpressionUtils;
+
+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 extends DefaultPlanRewriter<JobContext> {
+    PredicatePropagation propagation = new PredicatePropagation();
+    PullUpPredicates pollUpPredicates = new PullUpPredicates();
+
+    /**
+     * 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
+     */
+    @Override
+    public Plan visitLogicalJoin(LogicalJoin<? extends Plan, ? extends Plan> join, JobContext context) {
+        join = (LogicalJoin<? extends Plan, ? extends Plan>) super.visit(join, context);
+        Plan left = join.left();
+        Plan right = join.right();
+        Set<Expression> expressions = getAllExpressions(left, right, join.getOnClauseCondition());
+        List<Expression> otherJoinConjuncts = Lists.newArrayList(join.getOtherJoinConjuncts());
+        switch (join.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 join;
+        }
+        return join.withOtherJoinConjuncts(otherJoinConjuncts);
+    }
+
+    /**
+     * reference `inferOn`
+     */
+    @Override
+    public Plan visitLogicalFilter(LogicalFilter<? extends Plan> filter, JobContext context) {
+        filter = (LogicalFilter<? extends Plan>) super.visit(filter, context);
+        Set<Expression> filterPredicates = filter.accept(pollUpPredicates, null);
+        Set<Expression> filterChildPredicates = filter.child(0).accept(pollUpPredicates, null);

Review Comment:
   This code seem like every plan child has many repeated traverse the all child plan tree by the pollUpPredicates.
   You should add a cache for every plan in PollUpPredicates.
    



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate after push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r1015076884


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/InferPredicates.java:
##########
@@ -0,0 +1,118 @@
+// 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.jobs.JobContext;
+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.trees.plans.visitor.DefaultPlanRewriter;
+import org.apache.doris.nereids.util.ExpressionUtils;
+
+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 extends DefaultPlanRewriter<JobContext> {
+    PredicatePropagation propagation = new PredicatePropagation();
+    PullUpPredicates pollUpPredicates = new PullUpPredicates();
+
+    /**
+     * 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

Review Comment:
   Good comment :D, move before the class definition.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/jobs/rewrite/VisitorRewriteJob.java:
##########
@@ -0,0 +1,56 @@
+// 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.jobs.rewrite;
+
+import org.apache.doris.nereids.CascadesContext;
+import org.apache.doris.nereids.jobs.Job;
+import org.apache.doris.nereids.jobs.JobContext;
+import org.apache.doris.nereids.jobs.JobType;
+import org.apache.doris.nereids.memo.Group;
+import org.apache.doris.nereids.memo.GroupExpression;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.visitor.DefaultPlanRewriter;
+
+import java.util.Objects;
+
+/**
+ * Use visitor to rewrite the plan.
+ */
+public class VisitorRewriteJob extends Job {
+    private final Group group;
+
+    private final DefaultPlanRewriter<JobContext> planRewriter;
+
+    /**
+     * Constructor.
+     */
+    public VisitorRewriteJob(CascadesContext cascadesContext, DefaultPlanRewriter<JobContext> rewriter, boolean once) {
+        super(JobType.VISITOR_REWRITE, cascadesContext.getCurrentJobContext(), once);
+        this.group = Objects.requireNonNull(cascadesContext.getMemo().getRoot(), "group cannot be null");
+        this.planRewriter = Objects.requireNonNull(rewriter, "planRewriter cannot be null");
+    }
+
+    @Override
+    public void execute() {
+        GroupExpression logicalExpression = group.getLogicalExpression();
+        Plan root = context.getCascadesContext().getMemo().copyOut(logicalExpression, false);
+        Plan accept = root.accept(planRewriter, context);

Review Comment:
   ```suggestion
           Plan rewrittenRoot = root.accept(planRewriter, context);
   ```



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/jobs/rewrite/VisitorRewriteJob.java:
##########
@@ -0,0 +1,56 @@
+// 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.jobs.rewrite;
+
+import org.apache.doris.nereids.CascadesContext;
+import org.apache.doris.nereids.jobs.Job;
+import org.apache.doris.nereids.jobs.JobContext;
+import org.apache.doris.nereids.jobs.JobType;
+import org.apache.doris.nereids.memo.Group;
+import org.apache.doris.nereids.memo.GroupExpression;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.visitor.DefaultPlanRewriter;
+
+import java.util.Objects;
+
+/**
+ * Use visitor to rewrite the plan.
+ */
+public class VisitorRewriteJob extends Job {
+    private final Group group;
+
+    private final DefaultPlanRewriter<JobContext> planRewriter;
+
+    /**
+     * Constructor.
+     */
+    public VisitorRewriteJob(CascadesContext cascadesContext, DefaultPlanRewriter<JobContext> rewriter, boolean once) {
+        super(JobType.VISITOR_REWRITE, cascadesContext.getCurrentJobContext(), once);

Review Comment:
   You should support once or set always once.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/PredicatePropagation.java:
##########
@@ -0,0 +1,102 @@
+// 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.ComparisonPredicate;
+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`
+     * Now only support infer `ComparisonPredicate`.
+     * TODO: We should determine whether `expression` satisfies the condition for replacement
+     *       eg: Satisfy `expression` is non-deterministic
+     */
+    private Expression doInfer(Expression leftSlotEqualToRightSlot, Expression expression) {
+        return expression.accept(new DefaultExpressionRewriter<Void>() {
+
+            @Override
+            public Expression visit(Expression expr, Void context) {
+                return expr;
+            }
+
+            @Override
+            public Expression visitComparisonPredicate(ComparisonPredicate cp, Void context) {
+                if (!cp.left().isConstant() && !cp.right().isConstant()) {
+                    return cp;
+                }
+                return super.visit(cp, context);
+            }
+
+            @Override
+            public Expression visitSlotReference(SlotReference slotReference, Void context) {
+                if (slotReference.equals(leftSlotEqualToRightSlot.child(0))) {
+                    return leftSlotEqualToRightSlot.child(1);
+                } else if (slotReference.equals(leftSlotEqualToRightSlot.child(1))) {
+                    return leftSlotEqualToRightSlot.child(0);
+                } else {
+                    return slotReference;
+                }
+            }

Review Comment:
   the declare the shape in the visitComparisonPredicate will more clearer.
   ```java
   @Override
   public Expression visitComparisonPredicate(ComparisonPredicate cp, Void context) {
       if (cp.left().isSlot() && cp.right().isConstant()) {
           return swapSlot(cp);
       } else if (cp.left().isConstant() && cp.right().isSlot()) {
           return swapSlot(cp);
       }
       return super.visit(cp, context);
   }
   
   private Expression swapSlot(Expression expr) {
       return expr.rewriteUp(e -> {
           if (e.equals(leftSlotEqualToRightSlot.child(0)) {
               return leftSlotEqualToRightSlot.child(1);
           } else if (e.equals(leftSlotEqualToRightSlot.child(1)) {
               return leftSlotEqualToRightSlot.child(0);
           } else {
               return e;
           }
       });
   }
   ```



##########
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);
+    }
+
+    private Set<Expression> getAvailableExpressions(Set<Expression> predicates, Plan plan) {
+        predicates.addAll(propagation.infer(predicates));

Review Comment:
   Don't use side effect to modify the variable which owner out of this function,
   And `getXxx` has a modify operation is odd.
   
   You should create a new predicate set and copy the predicates from the parameter.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/InferPredicates.java:
##########
@@ -0,0 +1,118 @@
+// 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.jobs.JobContext;
+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.trees.plans.visitor.DefaultPlanRewriter;
+import org.apache.doris.nereids.util.ExpressionUtils;
+
+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 extends DefaultPlanRewriter<JobContext> {
+    PredicatePropagation propagation = new PredicatePropagation();
+    PullUpPredicates pollUpPredicates = new PullUpPredicates();
+
+    /**
+     * 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
+     */
+    @Override
+    public Plan visitLogicalJoin(LogicalJoin<? extends Plan, ? extends Plan> join, JobContext context) {
+        join = (LogicalJoin<? extends Plan, ? extends Plan>) super.visit(join, context);
+        Plan left = join.left();
+        Plan right = join.right();
+        Set<Expression> expressions = getAllExpressions(left, right, join.getOnClauseCondition());
+        List<Expression> otherJoinConjuncts = Lists.newArrayList(join.getOtherJoinConjuncts());
+        switch (join.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 join;
+        }
+        return join.withOtherJoinConjuncts(otherJoinConjuncts);
+    }
+
+    /**
+     * reference `inferOn`
+     */
+    @Override
+    public Plan visitLogicalFilter(LogicalFilter<? extends Plan> filter, JobContext context) {
+        filter = (LogicalFilter<? extends Plan>) super.visit(filter, context);
+        Set<Expression> filterPredicates = filter.accept(pollUpPredicates, null);
+        Set<Expression> filterChildPredicates = filter.child(0).accept(pollUpPredicates, null);

Review Comment:
   This code seem like every plan child has many repeated traverse the all child plan tree by the pollUpPredicates.
   I think we should support invoke poll up and infer predicate which just process one level
   ```java
   filter = (LogicalFilter<? extends Plan>) super.visit(filter, context);
   Set<Expression> childPredicates = pollUpPredicate(filter); // just pull up one level child
   Set<Expression> mergedPredicates = ImmutableSet.Builder()
       .addAll(filter.getPredicates())
       .addAll(childPredicates);
   Set<Expression> inferredPredicates = propagation.infer(mergedPredicates);
   if (!inferredPredicates.equals(filter.getPredicates()) {
       return new LogicalFilter(inferredPredicates, filter.child());
   }
   return filter;
   ```
    



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate when push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r996729772


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/InferPredicates.java:
##########
@@ -0,0 +1,123 @@
+// 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.rules.PlanRuleFactory;
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RulePromise;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.plans.JoinType;
+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.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * infer additional predicates for filter and join.
+ */
+public class InferPredicates implements PlanRuleFactory {
+    PredicatePropagation propagation = new PredicatePropagation();
+    EffectivePredicatesExtractor predicatesExtractor = new EffectivePredicatesExtractor();
+
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                inferWhere(),
+                inferOn()
+        );
+    }
+
+    private Rule inferWhere() {
+        return logicalFilter(any()).thenApply(ctx -> {
+            LogicalFilter<Plan> root = ctx.root;
+            Plan filter = ctx.cascadesContext.getMemo().copyOut(root.getGroupExpression().get(), false);
+            Set<Expression> filterPredicates = filter.accept(predicatesExtractor, null);
+            Set<Expression> filterChildPredicates = filter.child(0).accept(predicatesExtractor, null);
+            filterPredicates.removeAll(filterChildPredicates);
+            ExpressionUtils.extractConjunction(root.getPredicates()).forEach(filterPredicates::remove);

Review Comment:
   I think this rule should process the current predicate, and not need to remove the predicate which exist in the child, this is the responsibility of another rule.
   keep the logical orthogonality too, and this rule will become more clarity, so you not need to copy out from the memo in the EffectivePredicateExtractor. and then, EffectivePredicateExtractor can be removed
   
   



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] wangshuo128 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate when push down predicate

Posted by GitBox <gi...@apache.org>.
wangshuo128 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r997688593


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/InferPredicates.java:
##########
@@ -0,0 +1,123 @@
+// 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.rules.PlanRuleFactory;
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RulePromise;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.plans.JoinType;
+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.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * infer additional predicates for filter and join.
+ */
+public class InferPredicates implements PlanRuleFactory {

Review Comment:
   This could be derived from `RewriteRuleFactory` and remove the `defaultPromise` method. 



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] hello-stephen commented on pull request #12996: [Nereids][Improve] infer predicate when push down predicate

Posted by GitBox <gi...@apache.org>.
hello-stephen commented on PR #12996:
URL: https://github.com/apache/doris/pull/12996#issuecomment-1284385838

   TeamCity pipeline, clickbench performance test result:
    the sum of best hot time: 38.46 seconds
    load time: 585 seconds
    storage size: 17154562414 Bytes
    https://doris-community-test-1308700295.cos.ap-hongkong.myqcloud.com/tmp/20221020020345_clickbench_pr_31524.html


-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 merged pull request #12996: [Nereids][Improve] infer predicate after push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 merged PR #12996:
URL: https://github.com/apache/doris/pull/12996


-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate after push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r1015106069


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/InferPredicates.java:
##########
@@ -0,0 +1,118 @@
+// 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.jobs.JobContext;
+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.trees.plans.visitor.DefaultPlanRewriter;
+import org.apache.doris.nereids.util.ExpressionUtils;
+
+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 extends DefaultPlanRewriter<JobContext> {
+    PredicatePropagation propagation = new PredicatePropagation();
+    PullUpPredicates pollUpPredicates = new PullUpPredicates();
+
+    /**
+     * 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
+     */
+    @Override
+    public Plan visitLogicalJoin(LogicalJoin<? extends Plan, ? extends Plan> join, JobContext context) {
+        join = (LogicalJoin<? extends Plan, ? extends Plan>) super.visit(join, context);
+        Plan left = join.left();
+        Plan right = join.right();
+        Set<Expression> expressions = getAllExpressions(left, right, join.getOnClauseCondition());
+        List<Expression> otherJoinConjuncts = Lists.newArrayList(join.getOtherJoinConjuncts());
+        switch (join.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 join;
+        }
+        return join.withOtherJoinConjuncts(otherJoinConjuncts);
+    }
+
+    /**
+     * reference `inferOn`
+     */
+    @Override
+    public Plan visitLogicalFilter(LogicalFilter<? extends Plan> filter, JobContext context) {
+        filter = (LogicalFilter<? extends Plan>) super.visit(filter, context);
+        Set<Expression> filterPredicates = filter.accept(pollUpPredicates, null);
+        Set<Expression> filterChildPredicates = filter.child(0).accept(pollUpPredicates, null);

Review Comment:
   This code seem like every plan child has many repeated traverse the all child plan tree by the pollUpPredicates.
   You should add a cache for every plan in PollUpPredicates for speed up.
    



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate after push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r1010421765


##########
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 condition: 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();
   ```
   
   The second implicit condition: this rule dependent the action: every non-deterministic in the same sql should equals. for example: `a.id = b.id and a.id=rand()`, if we can not ensure this condition and infer `b.id=()`, it will be wrong.
   
   
   Another case is the filter `a.id = b.id and a.id = c.id`,  infer `b.id = c.id` maybe useless and have some executing overhead, so maybe we should add some rule to delete some useless expression in the future, or just process this case: `column1 = column2 and anyExpressionJust compareTo anyExpressionNotContainsSlotReference`
   
   So maybe we just process the case `a.id = b.id and a.id compareTo literal` for safety?



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate after push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r1010421765


##########
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 and have some executing overhead, so maybe we should add some rule to delete some useless expression in the future.
   
   



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate after push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r1010421765


##########
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 and 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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate after push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r1010421765


##########
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 condition: 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 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();
   ```
   
   The second implicit condition: this rule dependent the action: every non-deterministic in the same sql should equals. for example: `a.id = b.id and a.id=rand()`, if we can not ensure this condition and infer `b.id=rand()`, it will be wrong.
   
   
   Another case is the filter `a.id = b.id and a.id = c.id`,  infer `b.id = c.id` maybe useless and have some executing overhead, so maybe we should add some rule to delete some useless expression in the future, or just process this case: `column1 = column2 and anyExpression compareTo anyExpressionNotContainsSlotReference`
   
   So maybe we should only process the case `a.id = b.id and a.id compareTo literal` for safety?



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate after push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r1010421765


##########
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 condition: 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();
   ```
   
   The second implicit condition: this rule dependent the action: every non-deterministic in the same sql should equals. for example: `a.id = b.id and a.id=rand()`, if we can not ensure this condition and infer `b.id=rand()`, it will be wrong.
   
   
   Another case is the filter `a.id = b.id and a.id = c.id`,  infer `b.id = c.id` maybe useless and have some executing overhead, so maybe we should add some rule to delete some useless expression in the future, or just process this case: `column1 = column2 and anyExpression compareTo anyExpressionNotContainsSlotReference`
   
   So maybe we should only process the case `a.id = b.id and a.id compareTo literal` for safety?



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate after push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r1010421765


##########
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 condition: 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 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();
   ```
   
   The second implicit condition: this rule dependent the action: every non-deterministic in the same sql should equals. for example: `a.id = b.id and a.id=rand()`, if we can not ensure this condition and infer `b.id=rand()`, it will be wrong.
   
   
   Another case is the filter `a.id = b.id and a.id = c.id`,  infer `b.id = c.id` maybe useless and have some executing overhead, so maybe we should add some rule to delete some useless expression in the future, or just process this case: `column1 = column2 and anyExpression compareTo literal`
   
   So maybe we should only process the case `a.id = b.id and a.id compareTo literal` for safety?



-- 
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-unsubscribe@doris.apache.org

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


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


[GitHub] [doris] 924060929 commented on a diff in pull request #12996: [Nereids][Improve] infer predicate when push down predicate

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #12996:
URL: https://github.com/apache/doris/pull/12996#discussion_r996698062


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/PredicatePropagation.java:
##########
@@ -0,0 +1,100 @@
+// 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 com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * derive additional predicates.
+ * for example:
+ * a = b and a = 1 => b = 1
+ */
+public class PredicatePropagation {
+
+    /**
+     * infer additional predicates.
+     */
+    public Set<Expression> infer(List<Expression> predicates) {
+        Set<Expression> inferred = Sets.newHashSet();
+        for (Expression predicate : predicates) {
+            if (canEquivalentDeduce(predicate)) {
+                List<Expression> candidates = subtract(predicates, predicate);
+                candidates.forEach(candidate -> {
+                    inferred.add(transform(candidate, predicate.child(0), predicate.child(1)));
+                });
+            }
+        }
+        predicates.forEach(inferred::remove);
+        return inferred;
+    }
+
+    private Expression transform(Expression expression, Expression source, Expression target) {
+        Expression rewritten = replace(expression, source, target);
+        if (expression.equals(rewritten)) {
+            rewritten = mapChildren(expression, source, target);
+            if (expression.equals(rewritten)) {
+                return expression;
+            } else {
+                return rewritten;
+            }
+        } else {
+            return mapChildren(rewritten, source, target);
+        }
+    }
+
+    private Expression mapChildren(Expression expression, Expression source, Expression target) {
+        if (!expression.children().isEmpty()) {
+            List<Expression> children = Lists.newArrayList();
+            for (Expression child : expression.children()) {
+                children.add(transform(child, source, target));
+            }
+            return expression.withChildren(children);
+        } else {
+            return expression;
+        }
+    }
+
+    private Expression replace(Expression expression, Expression source, Expression target) {
+        if (expression.equals(source)) {
+            return target;
+        }
+        if (expression.equals(target)) {
+            return source;
+        }
+        return expression;
+    }
+
+    private boolean canEquivalentDeduce(Expression predicate) {
+        return predicate instanceof EqualTo && predicate.children().stream().allMatch(e -> e instanceof SlotReference);
+    }
+
+    private List<Expression> subtract(List<Expression> expressions, Expression target) {
+        ArrayList<Expression> cloneList = Lists.newArrayList(expressions);
+        cloneList.remove(target);
+        return cloneList;
+    }
+}

Review Comment:
   Do not recursively traverse/rewrite manually, too.
   
   Use DefaultExpressionRewriter:
   ```java
   class PredicatePropagation {
       public Set<Expression> infer(List<Expression> predicates) {
           Set<Expression> inferred = Sets.newHashSet();
           for (Expression predicate : predicates) {
               if (canEquivalentDeduce(predicate)) {
                   Expression leftSlotEqualToRightSlot = predicate;
   
                   List<Expression> newInferred = predicates.stream()
                           .filter(p -> !p.equals(leftSlotEqualToRightSlot))
                           .map(p -> doInfer(leftSlotEqualToRightSlot, p))
                           .collect(Collectors.toList());
                   inferred.addAll(newInferred);
               }
           }
           predicates.forEach(inferred::remove);
           return inferred;
       }
   
       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 expr.child(1);
                   } else if (expr.equals(leftSlotEqualToRightSlot.child(1))) {
                       return expr.child(0);
                   } else {
                       return expr;
                   }
               }
           }, null);
       }
   
       private boolean canEquivalentDeduce(Expression predicate) {
           return predicate instanceof EqualTo && predicate.children().stream().allMatch(e -> e instanceof SlotReference);
       }
   ```
   
   or you can add the common rewrite method to TreeNode:
   ```java
   /**
    * bottom-up rewrite.
    * @param rewriteFunction rewrite function.
    * @return rewritten result.
    */
   default NODE_TYPE rewriteUp(Function<NODE_TYPE, NODE_TYPE> rewriteFunction) {
       boolean changed = false;
       Builder<NODE_TYPE> newChildren = ImmutableList.builderWithExpectedSize(arity());
       for (NODE_TYPE child : children()) {
           NODE_TYPE newChild = child.rewriteUp(rewriteFunction);
           if (child != newChild) {
               changed = true;
           }
           newChildren.add(newChild);
       }
   
       NODE_TYPE rewrittenChildren = changed ? withChildren(newChildren.build()) : (NODE_TYPE) this;
       return rewriteFunction.apply(rewrittenChildren);
   }
   ```
   
   then
   
   ```java
   private Expression doInfer(Expression leftSlotEqualToRightSlot, Expression expression) {
       return expression.rewriteUp(expr -> {
           if (expr.equals(leftSlotEqualToRightSlot.child(0))) {
               return expr.child(1);
           } else if (expr.equals(leftSlotEqualToRightSlot.child(1))) {
               return expr.child(0);
           } else {
               return expr;
           }
       });
   }
   ``` 



-- 
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-unsubscribe@doris.apache.org

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


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