sarutak commented on code in PR #60296:
URL: https://github.com/apache/spark/pull/60296#discussion_r4568454490
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -596,32 +658,55 @@ object PullupCorrelatedPredicates extends
Rule[LogicalPlan] with PredicateHelper
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
+ // unchanged or inner joins it with the domain, and mayHaveCountBugAgg
uses the same check
+ // (SubExprUtils.hasOuterReferences).
+ // An Aggregate with an aggregate function with a default result, such
as COUNT, also
+ // qualifies, correlated or not, as before SPARK-60501; with
+ // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR, only
such an Aggregate
+ // does. So does it where the domain joins of DecorrelateInnerQuery,
which compute the
+ // outer query again, are known not to work, so as not to make such
queries worse than
+ // before. The check is conservative: e.g. the domain joins fail for a
streaming query
+ // and for outer references that are not orderable, and can find other
rows the second
+ // time for a non-deterministic input, or for a CTE that is not
inlined, which may be a
+ // non-deterministic one (a CTERelationRef does not tell).
+ val domainJoinsWork = !plan.isStreaming &&
+ plan.children.forall(c => c.deterministic &&
!c.containsPattern(CTE)) &&
Review Comment:
Thank you, this is a regression, and I reproduced it. With `o =
range(1000)`, `b(k, v) = range(1000)` and `spark60501_rk` returning a random
value in `[0, 1000)`, `SELECT c, COUNT(*) FROM (SELECT * FROM (SELECT o.k,
(SELECT COUNT(*) FROM (SELECT MAX(b.v) FROM b WHERE b.k = o.k)) c FROM o) WHERE
spark60501_rk(k) > 500) GROUP BY c` returned `(0, 119), (1, 138), (NULL, 234)`
on 23fd3dc and `(1, 491)` on master. On master, the same query with `SUM(c)`
over `COUNT(*) c` returns `NULL` for about 370 rows; this PR does not change
that path.
Following [11] and [15], I went through the rules that run between
`PullupCorrelatedPredicates` and `RewriteCorrelatedScalarSubquery`, and found
more of the same kind: `LimitPushDown` also pushes a `LIMIT` above a join into
its inputs, and a `LIMIT 1` below a `DISTINCT` or `INTERSECT`;
`ReplaceDeduplicateWithAggregate` turns `dropDuplicates` into `FIRST`; and
`FIRST`, `ANY_VALUE`, `COLLECT_LIST` or a `SUM` of `DOUBLE`s in the outer input
can give other values when computed again, though they are deterministic as
expressions. A list of what to reject would stay open, so e84359e8301 turns the
check around (`repeatableInput` and `mayMoveIntoOuterInput`): the subquery gets
the new handling only if its outer input is built from operators known to give
the same rows again (projections, filters, joins, set operations, sorts,
repartitions, and aggregates with `MIN`, `MAX`, `COUNT`, bitwise aggregates, or
`SUM` and `AVG` of integers or decimals), with deterministic expressions and
such sub
queries, over relations other than a CTE that is not inlined or a stream; and
if no operator above it in the plan the rule runs on can be moved into it by
those rules: a filter or join condition that is non-deterministic or has a
subquery that fails the same check, or a `LIMIT`, `OFFSET` or tail over a join,
an aggregate, a `DISTINCT`, a set operation or a `Deduplicate`. Anything else
keeps the previous plan. For this query, the subquery keeps the previous plan
and returns 1 for every row. `SubquerySuite` has a variant of this query
(`SELECT DISTINCT c`), and `PullupCorrelatedPredicatesSuite` checks the routing
for each of the shapes above.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -596,32 +658,55 @@ object PullupCorrelatedPredicates extends
Rule[LogicalPlan] with PredicateHelper
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
+ // unchanged or inner joins it with the domain, and mayHaveCountBugAgg
uses the same check
+ // (SubExprUtils.hasOuterReferences).
+ // An Aggregate with an aggregate function with a default result, such
as COUNT, also
+ // qualifies, correlated or not, as before SPARK-60501; with
+ // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR, only
such an Aggregate
+ // does. So does it where the domain joins of DecorrelateInnerQuery,
which compute the
+ // outer query again, are known not to work, so as not to make such
queries worse than
+ // before. The check is conservative: e.g. the domain joins fail for a
streaming query
+ // and for outer references that are not orderable, and can find other
rows the second
+ // time for a non-deterministic input, or for a CTE that is not
inlined, which may be a
Review Comment:
I could not reproduce it locally: with `a = SELECT id % 1000 k, id x FROM
range(0, 200000, 1, 64)` and `spark.sql.exchange.reuse=false`, the query
returned 1 for every row in three runs, on master and on 23fd3dc. The reasoning
holds, though, and with the check in the reply to [10], a `LIMIT`, `OFFSET`,
tail, window function or sample in the outer input, also inside a subquery
there, keeps the previous plan. That covers `ORDER BY` a non-unique key with
`LIMIT`, and a filter on `row_number()`, through its `Window`. On 23fd3dc, a
`LIMIT` above a join was also pushed into the outer input by `LimitPushDown`
(the optimized plan had five `LocalLimit`s, against three with the legacy
conf); now it keeps the previous plan too. This is conservative, e.g. a query
with a join and a `LIMIT`, such as one shown with `show()`, keeps the previous
result, while a `LIMIT` over a query without a join or an aggregate, or over a
`UNION ALL`, still gets the fix. `SubquerySuite` checks that a query over `
(SELECT * FROM o LIMIT 100)` and a `LEFT JOIN` with `LIMIT 100` get as many
joins as with the legacy conf.
##########
sql/core/src/test/resources/sql-tests/inputs/subquery/scalar-subquery/nested-scalar-subquery-count-bug.sql:
##########
@@ -28,6 +28,269 @@ select (
on l.cnt = r.cnt
) a from t1 order by a desc;
+-- test for count bug in nested aggregates whose lower aggregate has no
function with a default
+-- result, such as COUNT: the lower aggregate returns one row even when no row
of t2 matches
+select a1, ( select count(*) from (select max(b2) m from t2 where t1.a1 =
t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select count(*) from (select min(b2) m from t2 where t1.a1 =
t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select count(*) from (select sum(b2) m from t2 where t1.a1 =
t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select count(*) from (select avg(b2) m from t2 where t1.a1 =
t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select sum(s) from (select coalesce(sum(b2), 10) s from t2 where
t1.a1 = t2.b1) ) a
+from t1 order by a1;
+
+-- with a filter between the aggregates
+select a1, ( select count(*) from (select max(b2) m from t2 where t1.a1 =
t2.b1)
+ where m is null ) a
+from t1 order by a1;
+
+-- with a literal next to the lower aggregate function
+select a1, ( select sum(s) from (select 10 s, max(b2) m from t2 where t1.a1 =
t2.b1) ) a
+from t1 order by a1;
+
+-- with a non-equality correlated predicate
+select a1, ( select sum(s) from (select coalesce(sum(b2), 10) s from t2 where
t2.b1 < t1.a1) ) a
+from t1 order by a1;
+
+-- with three levels of aggregates
+select a1, ( select count(*) from (select max(m) m2 from (select max(b2) m
from t2
+ where t1.a1 = t2.b1)) ) a
+from t1 order by a1;
+
+-- with a grouped aggregate between the aggregates
+select a1, ( select count(*) from (select m from (select max(b2) m from t2
+ where t1.a1 = t2.b1) group by m) ) a
+from t1 order by a1;
+
+-- with a grouped top aggregate
+select a1, ( select count(*) from (select max(b2) m from t2 where t1.a1 =
t2.b1) group by m ) a
+from t1 order by a1;
+
+-- with correlated predicates in both aggregates
+select a1, ( select sum(s) from (select coalesce(sum(b2), 10) s from t2 where
t1.a1 = t2.b1)
+ where t1.a2 > 1 ) a
+from t1 order by a1;
+
+-- with an outer row whose correlated column is null
+select a1, ( select count(*) from (select max(b2) m from t2 where t.a1 =
t2.b1) ) a
+from values (0), (1), (null) as t(a1) order by a1;
+
+-- with a join, a union, an intersect, a limit or a window function over the
lower aggregates
+select a1, ( select count(*) from (select max(b2) m from t2 where t1.a1 =
t2.b1) l,
+ (select min(b2) n from t2 where t1.a1 = t2.b1) r ) a
+from t1 order by a1;
+
+select a1, ( select count(*) from (select max(b2) m from t2 where t1.a1 = t2.b1
+ union all select min(b2) from t2 where t1.a1 = t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select count(*) from (select max(b2) m from t2 where t1.a1 = t2.b1
+ intersect select max(b2) from t2 where t1.a1 = t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select count(*) from (select max(b2) m from t2 where t1.a1 =
t2.b1 limit 1) ) a
+from t1 order by a1;
+
+select a1, ( select count(*) from (select m, rank() over (order by m) r from
+ (select max(b2) m from t2 where t1.a1 = t2.b1)) ) a
+from t1 order by a1;
+
+-- with an uncorrelated lower aggregate and a correlated predicate above it
+select a1, ( select count(*) from (select max(b2) m from t2) where m > t1.a2 +
1 ) a
+from t1 order by a1;
+
+select a1, ( select count(*) from (select count(*) c from t2) where c > t1.a2
) a
+from t1 order by a1;
+
+-- with top aggregates over the one row of a lower aggregate that returns NULL
on empty input:
+-- functions that return over a NULL row what they return over no rows, such
as SUM and
+-- COLLECT_LIST, and others, such as COUNT(*), with FILTER, DISTINCT, decimal
and bigint inputs
+select a1, ( select collect_list(m) from (select max(b2) m from t2 where t1.a1
= t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select sum(m) + 1 from (select max(b2) m from t2 where t1.a1 =
t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select stddev_samp(m) from (select max(b2) m from t2 where t1.a1
= t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select struct(sum(m), count(m), max(m), min(m), avg(m),
collect_set(m))
+ from (select max(b2) m from t2 where t1.a1 = t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select collect_list(m) respect nulls from (select max(b2) m from
t2
+ where t1.a1 = t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select collect_set(m) respect nulls from (select max(b2) m from t2
+ where t1.a1 = t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select first(m) respect nulls from (select max(b2) m from t2
+ where t1.a1 = t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select struct(count(*), collect_list(m)) from (select max(b2) m
from t2
+ where t1.a1 = t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select struct(count(*) filter (where m is null), count(*) filter
(where m > 2))
+ from (select max(b2) m from t2 where t1.a1 = t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select struct(sum(m) filter (where m > 2), sum(m) filter (where m
> 3),
+ count(m) filter (where m is null), collect_list(m) filter (where m is null))
+ from (select max(b2) m from t2 where t1.a1 = t2.b1) ) a
+from t1 order by a1;
+
+-- a FILTER condition that fails on the NULL row is not evaluated for it,
since the count bug
Review Comment:
Agreed. e84359e8301 sends a top aggregate with a `FILTER` to
`DecorrelateInnerQuery`, like the functions outside the list, so this query now
fails with `DIVIDE_BY_ZERO` in ANSI mode, as the `LATERAL` and uncorrelated
forms do. The golden file and the comment above the query are updated. This
also replaces the check for a correlated subquery in a `FILTER`.
##########
sql/core/src/test/scala/org/apache/spark/sql/SubquerySuite.scala:
##########
@@ -3401,4 +3403,134 @@ class SubquerySuite extends SharedSparkSession
Row(1, 2))
}
}
+
+ test("SPARK-60501: count bug of correlated scalar subqueries over an emptied
local relation") {
+ withTempView("t1", "t2") {
+ sql("CREATE TEMP VIEW t1(a1, a2) AS VALUES (1, 1), (2, 2)")
+ sql("CREATE TEMP VIEW t2(b1, b2) AS VALUES (1, 1), (2, 2)")
+ // ConvertToLocalRelation, which the test session excludes, empties the
filtered relation.
+ withSQLConf(SQLConf.OPTIMIZER_EXCLUDED_RULES.key -> "") {
+ // Projections over a COUNT whose filtered input becomes empty.
+ checkAnswer(
+ sql("SELECT a1, (SELECT s * s FROM (SELECT c + 1 AS s FROM (SELECT
COUNT(*) c FROM t2 " +
+ "WHERE t2.b1 = t1.a1 AND t2.b2 > 10))) FROM t1"),
+ Seq(Row(1, 1), Row(2, 1)))
+ // Results of COUNT(*) over a lower MAX, which goes to decorrelation,
and of top aggregates
+ // over a lower MAX that stay in constructLeftJoins (the routing is
checked in
+ // PullupCorrelatedPredicatesSuite).
+ checkAnswer(
+ sql("SELECT a1, (SELECT COUNT(*) FROM (SELECT MAX(b2) m FROM t2 " +
+ "WHERE t2.b1 = t1.a1 AND t2.b2 > 10)) FROM t1"),
+ Seq(Row(1, 1), Row(2, 1)))
+ checkAnswer(
+ sql("SELECT a1, (SELECT struct(SUM(m), COUNT(m), COLLECT_LIST(m))
FROM " +
+ "(SELECT MAX(b2) m FROM t2 WHERE t2.b1 = t1.a1 AND t2.b2 > 10))
FROM t1"),
+ Seq(Row(1, Row(null, 0, Seq())), Row(2, Row(null, 0, Seq()))))
+ // An uncorrelated lower COUNT returns the correct result, as before
(the routing is
+ // checked in PullupCorrelatedPredicatesSuite).
+ checkAnswer(
+ sql("SELECT a1, (SELECT COUNT(*) FROM (SELECT COUNT(*) c FROM t2
WHERE t2.b2 > 10) " +
+ "WHERE c < t1.a2) FROM t1"),
+ Seq(Row(1, 1), Row(2, 1)))
+ }
+ }
+ }
+
+ test("SPARK-60501: a non-deterministic input of the operator with the
subquery keeps the " +
Review Comment:
Added, see the replies to [10] and [11].
##########
docs/sql-migration-guide.md:
##########
@@ -100,6 +100,7 @@ license: |
- Since Spark 4.4, a CHECK constraint that `ALTER TABLE ... ADD CONSTRAINT`
adds to a Data Source V2 table, and whose condition reads the current time,
date, catalog, user and the like, such as `ts <= current_timestamp()` or `db =
current_database()`, is checked against their values at the time of each write.
Previously, it was checked against their values at the time of the `ALTER
TABLE`, unless a write could not read back a predicate for its condition, such
as one with a lambda function or one that passes a column to `datediff`, `year`
or `upper` (SPARK-60032). Such a constraint is stored without a predicate, so
each write parses and analyzes its SQL text under the session of the write, as
it does for a constraint without a predicate that `CREATE TABLE` adds. A
setting of the write such as `spark.sql.ansi.enforceReservedKeywords`, which
reserves `TIME`, or `spark.sql.ansi.doubleQuotedIdentifiers` can then make it
fail to parse the text or read it differently. A row-level operation
that copies unchanged rows, such as a `DELETE` or `UPDATE` on a copy-on-write
table, fails with `CHECK_CONSTRAINT_VIOLATION` on a copied row that no longer
satisfies the condition. For example, `ts >= current_timestamp() - INTERVAL 30
DAYS` now fails such a `DELETE` once a copied row is older than 30 days. A
condition that Spark detects a write could resolve differently is stored as
before, so a write accepts and rejects the same rows for it as before. Examples
are conditions that also read a variable, a `CHAR` column, a name with more
than one part such as a column qualified by the table name, or a constant that
depends on the session time zone, such as `'2024-01-01 00:00:00'` cast to a
timestamp. So are conditions with a name such as `current_date` or `user`
without parentheses, which a write can read as a column name, and conditions
whose text the parser settings of the `ALTER TABLE`, such as
`spark.sql.ansi.doubleQuotedIdentifiers` or
`spark.sql.parser.escapedStringLiterals`, r
ead differently from their default values. ANSI mode,
`spark.sql.timestampType` and the session time zone are taken from the session
for this comparison, as for a generation expression. A condition that reads the
current date or time only through a typed literal such as `DATE 'today'` is
also stored as before. An existing constraint keeps its stored predicate until
it is dropped and added again. `Check.predicate()` is null for a constraint
stored without a predicate, so a connector that validates or enforces it itself
has to evaluate `Check.predicateSql()`. To restore the previous behavior, set
`spark.sql.legacy.freezeCurrentValuesInCheckConstraint` to `true` before adding
the constraint. A constraint added without it is not changed.
- Since Spark 4.4, a function created by `CREATE FUNCTION ... AS 'class'`
whose class implements
`org.apache.spark.sql.connector.catalog.functions.UnboundFunction` and extends
either a Hive UDF class (such as `UDF` or `GenericUDF`) or
`org.apache.spark.sql.expressions.UserDefinedAggregateFunction` runs as a
DataSource V2 function instead of a Hive UDF or Spark UDAF, including functions
created in earlier versions. Its result type, argument coercion, and null
handling are defined by the V2 implementation selected by
`UnboundFunction.bind`. Hive's `@UDFType` and Spark UDAF's `deterministic`
property do not control the V2 path. For scalar functions, determinism uses
`BoundFunction.isDeterministic()` (default `true`) and the arguments'
determinism. A call with constant arguments can therefore become eligible for
constant folding during query planning instead of being evaluated per row.
- Since Spark 4.4, `next_day` and `last_day` fail with `DATETIME_OVERFLOW`
when the result is later than the maximum `DATE`, `+5881580-07-11`, and `trunc`
fails with it when the result is earlier than the minimum `DATE`,
`-5877641-06-23`, regardless of `spark.sql.ansi.enabled`. Previously, these
functions silently returned a wrong date, in most cases one at the other end of
the `DATE` range; for example, `last_day(DATE'+5881580-07-11')` returned
`-5877641-07-12` and `trunc(DATE'-5877641-06-23', 'MONTH')` returned
`+5881580-06-20`, while `trunc` to `QUARTER` failed with `ARITHMETIC_OVERFLOW`.
`next_day` and `trunc` to `WEEK` also returned a wrong date for the first days
of the `DATE` range; for example, `next_day(DATE'-5877641-06-23', 'MO')` and
`trunc(DATE'-5877641-07-01', 'WEEK')` returned `-5877641-06-25`, a Thursday,
and now return `-5877641-06-29`.
+- Since Spark 4.4, a correlated scalar subquery whose top aggregate is over a
correlated aggregate without `GROUP BY` returns the correct result for an outer
row without matching rows. For example, `SELECT COUNT(*) FROM (SELECT MAX(b.v)
FROM b WHERE b.k = a.k)` returned `0` instead of `1` for such a row
(SPARK-60501, SPARK-60502). Data derived from affected query results may need
to be recomputed. An expression over the result of the lower aggregate,
including a Python UDF, can now also be evaluated for such a row, so it can
fail there, e.g. `10 / COALESCE(MAX(b.v), 0)` in ANSI mode, even when another
condition of the query removes that row. Such queries can also be planned with
more left outer joins than before. The fix is conservative: where the
decorrelation it relies on does not apply, such as in a streaming query, the
previous result is kept. To restore the previous behavior, set
`spark.sql.legacy.scalarSubqueryNestedAggregateCountBugBehavior` to `true`.
Review Comment:
Updated. The guide and the description now name a streaming query, a query
with a non-deterministic expression or a CTE that is not inlined, a subquery
over an outer input with a `LIMIT`, `OFFSET` or window function, and outer
references of a type that is not orderable, such as a map.
--
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]