sarutak commented on code in PR #60296:
URL: https://github.com/apache/spark/pull/60296#discussion_r4559639282
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,6 +567,85 @@ object PullupCorrelatedPredicates extends
Rule[LogicalPlan] with PredicateHelper
nonEquivalentGroupbyCols(query, aggNode.get).isEmpty
}
+ // Returns true if 'plan' returns exactly one row: an Aggregate without
grouping expressions
+ // returns one row even on empty input. Unlike guaranteedToReturnOneRow,
which allows at most
+ // one row, this must be exactly one, so it does not look through a Filter,
a Limit or a Window.
+ private def returnsExactlyOneRow(plan: LogicalPlan): Boolean = plan match {
+ case Project(_, child) => returnsExactlyOneRow(child)
+ case a: Aggregate => a.groupingExpressions.isEmpty
+ case _ => false
+ }
+
+ /**
+ * Returns an expression that computes `ae` over a single input row, or None
if it cannot.
+ * The expression applies the update expressions of the
[[DeclarativeAggregate]] once to its
+ * initial values, and then its evaluate expression; a FILTER keeps the
initial values when
+ * its condition does not hold. DISTINCT does not change the result over a
single row.
+ *
+ * Only a [[DeclarativeAggregate]] can be computed this way, see the note in
+ * [[ImperativeAggregate]]. Returns None if an argument or the FILTER is
non-deterministic,
+ * because the update expressions may evaluate an argument more than once
and the FILTER is
+ * evaluated once per buffer value; CheckAnalysis rejects a
non-deterministic argument, and SQL
+ * function resolution a non-deterministic FILTER, but a plan built another
way may not. Also
+ * returns None if the result does not keep the data type and nullability of
`ae`.
+ */
+ private def evalAggregateOnOneRow(ae: AggregateExpression):
Option[Expression] = {
+ ae.aggregateFunction match {
+ case f: DeclarativeAggregate
+ if f.children.forall(_.deterministic) &&
ae.filter.forall(_.deterministic) =>
+ def bindBuffer(e: Expression, values: Seq[Expression]): Expression = {
+ val buffer = AttributeMap(f.aggBufferAttributes.zip(values))
+ e.transform { case a: AttributeReference if buffer.contains(a) =>
buffer(a) }
+ }
+ val updated = f.updateExpressions.map(bindBuffer(_, f.initialValues))
+ val filtered = ae.filter match {
+ case Some(cond) => updated.zip(f.initialValues).map { case (u, i) =>
If(cond, u, i) }
+ case None => updated
+ }
+ val result = bindBuffer(f.evaluateExpression, filtered)
+ if (result.dataType == ae.dataType && (ae.nullable ||
!result.nullable)) {
+ Some(result)
+ } else {
+ None
+ }
+ case _ => None
+ }
+ }
+
+ /**
+ * Rewrites each Aggregate without grouping expressions over a node that
returns exactly one
+ * row (see `returnsExactlyOneRow`) into a Project, if
`evalAggregateOnOneRow` can compute all
+ * of its aggregate expressions. This removes a nested Aggregate from a
correlated scalar
+ * subquery, such as `SELECT MAX(c) FROM (SELECT SUM(b) AS c FROM t WHERE
t.a = outer.a)`, so
+ * that its count bug can be handled in
+ * [[RewriteCorrelatedScalarSubquery#constructLeftJoins]] instead of in
+ * [[DecorrelateInnerQuery]], which joins with the domain of the outer
columns.
+ */
+ private def collapseAggregatesOverOneRow(plan: LogicalPlan): LogicalPlan =
plan.transformUp {
+ // An Aggregate that carries a hint (an extension point, see
AggregateHint) is kept.
+ case a @ Aggregate(Nil, aggregateExpressions, child, None) if
returnsExactlyOneRow(child) =>
+ val results = aggregateExpressions.flatMap(_.collect {
+ case ae: AggregateExpression => ae.canonicalized ->
evalAggregateOnOneRow(ae)
+ }).toMap
+ if (results.values.forall(_.isDefined)) {
+ val projectList = aggregateExpressions.map(_.transformDown {
+ case ae: AggregateExpression => results(ae.canonicalized).get
+ }.asInstanceOf[NamedExpression])
+ Project(projectList, child)
+ } else {
+ a
+ }
+ }
+
+ // Strips the Projects without outer references at the top of 'plan', to
find the node that
+ // decides how the count bug is handled. A Project with outer references
stops the strip: it
+ // must be handled in DecorrelateInnerQuery, since constructLeftJoins
evaluates the top node
+ // over zero rows and cannot evaluate an outer reference there.
+ private def stripTopProjects(plan: LogicalPlan): LogicalPlan = plan match {
+ case p @ Project(_, child) if !p.projectList.exists(containsOuter) =>
stripTopProjects(child)
Review Comment:
This came from the stripping of top `Project`s, which is reverted in
5677e41df85. On 00ab7708f45 the `Project` at the top goes to
`DecorrelateInnerQuery` as on master, and the query returns `(1, 7), (2, 8)`. A
query of this shape is in the golden file now. The uncorrelated nested subquery
case goes away with it, since such a `Project` goes through the normal path of
`OptimizeSubqueries` again. In the separate PR, I will stop the stripping at a
`Project` with a subquery expression and add this test.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,6 +567,85 @@ object PullupCorrelatedPredicates extends
Rule[LogicalPlan] with PredicateHelper
nonEquivalentGroupbyCols(query, aggNode.get).isEmpty
}
+ // Returns true if 'plan' returns exactly one row: an Aggregate without
grouping expressions
+ // returns one row even on empty input. Unlike guaranteedToReturnOneRow,
which allows at most
+ // one row, this must be exactly one, so it does not look through a Filter,
a Limit or a Window.
+ private def returnsExactlyOneRow(plan: LogicalPlan): Boolean = plan match {
+ case Project(_, child) => returnsExactlyOneRow(child)
+ case a: Aggregate => a.groupingExpressions.isEmpty
+ case _ => false
+ }
+
+ /**
+ * Returns an expression that computes `ae` over a single input row, or None
if it cannot.
+ * The expression applies the update expressions of the
[[DeclarativeAggregate]] once to its
+ * initial values, and then its evaluate expression; a FILTER keeps the
initial values when
+ * its condition does not hold. DISTINCT does not change the result over a
single row.
+ *
+ * Only a [[DeclarativeAggregate]] can be computed this way, see the note in
+ * [[ImperativeAggregate]]. Returns None if an argument or the FILTER is
non-deterministic,
+ * because the update expressions may evaluate an argument more than once
and the FILTER is
+ * evaluated once per buffer value; CheckAnalysis rejects a
non-deterministic argument, and SQL
+ * function resolution a non-deterministic FILTER, but a plan built another
way may not. Also
+ * returns None if the result does not keep the data type and nullability of
`ae`.
+ */
+ private def evalAggregateOnOneRow(ae: AggregateExpression):
Option[Expression] = {
+ ae.aggregateFunction match {
+ case f: DeclarativeAggregate
+ if f.children.forall(_.deterministic) &&
ae.filter.forall(_.deterministic) =>
+ def bindBuffer(e: Expression, values: Seq[Expression]): Expression = {
+ val buffer = AttributeMap(f.aggBufferAttributes.zip(values))
+ e.transform { case a: AttributeReference if buffer.contains(a) =>
buffer(a) }
+ }
+ val updated = f.updateExpressions.map(bindBuffer(_, f.initialValues))
+ val filtered = ae.filter match {
+ case Some(cond) => updated.zip(f.initialValues).map { case (u, i) =>
If(cond, u, i) }
+ case None => updated
+ }
+ val result = bindBuffer(f.evaluateExpression, filtered)
Review Comment:
Thanks for pointing out that the second option would not cover this. The
collapse is reverted, so on 00ab7708f45 the argument of `MAX` is no longer
folded while the query is optimized: the lower `COUNT` sends the subquery to
`DecorrelateInnerQuery`, as on master, whose domain join gives `c = 0` for an
outer row without matching rows, and `MAX(10 / c)` evaluates `10 / c` at
runtime. As on master, it fails for such a row: with `a(k) = (1), (5)`, the
query fails with `DIVIDE_BY_ZERO` at runtime for `k = 5`. The query returns
`(1, 5.0), (2, 10.0)`, and a variant of it, with the golden file's tables and
`a1 = 0`, is in the golden file next to Q2 and Q3. The separate PR will rely on
the `tryEvalExpr` fallback of #60325 for the collapsed arguments.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -592,32 +671,69 @@ object PullupCorrelatedPredicates extends
Rule[LogicalPlan] with PredicateHelper
}
plan.transformExpressionsWithPruning(_.containsPattern(PLAN_EXPRESSION)) {
- case ScalarSubquery(sub, children, exprId, conditions, hint,
+ case ScalarSubquery(originalSub, children, exprId, conditions, hint,
mayHaveCountBugOld, needSingleJoinOld)
if children.nonEmpty =>
+ // An Aggregate without grouping expressions returns one row even on
empty input,
+ // whatever its aggregate functions are, and an Aggregate above it
sees that row. If the
+ // Aggregate is correlated, decorrelation can lose that row (see
below). An uncorrelated
+ // one keeps its row: [[DecorrelateInnerQuery]] leaves a subtree
without outer references
+ // (SubExprUtils.hasOuterReferences) unchanged, at most inner joining
it with the domain,
+ // and the non-legacy branch below uses the same check. With
+ // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR, only
such an Aggregate
+ // with an aggregate function that has a default result, such as
COUNT, qualifies,
+ // whether it is correlated or not.
+ val legacyNestedAggregateCountBug =
+
conf.getConf(SQLConf.LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR)
+ val legacyCountBugHandling =
conf.getConf(SQLConf.LEGACY_SCALAR_SUBQUERY_COUNT_BUG_HANDLING)
def mayHaveCountBugAgg(a: Aggregate): Boolean = {
- a.groupingExpressions.isEmpty &&
a.aggregateExpressions.exists(_.exists {
- case a: AggregateExpression =>
a.aggregateFunction.defaultResult.isDefined
- case _ => false
+ a.groupingExpressions.isEmpty && (if (legacyNestedAggregateCountBug)
{
+ a.aggregateExpressions.exists(_.exists {
+ case ae: AggregateExpression =>
ae.aggregateFunction.defaultResult.isDefined
+ case _ => false
+ })
+ } else {
+ SubExprUtils.hasOuterReferences(a)
})
}
+ // Collapsing an Aggregate over one row (see
collapseAggregatesOverOneRow) and looking
+ // through the Projects at the top let constructLeftJoins handle the
count bug of more
+ // subqueries. Neither is done when this rule runs again on a
rewritten subquery
+ // (mayHaveCountBugOld is defined), or when the plans of earlier
versions are kept:
+ // decorrelateInnerQuery is disabled, or
LEGACY_SCALAR_SUBQUERY_COUNT_BUG_HANDLING or
+ // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR is
enabled.
+ val simplifyForCountBug = mayHaveCountBugOld.isEmpty &&
+ SQLConf.get.decorrelateInnerQueryEnabled && !legacyCountBugHandling
&&
+ !legacyNestedAggregateCountBug
+ val sub = if (simplifyForCountBug) {
+ collapseAggregatesOverOneRow(originalSub)
+ } else {
+ originalSub
+ }
+ val topNode = if (simplifyForCountBug) stripTopProjects(sub) else sub
Review Comment:
Reverted with the collapse and the stripping of top `Project`s in
5677e41df85. 00ab7708f45 adds this query to `SubquerySuite` with
`spark.sql.optimizer.excludedRules` empty, so that `ConvertToLocalRelation`
runs. It returns 1 for every row, and the test fails on e77a0ba7ae1. For the
case of the collapse alone, `AVG` over a collapsed `MAX` over a correlated
`MAX`, I could not show a difference; `AVG` returns `NULL` there on every tree,
so I checked `COUNT(*)` instead: with `ConvertToLocalRelation`, `SELECT a1,
(SELECT COUNT(*) FROM (SELECT MAX(x) m FROM (SELECT MAX(t2.b2) x FROM t2 WHERE
t2.b1 = t1.a1 AND t2.b2 > 10))) FROM t1`, whose correct result is 1, returns
`(1, 1), (2, 1)` on e77a0ba7ae1 and 00ab7708f45, and `(1, 0), (2, 0)` on
master. 00ab7708f45 does not collapse, so it does not build that shape. In the
separate PR, I will apply both only when the result still matches that guard.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,6 +567,85 @@ object PullupCorrelatedPredicates extends
Rule[LogicalPlan] with PredicateHelper
nonEquivalentGroupbyCols(query, aggNode.get).isEmpty
}
+ // Returns true if 'plan' returns exactly one row: an Aggregate without
grouping expressions
+ // returns one row even on empty input. Unlike guaranteedToReturnOneRow,
which allows at most
+ // one row, this must be exactly one, so it does not look through a Filter,
a Limit or a Window.
+ private def returnsExactlyOneRow(plan: LogicalPlan): Boolean = plan match {
+ case Project(_, child) => returnsExactlyOneRow(child)
+ case a: Aggregate => a.groupingExpressions.isEmpty
+ case _ => false
+ }
+
+ /**
+ * Returns an expression that computes `ae` over a single input row, or None
if it cannot.
+ * The expression applies the update expressions of the
[[DeclarativeAggregate]] once to its
+ * initial values, and then its evaluate expression; a FILTER keeps the
initial values when
+ * its condition does not hold. DISTINCT does not change the result over a
single row.
+ *
+ * Only a [[DeclarativeAggregate]] can be computed this way, see the note in
+ * [[ImperativeAggregate]]. Returns None if an argument or the FILTER is
non-deterministic,
+ * because the update expressions may evaluate an argument more than once
and the FILTER is
+ * evaluated once per buffer value; CheckAnalysis rejects a
non-deterministic argument, and SQL
+ * function resolution a non-deterministic FILTER, but a plan built another
way may not. Also
+ * returns None if the result does not keep the data type and nullability of
`ae`.
+ */
+ private def evalAggregateOnOneRow(ae: AggregateExpression):
Option[Expression] = {
+ ae.aggregateFunction match {
+ case f: DeclarativeAggregate
+ if f.children.forall(_.deterministic) &&
ae.filter.forall(_.deterministic) =>
+ def bindBuffer(e: Expression, values: Seq[Expression]): Expression = {
+ val buffer = AttributeMap(f.aggBufferAttributes.zip(values))
+ e.transform { case a: AttributeReference if buffer.contains(a) =>
buffer(a) }
+ }
+ val updated = f.updateExpressions.map(bindBuffer(_, f.initialValues))
+ val filtered = ae.filter match {
+ case Some(cond) => updated.zip(f.initialValues).map { case (u, i) =>
If(cond, u, i) }
+ case None => updated
+ }
+ val result = bindBuffer(f.evaluateExpression, filtered)
+ if (result.dataType == ae.dataType && (ae.nullable ||
!result.nullable)) {
+ Some(result)
+ } else {
+ None
+ }
+ case _ => None
+ }
+ }
+
+ /**
+ * Rewrites each Aggregate without grouping expressions over a node that
returns exactly one
+ * row (see `returnsExactlyOneRow`) into a Project, if
`evalAggregateOnOneRow` can compute all
+ * of its aggregate expressions. This removes a nested Aggregate from a
correlated scalar
+ * subquery, such as `SELECT MAX(c) FROM (SELECT SUM(b) AS c FROM t WHERE
t.a = outer.a)`, so
+ * that its count bug can be handled in
+ * [[RewriteCorrelatedScalarSubquery#constructLeftJoins]] instead of in
+ * [[DecorrelateInnerQuery]], which joins with the domain of the outer
columns.
+ */
+ private def collapseAggregatesOverOneRow(plan: LogicalPlan): LogicalPlan =
plan.transformUp {
+ // An Aggregate that carries a hint (an extension point, see
AggregateHint) is kept.
+ case a @ Aggregate(Nil, aggregateExpressions, child, None) if
returnsExactlyOneRow(child) =>
+ val results = aggregateExpressions.flatMap(_.collect {
+ case ae: AggregateExpression => ae.canonicalized ->
evalAggregateOnOneRow(ae)
+ }).toMap
+ if (results.values.forall(_.isDefined)) {
+ val projectList = aggregateExpressions.map(_.transformDown {
+ case ae: AggregateExpression => results(ae.canonicalized).get
+ }.asInstanceOf[NamedExpression])
+ Project(projectList, child)
+ } else {
+ a
+ }
+ }
+
+ // Strips the Projects without outer references at the top of 'plan', to
find the node that
+ // decides how the count bug is handled. A Project with outer references
stops the strip: it
+ // must be handled in DecorrelateInnerQuery, since constructLeftJoins
evaluates the top node
+ // over zero rows and cannot evaluate an outer reference there.
+ private def stripTopProjects(plan: LogicalPlan): LogicalPlan = plan match {
+ case p @ Project(_, child) if !p.projectList.exists(containsOuter) =>
stripTopProjects(child)
Review Comment:
Reverted with the collapse and the stripping of top `Project`s in
5677e41df85. On 00ab7708f45 a subquery whose top node is a `Project` goes to
`DecorrelateInnerQuery` again as on master, so `inv(c)` sees only the real
counts, and `SUM(inv(c))` too: both return `(1, 50), (2, 100)` as on master,
with `inv = lambda x: 100 // x`. The routing change has a related case, a
Python UDF over an output of the lower aggregate, which #60366 fixes when every
outer row has matching rows; for an outer row without matching rows the UDF now
runs on `NULL` and can fail, see the comment above. In the separate PR, I will
skip a `Project` or an aggregate with a Python UDF.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -592,32 +671,69 @@ object PullupCorrelatedPredicates extends
Rule[LogicalPlan] with PredicateHelper
}
plan.transformExpressionsWithPruning(_.containsPattern(PLAN_EXPRESSION)) {
- case ScalarSubquery(sub, children, exprId, conditions, hint,
+ case ScalarSubquery(originalSub, children, exprId, conditions, hint,
mayHaveCountBugOld, needSingleJoinOld)
if children.nonEmpty =>
+ // An Aggregate without grouping expressions returns one row even on
empty input,
+ // whatever its aggregate functions are, and an Aggregate above it
sees that row. If the
+ // Aggregate is correlated, decorrelation can lose that row (see
below). An uncorrelated
+ // one keeps its row: [[DecorrelateInnerQuery]] leaves a subtree
without outer references
+ // (SubExprUtils.hasOuterReferences) unchanged, at most inner joining
it with the domain,
+ // and the non-legacy branch below uses the same check. With
+ // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR, only
such an Aggregate
+ // with an aggregate function that has a default result, such as
COUNT, qualifies,
+ // whether it is correlated or not.
+ val legacyNestedAggregateCountBug =
+
conf.getConf(SQLConf.LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR)
+ val legacyCountBugHandling =
conf.getConf(SQLConf.LEGACY_SCALAR_SUBQUERY_COUNT_BUG_HANDLING)
def mayHaveCountBugAgg(a: Aggregate): Boolean = {
- a.groupingExpressions.isEmpty &&
a.aggregateExpressions.exists(_.exists {
- case a: AggregateExpression =>
a.aggregateFunction.defaultResult.isDefined
- case _ => false
+ a.groupingExpressions.isEmpty && (if (legacyNestedAggregateCountBug)
{
+ a.aggregateExpressions.exists(_.exists {
+ case ae: AggregateExpression =>
ae.aggregateFunction.defaultResult.isDefined
+ case _ => false
+ })
+ } else {
+ SubExprUtils.hasOuterReferences(a)
})
}
+ // Collapsing an Aggregate over one row (see
collapseAggregatesOverOneRow) and looking
+ // through the Projects at the top let constructLeftJoins handle the
count bug of more
+ // subqueries. Neither is done when this rule runs again on a
rewritten subquery
+ // (mayHaveCountBugOld is defined), or when the plans of earlier
versions are kept:
+ // decorrelateInnerQuery is disabled, or
LEGACY_SCALAR_SUBQUERY_COUNT_BUG_HANDLING or
+ // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR is
enabled.
+ val simplifyForCountBug = mayHaveCountBugOld.isEmpty &&
Review Comment:
Mostly: 5677e41df85 reverts the collapse and the stripping of top
`Project`s, and they will go to a separate PR for `master`. This push also
changes three things that were not in e77a0ba7ae1. It keeps the old
default-result check next to the correlation check, see the comment above. It
keeps the previous routing where the domain joins of `DecorrelateInnerQuery` do
not work, see the comment above. And it adds the check for item 7, which keeps
`constructLeftJoins` for shapes such as `COLLECT_LIST(s)` over `MAX(b.v)`. That
check never changes the plan of a subquery that master handles in
`DecorrelateInnerQuery`, such as one with a lower `COUNT`. Among the shapes it
would accept, it leaves out a correlated subquery in a `FILTER` of the top
aggregate, which goes to `DecorrelateInnerQuery`: on master,
`constructLeftJoins` does not decorrelate that subquery, and the query fails
with `INTERNAL_ERROR` (`Cannot generate code for expression: outer(m)` in a
regular session). E.g. `SUM(m) FILT
ER (WHERE (SELECT MAX(c2) FROM t3 WHERE t3.c2 = m) IS NOT NULL)` over `MAX(b2)
AS m` now returns the correct result (golden file), as does a correlated
subquery in an argument, such as `SUM((SELECT MAX(c2) FROM t3 WHERE t3.c2 =
m))`, which the check does not accept either. SPARK-61615 covers the same
failure in the shapes that stay in `constructLeftJoins`, e.g. with a single
aggregate, over an uncorrelated lower `MAX`, or over a grouped lower aggregate.
I would include the check for item 7 in the backports too, since without it
shapes such as `COLLECT_LIST(s)` over `MAX(b.v)` get two more left outer joins
there; is that OK with you, or would you rather keep the backports to the
routing change alone (as narrowed on 00ab7708f45, without the check for item
7)? The routing change alone also fails Q2 and Q3 in ANSI mode, so this PR now
depends on #60366, which the backports need too.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,6 +567,85 @@ object PullupCorrelatedPredicates extends
Rule[LogicalPlan] with PredicateHelper
nonEquivalentGroupbyCols(query, aggNode.get).isEmpty
}
+ // Returns true if 'plan' returns exactly one row: an Aggregate without
grouping expressions
+ // returns one row even on empty input. Unlike guaranteedToReturnOneRow,
which allows at most
+ // one row, this must be exactly one, so it does not look through a Filter,
a Limit or a Window.
+ private def returnsExactlyOneRow(plan: LogicalPlan): Boolean = plan match {
+ case Project(_, child) => returnsExactlyOneRow(child)
+ case a: Aggregate => a.groupingExpressions.isEmpty
+ case _ => false
+ }
+
+ /**
+ * Returns an expression that computes `ae` over a single input row, or None
if it cannot.
+ * The expression applies the update expressions of the
[[DeclarativeAggregate]] once to its
+ * initial values, and then its evaluate expression; a FILTER keeps the
initial values when
+ * its condition does not hold. DISTINCT does not change the result over a
single row.
+ *
+ * Only a [[DeclarativeAggregate]] can be computed this way, see the note in
+ * [[ImperativeAggregate]]. Returns None if an argument or the FILTER is
non-deterministic,
+ * because the update expressions may evaluate an argument more than once
and the FILTER is
+ * evaluated once per buffer value; CheckAnalysis rejects a
non-deterministic argument, and SQL
+ * function resolution a non-deterministic FILTER, but a plan built another
way may not. Also
+ * returns None if the result does not keep the data type and nullability of
`ae`.
+ */
+ private def evalAggregateOnOneRow(ae: AggregateExpression):
Option[Expression] = {
+ ae.aggregateFunction match {
+ case f: DeclarativeAggregate
+ if f.children.forall(_.deterministic) &&
ae.filter.forall(_.deterministic) =>
+ def bindBuffer(e: Expression, values: Seq[Expression]): Expression = {
+ val buffer = AttributeMap(f.aggBufferAttributes.zip(values))
+ e.transform { case a: AttributeReference if buffer.contains(a) =>
buffer(a) }
+ }
+ val updated = f.updateExpressions.map(bindBuffer(_, f.initialValues))
+ val filtered = ae.filter match {
+ case Some(cond) => updated.zip(f.initialValues).map { case (u, i) =>
If(cond, u, i) }
+ case None => updated
+ }
+ val result = bindBuffer(f.evaluateExpression, filtered)
+ if (result.dataType == ae.dataType && (ae.nullable ||
!result.nullable)) {
+ Some(result)
+ } else {
+ None
+ }
+ case _ => None
+ }
+ }
+
+ /**
+ * Rewrites each Aggregate without grouping expressions over a node that
returns exactly one
+ * row (see `returnsExactlyOneRow`) into a Project, if
`evalAggregateOnOneRow` can compute all
+ * of its aggregate expressions. This removes a nested Aggregate from a
correlated scalar
+ * subquery, such as `SELECT MAX(c) FROM (SELECT SUM(b) AS c FROM t WHERE
t.a = outer.a)`, so
+ * that its count bug can be handled in
+ * [[RewriteCorrelatedScalarSubquery#constructLeftJoins]] instead of in
+ * [[DecorrelateInnerQuery]], which joins with the domain of the outer
columns.
+ */
+ private def collapseAggregatesOverOneRow(plan: LogicalPlan): LogicalPlan =
plan.transformUp {
Review Comment:
The rewrite is reverted here. I will put it next to `OptimizeOneRowPlan` in
the separate PR.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -592,32 +671,69 @@ object PullupCorrelatedPredicates extends
Rule[LogicalPlan] with PredicateHelper
}
plan.transformExpressionsWithPruning(_.containsPattern(PLAN_EXPRESSION)) {
- case ScalarSubquery(sub, children, exprId, conditions, hint,
+ case ScalarSubquery(originalSub, children, exprId, conditions, hint,
mayHaveCountBugOld, needSingleJoinOld)
if children.nonEmpty =>
+ // An Aggregate without grouping expressions returns one row even on
empty input,
+ // whatever its aggregate functions are, and an Aggregate above it
sees that row. If the
+ // Aggregate is correlated, decorrelation can lose that row (see
below). An uncorrelated
+ // one keeps its row: [[DecorrelateInnerQuery]] leaves a subtree
without outer references
+ // (SubExprUtils.hasOuterReferences) unchanged, at most inner joining
it with the domain,
+ // and the non-legacy branch below uses the same check. With
+ // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR, only
such an Aggregate
+ // with an aggregate function that has a default result, such as
COUNT, qualifies,
+ // whether it is correlated or not.
+ val legacyNestedAggregateCountBug =
+
conf.getConf(SQLConf.LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR)
+ val legacyCountBugHandling =
conf.getConf(SQLConf.LEGACY_SCALAR_SUBQUERY_COUNT_BUG_HANDLING)
def mayHaveCountBugAgg(a: Aggregate): Boolean = {
- a.groupingExpressions.isEmpty &&
a.aggregateExpressions.exists(_.exists {
- case a: AggregateExpression =>
a.aggregateFunction.defaultResult.isDefined
- case _ => false
+ a.groupingExpressions.isEmpty && (if (legacyNestedAggregateCountBug)
{
+ a.aggregateExpressions.exists(_.exists {
+ case ae: AggregateExpression =>
ae.aggregateFunction.defaultResult.isDefined
+ case _ => false
+ })
+ } else {
+ SubExprUtils.hasOuterReferences(a)
Review Comment:
Partly done in 00ab7708f45, for a list of functions. The count bug is
handled in `constructLeftJoins` as on master when the top aggregate has no
`GROUP BY`, only `Project`s are between the two aggregates, the lower one has
no `Aggregate` below it and no function with a `defaultResult`, and every
aggregate function of the top one is `MAX`, `MIN`, `SUM`, `AVG`, `COUNT`,
`FIRST`, `LAST`, or `COLLECT_LIST` or `COLLECT_SET` without `RESPECT NULLS`,
and its arguments are outputs of lower aggregate functions, such as `MAX`, and
its `FILTER` has no correlated subquery. A lower aggregate with a function with
a `defaultResult`, such as `COUNT` or `LISTAGG`, stays in
`DecorrelateInnerQuery` as on master, also when the top aggregate does not use
that function. Each of these returns over a row of `NULL`s what it returns over
no rows. A `FILTER` could only keep or drop that row, and, as on master,
`constructLeftJoins` does not evaluate its condition on that row.
`COLLECT_LIST` and `COLLECT_SET`
with `RESPECT NULLS` return `[NULL]` there, so they are not in the list.
Spark has no property that marks such functions, so I kept a list.
`STDDEV_SAMP`, `VAR_POP`, `PERCENTILE` and others also return over a row of
`NULL`s what they return over no rows, but I kept the list short and
conservative; they go to `DecorrelateInnerQuery`. `COLLECT_LIST(s)`, `SUM(s)`,
`COUNT(s)`, `AVG(s)` and `FIRST(s)` over `MAX(b.v)` have 1 left outer join
again, as on master.
Other shapes still have more left outer joins than on master, e.g.
`COUNT(*)` over `MAX(b.v)` goes from 1 to 2, `SUM(s)` over `COALESCE(SUM(b.v),
10)` from 1 to 3, and `COUNT(*)` over `MAX(b.v) UNION ALL MIN(b.v)` from 1 to
4. Most of them returned wrong results before. Some did not, such as
`PERCENTILE(s, 0.5)` and `STDDEV_SAMP(s)` over `MAX(b.v)`, which go from 1 to
3. The description has the measured table.
--
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: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]