dongjoon-hyun commented on code in PR #60764:
URL: https://github.com/apache/spark/pull/60764#discussion_r4659348827


##########
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:
   Thank you. Instead of more checks on the outer input, the PR now keeps 
conjuncts in place only in a filter for which master builds a domain join 
anyway, so it never computes the outer query again where master does not. The 
checks on the outer input are gone, and (1) to (5) return master's rows in my 
run (500, 0, 0, 0 and 0).
   



##########
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:
   I removed this case together with the check on the outer input.
   



##########
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:
   Added a plan test with a left outer join below, whose condition equates the 
outer column to an inner one, expecting the conjuncts to stay in the filter.
   



-- 
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]

Reply via email to