Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -152,10 +152,10 @@ abstract class Optimizer(sessionCatalog: SessionCatalog)
Batch("LocalRelation early", fixedPoint,
ConvertToLocalRelation,
PropagateEmptyRelation) ::
Batch("Pullup Correlated Expressions", Once,
PullupCorrelatedPredicates) ::
Batch("Subquery", FixedPoint(1),
OptimizeSubqueries) ::
OptimizeSubqueries,
PullupCorrelatedPredicates,
RewritePredicateSubquery) ::
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will it affect CBO?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gatorsmile Could you please elaborate ? My hope is that we can get better optimized plans as we will expose the full plan to entire set of optimizations ? As an example, lets say we have a rule that can convert leftsemi join to inner join, with this, we can hope to have this conversion and if we do, then CBO will be able to impact positively to re-order joins as required. Please let me know if i am missing something..

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Our CBO is based on the pattern matching. We only support InnerLike joins.

Is that possible the pattern matched before but it does not matched after we convert subquery to join? RewritePredicateSubquery adds LeftSemi or LeftAnti joins into the original plan.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gatorsmile At the moment, i am unable to think of a case when by moving the rewrite up would impact the pattern matching in CBO in a negative way since RewritePredicateSubquery needs to happen any way (it just happens later) . The leftsemi/anti join should end up being in the same position in the plan tree as we have the same pushdown rules for leftsemi and leftanti as there are for filters. If you have a case in mind, i can give it a quick try ?

