viirya commented on code in PR #60411:
URL: https://github.com/apache/spark/pull/60411#discussion_r4559268476


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinExec.scala:
##########
@@ -821,11 +824,14 @@ private[joins] class SortMergeAsOfJoinScanner(
   }
 
   /**
-   * Backward joins keep the last row that passes the as-of and residual 
conditions.
-   * Once the as-of condition has been true, the scan stops at the first row 
that fails
-   * it, as later sorted rows cannot satisfy it.
+   * Backward and forward joins scan the group in as-of key order for the row 
that passes the
+   * as-of and residual conditions and is closest to the left key: the first 
passing row or the
+   * last, as [[AsOfScanStrategy.firstMatchWins]] tells. Once the as-of 
condition has been true,
+   * the scan stops at the first row that fails it, as later sorted rows 
cannot satisfy it. That
+   * row is past the left key for a backward join, and past the tolerance for 
a forward join.

Review Comment:
   Fixed, with the suggested wording. The `matchOutlivesLeftRow` doc now says 
"at or ahead of" and "at or behind" the left key too.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinExec.scala:
##########
@@ -608,6 +609,9 @@ private[joins] class SortMergeAsOfJoinScanner(
           s"Unexpected nearest keys: $leftSortExprs and $rightSortExprs")
     }
 
+  // Lazy, since a nearest join has no strategy and never reads it.
+  private lazy val scanStrategy: AsOfScanStrategy = AsOfScanStrategy(direction)

Review Comment:
   Done. The scanner now checks the strategy when it is built with 
`useCursorScan`, so it fails whatever the input is. The test also runs with no 
right rows and with no rows at all.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinExec.scala:
##########
@@ -782,8 +786,7 @@ private[joins] class SortMergeAsOfJoinScanner(
 
   /** Finds the best right row in the current group for `leftRow`, or null if 
none passes. */
   private def findBestInGroup(leftRow: InternalRow): InternalRow = direction 
match {
-    case Backward => findLastBackward(leftRow)
-    case Forward => findFirstForward(leftRow)
+    case Backward | Forward => findInOrder(leftRow)

Review Comment:
   Done. The scanner keeps `orderedScanStrategy` as an `Option`, 
`findBestInGroup` dispatches on it, and `findWithCursor` reads the same field.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinExec.scala:
##########
@@ -1113,6 +1090,62 @@ private[execution] object SortMergeAsOfJoinScanner {
   }
 }
 
+/**
+ * What a backward or forward scan of a right group does differently. The 
right rows of a group
+ * and its left rows both come in ascending as-of key order. The interpreted 
scans of
+ * [[SortMergeAsOfJoinScanner]] and the generated scans of 
[[SortMergeAsOfJoinExec]] read every
+ * choice that depends on the direction from here, so the two cannot disagree.

Review Comment:
   Right, that said too much. The doc now says only that both scans read the 
choices from here, and that the scan loops are still written once for each.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinExec.scala:
##########
@@ -1113,6 +1090,62 @@ private[execution] object SortMergeAsOfJoinScanner {
   }
 }
 
+/**
+ * What a backward or forward scan of a right group does differently. The 
right rows of a group
+ * and its left rows both come in ascending as-of key order. The interpreted 
scans of
+ * [[SortMergeAsOfJoinScanner]] and the generated scans of 
[[SortMergeAsOfJoinExec]] read every
+ * choice that depends on the direction from here, so the two cannot disagree.
+ *
+ * A nearest join has no strategy: it compares the gaps on both sides of the 
left key, and only
+ * has an interpreted scan.
+ */
+private[joins] sealed abstract class AsOfScanStrategy {
+
+  /**
+   * Whether the first right row that passes the as-of and residual conditions 
is the closest to
+   * the left key, so the scan can stop there. Otherwise the last such row is 
the closest, and
+   * the scan reads on until a row fails the as-of condition.
+   */
+  def firstMatchWins: Boolean
+
+  /**
+   * For the cursor scan, whose as-of condition only compares the two sort 
keys: whether a right
+   * row that passes for one left row also passes for every later left row of 
the group.
+   *
+   * If so, a failing row is ahead of the left key. The scan stops there, and 
keeps the row for
+   * the next left row. If not, a failing row is behind the left key. No later 
left row can
+   * match it, so the scan drops it, and it checks the kept best row again for 
every left row.
+   */
+  def matchOutlivesLeftRow: Boolean

Review Comment:
   I do not expect them to differ. Both follow from where the passing rows are 
in the group, so `matchOutlivesLeftRow` is now `final` and derived as 
`!firstMatchWins`, and the doc says why.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinExec.scala:
##########
@@ -1113,6 +1090,62 @@ private[execution] object SortMergeAsOfJoinScanner {
   }
 }
 
