sarutak commented on code in PR #60764:
URL: https://github.com/apache/spark/pull/60764#discussion_r4658835987
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -133,6 +135,89 @@ 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, including the other conjuncts
of a filter that
+ * holds an IN or EXISTS subquery, which its domain is built with. 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.
+ *
+ * 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 it is deterministic, e.g. a `LogicalRDD` over
random values.
+ */
+ 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(_, _, Inner, Some(cond), _) => cond
+ }.flatMap(cond =>
collectEquivalentOuterReferences(splitConjunctivePredicates(cond)).keys))
+ lazy val outerIsRepeatable =
+ !outerPlan.isStreaming && outerPlan.children.forall(_.deterministic) &&
(outerPlan match {
+ case Filter(cond, _) => splitConjunctivePredicates(cond)
+
.filterNot(SubqueryExpression.hasInOrCorrelatedExistsSubquery).forall(_.deterministic)
+ case _ => true
+ })
Review Comment:
The check I suggested last time, now
`.filterNot(SubqueryExpression.hasInOrCorrelatedExistsSubquery)`, also skips
the conjuncts that hold another `IN` or `EXISTS` subquery, which I missed.
`RewritePredicateSubquery` rewrites the subquery conjuncts in their written
order (`withSubquery.foldLeft(newFilter)`) and builds each domain over the plan
`p` built so far, so an earlier conjunct such as `rk() < 50000 OR EXISTS
(...)`, which becomes an `ExistenceJoin` and a `Filter` in `p`, is evaluated
again for the domain of a later subquery. That is (1) in the review body:
master returned 494 rows, and this PR returned 263, with the `ExistenceJoin`
appearing twice in the optimized plan, which fits a row being kept only when
`rk()` passes in both evaluations (about 250 expected).
A simpler check closes it: `!outerPlan.isStreaming &&
outerPlan.deterministic`. `QueryPlan.deterministic` covers the operator's own
expressions and its children, and `PlanExpression.deterministic` looks into the
subquery plans, so no conjunct needs to be special-cased. I applied that one
line on top of cfcf7f433b7: the PR's tests pass, (1) returns 527 rows with
master's plan, and the other probes from my earlier reviews give the same
results as this PR, except that `a2.k = a1.k AND rand(0) < 2` no longer builds
a domain (the third row of my first plan cost table). The cost is that it also
falls back in two more cases: when an operator other than a `Filter` holds
another non-deterministic expression (by reading the code, e.g. `rand()` in the
same SELECT list), and when the subquery has a non-deterministic conjunct of
its own (except a scalar subquery in a `Filter`, which this PR already lets
fall back): for `SELECT a1.k, (SELECT max(g) FROM a3 WHERE a3.k = a1.k AND
rand(0) < 1 / a3
.g) m FROM a1`, with `a1(k, v) = (1, 1), (2, 0)` and `a3(k, g) = (1, 3), (9,
0)`, this PR does not fail, while master and the one-line check fail with
DIVIDE_BY_ZERO. If you want to keep that case, the check could leave out the
subquery being decorrelated, e.g. check `outerPlan.children` and every
expression of `outerPlan` except that subquery expression (I have not tried
this). Either way it does not cover (2)-(4) in the review body.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuerySuite.scala:
##########
@@ -210,6 +212,92 @@ class DecorrelateInnerQuerySuite extends PlanTest {
check(innerPlan, outerPlan, correctAnswer, Seq(x <=> x))
}
+ test("SPARK-62142: keep the predicates up to the last one that may not move
in the filter") {
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+ val guard = If(b < 0, Cast(RaiseError(Literal("negative b")),
BooleanType), b > 0)
+ val minB = Alias(min(b), "min_b")()
+ // The remainder by an outer column can fail, so it stays in the filter
after the throwable
+ // guard, and so does the equality written before the guard. So do the
correlated
+ // conjuncts written after them that read an inner column, so that the
equalities become keys
+ // of the domain join, while `y <=> z` is still pulled up. `a > 0` and
`a < 10` move below.
+ val innerPlan =
+ Aggregate(Nil, Seq(minB),
+ Filter(a > 0 && OuterReference(x) === a && guard &&
+ Literal(1) % OuterReference(y) === 0 && OuterReference(y) === b
&&
+ (OuterReference(y) <=> OuterReference(z)) && OuterReference(z)
=== c && a < 10,
+ testRelation))
+ val correctAnswer =
+ Aggregate(Seq(x, y, z), Seq(minB, x, y, z),
+ Filter(x === a && guard && Literal(1) % y === 0 && y === b && z ===
c,
+ DomainJoin(Seq(x, y, z), Filter(a > 0 && a < 10, testRelation))))
+ check(innerPlan, testRelation2, correctAnswer, Seq(x <=> x, y <=> y, z
<=> z, y <=> z))
+
+ // A guard that reads no outer column needs no domain, so the equality
is still pulled up.
+ check(
+ Aggregate(Nil, Seq(minB), Filter(guard && OuterReference(x) === a,
testRelation)),
+ testRelation2,
+ Aggregate(Seq(a), Seq(minB, a), Filter(guard, testRelation)),
+ Seq(x === a))
+
+ // The domain can not stand for these outer columns or outer queries, or
for `x`, which a
+ // filter below equates to `a`, so nothing is kept.
+ Seq(
+ LocalRelation(AttributeReference("m", MapType(IntegerType,
IntegerType))()),
+ LocalRelation(AttributeReference("s", StringType("UTF8_LCASE"))()),
+ LocalRelation(AttributeReference("d", DoubleType)()),
+ LocalRelation(AttributeReference("p", new ExamplePointUDT)()),
+ LocalRelation(AttributeReference("q", ArrayType(new
ExamplePointUDT))()),
+ LocalRelation(AttributeReference("r", new StructType().add("p", new
ExamplePointUDT))()),
+ LocalRelation(Seq(x), isStreaming = true),
+ Project(Seq(x, Alias(Rand(0), "r")()), testRelation2)).foreach {
outerPlan =>
+ val o = outerPlan.output.head
+ check(
+ Aggregate(Nil, Seq(minB), Filter(IsNotNull(OuterReference(o)) &&
guard, testRelation)),
+ outerPlan,
+ Aggregate(Nil, Seq(minB), Filter(guard, testRelation)),
+ Seq(IsNotNull(o)))
+ }
+ check(
+ Aggregate(Nil, Seq(minB),
+ Filter(guard && Literal(1) % OuterReference(x) === 0,
+ Filter(OuterReference(x) === a, testRelation))),
+ testRelation2,
+ Aggregate(Seq(a), Seq(minB, a), Filter(guard, testRelation)),
+ Seq(x === a, Literal(1) % x === 0))
+ // The domain of a subquery in a filter is built with the other
conjuncts of the filter.
Review Comment:
nit: the outer `Filter` in this test (`Rand(0) < 0.5`) holds no `IN` or
`EXISTS` subquery, and for a scalar subquery in a `Filter`,
`RewriteCorrelatedScalarSubquery` builds the domain over the filter's child, so
this comment does not describe what the test checks. It checks that a
non-deterministic conjunct of the outer `Filter` makes the subquery's filter be
decorrelated as before, so the comment could say that.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -133,6 +135,89 @@ 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, including the other conjuncts
of a filter that
+ * holds an IN or EXISTS subquery, which its domain is built with. 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.
+ *
+ * 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 it is deterministic, e.g. a `LogicalRDD` over
random values.
+ */
+ 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(_, _, Inner, Some(cond), _) => cond
Review Comment:
nit: no test fails when this goes back to `Join(_, _, _, Some(cond), _)` (I
ran that mutant). A plan test where a filter whose kept conjuncts read `x` sits
above a `LeftOuter` join whose condition has `OuterReference(x)` equal to an
inner column, expecting those conjuncts to stay in the filter instead of
falling back, would pin 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]