Skip to content

Commit

Permalink
[SPARK-33122][SQL] Remove redundant aggregates in the Optimzier
Browse files Browse the repository at this point in the history
### What changes were proposed in this pull request?

Added optimizer rule `RemoveRedundantAggregates`. It removes redundant aggregates from a query plan. A redundant aggregate is an aggregate whose only goal is to keep distinct values, while its parent aggregate would ignore duplicate values.

The affected part of the query plan for TPCDS q87:

Before:
```
== Physical Plan ==
*(26) HashAggregate(keys=[], functions=[count(1)])
+- Exchange SinglePartition, true, [id=#785]
   +- *(25) HashAggregate(keys=[], functions=[partial_count(1)])
      +- *(25) HashAggregate(keys=[c_last_name#61, c_first_name#60, d_date#26], functions=[])
         +- *(25) HashAggregate(keys=[c_last_name#61, c_first_name#60, d_date#26], functions=[])
            +- *(25) HashAggregate(keys=[c_last_name#61, c_first_name#60, d_date#26], functions=[])
               +- *(25) HashAggregate(keys=[c_last_name#61, c_first_name#60, d_date#26], functions=[])
                  +- *(25) HashAggregate(keys=[c_last_name#61, c_first_name#60, d_date#26], functions=[])
                     +- Exchange hashpartitioning(c_last_name#61, c_first_name#60, d_date#26, 5), true, [id=#724]
                        +- *(24) HashAggregate(keys=[c_last_name#61, c_first_name#60, d_date#26], functions=[])
                           +- SortMergeJoin [coalesce(c_last_name#61, ), isnull(c_last_name#61), coalesce(c_first_name#60, ), isnull(c_first_name#60), coalesce(d_date#26, 0), isnull(d_date#26)], [coalesce(c_last_name#221, ), isnull(c_last_name#221), coalesce(c_first_name#220, ), isnull(c_first_name#220), coalesce(d_date#186, 0), isnull(d_date#186)], LeftAnti
                              :- ...
```

After:
```
== Physical Plan ==
*(26) HashAggregate(keys=[], functions=[count(1)])
+- Exchange SinglePartition, true, [id=#751]
   +- *(25) HashAggregate(keys=[], functions=[partial_count(1)])
      +- *(25) HashAggregate(keys=[c_last_name#61, c_first_name#60, d_date#26], functions=[])
         +- Exchange hashpartitioning(c_last_name#61, c_first_name#60, d_date#26, 5), true, [id=#694]
            +- *(24) HashAggregate(keys=[c_last_name#61, c_first_name#60, d_date#26], functions=[])
               +- SortMergeJoin [coalesce(c_last_name#61, ), isnull(c_last_name#61), coalesce(c_first_name#60, ), isnull(c_first_name#60), coalesce(d_date#26, 0), isnull(d_date#26)], [coalesce(c_last_name#221, ), isnull(c_last_name#221), coalesce(c_first_name#220, ), isnull(c_first_name#220), coalesce(d_date#186, 0), isnull(d_date#186)], LeftAnti
                  :- ...
```

### Why are the changes needed?

Performance improvements - few TPCDS queries have these kinds of duplicate aggregates.

### Does this PR introduce _any_ user-facing change?

No

### How was this patch tested?

UT

Benchmarks (sf=5):

OpenJDK 64-Bit Server VM 1.8.0_265-b01 on Linux 5.8.13-arch1-1
Intel(R) Core(TM) i5-6500 CPU  3.20GHz

| Query | Before  | After | Speedup |
| ------| ------- | ------| ------- |
| q14a | 44s | 44s | 1x |
| q14b | 41s | 41s | 1x |
| q38  | 6.5s | 5.9s | 1.1x |
| q87  | 7.2s | 6.8s | 1.1x |
| q14a-v2.7 | 55s | 53s | 1x |

Closes #30018 from tanelk/SPARK-33122.

Lead-authored-by: tanel.kiis@gmail.com <tanel.kiis@gmail.com>
Co-authored-by: Tanel Kiis <tanel.kiis@reach-u.com>
Signed-off-by: Takeshi Yamamuro <yamamuro@apache.org>
  • Loading branch information
