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


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/RewriteAsOfJoinSuite.scala:
##########
@@ -277,39 +277,44 @@ class RewriteAsOfJoinSuite extends PlanTest {
     comparePlans(rewritten, correctAnswer, checkAnalysis = false)
   }
 
-  test("no rewrite when the node requires the sort-merge as-of join operator") 
{
-    // A node flagged `requiresSortMergeAsOfJoin = true` (e.g. from a SQL 
MATCH_CONDITION) is
-    // left untouched so the sort-merge physical operator handles it instead.
-    val query = AsOfJoin(left, right, left.output(0), right.output(0), None, 
Inner,
-      tolerance = None, allowExactMatches = true, direction = 
AsOfJoinDirection("backward"))
-      .copy(requiresSortMergeAsOfJoin = true)
-    val analyzed = query.analyze
-
-    // The flag must survive analysis, so it, not a dropped flag, is what 
makes this a no-op.
-    assert(analyzed.collectFirst { case a: AsOfJoin => a 
}.exists(_.requiresSortMergeAsOfJoin),
-      "expected the analyzed plan to still carry requiresSortMergeAsOfJoin = 
true")
-
-    val rewritten = RewriteAsOfJoin(analyzed)
-
-    comparePlans(rewritten, analyzed)
-  }
-
   test("no rewrite when the sort-merge as-of join operator is enabled by 
config") {
-    // With the config on, the sort-merge operator is enabled globally, so 
even a plain node
-    // (flag off) is left intact rather than rewritten to a subquery.
+    // Analysis records the strategy, so later config changes do not affect 
the rewrite.
     withSQLConf(SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> "true") {
       val query = AsOfJoin(left, right, left.output(0), right.output(0), None, 
Inner,
         tolerance = None, allowExactMatches = true, direction = 
AsOfJoinDirection("backward"))
       val analyzed = query.analyze
 
-      comparePlans(RewriteAsOfJoin(analyzed), analyzed)
+      withSQLConf(SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> "false") {
+        comparePlans(RewriteAsOfJoin(analyzed), analyzed)
+      }
+    }
+  }
+
+  test("sort-merge normalization preserves the tolerance condition on repeated 
application") {
+    withSQLConf(SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> "true") {
+      val analyzed = AsOfJoin(
+        left = left,
+        right = right,
+        leftAsOf = right.output(0),
+        rightAsOf = left.output(0),
+        condition = None,
+        joinType = Inner,
+        tolerance = Some(Literal(1)),
+        allowExactMatches = true,
+        direction = AsOfJoinDirection("backward")
+      ).analyze.asInstanceOf[AsOfJoin]
+
+      val normalized = RewriteAsOfJoin(analyzed).asInstanceOf[AsOfJoin]
+
+      assert(normalized.asOfCondition == analyzed.asOfCondition)

Review Comment:
   **Nit (P3):** `RewriteAsOfJoin` now rewrites only nodes with 
`requiresSortMergeAsOfJoin = false`, so it returns this sort-merge node 
unchanged, and `normalized` is the same plan as `analyzed`. This assertion and 
the final `comparePlans` therefore pass by construction. Nothing in the test 
checks the tolerance bound that its name says is preserved. No end-to-end test 
covers the case either: both reversed-key tests in `SortMergeAsOfJoinSuite` 
('join keys can be reversed' and 'nearest join with swapped as-of columns') 
pass `tolerance = null`.
   
   That leaves no failure signal for tolerances on the new reversed-key 
normalization, which flips the direction while `asOfCondition` keeps the user's 
key orientation. For example, suppose the condition were built from the 
normalized keys without flipping the direction. This reversed backward join 
with tolerance 1 would then accept right keys in `[lk - 1, lk]` instead of 
`[lk, lk + 1]`, and this suite would still pass.
   
   Consider renaming the test to what it checks and asserting the expected 
analyzed `asOfCondition` for the reversed keys. Also consider adding an 
end-to-end reversed-key join with a tolerance to `SortMergeAsOfJoinSuite` under 
both analyzers.
   
   **Verification:**
   - **Regression:** With the sort-merge flag on and the keys passed reversed, 
a backward join with a tolerance keeps a right row inside the tolerance window 
and rejects a right row beyond it, under both analyzers.
   - **Inspection:** The reversed-key tolerance test's name matches its 
assertions, and none of its assertions compares a rule's unchanged output with 
its input.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/AsOfJoinMatchConditionResolution.scala:
##########
@@ -0,0 +1,210 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.plans._
+import org.apache.spark.sql.catalyst.plans.logical.AsOfJoin
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{DecimalType, DoubleType, IntegralType, 
NullType}
+
+/** The executable fields produced by resolving ASOF keys. */
+private[sql] case class MaterializedMatchCondition(
+    asOfCondition: Expression,
+    direction: AsOfJoinDirection,
+    leftSortExpressions: Seq[Expression],
+    rightSortExpressions: Seq[Expression],
+    orderExpression: Option[Expression] = None) {
+
+  /** Replaces the pending operands with the resolved comparison and sort 
keys. */
+  def toJoin(join: AsOfJoin): AsOfJoin = {
+    join.copy(
+      asOfCondition = asOfCondition,
+      direction = direction,
+      leftSortExprs = leftSortExpressions,
+      rightSortExprs = rightSortExpressions,
+      matchLeftOperand = None,
+      matchOperator = None,
+      matchRightOperand = None,
+      requiresSortMergeAsOfJoin = orderExpression.isEmpty,
+      orderExpression = orderExpression
+    )
+  }
+}
+
+/** Shared ASOF key normalization for the fixed-point and single-pass 
analyzers. */
+private[sql] object AsOfJoinMatchConditionResolution {
+
+  /** Materializes a SQL MATCH_CONDITION once both operands are resolved. */
+  def materialize(
+      join: AsOfJoin,
+      leftSet: AttributeSet,
+      rightSet: AttributeSet,
+      leftOperand: Expression,
+      operator: MatchComparisonOperator,
+      rightOperand: Expression): Option[MaterializedMatchCondition] = {
+    AsOfJoinValidation.validateMatchConditionTableReferences(
+      join = join,
+      leftSet = leftSet,
+      rightSet = rightSet,
+      leftExpr = leftOperand,
+      rightExpr = rightOperand
+    )
+
+    if (leftOperand.resolved && rightOperand.resolved) {
+      AsOfJoinValidation.validateMatchConditionOperands(
+        join = join,
+        leftExpr = leftOperand,
+        rightExpr = rightOperand
+      )
+      val (normalizedLeft, normalizedRight, normalizedOperator) =
+        AsOfJoin.normalizeMatchOperands(
+          leftSet = leftSet,
+          rightSet = rightSet,
+          expr1 = leftOperand,
+          operator = operator,
+          expr2 = rightOperand
+        )
+      val (asOfCondition, leftSort, rightSort) = 
AsOfJoin.materializeMatchComparison(
+        leftOperand = normalizedLeft,
+        rightOperand = normalizedRight,
+        normalizedOp = normalizedOperator
+      )
+      Some(MaterializedMatchCondition(
+        asOfCondition = asOfCondition,
+        direction = normalizedOperator.direction,
+        leftSortExpressions = leftSort,
+        rightSortExpressions = rightSort
+      ))
+    } else {
+      None
+    }
+  }
+
+  /** Resolves DataFrame keys and selects the execution strategy during 
analysis. */
+  def materializeDataFrame(
+      join: AsOfJoin,
+      leftSet: AttributeSet,
+      rightSet: AttributeSet,
+      leftOperand: Expression,
+      rightOperand: Expression): Option[MaterializedMatchCondition] = {
+    if (!leftOperand.resolved || !rightOperand.resolved || 
!join.tolerance.forall(_.resolved)) {
+      return None
+    }
+
+    AsOfJoinValidation.validateTolerance(join)
+
+    val useSortMerge = SQLConf.get.sortMergeAsOfJoinEnabled
+    if (useSortMerge) {
+      AsOfJoinValidation.validateMatchConditionTableReferences(
+        join = join,
+        leftSet = leftSet,
+        rightSet = rightSet,
+        leftExpr = leftOperand,
+        rightExpr = rightOperand
+      )
+      AsOfJoinValidation.validateMatchConditionOperands(
+        join = join,
+        leftExpr = leftOperand,
+        rightExpr = rightOperand
+      )
+    }
+    AsOfJoinValidation.validateNearestStringKeys(

Review Comment:
   Yes, we can defer the correlated-subquery STRING ranking fix to a separate 
PR.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4395611808","thread_id":"inline:4395611808","verdict_sha256":"e66a6a1f0f7984f66155f808912fa1adce4eddd91f9ec145779d15b8565737e8"}
 -->



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