spark-test commented on code in PR #60366:
URL: https://github.com/apache/spark/pull/60366#discussion_r4547009620
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +868,79 @@ 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.
+ 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))
Review Comment:
**Nit (P3):** Declaring every pulled-out reference nullable makes
`if(isnull(alwaysTrue), 0, aggResult)` nullable even for a non-nullable
function like `COUNT` whose empty-input result is not NULL. An expression that
records its inputs' nullability then gets a wider type under its original
expression ID. Consider `LATERAL (SELECT array(COUNT(*)) AS arr FROM r WHERE
r.c = l.a)`. Reading the code, `arr` is analyzed as `array<bigint not null>`
but is now produced as `array<bigint>`, while the references above the subquery
keep `array<bigint not null>`. `UpdateAttributeNullability` fixes only
top-level nullability, so the mismatch remains, and map and struct constructors
behave the same way. Rows do not change, because the value is never NULL, which
is also why no `checkAnswer` test can notice. For such functions, marking the
matched branch's value non-null, for example `KnownNotNull(aggResult)` inside
the `If`, would keep the analyzed type.
**Verification:**
- **Regression:** In a correlated subquery whose COUNT bug
DecorrelateInnerQuery handles, an expression column such as array(COUNT(*)),
and a struct or map over COUNT, keeps its analyzed data type, including element
and field nullability, in the rewritten plan.
- **Behavior:** Such a query returns the same rows as before for outer rows
with and without matching rows, including the empty-input value for a row
without matches.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +868,79 @@ 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
Review Comment:
**Nit (P3):** This comment presents evaluating the whole expression on zero
rows as avoided, but `RewriteCorrelatedScalarSubquery.constructLeftJoins` still
does it for correlated scalar subqueries. It computes
`evalSubqueryOnZeroTups(query)` (subquery.scala:914) before it checks
`mayHaveCountBug`, and `tryEvalExpr` evals a foldable result with no error
handling. Reading the code, that keeps raising DIVIDE_BY_ZERO at planning time
in two places. One is the scalar subqueries it corrects itself, such as
`(SELECT 10 / COUNT(*) FROM r WHERE l.a = r.c)` in ANSI mode. The other is
Project-rooted subqueries whose COUNT bug this code now handles, such as
`(SELECT d FROM (SELECT 10 / COUNT(*) d FROM r WHERE l.a = r.c))`. On the first
path, a Python UDF result also stays in the `If` as `udf(0)` and runs for every
outer row. The PR description defers all of this to SPARK-61444, but only
there, so a reader of this comment cannot tell that the fix is partial. A
`TODO(SPARK-61444)` here could no
te that `constructLeftJoins` still evaluates the whole zero-row result of
correlated scalar subqueries, including the ones handled here whose rewritten
expression it reaches before any Aggregate, such as under a Project.
**Verification:**
- **Inspection:** The COUNT-bug comment in DecorrelateInnerQuery contains a
TODO that names SPARK-61444 and identifies constructLeftJoins' zero-row
evaluation of correlated scalar subqueries, including those whose COUNT bug
this code handled, as the deferred path, and no code changes.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +868,79 @@ 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.
+ 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 single aggregate function or a literal (SPARK-43156)
keeps its name in the
+ // new aggregate.
+ case a @ Alias(child @ (_: Literal | _: AggregateExpression),
_) =>
Review Comment:
**Nit (P3):** This branch adds a single aggregate function such as `COUNT(*)
AS c` to the new Aggregate without registering it in `pulledOut`. An expression
column over the same deterministic function therefore pulls it out again as
another `aggResult` column. Take `COUNT(*) AS c, SUM(b.v) / COUNT(*) AS avg` in
a correlated LATERAL subquery. Reading the code, the decorrelated Aggregate
then outputs `count(1)` twice, and every inner-group row entering the left
outer domain join carries the duplicate value; `PhysicalAggregation` still
computes it only once. The base branch output two value columns for this query,
and reusing `c`'s corrected value `if(isnull(alwaysTrue), 0, c)` in `avg` would
also give two, with the same results. The new plan test pins the duplicate
(`cntRes` and `c2`, `maxRes` and `m`, at DecorrelateInnerQuerySuite.scala:255).
Seeding `pulledOut` with each deterministic bare column's corrected reference
would remove it. That needs a first pass, because a bare column
can come after the expression that uses its function.
**Verification:**
- **Regression:** For a correlated subquery whose COUNT bug
DecorrelateInnerQuery handles, with a bare aggregate column and an expression
column over the same deterministic function, including when the expression
column comes first, the rewritten Aggregate outputs that function once, and the
expression refers to the bare column's corrected value.
- **Behavior:** Such a query returns the same rows as before for outer rows
with and without matching rows.
- **Compatibility:** A non-deterministic aggregate function used both bare
and in an expression column still gets its own column for each use.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuerySuite.scala:
##########
@@ -209,6 +210,117 @@ class DecorrelateInnerQuerySuite extends PlanTest {
check(innerPlan, outerPlan, correctAnswer, Seq(x <=> x))
}
+ test("SPARK-61482: COUNT bug handling evaluates only aggregate functions on
zero tuples") {
+ val outerPlan = testRelation2
+ // Two separate `count(1)` instances, as two `COUNT(*)` in a query are:
canonically equal,
+ // so they are deduplicated into one output, with different `exprId`s.
Review Comment:
**Nit (P3):** The colon after "are" and the trailing "with different
`exprId`s" make this read as if the single deduplicated output had different
expression IDs. It is the two `count(1)` instances that have different IDs, and
they share one `aggResult` column. A reordering:
```suggestion
// Two separate `count(1)` instances with different `exprId`s, like two
`COUNT(*)` in a
// query. They are canonically equal, so they are deduplicated into one
output.
```
**Verification:**
- **Inspection:** The comment reads as one grammatical statement that the
two count(1) instances, with different expression IDs, are canonically equal
and share one output, and no code changes.
##########
sql/core/src/test/scala/org/apache/spark/sql/SubquerySuite.scala:
##########
@@ -1874,6 +1874,89 @@ class SubquerySuite extends SharedSparkSession
checkAnswer(df, Nil)
}
+ test("SPARK-61482: COUNT bug of a lower aggregate with an expression over
aggregate functions") {
+ // `ml` keeps only the rows of `l` with matching rows in `r`.
+ withTempView("ml") {
+ sql("CREATE TEMPORARY VIEW ml AS SELECT * FROM l WHERE a > 1")
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+ // The expression over COUNT(*) fails on zero tuples, but is not
evaluated on them
+ // while the query is optimized.
Review Comment:
**Nit (P3):** While the subquery is optimized, `PushFoldableIntoBranches`
pushes the cast and the division into `if(isnull(alwaysTrue), 0, aggResult)`.
`ConstantFolding` then evaluates the zero-tuple branch `10.0 / CAST(0 AS
DOUBLE)` as a conditional branch: it catches the DIVIDE_BY_ZERO and leaves the
branch for runtime. So the value is evaluated during optimization, and the
query still optimizes because that failure is tolerated. A rewording:
```suggestion
// The expression over COUNT(*) fails on zero tuples, but that value
is only used in a
// conditional branch, where constant folding tolerates the failure
while optimizing.
```
**Verification:**
- **Inspection:** The comment explains that optimization succeeds because
the failing zero-tuple value sits in a conditional branch, which constant
folding does not fail on, rather than because the value is never evaluated, and
no code changes.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuerySuite.scala:
##########
@@ -209,6 +210,117 @@ class DecorrelateInnerQuerySuite extends PlanTest {
check(innerPlan, outerPlan, correctAnswer, Seq(x <=> x))
}
+ test("SPARK-61482: COUNT bug handling evaluates only aggregate functions on
zero tuples") {
+ val outerPlan = testRelation2
+ // Two separate `count(1)` instances, as two `COUNT(*)` in a query are:
canonically equal,
+ // so they are deduplicated into one output, with different `exprId`s.
+ val cnt1 = count(Literal(1))
+ val cnt2 = count(Literal(1))
+ val maxB = max(b)
+ // Expressions over an aggregate function used twice and over one whose
result over zero
+ // tuples is NULL, single aggregate functions whose results over zero
tuples are not NULL
+ // and NULL, and a literal.
+ val d = Alias(cnt1 * 10L + cnt2, "d")()
+ val e = Alias(Coalesce(Seq(maxB, Literal(0))), "e")()
+ val c = Alias(count(Literal(1)), "c")()
+ val m = Alias(maxB, "m")()
+ val l = Alias(Literal(5), "l")()
+ val innerPlan =
+ Aggregate(Nil, Seq(d, e, c, m, l),
+ Filter(OuterReference(x) === a,
+ testRelation))
+ val (outputPlan, joinCond) =
+ DecorrelateInnerQuery(innerPlan, outerPlan.select(), handleCountBug =
true)
+
+ val cntRes = Alias(cnt1, "aggResult")()
+ val maxRes = Alias(maxB, "aggResult")()
+ val c2 = c.newInstance()
+ val l2 = l.newInstance()
+ val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
+ val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
+ def zeroTups(default: Expression, ref: NamedExpression): Expression =
+ If(IsNull(alwaysTrueRef), default, ref.toAttribute.withNullability(true))
+ val x2 = x.newInstance()
+ val cntValue = zeroTups(Literal(0L), cntRes)
+ val correctAnswer =
+ Project(Seq(
+ Alias(cntValue * 10L + cntValue, "d")(d.exprId),
+ Alias(Coalesce(Seq(maxRes.toAttribute.withNullability(true),
Literal(0))), "e")(
+ e.exprId),
+ Alias(zeroTups(Literal(0L), c2), "c")(c.exprId),
+ m.toAttribute.withNullability(true),
+ Alias(zeroTups(Literal(5), l2), "l")(l.exprId),
+ x2),
+ DomainJoin(Seq(x2),
+ Aggregate(Seq(a), Seq(cntRes, maxRes, c2, m, l2, a, alwaysTrue),
+ testRelation),
+ LeftOuter,
+ Some(x2 === a)))
+ check(outputPlan, joinCond, correctAnswer, Seq(x2 <=> x))
+ }
+
+ test("SPARK-61482: COUNT bug handling does not deduplicate non-deterministic
aggregates") {
+ val outerPlan = testRelation2
+ // A non-deterministic aggregate function used twice in an expression. The
two uses are
+ // canonically equal, but `PhysicalAggregation` does not deduplicate them,
so each must keep
+ // its own column and the expression must refer to both. (A
non-deterministic aggregate
+ // cannot occur in a query that passes analysis, so this only pins the
defensive behavior;
+ // the plan is inspected directly rather than compared, as it would not
pass `checkAnalysis`.)
Review Comment:
**Nit (P3):** Analysis rejects this fixture because `rand(1)` is a
non-deterministic argument (`ExprUtils.assertValidAggregation`). It does admit
a non-deterministic aggregate function whose arguments are deterministic, such
as a UDAF registered with `asNondeterministic()`: `CheckAnalysis` exempts
`Aggregate` from its non-determinism check, and only LATERAL subqueries reject
non-deterministic subqueries. Reading the code, with `nd` such a UDAF, `nd(r.d)
- nd(r.d) + COUNT(*)` reaches the per-use branch at
DecorrelateInnerQuery.scala:901 in a correlated scalar subquery over a lower
COUNT Aggregate, and also in an EXISTS or IN subquery. So the guard is not only
defensive, and describing it that way invites removing it. A rewording:
```suggestion
// its own column and the expression must refer to both. (A
non-deterministic UDAF with
// deterministic arguments passes analysis and reaches this guard. This
fixture's argument
// is not deterministic, so the plan would not pass `checkAnalysis` and
is inspected directly.)
```
**Verification:**
- **Inspection:** The comment of the test that keeps non-deterministic
aggregates per use states that only its own fixture fails analysis and that a
non-deterministic aggregate function with deterministic arguments reaches the
guard, and no code changes.
--
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]