cloud-fan commented on code in PR #60403:
URL: https://github.com/apache/spark/pull/60403#discussion_r4570393526


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2315,6 +2321,22 @@ object InferFiltersFromConstraints extends 
Rule[LogicalPlan]
 
         case _ => join
       }
+
+    // A right row that fails the ON condition is never the match of any left 
row, so a filter
+    // that follows from the left constraints and the ON condition can drop it 
before the join.
+    // An inner join also drops the left rows without a match, so its left 
side gets one too.
+    case j: AsOfJoin =>
+      val allConstraints = getAllConstraints(j.left, j.right, j.condition)
+      val newLeft = j.joinType match {
+        case Inner => inferAsOfInputFilter(j.left, allConstraints)
+        case LeftOuter => j.left
+        case other =>
+          throw SparkException.internalError(s"Unexpected as-of join type: 
$other")
+      }
+      // With LeftOuter only the right input gets a filter, so a self join 
loses its shared
+      // exchange. Skipping the filter when both inputs match would keep it, 
but the filter drops
+      // right rows before the shuffle.

Review Comment:
   **Nit (P3):** 'when both inputs match' can be read as a condition on join 
matches, because this comment block uses 'match' for a left row's as-of match 
at line 2325. The PR description names the alternative as leaving the right 
side unfiltered when both sides are the same plan, and the comment could say 
the same:
   
   ```suggestion
         // With LeftOuter only the right input gets a filter, so a self join 
loses its shared
         // exchange. Leaving the right input unfiltered when both inputs are 
the same plan would
         // keep it, but the filter drops right rows before the shuffle.
   ```
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60403#discussion_r4562643206).
   
   **Verification:**
   - **Inspection:** The comment on the left outer self-join trade-off in the 
AsOfJoin case of Optimizer.scala describes the rejected alternative as leaving 
the right input unfiltered when both inputs are the same plan, and does not use 
'match' for it.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2315,6 +2321,22 @@ object InferFiltersFromConstraints extends 
Rule[LogicalPlan]
 
         case _ => join
       }