2 people authored and maropu committed Mar 20, 2021
1 parent 7a8a600 commit 620cae0
Show file tree
Hide file tree
Showing 6 changed files with 284 additions and 52 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3114,56 +3114,6 @@ class Analyzer(override val catalogManager: CatalogManager)
}
}

/**
* Pulls out nondeterministic expressions from LogicalPlan which is not Project or Filter,
* put them into an inner Project and finally project them away at the outer Project.
*/
object PullOutNondeterministic extends Rule[LogicalPlan] {
override def apply(plan: LogicalPlan): LogicalPlan = plan.resolveOperatorsUp {
case p if !p.resolved => p // Skip unresolved nodes.
case p: Project => p
case f: Filter => f

case a: Aggregate if a.groupingExpressions.exists(!_.deterministic) =>
val nondeterToAttr = getNondeterToAttr(a.groupingExpressions)
val newChild = Project(a.child.output ++ nondeterToAttr.values, a.child)
a.transformExpressions { case e =>
nondeterToAttr.get(e).map(_.toAttribute).getOrElse(e)
}.copy(child = newChild)

// Don't touch collect metrics. Top-level metrics are not supported (check analysis will fail)
// and we want to retain them inside the aggregate functions.
case m: CollectMetrics => m

// todo: It's hard to write a general rule to pull out nondeterministic expressions
// from LogicalPlan, currently we only do it for UnaryNode which has same output
// schema with its child.
case p: UnaryNode if p.output == p.child.output && p.expressions.exists(!_.deterministic) =>
val nondeterToAttr = getNondeterToAttr(p.expressions)
val newPlan = p.transformExpressions { case e =>
nondeterToAttr.get(e).map(_.toAttribute).getOrElse(e)
}
val newChild = Project(p.child.output ++ nondeterToAttr.values, p.child)
Project(p.output, newPlan.withNewChildren(newChild :: Nil))
}

private def getNondeterToAttr(exprs: Seq[Expression]): Map[Expression, NamedExpression] = {
exprs.filterNot(_.deterministic).flatMap { expr =>
val leafNondeterministic = expr.collect {
case n: Nondeterministic => n
case udf: UserDefinedExpression if !udf.deterministic => udf
}
leafNondeterministic.distinct.map { e =>
val ne = e match {
case n: NamedExpression => n
case _ => Alias(e, "_nondeterministic")()
}
e -> ne
}
}.toMap
}
}

/**
* Set the seed for random number generation.
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* 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.spark.sql.catalyst.analysis

import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.catalyst.plans.logical._
import org.apache.spark.sql.catalyst.rules.Rule

/**
* Pulls out nondeterministic expressions from LogicalPlan which is not Project or Filter,
* put them into an inner Project and finally project them away at the outer Project.
*/
object PullOutNondeterministic extends Rule[LogicalPlan] {
override def apply(plan: LogicalPlan): LogicalPlan = plan resolveOperatorsUp applyLocally

val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
case p if !p.resolved => p // Skip unresolved nodes.
case p: Project => p
case f: Filter => f

case a: Aggregate if a.groupingExpressions.exists(!_.deterministic) =>
val nondeterToAttr = getNondeterToAttr(a.groupingExpressions)
val newChild = Project(a.child.output ++ nondeterToAttr.values, a.child)
a.transformExpressions { case e =>
nondeterToAttr.get(e).map(_.toAttribute).getOrElse(e)
}.copy(child = newChild)

// Don't touch collect metrics. Top-level metrics are not supported (check analysis will fail)
// and we want to retain them inside the aggregate functions.
case m: CollectMetrics => m

// todo: It's hard to write a general rule to pull out nondeterministic expressions
// from LogicalPlan, currently we only do it for UnaryNode which has same output
// schema with its child.
case p: UnaryNode if p.output == p.child.output && p.expressions.exists(!_.deterministic) =>
val nondeterToAttr = getNondeterToAttr(p.expressions)
val newPlan = p.transformExpressions { case e =>
nondeterToAttr.get(e).map(_.toAttribute).getOrElse(e)
}
val newChild = Project(p.child.output ++ nondeterToAttr.values, p.child)
Project(p.output, newPlan.withNewChildren(newChild :: Nil))
}