+/**
+ * What a backward or forward scan of a right group does differently. The 
right rows of a group
+ * and its left rows both come in ascending as-of key order. The interpreted 
scans of
+ * [[SortMergeAsOfJoinScanner]] and the generated scans of 
[[SortMergeAsOfJoinExec]] read every
+ * choice that depends on the direction from here, so the two cannot disagree.
+ *
+ * A nearest join has no strategy: it compares the gaps on both sides of the 
left key, and only
+ * has an interpreted scan.
+ */
+private[joins] sealed abstract class AsOfScanStrategy {
+
+  /**
+   * Whether the first right row that passes the as-of and residual conditions 
is the closest to
+   * the left key, so the scan can stop there. Otherwise the last such row is 
the closest, and
+   * the scan reads on until a row fails the as-of condition.
+   */
+  def firstMatchWins: Boolean
+
+  /**
+   * For the cursor scan, whose as-of condition only compares the two sort 
keys: whether a right
+   * row that passes for one left row also passes for every later left row of 
the group.
+   *
+   * If so, a failing row is ahead of the left key. The scan stops there, and 
keeps the row for
+   * the next left row. If not, a failing row is behind the left key. No later 
left row can
+   * match it, so the scan drops it, and it checks the kept best row again for 
every left row.
+   */
+  def matchOutlivesLeftRow: Boolean
+}
+
+private[joins] object AsOfScanStrategy {
+
+  /** Backward (left.t >= right.t): the passing rows come first, and the last 
one is closest. */
+  case object LastMatch extends AsOfScanStrategy {
+    override def firstMatchWins: Boolean = false
+    override def matchOutlivesLeftRow: Boolean = true

Review Comment:
   Done. `AsOfScanStrategy.cursorOperands` now holds the comparisons each 
direction takes, and `supportsCursorScan` reads it. That was also the last 
place that matched on the direction with a default case.



##########
sql/core/src/test/scala/org/apache/spark/sql/SortMergeAsOfJoinSuite.scala:
##########
@@ -2495,4 +2496,97 @@ class SortMergeAsOfJoinSuite extends QueryTest
       }
     }
   }