+
+    // A right row that fails the ON condition is never the match of any left 
row, so a filter
+    // that follows from the left constraints and the ON condition can drop it 
before the join.
+    // An inner join also drops the left rows without a match, so its left 
side gets one too.
+    case j: AsOfJoin =>
+      val allConstraints = getAllConstraints(j.left, j.right, j.condition)
+      val newLeft = j.joinType match {
+        case Inner => inferAsOfInputFilter(j.left, allConstraints)
+        case LeftOuter => j.left
+        case other =>
+          throw SparkException.internalError(s"Unexpected as-of join type: 
$other")
+      }
+      // With LeftOuter only the right input gets a filter, so a self join 
loses its shared
+      // exchange. Skipping the filter when both inputs match would keep it, 
but the filter drops
+      // right rows before the shuffle.
+      j.copy(left = newLeft, right = inferAsOfInputFilter(j.right, 
allConstraints))

Review Comment:
   **Blocking (P1):** This filter changes which right row the sort-merge as-of 
join reads after a key group. To end a group, `bufferRightGroup` and 
`advanceRightTo` read the next right row and project every right ON key on it 
(`rightKeyProj`, SortMergeAsOfJoinExec.scala:595, read at 725 and 749, and at 
970 in the cursor scan). The rows this filter drops are gone before that read, 
so a right ON key that can fail, such as an ANSI division or a narrowing cast, 
can now be evaluated on a row the base branch never reached.
   
   The existing test 'cursor scan: a NULL right ON key ends the group like any 
later key' (AsOfJoinSortMergeSQLSuite.scala:1894) is exactly this case. It runs 
with ANSI on, over a single-partition right view of `(1, 10, 2, 1, 'match')`, 
`(2, NULL, 1, 1, 'null key')` and `(3, 1, 0, 1, 'bad')`, and `ON t.k1 = r.k1 
AND t.k2 = r.a / r.b` makes the right keys `(r.k1, r.a / r.b)`. From reading 
the code: on the base branch the scan reads 'null key' after the `k1 = 1` 
group, its key `(2, NULL)` ends the group, and the query returns `(1, 
'match')`, as the test asserts. With this rule, `r.a IS NOT NULL` drops 'null 
key', so the row read after the group is 'bad', and projecting its key divides 
by zero. Nothing evaluates `r.a / r.b` on 'bad' earlier: a single-partition 
input needs no hash exchange, and the sort compares the second key only between 
rows with equal `k1`. The PR now wraps that test in `withNullOnKeysKept`, and 
the PR description reports that with the rule on, the test reads on to t
 he row whose ON key divides by zero.
   
   The sort-merge as-of operator with this read-ahead ships in 4.3.0, and the 
description says query results stay the same, so this is a query that works on 
the base branch and now fails with DIVIDE_BY_ZERO. Filtering the left input of 
an inner join only shortens how far the scan reads the right input, so that 
side is not affected.
   
   **Recommended change:** In the AsOfJoin case of InferFiltersFromConstraints 
(Optimizer.scala:2328-2339), leave the right input unfiltered when the right 
side of an `=` ON conjunct that compares a left expression with a right one 
fails the rule's existing cannot-fail check. Add a code comment explaining why: 
the sort-merge as-of join reads the right row after each key group and projects 
those keys on it, so dropping right rows could make it project a key that fails 
on a row it did not read before. Keep inferring the left-input filter of an 
inner join. Add plan tests for the guard to the optimizer filter-inference 
tests. In the sort-merge as-of SQL tests, also run the query of 'cursor scan: a 
NULL right ON key ends the group like any later key' 
(AsOfJoinSortMergeSQLSuite.scala:1894) with the rule on.
   
   **Why this works:** If every right equi-key expression passes the 
cannot-fail check, none of them can fail on any row, so reading a different row 
after a group adds no failure, and the inference stays. If one of them can 
fail, the right input reaches the operator with the same rows as on the base 
branch, so the scan reads the same rows and projects the same keys.
   
   **Compatibility:** Inference for as-of joins whose right equi-key 
expressions cannot fail stays as it is, and so does every existing expected 
plan in the filter-inference tests.
   
   **Risks:** As-of joins whose right ON key can fail, such as through an ANSI 
division, a narrowing cast or a UDF, lose the right-input filter, so their 
right input is shuffled and sorted as on the base branch. Removing the guard 
restores the current behavior, and no config gates it. The cannot-fail check is 
conservative, so a few right keys that cannot fail, such as upper(s), also lose 
the right-input filter.
   
   **Constraints:** Use the rule's existing cannot-fail check, and count as 
equi-keys the same ON conjuncts that the as-of join planning extracts. Keep the 
regular Join cases, canBeAsOfFilter and the Filter case unchanged. Keep the 
left-input filter of an inner as-of join, and keep the comment that records the 
left outer self-join trade-off.
   
   **Exclusions:**
   - Regular sort-merge joins are left unchanged, although on the base branch 
their scan already reads ahead in the same way under this rule's Join cases.
   
   **Verification:**
   - **Regression:** Set ANSI on, one shuffle partition, and a single-partition 
right view holding (1, 10, 2, 1, 'match'), (2, NULL, 1, 1, 'null key') and (3, 
1, 0, 1, 'bad'). With InferFiltersFromConstraints on, the sort-merge ASOF JOIN 
ON t.k1 = r.k1 AND t.k2 = r.a / r.b returns (1, 'match') in both the buffered 
and the cursor scan, with as-of join codegen off and on.
   - **Behavior:** For inner and left outer as-of joins whose ON condition has 
a right equi-key that can fail, the optimized right input has no inferred 
filter, and an inner join's left input still gets its inferred filter.
   - **Compatibility:** As-of joins whose right equi-keys cannot fail, 
including a join with a tolerance under ANSI, get the same inferred filters as 
before the repair, and regular joins are unchanged.



##########
sql/core/src/test/scala/org/apache/spark/sql/AsOfJoinSortMergeSQLSuite.scala:
##########
@@ -160,16 +162,67 @@ class AsOfJoinSortMergeSQLSuite extends QueryTest
     }
   }
 
