sarutak commented on code in PR #60764:
URL: https://github.com/apache/spark/pull/60764#discussion_r4656590958
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -133,6 +135,87 @@ object DecorrelateInnerQuery extends PredicateHelper {
}
}
+ /**
+ * Splits the conjuncts of a filter whose results are aggregated, e.g. under
an Aggregate, a
+ * Window, a Distinct, a Limit or an Offset, or used by a set operation, in
their written order,
+ * into the ones moved into a filter below, the ones kept in the filter and
the others, which are
+ * decorrelated as before.
+ *
+ * A correlated conjunct used as a join condition with the outer query is
evaluated after the
+ * filter, or ahead of it once pushed into the outer query, and the
conjuncts left in the filter
+ * read the inner column that such an equality equates to an outer column.
So when a conjunct
+ * may not be evaluated ahead of the others (see `splitMovable`, which takes
an outer reference
+ * as a column), it and the ones written before it are kept in the filter.
They read the domain
+ * attributes of their outer columns, so they are evaluated in their written
order on the values
+ * of each outer row. When they read outer columns, the correlated conjuncts
written after them
+ * that read an inner column are kept too, so that the equalities among them
become keys of the
+ * domain join. The uncorrelated conjuncts that may move are moved below,
where they can still be
+ * pushed into a scan.
+ *
+ * The domain groups the outer rows by its columns, joins them back with
`<=>` and reads the outer
+ * query once more. So an outer column that a kept conjunct reads must be
orderable, its equal
+ * values must be identical, unlike a string of a non-binary collation or a
floating-point value,
+ * also in a user-defined type, and no filter or join below may equate it to
an inner column,
+ * which would stand for it instead. The outer query must also return the
same rows again, so it
+ * must not be streaming or non-deterministic. Otherwise nothing is kept,
unless the filter is
+ * used by a set operation, where the domain has every outer column anyway,
and a correlated
+ * conjunct written after the kept ones is not kept either.
+ *
+ * TODO: Keep the written order also for these outer columns and outer
queries, for a filter whose
+ * results are not aggregated, e.g. in an EXISTS subquery without a Limit or
a set operation, for
+ * the condition of a join in the subquery, across operators, e.g. for a
throwable conjunct in a
+ * filter above another one with a correlated equality, and for an outer
column that the outer
+ * query computes with an expression that can fail. Also detect an outer
query that returns
+ * other rows again although its children are deterministic, e.g. a
`LogicalRDD` over random
+ * values, or another non-deterministic conjunct of the filter that holds an
EXISTS subquery.
+ */
+ private def splitKeptInPlace(
+ conditions: Seq[Expression],
+ child: LogicalPlan,
+ outerPlan: LogicalPlan,
+ underSetOp: Boolean): (Seq[Expression], Seq[Expression],
Seq[Expression]) = {
+ val stayUp = splitMovable(conditions.map(stripOuterReference),
Seq(child))._2.toSet
+ def mayNotMove(cond: Expression): Boolean =
stayUp.contains(stripOuterReference(cond))
+ val (prefix, rest) =
conditions.splitAt(conditions.lastIndexWhere(mayNotMove) + 1)
+ lazy val equatedBelow = AttributeSet(child.collect {
+ case Filter(cond, _) => cond
+ case Join(_, _, _, Some(cond), _) => cond
Review Comment:
nit: the `Join` case builds `equivalences` only for an inner join (`if
(!isInnerJoin) { ... equivalences = AttributeMap.empty[Attribute] }` in
`splitCorrelatedPredicate`), so a correlated equality in the condition of an
outer join below does not map the outer column to an inner one. Collecting
every join condition here makes such a filter fall back although it could keep
its conjuncts. Could this be `case Join(_, _, Inner, Some(cond), _) => cond`?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -133,6 +135,87 @@ object DecorrelateInnerQuery extends PredicateHelper {
}
}
+ /**
+ * Splits the conjuncts of a filter whose results are aggregated, e.g. under
an Aggregate, a
+ * Window, a Distinct, a Limit or an Offset, or used by a set operation, in
their written order,
+ * into the ones moved into a filter below, the ones kept in the filter and
the others, which are
+ * decorrelated as before.
+ *
+ * A correlated conjunct used as a join condition with the outer query is
evaluated after the
+ * filter, or ahead of it once pushed into the outer query, and the
conjuncts left in the filter
+ * read the inner column that such an equality equates to an outer column.
So when a conjunct
+ * may not be evaluated ahead of the others (see `splitMovable`, which takes
an outer reference
+ * as a column), it and the ones written before it are kept in the filter.
They read the domain
+ * attributes of their outer columns, so they are evaluated in their written
order on the values
+ * of each outer row. When they read outer columns, the correlated conjuncts
written after them
+ * that read an inner column are kept too, so that the equalities among them
become keys of the
+ * domain join. The uncorrelated conjuncts that may move are moved below,
where they can still be
+ * pushed into a scan.
+ *
+ * The domain groups the outer rows by its columns, joins them back with
`<=>` and reads the outer
+ * query once more. So an outer column that a kept conjunct reads must be
orderable, its equal
+ * values must be identical, unlike a string of a non-binary collation or a
floating-point value,
+ * also in a user-defined type, and no filter or join below may equate it to
an inner column,
+ * which would stand for it instead. The outer query must also return the
same rows again, so it
+ * must not be streaming or non-deterministic. Otherwise nothing is kept,
unless the filter is
+ * used by a set operation, where the domain has every outer column anyway,
and a correlated
+ * conjunct written after the kept ones is not kept either.
Review Comment:
nit: "Otherwise nothing is kept, unless the filter is used by a set
operation, ..., and a correlated conjunct written after the kept ones is not
kept either." is hard to follow: the code falls back for the whole filter when
an outer column of the prefix can not be in the domain, but decorrelates a
later correlated conjunct whose outer column can not be in the domain as
before. Could it say, e.g., "Otherwise nothing is kept, unless the filter is
used by a set operation, where the domain has every outer column anyway. A
correlated conjunct written after the kept ones that reads an outer column that
can not be in the domain is decorrelated as before."?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -133,6 +135,87 @@ object DecorrelateInnerQuery extends PredicateHelper {
}
}
+ /**
+ * Splits the conjuncts of a filter whose results are aggregated, e.g. under
an Aggregate, a
+ * Window, a Distinct, a Limit or an Offset, or used by a set operation, in
their written order,
+ * into the ones moved into a filter below, the ones kept in the filter and
the others, which are
+ * decorrelated as before.
+ *
+ * A correlated conjunct used as a join condition with the outer query is
evaluated after the
+ * filter, or ahead of it once pushed into the outer query, and the
conjuncts left in the filter
+ * read the inner column that such an equality equates to an outer column.
So when a conjunct
+ * may not be evaluated ahead of the others (see `splitMovable`, which takes
an outer reference
+ * as a column), it and the ones written before it are kept in the filter.
They read the domain
+ * attributes of their outer columns, so they are evaluated in their written
order on the values
+ * of each outer row. When they read outer columns, the correlated conjuncts
written after them
+ * that read an inner column are kept too, so that the equalities among them
become keys of the
+ * domain join. The uncorrelated conjuncts that may move are moved below,
where they can still be
+ * pushed into a scan.
+ *
+ * The domain groups the outer rows by its columns, joins them back with
`<=>` and reads the outer
+ * query once more. So an outer column that a kept conjunct reads must be
orderable, its equal
+ * values must be identical, unlike a string of a non-binary collation or a
floating-point value,
+ * also in a user-defined type, and no filter or join below may equate it to
an inner column,
+ * which would stand for it instead. The outer query must also return the
same rows again, so it
+ * must not be streaming or non-deterministic. Otherwise nothing is kept,
unless the filter is
+ * used by a set operation, where the domain has every outer column anyway,
and a correlated
+ * conjunct written after the kept ones is not kept either.
+ *
+ * TODO: Keep the written order also for these outer columns and outer
queries, for a filter whose
+ * results are not aggregated, e.g. in an EXISTS subquery without a Limit or
a set operation, for
+ * the condition of a join in the subquery, across operators, e.g. for a
throwable conjunct in a
+ * filter above another one with a correlated equality, and for an outer
column that the outer
+ * query computes with an expression that can fail. Also detect an outer
query that returns
+ * other rows again although its children are deterministic, e.g. a
`LogicalRDD` over random
+ * values, or another non-deterministic conjunct of the filter that holds an
EXISTS subquery.
+ */
+ private def splitKeptInPlace(
+ conditions: Seq[Expression],
+ child: LogicalPlan,
+ outerPlan: LogicalPlan,
+ underSetOp: Boolean): (Seq[Expression], Seq[Expression],
Seq[Expression]) = {
+ val stayUp = splitMovable(conditions.map(stripOuterReference),
Seq(child))._2.toSet
+ def mayNotMove(cond: Expression): Boolean =
stayUp.contains(stripOuterReference(cond))
+ val (prefix, rest) =
conditions.splitAt(conditions.lastIndexWhere(mayNotMove) + 1)
+ lazy val equatedBelow = AttributeSet(child.collect {
+ case Filter(cond, _) => cond
+ case Join(_, _, _, Some(cond), _) => cond
+ }.flatMap(cond =>
collectEquivalentOuterReferences(splitConjunctivePredicates(cond)).keys))
+ lazy val outerIsRepeatable =
+ !outerPlan.isStreaming && outerPlan.children.forall(_.deterministic)
Review Comment:
This checks only the children of the operator that holds the subquery. For
an `IN` or `EXISTS` subquery in a `Filter`, `RewritePredicateSubquery` builds
the domain over the filter's child with the filter's other conjuncts applied,
so a non-deterministic one among them is evaluated again for the domain. With a
table `gb(k INT, v INT)` filled by `INSERT INTO gb SELECT id, id FROM
range(100000)` and `rk` = `udf(() =>
scala.util.Random.nextInt(100000)).asNondeterministic()`:
```sql
SELECT count(*) FROM (SELECT id kk FROM range(1000)) o WHERE rk() < 50000 AND
o.kk IN (SELECT DISTINCT gb.v FROM gb WHERE gb.k = o.kk AND
CASE WHEN gb.v < 0 THEN raise_error('neg') ELSE true END)
```
Every `kk` is in `gb`, so about 500 rows are expected. Master returned 486,
with a plain left semi join and no domain. This PR returned 270, with a domain
join, which fits a row being kept only when `rk()` passes in both evaluations
(about 250 expected). The guard never fires here. (With `EXISTS (SELECT 1 FROM
gb WHERE ... LIMIT 1)` in place of the `IN`, this PR returned 271 rows, about
the same as above, and master returned 0 rows, which I have not looked into, so
I left that form out.)
My previous comment mentioned this case without a measurement, and the TODO
now names it for an `EXISTS` subquery. Since master returns the right rows
here, could this PR fall back for it instead? For example, when `outerPlan` is
a `Filter`, also require every conjunct of its condition without an `IN` or
`EXISTS` subquery to be deterministic. For a scalar subquery in a `Filter` that
would only fall back more often than needed. The description's "when the outer
query is streaming or non-deterministic" would then hold for this case too.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -621,18 +712,22 @@ object DecorrelateInnerQuery extends PredicateHelper {
val (equalityCond, predicates) =
if (underSetOp) (Seq.empty[Expression], correlated)
else correlated.partition(canPullUpOverAgg)
- val outerReferences = collectOuterReferences(predicates)
+ // No equality equates an outer column that a kept conjunct
reads, here or below (see
+ // `splitKeptInPlace`), so the kept conjuncts read its domain
attribute.
+ val outerReferences = collectOuterReferences(predicates ++
keptInPlace)
val newOuterReferences =
parentOuterReferences ++ outerReferences -- equivalences.keySet
- val (newChild, joinCond, outerReferenceMap) =
- decorrelate(child, newOuterReferences, aggregated, underSetOp)
+ val (newChild, joinCond, outerReferenceMap) = decorrelate(
+ movedBelow.reduceOption(And).map(Filter(_,
child)).getOrElse(child),
+ newOuterReferences, aggregated, underSetOp)
// Add the outer references mapping collected from the equality
conditions.
val newOuterReferenceMap = outerReferenceMap ++ equivalences
// Replace all outer references in the non-equality predicates.
val newCorrelated = replaceOuterReferences(predicates,
newOuterReferenceMap)
+ val newKeptInPlace = replaceOuterReferences(keptInPlace,
newOuterReferenceMap)
Review Comment:
nit: as the comment above says ("No equality equates an outer column that a
kept conjunct reads, here or below"), `newOuterReferenceMap` and
`outerReferenceMap` give the same result for the kept conjuncts. If a later
change lets an equality of this filter equate such a column, the kept conjuncts
would again be rewritten to the inner columns of the equalities written after
them without any error, as in the first item of the earlier review on
6ff4bf6dad2. Could you add
`assert(!collectOuterReferences(keptInPlace).exists(equivalences.contains))`,
or go back to `outerReferenceMap` here, as on 08f504a1595, so that such a
conjunct keeps an `OuterReference` instead of silently reading an inner column?
(Neither covers an equality below, which `equatedBelow` handles.)
--
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]