cloud-fan commented on code in PR #60227:
URL: https://github.com/apache/spark/pull/60227#discussion_r4514171064
##########
sql/core/src/test/scala/org/apache/spark/sql/SortMergeAsOfJoinSuite.scala:
##########
@@ -67,38 +71,85 @@ class SortMergeAsOfJoinSuite extends QueryTest
(df1, df2)
}
- // Like checkAnswer, but also asserts the right-side buffer spilled
(spillSize > 0).
- private def checkAnswerAndSpill(df: classic.DataFrame, expectedAnswer:
Seq[Row]): Unit = {
- checkAnswer(df, expectedAnswer)
- val op = collectFirst(df.queryExecution.executedPlan) {
- case s: SortMergeAsOfJoinExec => s
+ // Like checkAnswer, but also asserts the right-side buffer spilled
(spillSize > 0). Runs with
+ // the ASOF join codegen off and on, so both paths must handle the spilled
buffer.
+ private def checkAnswerAndSpill(df: => classic.DataFrame, expectedAnswer:
Seq[Row]): Unit = {
+ Seq(false, true).foreach { codegen =>
+ withClue(s"ASOF join codegen $codegen: ") {
+ withSQLConf(SQLConf.ENABLE_SORT_MERGE_AS_OF_JOIN_CODEGEN.key ->
codegen.toString) {
+ val query = df
+ checkAnswer(query, expectedAnswer)
+ val op = collectFirst(query.queryExecution.executedPlan) {
+ case s: SortMergeAsOfJoinExec => s
+ }
+ assert(op.isDefined,
+ s"Expected SortMergeAsOfJoinExec in
plan:\n${query.queryExecution.executedPlan}")
+ assert(op.get.metrics("spillSize").value > 0,
+ s"Expected the right-side buffer to spill (spillSize > 0), " +
+ s"got ${op.get.metrics("spillSize").value}")
+ assert(op.get.metrics("numAsOfCursorTasks").value == 0,
+ "Expected the buffered scan, but a task used the cursor scan")
+ assert(isGenerated(query.queryExecution.executedPlan, op.get) ==
+ (codegen && op.get.direction != Nearest),
+ s"Unexpected ASOF join codegen in
plan:\n${query.queryExecution.executedPlan}")
+ }
+ }
+ }
+ }
+
+ // Whether `join` runs in a codegen stage, and not only in a stage below it.
+ private def isGenerated(plan: SparkPlan, join: SortMergeAsOfJoinExec):
Boolean = {
+ def inStage(node: SparkPlan): Boolean = node match {
+ case j: SortMergeAsOfJoinExec => j eq join
+ case _: InputAdapter => false
+ case other => other.children.exists(inStage)
}
- assert(op.isDefined,
- s"Expected SortMergeAsOfJoinExec in
plan:\n${df.queryExecution.executedPlan}")
- assert(op.get.metrics("spillSize").value > 0,
- s"Expected the right-side buffer to spill (spillSize > 0), " +
- s"got ${op.get.metrics("spillSize").value}")
- assert(op.get.metrics("numAsOfCursorTasks").value == 0,
- "Expected the buffered scan, but a task used the cursor scan")
+ collect(plan) { case stage: WholeStageCodegenExec if inStage(stage.child)
=> stage }.nonEmpty
}
/**
- * Like checkAnswer, but also asserts that the join used the cursor scan. A
right group spills
- * from its second row, so a cursor scan that buffered rows would show a
spill.
+ * Like checkAnswer, but also asserts that the join used the cursor scan,
with the ASOF join
+ * codegen off and on. A right group spills from its second row, so a cursor
scan that
+ * buffered rows would show a spill.
*/
- private def checkCursorScan(df: classic.DataFrame, expectedAnswer:
Seq[Row]): Unit = {
- withSQLConf(
- SQLConf.SORT_MERGE_JOIN_EXEC_BUFFER_IN_MEMORY_THRESHOLD.key -> "1",
- SQLConf.SORT_MERGE_JOIN_EXEC_BUFFER_SPILL_THRESHOLD.key -> "1") {
- checkAnswer(df, expectedAnswer)
+ private def checkCursorScan(df: => classic.DataFrame, expectedAnswer:
Seq[Row]): Unit = {
+ Seq(false, true).foreach { codegen =>
+ withClue(s"ASOF join codegen $codegen: ") {
+ withSQLConf(
+ SQLConf.ENABLE_SORT_MERGE_AS_OF_JOIN_CODEGEN.key ->
codegen.toString,
+ SQLConf.SORT_MERGE_JOIN_EXEC_BUFFER_IN_MEMORY_THRESHOLD.key -> "1",
+ SQLConf.SORT_MERGE_JOIN_EXEC_BUFFER_SPILL_THRESHOLD.key -> "1") {
+ val query = df
+ checkAnswer(query, expectedAnswer)
+ val plan = query.queryExecution.executedPlan
+ val op = collectFirst(plan) { case s: SortMergeAsOfJoinExec => s }
+ assert(op.isDefined, s"Expected SortMergeAsOfJoinExec in
plan:\n$plan")
+ assert(op.get.metrics("numAsOfCursorTasks").value > 0, "Expected the
cursor scan")
+ assert(op.get.metrics("spillSize").value == 0, "The cursor scan
buffered right rows")
+ assert(isGenerated(plan, op.get) == codegen, s"Unexpected ASOF join
codegen in:\n$plan")
+ }
+ }
}
- val op = collectFirst(df.queryExecution.executedPlan) {
- case s: SortMergeAsOfJoinExec => s
+ }
+
+ /**
+ * Like checkAnswer, with the ASOF join codegen off and on. Also asserts
that the plan has the
+ * join, and that it ran generated exactly when the codegen is on and the
join is not nearest.
+ */
+ private def checkAnswerCodegenOffAndOn(df: => DataFrame, expectedAnswer:
Seq[Row]): Unit = {
Review Comment:
**Nit (P3):** The checks the earlier thread named now go through this
helper, but seven backward or forward tests that build a tolerance still check
only once, so with the new flag on by default they run only the generated
buffered scan: 'backward and forward joins support TIME keys', 'backward join -
tolerance = 1', the interval-tolerance test for each direction and key type,
'forward join - tolerance', the cast-key check in 'sort-merge joins reject a
tolerance on STRING keys', 'reversed join keys respect the tolerance', and
'forward join - residual rejects every row within the tolerance'. SQL cannot
write a tolerance (several comparisons in MATCH_CONDITION are a
ParseException), so the golden files' whole-stage-off runs never build one
either. That leaves the interpreted scanner's tolerance handling, such as the
early `return null` in `findFirstForward` once a row is past the tolerance,
with no test that runs it. `SQLMetricsSuite`'s sort-merge ASOF `numOutputRows`
checks also ru
n only the generated scan now, including the LEFT OUTER case with NULL left
equi-keys, which the interpreted scanner counts in its own branch.
Could you run the plain `checkAnswer` tests through this helper, and the
three single-pass analyzer grid tests (TIME keys, cast keys, reversed keys)
through a codegen off/on loop that keeps `checkToRDD = false`, like
`checkAnswerWithoutRDD` in `AsOfJoinSortMergeSQLSuite`? In `SQLMetricsSuite`,
loop the ASOF checks over the new flag and build each DataFrame inside the
loop, since a DataFrame keeps the plan it got first.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60227#discussion_r4510492793).
**Verification:**
- **Regression:** With the ASOF join codegen off, backward and forward
sort-merge ASOF joins with a tolerance, including a forward join whose residual
condition rejects every row inside the tolerance while a later row past it
passes the residual, return the expected rows, and the run confirms the join
did not run generated.
- **Regression:** With the ASOF join codegen off, a LEFT OUTER sort-merge
ASOF join whose left side has NULL equi-keys reports one output row per left
row, so a lost count for the NULL-key rows in the interpreted scan fails the
check.
- **Compatibility:** With the ASOF join codegen on, the same tolerance and
output-row checks still pass and confirm the join ran generated.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinExec.scala:
##########
@@ -133,6 +129,396 @@ case class SortMergeAsOfJoinExec(
}
}
+ /** Whether the join reads the right side once with a cursor, instead of
buffering it. */
+ private def cursorScanEnabled: Boolean =
conf.sortMergeAsOfJoinCursorScanEnabled &&
+ SortMergeAsOfJoinScanner.supportsCursorScan(
+ direction, asOfCondition, condition, leftSortExprs, rightSortExprs)
+
+ // Nearest joins keep the interpreted scan, as its distance compare is
harder to generate. The
+ // config is read once, when the join is planned.
+ override def supportCodegen: Boolean = direction != Nearest && codegenEnabled
+
+ // Hides `codegenEnabled` in the plan string.
+ override def stringArgs: Iterator[Any] =
super.stringArgs.toSeq.dropRight(1).iterator
+
+ override def inputRDDs(): Seq[RDD[InternalRow]] =
+ left.execute() :: right.execute() :: Nil
+
+ // A left row makes at most one output row, so the output row needs no copy.
+ override def needCopyResult: Boolean = false
+
+ // The join loop reads the stage's input, so it stops at a LIMIT fused above
it.
+ override protected def canCheckLimitNotReached: Boolean = true
+
+ /**
+ * Generates the join loop. For each left row, a generated function finds
the best right row,
+ * or null: the cursor scan, or a scan of the buffered right group. The
output columns go
+ * straight to the parent operator.
+ */
+ override protected def doProduce(ctx: CodegenContext): String = {
+ // Inline mutable state since not many join operations in a task
+ val leftInput = ctx.addMutableState("scala.collection.Iterator",
"leftInput",
+ v => s"$v = inputs[0];", forceInline = true)
+ val rightInput = ctx.addMutableState("scala.collection.Iterator",
"rightInput",
+ v => s"$v = inputs[1];", forceInline = true)
+ // The next right row, or null once the right side is done. Reading the
right row after it
+ // can overwrite it, so anything that keeps it longer must copy it.
+ val rightPeek = ctx.addMutableState("UnsafeRow", "rightPeek", forceInline
= true)
+ val nextRightName = ctx.freshName("nextRight")
+ val nextRight = ctx.addNewFunction(nextRightName,
+ s"""
+ |private UnsafeRow $nextRightName() {
+ | return $rightInput.hasNext() ? (UnsafeRow) $rightInput.next() :
null;
+ |}
+ """.stripMargin, inlineToOuterClass = true)
+
+ val (findMatch, initScan) = if (cursorScanEnabled) {
+ genCursorScan(ctx, rightPeek, nextRight)
+ } else {
+ genBufferedScan(ctx, rightInput, rightPeek, nextRight)
+ }
+
+ val leftRow = ctx.freshName("leftRow")
+ val matched = ctx.freshName("matched")
+ val leftVars = genOneSideJoinVars(ctx, leftRow, left, setDefaultValue =
false)
+ val rightVars =
+ genOneSideJoinVars(ctx, matched, right, setDefaultValue = joinType ==
LeftOuter)
+ // An inner join drops a left row with no match. A left outer join keeps
it with nulls.
+ val skipUnmatched = if (joinType == LeftOuter) "" else s"if ($matched ==
null) continue;"
+ val numOutput = metricTerm(ctx, "numOutputRows")
+ val initJoin = ctx.addMutableState(CodeGenerator.JAVA_BOOLEAN, "initJoin")
+ val thisPlan = ctx.addReferenceObj("plan", this)
+
+ s"""
+ |if (!$initJoin) {
+ | $initJoin = true;
+ | $rightPeek = $nextRight();
+ | $initScan
+ |}
+ |while ($limitNotReachedCond $leftInput.hasNext()) {
+ | InternalRow $leftRow = (InternalRow) $leftInput.next();
+ | UnsafeRow $matched = $findMatch($leftRow);
+ | $skipUnmatched
+ | $numOutput.add(1);
+ | ${consume(ctx, leftVars ++ rightVars)}
+ | if (shouldStop()) return;
+ |}
+ |$thisPlan.cleanupResources();
+ """.stripMargin
+ }
+
+ /**
+ * Generates the cursor scan of [[SortMergeAsOfJoinScanner]] (see
`findWithCursor` there).
+ * Returns the function that finds the best right row for a left row, and
the code that
+ * starts the scan.
+ */
+ private def genCursorScan(
+ ctx: CodegenContext,
+ rightPeek: String,
+ nextRight: String): (String, String) = {
+ // The best right row so far: null, or `bestBuffer`, which holds a copy of
it.
+ val cursorBest = ctx.addMutableState("UnsafeRow", "cursorBest",
forceInline = true)
+ val bestBuffer = ctx.addMutableState("UnsafeRow", "cursorBestBuffer",
forceInline = true)
+ val groupHasRight =
+ ctx.addMutableState(CodeGenerator.JAVA_BOOLEAN, "cursorGroupHasRight",
forceInline = true)
+ val copyToBestName = ctx.freshName("copyToCursorBestBuffer")
+ val copyToBest = ctx.addNewFunction(copyToBestName,
+ s"""
+ |private UnsafeRow $copyToBestName(UnsafeRow row) {
+ | if ($bestBuffer == null) {
+ | $bestBuffer = row.copy();
+ | } else {
+ | $bestBuffer.copyFrom(row);
+ | }
+ | return $bestBuffer;
+ |}
+ """.stripMargin, inlineToOuterClass = true)
+ val leftRow = ctx.freshName("leftRow")
+ val (readLeftKeys, compareRightKeys, onNewGroup) =
+ genEquiKeys(ctx, leftRow, rightPeek)
+ val leftAsOfKey = createJoinKey(ctx, leftRow, leftSortExprs.take(1),
left.output).head
+ val rightAsOfKey = createJoinKey(ctx, rightPeek, rightSortExprs.take(1),
right.output).head
+ val asOfHolds = genConditionFunction(ctx, asOfCondition, "asOfHolds")
+ // A new group skips the right rows of earlier groups without evaluating
either as-of key,
+ // then records whether the group has a right row. Without equi-keys, the
only group starts
+ // with the scan.
+ val (startGroup, startOnlyGroup) = if (leftKeys.isEmpty) {
+ ("", s"$groupHasRight = $rightPeek != null;")
+ } else {
+ val start =
+ s"""
+ |$cursorBest = null;
+ |while ($rightPeek != null) {
+ | $compareRightKeys
+ | if (comp <= 0) break;
+ | $rightPeek = $nextRight();
+ |}
+ |$groupHasRight = $rightPeek != null && comp == 0;
+ """.stripMargin
+ (start, "")
+ }
+ // Forward checks the kept row again first. On a failing row, forward
drops it, since no
+ // later left row can match it, and backward stops there and keeps it for
the next left row.
+ val (checkKeptRow, onPass, onFail) = direction match {
+ case Forward =>
+ val check =
+ s"""
+ |if ($cursorBest != null) {
+ | if ($asOfHolds($leftRow, $cursorBest)) return $cursorBest;
+ | $cursorBest = null;
+ |}
+ """.stripMargin
+ (check, s"return $cursorBest;", s"$rightPeek = $nextRight();")
+ case _ =>
+ ("", "", s"return $cursorBest;")
+ }
+
+ val funcName = ctx.freshName("findWithCursor")
+ val func = ctx.addNewFunction(funcName,
+ s"""
+ |private UnsafeRow $funcName(InternalRow $leftRow) {
+ | int comp = 0;
+ | $readLeftKeys
+ | ${onNewGroup(startGroup)}
+ | // A group with no right rows never evaluates the left as-of key,
which can fail at
+ | // runtime, for example on an invalid cast under ANSI.
+ | if (!$groupHasRight) return null;
+ | ${leftAsOfKey.code}
+ | // A NULL left as-of key matches nothing. It must not move the
cursor.
+ | if (${leftAsOfKey.isNull}) return null;
+ | $checkKeptRow
+ | while ($rightPeek != null) {
+ | $compareRightKeys
+ | // The group's right rows end at the first row of a later group.
+ | if (comp != 0) return $cursorBest;
+ | ${rightAsOfKey.code}
+ | if (${rightAsOfKey.isNull}) {
+ | $rightPeek = $nextRight();
+ | continue;
+ | }
+ | if ($asOfHolds($leftRow, $rightPeek)) {
+ | // The next right row can overwrite `rightPeek`, so keep a
copy.
+ | $cursorBest = $copyToBest($rightPeek);
+ | $rightPeek = $nextRight();
+ | $onPass
+ | } else {
+ | $onFail
+ | }
+ | }
+ | return $cursorBest;
+ |}
+ """.stripMargin, inlineToOuterClass = true)
+ (func, s"""
+ |${metricTerm(ctx, "numAsOfCursorTasks")}.add(1);
+ |$startOnlyGroup
+ """.stripMargin)
+ }
+
+ /**
+ * Generates the buffered scan of [[SortMergeAsOfJoinScanner]]. Each right
group stays in an
+ * [[ExternalAppendOnlyUnsafeRowArray]], which can spill, and is scanned for
every left row.
+ * Returns the function that finds the best right row for a left row, and
the code that
+ * starts the scan.
+ */
+ private def genBufferedScan(
+ ctx: CodegenContext,
+ rightInput: String,
+ rightPeek: String,
+ nextRight: String): (String, String) = {
+ val clsName = classOf[ExternalAppendOnlyUnsafeRowArray].getName
+ val inMemoryThreshold = conf.sortMergeJoinExecBufferInMemoryThreshold
+ val sizeInBytesSpillThreshold =
conf.sortMergeJoinExecBufferSpillSizeThreshold
+ val spillThreshold = conf.sortMergeJoinExecBufferSpillThreshold
+ // Inline mutable state since not many join operations in a task
+ val group = ctx.addMutableState(clsName, "rightGroup",
+ v => s"$v = new $clsName($inMemoryThreshold,
${sizeInBytesSpillThreshold}L, " +
+ s"$spillThreshold, ${sizeInBytesSpillThreshold}L);",
+ forceInline = true)
+ val leftRow = ctx.freshName("leftRow")
+
+ val fillGroup = if (leftKeys.isEmpty) {
+ val allBuffered = ctx.addMutableState(CodeGenerator.JAVA_BOOLEAN,
"allRightBuffered")
+ s"""
+ |if (!$allBuffered) {
+ | // No equi-keys, so the whole right side is one group.
+ | $allBuffered = true;
+ | if ($rightPeek != null) {
+ | $group.add($rightPeek);
+ | $rightPeek = null;
+ | }
+ | while ($rightInput.hasNext()) {
+ | $group.add((UnsafeRow) $rightInput.next());
+ | }
+ |}
+ """.stripMargin
+ } else {
+ val (readLeftKeys, compareRightKeys, onNewGroup) =
+ genEquiKeys(ctx, leftRow, rightPeek)
+ val bufferGroup =
+ s"""
+ |$group.clear();
+ |while ($rightPeek != null) {
+ | $compareRightKeys
+ | if (comp > 0) {
+ | $rightPeek = $nextRight();
+ | continue;
+ | }
+ | if (comp < 0) break;
+ | $group.add($rightPeek);
+ | $rightPeek = $nextRight();
+ |}
+ """.stripMargin
+ s"""
+ |$readLeftKeys
+ |${onNewGroup(bufferGroup)}
+ """.stripMargin
+ }
+
+ val asOfHolds = genConditionFunction(ctx, asOfCondition, "asOfHolds")
+ val rightRow = ctx.freshName("rightRow")
+ val residualHolds = condition
+ .map(cond => s"${genConditionFunction(ctx, cond,
"residualHolds")}($leftRow, $rightRow)")
+ .getOrElse("true")
+ val needsCopy = ctx.freshName("needsCopy")
+ val best = ctx.freshName("best")
+ // A spilled group reuses one row on every next(), so a kept match must be
copied.
+ val retained = s"($needsCopy ? $rightRow.copy() : $rightRow)"
+ // Backward keeps the last passing row, and forward returns the first.
Once the as-of
+ // condition has held, the first row that fails it ends the scan.
+ val (onMatch, onPastMatches, noMoreRows) = direction match {
+ case Forward => (s"return $retained;", "return null;", "return null;")
+ case _ => (s"$best = $retained;", s"return $best;", s"return $best;")
+ }
+ val iter = ctx.freshName("iter")
+ val asOfSeen = ctx.freshName("asOfSeen")
+
+ val funcName = ctx.freshName("findInGroup")
+ // The scan often stops early, so it closes the iterator to close the
spill files it reads.
+ val func = ctx.addNewFunction(funcName,
+ s"""
+ |private UnsafeRow $funcName(InternalRow $leftRow) throws
java.io.IOException {
+ | int comp = 0;
+ | $fillGroup
+ | scala.collection.Iterator<UnsafeRow> $iter =
$group.generateIterator();
+ | try {
+ | boolean $needsCopy = $group.isSpillBacked();
+ | boolean $asOfSeen = false;
+ | UnsafeRow $best = null;
+ | while ($iter.hasNext()) {
+ | UnsafeRow $rightRow = (UnsafeRow) $iter.next();
+ | if ($asOfHolds($leftRow, $rightRow)) {
+ | $asOfSeen = true;
+ | if ($residualHolds) {
+ | $onMatch
+ | }
+ | } else if ($asOfSeen) {
+ | $onPastMatches
+ | }
+ | }
+ | $noMoreRows
+ | } finally {
+ | if ($iter instanceof java.io.Closeable) {
+ | ((java.io.Closeable) $iter).close();
Review Comment:
**Nit (P3):** This close releases a spilled group's unread spill readers as
soon as the generated scan returns. The interpreted `findLastBackward`,
`findFirstForward` and `findNearest` still return early without closing the
iterator from `rightGroupBuffer.generateIterator()`, so their readers stay open
until the task ends, as on the base branch. Those scans still run every nearest
join, and every backward or forward join with the new flag off, with
whole-stage codegen off or NO_CODEGEN, over `spark.sql.codegen.maxFields`, with
a CodegenFallback expression, or on compile fallback. Leaving them to #60240 is
fine, but only the PR description and your conversation comment say so; nothing
in the interpreted scanner does. Could you add a TODO naming SPARK-61248 there,
for example one above the dispatch in `findBestInGroup` that covers all three
scans, saying that an early return keeps the group's unread spill files open
until the task ends, while the generated scan already closes them?
This extends an [existing
discussion](https://github.com/apache/spark/pull/60227#issuecomment-6741672819).
**Verification:**
- **Inspection:** Reading the interpreted buffered scans for backward,
forward and nearest joins shows, at or above their early returns, a TODO that
names SPARK-61248 and says returning early keeps the group's unread spill files
open until the task ends, with no executable line changed.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/UnionCodegenSuite.scala:
##########
@@ -533,6 +534,89 @@ class UnionCodegenSuite extends SharedSparkSession with
AdaptiveSparkPlanHelper
}
}
+ /** A union of an ASOF join in `direction` and a range. */
+ private def asOfJoinUnion(direction: String): DataFrame = {
+ // `joinAsOf` is on the classic Dataset, so build the inputs from
`spark.range`.
+ val left = spark.range(10).select(col("id").as("k"), (col("id") *
2).as("ts"))
+ val right = spark.range(10).select(col("id").as("k"), (col("id") * 2 -
1).as("ts"))
+ left.joinAsOf(right, left("ts"), right("ts"), usingColumns = Seq("k"),
+ joinType = "inner", tolerance = null, allowExactMatches = true,
direction = direction)
+ .select(left("k"), right("ts"))
+ .union(rangeDF(100, 103).select(col("id").as("k"), col("id").as("ts")))
+ }
+
+ /** The rows of `asOfJoinUnion` in any direction: each key has one right
row, just before. */
Review Comment:
**Nit (P3):** These rows hold only for backward and nearest joins. Each key
k has a left row at ts = 2k and one right row at ts = 2k - 1, so a forward
join, which needs right.ts >= left.ts, matches nothing, and
`asOfJoinUnion("forward")` returns only the three range rows. The tests pass
because they call the helper only with "backward" and "nearest", but a later
test that passes "forward" and trusts this comment would fail its checkAnswer
for a reason the comment hides.
```suggestion
/** The rows of `asOfJoinUnion`, backward or nearest: each key has one
right row, just before. */
```
**Verification:**
- **Inspection:** The comment on the expected rows of the ASOF-join union
helper names only backward and nearest joins, and every caller of the helper
passes one of those directions.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinExec.scala:
##########
@@ -133,6 +128,383 @@ case class SortMergeAsOfJoinExec(
}
}
+ /** Whether the join reads the right side once with a cursor, instead of
buffering it. */
+ private def cursorScanEnabled: Boolean =
conf.sortMergeAsOfJoinCursorScanEnabled &&
+ SortMergeAsOfJoinScanner.supportsCursorScan(
+ direction, asOfCondition, condition, leftSortExprs, rightSortExprs)
+
+ // Nearest joins keep the interpreted scan, as its distance compare is
harder to generate.
+ override def supportCodegen: Boolean =
+ direction != Nearest &&
conf.getConf(SQLConf.ENABLE_SORT_MERGE_AS_OF_JOIN_CODEGEN)
+
+ override def inputRDDs(): Seq[RDD[InternalRow]] =
+ left.execute() :: right.execute() :: Nil
+
+ // A left row makes at most one output row, so the output row needs no copy.
+ override def needCopyResult: Boolean = false
+
+ /**
+ * Generates the join loop. For each left row, a generated function finds
the best right row,
+ * or null: the cursor scan, or a scan of the buffered right group. The
output columns go
+ * straight to the parent operator.
+ */
+ override protected def doProduce(ctx: CodegenContext): String = {
+ // Inline mutable state since not many join operations in a task
+ val leftInput = ctx.addMutableState("scala.collection.Iterator",
"leftInput",
+ v => s"$v = inputs[0];", forceInline = true)
+ val rightInput = ctx.addMutableState("scala.collection.Iterator",
"rightInput",
+ v => s"$v = inputs[1];", forceInline = true)
+ // The next right row, or null once the right side is done. Reading the
right row after it
+ // can overwrite it, so anything that keeps it longer must copy it.
+ val rightPeek = ctx.addMutableState("UnsafeRow", "rightPeek", forceInline
= true)
+ val nextRightName = ctx.freshName("nextRight")
+ val nextRight = ctx.addNewFunction(nextRightName,
+ s"""
+ |private UnsafeRow $nextRightName() {
+ | return $rightInput.hasNext() ? (UnsafeRow) $rightInput.next() :
null;
+ |}
+ """.stripMargin, inlineToOuterClass = true)
+
+ val (findMatch, initScan) = if (cursorScanEnabled) {
+ genCursorScan(ctx, rightPeek, nextRight)
+ } else {
+ genBufferedScan(ctx, rightInput, rightPeek, nextRight)
+ }
+
+ val leftRow = ctx.freshName("leftRow")
+ val matched = ctx.freshName("matched")
+ val leftVars = genOneSideJoinVars(ctx, leftRow, left, setDefaultValue =
false)
+ val rightVars =
+ genOneSideJoinVars(ctx, matched, right, setDefaultValue = joinType ==
LeftOuter)
+ // An inner join drops a left row with no match. A left outer join keeps
it with nulls.
+ val skipUnmatched = if (joinType == LeftOuter) "" else s"if ($matched ==
null) continue;"
+ val numOutput = metricTerm(ctx, "numOutputRows")
+ val initJoin = ctx.addMutableState(CodeGenerator.JAVA_BOOLEAN, "initJoin")
+ val thisPlan = ctx.addReferenceObj("plan", this)
+
+ s"""
+ |if (!$initJoin) {
+ | $initJoin = true;
+ | $rightPeek = $nextRight();
+ | $initScan
+ |}
+ |while ($leftInput.hasNext()) {
+ | InternalRow $leftRow = (InternalRow) $leftInput.next();
+ | UnsafeRow $matched = $findMatch($leftRow);
+ | $skipUnmatched
+ | $numOutput.add(1);
+ | ${consume(ctx, leftVars ++ rightVars)}
+ | if (shouldStop()) return;
+ |}
+ |$thisPlan.cleanupResources();
+ """.stripMargin
+ }
+
+ /**
+ * Generates the cursor scan of [[SortMergeAsOfJoinScanner]] (see
`findWithCursor` there).
+ * Returns the function that finds the best right row for a left row, and
the code that
+ * starts the scan.
+ */
+ private def genCursorScan(
+ ctx: CodegenContext,
+ rightPeek: String,
+ nextRight: String): (String, String) = {
+ // The best right row so far: null, or `bestBuffer`, which holds a copy of
it.
+ val cursorBest = ctx.addMutableState("UnsafeRow", "cursorBest",
forceInline = true)
+ val bestBuffer = ctx.addMutableState("UnsafeRow", "cursorBestBuffer",
forceInline = true)
+ val groupHasRight =
+ ctx.addMutableState(CodeGenerator.JAVA_BOOLEAN, "cursorGroupHasRight",
forceInline = true)
+ val copyToBestName = ctx.freshName("copyToCursorBestBuffer")
+ val copyToBest = ctx.addNewFunction(copyToBestName,
+ s"""
+ |private UnsafeRow $copyToBestName(UnsafeRow row) {
+ | if ($bestBuffer == null) {
+ | $bestBuffer = row.copy();
+ | } else {
+ | $bestBuffer.copyFrom(row);
+ | }
+ | return $bestBuffer;
+ |}
+ """.stripMargin, inlineToOuterClass = true)
+ val leftRow = ctx.freshName("leftRow")
+ val (readLeftKeys, compareRightKeys, onNewGroup) =
+ genEquiKeys(ctx, leftRow, rightPeek)
+ val leftAsOfKey = createJoinKey(ctx, leftRow, leftSortExprs.take(1),
left.output).head
+ val rightAsOfKey = createJoinKey(ctx, rightPeek, rightSortExprs.take(1),
right.output).head
+ val asOfHolds = genConditionFunction(ctx, asOfCondition, "asOfHolds")
+ // A new group skips the right rows of earlier groups without evaluating
either as-of key,
+ // then records whether the group has a right row. Without equi-keys, the
only group starts
+ // with the scan.
+ val (startGroup, startOnlyGroup) = if (leftKeys.isEmpty) {
+ ("", s"$groupHasRight = $rightPeek != null;")
+ } else {
+ val start =
+ s"""
+ |$cursorBest = null;
+ |while ($rightPeek != null) {
+ | $compareRightKeys
+ | if (comp <= 0) break;
+ | $rightPeek = $nextRight();
+ |}
+ |$groupHasRight = $rightPeek != null && comp == 0;
+ """.stripMargin
+ (start, "")
+ }
+ // Forward checks the kept row again first. On a failing row, forward
drops it, since no
+ // later left row can match it, and backward stops there and keeps it for
the next left row.
+ val (checkKeptRow, onPass, onFail) = direction match {
+ case Forward =>
+ val check =
+ s"""
+ |if ($cursorBest != null) {
+ | if ($asOfHolds($leftRow, $cursorBest)) return $cursorBest;
+ | $cursorBest = null;
+ |}
+ """.stripMargin
+ (check, s"return $cursorBest;", s"$rightPeek = $nextRight();")
+ case _ =>
+ ("", "", s"return $cursorBest;")
+ }
+
+ val funcName = ctx.freshName("findWithCursor")
+ val func = ctx.addNewFunction(funcName,
+ s"""
+ |private UnsafeRow $funcName(InternalRow $leftRow) {
+ | int comp = 0;
+ | $readLeftKeys
+ | ${onNewGroup(startGroup)}
+ | // Like the buffered scan, a group with no right rows never
evaluates the left as-of
+ | // key, which can fail at runtime, for example on an invalid cast
under ANSI.
+ | if (!$groupHasRight) return null;
+ | ${leftAsOfKey.code}
+ | // A NULL left as-of key matches nothing. It must not move the
cursor.
+ | if (${leftAsOfKey.isNull}) return null;
+ | $checkKeptRow
+ | while ($rightPeek != null) {
+ | $compareRightKeys
+ | // The group's right rows end at the first row of a later group.
+ | if (comp != 0) return $cursorBest;
+ | ${rightAsOfKey.code}
+ | if (${rightAsOfKey.isNull}) {
+ | $rightPeek = $nextRight();
+ | continue;
+ | }
+ | if ($asOfHolds($leftRow, $rightPeek)) {
+ | // The next right row can overwrite `rightPeek`, so keep a
copy.
+ | $cursorBest = $copyToBest($rightPeek);
+ | $rightPeek = $nextRight();
+ | $onPass
+ | } else {
+ | $onFail
+ | }
+ | }
+ | return $cursorBest;
+ |}
+ """.stripMargin, inlineToOuterClass = true)
+ (func, s"""
+ |${metricTerm(ctx, "numAsOfCursorTasks")}.add(1);
+ |$startOnlyGroup
+ """.stripMargin)
+ }
+
+ /**
+ * Generates the buffered scan of [[SortMergeAsOfJoinScanner]]. Each right
group stays in an
+ * [[ExternalAppendOnlyUnsafeRowArray]], which can spill, and is scanned for
every left row.
+ * Returns the function that finds the best right row for a left row, and
the code that
+ * starts the scan.
+ */
+ private def genBufferedScan(
+ ctx: CodegenContext,
+ rightInput: String,
+ rightPeek: String,
+ nextRight: String): (String, String) = {
+ val clsName = classOf[ExternalAppendOnlyUnsafeRowArray].getName
+ val inMemoryThreshold = conf.sortMergeJoinExecBufferInMemoryThreshold
+ val sizeInBytesSpillThreshold =
conf.sortMergeJoinExecBufferSpillSizeThreshold
+ val spillThreshold = conf.sortMergeJoinExecBufferSpillThreshold
+ // Inline mutable state since not many join operations in a task
+ val group = ctx.addMutableState(clsName, "rightGroup",
+ v => s"$v = new $clsName($inMemoryThreshold,
${sizeInBytesSpillThreshold}L, " +
+ s"$spillThreshold, ${sizeInBytesSpillThreshold}L);",
+ forceInline = true)
+ val leftRow = ctx.freshName("leftRow")
+
+ val fillGroup = if (leftKeys.isEmpty) {
+ val allBuffered = ctx.addMutableState(CodeGenerator.JAVA_BOOLEAN,
"allRightBuffered")
+ s"""
+ |if (!$allBuffered) {
+ | // No equi-keys, so the whole right side is one group.
+ | $allBuffered = true;
+ | if ($rightPeek != null) {
+ | $group.add($rightPeek);
+ | $rightPeek = null;
+ | }
+ | while ($rightInput.hasNext()) {
+ | $group.add((UnsafeRow) $rightInput.next());
+ | }
+ |}
+ """.stripMargin
+ } else {
+ val (readLeftKeys, compareRightKeys, onNewGroup) =
+ genEquiKeys(ctx, leftRow, rightPeek)
+ val bufferGroup =
+ s"""
+ |$group.clear();
+ |while ($rightPeek != null) {
+ | $compareRightKeys
+ | if (comp > 0) {
+ | $rightPeek = $nextRight();
+ | continue;
+ | }
+ | if (comp < 0) break;
+ | $group.add($rightPeek);
+ | $rightPeek = $nextRight();
+ |}
+ """.stripMargin
+ s"""
+ |$readLeftKeys
+ |${onNewGroup(bufferGroup)}
+ """.stripMargin
+ }
+
+ val asOfHolds = genConditionFunction(ctx, asOfCondition, "asOfHolds")
+ val rightRow = ctx.freshName("rightRow")
+ val residualHolds = condition
+ .map(cond => s"${genConditionFunction(ctx, cond,
"residualHolds")}($leftRow, $rightRow)")
+ .getOrElse("true")
+ val needsCopy = ctx.freshName("needsCopy")
+ val best = ctx.freshName("best")
+ // A spilled group reuses one row on every next(), so a kept match must be
copied.
+ val retained = s"($needsCopy ? $rightRow.copy() : $rightRow)"
+ // Backward keeps the last passing row, and forward returns the first.
Once the as-of
+ // condition has held, the first row that fails it ends the scan.
+ val (onMatch, onPastMatches, noMoreRows) = direction match {
+ case Forward => (s"return $retained;", "return null;", "return null;")
+ case _ => (s"$best = $retained;", s"return $best;", s"return $best;")
+ }
+ val iter = ctx.freshName("iter")
+ val asOfSeen = ctx.freshName("asOfSeen")
+
+ val funcName = ctx.freshName("findInGroup")
+ val func = ctx.addNewFunction(funcName,
+ s"""
+ |private UnsafeRow $funcName(InternalRow $leftRow) {
+ | int comp = 0;
+ | $fillGroup
+ | scala.collection.Iterator<UnsafeRow> $iter =
$group.generateIterator();
+ | boolean $needsCopy = $group.isSpillBacked();
+ | boolean $asOfSeen = false;
+ | UnsafeRow $best = null;
+ | while ($iter.hasNext()) {
+ | UnsafeRow $rightRow = (UnsafeRow) $iter.next();
+ | if ($asOfHolds($leftRow, $rightRow)) {
+ | $asOfSeen = true;
+ | if ($residualHolds) {
+ | $onMatch
+ | }
+ | } else if ($asOfSeen) {
+ | $onPastMatches
+ | }
+ | }
+ | $noMoreRows
+ |}
+ """.stripMargin, inlineToOuterClass = true)
+ val spillHook =
s"${classOf[JoinHelper].getName}.recordSpillSizeOnTaskCompletion(" +
+ s"$group, ${metricTerm(ctx, "spillSize")});"
+ (func, spillHook)
+ }
+
+ /**
+ * Generates the equi-key code of a scan, as three parts:
+ * - read the left keys, and return null for a NULL key, which matches
nothing;
+ * - set `comp` to the order of the left keys against the keys of
`rightPeek`, where a NULL
+ * right key sorts before any value, as in the interpreted scan;
+ * - run the given code when the left keys start a new group.
+ * With no equi-keys all three are empty, so `comp` stays 0 and there is one
group.
+ */
+ private def genEquiKeys(
+ ctx: CodegenContext,
+ leftRow: String,
+ rightPeek: String): (String, String, String => String) = {
+ if (leftKeys.isEmpty) return ("", "", _ => "")
+ val leftKeyVars = createJoinKey(ctx, leftRow, leftKeys, left.output)
+ val rightKeyVars = createJoinKey(ctx, rightPeek, rightKeys, right.output)
+ // The keys of the current left group, kept across calls.
+ val groupKeyVars = copyKeys(ctx, leftKeyVars)
+ val groupValid = ctx.addMutableState(CodeGenerator.JAVA_BOOLEAN,
"groupValid")
+
+ val readLeftKeys =
+ s"""
+ |${leftKeyVars.map(_.code).mkString("\n")}
+ |${anyNull(leftKeyVars).map(isNull => s"if ($isNull) return
null;").getOrElse("")}
+ """.stripMargin
+ // A NULL right key is compared, not skipped, so the scan stops where the
interpreted one does.
+ val compareRightKeys =
+ s"""
+ |${rightKeyVars.map(_.code).mkString("\n")}
+ |${genRightKeyComparison(ctx, leftKeyVars, rightKeyVars)}
+ """.stripMargin
+ val newGroup = ctx.freshName("newGroup")
+ val onNewGroup = (code: String) =>
+ s"""
+ |boolean $newGroup = !$groupValid;
+ |if ($groupValid) {
+ | ${genComparison(ctx, leftKeyVars, groupKeyVars)}
+ | $newGroup = comp != 0;
+ |}
+ |if ($newGroup) {
+ | ${groupKeyVars.map(_.code).mkString("\n")}
+ | $groupValid = true;
+ | $code
+ |}
+ """.stripMargin
+ (readLeftKeys, compareRightKeys, onNewGroup)
+ }
+
+ /** The Java check that any of `keys` is NULL, or None when no key can be
NULL. */
+ private def anyNull(keys: Seq[ExprCode]): Option[String] = {
+ val isNulls = keys.map(_.isNull).filter(_ != FalseLiteral)
+ if (isNulls.isEmpty) None else Some(isNulls.mkString(" || "))
+ }
+
+ /**
+ * Generates code that sets `comp` to the order of the left keys against the
right keys, key
+ * by key. The left keys are never NULL here. A NULL right key sorts before
any value, as in
+ * the interpreted ordering, so it compares as smaller.
+ */
+ private def genRightKeyComparison(
+ ctx: CodegenContext,
+ leftVars: Seq[ExprCode],
+ rightVars: Seq[ExprCode]): String = {
+ leftVars.zip(rightVars).zipWithIndex.map { case ((l, r), i) =>
+ val compare = ctx.genComp(leftKeys(i).dataType, l.value, r.value)
+ val withNull = if (r.isNull == FalseLiteral) compare else s"(${r.isNull}
? 1 : ($compare))"
Review Comment:
Agreed, #60239 is a good backport candidate. branch-4.x and branch-4.3, and
so the 4.3.0 release, still build the interpreted equi-key ordering from the
left keys' nullability, so they return wrong rows or fail for a NOT NULL left
key against a NULL right key. branch-4.2 and older don't have the sort-merge
ASOF join. Let's pick the target branches on #60239 when it merges.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4510492783","thread_id":"inline:4510492783","verdict_sha256":"b0c40d59136ce3edbb0e434ef269775461cbf0e6ecdef05caab138bf748bcc6f"}
-->
--
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]