dongjoon-hyun commented on code in PR #60296:
URL: https://github.com/apache/spark/pull/60296#discussion_r4569086751
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,7 +567,124 @@ object PullupCorrelatedPredicates extends
Rule[LogicalPlan] with PredicateHelper
nonEquivalentGroupbyCols(query, aggNode.get).isEmpty
}
- private def rewriteSubQueries(plan: LogicalPlan): LogicalPlan = {
+ // Whether some aggregate function of `a` has a default result on empty
input, such as COUNT.
+ private def hasDefaultResult(a: Aggregate): Boolean =
+ a.aggregateExpressions.exists(_.exists {
+ case ae: AggregateExpression =>
ae.aggregateFunction.defaultResult.isDefined
+ case _ => false
+ })
+
+ /**
+ * Returns true if the Aggregate without grouping expressions `agg` returns
the same result
+ * over the one row that the Aggregate without grouping expressions below it
returns on empty
+ * input as over no rows, so that constructLeftJoins handles its count bug
correctly even
+ * though decorrelation loses that row, with fewer joins than
DecorrelateInnerQuery. E.g.
+ * SUM(s) and COLLECT_LIST(s) over s = MAX(b.v) return NULL and [] over
both. The check is
+ * conservative: it accepts only a short list of functions of `agg` directly
over outputs of
+ * lower aggregate functions, with only Projects between, and leaves other
shapes that have
+ * this property, such as STDDEV_SAMP(s), to DecorrelateInnerQuery. It never
accepts a lower
+ * Aggregate with a function with a `defaultResult`, such as COUNT, which
DecorrelateInnerQuery
+ * handled before SPARK-60501. Like the rest of the count bug handling, this
relies on
+ * `defaultResult` matching the result on empty input.
+ */
+ private def sameResultOverEmptyLowerAggregate(agg: Aggregate): Boolean = {
+ // The attributes of `plan` that the count bug handling takes as NULL when
the lower Aggregate
+ // gets empty input.
+ def nullOnEmptyInput(plan: LogicalPlan): Option[AttributeSet] = plan match
{
+ case Project(projectList, child) =>
+ nullOnEmptyInput(child).map { attrs =>
+ AttributeSet(projectList.collect {
+ case a: Attribute if attrs.contains(a) => a
+ case a @ Alias(c: Attribute, _) if attrs.contains(c) =>
a.toAttribute
+ })
+ }
+ case lower: Aggregate if lower.groupingExpressions.isEmpty &&
+ !lower.child.exists(_.isInstanceOf[Aggregate]) &&
!hasDefaultResult(lower) =>
+ Some(AttributeSet(lower.aggregateExpressions.collect {
+ case a @ Alias(_: AggregateExpression, _) => a.toAttribute
+ }))
+ case _ => None
+ }
+ val aggregates = agg.aggregateExpressions.flatMap(_.collect {
+ case ae: AggregateExpression => ae
+ })
+ agg.groupingExpressions.isEmpty &&
+ nullOnEmptyInput(agg.child).exists { attrs =>
+ aggregates.forall { ae =>
+ val sameResultOverNulls = ae.aggregateFunction match {
+ case _: Max | _: Min | _: Sum | _: Average | _: Count | _: First |
_: Last => true
+ // With RESPECT NULLS, they collect the NULLs.
+ case c: CollectList => c.ignoreNulls
+ case c: CollectSet => c.ignoreNulls
+ case _ => false
+ }
+ // A FILTER condition can fail on the row of NULLs, which
constructLeftJoins does not
+ // evaluate it on, so it is left to DecorrelateInnerQuery.
+ ae.filter.isEmpty && sameResultOverNulls &&
ae.aggregateFunction.children.forall {
+ case a: Attribute => attrs.contains(a)
+ case _ => false
+ }
+ }
+ }
+ }
+
+ /**
+ * Whether `input`, the outer input of an operator with a correlated
subquery, gives the same
+ * rows when the domain joins of [[DecorrelateInnerQuery]] compute it again.
The check is
+ * conservative: it accepts only operators known to keep the same rows,
deterministic
+ * expressions, aggregate functions whose result does not depend on the
order of the rows, and
+ * leaves other than a CTE that is not inlined (which may be a
non-deterministic one; a
+ * CTERelationRef does not tell) and a streaming source, for which the
domain joins fail. It
+ * also checks the plans of the subqueries in `input`. Anything else, e.g. a
LIMIT, a window
+ * function, a sample or a FIRST, keeps the previous handling.
+ */
+ private def repeatableInput(input: LogicalPlan): Boolean = !input.exists { p
=>
+ val known = p match {
+ case _: Project | _: Filter | _: Join | _: Union | _: Distinct | _:
Intersect | _: Except |
+ _: Sort | _: SubqueryAlias | _: RepartitionOperation => true
+ case a: Aggregate => !a.aggregateExpressions.exists(_.exists {
+ case ae: AggregateExpression => !orderIrrelevant(ae.aggregateFunction)
+ case _ => false
+ })
+ case _: CTERelationRef => false
+ case l: LeafNode => !l.isStreaming
+ case _ => false
Review Comment:
**[20] `repeatableInput` rejects what this rule and
`RewriteNonCorrelatedExists` make from inputs it would accept, so the fix
silently does not apply to them.**
`apply` rewrites the plan bottom-up, so when it reaches the operator with
this subquery, a correlated subquery in its outer input has already been
decorrelated, and L653 checks that new plan through `p.subqueries`.
`DecorrelateInnerQuery` puts a `DomainJoin` there for a non-equality predicate
under an aggregate or a set operation (DecorrelateInnerQuery.scala:614,
DecorrelateInnerQuery.scala:526), and L651 rejects it. E.g. in
```sql
SELECT o.k, (SELECT COUNT(*) FROM (SELECT MAX(b.v) FROM b WHERE b.k = o.k))
FROM (SELECT a.*, (SELECT MAX(c.x) FROM c WHERE c.k > a.k) mx FROM a) o
```
the subquery for `mx` becomes an `Aggregate` over `Filter(c.k > k',
DomainJoin([k'], c))` first, so the outer subquery keeps returning `0` for a
`k` without rows in `b`. The same happens with an uncorrelated `EXISTS` in or
above the outer input, which `RewriteNonCorrelatedExists` already turned into
`IsNotNull(ScalarSubquery(Limit(1, ...)))` in `FinishAnalysis`
(finishAnalysis.scala:76), and with a `LATERAL` join in the outer input. None
of them gives other rows when computed again, and the migration guide does not
name them.
A `DomainJoin` in a subquery of an operator in the outer input takes its
domain from that operator's input, which this check has already accepted, so it
could be accepted there. A `DomainJoin` directly in the input, as in a nested
subquery that `OptimizeSubqueries` optimizes before the domain joins of its
parent are rewritten, takes its domain from outside the plan this rule sees, so
it should stay rejected. Could the check accept the first kind, the `Limit(1)`
of an uncorrelated `EXISTS`, and a `LateralJoin` whose subquery passes the
check? Otherwise, could the guide name these inputs?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,7 +567,124 @@ object PullupCorrelatedPredicates extends
Rule[LogicalPlan] with PredicateHelper
nonEquivalentGroupbyCols(query, aggNode.get).isEmpty
}
- private def rewriteSubQueries(plan: LogicalPlan): LogicalPlan = {
+ // Whether some aggregate function of `a` has a default result on empty
input, such as COUNT.
+ private def hasDefaultResult(a: Aggregate): Boolean =
+ a.aggregateExpressions.exists(_.exists {
+ case ae: AggregateExpression =>
ae.aggregateFunction.defaultResult.isDefined
+ case _ => false
+ })
+
+ /**
+ * Returns true if the Aggregate without grouping expressions `agg` returns
the same result
+ * over the one row that the Aggregate without grouping expressions below it
returns on empty
+ * input as over no rows, so that constructLeftJoins handles its count bug
correctly even
+ * though decorrelation loses that row, with fewer joins than
DecorrelateInnerQuery. E.g.
+ * SUM(s) and COLLECT_LIST(s) over s = MAX(b.v) return NULL and [] over
both. The check is
+ * conservative: it accepts only a short list of functions of `agg` directly
over outputs of
+ * lower aggregate functions, with only Projects between, and leaves other
shapes that have
+ * this property, such as STDDEV_SAMP(s), to DecorrelateInnerQuery. It never
accepts a lower
+ * Aggregate with a function with a `defaultResult`, such as COUNT, which
DecorrelateInnerQuery
+ * handled before SPARK-60501. Like the rest of the count bug handling, this
relies on
+ * `defaultResult` matching the result on empty input.
+ */
+ private def sameResultOverEmptyLowerAggregate(agg: Aggregate): Boolean = {
+ // The attributes of `plan` that the count bug handling takes as NULL when
the lower Aggregate
+ // gets empty input.
+ def nullOnEmptyInput(plan: LogicalPlan): Option[AttributeSet] = plan match
{
+ case Project(projectList, child) =>
+ nullOnEmptyInput(child).map { attrs =>
+ AttributeSet(projectList.collect {
+ case a: Attribute if attrs.contains(a) => a
+ case a @ Alias(c: Attribute, _) if attrs.contains(c) =>
a.toAttribute
+ })
+ }
+ case lower: Aggregate if lower.groupingExpressions.isEmpty &&
+ !lower.child.exists(_.isInstanceOf[Aggregate]) &&
!hasDefaultResult(lower) =>
+ Some(AttributeSet(lower.aggregateExpressions.collect {
+ case a @ Alias(_: AggregateExpression, _) => a.toAttribute
+ }))
+ case _ => None
+ }
+ val aggregates = agg.aggregateExpressions.flatMap(_.collect {
+ case ae: AggregateExpression => ae
+ })
+ agg.groupingExpressions.isEmpty &&
+ nullOnEmptyInput(agg.child).exists { attrs =>
+ aggregates.forall { ae =>
+ val sameResultOverNulls = ae.aggregateFunction match {
+ case _: Max | _: Min | _: Sum | _: Average | _: Count | _: First |
_: Last => true
+ // With RESPECT NULLS, they collect the NULLs.
+ case c: CollectList => c.ignoreNulls
+ case c: CollectSet => c.ignoreNulls
+ case _ => false
+ }
+ // A FILTER condition can fail on the row of NULLs, which
constructLeftJoins does not
+ // evaluate it on, so it is left to DecorrelateInnerQuery.
+ ae.filter.isEmpty && sameResultOverNulls &&
ae.aggregateFunction.children.forall {
+ case a: Attribute => attrs.contains(a)
+ case _ => false
+ }
+ }
+ }
+ }
+
+ /**
+ * Whether `input`, the outer input of an operator with a correlated
subquery, gives the same
+ * rows when the domain joins of [[DecorrelateInnerQuery]] compute it again.
The check is
+ * conservative: it accepts only operators known to keep the same rows,
deterministic
+ * expressions, aggregate functions whose result does not depend on the
order of the rows, and
+ * leaves other than a CTE that is not inlined (which may be a
non-deterministic one; a
+ * CTERelationRef does not tell) and a streaming source, for which the
domain joins fail. It
+ * also checks the plans of the subqueries in `input`. Anything else, e.g. a
LIMIT, a window
+ * function, a sample or a FIRST, keeps the previous handling.
+ */
+ private def repeatableInput(input: LogicalPlan): Boolean = !input.exists { p
=>
+ val known = p match {
+ case _: Project | _: Filter | _: Join | _: Union | _: Distinct | _:
Intersect | _: Except |
+ _: Sort | _: SubqueryAlias | _: RepartitionOperation => true
+ case a: Aggregate => !a.aggregateExpressions.exists(_.exists {
+ case ae: AggregateExpression => !orderIrrelevant(ae.aggregateFunction)
+ case _ => false
+ })
+ case _: CTERelationRef => false
+ case l: LeafNode => !l.isStreaming
+ case _ => false
+ }
+ !known || !p.expressions.forall(_.deterministic) ||
!p.subqueries.forall(repeatableInput)
+ }
+
+ private def orderIrrelevant(f: AggregateFunction): Boolean = f match {
+ case _: Min | _: Max | _: Count | _: BitAndAgg | _: BitOrAgg | _:
BitXorAgg => true
+ case _: Sum | _: Average => !f.children.exists(c =>
+ c.dataType == FloatType || c.dataType == DoubleType)
+ case _ => false
+ }
+
+ /**
+ * Whether the operators above the operator with the correlated subquery
`exprId` in `root`,
+ * the plan this rule runs on (the whole query, or the plan of a subquery
when
+ * OptimizeSubqueries optimizes it), may put something into its outer input
that gives other
+ * rows when computed again, through the rules that run before
RewriteCorrelatedScalarSubquery
+ * builds the domain joins: PushDownPredicates can push a filter or join
condition there, and
+ * LimitPushDown a LIMIT, into the inputs of a join or, for a LIMIT 1, below
an aggregate. The
+ * check is conservative and looks at all of `root`.
+ */
+ private def mayMoveIntoOuterInput(root: LogicalPlan, exprId: ExprId):
Boolean =
+ root.exists {
+ case p @ (_: Filter | _: Join) =>
+ !p.expressions.forall(_.deterministic) ||
p.expressions.exists(_.exists {
+ case s: SubqueryExpression => s.exprId != exprId &&
!repeatableInput(s.plan)
+ case _ => false
+ })
+ case l @ (_: LocalLimit | _: GlobalLimit | _: Offset | _: Tail) =>
l.exists {
Review Comment:
**[19] This check turns the fix off for any `LIMIT` over any join or
aggregate, while `LimitPushDown` pushes much less, so `show()` and `collect()`
of the same DataFrame can disagree.**
Thank you for the reply on [11]. It says that a query with a join and a
`LIMIT`, such as one shown with `show()`, keeps the previous result. The check
is wider than that:
- `LimitPushDown` pushes a limit below an `Aggregate` only for a `LIMIT 1`
over a group-only one (Optimizer.scala:1026-1028), but L680 matches any
`LIMIT`, `OFFSET` or tail over any `Aggregate`, at any depth.
- `pushLocalLimitThroughJoin` pushes a limit into an outer join with a
condition, or into a join without one (Optimizer.scala:974-986). An inner join
with a condition keeps it above (`case _ => join`), but L680 matches it too.
So with `df = spark.sql("SELECT o.g, (SELECT COUNT(*) FROM (SELECT MAX(b.v)
FROM b WHERE b.k = o.g)) c FROM (SELECT g, SUM(x) s FROM t GROUP BY g) o")`,
for a `g` without rows in `b`, `df.collect()` returns `c = 1` but `df.show()`
returns `0`, since `show()` puts a `LIMIT 21` above the `Aggregate`. The same
goes for `head()`, `take()` or a SQL `LIMIT` over most grouped or joined
queries, and nothing in the plan or the result tells the user which one they
got. The migration guide names "a `LIMIT` in the outer input or above a join",
and the scaladoc at L669 "for a LIMIT 1, below an aggregate".
Could L679-683 follow what `LimitPushDown` does: an `Aggregate`, `Distinct`,
`Intersect`, `Except` or `Deduplicate` only under a `LIMIT 1`, and a join only
of a type that `pushLocalLimitThroughJoin` pushes into? A test with `LIMIT 21`
over a grouped outer input could pin it.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,7 +567,124 @@ object PullupCorrelatedPredicates extends
Rule[LogicalPlan] with PredicateHelper
nonEquivalentGroupbyCols(query, aggNode.get).isEmpty
}
- private def rewriteSubQueries(plan: LogicalPlan): LogicalPlan = {
+ // Whether some aggregate function of `a` has a default result on empty
input, such as COUNT.
+ private def hasDefaultResult(a: Aggregate): Boolean =
+ a.aggregateExpressions.exists(_.exists {
+ case ae: AggregateExpression =>
ae.aggregateFunction.defaultResult.isDefined
+ case _ => false
+ })
+
+ /**
+ * Returns true if the Aggregate without grouping expressions `agg` returns
the same result
+ * over the one row that the Aggregate without grouping expressions below it
returns on empty
+ * input as over no rows, so that constructLeftJoins handles its count bug
correctly even
+ * though decorrelation loses that row, with fewer joins than
DecorrelateInnerQuery. E.g.
+ * SUM(s) and COLLECT_LIST(s) over s = MAX(b.v) return NULL and [] over
both. The check is
+ * conservative: it accepts only a short list of functions of `agg` directly
over outputs of
+ * lower aggregate functions, with only Projects between, and leaves other
shapes that have
+ * this property, such as STDDEV_SAMP(s), to DecorrelateInnerQuery. It never
accepts a lower
+ * Aggregate with a function with a `defaultResult`, such as COUNT, which
DecorrelateInnerQuery
+ * handled before SPARK-60501. Like the rest of the count bug handling, this
relies on
+ * `defaultResult` matching the result on empty input.
+ */
+ private def sameResultOverEmptyLowerAggregate(agg: Aggregate): Boolean = {
+ // The attributes of `plan` that the count bug handling takes as NULL when
the lower Aggregate
+ // gets empty input.
+ def nullOnEmptyInput(plan: LogicalPlan): Option[AttributeSet] = plan match
{
+ case Project(projectList, child) =>
+ nullOnEmptyInput(child).map { attrs =>
+ AttributeSet(projectList.collect {
+ case a: Attribute if attrs.contains(a) => a
+ case a @ Alias(c: Attribute, _) if attrs.contains(c) =>
a.toAttribute
+ })
+ }
+ case lower: Aggregate if lower.groupingExpressions.isEmpty &&
+ !lower.child.exists(_.isInstanceOf[Aggregate]) &&
!hasDefaultResult(lower) =>
+ Some(AttributeSet(lower.aggregateExpressions.collect {
+ case a @ Alias(_: AggregateExpression, _) => a.toAttribute
+ }))
+ case _ => None
+ }
+ val aggregates = agg.aggregateExpressions.flatMap(_.collect {
+ case ae: AggregateExpression => ae
+ })
+ agg.groupingExpressions.isEmpty &&
+ nullOnEmptyInput(agg.child).exists { attrs =>
+ aggregates.forall { ae =>
+ val sameResultOverNulls = ae.aggregateFunction match {
+ case _: Max | _: Min | _: Sum | _: Average | _: Count | _: First |
_: Last => true
+ // With RESPECT NULLS, they collect the NULLs.
+ case c: CollectList => c.ignoreNulls
+ case c: CollectSet => c.ignoreNulls
+ case _ => false
+ }
+ // A FILTER condition can fail on the row of NULLs, which
constructLeftJoins does not
+ // evaluate it on, so it is left to DecorrelateInnerQuery.
+ ae.filter.isEmpty && sameResultOverNulls &&
ae.aggregateFunction.children.forall {
+ case a: Attribute => attrs.contains(a)
+ case _ => false
+ }
+ }
+ }
+ }
+
+ /**
+ * Whether `input`, the outer input of an operator with a correlated
subquery, gives the same
+ * rows when the domain joins of [[DecorrelateInnerQuery]] compute it again.
The check is
+ * conservative: it accepts only operators known to keep the same rows,
deterministic
+ * expressions, aggregate functions whose result does not depend on the
order of the rows, and
+ * leaves other than a CTE that is not inlined (which may be a
non-deterministic one; a
+ * CTERelationRef does not tell) and a streaming source, for which the
domain joins fail. It
+ * also checks the plans of the subqueries in `input`. Anything else, e.g. a
LIMIT, a window
+ * function, a sample or a FIRST, keeps the previous handling.
+ */
+ private def repeatableInput(input: LogicalPlan): Boolean = !input.exists { p
=>
+ val known = p match {
+ case _: Project | _: Filter | _: Join | _: Union | _: Distinct | _:
Intersect | _: Except |
+ _: Sort | _: SubqueryAlias | _: RepartitionOperation => true
+ case a: Aggregate => !a.aggregateExpressions.exists(_.exists {
+ case ae: AggregateExpression => !orderIrrelevant(ae.aggregateFunction)
+ case _ => false
+ })
+ case _: CTERelationRef => false
+ case l: LeafNode => !l.isStreaming
+ case _ => false
+ }
+ !known || !p.expressions.forall(_.deterministic) ||
!p.subqueries.forall(repeatableInput)
+ }
+
+ private def orderIrrelevant(f: AggregateFunction): Boolean = f match {
Review Comment:
**[21] Nit: `orderIrrelevant` repeats `isOrderIrrelevantAggFunction` of
`EliminateSorts` (Optimizer.scala:2552-2556).**
Both accept `Min`, `Max`, `Count`, the bitwise aggregates, and `Sum` and
`Average` of anything but `FLOAT` and `DOUBLE`. They already differ, since
`EliminateSorts` also accepts `CentralMomentAgg`, and with [18] they would
differ on `Average` too. This rule needs the stricter property, that computing
the plan again gives the same values, not only that a `Sort` below the
aggregate does not matter. Could the two share one helper that takes the
strictness as a parameter, or could this one say why it differs? If the
property of [16] goes on `AggregateFunction`, this one could go there as well.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,7 +567,124 @@ object PullupCorrelatedPredicates extends
Rule[LogicalPlan] with PredicateHelper
nonEquivalentGroupbyCols(query, aggNode.get).isEmpty
}
- private def rewriteSubQueries(plan: LogicalPlan): LogicalPlan = {
+ // Whether some aggregate function of `a` has a default result on empty
input, such as COUNT.
+ private def hasDefaultResult(a: Aggregate): Boolean =
+ a.aggregateExpressions.exists(_.exists {
+ case ae: AggregateExpression =>
ae.aggregateFunction.defaultResult.isDefined
+ case _ => false
+ })
+
+ /**
+ * Returns true if the Aggregate without grouping expressions `agg` returns
the same result
+ * over the one row that the Aggregate without grouping expressions below it
returns on empty
+ * input as over no rows, so that constructLeftJoins handles its count bug
correctly even
+ * though decorrelation loses that row, with fewer joins than
DecorrelateInnerQuery. E.g.
+ * SUM(s) and COLLECT_LIST(s) over s = MAX(b.v) return NULL and [] over
both. The check is
+ * conservative: it accepts only a short list of functions of `agg` directly
over outputs of
+ * lower aggregate functions, with only Projects between, and leaves other
shapes that have
+ * this property, such as STDDEV_SAMP(s), to DecorrelateInnerQuery. It never
accepts a lower
+ * Aggregate with a function with a `defaultResult`, such as COUNT, which
DecorrelateInnerQuery
+ * handled before SPARK-60501. Like the rest of the count bug handling, this
relies on
+ * `defaultResult` matching the result on empty input.
+ */
+ private def sameResultOverEmptyLowerAggregate(agg: Aggregate): Boolean = {
+ // The attributes of `plan` that the count bug handling takes as NULL when
the lower Aggregate
+ // gets empty input.
+ def nullOnEmptyInput(plan: LogicalPlan): Option[AttributeSet] = plan match
{
+ case Project(projectList, child) =>
+ nullOnEmptyInput(child).map { attrs =>
+ AttributeSet(projectList.collect {
+ case a: Attribute if attrs.contains(a) => a
+ case a @ Alias(c: Attribute, _) if attrs.contains(c) =>
a.toAttribute
+ })
+ }
+ case lower: Aggregate if lower.groupingExpressions.isEmpty &&
+ !lower.child.exists(_.isInstanceOf[Aggregate]) &&
!hasDefaultResult(lower) =>
+ Some(AttributeSet(lower.aggregateExpressions.collect {
+ case a @ Alias(_: AggregateExpression, _) => a.toAttribute
+ }))
+ case _ => None
+ }
+ val aggregates = agg.aggregateExpressions.flatMap(_.collect {
+ case ae: AggregateExpression => ae
+ })
+ agg.groupingExpressions.isEmpty &&
+ nullOnEmptyInput(agg.child).exists { attrs =>
+ aggregates.forall { ae =>
+ val sameResultOverNulls = ae.aggregateFunction match {
+ case _: Max | _: Min | _: Sum | _: Average | _: Count | _: First |
_: Last => true
+ // With RESPECT NULLS, they collect the NULLs.
+ case c: CollectList => c.ignoreNulls
+ case c: CollectSet => c.ignoreNulls
+ case _ => false
+ }
+ // A FILTER condition can fail on the row of NULLs, which
constructLeftJoins does not
+ // evaluate it on, so it is left to DecorrelateInnerQuery.
+ ae.filter.isEmpty && sameResultOverNulls &&
ae.aggregateFunction.children.forall {
+ case a: Attribute => attrs.contains(a)
+ case _ => false
+ }
+ }
+ }
+ }
+
+ /**
+ * Whether `input`, the outer input of an operator with a correlated
subquery, gives the same
+ * rows when the domain joins of [[DecorrelateInnerQuery]] compute it again.
The check is
+ * conservative: it accepts only operators known to keep the same rows,
deterministic
+ * expressions, aggregate functions whose result does not depend on the
order of the rows, and
+ * leaves other than a CTE that is not inlined (which may be a
non-deterministic one; a
+ * CTERelationRef does not tell) and a streaming source, for which the
domain joins fail. It
+ * also checks the plans of the subqueries in `input`. Anything else, e.g. a
LIMIT, a window
+ * function, a sample or a FIRST, keeps the previous handling.
+ */
+ private def repeatableInput(input: LogicalPlan): Boolean = !input.exists { p
=>
+ val known = p match {
+ case _: Project | _: Filter | _: Join | _: Union | _: Distinct | _:
Intersect | _: Except |
+ _: Sort | _: SubqueryAlias | _: RepartitionOperation => true
+ case a: Aggregate => !a.aggregateExpressions.exists(_.exists {
+ case ae: AggregateExpression => !orderIrrelevant(ae.aggregateFunction)
+ case _ => false
+ })
+ case _: CTERelationRef => false
+ case l: LeafNode => !l.isStreaming
+ case _ => false
+ }
+ !known || !p.expressions.forall(_.deterministic) ||
!p.subqueries.forall(repeatableInput)
+ }
+
+ private def orderIrrelevant(f: AggregateFunction): Boolean = f match {
+ case _: Min | _: Max | _: Count | _: BitAndAgg | _: BitOrAgg | _:
BitXorAgg => true
+ case _: Sum | _: Average => !f.children.exists(c =>
Review Comment:
**[18] `orderIrrelevant` accepts `AVG` of integers, but `Average` sums them
as `DOUBLE`, so the domain joins can compute another average than the main
copy.**
Thank you for turning the check around for [10] and [11].
`Average.sumDataType` is `DOUBLE` for every input other than a decimal or an
ANSI interval (Average.scala:80), and each update casts the value to it before
adding (Average.scala:133). Floating-point addition is not associative, so the
result depends on the order in which the values and partial sums are added,
which is why this check rejects a `SUM` of `DOUBLE`s. On Spark 4.3.0, the same
three `BIGINT` values give two averages, depending only on their order, while
`SUM` agrees:
```sql
SELECT avg(x), sum(x) FROM (SELECT /*+ COALESCE(1) */ * FROM VALUES
(1, 9007199254740992L), (2, 1L), (3, 1L) t(i, x) ORDER BY i);
-- 3.0023997515803305E15 9007199254740994
-- With 9007199254740992L as the last row instead:
-- 3.0023997515803315E15 9007199254740994
```
So an outer input such as `(SELECT g, AVG(ts) m FROM e GROUP BY g) o` passes
`repeatableInput`, and the subquery gets the left outer domain join. When the
subquery correlates on `m`, e.g. `(SELECT COUNT(*) FROM (SELECT MAX(b.v) FROM b
WHERE b.v = o.m))`, or `o` keeps its groups with a `HAVING` on `AVG(ts)`, the
domain computes `AVG` again in another stage, which adds the partial sums in
its own shuffle fetch order. An outer row whose average differs in the last
bit, or passes the `HAVING` in only one copy, then finds no domain row and gets
`NULL` instead of `1`. On `master`, this shape has no domain join, so a matched
row gets `1`. It needs `BIGINT` values whose sum exceeds 2^53, such as epoch
microseconds or large ids. Near overflow, a `SUM` of `BIGINT`s in ANSI mode and
a `SUM` or `AVG` of decimals can also overflow in one order and not in another,
but that gives an error or `NULL` rather than a lost match.
Could `orderIrrelevant` accept `Average` only for decimal and ANSI interval
inputs, and could `PullupCorrelatedPredicatesSuite` check an outer input with
an `AVG` of an `INT`? The PR description, which lists `SUM` and `AVG` of
integers, would change with it.
--
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]