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


##########
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()) {

Review Comment:
   **Blocking (P1):** With a LIMIT that is not the plan root above a backward 
or forward ASOF join, for example `INSERT INTO t SELECT ... ASOF JOIN ... LIMIT 
10`, a LIMIT in a subquery, or `df.limit(10).write`, the 
`LocalLimitExec`/`GlobalLimitExec` now fuses into this join's codegen stage, 
but this loop never checks the limit. Once the limit is reached, 
`BaseLimitExec.doConsume` only skips each row, nothing is appended, 
`shouldStop()` stays false, and the join keeps calling the match function for 
every remaining left row of the partition.
   
   On the base branch the join sat behind an `InputAdapter`, whose loop is 
`while ($limitNotReachedCond $input.hasNext())`, so it stopped after `limit` 
rows. Now the extra work grows with the partition: linear for the cursor scan, 
and one rescan of the right group per left row for the buffered scan (up to O(N 
* M) with no equi-keys, rereading spilled buffers). `numOutputRows` also counts 
the rows the limit drops. A top-level `SELECT ... LIMIT n` is not affected, 
because `CollectLimitExec` pulls lazily.
   
   `CodegenSupport.limitNotReachedChecks` asks the data-producing loop to carry 
these checks, and this loop is the stage's data-producing loop. The fix is 
`override protected def canCheckLimitNotReached: Boolean = true` plus `while 
($limitNotReachedCond $leftInput.hasNext())`. The check reads the limit's own 
counter, so it drops no row the limit keeps. A test with a LIMIT fused above 
the join that checks the join's `numOutputRows` would catch this.
   
   **Verification:**
   - **Regression:** A LIMIT n that is not the plan root, such as a LIMIT in a 
subquery that is then aggregated, over a generated backward cursor-scan ASOF 
join and over a generated buffered-scan join with a tolerance, on one partition 
with more than n matching left rows, returns the same rows as with the join's 
codegen off, and the join's number-of-output-rows metric is n rather than the 
partition's left row count.
   - **Compatibility:** A top-level LIMIT, and the same joins without any 
LIMIT, return the same rows and output-row metrics as before the change.



##########
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:
   **Non-blocking (P2):** This compares a NULL right equi-key as smaller than 
any left key, which matches the right child's ascending NULLS FIRST sort. The 
comments here and at lines 420-421 and 441 say the interpreted scan behaves the 
same way, but it does not. `SortMergeAsOfJoinScanner.equiKeyOrdering` builds 
its key attributes from the left keys' nullability (`key.nullable`). When a 
left key is NOT NULL, `GenerateOrdering` emits no null check, so a NULL right 
key from `rightKeyProj` is compared as its zeroed slot: 0 for numbers, and a 
null `UTF8String` for strings. `advanceRightTo`, `bufferRightGroup` and 
`compareToRightPeek` all use that ordering, and no optimizer rule filters out 
NULL right keys before the join.
   
   Reading the code, with a NOT NULL left key `t.k` and right rows `(NULL, 
...)` then `(-1, ...)`, the interpreted scan stops at the NULL row for left key 
-1 and returns no match. For left key 0 it matches the NULL-key row, and with 
string keys it throws a NullPointerException. This wrong result already exists 
on the base branch, and the generated path fixes it. But the interpreted path 
still runs for nearest joins, with the new flag or whole-stage codegen off, on 
codegen fallback, and past `spark.sql.codegen.maxFields`, so the same query now 
returns different rows depending on whether codegen applies.
   
   I'd fix it in the interpreted ordering, which also covers nearest joins: 
build its attributes as nullable when either side's key is nullable 
(`key.nullable || rightKeys(i).nullable`). Left keys are already NULL-checked 
before any compare. Please also correct the parity comments, and add a test 
with a NOT NULL left key and a nullable right key (integer left keys 0 and -1, 
plus a string key) through `checkWithAsOfJoinCodegenOffAndOn` and as a nearest 
join.
   
   **Verification:**
   - **Regression:** Inner backward ASOF joins with a NOT NULL integer left key 
of 0, and of -1, against a right side whose NULL-key row sorts before the 
matching key, return no row for key 0 and the matching right row for key -1, 
with the join's codegen off and on and with the cursor scan off and on.
   - **Regression:** The same join shape on a STRING equi-key returns the 
matching right row instead of failing, with the join's codegen off and on.
   - **Behavior:** A nearest ASOF join over the same inputs never pairs a left 
row with a right row whose equi-key is NULL.
   - **Compatibility:** Joins whose equi-keys are nullable on both sides, or 
NOT NULL on both sides, return the same rows as before the change.



##########
sql/core/src/test/scala/org/apache/spark/sql/AsOfJoinSortMergeSQLSuite.scala:
##########
@@ -69,9 +70,54 @@ class AsOfJoinSortMergeSQLSuite extends QueryTest
   }
 
   private def checkSortMergeAsOf(query: => DataFrame, expected: Seq[Row]): 
