sarutak commented on code in PR #60366:
URL: https://github.com/apache/spark/pull/60366#discussion_r4560055953
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +868,92 @@ object DecorrelateInnerQuery extends PredicateHelper {
// | 0 | null | null | 0 |
<--- correct result
// +---+------+------------+--------------------------------+
if (groupingExpressions.isEmpty && handleCountBug) {
- // Evaluate the aggregate expressions with zero tuples.
- val resultMap =
RewriteCorrelatedScalarSubquery.evalAggregateOnZeroTups(newAggregate)
val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
val expressions = ArrayBuffer.empty[NamedExpression]
- // Create new aliases for aggregate expressions that have
non-null default
- // values and reconstruct the output with the `alwaysTrue`
marker.
- val projectList = newAggregate.aggregateExpressions.map { a =>
- resultMap.get(a.exprId) match {
- // Aggregate expression is not subject to the count bug.
- case Some(Literal(null, _)) | None =>
+ // `ref` if `zeroTupsResult` is NULL, or
+ // `if(isnull(alwaysTrue), zeroTupsResult, ref)` otherwise.
+ def withZeroTupsResult(zeroTupsResult: Expression, ref:
Attribute): Expression =
+ zeroTupsResult match {
+ case Literal(null, _) => ref
+ case default => If(IsNull(alwaysTrueRef), default, ref)
+ }
+ // Only the aggregate functions are evaluated with zero tuples,
by taking their
+ // default results. An expression over them is computed above
the left outer
+ // domain join on the corrected values, so that it is evaluated
once per row on
+ // the value of that row, as for an outer row that has matching
rows. Evaluating
+ // the whole expression with zero tuples instead fails at
planning time if it
+ // throws (e.g. `10 / count(*)` in ANSI mode); and a Python UDF
over them, which
+ // `ExtractPythonUDFs` lifts out of the conditional branch,
would otherwise run at
+ // runtime for every outer row, including the rows whose
subquery has matching rows.
+ //
+ // This pulls out every aggregate function, so an expression
over several of them,
+ // e.g. `max(v) - min(v)`, carries one value per function into
the domain join
+ // instead of one per column. Only an expression that contains a
Python UDF needs
+ // the pull-out; for the others the same results could be kept
by leaving the
+ // expression in the Aggregate and reading
`if(isnull(alwaysTrue), <expression with
+ // each aggregate function replaced by its unfolded empty-input
result>, column)`,
+ // which constant folding tolerates in the conditional branch.
This single path is
+ // kept for simplicity; the alternative is a possible follow-up.
+ //
+ // TODO(SPARK-61444):
`RewriteCorrelatedScalarSubquery.constructLeftJoins` still
+ // statically evaluates the whole zero-row result of a
correlated scalar subquery,
+ // including subqueries whose count bug is handled here when it
reaches their
+ // rewritten expression (e.g. under a Project with no top
Aggregate), so such a
+ // subquery can still fail while the query is optimized (e.g.
`10 / count(*)` in
+ // ANSI mode). SPARK-61444 addresses that path.
+ val pulledOut = mutable.HashMap.empty[Expression, Expression]
+ def pullOut(e: Expression, name: String, zeroTupsResult:
Expression): Expression = {
+ def mk = {
+ val alias = Alias(e, name)()
+ expressions += alias
+ // The attribute is nullable since it is from the right-hand
side of a
+ // left outer join.
+ withZeroTupsResult(zeroTupsResult,
alias.toAttribute.withNullability(true))
+ }
+ // Deduplicate deterministic expressions only, as
`PhysicalAggregation` does: a
+ // non-deterministic aggregate function used more than once is
computed once per
+ // use there, and sharing one column would make the uses take
the same value.
+ if (e.deterministic)
pulledOut.getOrElseUpdate(e.canonicalized, mk) else mk
+ }
+ def zeroTupsResult(ae: AggregateExpression): Literal = {
+ val f = ae.aggregateFunction
+ f.defaultResult.getOrElse(Literal.create(null, f.dataType))
+ }
+ def rewrite(e: Expression): Expression = e match {
+ case ae: AggregateExpression => pullOut(ae, "aggResult",
zeroTupsResult(ae))
+ // An attribute inside an expression over aggregate functions.
A grouping-less
+ // Aggregate cannot reference one outside an aggregate
function (the analyzer
+ // rejects it), so this is unreachable from SQL; as
+ // `RewriteCorrelatedScalarSubquery.evalAggExprOnZeroTups`,
take it as NULL over
+ // zero rows in case it is reached.
+ case r: AttributeReference => pullOut(r, r.name,
Literal.create(null, r.dataType))
+ case other => other.mapChildren(rewrite)
+ }
+ val projectList = newAggregate.aggregateExpressions.map {
+ // Not subject to the count bug: NULL for zero tuples.
+ case a @ (_: AttributeReference | Alias(_: AttributeReference,
_)) =>
+ expressions += a
+ a.toAttribute.withNullability(true)
+ // A literal (SPARK-43156) keeps its name in the new aggregate.
+ case a @ Alias(l: Literal, _) =>
+ if (l.value == null) {
expressions += a
- // The attribute is nullable since it is from the
right-hand side of a
- // left outer join.
a.toAttribute.withNullability(true)
- case Some(default) =>
- assert(a.isInstanceOf[Alias], s"Cannot have non-aliased
expression $a in " +
- s"aggregate that evaluates to non-null value with zero
tuples.")
+ } else {
val newAttr = a.newInstance()
- val ref = newAttr.toAttribute.withNullability(true)
expressions += newAttr
- Alias(If(IsNull(alwaysTrueRef), default, ref),
a.name)(a.exprId)
- }
+ Alias(withZeroTupsResult(l,
newAttr.toAttribute.withNullability(true)),
+ a.name)(a.exprId)
+ }
+ // A single aggregate function, or an expression over
aggregate functions,
+ // computed over the pulled-out, corrected values. A single
function keeps its
+ // output name and exprId and shares its column with any
expression over it.
+ case a: Alias =>
Review Comment:
Thank you, and you are right. I measured it: on master the correlated
`LATERAL (SELECT CASE WHEN
COUNT(*) = 0 THEN 0 ELSE udf(10 / COUNT(*)) END ...)` returns a row for an
outer row without
matching rows (ANSI), and with this PR it fails with `DIVIDE_BY_ZERO` there,
because the expression
moves above the domain join and `ExtractPythonUDFs` lifts the UDF argument
out of the branch. The
uncorrelated form already fails the same way on master, so this PR makes the
correlated form
consistent with it. I went with documenting it as a behavior change rather
than special-casing it
(keeping it working would make the correlated form diverge from the
uncorrelated one): I reworded
the user-facing section and added a `SubquerySuite` test that pins the
runtime failure.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +868,92 @@ object DecorrelateInnerQuery extends PredicateHelper {
// | 0 | null | null | 0 |
<--- correct result
// +---+------+------------+--------------------------------+
if (groupingExpressions.isEmpty && handleCountBug) {
- // Evaluate the aggregate expressions with zero tuples.
- val resultMap =
RewriteCorrelatedScalarSubquery.evalAggregateOnZeroTups(newAggregate)
val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
val expressions = ArrayBuffer.empty[NamedExpression]
- // Create new aliases for aggregate expressions that have
non-null default
- // values and reconstruct the output with the `alwaysTrue`
marker.
- val projectList = newAggregate.aggregateExpressions.map { a =>
- resultMap.get(a.exprId) match {
- // Aggregate expression is not subject to the count bug.
- case Some(Literal(null, _)) | None =>
+ // `ref` if `zeroTupsResult` is NULL, or
+ // `if(isnull(alwaysTrue), zeroTupsResult, ref)` otherwise.
+ def withZeroTupsResult(zeroTupsResult: Expression, ref:
Attribute): Expression =
+ zeroTupsResult match {
+ case Literal(null, _) => ref
+ case default => If(IsNull(alwaysTrueRef), default, ref)
+ }
+ // Only the aggregate functions are evaluated with zero tuples,
by taking their
+ // default results. An expression over them is computed above
the left outer
+ // domain join on the corrected values, so that it is evaluated
once per row on
+ // the value of that row, as for an outer row that has matching
rows. Evaluating
+ // the whole expression with zero tuples instead fails at
planning time if it
+ // throws (e.g. `10 / count(*)` in ANSI mode); and a Python UDF
over them, which
+ // `ExtractPythonUDFs` lifts out of the conditional branch,
would otherwise run at
+ // runtime for every outer row, including the rows whose
subquery has matching rows.
+ //
+ // This pulls out every aggregate function, so an expression
over several of them,
+ // e.g. `max(v) - min(v)`, carries one value per function into
the domain join
+ // instead of one per column. Only an expression that contains a
Python UDF needs
+ // the pull-out; for the others the same results could be kept
by leaving the
+ // expression in the Aggregate and reading
`if(isnull(alwaysTrue), <expression with
+ // each aggregate function replaced by its unfolded empty-input
result>, column)`,
+ // which constant folding tolerates in the conditional branch.
This single path is
+ // kept for simplicity; the alternative is a possible follow-up.
+ //
+ // TODO(SPARK-61444):
`RewriteCorrelatedScalarSubquery.constructLeftJoins` still
+ // statically evaluates the whole zero-row result of a
correlated scalar subquery,
+ // including subqueries whose count bug is handled here when it
reaches their
+ // rewritten expression (e.g. under a Project with no top
Aggregate), so such a
+ // subquery can still fail while the query is optimized (e.g.
`10 / count(*)` in
+ // ANSI mode). SPARK-61444 addresses that path.
+ val pulledOut = mutable.HashMap.empty[Expression, Expression]
+ def pullOut(e: Expression, name: String, zeroTupsResult:
Expression): Expression = {
+ def mk = {
+ val alias = Alias(e, name)()
+ expressions += alias
+ // The attribute is nullable since it is from the right-hand
side of a
+ // left outer join.
+ withZeroTupsResult(zeroTupsResult,
alias.toAttribute.withNullability(true))
+ }
+ // Deduplicate deterministic expressions only, as
`PhysicalAggregation` does: a
+ // non-deterministic aggregate function used more than once is
computed once per
+ // use there, and sharing one column would make the uses take
the same value.
+ if (e.deterministic)
pulledOut.getOrElseUpdate(e.canonicalized, mk) else mk
+ }
+ def zeroTupsResult(ae: AggregateExpression): Literal = {
+ val f = ae.aggregateFunction
+ f.defaultResult.getOrElse(Literal.create(null, f.dataType))
+ }
+ def rewrite(e: Expression): Expression = e match {
+ case ae: AggregateExpression => pullOut(ae, "aggResult",
zeroTupsResult(ae))
+ // An attribute inside an expression over aggregate functions.
A grouping-less
+ // Aggregate cannot reference one outside an aggregate
function (the analyzer
+ // rejects it), so this is unreachable from SQL; as
+ // `RewriteCorrelatedScalarSubquery.evalAggExprOnZeroTups`,
take it as NULL over
+ // zero rows in case it is reached.
+ case r: AttributeReference => pullOut(r, r.name,
Literal.create(null, r.dataType))
+ case other => other.mapChildren(rewrite)
+ }
+ val projectList = newAggregate.aggregateExpressions.map {
+ // Not subject to the count bug: NULL for zero tuples.
+ case a @ (_: AttributeReference | Alias(_: AttributeReference,
_)) =>
+ expressions += a
+ a.toAttribute.withNullability(true)
+ // A literal (SPARK-43156) keeps its name in the new aggregate.
+ case a @ Alias(l: Literal, _) =>
+ if (l.value == null) {
expressions += a
- // The attribute is nullable since it is from the
right-hand side of a
- // left outer join.
a.toAttribute.withNullability(true)
- case Some(default) =>
- assert(a.isInstanceOf[Alias], s"Cannot have non-aliased
expression $a in " +
- s"aggregate that evaluates to non-null value with zero
tuples.")
+ } else {
val newAttr = a.newInstance()
- val ref = newAttr.toAttribute.withNullability(true)
expressions += newAttr
- Alias(If(IsNull(alwaysTrueRef), default, ref),
a.name)(a.exprId)
- }
+ Alias(withZeroTupsResult(l,
newAttr.toAttribute.withNullability(true)),
+ a.name)(a.exprId)
+ }
+ // A single aggregate function, or an expression over
aggregate functions,
+ // computed over the pulled-out, corrected values. A single
function keeps its
+ // output name and exprId and shares its column with any
expression over it.
Review Comment:
Thank you — the description on GitHub was stale; I had updated it only
locally. I have now updated
the PR body: the single-aggregate-function plan change (it goes through the
pull-out too), the
number of new tests, and the non-deterministic-test note are corrected.
##########
sql/core/src/test/scala/org/apache/spark/sql/SubquerySuite.scala:
##########
@@ -1874,6 +1875,107 @@ class SubquerySuite extends SharedSparkSession
checkAnswer(df, Nil)
}
+ test("SPARK-61482: COUNT bug of a lower aggregate with an expression over
aggregate functions") {
Review Comment:
Added. The runtime failure for an outer row without matching rows is now
checked for the scalar,
`LATERAL` and `IN` forms, and the guarded Python UDF has its own test (see
the correctness reply).
I also renamed the test to "an expression over aggregate functions in a
correlated subquery
(scalar, LATERAL, EXISTS and IN)".
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +868,92 @@ object DecorrelateInnerQuery extends PredicateHelper {
// | 0 | null | null | 0 |
<--- correct result
// +---+------+------------+--------------------------------+
if (groupingExpressions.isEmpty && handleCountBug) {
- // Evaluate the aggregate expressions with zero tuples.
- val resultMap =
RewriteCorrelatedScalarSubquery.evalAggregateOnZeroTups(newAggregate)
val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
val expressions = ArrayBuffer.empty[NamedExpression]
- // Create new aliases for aggregate expressions that have
non-null default
- // values and reconstruct the output with the `alwaysTrue`
marker.
- val projectList = newAggregate.aggregateExpressions.map { a =>
- resultMap.get(a.exprId) match {
- // Aggregate expression is not subject to the count bug.
- case Some(Literal(null, _)) | None =>
+ // `ref` if `zeroTupsResult` is NULL, or
+ // `if(isnull(alwaysTrue), zeroTupsResult, ref)` otherwise.
+ def withZeroTupsResult(zeroTupsResult: Expression, ref:
Attribute): Expression =
+ zeroTupsResult match {
+ case Literal(null, _) => ref
+ case default => If(IsNull(alwaysTrueRef), default, ref)
+ }
+ // Only the aggregate functions are evaluated with zero tuples,
by taking their
+ // default results. An expression over them is computed above
the left outer
+ // domain join on the corrected values, so that it is evaluated
once per row on
+ // the value of that row, as for an outer row that has matching
rows. Evaluating
+ // the whole expression with zero tuples instead fails at
planning time if it
+ // throws (e.g. `10 / count(*)` in ANSI mode); and a Python UDF
over them, which
+ // `ExtractPythonUDFs` lifts out of the conditional branch,
would otherwise run at
+ // runtime for every outer row, including the rows whose
subquery has matching rows.
+ //
+ // This pulls out every aggregate function, so an expression
over several of them,
+ // e.g. `max(v) - min(v)`, carries one value per function into
the domain join
+ // instead of one per column. Only an expression that contains a
Python UDF needs
+ // the pull-out; for the others the same results could be kept
by leaving the
+ // expression in the Aggregate and reading
`if(isnull(alwaysTrue), <expression with
+ // each aggregate function replaced by its unfolded empty-input
result>, column)`,
+ // which constant folding tolerates in the conditional branch.
This single path is
+ // kept for simplicity; the alternative is a possible follow-up.
+ //
+ // TODO(SPARK-61444):
`RewriteCorrelatedScalarSubquery.constructLeftJoins` still
+ // statically evaluates the whole zero-row result of a
correlated scalar subquery,
+ // including subqueries whose count bug is handled here when it
reaches their
+ // rewritten expression (e.g. under a Project with no top
Aggregate), so such a
+ // subquery can still fail while the query is optimized (e.g.
`10 / count(*)` in
+ // ANSI mode). SPARK-61444 addresses that path.
+ val pulledOut = mutable.HashMap.empty[Expression, Expression]
+ def pullOut(e: Expression, name: String, zeroTupsResult:
Expression): Expression = {
+ def mk = {
+ val alias = Alias(e, name)()
+ expressions += alias
+ // The attribute is nullable since it is from the right-hand
side of a
+ // left outer join.
+ withZeroTupsResult(zeroTupsResult,
alias.toAttribute.withNullability(true))
+ }
+ // Deduplicate deterministic expressions only, as
`PhysicalAggregation` does: a
+ // non-deterministic aggregate function used more than once is
computed once per
+ // use there, and sharing one column would make the uses take
the same value.
+ if (e.deterministic)
pulledOut.getOrElseUpdate(e.canonicalized, mk) else mk
+ }
+ def zeroTupsResult(ae: AggregateExpression): Literal = {
+ val f = ae.aggregateFunction
+ f.defaultResult.getOrElse(Literal.create(null, f.dataType))
+ }
+ def rewrite(e: Expression): Expression = e match {
+ case ae: AggregateExpression => pullOut(ae, "aggResult",
zeroTupsResult(ae))
+ // An attribute inside an expression over aggregate functions.
A grouping-less
+ // Aggregate cannot reference one outside an aggregate
function (the analyzer
+ // rejects it), so this is unreachable from SQL; as
+ // `RewriteCorrelatedScalarSubquery.evalAggExprOnZeroTups`,
take it as NULL over
+ // zero rows in case it is reached.
+ case r: AttributeReference => pullOut(r, r.name,
Literal.create(null, r.dataType))
+ case other => other.mapChildren(rewrite)
+ }
+ val projectList = newAggregate.aggregateExpressions.map {
+ // Not subject to the count bug: NULL for zero tuples.
+ case a @ (_: AttributeReference | Alias(_: AttributeReference,
_)) =>
+ expressions += a
+ a.toAttribute.withNullability(true)
+ // A literal (SPARK-43156) keeps its name in the new aggregate.
+ case a @ Alias(l: Literal, _) =>
Review Comment:
Done. Removed the literal-specific branch. A literal now takes the generic
`case a: Alias` path and
stays a constant in the `Project` above the join, saving the extra
`Aggregate` column and the `If`.
--
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]