sarutak commented on code in PR #60296:
URL: https://github.com/apache/spark/pull/60296#discussion_r4570113218
##########
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:
Thank you, I reproduced the two averages on 4.3.0 with your query
(`3.0023997515803305E15` and `3.0023997515803315E15`, with the same `SUM`).
ab03df9cb5b accepts `Average` only for decimal and ANSI interval inputs, and
`PullupCorrelatedPredicatesSuite` checks that an outer input with an `AVG` of
an `INT` keeps the previous plan. The description now says `SUM` of integers or
decimals, and `AVG` of decimals.
##########
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:
Agreed, thank you. ab03df9cb5b follows the cases of `LimitPushDown`
(`limitMayBePushedIn`): through a `UNION ALL`, an `OFFSET` and a `Project` over
a join, into an outer join with a condition and a join without one, and, only
for a `LIMIT 1`, below a group-only aggregate, which a `DISTINCT`, `INTERSECT`,
`EXCEPT` or `Deduplicate` becomes. So a `LIMIT 21` over a grouped outer input
or over an inner join with a condition gets the fix, and `show()` and
`collect()` agree there; `SubquerySuite` checks both results, and
`PullupCorrelatedPredicatesSuite` the routing, also for a `LIMIT 1` over an
aggregate that is not group-only. An outer join with a condition under a
`LIMIT`, such as `show()` of a `LEFT JOIN`, still keeps the previous plan,
since `LimitPushDown` pushes the limit into its outer input. The scaladoc, the
migration guide and the description say so now.
##########
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:
Thank you. ab03df9cb5b accepts a `DomainJoin` in a subquery of an operator
in the outer input, and keeps rejecting one directly in the outer input, as you
suggested; it accepts a `LIMIT` over rows of constants, such as the `Limit(1)`
that `RewriteNonCorrelatedExists` adds for an uncorrelated `EXISTS`, and a
`LateralJoin` whose subquery passes the check. `SubquerySuite` checks that your
query, an outer input with an uncorrelated `EXISTS` and one with a `LATERAL`
join now return 1 for a `k` without rows in `b`.
##########
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:
`orderIrrelevant` now says why it is stricter than
`isOrderIrrelevantAggFunction`: it needs the same value when computed again in
another order, so it rejects floating-point sums, `AVG` of anything but
decimals and ANSI intervals, and `CentralMomentAgg`. I would like to fold both
into the property of [16] in that follow-up, so that each function states it
once.
--
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]