sarutak commented on code in PR #60296:
URL: https://github.com/apache/spark/pull/60296#discussion_r4573386161
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -670,25 +852,26 @@ object PullupCorrelatedPredicates extends
Rule[LogicalPlan] with PredicateHelper
/**
* Pull up the correlated predicates and rewrite all subqueries in an
operator tree..
*/
- def apply(plan: LogicalPlan): LogicalPlan = plan.transformUpWithPruning(
- _.containsPattern(PLAN_EXPRESSION)) {
- case j: LateralJoin =>
- val newPlan = rewriteSubQueries(j)
- // Since a lateral join's output depends on its left child output and
its lateral subquery's
- // plan output, we need to trim the domain attributes added to the
subquery's plan output
- // to preserve the original output of the join.
- if (!j.sameOutput(newPlan)) {
- Project(j.output, newPlan)
- } else {
- newPlan
- }
- case j: Join if
conf.getConf(DECORRELATE_PREDICATE_SUBQUERIES_IN_JOIN_CONDITION) =>
- rewriteSubQueries(j)
- // Only a few unary nodes (Project/Filter/Aggregate) can contain
subqueries.
- case q: UnaryNode =>
- rewriteSubQueries(q)
- case s: SupportsSubquery =>
- rewriteSubQueries(s)
+ def apply(plan: LogicalPlan): LogicalPlan = {
Review Comment:
Done, `apply` has its old layout again with `, plan` in the four calls.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,7 +567,168 @@ 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 (other than
+ * over rows of constants), a window function, a sample or a FIRST, keeps
the previous
+ * handling.
+ */
+ private def repeatableInput(input: LogicalPlan, inSubquery: Boolean =
false): Boolean =
+ !input.exists { p =>
+ val known = p match {
+ case _: Project | _: Filter | _: Join | _: Union | _: Distinct | _:
Intersect | _: Except |
+ _: Sort | _: SubqueryAlias | _: RepartitionOperation | _:
LateralJoin => true
+ // The domain join of a subquery of an operator in `input` takes its
domain from the input
+ // of that operator, which this check accepts too. Directly in
`input`, its domain comes
+ // from outside the plan this rule sees.
+ case _: DomainJoin => inSubquery
+ // E.g. the LIMIT 1 that RewriteNonCorrelatedExists adds for an
uncorrelated EXISTS.
+ case l @ (_: LocalLimit | _: GlobalLimit) =>
constantOutput(l.children.head)
+ 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(_, inSubquery = true))
+ }
+
+ // Whether every row of `plan` is the same row of constants, so that a LIMIT
over it gives the
+ // same rows whichever rows it keeps.
+ private def constantOutput(plan: LogicalPlan): Boolean = plan match {
+ case Project(projectList, _) => projectList.forall {
+ case Alias(child, _) => child.foldable
+ case e => e.foldable
+ }
+ case l @ (_: LocalLimit | _: GlobalLimit) =>
constantOutput(l.children.head)
+ case _ => false
+ }
+
+ // Whether `f` gives the same value when computed again over the same rows
in another order.
+ // This is stricter than EliminateSorts.isOrderIrrelevantAggFunction, which
only needs the
+ // result not to depend on a Sort below the aggregate: floating-point
addition is not
+ // associative, so neither a SUM of floating-point values nor an AVG of
anything but decimals
+ // and ANSI intervals, which AVG adds up as DOUBLE, nor a CentralMomentAgg
qualifies.
+ private def orderIrrelevant(f: AggregateFunction): Boolean = f match {
+ case _: Min | _: Max | _: Count | _: BitAndAgg | _: BitOrAgg | _:
BitXorAgg => true
+ case _: Sum => !f.children.exists(c => c.dataType == FloatType ||
c.dataType == DoubleType)
+ case _: Average => f.children.forall(c =>
+ c.dataType.isInstanceOf[DecimalType] ||
c.dataType.isInstanceOf[AnsiIntervalType])
+ 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 some joins or, for a LIMIT 1,
below a group-only
+ * aggregate (see limitMayBePushedIn). 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, inSubquery = true)
+ case _ => false
+ })
+ case l @ LocalLimit(limitExpr, child) =>
Review Comment:
Done: the binder is gone with `limitMayBePushedIn`'s case, and
`constantOutput` uses `trimAliases`.
--
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]