LukaZdravic commented on code in PR #60227:
URL: https://github.com/apache/spark/pull/60227#discussion_r4514610318
##########
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:
Added a TODO comment above 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]