Unit = {
-    val df = query
-    assertUsesSortMergeAsOfJoin(df)
-    checkAnswer(df, expected)
+    checkWithAsOfJoinCodegenOffAndOn(query) { df =>
+      assertUsesSortMergeAsOfJoin(df)
+      checkAnswer(df, expected)
+    }
+  }
+
+  /**
+   * Runs `check` on `query` with the ASOF join codegen off, then on, and 
asserts which ASOF
+   * joins ran generated. A DataFrame keeps the plan it got first, so the run 
with the codegen
+   * off checks a new DataFrame for the same query. The run with it on, the 
default, checks
+   * `query` itself, which the test may check again afterwards.
+   */
+  private def checkWithAsOfJoinCodegenOffAndOn(query: => DataFrame)(

Review Comment:
   **Nit (P3):** With the new flag on by default, checks that bypass this 
helper now run only the generated scan for backward and forward joins, although 
the interpreted scan is still what runs with the flag or whole-stage codegen 
off and on codegen fallback. In this suite that includes the 
`QueryTest.checkAnswer(..., checkToRDD = false)` checks at lines 279, 334, 355, 
386 and 416, the ANSI test 'cursor scan: a failing as-of side fails the query 
when its key has right rows' (`intercept` at line 1871), and the randomized 
oracle (`checkAnswer` at line 1939), which loops only over the cursor-scan 
setting. In `SortMergeAsOfJoinSuite`, `checkCursorScan` and direct checks such 
as 'null equi-keys with EqualTo condition', 'empty left side', 'empty right 
side' and 'residual condition via joinExprs' also run once.
   
   The PR description says every check in this suite runs with the codegen off 
and on. Could you route these through `checkWithAsOfJoinCodegenOffAndOn`, or a 
`Seq(false, true)` loop as `checkAnswerAndSpill` does? The random oracle 
matters most, because it is the only randomized check of whether a scan drops, 
mixes up or reuses rows.
   
   **Verification:**
   - **Inspection:** Every backward or forward ASOF check in the SQL and 
DataFrame join suites either runs in both codegen modes or states why one mode 
is enough.
   - **Behavior:** With the join's codegen off, the randomized oracle, the ANSI 
failing-side test, and the null equi-key, empty-side, residual-condition and 
reversed-key checks pass and confirm the join did not run generated.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -1694,6 +1695,7 @@ object UnionExec {
   def isKnownMultiInputRDDCodegen(p: SparkPlan): Boolean = p match {
     case _: SortMergeJoinExec => true
     case _: ShuffledHashJoinExec => true
+    case _: SortMergeAsOfJoinExec => true

Review Comment:
   **Blocking (P1):** This matches every `SortMergeAsOfJoinExec` by type, but 
only a generated backward or forward join returns two RDDs from `inputRDDs()`. 
A nearest join, or any ASOF join with 
`spark.sql.codegen.join.sortMergeAsOfJoin.enabled=false`, has `supportCodegen = 
false`, so `CollapseCodegenStages` wraps it in an `InputAdapter` and the union 
child contributes one RDD, exactly as on the base branch. The gate checks 
`children.exists(_.exists(UnionExec.isKnownMultiInputRDDCodegen))`, so such a 
union now reports `multi-rdd-child` and loses the whole-stage fusion it had on 
the base branch and in 4.3.0.
   
   Every union branch then ends its own stage and materializes its rows for the 
parent to read back, which is extra CPU for every row with no codegen gain in 
return. `UnionBenchmark-results.txt` shows the fused union 1.1x to 4.2x faster 
on plain unions. It also means turning the new flag off does not restore the 
base-branch plan.
   
   ```suggestion
       case j: SortMergeAsOfJoinExec => j.supportCodegen
   ```
   
   This still lists every join that can generate two RDDs. When another check, 
such as `maxFields`, keeps a supporting join out of a stage, the join stays 
listed and the union just does not fuse. Could you also add `UnionCodegenSuite` 
cases with a nearest join and with the flag off that assert the union still 
fuses? The new test's comment says the union falls back "for that child", but 
the test asserts that no union fuses.
   
   **Verification:**
   - **Regression:** A union over a nearest ASOF join, and a union over a 
backward ASOF join with the join's codegen flag off, each run in a fused union 
codegen stage and return the same rows as with union codegen off.
   - **Compatibility:** A union over a generated backward ASOF join still does 
not fuse and returns correct rows.



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