dongjoon-hyun commented on code in PR #60411:
URL: https://github.com/apache/spark/pull/60411#discussion_r4558627896
##########
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:
Since `scanStrategy` is lazy, a hand-built nearest scanner with
`useCursorScan = true` fails only when a left row gets past the empty-group
check (line 878) and the NULL as-of key check (line 883) in `findWithCursor`.
If every left row of a partition has a NULL as-of key, or falls in a group that
has no right rows, `findWithCursor` returns `null` before it reads
`scanStrategy`. Then an inner join returns no rows and a left outer join
returns null-padded rows, with no error. The new `nearest join has no cursor
scan` test uses `Seq(5)` and `Seq(1, 9)`, so it doesn't cover these inputs.
How about checking the strategy in the constructor when `useCursorScan` is
true, for example next to `numAsOfCursorTasks += 1`? Then such a scanner fails
for any input, as the PR description says.
##########
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:
Nit: this matches on the direction, and `findInOrder` then reads the
strategy of the same direction through the lazy `scanStrategy`. How about
keeping the `Option` once and dispatching on it, like `supportCodegen` does?
```scala
// None for a nearest join, which has no ordered scan.
private val orderedScanStrategy: Option[AsOfScanStrategy] =
AsOfScanStrategy.of(direction)
private def findBestInGroup(leftRow: InternalRow): InternalRow =
orderedScanStrategy match {
case Some(strategy) => findInOrder(leftRow, strategy)
case None => findNearest(leftRow)
}
```
`findWithCursor` could read the same field, together with the constructor
check suggested at line 613.
##########
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:
This says that the interpreted and the generated scans read every choice
that depends on the direction from here, "so the two cannot disagree". But
`findBestInGroup` (line 788) and `supportsCursorScan` (line 1062) still match
on the direction, and the scan loops are still written twice, once in Scala and
once as generated Java, as the PR description says. The two flags keep these
choices in one place, but the loops can still drift apart, which is what the
new differential test checks. Could the doc say only what the flags guarantee,
for example that both scans read the choices that depend on the direction from
here?
##########
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:
For both strategies, `matchOutlivesLeftRow` is `!firstMatchWins`, so the
class carries one bit. Nothing ties the two flags together, so a new strategy
could set both to `true`. Then the generated cursor scan would return the first
passing row, never check the kept row again, and stop at a failing row, which
is neither a backward nor a forward scan. Could one flag be derived from the
other, for example `final def matchOutlivesLeftRow: Boolean = !firstMatchWins`
with the doc saying why, or do you expect them to differ for a future direction?
##########
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:
For `nearest`, the ASOF join codegen never applies, so the two nearest tests
compare the interpreted scan with itself, 32 cases with the codegen off and on
for each join type. They only add the check that the plan is not generated,
which the existing nearest tests already make through `assertAsOfJoinCodegen`,
and which the new `a nearest join built with the codegen on has no generated
scan` test covers directly. In the backward and forward tests, 12 of the 32
cases set `cursorScan = true` with a residual condition or a tolerance, which
`supportsCursorScan` rejects, so they repeat the case with `cursorScan =
false`. Could we drop `nearest` here and skip those 12 cases, to keep the
`sql/core` test time down?
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinScannerSuite.scala:
##########
@@ -41,6 +42,29 @@ class SortMergeAsOfJoinScannerSuite extends SparkFunSuite
with LocalSparkContext
private val factoryModes =
Seq(CodegenObjectFactoryMode.CODEGEN_ONLY,
CodegenObjectFactoryMode.NO_CODEGEN)
+ test("only backward and forward joins have a scan strategy") {
+ assert(AsOfScanStrategy.of(Backward).contains(AsOfScanStrategy.LastMatch))
+ assert(AsOfScanStrategy.of(Forward).contains(AsOfScanStrategy.FirstMatch))
+ assert(AsOfScanStrategy.of(Nearest).isEmpty)
+ assert(AsOfScanStrategy(Backward) == AsOfScanStrategy.LastMatch)
+ assert(AsOfScanStrategy(Forward) == AsOfScanStrategy.FirstMatch)
+ checkError(
+ exception = intercept[SparkException](AsOfScanStrategy(Nearest)),
+ condition = "INTERNAL_ERROR",
+ parameters = Map("message" -> "The Nearest AS-OF join has no ordered
scan"))
+ }
+
+ test("nearest join has no cursor scan") {
+ val leftKey = AttributeReference("leftKey", IntegerType)()
+ val rightKey = AttributeReference("rightKey", IntegerType)()
+ // A scanner built by hand must fail, not run the cursor of another
direction.
+ val error = intercept[SparkException] {
+ runScan(Seq(5), Seq(1, 9), leftKey, rightKey, Literal.TrueLiteral,
Nearest,
+ useCursorScan = true)
+ }
+ assert(error.getMessage.contains("The Nearest AS-OF join has no ordered
scan"))
Review Comment:
Nit: the error is thrown in a task, so this checks only that the job-abort
message contains the text. How about checking the cause with `checkError`, like
the test above?
```scala
checkError(
exception = error.getCause.asInstanceOf[SparkException],
condition = "INTERNAL_ERROR",
parameters = Map("message" -> "The Nearest AS-OF join has no ordered
scan"))
```
##########
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:
`matchOutlivesLeftRow` is right for a backward join only because
`supportsCursorScan` (lines 1062-1068) accepts just `>=` and `>` for a backward
join, and just `<=` and `<` for a forward join, with the left key first. That
pairing still matches on the direction on its own, outside `AsOfScanStrategy`.
So a reader has to check both places to see that the flag holds, and the flag
won't follow a later change to the accepted conditions. Could
`AsOfScanStrategy` also own the cursor comparisons it accepts, for example `def
cursorOperands(asOfCondition: Expression): Option[(Expression, Expression)]`,
so that each direction and its operators are paired in one place?
##########
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:
With `cursorScan = true`, this doesn't check that the cursor scan ran.
`supportsCursorScan` rejects a residual condition and a tolerance, so only 4 of
the 32 cases of a backward or forward join use the cursor scan. If the
condition that `joinAsOf` builds stops matching `supportsCursorScan` one day,
those cases would quietly run the buffered scan, and the generated
`findWithCursor` would lose this coverage. How about asserting
`numAsOfCursorTasks > 0`, as `checkCursorScan` does, when `cursorScan &&
!residual && tolerance.isEmpty` for a backward or forward join, and `== 0`
otherwise?
--
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]