+
+  // (grp, ts, v, tag) rows for the differential test below. Both sides have 
ties on `ts` with
+  // different tags, NULL as-of keys, a NULL equi-key and a group that the 
other side lacks. The
+  // left keys fall before, on, between and after the right keys of their 
group.
+  private def directionTestSides(): (classic.DataFrame, classic.DataFrame) = {
+    val schema = StructType(
+      StructField("grp", StringType) ::
+        StructField("ts", IntegerType) ::
+        StructField("v", IntegerType) ::
+        StructField("tag", StringType) :: Nil)
+    val leftRows = List(
+      Row("A", 1, 5, "l1"), Row("A", 5, 5, "l2"), Row("A", 5, 1, "l3"), 
Row("A", null, 5, "l4"),
+      Row("A", 9, 5, "l5"), Row("A", 20, 5, "l6"), Row("B", 4, 5, "l7"), 
Row("C", 4, 5, "l8"),
+      Row(null, 5, 5, "l9"))
+    val rightRows = List(
+      Row("A", 2, 1, "r1"), Row("A", 5, 9, "r2"), Row("A", 5, 3, "r3"), 
Row("A", null, 1, "r4"),
+      Row("A", 7, 3, "r5"), Row("A", 7, 7, "r6"), Row("A", 12, 1, "r7"), 
Row("B", 1, 1, "r8"),
+      Row("B", 4, 6, "r9"), Row("D", 4, 1, "r10"), Row(null, 5, 1, "r11"))
+    // One partition per side fixes the order within a tie.
+    (spark.createDataFrame(leftRows.asJava, schema).coalesce(1),
+      spark.createDataFrame(rightRows.asJava, schema).coalesce(1))
+  }
+
+  for {
+    direction <- Seq("backward", "forward", "nearest")

Review Comment:
   Done. The test covers backward and forward joins only, and runs the cursor 
scan on and off only where the join can use it, so 20 cases instead of 32.



##########
sql/core/src/test/scala/org/apache/spark/sql/SortMergeAsOfJoinSuite.scala:
##########
@@ -2495,4 +2496,97 @@ class SortMergeAsOfJoinSuite extends QueryTest
       }
     }
   }
+
+  // (grp, ts, v, tag) rows for the differential test below. Both sides have 
ties on `ts` with
+  // different tags, NULL as-of keys, a NULL equi-key and a group that the 
other side lacks. The
+  // left keys fall before, on, between and after the right keys of their 
group.
+  private def directionTestSides(): (classic.DataFrame, classic.DataFrame) = {
+    val schema = StructType(
+      StructField("grp", StringType) ::
+        StructField("ts", IntegerType) ::
+        StructField("v", IntegerType) ::
+        StructField("tag", StringType) :: Nil)
+    val leftRows = List(
+      Row("A", 1, 5, "l1"), Row("A", 5, 5, "l2"), Row("A", 5, 1, "l3"), 
Row("A", null, 5, "l4"),
+      Row("A", 9, 5, "l5"), Row("A", 20, 5, "l6"), Row("B", 4, 5, "l7"), 
Row("C", 4, 5, "l8"),
+      Row(null, 5, 5, "l9"))
+    val rightRows = List(
+      Row("A", 2, 1, "r1"), Row("A", 5, 9, "r2"), Row("A", 5, 3, "r3"), 
Row("A", null, 1, "r4"),
+      Row("A", 7, 3, "r5"), Row("A", 7, 7, "r6"), Row("A", 12, 1, "r7"), 
Row("B", 1, 1, "r8"),
+      Row("B", 4, 6, "r9"), Row("D", 4, 1, "r10"), Row(null, 5, 1, "r11"))
+    // One partition per side fixes the order within a tie.
+    (spark.createDataFrame(leftRows.asJava, schema).coalesce(1),
+      spark.createDataFrame(rightRows.asJava, schema).coalesce(1))
+  }
+
+  for {
+    direction <- Seq("backward", "forward", "nearest")
+    joinType <- Seq("inner", "left")
+  } {
+    test(s"$direction $joinType join returns the same rows with the ASOF join 
codegen off and on") {
+      val leftRowCount = directionTestSides()._1.count()
+      var matchedRows = 0L
+      for {
+        equiKey <- Seq(false, true)
+        residual <- Seq(false, true)
+        tolerance <- Seq(None, Some(2))
+        allowExactMatches <- Seq(false, true)
+        cursorScan <- Seq(false, true)
+      } {
+        withClue(s"equi-key $equiKey, residual $residual, tolerance 
$tolerance, " +
+            s"exact matches $allowExactMatches, cursor scan $cursorScan: ") {
+          withSQLConf(
+              SQLConf.SHUFFLE_PARTITIONS.key -> "1",
+              SQLConf.SORT_MERGE_AS_OF_JOIN_CURSOR_SCAN_ENABLED.key -> 
cursorScan.toString) {

Review Comment:
   Done. It asserts that `numAsOfCursorTasks > 0` exactly when the cursor scan 
is on, which now happens only for the cases that can use 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]

Reply via email to