Batch("Replace Operators", fixedPoint,
RewriteExceptAll,
RewriteIntersectAll,
Expand Down Expand Up @@ -187,9 +187,8 @@ abstract class Optimizer(sessionCatalog: SessionCatalog)
// "Extract PythonUDF From JoinCondition".
Batch("Check Cartesian Products", Once,
CheckCartesianProducts) :+
Batch("RewriteSubquery", Once,
RewritePredicateSubquery,
ColumnPruning,
Batch("Final Column Pruning", Once,
FinalColumnPruning,
CollapseProject,
RemoveNoopOperators) :+
// This batch must be executed after the `RewriteSubquery` batch, which creates joins.
Expand Down Expand Up @@ -548,12 +547,44 @@ object PushProjectionThroughUnion extends Rule[LogicalPlan] with PredicateHelper
* remove the Project p2 in the following pattern:
*
* p1 @ Project(_, Filter(_, p2 @ Project(_, child))) if p2.outputSet.subsetOf(p2.inputSet)
* p1 @ Project(_, j @ Join(p2 @ Project(_, child), _, LeftSemiOrAnti(_), _))
*
* p2 is usually inserted by this rule and useless, p1 could prune the columns anyway.
*/
object ColumnPruning extends Rule[LogicalPlan] {

def apply(plan: LogicalPlan): LogicalPlan = removeProjectBeforeFilter(plan transform {
def apply(plan: LogicalPlan): LogicalPlan = removeProjectBeforeFilter(FinalColumnPruning(plan))

/**
* The Project before Filter or LeftSemi/LeftAnti not necessary but conflict with
* PushPredicatesThroughProject, so remove it. Since the Projects have been added
* top-down, we need to remove in bottom-up order, otherwise lower Projects can be missed.
*
* While removing the projects below a self join, we should ensure that the plan remains
* valid after removing the project. The project node could have been added to de-duplicate
* the attributes and thus we need to check for this case before removing the project node.
*/
private def removeProjectBeforeFilter(plan: LogicalPlan): LogicalPlan = plan transformUp {
case p1 @ Project(_, f @ Filter(_, p2 @ Project(_, child)))
if p2.outputSet.subsetOf(child.outputSet) &&
// We only remove attribute-only project.
p2.projectList.forall(_.isInstanceOf[AttributeReference]) =>
p1.copy(child = f.copy(child = child))

case p1 @ Project(_, j @ Join(p2 @ Project(_, child), right, LeftSemiOrAnti(_), _, _))
if p2.outputSet.subsetOf(child.outputSet) &&
// We only remove attribute-only project.
p2.projectList.forall(_.isInstanceOf[AttributeReference]) &&
child.outputSet.intersect(right.outputSet).isEmpty =>
p1.copy(child = j.copy(left = child))
}
}

/**
* Attempts to eliminate the reading of unneeded columns from the query plan.
*/
object FinalColumnPruning extends Rule[LogicalPlan] {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do we need to separate the column pruning rule?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there is a subquery related bug fix: #25204

Is it related to your change as well?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cloud-fan I took a very quick look. It does not seem related to this PR.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cloud-fan

why do we need to separate the column pruning rule?

Perhaps there is a better way to do this. But here is the problem. Please take a look at RewriteSubquerySuite: Column pruning after rewriting predicate subquery. This test case is expecting that we perform column pruning to filter out un-needed columns before the join. Here is the input plan :

Project [a#0]                    
 +- Join LeftSemi, (a#0 = x#2)    
   +-LocalRelation [a#0, b#1]       
   +- LocalRelation [x#2]

Due to the presence Project on top of LeftSemi, the regular ColumnPruning rule is not able to add the Project on top of the left child of LeftSemiJoin. This is done to avoid the cycle between ColumnPruning and PushPredicateThroughProject. Thats why i created this FinalColumnPruning rule that does not have the logic to remove the project.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is done to avoid the cycle between ColumnPruning and PushPredicateThroughProject

I don't see a filter in the input plan, how is it related to PushPredicateThroughProject?

Copy link
Contributor Author

@dilipbiswal dilipbiswal Jul 26, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cloud-fan so the LeftSemi/Anti pattern is treated like a Filter in modified ColumnPruning rule. Since we convert the subqueries (which was in Filter form) to join early now, we are basically treating it like a Filter in related rules.

how is it related to PushPredicateThroughProject

Sorry.. just to clarify, In the prior PR, we have added PushDownLeftSemiAntiJoin where a LeftSemi/Anti join is pushed down below Project. So the Cycle would be between ColumnPruning and PushDownLeftSemiAntiJoin.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah i see, thanks for explaination!

def apply(plan: LogicalPlan): LogicalPlan = plan transform {
// Prunes the unused columns from project list of Project/Aggregate/Expand
case p @ Project(_, p2: Project) if !p2.outputSet.subsetOf(p.references) =>
p.copy(child = p2.copy(projectList = p2.projectList.filter(p.references.contains)))
Expand Down Expand Up @@ -656,27 +687,15 @@ object ColumnPruning extends Rule[LogicalPlan] {
} else {
p
}
})
}

/** Applies a projection only when the child is producing unnecessary attributes */
private def prunedChild(c: LogicalPlan, allReferences: AttributeSet) =
private def prunedChild(c: LogicalPlan, allReferences: AttributeSet) = {
if (!c.outputSet.subsetOf(allReferences)) {
Project(c.output.filter(allReferences.contains), c)
} else {
c
}

/**
* The Project before Filter is not necessary but conflict with PushPredicatesThroughProject,
* so remove it. Since the Projects have been added top-down, we need to remove in bottom-up
* order, otherwise lower Projects can be missed.
*/
private def removeProjectBeforeFilter(plan: LogicalPlan): LogicalPlan = plan transformUp {
case p1 @ Project(_, f @ Filter(_, p2 @ Project(_, child)))
if p2.outputSet.subsetOf(child.outputSet) &&
// We only remove attribute-only project.
p2.projectList.forall(_.isInstanceOf[AttributeReference]) =>
p1.copy(child = f.copy(child = child))
}
}

Expand Down Expand Up @@ -1113,8 +1132,11 @@ object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelpe

case filter @ Filter(condition, union: Union) =>
// Union could change the rows, so non-deterministic predicate can't be pushed down
val (pushDown, stayUp) = splitConjunctivePredicates(condition).partition(_.deterministic)
val (candidates, containingNonDeterministic) =
splitConjunctivePredicates(condition).partition(_.deterministic)

val (pushDown, rest) = candidates.partition { cond => !SubExprUtils.containsOuter(cond) }
val stayUp = rest ++ containingNonDeterministic
if (pushDown.nonEmpty) {
val pushDownCond = pushDown.reduceLeft(And)
val output = union.output
Expand Down Expand Up @@ -1227,7 +1249,7 @@ object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelpe
val attributes = plan.outputSet
val matched = condition.find {
case s: SubqueryExpression => s.plan.outputSet.intersect(attributes).nonEmpty
case _ => false
case e => SubExprUtils.containsOuter(e)
}
matched.isEmpty
}
Expand All @@ -1253,13 +1275,17 @@ object PushPredicateThroughJoin extends Rule[LogicalPlan] with PredicateHelper {
* @return (canEvaluateInLeft, canEvaluateInRight, haveToEvaluateInBoth)
*/
private def split(condition: Seq[Expression], left: LogicalPlan, right: LogicalPlan) = {
val (pushDownCandidates, nonDeterministic) = condition.partition(_.deterministic)
val (candidates, nonDeterministic) = condition.partition(_.deterministic)
val (pushDownCandidates, subquery) = candidates.partition { cond =>
!SubExprUtils.containsOuter(cond)
}
val (leftEvaluateCondition, rest) =
pushDownCandidates.partition(_.references.subsetOf(left.outputSet))
val (rightEvaluateCondition, commonCondition) =
rest.partition(expr => expr.references.subsetOf(right.outputSet))
rest.partition(expr => expr.references.subsetOf(right.outputSet))

(leftEvaluateCondition, rightEvaluateCondition, commonCondition ++ nonDeterministic)
(leftEvaluateCondition, rightEvaluateCondition,
subquery ++ commonCondition ++ nonDeterministic)
}

def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,12 @@ class RewriteSubquerySuite extends PlanTest {

object Optimize extends RuleExecutor[LogicalPlan] {
val batches =
Batch("Subquery", Once,
RewritePredicateSubquery) ::
Batch("Column Pruning", FixedPoint(100), ColumnPruning) ::
Batch("Rewrite Subquery", FixedPoint(1),
Batch("Final Column Pruning", FixedPoint(1),
RewritePredicateSubquery,
ColumnPruning,
FinalColumnPruning,
CollapseProject,
RemoveNoopOperators) :: Nil
}
Expand Down
Loading