private def getNondeterToAttr(exprs: Seq[Expression]): Map[Expression, NamedExpression] = {
exprs.filterNot(_.deterministic).flatMap { expr =>
val leafNondeterministic = expr.collect {
case n: Nondeterministic => n
case udf: UserDefinedExpression if !udf.deterministic => udf
}
leafNondeterministic.distinct.map { e =>
val ne = e match {
case n: NamedExpression => n
case _ => Alias(e, "_nondeterministic")()
}
e -> ne
}
}.toMap
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ abstract class Optimizer(catalogManager: CatalogManager)
RewriteCorrelatedScalarSubquery,
EliminateSerialization,
RemoveRedundantAliases,
RemoveRedundantAggregates,
UnwrapCastInBinaryComparison,
RemoveNoopOperators,
OptimizeUpdateFields,
Expand Down Expand Up @@ -496,6 +497,50 @@ object RemoveRedundantAliases extends Rule[LogicalPlan] {
def apply(plan: LogicalPlan): LogicalPlan = removeRedundantAliases(plan, AttributeSet.empty)
}

/**
* Remove redundant aggregates from a query plan. A redundant aggregate is an aggregate whose
* only goal is to keep distinct values, while its parent aggregate would ignore duplicate values.
*/
object RemoveRedundantAggregates extends Rule[LogicalPlan] with AliasHelper {
def apply(plan: LogicalPlan): LogicalPlan = plan transformUp {
case upper @ Aggregate(_, _, lower: Aggregate) if lowerIsRedundant(upper, lower) =>
val aliasMap = getAliasMap(lower)

val newAggregate = upper.copy(
child = lower.child,
groupingExpressions = upper.groupingExpressions.map(replaceAlias(_, aliasMap)),
aggregateExpressions = upper.aggregateExpressions.map(
replaceAliasButKeepName(_, aliasMap))
)

// We might have introduces non-deterministic grouping expression
if (newAggregate.groupingExpressions.exists(!_.deterministic)) {
PullOutNondeterministic.applyLocally.applyOrElse(newAggregate, identity[LogicalPlan])
} else {
newAggregate
}
}

private def lowerIsRedundant(upper: Aggregate, lower: Aggregate): Boolean = {
val upperHasNoAggregateExpressions = !upper.aggregateExpressions.exists(isAggregate)

lazy val upperRefsOnlyDeterministicNonAgg = upper.references.subsetOf(AttributeSet(
lower
.aggregateExpressions
.filter(_.deterministic)
.filter(!isAggregate(_))
.map(_.toAttribute)
))

upperHasNoAggregateExpressions && upperRefsOnlyDeterministicNonAgg
}

private def isAggregate(expr: Expression): Boolean = {
expr.find(e => e.isInstanceOf[AggregateExpression] ||
PythonUDF.isGroupedAggPandasUDF(e)).isDefined
}
}

/**
* Remove no-op operators from the query plan that do not make any modifications.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -624,7 +624,7 @@ case class Range(
*
* @param groupingExpressions expressions for grouping keys
* @param aggregateExpressions expressions for a project list, which could contain
* [[AggregateFunction]]s.
* [[AggregateExpression]]s.
*
* Note: Currently, aggregateExpressions is the project list of this Group by operator. Before
* separating projection from grouping and aggregate, we should avoid expression-level optimization
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
/*
* 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.spark.sql.catalyst.optimizer

import org.apache.spark.api.python.PythonEvalType
import org.apache.spark.sql.catalyst.dsl.expressions._
import org.apache.spark.sql.catalyst.dsl.plans._
import org.apache.spark.sql.catalyst.expressions.{Expression, PythonUDF}
import org.apache.spark.sql.catalyst.plans.PlanTest
import org.apache.spark.sql.catalyst.plans.logical.{LocalRelation, LogicalPlan}
import org.apache.spark.sql.catalyst.rules.RuleExecutor
import org.apache.spark.sql.types.IntegerType

class RemoveRedundantAggregatesSuite extends PlanTest {

object Optimize extends RuleExecutor[LogicalPlan] {
val batches = Batch("RemoveRedundantAggregates", FixedPoint(10),
RemoveRedundantAggregates) :: Nil
}

private def aggregates(e: Expression): Seq[Expression] = {
Seq(
count(e),
PythonUDF("pyUDF", null, IntegerType, Seq(e),
PythonEvalType.SQL_GROUPED_AGG_PANDAS_UDF, udfDeterministic = true)
)
}

test("Remove redundant aggregate") {
val relation = LocalRelation('a.int, 'b.int)
for (agg <- aggregates('b)) {
val query = relation
.groupBy('a)('a, agg)
.groupBy('a)('a)
.analyze
val expected = relation
.groupBy('a)('a)
.analyze
val optimized = Optimize.execute(query)
comparePlans(optimized, expected)
}
}

test("Remove 2 redundant aggregates") {
val relation = LocalRelation('a.int, 'b.int)
for (agg <- aggregates('b)) {
val query = relation
.groupBy('a)('a, agg)
.groupBy('a)('a)
.groupBy('a)('a)
.analyze
val expected = relation
.groupBy('a)('a)
.analyze
val optimized = Optimize.execute(query)
comparePlans(optimized, expected)
}
}

test("Remove redundant aggregate with different grouping") {
val relation = LocalRelation('a.int, 'b.int)
val query = relation
.groupBy('a, 'b)('a)
.groupBy('a)('a)
.analyze
val expected = relation
.groupBy('a)('a)
.analyze
val optimized = Optimize.execute(query)
comparePlans(optimized, expected)
}

test("Remove redundant aggregate with aliases") {
val relation = LocalRelation('a.int, 'b.int)
for (agg <- aggregates('b)) {
val query = relation
.groupBy('a + 'b)(('a + 'b) as 'c, agg)
.groupBy('c)('c)
.analyze
val expected = relation
.groupBy('a + 'b)(('a + 'b) as 'c)
.analyze
val optimized = Optimize.execute(query)
comparePlans(optimized, expected)
}
}

test("Remove redundant aggregate with non-deterministic upper") {
val relation = LocalRelation('a.int, 'b.int)
val query = relation
.groupBy('a)('a)
.groupBy('a)('a, rand(0) as 'c)
.analyze
val expected = relation
.groupBy('a)('a, rand(0) as 'c)
.analyze
val optimized = Optimize.execute(query)
comparePlans(optimized, expected)
}

test("Remove redundant aggregate with non-deterministic lower") {
val relation = LocalRelation('a.int, 'b.int)
val query = relation
.groupBy('a, 'c)('a, rand(0) as 'c)
.groupBy('a, 'c)('a, 'c)
.analyze
val expected = relation
.groupBy('a, 'c)('a, rand(0) as 'c)
.analyze
val optimized = Optimize.execute(query)
comparePlans(optimized, expected)
}

test("Keep non-redundant aggregate - upper has agg expression") {
val relation = LocalRelation('a.int, 'b.int)
for (agg <- aggregates('b)) {
val query = relation
.groupBy('a, 'b)('a, 'b)
// The count would change if we remove the first aggregate
.groupBy('a)('a, agg)
.analyze
val optimized = Optimize.execute(query)
comparePlans(optimized, query)
}
}

test("Keep non-redundant aggregate - upper references agg expression") {
val relation = LocalRelation('a.int, 'b.int)
for (agg <- aggregates('b)) {
val query = relation
.groupBy('a)('a, agg as 'c)
.groupBy('c)('c)
.analyze
val optimized = Optimize.execute(query)
comparePlans(optimized, query)
}
}

test("Keep non-redundant aggregate - upper references non-deterministic non-grouping") {
val relation = LocalRelation('a.int, 'b.int)
val query = relation
.groupBy('a)('a, ('a + rand(0)) as 'c)
.groupBy('a, 'c)('a, 'c)
.analyze
val optimized = Optimize.execute(query)
comparePlans(optimized, query)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ abstract class RemoveRedundantProjectsSuiteBase
|)
|""".stripMargin

Seq(("UNION", 2, 2), ("UNION ALL", 1, 2)).foreach { case (setOperation, enabled, disabled) =>
Seq(("UNION", 1, 2), ("UNION ALL", 1, 2)).foreach { case (setOperation, enabled, disabled) =>
val query = queryTemplate.format(setOperation)
assertProjectExec(query, enabled = enabled, disabled = disabled)
}
Expand Down

0 comments on commit 620cae0

Please sign in to comment.