-  /** Names of the columns that the scan of `table` filters on. */
-  private def scanFilterColumns(df: DataFrame, table: String): Set[String] = {
+  /** The data filters that the scan of `table` runs. */
+  private def scanDataFilters(df: DataFrame, table: String): Seq[Expression] = 
{
     val plan = df.queryExecution.executedPlan
     val scans = collect(plan) {
       case scan: FileSourceScanExec if scan.tableIdentifier.exists(_.table == 
table) => scan
     }
     assert(scans.length == 1, s"Expected one scan of $table in plan:\n$plan")
-    scans.head.dataFilters.flatMap(_.references.map(_.name)).toSet
+    scans.head.dataFilters
+  }
+
+  /** Names of the columns that the scan of `table` filters on. */
+  private def scanFilterColumns(df: DataFrame, table: String): Set[String] =
+    scanDataFilters(df, table).flatMap(_.references.map(_.name)).toSet
+
+  /** The joins below the left input and below the right input of the as-of 
join of `df`. */
+  private def joinsBelowAsOfInputs(df: DataFrame): (Seq[BaseJoinExec], 
Seq[BaseJoinExec]) = {
+    val plan = df.queryExecution.executedPlan
+    val asOfJoins = collect(plan) { case j: SortMergeAsOfJoinExec => j }
+    assert(asOfJoins.length == 1, s"Expected one SortMergeAsOfJoinExec in 
plan:\n$plan")
+    def joinsBelow(input: SparkPlan): Seq[BaseJoinExec] =
+      collect(input) { case j: BaseJoinExec => j }
+    (joinsBelow(asOfJoins.head.left), joinsBelow(asOfJoins.head.right))
   }
 
+  /**
+   * Checks the rows of `query` with InferFiltersFromConstraints excluded and 
with it on. With it
+   * on, asserts one join below the as-of input with the subquery and none 
below the other input.
+   * Returns the query with the rule on.
+   */
+  private def checkOneSubqueryJoin(
+      query: String, onLeftInput: Boolean, expected: Seq[Row]): DataFrame = {
+    withSQLConf(SQLConf.OPTIMIZER_EXCLUDED_RULES.key -> 
InferFiltersFromConstraints.ruleName) {
+      checkSortMergeAsOf(sql(query), expected)
+    }
+    val df = sql(query)
+    checkSortMergeAsOf(df, expected)
+    val (leftJoins, rightJoins) = joinsBelowAsOfInputs(df)
+    val (subqueryJoins, otherJoins) =
+      if (onLeftInput) (leftJoins, rightJoins) else (rightJoins, leftJoins)
+    assert(subqueryJoins.size == 1 && otherJoins.isEmpty,
+      s"Expected one join below only the input with the subquery in plan:\n" +
+        df.queryExecution.executedPlan)
+    df
+  }
+
+  /** Whether the scan of `table` keeps only the rows where string `column` 
equals `value`. */
+  private def scanFiltersOnEquality(
+      df: DataFrame, table: String, column: String, value: String): Boolean =
+    scanDataFilters(df, table).exists {
+      case EqualTo(a: Attribute, Literal(v, _: StringType)) =>
+        a.name == column && v.toString == value
+      case _ => false
+    }
+
+  /**
+   * Runs `f` without InferFiltersFromConstraints. It would drop the right 
rows with a NULL ON
+   * key before the join, so a test of how the join itself treats NULL keys 
would not see them.
+   */
+  private def withNullOnKeysKept(f: => Unit): Unit =

Review Comment:
   **Nit (P3):** `withNullOnKeysKept` only excludes 
`InferFiltersFromConstraints`. Nothing in the tests it wraps, or in the 
randomized spill test with its inline exclusion (lines 2312-2316), checks that 
the NULL-key rows still reach `SortMergeAsOfJoinExec`. A NULL key never 
matches, so the expected rows are the same either way. If a later change drops 
those rows before the join some other way, such as another rule that infers 
`isnotnull` on the keys, the backward-match, two-ON-key, NOT NULL left key and 
spill tests keep passing and silently stop testing how the operator handles 
NULL keys. Only 'cursor scan: a NULL right ON key ends the group like any later 
key' would still fail, with DIVIDE_BY_ZERO. In `SortMergeAsOfJoinSuite` this PR 
already guards the same premise with `checkAnswerWithNullOnKeys`, which 
compares the row count of each analyzed as-of input with its optimized one; the 
same check here would give these tests that signal.
   
   **Verification:**
   - **Behavior:** The new check runs in the three cursor-scan NULL-key tests, 
in the gridTest for a NOT NULL left key against a NULL right key, and in the 
randomized spill test. It passes with InferFiltersFromConstraints excluded, and 
it fails when NULL-key right rows are filtered out before the as-of join, for 
example with the rule left on in a test whose ON keys are plain columns.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2264,14 +2264,18 @@ object InferFiltersFromGenerate extends 
Rule[LogicalPlan] {
  * Generate a list of additional filters from an operator's existing 
constraint but remove those
  * that are either already part of the operator's condition or are part of the 
operator's child
  * constraints. These filters are currently inserted to the existing 
conditions in the Filter
- * operators and on either side of Join operators.
+ * operators and on either side of Join and AsOfJoin operators.
  *
  * Note: While this optimization is applicable to a lot of types of join, it 
primarily benefits
  * Inner and LeftSemi joins.
  */
 object InferFiltersFromConstraints extends Rule[LogicalPlan]
   with PredicateHelper with ConstraintHelper {
 
+  // Marks the Filters the AsOfJoin case adds, so the Filter case adds no 
failable or subquery
+  // filter to them.

Review Comment:
   **Nit (P3):** The tag only switches the Filter case to `canBeAsOfFilter` 
(lines 2290-2291), which rejects IN and correlated EXISTS subqueries and 
filters that can fail (2384-2385). `cannotFail` treats an uncorrelated scalar 
subquery as a constant (2407), so a predicate such as `r.k > (SELECT max(x) 
FROM t)` still passes, as the new test 'as-of joins: a scalar subquery compared 
with the ON key still filters the other side' expects. A reader who trusts this 
comment would assume that no subquery of any kind reaches an as-of input.
   
   ```suggestion
     // Marks the Filters the AsOfJoin case adds, so the Filter case adds no 
failable, IN or
     // correlated EXISTS filter to them.
   ```
   
   **Verification:**
   - **Inspection:** The comment on the as-of filter tag in Optimizer.scala 
names failable, IN and correlated EXISTS filters as what the Filter case leaves 
out, which matches canBeAsOfFilter and the plan test showing that scalar 
subquery comparisons are still inferred.



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