This is an automated email from the ASF dual-hosted git repository.
cloud-fan pushed a commit to branch branch-4.x
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/branch-4.x by this push:
new a129836cb4aa [SPARK-61201][SQL] Add whole-stage codegen to the
sort-merge ASOF join
a129836cb4aa is described below
commit a129836cb4aae88b4fb28fc33d7c65edbe3f0f64
Author: Luka Zdravić <[email protected]>
AuthorDate: Wed Nov 11 00:54:50 2026 +0000
[SPARK-61201][SQL] Add whole-stage codegen to the sort-merge ASOF join
### What changes were proposed in this pull request?
`SortMergeAsOfJoinExec` gets whole-stage codegen for backward and forward
joins. The generated code runs the same two scans as
`SortMergeAsOfJoinScanner`: the cursor scan, and the buffered scan of each
right-side group. It compares the ON keys, checks the MATCH_CONDITION and the
residual ON condition inline, and passes the output columns straight to the
parent.
- The right-side buffer stays an `ExternalAppendOnlyUnsafeRowArray`, which
can spill, as in `SortMergeJoinExec`. Nearest joins keep the interpreted scan.
- The generated join loop checks a LIMIT fused above it, as the loop of an
`InputAdapter` does, so the join still stops early under a LIMIT.
- The join's children get their own codegen stages.
`UnionExec.isKnownMultiInputRDDCodegen` lists the join whenever it may generate
code (a backward or forward join planned with this codegen on), so a union over
a nearest join, or with this codegen off, still fuses.
- The new internal config
`spark.sql.codegen.join.sortMergeAsOfJoin.enabled` (default `true`) turns it
off. The planner records it in the join (`codegenEnabled`), so the codegen
stages and the union check give the same answer even if the config changes
before the query runs.
- The generated buffered scan closes the group's iterator when it returns,
so the spill files it did not read close right away. #60240 (SPARK-61248) does
the same for the interpreted scan.
- The join gets its own variable prefix in generated code. A skewed join is
named `SortMergeAsOfJoin(skew=true)`, which is not a valid Java name, so
without it the generated code of a skewed join does not compile.
- `createJoinKey`, `copyKeys` and `genComparison` move unchanged from
`SortMergeJoinExec` to `JoinCodegenSupport`.
### Why are the changes needed?
The interpreted scan pays general costs on every row, and the join ends the
codegen stage above it, so each output row is built and handed over one by one.
Local benchmark against master (best of 5 runs; nearest best of 10;
`local[1]`, JDK 25, AQE off; times include generating and sorting both inputs):
| Case | master (ms) | this PR (ms) |
|---|---|---|
| backward, cursor, 100 keys, 2M rows | 1636 | 1305 (1.25x) |
| forward, cursor, 100 keys, 2M rows | 1618 | 1277 (1.27x) |
| LEFT OUTER backward, cursor, 100 keys, 2M rows | 1663 | 1316 (1.26x) |
| backward, cursor, no ON key, 2M rows | 675 | 447 (1.51x) |
| backward, cursor, 200K keys of 10 rows | 1308 | 974 (1.34x) |
| backward, cursor, STRING key, 100 keys, 2M rows | 2851 | 1963 (1.45x) |
| backward, buffered (tolerance), 400K rows | 1172 | 539 (2.17x) |
| backward, buffered (extra ON condition), 400K rows | 844 | 455 (1.85x) |
| nearest (not generated), 400K rows | 704 | 669 (same) |
### Does this PR introduce _any_ user-facing change?
No. The codegen returns the same rows and raises the same errors as the
interpreted scan.
### How was this patch tested?
The checks in `AsOfJoinSortMergeSQLSuite` run with this codegen off and on,
and assert which joins were generated. That includes the randomized comparison
with a plain join, the NOT NULL left key checks, the ANSI error checks, and the
`checkToRDD = false` checks. In `SortMergeAsOfJoinSuite`, every backward and
forward check that runs a sort-merge ASOF join runs both ways too, except the
two spill-file tests, which test the generated scan on purpose. So do the
sort-merge cases of the n [...]
New tests: a NULL right ON key, a collated ON key, a LIMIT fused into the
join's stage (the join stops after 5 output rows), a generated backward and
forward scan over a spilled group that must not leave its spill files open, a
`WholeStageCodegenSuite` case, a skewed join whose generated code must compile,
and `UnionCodegenSuite` cases: a union over a generated join does not fuse, one
over a nearest join or with this codegen off does, and changing the config
between planning and runni [...]
Removing any of these fails at least one test: the cursor's empty-group
check, its best-row copy, its group reset, the NULL right-key compare, the
LIMIT check, the union list entry or its codegen condition, the recorded
config, the close of the buffered scan's iterator, and the join's variable
prefix.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code
This pull request and its description were written by Isaac.
Closes #60227 from LukaZdravic/asof-jvm-codegen.
Authored-by: Luka Zdravić <[email protected]>
Signed-off-by: Wenchen Fan <[email protected]>
(cherry picked from commit 05f050aace098fb930cbabe9d64de4e2cbfb066a)
Signed-off-by: Wenchen Fan <[email protected]>
skip-checks: true
---
.../org/apache/spark/sql/internal/SQLConf.scala | 9 +
.../spark/sql/execution/SparkStrategies.scala | 3 +-
.../sql/execution/WholeStageCodegenExec.scala | 8 +-
.../sql/execution/basicPhysicalOperators.scala | 4 +-
.../sql/execution/joins/JoinCodegenSupport.scala | 41 +-
.../execution/joins/SortMergeAsOfJoinExec.scala | 413 +++++++++++++++++-
.../sql/execution/joins/SortMergeJoinExec.scala | 37 --
.../sql-tests/inputs/join-asof-containers.sql | 5 +
.../sql-tests/inputs/join-asof-context.sql | 5 +
.../sql-tests/inputs/join-asof-corners.sql | 5 +
.../sql-tests/inputs/join-asof-crossfeature.sql | 5 +
.../sql-tests/inputs/join-asof-datatypes.sql | 5 +
.../sql-tests/inputs/join-asof-errors.sql | 5 +
.../sql-tests/inputs/join-asof-expressions.sql | 5 +
.../sql-tests/inputs/join-asof-grammar.sql | 5 +
.../sql-tests/inputs/join-asof-semantics.sql | 5 +
.../spark/sql/AsOfJoinSortMergeSQLSuite.scala | 199 +++++++--
.../apache/spark/sql/SortMergeAsOfJoinSuite.scala | 475 +++++++++++++--------
.../spark/sql/TimestampNanosJoinSuiteBase.scala | 47 +-
.../spark/sql/execution/UnionCodegenSuite.scala | 84 ++++
.../sql/execution/WholeStageCodegenSuite.scala | 96 ++++-
.../sql/execution/metric/SQLMetricsSuite.scala | 32 +-
22 files changed, 1190 insertions(+), 303 deletions(-)
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
index a732fd4ec01d..b5268c92ea7f 100644
--- a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
@@ -4496,6 +4496,15 @@ object SQLConf {
.booleanConf
.createWithDefault(true)
+ val ENABLE_SORT_MERGE_AS_OF_JOIN_CODEGEN =
+ buildConf("spark.sql.codegen.join.sortMergeAsOfJoin.enabled")
+ .internal()
+ .doc("When true, enable code-gen for backward and forward sort-merge
AS-OF join.")
+ .version("4.4.0")
+ .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
+ .booleanConf
+ .createWithDefault(true)
+
val MAX_NESTED_VIEW_DEPTH =
buildConf("spark.sql.view.maxNestedViewDepth")
.internal()
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala
index 647fb3a3b819..f4de8cf89bcf 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala
@@ -401,7 +401,8 @@ abstract class SparkStrategies extends
QueryPlanner[SparkPlan] {
joinType = j.joinType,
condition = residual,
left = planLater(j.left),
- right = planLater(j.right)
+ right = planLater(j.right),
+ codegenEnabled =
conf.getConf(SQLConf.ENABLE_SORT_MERGE_AS_OF_JOIN_CODEGEN)
) :: Nil
case _ => Nil
}
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/WholeStageCodegenExec.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/WholeStageCodegenExec.scala
index cc46d3bdecc0..a91442cd858c 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/WholeStageCodegenExec.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/WholeStageCodegenExec.scala
@@ -38,7 +38,7 @@ import
org.apache.spark.sql.catalyst.plans.physical.Partitioning
import org.apache.spark.sql.catalyst.rules.Rule
import org.apache.spark.sql.execution.aggregate.{HashAggregateExec,
SortAggregateExec}
import org.apache.spark.sql.execution.columnar.InMemoryTableScanExec
-import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec,
BroadcastNestedLoopJoinExec, ShuffledHashJoinExec, SortMergeJoinExec}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec,
BroadcastNestedLoopJoinExec, ShuffledHashJoinExec, SortMergeAsOfJoinExec,
SortMergeJoinExec}
import org.apache.spark.sql.execution.metric.SQLMetrics
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types._
@@ -57,6 +57,8 @@ trait CodegenSupport extends SparkPlan {
case _: BroadcastHashJoinExec => "bhj"
case _: ShuffledHashJoinExec => "shj"
case _: SortMergeJoinExec => "smj"
+ // A skewed join is named "SortMergeAsOfJoin(skew=true)", which is not a
valid Java name.
+ case _: SortMergeAsOfJoinExec => "smaj"
case _: BroadcastNestedLoopJoinExec => "bnlj"
case _: RDDScanExec => "rdd"
case _: OneRowRelationExec => "orr"
@@ -1230,6 +1232,10 @@ case class CollapseCodegenStages(
// The children of ShuffledHashJoin should do codegen separately.
j.withNewChildren(j.children.map(
child => InputAdapter(insertWholeStageCodegen(child))))
+ case j: SortMergeAsOfJoinExec =>
+ // The children of SortMergeAsOfJoin should do codegen separately.
+ j.withNewChildren(j.children.map(
+ child => InputAdapter(insertWholeStageCodegen(child))))
case p => p.withNewChildren(p.children.map(insertInputAdapter))
}
}
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala
index ddb4438d884f..55f425dddfbf 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala
@@ -36,7 +36,8 @@ import org.apache.spark.sql.catalyst.optimizer.CollapseProject
import org.apache.spark.sql.catalyst.plans.logical.Sample
import org.apache.spark.sql.catalyst.plans.physical._
import org.apache.spark.sql.catalyst.trees.TreeNodeTag
-import org.apache.spark.sql.execution.joins.{ShuffledHashJoinExec,
SortMergeJoinExec}
+import org.apache.spark.sql.execution.joins.{ShuffledHashJoinExec,
SortMergeAsOfJoinExec,
+ SortMergeJoinExec}
import org.apache.spark.sql.execution.metric.{SQLMetric, SQLMetrics}
import org.apache.spark.sql.internal.{SQLConf, StaticSQLConf}
import org.apache.spark.sql.types.{LongType, StructType}
@@ -1700,6 +1701,7 @@ object UnionExec {
def isKnownMultiInputRDDCodegen(p: SparkPlan): Boolean = p match {
case _: SortMergeJoinExec => true
case _: ShuffledHashJoinExec => true
+ case j: SortMergeAsOfJoinExec => j.supportCodegen
case _ => false
}
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/JoinCodegenSupport.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/JoinCodegenSupport.scala
index 056ddca2072d..dcf33fa3cdd2 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/JoinCodegenSupport.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/JoinCodegenSupport.scala
@@ -17,7 +17,7 @@
package org.apache.spark.sql.execution.joins
-import org.apache.spark.sql.catalyst.expressions.{BindReferences,
BoundReference, Expression}
+import org.apache.spark.sql.catalyst.expressions.{Attribute, BindReferences,
BoundReference, Expression}
import org.apache.spark.sql.catalyst.expressions.codegen._
import org.apache.spark.sql.catalyst.expressions.codegen.Block._
import org.apache.spark.sql.execution.{CodegenSupport, SparkPlan}
@@ -27,6 +27,45 @@ import org.apache.spark.sql.execution.{CodegenSupport,
SparkPlan}
*/
trait JoinCodegenSupport extends CodegenSupport with BaseJoinExec {
+ /** Generates the code for join keys `keys` read from `row`, whose columns
are `input`. */
+ protected def createJoinKey(
+ ctx: CodegenContext,
+ row: String,
+ keys: Seq[Expression],
+ input: Seq[Attribute]): Seq[ExprCode] = {
+ ctx.INPUT_ROW = row
+ ctx.currentVars = null
+ BindReferences.bindReferences(keys, input).map(_.genCode(ctx))
+ }
+
+ /** Copies join keys into class members, so they can be used in a later
function call. */
+ protected def copyKeys(ctx: CodegenContext, vars: Seq[ExprCode]):
Seq[ExprCode] = {
+ vars.zipWithIndex.map { case (ev, i) =>
+ ctx.addBufferedState(leftKeys(i).dataType, "value", ev.value)
+ }
+ }
+
+ /** Generates the code that sets `comp` to the order of the join keys `a`
and `b`. */
+ protected def genComparison(ctx: CodegenContext, a: Seq[ExprCode], b:
Seq[ExprCode]): String = {
+ // The first key compare always runs, so emit it unguarded. Each
subsequent key compare runs
+ // only when previous keys were equal (comp == 0).
+ val pairs = a.zip(b).zipWithIndex
+ val firstCompare = pairs.headOption.map { case ((l, r), i) =>
+ s"comp = ${ctx.genComp(leftKeys(i).dataType, l.value, r.value)};"
+ }.getOrElse("comp = 0;")
+ val restCompares = pairs.drop(1).map { case ((l, r), i) =>
+ s"""
+ |if (comp == 0) {
+ | comp = ${ctx.genComp(leftKeys(i).dataType, l.value, r.value)};
+ |}
+ """.stripMargin.trim
+ }
+ s"""
+ |$firstCompare
+ |${restCompares.mkString("\n")}
+ """.stripMargin
+ }
+
/**
* Generate the (non-equi) condition used to filter joined rows.
* This is used in Inner, Left Semi, Left Anti and Full Outer joins.
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinExec.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinExec.scala
index eb866d37d4ff..192133363b10 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinExec.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinExec.scala
@@ -25,7 +25,8 @@ import org.apache.spark.rdd.RDD
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.catalyst.expressions.BindReferences.bindReference
-import org.apache.spark.sql.catalyst.expressions.codegen.{CodegenContext,
GeneratePredicate}
+import org.apache.spark.sql.catalyst.expressions.codegen.{CodegenContext,
CodeGenerator, ExprCode,
+ FalseLiteral, GeneratePredicate}
import org.apache.spark.sql.catalyst.plans._
import org.apache.spark.sql.catalyst.plans.logical.AsOfJoin
import org.apache.spark.sql.catalyst.plans.physical._
@@ -49,6 +50,12 @@ import org.apache.spark.unsafe.types.TimestampNanosVal
* [[SortMergeAsOfJoinScanner.supportsCursorScan]]) read the right side once
* and buffer nothing.
*
+ * Backward and forward joins support whole-stage codegen. The generated code
runs the cursor
+ * scan or the buffered scan and checks the conditions. The right-side buffer
stays a Scala
+ * object, since it can spill to disk. Nearest joins keep the interpreted
scan. `codegenEnabled`
+ * is the codegen config as it was when the join was planned. A join built by
hand, not by the
+ * planner, gets `false`.
+ *
* Note: When there are no equi-keys, both sides are collected into a
* single partition (AllTuples) and, without a cursor scan, the entire
* right side is buffered.
@@ -64,6 +71,7 @@ case class SortMergeAsOfJoinExec(
condition: Option[Expression],
left: SparkPlan,
right: SparkPlan,
+ codegenEnabled: Boolean = false,
isSkewJoin: Boolean = false) extends ShuffledJoin {
// The sides may have different key counts: each side is sorted on its own,
and only the
@@ -79,14 +87,6 @@ case class SortMergeAsOfJoinExec(
"spillSize" -> SQLMetrics.createSizeMetric(sparkContext, "spill size"),
"numAsOfCursorTasks" -> SQLMetrics.createMetric(sparkContext, "number of
cursor scan tasks"))
- override def supportCodegen: Boolean = false
-
- // Codegen stubs (not called since supportCodegen = false)
- override def inputRDDs(): Seq[RDD[InternalRow]] =
- left.execute() :: right.execute() :: Nil
- override protected def doProduce(ctx: CodegenContext): String =
- throw SparkException.internalError(s"$nodeName does not support codegen")
-
override def requiredChildDistribution: Seq[Distribution] = {
if (leftKeys.isEmpty) {
AllTuples :: AllTuples :: Nil
@@ -112,9 +112,7 @@ case class SortMergeAsOfJoinExec(
val sizeInBytesSpillThreshold =
conf.sortMergeJoinExecBufferSpillSizeThreshold
val spillThreshold = conf.sortMergeJoinExecBufferSpillThreshold
val numAsOfCursorTasks = longMetric("numAsOfCursorTasks")
- val useCursorScan = conf.sortMergeAsOfJoinCursorScanEnabled &&
- SortMergeAsOfJoinScanner.supportsCursorScan(
- direction, asOfCondition, condition, leftSortExprs, rightSortExprs)
+ val useCursorScan = cursorScanEnabled
left.execute().zipPartitions(right.execute()) { (leftIter, rightIter) =>
val scanner = new SortMergeAsOfJoinScanner(
@@ -133,6 +131,397 @@ 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
+ // codegen config is read once, when the join is planned.
+ override def supportCodegen: Boolean = direction != Nearest && codegenEnabled
+
+ // ShuffledJoin already hides `isSkewJoin`, the last field. This also hides
`codegenEnabled`,
+ // the field before it, 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, which reads the right side once and never
steps back. The left
+ * rows of a group come in ascending as-of key order, so backward keeps its
best row for the
+ * next left row, and forward drops each failing row. 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. 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();
+ | }
+ | }
+ |}
+ """.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;
+ * - 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. It sorts before any value.
+ 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, 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))"
+ s"if (comp == 0) comp = $withNull;"
+ }.mkString("comp = 0;\n", "\n", "")
+ }
+
+ /** Generates a function that tells whether `cond` is TRUE for a left row
and a right row. */
+ private def genConditionFunction(
+ ctx: CodegenContext,
+ cond: Expression,
+ name: String): String = {
+ val leftRow = ctx.freshName("leftRow")
+ val rightRow = ctx.freshName("rightRow")
+ val leftVars = genOneSideJoinVars(ctx, leftRow, left, setDefaultValue =
false)
+ val (_, checkCondition, _) =
+ getJoinCondition(ctx, cond, leftVars, left, right, Some(rightRow))
+ val funcName = ctx.freshName(name)
+ ctx.addNewFunction(funcName,
+ s"""
+ |private boolean $funcName(InternalRow $leftRow, InternalRow
$rightRow) {
+ | $checkCondition {
+ | return true;
+ | }
+ | return false;
+ |}
+ """.stripMargin)
+ }
+
override protected def withNewChildrenInternal(
newLeft: SparkPlan, newRight: SparkPlan): SortMergeAsOfJoinExec = {
copy(left = newLeft, right = newRight)
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeJoinExec.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeJoinExec.scala
index 88ee2508384a..7f375b1089ed 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeJoinExec.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeJoinExec.scala
@@ -23,7 +23,6 @@ import org.apache.spark.TaskContext
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions._
-import org.apache.spark.sql.catalyst.expressions.BindReferences.bindReferences
import org.apache.spark.sql.catalyst.expressions.codegen._
import org.apache.spark.sql.catalyst.expressions.codegen.Block._
import org.apache.spark.sql.catalyst.plans._
@@ -187,42 +186,6 @@ case class SortMergeJoinExec(
streamedPlan.execute() :: bufferedPlan.execute() :: Nil
}
- private def createJoinKey(
- ctx: CodegenContext,
- row: String,
- keys: Seq[Expression],
- input: Seq[Attribute]): Seq[ExprCode] = {
- ctx.INPUT_ROW = row
- ctx.currentVars = null
- bindReferences(keys, input).map(_.genCode(ctx))
- }
-
- private def copyKeys(ctx: CodegenContext, vars: Seq[ExprCode]):
Seq[ExprCode] = {
- vars.zipWithIndex.map { case (ev, i) =>
- ctx.addBufferedState(leftKeys(i).dataType, "value", ev.value)
- }
- }
-
- private def genComparison(ctx: CodegenContext, a: Seq[ExprCode], b:
Seq[ExprCode]): String = {
- // The first key compare always runs, so emit it unguarded. Each
subsequent key compare runs
- // only when previous keys were equal (comp == 0).
- val pairs = a.zip(b).zipWithIndex
- val firstCompare = pairs.headOption.map { case ((l, r), i) =>
- s"comp = ${ctx.genComp(leftKeys(i).dataType, l.value, r.value)};"
- }.getOrElse("comp = 0;")
- val restCompares = pairs.drop(1).map { case ((l, r), i) =>
- s"""
- |if (comp == 0) {
- | comp = ${ctx.genComp(leftKeys(i).dataType, l.value, r.value)};
- |}
- """.stripMargin.trim
- }
- s"""
- |$firstCompare
- |${restCompares.mkString("\n")}
- """.stripMargin
- }
-
/**
* Generate a function to scan both sides to find a match, returns:
* 1. the function name
diff --git
a/sql/core/src/test/resources/sql-tests/inputs/join-asof-containers.sql
b/sql/core/src/test/resources/sql-tests/inputs/join-asof-containers.sql
index 84fd4e84f4ce..444ed86f4ae4 100644
--- a/sql/core/src/test/resources/sql-tests/inputs/join-asof-containers.sql
+++ b/sql/core/src/test/resources/sql-tests/inputs/join-asof-containers.sql
@@ -2,6 +2,11 @@
--SET spark.sql.join.asofJoin.enabled=true
+-- Run with codegen on and off.
+--CONFIG_DIM1 spark.sql.codegen.wholeStage=true
+--CONFIG_DIM1
spark.sql.codegen.wholeStage=false,spark.sql.codegen.factoryMode=CODEGEN_ONLY
+--CONFIG_DIM1
spark.sql.codegen.wholeStage=false,spark.sql.codegen.factoryMode=NO_CODEGEN
+
CREATE OR REPLACE TEMP VIEW trades(trade_time, symbol, quantity) AS
VALUES (TIMESTAMP '2026-06-29 10:00:05', 'AAPL', 100),
(TIMESTAMP '2026-06-29 10:00:11', 'AAPL', 200),
diff --git a/sql/core/src/test/resources/sql-tests/inputs/join-asof-context.sql
b/sql/core/src/test/resources/sql-tests/inputs/join-asof-context.sql
index bd08ebf3e78a..622e816a369b 100644
--- a/sql/core/src/test/resources/sql-tests/inputs/join-asof-context.sql
+++ b/sql/core/src/test/resources/sql-tests/inputs/join-asof-context.sql
@@ -2,6 +2,11 @@
--SET spark.sql.join.asofJoin.enabled=true
+-- Run with codegen on and off.
+--CONFIG_DIM1 spark.sql.codegen.wholeStage=true
+--CONFIG_DIM1
spark.sql.codegen.wholeStage=false,spark.sql.codegen.factoryMode=CODEGEN_ONLY
+--CONFIG_DIM1
spark.sql.codegen.wholeStage=false,spark.sql.codegen.factoryMode=NO_CODEGEN
+
CREATE OR REPLACE TEMP VIEW trades(trade_time, symbol, quantity) AS
VALUES (TIMESTAMP '2026-06-29 10:00:05', 'AAPL', 100),
(TIMESTAMP '2026-06-29 10:00:11', 'AAPL', 200),
diff --git a/sql/core/src/test/resources/sql-tests/inputs/join-asof-corners.sql
b/sql/core/src/test/resources/sql-tests/inputs/join-asof-corners.sql
index 8e60d2870850..46364f0f6067 100644
--- a/sql/core/src/test/resources/sql-tests/inputs/join-asof-corners.sql
+++ b/sql/core/src/test/resources/sql-tests/inputs/join-asof-corners.sql
@@ -2,6 +2,11 @@
--SET spark.sql.join.asofJoin.enabled=true
+-- Run with codegen on and off.
+--CONFIG_DIM1 spark.sql.codegen.wholeStage=true
+--CONFIG_DIM1
spark.sql.codegen.wholeStage=false,spark.sql.codegen.factoryMode=CODEGEN_ONLY
+--CONFIG_DIM1
spark.sql.codegen.wholeStage=false,spark.sql.codegen.factoryMode=NO_CODEGEN
+
CREATE OR REPLACE TEMP VIEW trades(trade_time, symbol, quantity) AS
VALUES (TIMESTAMP '2026-06-29 10:00:05', 'AAPL', 100),
(TIMESTAMP '2026-06-29 10:00:11', 'AAPL', 200),
diff --git
a/sql/core/src/test/resources/sql-tests/inputs/join-asof-crossfeature.sql
b/sql/core/src/test/resources/sql-tests/inputs/join-asof-crossfeature.sql
index 3086125466d5..e54499365a83 100644
--- a/sql/core/src/test/resources/sql-tests/inputs/join-asof-crossfeature.sql
+++ b/sql/core/src/test/resources/sql-tests/inputs/join-asof-crossfeature.sql
@@ -2,6 +2,11 @@
--SET spark.sql.join.asofJoin.enabled=true
+-- Run with codegen on and off.
+--CONFIG_DIM1 spark.sql.codegen.wholeStage=true
+--CONFIG_DIM1
spark.sql.codegen.wholeStage=false,spark.sql.codegen.factoryMode=CODEGEN_ONLY
+--CONFIG_DIM1
spark.sql.codegen.wholeStage=false,spark.sql.codegen.factoryMode=NO_CODEGEN
+
CREATE OR REPLACE TEMP VIEW trades(trade_time, symbol, quantity) AS
VALUES (TIMESTAMP '2026-06-29 10:00:05', 'AAPL', 100),
(TIMESTAMP '2026-06-29 10:00:11', 'AAPL', 200),
diff --git
a/sql/core/src/test/resources/sql-tests/inputs/join-asof-datatypes.sql
b/sql/core/src/test/resources/sql-tests/inputs/join-asof-datatypes.sql
index 6116b77139e0..d2c0d5bf7d69 100644
--- a/sql/core/src/test/resources/sql-tests/inputs/join-asof-datatypes.sql
+++ b/sql/core/src/test/resources/sql-tests/inputs/join-asof-datatypes.sql
@@ -2,6 +2,11 @@
--SET spark.sql.join.asofJoin.enabled=true
+-- Run with codegen on and off.
+--CONFIG_DIM1 spark.sql.codegen.wholeStage=true
+--CONFIG_DIM1
spark.sql.codegen.wholeStage=false,spark.sql.codegen.factoryMode=CODEGEN_ONLY
+--CONFIG_DIM1
spark.sql.codegen.wholeStage=false,spark.sql.codegen.factoryMode=NO_CODEGEN
+
CREATE OR REPLACE TEMP VIEW deploys(deploy_ts, seq, service, version) AS
VALUES (TIMESTAMP '2026-06-29 10:00:00', 1, 'api', 'v1.0'),
(TIMESTAMP '2026-06-29 10:00:00', 2, 'api', 'v1.1'),
diff --git a/sql/core/src/test/resources/sql-tests/inputs/join-asof-errors.sql
b/sql/core/src/test/resources/sql-tests/inputs/join-asof-errors.sql
index 7d9e489bb691..d97427f15c16 100644
--- a/sql/core/src/test/resources/sql-tests/inputs/join-asof-errors.sql
+++ b/sql/core/src/test/resources/sql-tests/inputs/join-asof-errors.sql
@@ -2,6 +2,11 @@
--SET spark.sql.join.asofJoin.enabled=true
+-- Run with codegen on and off.
+--CONFIG_DIM1 spark.sql.codegen.wholeStage=true
+--CONFIG_DIM1
spark.sql.codegen.wholeStage=false,spark.sql.codegen.factoryMode=CODEGEN_ONLY
+--CONFIG_DIM1
spark.sql.codegen.wholeStage=false,spark.sql.codegen.factoryMode=NO_CODEGEN
+
CREATE OR REPLACE TEMP VIEW trades(trade_time, symbol, quantity) AS
VALUES (TIMESTAMP '2026-06-29 10:00:05', 'AAPL', 100),
(TIMESTAMP '2026-06-29 10:00:11', 'AAPL', 200),
diff --git
a/sql/core/src/test/resources/sql-tests/inputs/join-asof-expressions.sql
b/sql/core/src/test/resources/sql-tests/inputs/join-asof-expressions.sql
index 976db528dafc..c095930a6f43 100644
--- a/sql/core/src/test/resources/sql-tests/inputs/join-asof-expressions.sql
+++ b/sql/core/src/test/resources/sql-tests/inputs/join-asof-expressions.sql
@@ -2,6 +2,11 @@
--SET spark.sql.join.asofJoin.enabled=true
+-- Run with codegen on and off.
+--CONFIG_DIM1 spark.sql.codegen.wholeStage=true
+--CONFIG_DIM1
spark.sql.codegen.wholeStage=false,spark.sql.codegen.factoryMode=CODEGEN_ONLY
+--CONFIG_DIM1
spark.sql.codegen.wholeStage=false,spark.sql.codegen.factoryMode=NO_CODEGEN
+
CREATE OR REPLACE TEMP VIEW trades(trade_time, symbol, quantity) AS
VALUES (TIMESTAMP '2026-06-29 10:00:05', 'AAPL', 100),
(TIMESTAMP '2026-06-29 10:00:11', 'AAPL', 200),
diff --git a/sql/core/src/test/resources/sql-tests/inputs/join-asof-grammar.sql
b/sql/core/src/test/resources/sql-tests/inputs/join-asof-grammar.sql
index 329710f676c0..91a83fafa839 100644
--- a/sql/core/src/test/resources/sql-tests/inputs/join-asof-grammar.sql
+++ b/sql/core/src/test/resources/sql-tests/inputs/join-asof-grammar.sql
@@ -2,6 +2,11 @@
--SET spark.sql.join.asofJoin.enabled=true
+-- Run with codegen on and off.
+--CONFIG_DIM1 spark.sql.codegen.wholeStage=true
+--CONFIG_DIM1
spark.sql.codegen.wholeStage=false,spark.sql.codegen.factoryMode=CODEGEN_ONLY
+--CONFIG_DIM1
spark.sql.codegen.wholeStage=false,spark.sql.codegen.factoryMode=NO_CODEGEN
+
CREATE OR REPLACE TEMP VIEW trades(trade_time, symbol, quantity) AS
VALUES (TIMESTAMP '2026-06-29 10:00:05', 'AAPL', 100),
(TIMESTAMP '2026-06-29 10:00:11', 'AAPL', 200),
diff --git
a/sql/core/src/test/resources/sql-tests/inputs/join-asof-semantics.sql
b/sql/core/src/test/resources/sql-tests/inputs/join-asof-semantics.sql
index ac6796f4cb6d..5d943639aef9 100644
--- a/sql/core/src/test/resources/sql-tests/inputs/join-asof-semantics.sql
+++ b/sql/core/src/test/resources/sql-tests/inputs/join-asof-semantics.sql
@@ -2,6 +2,11 @@
--SET spark.sql.join.asofJoin.enabled=true
+-- Run with codegen on and off.
+--CONFIG_DIM1 spark.sql.codegen.wholeStage=true
+--CONFIG_DIM1
spark.sql.codegen.wholeStage=false,spark.sql.codegen.factoryMode=CODEGEN_ONLY
+--CONFIG_DIM1
spark.sql.codegen.wholeStage=false,spark.sql.codegen.factoryMode=NO_CODEGEN
+
CREATE OR REPLACE TEMP VIEW trades(trade_time, symbol, quantity) AS
VALUES (TIMESTAMP '2026-06-29 10:00:05', 'AAPL', 100),
(TIMESTAMP '2026-06-29 10:00:11', 'AAPL', 200),
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/AsOfJoinSortMergeSQLSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/AsOfJoinSortMergeSQLSuite.scala
index 9804ae623062..aaed548d0f8b 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/AsOfJoinSortMergeSQLSuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/AsOfJoinSortMergeSQLSuite.scala
@@ -23,9 +23,10 @@ import scala.util.Random
import org.apache.spark.SparkThrowable
import org.apache.spark.sql.catalyst.expressions.{Cast,
CodegenObjectFactoryMode}
-import org.apache.spark.sql.catalyst.plans.{AsOfJoinDirection, Backward,
Forward}
+import org.apache.spark.sql.catalyst.plans.{AsOfJoinDirection, Backward,
Forward, Nearest}
import org.apache.spark.sql.catalyst.plans.logical.AsOfJoin
-import org.apache.spark.sql.execution.FileSourceScanExec
+import org.apache.spark.sql.execution.{FileSourceScanExec, InputAdapter,
SparkPlan,
+ WholeStageCodegenExec}
import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
import org.apache.spark.sql.execution.joins.SortMergeAsOfJoinExec
import org.apache.spark.sql.internal.SQLConf
@@ -69,9 +70,65 @@ 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)(
+ check: DataFrame => Unit): Unit = {
+ withClue("ASOF join codegen off: ") {
+ withSQLConf(SQLConf.ENABLE_SORT_MERGE_AS_OF_JOIN_CODEGEN.key -> "false")
{
+ val df = classic.Dataset.ofRows(spark, query.queryExecution.logical)
+ check(df)
+ assertAsOfJoinCodegen(df, codegen = false)
+ }
+ }
+ withClue("ASOF join codegen on: ") {
+ val df = query
+ check(df)
+ assertAsOfJoinCodegen(df, codegen = true)
+ }
+ }
+
+ /**
+ * Like `QueryTest.checkAnswer` with `checkToRDD = false`, which single-pass
analysis needs, with
+ * the ASOF join codegen off and on.
+ */
+ private def checkAnswerWithoutRDD(query: => DataFrame, expected: Seq[Row]):
Unit =
+ checkWithAsOfJoinCodegenOffAndOn(query) { df =>
+ QueryTest.checkAnswer(df = df, expectedAnswer = expected, checkToRDD =
false)
+ }
+
+ /**
+ * Asserts which ASOF joins of `df`, read after `df` ran, are in a codegen
stage: with the
+ * codegen on, all but the nearest ones, and with it off, none. Spark builds
no codegen stage
+ * when whole-stage codegen is off or the codegen factory mode is NO_CODEGEN.
+ */
+ private def assertAsOfJoinCodegen(df: DataFrame, codegen: Boolean): Unit = {
+ val sqlConf = spark.sessionState.conf
+ val stagesOn = sqlConf.wholeStageEnabled &&
+ sqlConf.codegenFactoryMode != CodegenObjectFactoryMode.NO_CODEGEN
+ def stageJoins(plan: SparkPlan): Seq[SortMergeAsOfJoinExec] = plan match {
+ case _: InputAdapter => Nil
+ case j: SortMergeAsOfJoinExec => j +: j.children.flatMap(stageJoins)
+ case other => other.children.flatMap(stageJoins)
+ }
+ val plan = df.queryExecution.executedPlan
+ val generated = collect(plan) { case stage: WholeStageCodegenExec => stage
}
+ .flatMap(stage => stageJoins(stage.child))
+ val joins = collect(plan) { case j: SortMergeAsOfJoinExec => j }
+ val expected = if (codegen && stagesOn) joins.filter(_.direction !=
Nearest) else Nil
+ // The sizes too: two equal joins make one set element, so one of them
could hide.
+ assert(generated.size == expected.size && generated.toSet ==
expected.toSet,
+ s"Unexpected ASOF join codegen in plan:\n$plan")
}
private def setupTradeQuoteViews(): Unit = {
@@ -149,9 +206,10 @@ class AsOfJoinSortMergeSQLSuite extends QueryTest
}
/**
- * Checks `query` with the cursor scan off and on. A right group spills from
its second row,
- * so a cursor scan that buffered rows would show a spill. One partition
puts every equi-key
- * in one task, so the cursor scan also has to move between groups.
+ * Checks `query` with the cursor scan off and on, each with the codegen off
and on. A right
+ * group spills from its second row, so a cursor scan that buffered rows
would show a spill.
+ * One partition puts every equi-key in one task, so the cursor scan also
has to move between
+ * groups.
*/
private def checkCursorScan(query: => DataFrame, expected: Seq[Row]): Unit =
{
withSQLConf(
@@ -159,22 +217,25 @@ class AsOfJoinSortMergeSQLSuite extends QueryTest
SQLConf.SORT_MERGE_JOIN_EXEC_BUFFER_IN_MEMORY_THRESHOLD.key -> "1",
SQLConf.SORT_MERGE_JOIN_EXEC_BUFFER_SPILL_THRESHOLD.key -> "1") {
withSQLConf(SQLConf.SORT_MERGE_AS_OF_JOIN_CURSOR_SCAN_ENABLED.key ->
"false") {
- val buffered = query
- checkAnswer(buffered, expected)
- assert(asOfJoinMetric(buffered, "numAsOfCursorTasks") == 0)
+ checkWithAsOfJoinCodegenOffAndOn(query) { buffered =>
+ checkAnswer(buffered, expected)
+ assert(asOfJoinMetric(buffered, "numAsOfCursorTasks") == 0)
+ }
+ }
+ checkWithAsOfJoinCodegenOffAndOn(query) { cursor =>
+ checkAnswer(cursor, expected)
+ assert(asOfJoinMetric(cursor, "numAsOfCursorTasks") > 0, "Expected the
cursor scan")
+ assert(asOfJoinMetric(cursor, "spillSize") == 0, "The cursor scan
buffered right rows")
}
- val cursor = query
- checkAnswer(cursor, expected)
- assert(asOfJoinMetric(cursor, "numAsOfCursorTasks") > 0, "Expected the
cursor scan")
- assert(asOfJoinMetric(cursor, "spillSize") == 0, "The cursor scan
buffered right rows")
}
}
/** Checks `query`, and that it keeps the buffered scan with the cursor scan
on. */
private def checkBufferedScan(query: => DataFrame, expected: Seq[Row]): Unit
= {
- val df = query
- checkAnswer(df, expected)
- assert(asOfJoinMetric(df, "numAsOfCursorTasks") == 0, "Expected the
buffered scan")
+ checkWithAsOfJoinCodegenOffAndOn(query) { df =>
+ checkAnswer(df, expected)
+ assert(asOfJoinMetric(df, "numAsOfCursorTasks") == 0, "Expected the
buffered scan")
+ }
}
test("INNER ASOF JOIN with TIMESTAMP MATCH_CONDITION") {
@@ -226,7 +287,7 @@ class AsOfJoinSortMergeSQLSuite extends QueryTest
assert(join.leftSortExprs == Seq(join.left.output.head))
assert(join.rightSortExprs == Seq(join.right.output.head))
// Single-pass analysis does not support the deserializer used by
checkToRDD.
- QueryTest.checkAnswer(df = query, expectedAnswer = Seq(Row(2)),
checkToRDD = false)
+ checkAnswerWithoutRDD(query, Seq(Row(2)))
}
}
@@ -281,7 +342,7 @@ class AsOfJoinSortMergeSQLSuite extends QueryTest
case (false, false) => Seq(Row(1, 2), Row(2, 1), Row(3, 2))
}
assertUsesSortMergeAsOfJoin(query)
- QueryTest.checkAnswer(df = query, expectedAnswer = expected,
checkToRDD = false)
+ checkAnswerWithoutRDD(query, expected)
}
}
@@ -302,11 +363,7 @@ class AsOfJoinSortMergeSQLSuite extends QueryTest
|""".stripMargin
)
assertUsesSortMergeAsOfJoin(query)
- QueryTest.checkAnswer(
- df = query,
- expectedAnswer = Seq(Row(if (op == ">=") 2 else 3)),
- checkToRDD = false
- )
+ checkAnswerWithoutRDD(query, Seq(Row(if (op == ">=") 2 else 3)))
}
val structKey = "named_struct('ts', ts, 'n', n)"
@@ -333,11 +390,7 @@ class AsOfJoinSortMergeSQLSuite extends QueryTest
val join = query.queryExecution.analyzed.collectFirst { case j:
AsOfJoin => j }.get
val casts = join.asOfCondition.collect { case c: Cast => c }
assert(casts.size == 1, join.asOfCondition.treeString)
- QueryTest.checkAnswer(
- df = query,
- expectedAnswer = Seq(Row(if (op == ">=") 2 else 3)),
- checkToRDD = false
- )
+ checkAnswerWithoutRDD(query, Seq(Row(if (op == ">=") 2 else 3)))
}
}
@@ -363,11 +416,7 @@ class AsOfJoinSortMergeSQLSuite extends QueryTest
|""".stripMargin
)
assertUsesSortMergeAsOfJoin(query)
- QueryTest.checkAnswer(
- df = query,
- expectedAnswer = Seq(Row(1, null), Row(2, 2)),
- checkToRDD = false
- )
+ checkAnswerWithoutRDD(query, Seq(Row(1, null), Row(2, 2)))
}
}
}
@@ -1554,6 +1603,43 @@ class AsOfJoinSortMergeSQLSuite extends QueryTest
Row(1, "q11") :: Row(2, "q12") :: Row(3, null) :: Row(4, null) :: Row(5,
null) :: Nil)
}
+ test("cursor scan: a NULL right ON key ends the group like any later key") {
+ // Row 'null key' has k1 = 2, so it ends the group of k1 = 1, and the scan
stops there. It
+ // must not read on to row 'bad', whose ON key r.a / r.b divides by zero
under ANSI.
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+ withOrderedRightView(
+ "(1, 10, 2, 1, 'match'), (2, NULL, 1, 1, 'null key'), (3, 1, 0, 1,
'bad')",
+ "k1, a, b, ts, tag") {
+ checkCursorScan(
+ sql(
+ """
+ |SELECT t.k1, r.tag
+ |FROM VALUES (1, 5.0D, 10) AS t(k1, k2, ts)
+ |ASOF JOIN r
+ | MATCH_CONDITION (t.ts >= r.ts)
+ | ON t.k1 = r.k1 AND t.k2 = r.a / r.b
+ |""".stripMargin),
+ Row(1, "match") :: Nil)
+ }
+ }
+ }
+
+ test("cursor scan: a collated ON key matches by its collation") {
+ // Under UTF8_LCASE, 'a' equals 'A'. A binary compare of the keys would
find no match.
+ checkCursorScan(
+ sql(
+ """
+ |SELECT t.id, q.tag
+ |FROM VALUES (1, 'a' COLLATE UTF8_LCASE, 10), (2, 'b' COLLATE
UTF8_LCASE, 10)
+ | AS t(id, sym, ts)
+ |ASOF JOIN VALUES ('A' COLLATE UTF8_LCASE, 5, 'x'), ('B' COLLATE
UTF8_LCASE, 6, 'y'),
+ | ('c' COLLATE UTF8_LCASE, 1, 'z') AS q(sym, ts, tag)
+ | MATCH_CONDITION (t.ts >= q.ts)
+ | ON t.sym = q.sym
+ |""".stripMargin),
+ Row(1, "x") :: Row(2, "y") :: Nil)
+ }
+
// Queries with NOT NULL left ON keys against nullable right ON keys that
hold a NULL. The NULL
// right key sorts first, so it must compare below every left key. Read as
its empty value, it
// would match left key 0 and end the group of key -1 before its row, or
fail to compare.
@@ -1609,6 +1695,34 @@ class AsOfJoinSortMergeSQLSuite extends QueryTest
checkCursorScan(sql(query), expected)
}
+ test("a LIMIT in the join's codegen stage stops the join early") {
+ // All 100 left rows match. The LIMIT is under an aggregate, so it runs in
the join's codegen
+ // stage. The join must stop after 5 output rows instead of joining the
rest of the partition.
+ withSQLConf(SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+ Seq(
+ ("", true),
+ // A residual ON condition keeps the buffered scan.
+ (" AND t.id + 1 > q.id", false)
+ ).foreach { case (residual, cursorScan) =>
+ withClue(s"cursor scan $cursorScan: ") {
+ checkWithAsOfJoinCodegenOffAndOn(sql(
+ s"""
+ |SELECT count(*) FROM (
+ | SELECT t.id FROM range(100) t
+ | ASOF JOIN range(100) q
+ | MATCH_CONDITION (t.id >= q.id)
+ | ON t.id % 2 = q.id % 2$residual
+ | LIMIT 5)
+ |""".stripMargin)) { df =>
+ checkAnswer(df, Row(5) :: Nil)
+ assert(asOfJoinMetric(df, "numOutputRows") == 5)
+ assert((asOfJoinMetric(df, "numAsOfCursorTasks") > 0) ==
cursorScan)
+ }
+ }
+ }
+ }
+ }
+
test("cursor scan: a MATCH_CONDITION with the right side first still uses
the cursor scan") {
// The analyzer puts the left side first, so q.ts <= t.ts runs as t.ts >=
q.ts.
Seq(
@@ -1832,10 +1946,12 @@ class AsOfJoinSortMergeSQLSuite extends QueryTest
for {
op <- Seq(">=", "<=")
cursorScan <- Seq(false, true)
+ codegen <- Seq(false, true)
} {
- withClue(s"$leftSide $op q.v, cursor scan $cursorScan: ") {
+ withClue(s"$leftSide $op q.v, cursor scan $cursorScan, codegen
$codegen: ") {
withSQLConf(
- SQLConf.SORT_MERGE_AS_OF_JOIN_CURSOR_SCAN_ENABLED.key ->
cursorScan.toString) {
+ SQLConf.SORT_MERGE_AS_OF_JOIN_CURSOR_SCAN_ENABLED.key ->
cursorScan.toString,
+ SQLConf.ENABLE_SORT_MERGE_AS_OF_JOIN_CODEGEN.key ->
codegen.toString) {
val e = intercept[RuntimeException] {
sql(
s"""
@@ -1904,14 +2020,15 @@ class AsOfJoinSortMergeSQLSuite extends QueryTest
withSQLConf(
SQLConf.SHUFFLE_PARTITIONS.key -> "1",
SQLConf.SORT_MERGE_AS_OF_JOIN_CURSOR_SCAN_ENABLED.key ->
cursorScan.toString) {
- val df = sql(
+ checkWithAsOfJoinCodegenOffAndOn(sql(
s"""
|SELECT t.id, q.ts, q.tag
|FROM t $joinType ASOF JOIN q
| MATCH_CONDITION (t.ts $op q.ts) ON t.k = q.k
- |""".stripMargin)
- checkAnswer(df, expected)
- assert((asOfJoinMetric(df, "numAsOfCursorTasks") > 0) ==
cursorScan)
+ |""".stripMargin)) { df =>
+ checkAnswer(df, expected)
+ assert((asOfJoinMetric(df, "numAsOfCursorTasks") > 0) ==
cursorScan)
+ }
}
}
}
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/SortMergeAsOfJoinSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/SortMergeAsOfJoinSuite.scala
index af2b714f1e5d..cfd6d84a6d5e 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/SortMergeAsOfJoinSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/SortMergeAsOfJoinSuite.scala
@@ -17,15 +17,19 @@
package org.apache.spark.sql
+import java.lang.management.ManagementFactory
import java.sql.Timestamp
import java.time.{Duration, Instant, LocalDateTime}
import scala.jdk.CollectionConverters._
+import com.sun.management.UnixOperatingSystemMXBean
+
import org.apache.spark.sql.catalyst.expressions.{BinaryComparison,
Expression, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual}
-import org.apache.spark.sql.catalyst.plans.{AsOfJoinDirection, Backward,
Forward}
+import org.apache.spark.sql.catalyst.plans.{AsOfJoinDirection, Backward,
Forward, Nearest}
import org.apache.spark.sql.catalyst.plans.logical.{AsOfJoin, LogicalPlan}
import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.{InputAdapter, SparkPlan,
WholeStageCodegenExec}
import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
import org.apache.spark.sql.execution.joins.SortMergeAsOfJoinExec
import org.apache.spark.sql.internal.SQLConf
@@ -67,38 +71,96 @@ 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, except for a
+ // nearest join, which runs the interpreted scan both times.
+ private def checkAnswerAndSpill(df: => classic.DataFrame, expectedAnswer:
Seq[Row]): Unit = {
+ withAsOfJoinCodegenOffAndOn { codegen =>
+ val query = df
+ checkAnswer(query, expectedAnswer)
+ val op = assertAsOfJoinCodegen(query, codegen)
+ assert(op.metrics("spillSize").value > 0,
+ s"Expected the right-side buffer to spill (spillSize > 0), " +
+ s"got ${op.metrics("spillSize").value}")
+ assert(op.metrics("numAsOfCursorTasks").value == 0,
+ "Expected the buffered scan, but a task used the cursor scan")
}
- 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")
+ }
+
+ // 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)
+ }
+ 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 = {
+ withAsOfJoinCodegenOffAndOn { codegen =>
+ withSQLConf(
+ 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 op = assertAsOfJoinCodegen(query, codegen)
+ assert(op.metrics("numAsOfCursorTasks").value > 0, "Expected the
cursor scan")
+ assert(op.metrics("spillSize").value == 0, "The cursor scan buffered
right rows")
+ }
}
- val op = collectFirst(df.queryExecution.executedPlan) {
- case s: SortMergeAsOfJoinExec => s
+ }
+
+ /**
+ * Runs `f` with the ASOF join codegen off, then on, and passes it the
setting. Build each
+ * DataFrame inside `f`, since a DataFrame keeps the plan it got first.
+ */
+ private def withAsOfJoinCodegenOffAndOn(f: Boolean => Unit): Unit = {
+ Seq(false, true).foreach { codegen =>
+ withClue(s"ASOF join codegen $codegen: ") {
+ withSQLConf(SQLConf.ENABLE_SORT_MERGE_AS_OF_JOIN_CODEGEN.key ->
codegen.toString) {
+ f(codegen)
+ }
+ }
+ }
+ }
+
+ /**
+ * Asserts that `df`, after it ran, has a sort-merge ASOF join, and that the
join ran generated
+ * exactly when the codegen is on and the join is not nearest. Returns the
join.
+ */
+ private def assertAsOfJoinCodegen(df: DataFrame, codegen: Boolean):
SortMergeAsOfJoinExec = {
+ val plan = df.queryExecution.executedPlan
+ val op = collectFirst(plan) { case s: SortMergeAsOfJoinExec => s }
+ assert(op.isDefined, s"Expected SortMergeAsOfJoinExec in plan:\n$plan")
+ assert(isGenerated(plan, op.get) == (codegen && op.get.direction !=
Nearest),
+ s"Unexpected ASOF join codegen in:\n$plan")
+ op.get
+ }
+
+ /**
+ * 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.
+ * Single-pass analysis needs `checkToRDD = false`.
+ */
+ private def checkAnswerCodegenOffAndOn(
+ df: => DataFrame,
+ expectedAnswer: Seq[Row],
+ checkToRDD: Boolean = true): Unit = {
+ withAsOfJoinCodegenOffAndOn { codegen =>
+ val query = df
+ if (checkToRDD) {
+ checkAnswer(query, expectedAnswer)
+ } else {
+ QueryTest.checkAnswer(df = query, expectedAnswer = expectedAnswer,
checkToRDD = false)
+ }
+ assertAsOfJoinCodegen(query, codegen)
}
- assert(op.isDefined,
- s"Expected SortMergeAsOfJoinExec in
plan:\n${df.queryExecution.executedPlan}")
- assert(op.get.metrics("numAsOfCursorTasks").value > 0, "Expected the
cursor scan")
- assert(op.get.metrics("spillSize").value == 0, "The cursor scan buffered
right rows")
}
/**
@@ -186,7 +248,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
test("backward join - usingColumns") {
val (df1, df2) = prepareForAsOfJoin()
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df1.joinAsOf(
df2, df1.col("a"), df2.col("a"), usingColumns = Seq("b"),
joinType = "inner", tolerance = null,
@@ -199,7 +261,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
test("backward join - left outer") {
val (df1, df2) = prepareForAsOfJoin()
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df1.joinAsOf(
df2, df1.col("a"), df2.col("a"), usingColumns = Seq("b"),
joinType = "leftouter", tolerance = null,
@@ -258,20 +320,22 @@ class SortMergeAsOfJoinSuite extends QueryTest
("backward", Backward, Row(10, "a", 5, "r2")),
("forward", Forward, Row(10, "a", 15, "r3"))
).foreach { case (directionName, direction, expected) =>
- val joined = left.joinAsOf(
- right, left.col("ts"), right.col("ts"), usingColumns = Seq.empty,
- joinType = "inner", tolerance = null,
- allowExactMatches = true, direction = directionName)
- checkAnswer(joined, expected :: Nil)
- val op = collectFirst(joined.queryExecution.executedPlan) {
- case s: SortMergeAsOfJoinExec => s
- }.get
- val rightSideFirst = op.asOfCondition match {
- case c: BinaryComparison =>
c.left.references.subsetOf(op.right.outputSet)
- case _ => false
+ withClue(s"$directionName: ") {
+ withAsOfJoinCodegenOffAndOn { codegen =>
+ val joined = left.joinAsOf(
+ right, left.col("ts"), right.col("ts"), usingColumns = Seq.empty,
+ joinType = "inner", tolerance = null,
+ allowExactMatches = true, direction = directionName)
+ checkAnswer(joined, expected :: Nil)
+ val op = assertAsOfJoinCodegen(joined, codegen)
+ val rightSideFirst = op.asOfCondition match {
+ case c: BinaryComparison =>
c.left.references.subsetOf(op.right.outputSet)
+ case _ => false
+ }
+ assert(rightSideFirst, s"Expected the right side first in
${op.asOfCondition}")
+ assert(op.direction === direction)
+ }
}
- assert(rightSideFirst, s"Expected the right side first in
${op.asOfCondition}")
- assert(op.direction === direction)
}
}
}
@@ -423,23 +487,25 @@ class SortMergeAsOfJoinSuite extends QueryTest
val rightKey = right.col(if (ltzOnLeft) "ntz" else "ltz")
for (direction <- Seq("backward", "forward", "nearest")) {
- val joined = left.joinAsOf(
- other = right, leftAsOf = leftKey, rightAsOf = rightKey,
- usingColumns = Seq.empty, joinType = "inner", tolerance = null,
- allowExactMatches = true, direction = direction
- ).select("tag")
- val join = joined.queryExecution.analyzed.collectFirst { case j:
AsOfJoin => j }.get
- assert(join.leftSortExprs.head.dataType ==
- (if (ltzOnLeft || direction == "nearest") TimestampType else
TimestampNTZType))
- assert(join.rightSortExprs.head.dataType == TimestampType)
- val expected = if (direction == "forward") "after" else "before"
- QueryTest.checkAnswer(
- df = joined, expectedAnswer = Seq(Row(expected)), checkToRDD =
false)
- val physicalJoin =
collectFirst(joined.queryExecution.executedPlan) {
- case j: SortMergeAsOfJoinExec => j
- }.get
- assert(physicalJoin.leftSortExprs.head.dataType ==
join.leftSortExprs.head.dataType)
- assert(physicalJoin.rightSortExprs.head.dataType ==
TimestampType)
+ withAsOfJoinCodegenOffAndOn { codegen =>
+ val joined = left.joinAsOf(
+ other = right, leftAsOf = leftKey, rightAsOf = rightKey,
+ usingColumns = Seq.empty, joinType = "inner", tolerance =
null,
+ allowExactMatches = true, direction = direction
+ ).select("tag")
+ val join =
+ joined.queryExecution.analyzed.collectFirst { case j:
AsOfJoin => j }.get
+ assert(join.leftSortExprs.head.dataType ==
+ (if (ltzOnLeft || direction == "nearest") TimestampType else
TimestampNTZType))
+ assert(join.rightSortExprs.head.dataType == TimestampType)
+ val expected = if (direction == "forward") "after" else
"before"
+ QueryTest.checkAnswer(
+ df = joined, expectedAnswer = Seq(Row(expected)), checkToRDD
= false)
+ val physicalJoin = assertAsOfJoinCodegen(joined, codegen)
+ assert(
+ physicalJoin.leftSortExprs.head.dataType ==
join.leftSortExprs.head.dataType)
+ assert(physicalJoin.rightSortExprs.head.dataType ==
TimestampType)
+ }
}
}
}
@@ -473,14 +539,13 @@ class SortMergeAsOfJoinSuite extends QueryTest
case "array" => functions.array(df.col("ts"))
case "nested" => functions.struct(functions.array(df.col("k")))
}
- val joined = left.joinAsOf(
+ def joined: DataFrame = left.joinAsOf(
other = right, leftAsOf = key(left), rightAsOf = key(right),
usingColumns = Seq.empty, joinType = "inner", tolerance = null,
allowExactMatches = true, direction = direction
).select("tag")
val expected = if (direction == "backward") "before" else "after"
- QueryTest.checkAnswer(
- df = joined, expectedAnswer = Seq(Row(expected)), checkToRDD =
false)
+ checkAnswerCodegenOffAndOn(joined, Seq(Row(expected)), checkToRDD =
false)
}
}
}
@@ -498,16 +563,19 @@ class SortMergeAsOfJoinSuite extends QueryTest
| (TIMESTAMP_NTZ '2024-03-10 02:50:00', 'near'),
| (TIMESTAMP_NTZ '2024-03-10 03:00:00', 'far') AS t(rk, tag)
|""".stripMargin)
- val joined = left.joinAsOf(
- other = right, leftAsOf = left.col("lk"), rightAsOf =
right.col("rk"),
- usingColumns = Seq.empty, joinType = "inner", tolerance = null,
- allowExactMatches = true, direction = "backward"
- ).select("tag")
- assert(joined.queryExecution.analyzed.resolved)
+ withAsOfJoinCodegenOffAndOn { codegen =>
+ val joined = left.joinAsOf(
+ other = right, leftAsOf = left.col("lk"), rightAsOf =
right.col("rk"),
+ usingColumns = Seq.empty, joinType = "inner", tolerance = null,
+ allowExactMatches = true, direction = "backward"
+ ).select("tag")
+ assert(joined.queryExecution.analyzed.resolved)
- withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> "UTC") {
- QueryTest.checkAnswer(
- df = joined, expectedAnswer = Seq(Row("near")), checkToRDD = false)
+ withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> "UTC") {
+ QueryTest.checkAnswer(
+ df = joined, expectedAnswer = Seq(Row("near")), checkToRDD =
false)
+ assertAsOfJoinCodegen(joined, codegen)
+ }
}
}
}
@@ -538,7 +606,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
(source, target, targetType) <- Seq(
("ltz", "ntz", TimestampNTZType), ("ntz", "ltz", TimestampType))
} {
- val joined = left.joinAsOf(
+ def joined: DataFrame = left.joinAsOf(
other = right, leftAsOf = left.col(source).cast(targetType),
rightAsOf = right.col(target), usingColumns = Seq.empty, joinType
= "inner",
tolerance = null, allowExactMatches = true, direction = direction
@@ -546,8 +614,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
val join = joined.queryExecution.analyzed.collectFirst { case j:
AsOfJoin => j }.get
assert((join.leftSortExprs ++ join.rightSortExprs).forall(_.dataType
== targetType))
val expected = if (direction == "forward") "after" else "before"
- QueryTest.checkAnswer(
- df = joined, expectedAnswer = Seq(Row(expected)), checkToRDD =
false)
+ checkAnswerCodegenOffAndOn(joined, Seq(Row(expected)), checkToRDD =
false)
}
}
}
@@ -572,20 +639,20 @@ class SortMergeAsOfJoinSuite extends QueryTest
key <- Seq("id", "ts")
direction <- Seq("backward", "forward", "nearest")
} {
- val joined = left.joinAsOf(
- other = right, leftAsOf = left.col(key), rightAsOf =
right.col(key),
- usingColumns = Seq.empty, joinType = "inner", tolerance = null,
- allowExactMatches = true, direction = direction
- ).select("tag")
- val join = joined.queryExecution.analyzed.collectFirst { case j:
AsOfJoin => j }.get
- assert(join.requiresSortMergeAsOfJoin)
- val expected = if (direction == "forward") "after" else "before"
- withSQLConf(SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> "false") {
- QueryTest.checkAnswer(
- df = joined, expectedAnswer = Seq(Row(expected)), checkToRDD =
false)
- assert(collectFirst(joined.queryExecution.executedPlan) {
- case s: SortMergeAsOfJoinExec => s
- }.isDefined)
+ withAsOfJoinCodegenOffAndOn { codegen =>
+ val joined = left.joinAsOf(
+ other = right, leftAsOf = left.col(key), rightAsOf =
right.col(key),
+ usingColumns = Seq.empty, joinType = "inner", tolerance = null,
+ allowExactMatches = true, direction = direction
+ ).select("tag")
+ val join = joined.queryExecution.analyzed.collectFirst { case j:
AsOfJoin => j }.get
+ assert(join.requiresSortMergeAsOfJoin)
+ val expected = if (direction == "forward") "after" else "before"
+ withSQLConf(SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> "false") {
+ QueryTest.checkAnswer(
+ df = joined, expectedAnswer = Seq(Row(expected)), checkToRDD =
false)
+ assertAsOfJoinCodegen(joined, codegen)
+ }
}
}
}
@@ -639,16 +706,19 @@ class SortMergeAsOfJoinSuite extends QueryTest
val left = spark.sql("SELECT named_struct('A', CAST(10 AS INT)) AS lk")
val right = spark.sql(
"SELECT named_struct('a', CAST(9 AS BIGINT)) AS rk, 'before' AS tag")
- val joined = left.joinAsOf(
- other = right, leftAsOf = left.col("lk"), rightAsOf =
right.col("rk"),
- usingColumns = Seq.empty, joinType = "inner", tolerance = null,
- allowExactMatches = true, direction = "backward"
- ).select("tag")
- assert(joined.queryExecution.analyzed.resolved)
+ withAsOfJoinCodegenOffAndOn { codegen =>
+ val joined = left.joinAsOf(
+ other = right, leftAsOf = left.col("lk"), rightAsOf =
right.col("rk"),
+ usingColumns = Seq.empty, joinType = "inner", tolerance = null,
+ allowExactMatches = true, direction = "backward"
+ ).select("tag")
+ assert(joined.queryExecution.analyzed.resolved)
- withSQLConf(SQLConf.CASE_SENSITIVE.key -> "true") {
- QueryTest.checkAnswer(
- df = joined, expectedAnswer = Seq(Row("before")), checkToRDD =
false)
+ withSQLConf(SQLConf.CASE_SENSITIVE.key -> "true") {
+ QueryTest.checkAnswer(
+ df = joined, expectedAnswer = Seq(Row("before")), checkToRDD =
false)
+ assertAsOfJoinCodegen(joined, codegen)
+ }
}
}
}
@@ -672,14 +742,13 @@ class SortMergeAsOfJoinSuite extends QueryTest
| (49, 'before'), (52, 'after') AS t(k, tag)
|""".stripMargin)
for (direction <- Seq("backward", "forward", "nearest")) {
- val joined = left.joinAsOf(
+ def joined: DataFrame = left.joinAsOf(
other = right, leftAsOf = left.col("k"), rightAsOf =
right.col("k"),
usingColumns = Seq.empty, joinType = "inner", tolerance = null,
allowExactMatches = true, direction = direction
).select("tag")
val expected = if (direction == "forward") "after" else "before"
- QueryTest.checkAnswer(
- df = joined, expectedAnswer = Seq(Row(expected)), checkToRDD =
false)
+ checkAnswerCodegenOffAndOn(joined, Seq(Row(expected)), checkToRDD
= false)
}
}
}
@@ -697,7 +766,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
|FROM VALUES (16777218, 'before'), (16777220, 'after') AS t(k, tag)
|""".stripMargin)
for (direction <- Seq("backward", "forward", "nearest")) {
- val joined = left.joinAsOf(
+ def joined: DataFrame = left.joinAsOf(
other = right, leftAsOf = left.col("k"), rightAsOf =
right.col("k"),
usingColumns = Seq.empty, joinType = "inner", tolerance = null,
allowExactMatches = true, direction = direction
@@ -711,8 +780,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
assert(join.rightSortExprs.head.dataType == FloatType)
}
val expected = if (direction == "forward") "after" else "before"
- QueryTest.checkAnswer(
- df = joined, expectedAnswer = Seq(Row(expected)), checkToRDD =
false)
+ checkAnswerCodegenOffAndOn(joined, Seq(Row(expected)), checkToRDD =
false)
}
}
}
@@ -792,15 +860,14 @@ class SortMergeAsOfJoinSuite extends QueryTest
direction <- Seq("backward", "forward")
exact <- Seq(false, true)
} {
- val joined = left.joinAsOf(
+ def joined: DataFrame = left.joinAsOf(
other = right, leftAsOf = left.col("k"), rightAsOf =
right.col("k"),
usingColumns = Seq.empty, joinType = "inner",
tolerance = functions.lit(Duration.ofMinutes(3)),
allowExactMatches = exact, direction = direction
).select("tag")
val expected = if (exact) "exact" else if (direction == "forward")
"after" else "before"
- QueryTest.checkAnswer(
- df = joined, expectedAnswer = Seq(Row(expected)), checkToRDD =
false)
+ checkAnswerCodegenOffAndOn(joined, Seq(Row(expected)), checkToRDD =
false)
}
}
}
@@ -825,7 +892,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
Row(leftTime, afterTime, "after")
}
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
left.joinAsOf(
other = right, leftAsOf = left.col("ts"), rightAsOf =
right.col("ts"),
usingColumns = Seq.empty, joinType = "inner", tolerance = null,
@@ -856,7 +923,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
Row(leftTime, afterTime, "after")
}
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
left.joinAsOf(
other = right, leftAsOf = left.col("ts"), rightAsOf =
right.col("ts"),
usingColumns = Seq.empty, joinType = "inner", tolerance = null,
@@ -936,7 +1003,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
test("backward join - tolerance = 1") {
val (df1, df2) = prepareForAsOfJoin()
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df1.joinAsOf(
df2, df1.col("a"), df2.col("a"), usingColumns = Seq.empty,
joinType = "inner",
@@ -951,7 +1018,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
test("backward join - allowExactMatches = false") {
val (df1, df2) = prepareForAsOfJoin()
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df1.joinAsOf(
df2, df1.col("a"), df2.col("a"), usingColumns = Seq.empty,
joinType = "inner", tolerance = null,
@@ -974,7 +1041,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
StructField("a", IntegerType, false) ::
StructField("b", StringType, false) ::
StructField("left_val", StringType, false) :: Nil))
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
emptyDf.joinAsOf(
df2, emptyDf.col("a"), df2.col("a"), usingColumns = Seq.empty,
joinType = "inner", tolerance = null,
@@ -992,7 +1059,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
StructField("b", StringType) ::
StructField("right_val", IntegerType) :: Nil))
// Inner join: no matches possible
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df1.joinAsOf(
emptyDf, df1.col("a"), emptyDf.col("a"), usingColumns = Seq.empty,
joinType = "inner", tolerance = null,
@@ -1000,7 +1067,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
Seq.empty
)
// Left outer: all left rows with null right
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df1.joinAsOf(
emptyDf, df1.col("a"), emptyDf.col("a"), usingColumns = Seq.empty,
joinType = "leftouter", tolerance = null,
@@ -1026,7 +1093,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
List(Row(1, "a"), Row(null, "b"), Row(5, "c")).asJava, schema2)
// Null as-of keys should not match anything (as-of condition
// evaluates to null for null inputs)
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df1.joinAsOf(
df2, df1.col("a"), df2.col("a"), usingColumns = Seq.empty,
joinType = "leftouter", tolerance = null,
@@ -1057,7 +1124,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
Row("A", 2, "a1"), Row("A", 7, "a2"), Row("A", 12, "a3"),
Row("B", 1, "b1"), Row("B", 6, "b2"), Row("B", 10, "b3")
).asJava, schema2)
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df1.joinAsOf(
df2, df1.col("ts"), df2.col("ts"), usingColumns = Seq("grp"),
joinType = "inner", tolerance = null,
@@ -1083,7 +1150,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
List(Row(100L, "a"), Row(200L, "b"), Row(300L, "c")).asJava, schema1)
val df2 = spark.createDataFrame(
List(Row(50L, "x"), Row(150L, "y"), Row(250L, "z")).asJava, schema2)
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df1.joinAsOf(
df2, df1.col("ts"), df2.col("ts"), usingColumns = Seq.empty,
joinType = "inner", tolerance = null,
@@ -1107,7 +1174,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
List(Row(1.5, "a"), Row(3.0, "b"), Row(5.5, "c")).asJava, schema1)
val df2 = spark.createDataFrame(
List(Row(1.0, "x"), Row(2.5, "y"), Row(4.0, "z")).asJava, schema2)
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df1.joinAsOf(
df2, df1.col("ts"), df2.col("ts"), usingColumns = Seq.empty,
joinType = "inner", tolerance = null,
@@ -1141,17 +1208,13 @@ class SortMergeAsOfJoinSuite extends QueryTest
s"SELECT CAST('$key' AS $rightType) AS k, '$tag' AS tag"
}.mkString(" UNION ALL ")
)
- val result = left.joinAsOf(
+ def result: DataFrame = left.joinAsOf(
other = right, leftAsOf = left.col("k"), rightAsOf =
right.col("k"),
usingColumns = Seq.empty, joinType = "inner", tolerance = null,
allowExactMatches = true, direction = direction
).select(right.col("tag"))
- checkAnswer(result, Seq(Row(expected)))
- assert(collectFirst(result.queryExecution.executedPlan) {
- case s: SortMergeAsOfJoinExec => s
- }.isDefined, s"Expected SortMergeAsOfJoinExec in plan:\n" +
- result.queryExecution.executedPlan)
+ checkAnswerCodegenOffAndOn(result, Seq(Row(expected)))
}
}
}
@@ -1189,7 +1252,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
|AS t(case_id, k, tag)
|""".stripMargin
)
- val result = left.joinAsOf(
+ def result: DataFrame = left.joinAsOf(
other = right, leftAsOf = left.col("k"), rightAsOf =
right.col("k"),
usingColumns = Seq("case_id"), joinType = "leftouter",
tolerance = functions.lit(Duration.ofDays(2)),
@@ -1198,7 +1261,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
val closest = if (direction == "forward") "after" else "before"
withClue(s"legacyInterval=$legacyInterval,
allowExactMatches=$allowExactMatches: ") {
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
result,
Seq(
Row("inside", closest),
@@ -1239,7 +1302,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
StructField("val", StringType) :: Nil)
val df = spark.createDataFrame(
List(Row(1, "a"), Row(3, "b"), Row(5, "c")).asJava, schema)
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df.joinAsOf(
df, df.col("ts"), df.col("ts"), usingColumns = Seq.empty,
joinType = "inner", tolerance = null,
@@ -1263,7 +1326,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
List(Row(2, "a"), Row(5, "b"), Row(9, "c")).asJava, schema1)
val df2 = spark.createDataFrame(
List(Row(1, "x"), Row(4, "y"), Row(7, "z")).asJava, schema2)
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df1.joinAsOf(
df2, df1.col("ts"), df2.col("ts"), usingColumns = Seq.empty,
joinType = "inner", tolerance = null,
@@ -1287,7 +1350,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
List(Row(1, "a"), Row(5, "b"), Row(10, "c")).asJava, schema1)
val df2 = spark.createDataFrame(
List(Row(3, "x"), Row(7, "y")).asJava, schema2)
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df1.joinAsOf(
df2, df1.col("ts"), df2.col("ts"), usingColumns = Seq.empty,
joinType = "leftouter", tolerance = null,
@@ -1312,7 +1375,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
val df2 = spark.createDataFrame(
List(Row(2, "x"), Row(7, "y"), Row(15, "z")).asJava, schema2)
// tolerance = 3: only match if right.ts <= left.ts + 3
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df1.joinAsOf(
df2, df1.col("ts"), df2.col("ts"), usingColumns = Seq.empty,
joinType = "inner",
@@ -1495,7 +1558,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
val right = spark.sql(
"SELECT * FROM VALUES ('p'), ('100'), ('h'), ('10'), ('9') AS
t(k)")
for (direction <- Seq("backward", "forward")) {
- val joined = left.joinAsOf(
+ def joined: DataFrame = left.joinAsOf(
other = right, leftAsOf = left.col("k"), rightAsOf =
right.col("k"),
usingColumns = Seq.empty, joinType = "leftouter", tolerance =
null,
allowExactMatches = true, direction = direction
@@ -1505,7 +1568,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
} else {
Seq(Row("50", "9"), Row("k", "p"), Row("u", null))
}
- QueryTest.checkAnswer(df = joined, expectedAnswer = expected,
checkToRDD = false)
+ checkAnswerCodegenOffAndOn(joined, expected, checkToRDD = false)
}
}
}
@@ -1536,14 +1599,13 @@ class SortMergeAsOfJoinSuite extends QueryTest
condition = "AS_OF_JOIN.UNSUPPORTED_TOLERANCE_KEY_TYPE",
parameters = Map("dataType" -> s""""STRING$collation"""")
)
- val castKeys = left.joinAsOf(
+ def castKeys: DataFrame = left.joinAsOf(
other = right, leftAsOf = left.col("lk").cast("int"),
rightAsOf = right.col("rk").cast("int"), usingColumns =
Seq.empty,
joinType = "inner", tolerance = functions.lit(10),
allowExactMatches = true, direction = direction
).select("rk")
- QueryTest.checkAnswer(
- df = castKeys, expectedAnswer = Seq(Row("50")), checkToRDD =
false)
+ checkAnswerCodegenOffAndOn(castKeys, Seq(Row("50")), checkToRDD =
false)
}
}
}
@@ -1591,7 +1653,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
direction <- Seq("backward", "forward")
allowExactMatches <- Seq(false, true)
} {
- val joined = left.joinAsOf(
+ def joined: DataFrame = left.joinAsOf(
other = right, leftAsOf = left.col("lk"), rightAsOf =
right.col("rk"),
usingColumns = Seq.empty, joinType = "leftouter", tolerance =
null,
allowExactMatches = allowExactMatches, direction = direction
@@ -1603,8 +1665,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
} else {
null
}
- QueryTest.checkAnswer(
- df = joined, expectedAnswer = Seq(Row(expected)), checkToRDD =
false)
+ checkAnswerCodegenOffAndOn(joined, Seq(Row(expected)), checkToRDD
= false)
}
}
}
@@ -1619,13 +1680,12 @@ class SortMergeAsOfJoinSuite extends QueryTest
"SELECT * FROM VALUES (7, 'far'), (9, 'before'), (12, 'after') AS
t(rk, tag)")
for ((direction, expected) <- Seq(
"backward" -> "after", "forward" -> "before", "nearest" ->
"before")) {
- val reversed = left.joinAsOf(
+ def reversed: DataFrame = left.joinAsOf(
other = right, leftAsOf = right.col("rk"), rightAsOf =
left.col("lk"),
usingColumns = Seq.empty, joinType = "inner", tolerance = null,
allowExactMatches = true, direction = direction
).select("tag")
- QueryTest.checkAnswer(
- df = reversed, expectedAnswer = Seq(Row(expected)), checkToRDD =
false)
+ checkAnswerCodegenOffAndOn(reversed, Seq(Row(expected)), checkToRDD
= false)
}
}
}
@@ -1641,15 +1701,13 @@ class SortMergeAsOfJoinSuite extends QueryTest
|(18, 'outside before'), (22, 'outside after') AS t(rk, tag)
|""".stripMargin)
for ((direction, expected) <- Seq("backward" -> "after", "forward" ->
"before")) {
- val reversed = left.joinAsOf(
+ def reversed: DataFrame = left.joinAsOf(
other = right, leftAsOf = right.col("rk"), rightAsOf =
left.col("lk"),
usingColumns = Seq.empty, joinType = "leftouter", tolerance =
functions.lit(1),
allowExactMatches = true, direction = direction
).select("lk", "tag")
- QueryTest.checkAnswer(
- df = reversed, expectedAnswer = Seq(Row(10, expected), Row(20,
null)),
- checkToRDD = false
- )
+ checkAnswerCodegenOffAndOn(
+ reversed, Seq(Row(10, expected), Row(20, null)), checkToRDD =
false)
}
}
}
@@ -1665,16 +1723,16 @@ class SortMergeAsOfJoinSuite extends QueryTest
val right = spark.sql("SELECT * FROM VALUES ('B', CAST(NULL AS BIGINT))
AS t(k, v)")
for (direction <- Seq("backward", "forward")) {
withClue(s"$direction: ") {
- val reversed = left.joinAsOf(
- other = right, leftAsOf = right.col("v"), rightAsOf =
left.col("v") * 1000,
- usingColumns = Seq("k"), joinType = "left", tolerance = null,
- allowExactMatches = true, direction = direction)
- checkAnswer(reversed, Row("B", Long.MaxValue, null, null) :: Nil)
- val op = collectFirst(reversed.queryExecution.executedPlan) {
- case s: SortMergeAsOfJoinExec => s
+ withAsOfJoinCodegenOffAndOn { codegen =>
+ val reversed = left.joinAsOf(
+ other = right, leftAsOf = right.col("v"), rightAsOf =
left.col("v") * 1000,
+ usingColumns = Seq("k"), joinType = "left", tolerance = null,
+ allowExactMatches = true, direction = direction)
+ checkAnswer(reversed, Row("B", Long.MaxValue, null, null) :: Nil)
+ val op = assertAsOfJoinCodegen(reversed, codegen)
+ assert(op.metrics("numAsOfCursorTasks").value == 0,
+ s"Expected the buffered
scan:\n${reversed.queryExecution.executedPlan}")
}
- assert(op.exists(_.metrics("numAsOfCursorTasks").value == 0),
- s"Expected the buffered
scan:\n${reversed.queryExecution.executedPlan}")
}
}
}
@@ -1705,10 +1763,10 @@ class SortMergeAsOfJoinSuite extends QueryTest
allowExactMatches = true, direction =
AsOfJoinDirection(direction)
)
}
- val joined = classic.Dataset.ofRows(spark, plan)
+ def joined: DataFrame = classic.Dataset.ofRows(spark, plan)
val expected = if (direction == "forward") "after" else "before"
- QueryTest.checkAnswer(
- df = joined, expectedAnswer = Seq(Row(1, expected), Row(2, null)),
checkToRDD = false)
+ checkAnswerCodegenOffAndOn(
+ joined, Seq(Row(1, expected), Row(2, null)), checkToRDD = false)
}
}
}
@@ -1925,7 +1983,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
test("forward join - allowExactMatches = false") {
val (df1, df2) = prepareForAsOfJoin()
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df1.joinAsOf(
df2, df1.col("a"), df2.col("a"), usingColumns = Seq.empty,
joinType = "inner", tolerance = null,
@@ -2021,7 +2079,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
val df2 = spark.createDataFrame(
List(Row(null, 3, "x"), Row(1, 4, "y"), Row(null, 8, "z")).asJava,
schema2)
// Inner join: null equi-keys should produce no match
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df1.joinAsOf(
df2, df1.col("ts"), df2.col("ts"), usingColumns = Seq("grp"),
joinType = "inner", tolerance = null,
@@ -2033,7 +2091,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
)
)
// Left outer: null equi-keys should emit null right
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df1.joinAsOf(
df2, df1.col("ts"), df2.col("ts"), usingColumns = Seq("grp"),
joinType = "leftouter", tolerance = null,
@@ -2063,15 +2121,13 @@ class SortMergeAsOfJoinSuite extends QueryTest
// One partition: with several, the NULL right row could land apart from
the left rows and
// never be compared.
withSQLConf(SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
- val joined = left.joinAsOf(
- right, left.col("ts"), right.col("ts"), usingColumns = Seq("k"),
- joinType = "leftouter", tolerance = null,
- allowExactMatches = true, direction = "nearest")
- .select(left.col("k"), right.col("tag"))
- checkAnswer(joined, Row(-1, "minus one") :: Row(0, null) :: Nil)
- assert(collectFirst(joined.queryExecution.executedPlan) {
- case j: SortMergeAsOfJoinExec => j
- }.isDefined, s"Expected SortMergeAsOfJoinExec in
plan:\n${joined.queryExecution}")
+ checkAnswerCodegenOffAndOn(
+ left.joinAsOf(
+ right, left.col("ts"), right.col("ts"), usingColumns = Seq("k"),
+ joinType = "leftouter", tolerance = null,
+ allowExactMatches = true, direction = "nearest")
+ .select(left.col("k"), right.col("tag")),
+ Row(-1, "minus one") :: Row(0, null) :: Nil)
}
}
@@ -2089,24 +2145,27 @@ class SortMergeAsOfJoinSuite extends QueryTest
List(Row(null, 5, "a"), Row(1, 5, "b"), Row(null, 10, "c")).asJava,
schema1)
val df2 = spark.createDataFrame(
List(Row(null, 3, "x"), Row(1, 4, "y"), Row(null, 8, "z")).asJava,
schema2)
- val joined = df1.joinAsOf(
- df2, df1.col("ts"), df2.col("ts"),
- joinExprs = df1.col("grp") <=> df2.col("grp"),
- joinType = "inner", tolerance = null,
- allowExactMatches = true, direction = "backward")
- checkAnswer(
- joined,
- Seq(
- Row(null, 5, "a", null, 3, "x"),
- Row(1, 5, "b", 1, 4, "y"),
- Row(null, 10, "c", null, 8, "z")
+ withAsOfJoinCodegenOffAndOn { codegen =>
+ val joined = df1.joinAsOf(
+ df2, df1.col("ts"), df2.col("ts"),
+ joinExprs = df1.col("grp") <=> df2.col("grp"),
+ joinType = "inner", tolerance = null,
+ allowExactMatches = true, direction = "backward")
+ checkAnswer(
+ joined,
+ Seq(
+ Row(null, 5, "a", null, 3, "x"),
+ Row(1, 5, "b", 1, 4, "y"),
+ Row(null, 10, "c", null, 8, "z")
+ )
)
- )
- val plan = joined.queryExecution.executedPlan
- val asOfExecs = collectWithSubqueries(plan) { case j:
SortMergeAsOfJoinExec => j }
- assert(asOfExecs.length == 1, s"expected one SortMergeAsOfJoinExec
in:\n$plan")
- assert(asOfExecs.head.leftKeys.isEmpty && asOfExecs.head.rightKeys.isEmpty,
- s"<=> must be a residual, so equi-keys must be empty, got
${asOfExecs.head}")
+ assertAsOfJoinCodegen(joined, codegen)
+ val plan = joined.queryExecution.executedPlan
+ val asOfExecs = collectWithSubqueries(plan) { case j:
SortMergeAsOfJoinExec => j }
+ assert(asOfExecs.length == 1, s"expected one SortMergeAsOfJoinExec
in:\n$plan")
+ assert(asOfExecs.head.leftKeys.isEmpty &&
asOfExecs.head.rightKeys.isEmpty,
+ s"<=> must be a residual, so equi-keys must be empty, got
${asOfExecs.head}")
+ }
}
test("residual condition via joinExprs") {
@@ -2131,7 +2190,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
// Backward join with residual amount > threshold:
// left(A,10,50): scan right ts<=10: (8,60) 50>60? No; (5,40) 50>40? Yes
-> match (5,40)
// left(A,20,30): scan right ts<=20: (15,25) 30>25? Yes -> match (15,25)
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df1.joinAsOf(
df2, df1.col("ts"), df2.col("ts"),
joinExprs = (df1.col("grp") === df2.col("grp")) &&
@@ -2156,7 +2215,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
StructField("threshold", IntegerType) :: Nil)
val df1 = spark.createDataFrame(List(Row(4, 30), Row(5, 10)).asJava,
schema1)
val df2 = spark.createDataFrame(List(Row(6, 20), Row(9, 1)).asJava,
schema2)
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df1.joinAsOf(
df2, df1.col("ts"), df2.col("ts"),
joinExprs = df1.col("amount") > df2.col("threshold"),
@@ -2177,7 +2236,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
Seq(true, false).foreach { ansiEnabled =>
withSQLConf(SQLConf.ANSI_ENABLED.key -> ansiEnabled.toString) {
Seq(true, false).foreach { allowExactMatches =>
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df1.joinAsOf(
df2, df1.col("ts"), df2.col("ts"), usingColumns = Seq.empty,
joinType = "inner", tolerance = null,
@@ -2241,7 +2300,7 @@ class SortMergeAsOfJoinSuite extends QueryTest
)
)
// Equi-key (bufferRightGroup): at most one right row per group, so it
does not spill.
- checkAnswer(
+ checkAnswerCodegenOffAndOn(
df1.joinAsOf(
df2, df1.col("a"), df2.col("a"), usingColumns = Seq("b"),
joinType = "inner", tolerance = null,
@@ -2398,4 +2457,42 @@ class SortMergeAsOfJoinSuite extends QueryTest
)
}
}
+
+ Seq("backward", "forward").foreach { direction =>
+ test(s"generated $direction scan closes the spill readers of a group it
leaves early") {
+
assume(ManagementFactory.getOperatingSystemMXBean.isInstanceOf[UnixOperatingSystemMXBean],
+ "needs a JVM that counts its open files")
+ withSQLConf(
+ SQLConf.ENABLE_SORT_MERGE_AS_OF_JOIN_CODEGEN.key -> "true",
+ SQLConf.SORT_MERGE_JOIN_EXEC_BUFFER_IN_MEMORY_THRESHOLD.key -> "1",
+ SQLConf.SORT_MERGE_JOIN_EXEC_BUFFER_SPILL_THRESHOLD.key -> "10",
+ // The cursor scan never buffers, so turn it off to test the spill.
+ SQLConf.SORT_MERGE_AS_OF_JOIN_CURSOR_SCAN_ENABLED.key -> "false") {
+ // One right group of 50 rows that spills every 10 rows. Each left key
k matches the right
+ // key k, so every scan stops with the later spill files of the group
still unread.
+ val left = spark.range(1, 17).selectExpr("CAST(id AS INT) AS ts")
+ val right = spark.range(50).selectExpr("CAST(id AS INT) AS ts")
+ val df = left.joinAsOf(
+ right, left.col("ts"), right.col("ts"), usingColumns = Seq.empty,
+ joinType = "inner", tolerance = null,
+ allowExactMatches = true, direction = direction)
+ // Counts inside the task, since the task closes every spill reader
when it ends.
+ val results = df.queryExecution.toRdd.mapPartitions { rows =>
+ val bean = ManagementFactory.getOperatingSystemMXBean
+ .asInstanceOf[UnixOperatingSystemMXBean]
+ val before = bean.getOpenFileDescriptorCount
+ val matches = rows.map(row => (row.getInt(0), row.getInt(1))).toList
+ Iterator.single((matches, bean.getOpenFileDescriptorCount - before))
+ }.collect()
+ val plan = df.queryExecution.executedPlan
+ val join = collectFirst(plan) { case j: SortMergeAsOfJoinExec => j }
+ assert(join.exists(isGenerated(plan, _)), s"Expected the generated
scan in:\n$plan")
+ assert(join.get.metrics("spillSize").value > 0, "Expected the right
group to spill")
+ assert(results.length == 1, "Expected one task, since there is no ON
key")
+ val (matches, openedFiles) = results.head
+ assert(matches == (1 to 16).map(k => (k, k)).toList)
+ assert(openedFiles < 8, s"the scan left $openedFiles more files open")
+ }
+ }
+ }
}
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/TimestampNanosJoinSuiteBase.scala
b/sql/core/src/test/scala/org/apache/spark/sql/TimestampNanosJoinSuiteBase.scala
index 2157c2ecf929..b0526aaa066b 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/TimestampNanosJoinSuiteBase.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/TimestampNanosJoinSuiteBase.scala
@@ -24,9 +24,9 @@ import scala.jdk.CollectionConverters._
import org.apache.spark.SparkConf
import org.apache.spark.sql.catalyst.expressions.EqualTo
import org.apache.spark.sql.catalyst.plans.logical.Join
-import org.apache.spark.sql.execution.SparkPlan
+import org.apache.spark.sql.execution.{InputAdapter, SparkPlan,
WholeStageCodegenExec}
import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
-import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec,
ShuffledHashJoinExec, SortMergeJoinExec}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec,
ShuffledHashJoinExec, SortMergeAsOfJoinExec, SortMergeJoinExec}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.SharedSparkSession
import org.apache.spark.sql.types._
@@ -133,6 +133,16 @@ abstract class TimestampNanosJoinSuiteBase extends
SharedSparkSession with Adapt
}
}
+ /** Whether a sort-merge ASOF join of `plan` runs in a codegen stage, not
only in one below it. */
+ private def isAsOfJoinGenerated(plan: SparkPlan): Boolean = {
+ def inStage(node: SparkPlan): Boolean = node match {
+ case _: SortMergeAsOfJoinExec => true
+ case _: InputAdapter => false
+ case other => other.children.exists(inStage)
+ }
+ collect(plan) { case stage: WholeStageCodegenExec if inStage(stage.child)
=> stage }.nonEmpty
+ }
+
private def cgLabel(cgConf: Seq[(String, String)]): String =
if (cgConf.contains(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "true"))
"codegen on"
else "codegen off"
@@ -434,16 +444,29 @@ abstract class TimestampNanosJoinSuiteBase extends
SharedSparkSession with Adapt
(leftKey, rightRows, (backward, forward, nearest)) <- cases
(direction, expected) <-
Seq("backward" -> backward, "forward" -> forward, "nearest" ->
nearest)
- } withSQLConf(SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key ->
sortMerge) {
- val l = df(s"2020-01-01T$leftKey" -> 0)
- val r = df(rightRows.map { case (k, v) => s"2020-01-01T$k" -> v }:
_*)
- // The single-pass analyzer cannot resolve the deserializer
`checkToRDD` adds.
- QueryTest.checkAnswer(
- df = l.joinAsOf(r, l("k"), r("k"), usingColumns = Seq.empty,
joinType = "inner",
- tolerance = null, allowExactMatches = true, direction =
direction)
- .select(r("v")),
- expectedAnswer = Seq(Row(expected)),
- checkToRDD = false)
+ // Only a backward or forward sort-merge join has a generated scan.
+ codegen <-
+ (if (sortMerge == "true" && direction != "nearest") Seq(false,
true) else Seq(true))
+ } withClue(s"sort-merge $sortMerge, $direction, ASOF join codegen
$codegen: ") {
+ withSQLConf(
+ SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> sortMerge,
+ SQLConf.ENABLE_SORT_MERGE_AS_OF_JOIN_CODEGEN.key ->
codegen.toString) {
+ val l = df(s"2020-01-01T$leftKey" -> 0)
+ val r = df(rightRows.map { case (k, v) => s"2020-01-01T$k" -> v
}: _*)
+ val joined = l.joinAsOf(r, l("k"), r("k"), usingColumns =
Seq.empty,
+ joinType = "inner", tolerance = null, allowExactMatches = true,
+ direction = direction).select(r("v"))
+ // The single-pass analyzer cannot resolve the deserializer
`checkToRDD` adds.
+ QueryTest.checkAnswer(
+ df = joined, expectedAnswer = Seq(Row(expected)), checkToRDD =
false)
+ val plan = joined.queryExecution.executedPlan
+ assert(collectFirst(plan) { case j: SortMergeAsOfJoinExec => j
}.isDefined ==
+ (sortMerge == "true"), s"Unexpected sort-merge ASOF join
choice in:\n$plan")
+ if (sortMerge == "true") {
+ assert(isAsOfJoinGenerated(plan) == (codegen && direction !=
"nearest"),
+ s"Unexpected ASOF join codegen in:\n$plan")
+ }
+ }
}
// A nanosecond subtraction in an as-of key or in the join condition
is still rejected.
Seq(
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/execution/UnionCodegenSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/execution/UnionCodegenSuite.scala
index 43797cca0692..a393885bc293 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/execution/UnionCodegenSuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/execution/UnionCodegenSuite.scala
@@ -27,6 +27,7 @@ import org.apache.spark.sql.catalyst.trees.TreeNodeTag
import org.apache.spark.sql.execution.adaptive.{AdaptiveSparkPlanExec,
AdaptiveSparkPlanHelper}
import org.apache.spark.sql.execution.columnar.InMemoryTableScanLike
import org.apache.spark.sql.execution.exchange.{EnsureRequirements,
REPARTITION_BY_NUM, ShuffleExchangeExec}
+import org.apache.spark.sql.execution.joins.SortMergeAsOfJoinExec
import org.apache.spark.sql.functions._
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.SharedSparkSession
@@ -589,6 +590,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`, backward or nearest: each key has one right
row, just before. */
+ private val asOfJoinUnionRows =
+ (0L until 10L).map(k => Row(k, 2 * k - 1)) ++ (100L until 103L).map(k =>
Row(k, k))
+
+ test("Sort-merge ASOF join child union correctness") {
+ // A generated ASOF join reads two RDDs, so the union must not fuse: each
child of a fused
+ // union must give it one RDD, so the query would fail.
+ withSQLConf(
+ SQLConf.WHOLESTAGE_UNION_CODEGEN_ENABLED.key -> "true",
+ SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> "true",
+ SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1") {
+ val (fused, _) = assertFlagParity(() => asOfJoinUnion("backward"))
+ checkAnswer(fused, asOfJoinUnionRows)
+ // The ASOF join has to run in a codegen stage, or this test does not
reach the denylist.
+ def inStage(plan: SparkPlan): Boolean = plan match {
+ case _: SortMergeAsOfJoinExec => true
+ case _: InputAdapter => false
+ case other => other.children.exists(inStage)
+ }
+ assert(collect(fused.queryExecution.executedPlan) {
+ case stage: WholeStageCodegenExec if inStage(stage.child) => stage
+ }.nonEmpty, s"expected the ASOF join in a codegen
stage:\n${fused.queryExecution}")
+ assert(codegenUnions(fused).isEmpty,
+ s"the denylist has to keep this union out of
codegen:\n${fused.queryExecution}")
+ }
+ }
+
+ test("Union over a sort-merge ASOF join that does not generate code still
fuses") {
+ // A nearest join, or any ASOF join with its codegen off, sits behind an
InputAdapter and
+ // gives the union one RDD, so the union keeps its codegen.
+ Seq(("nearest", "true"), ("backward", "false")).foreach { case (direction,
asOfCodegen) =>
+ withClue(s"$direction, ASOF join codegen $asOfCodegen: ") {
+ withSQLConf(
+ SQLConf.WHOLESTAGE_UNION_CODEGEN_ENABLED.key -> "true",
+ SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> "true",
+ SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+ SQLConf.ENABLE_SORT_MERGE_AS_OF_JOIN_CODEGEN.key -> asOfCodegen) {
+ val (fused, _) = assertFlagParity(() => asOfJoinUnion(direction))
+ checkAnswer(fused, asOfJoinUnionRows)
+ assert(codegenUnions(fused).nonEmpty,
+ s"the union has to take part in codegen:\n${fused.queryExecution}")
+ }
+ }
+ }
+ }
+
+ test("Union over a sort-merge ASOF join keeps its plan when the ASOF codegen
conf changes") {
+ // The join records the conf when it is planned, and both the codegen
stages and the union's
+ // codegen check read that record. If the check read the live conf
instead, turning it on
+ // after a union fused over a join planned without codegen would leave the
union without its
+ // numOutputRows metric, and the query would fail.
+ Seq(("false", "true"), ("true", "false")).foreach { case (planned, atRun)
=>
+ withClue(s"ASOF join codegen $planned when planned, $atRun when run: ") {
+ withSQLConf(
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+ SQLConf.WHOLESTAGE_UNION_CODEGEN_ENABLED.key -> "true",
+ SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> "true",
+ SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+ SQLConf.ENABLE_SORT_MERGE_AS_OF_JOIN_CODEGEN.key -> planned) {
+ val df = asOfJoinUnion("backward")
+ df.queryExecution.executedPlan
+ withSQLConf(SQLConf.ENABLE_SORT_MERGE_AS_OF_JOIN_CODEGEN.key ->
atRun) {
+ checkAnswer(df, asOfJoinUnionRows)
+ }
+ // The union fuses only over a join that was planned without codegen.
+ assert(codegenUnions(df).nonEmpty == (planned == "false"),
+ s"unexpected union codegen:\n${df.queryExecution}")
+ }
+ }
+ }
+ }
+
//
---------------------------------------------------------------------------
// Columnar fallback
//
---------------------------------------------------------------------------
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala
index c4a81d60a59a..0444471df733 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala
@@ -41,7 +41,7 @@ import
org.apache.spark.sql.execution.adaptive.DisableAdaptiveExecutionSuite
import org.apache.spark.sql.execution.aggregate.{HashAggregateExec,
SortAggregateExec}
import org.apache.spark.sql.execution.columnar.InMemoryTableScanExec
import org.apache.spark.sql.execution.debug.{codegenString, codegenStringSeq}
-import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec,
BroadcastNestedLoopJoinExec, CartesianProductExec, ShuffledHashJoinExec,
SortMergeJoinExec}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec,
BroadcastNestedLoopJoinExec, CartesianProductExec, ShuffledHashJoinExec,
SortMergeAsOfJoinExec, SortMergeJoinExec}
import org.apache.spark.sql.functions._
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.SharedSparkSession
@@ -639,6 +639,100 @@ class WholeStageCodegenSuite extends SharedSparkSession
checkAnswer(twoJoinsDF, Seq(Row(6), Row(7), Row(8), Row(9)))
}
+ test("Backward and forward sort-merge ASOF joins should be included in
WholeStageCodegen") {
+ // One partition puts every key in one task, so the scan has to move
between keys.
+ withSQLConf(
+ SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> "true",
+ SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+ val trades = Seq((5, 1), (11, 1), (12, 2), (3, 3)).toDF("ts", "k")
+ val quotes = Seq((0, 1, "a"), (7, 1, "b"), (10, 1, "c"), (8, 2, "d"),
(9, 3, "e"))
+ .toDF("ts", "k", "v")
+ def asOfJoin(joinType: String, direction: String, tolerance:
Option[Int]): DataFrame =
+ trades.joinAsOf(
+ quotes, trades("ts"), quotes("ts"), usingColumns = Seq("k"),
joinType = joinType,
+ tolerance = tolerance.map(lit).orNull, allowExactMatches = true,
direction = direction)
+ // Whether the ASOF join runs in a codegen stage, and not only in a
stage below it.
+ def isGenerated(df: DataFrame): Boolean = {
+ def inStage(plan: SparkPlan): Boolean = plan match {
+ case _: SortMergeAsOfJoinExec => true
+ case _: InputAdapter => false
+ case other => other.children.exists(inStage)
+ }
+ df.queryExecution.executedPlan.collect {
+ case stage: WholeStageCodegenExec if inStage(stage.child) => stage
+ }.nonEmpty
+ }
+ // Whether the plan has the ASOF join at all, so a "not generated" check
cannot pass on a
+ // plan without it.
+ def hasAsOfJoin(df: DataFrame): Boolean =
+
df.queryExecution.executedPlan.exists(_.isInstanceOf[SortMergeAsOfJoinExec])
+ // How many tasks of the ASOF join used the cursor scan, read after the
join ran.
+ def cursorTasks(df: DataFrame): Long =
df.queryExecution.executedPlan.collect {
+ case j: SortMergeAsOfJoinExec => j.metrics("numAsOfCursorTasks").value
+ }.sum
+
+ // Cursor scan: the last quote at or before each trade. The only quote
of key 3 is after
+ // trade 3, so trade 3 gets none. A cursor that kept key 2's quote would
give it "d".
+ val backward = asOfJoin("inner", "backward", None)
+ assert(isGenerated(backward))
+ checkAnswer(backward,
+ Seq(Row(5, 1, 0, 1, "a"), Row(11, 1, 10, 1, "c"), Row(12, 2, 8, 2,
"d")))
+ assert(cursorTasks(backward) > 0, "Expected the cursor scan")
+
+ // Cursor scan, forward: a trade with no later quote keeps nulls in a
left outer join.
+ val forward = asOfJoin("leftouter", "forward", None)
+ assert(isGenerated(forward))
+ checkAnswer(forward, Seq(Row(5, 1, 7, 1, "b"), Row(11, 1, null, null,
null),
+ Row(12, 2, null, null, null), Row(3, 3, 9, 3, "e")))
+ assert(cursorTasks(forward) > 0, "Expected the cursor scan")
+
+ // Buffered scan: with a tolerance of 2, only trade 11 has a quote close
enough.
+ val buffered = asOfJoin("inner", "backward", Some(2))
+ assert(isGenerated(buffered))
+ checkAnswer(buffered, Seq(Row(11, 1, 10, 1, "c")))
+ assert(cursorTasks(buffered) == 0, "Expected the buffered scan")
+
+ // Nearest joins keep the interpreted scan.
+ val nearest = asOfJoin("inner", "nearest", None)
+ assert(hasAsOfJoin(nearest) && !isGenerated(nearest))
+ checkAnswer(nearest, Seq(Row(5, 1, 7, 1, "b"), Row(11, 1, 10, 1, "c"),
+ Row(12, 2, 8, 2, "d"), Row(3, 3, 9, 3, "e")))
+
+ // With the codegen off, the interpreted scan gives the same rows.
+ withSQLConf(SQLConf.ENABLE_SORT_MERGE_AS_OF_JOIN_CODEGEN.key -> "false")
{
+ val off = asOfJoin("inner", "backward", None)
+ assert(hasAsOfJoin(off) && !isGenerated(off))
+ checkAnswer(off, Seq(Row(5, 1, 0, 1, "a"), Row(11, 1, 10, 1, "c"),
Row(12, 2, 8, 2, "d")))
+ }
+ }
+ }
+
+ test("A skewed sort-merge ASOF join should generate code that compiles") {
+ withSQLConf(SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> "true") {
+ val trades = Seq((5, 1), (11, 1)).toDF("ts", "k")
+ val quotes = Seq((0, 1, "a"), (10, 1, "c")).toDF("ts", "k", "v")
+ val df = trades.joinAsOf(
+ quotes, trades("ts"), quotes("ts"), usingColumns = Seq("k"), joinType
= "inner",
+ tolerance = null, allowExactMatches = true, direction = "backward")
+ // No skew rule marks an ASOF join here, so mark it by hand. The skew
changes its name.
+ val skewed = df.queryExecution.executedPlan.transform {
+ case j: SortMergeAsOfJoinExec => j.copy(isSkewJoin = true)
+ }
+ def inStage(plan: SparkPlan): Boolean = plan match {
+ case j: SortMergeAsOfJoinExec => j.isSkewJoin
+ case _: InputAdapter => false
+ case other => other.children.exists(inStage)
+ }
+ val stages = skewed.collect {
+ case stage: WholeStageCodegenExec if inStage(stage.child) => stage
+ }
+ assert(stages.length == 1, s"Expected the skewed join in one codegen
stage:\n$skewed")
+ // Without its own variable prefix, the join names its variables after
+ // "SortMergeAsOfJoin(skew=true)" and the code does not compile.
+ CodeGenerator.compile(stages.head.doCodeGen()._2)
+ }
+ }
+
test("Inner/Cross BroadcastNestedLoopJoinExec should be included in
WholeStageCodegen") {
val df1 = spark.range(4).select($"id".as("k1"))
val df2 = spark.range(3).select($"id".as("k2"))
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/execution/metric/SQLMetricsSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/execution/metric/SQLMetricsSuite.scala
index ddad172f7f81..59448614edde 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/execution/metric/SQLMetricsSuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/execution/metric/SQLMetricsSuite.scala
@@ -447,14 +447,32 @@ class SQLMetricsSuite extends SharedSparkSession with
SQLMetricsTestUtils
}
test("SortMergeAsOfJoin metrics") {
- // Only numOutputRows here; spillSize is covered in SortMergeAsOfJoinSuite.
- def checkNumOutputRows(df: DataFrame, expected: Long): Unit = {
- df.collect()
- val op = df.queryExecution.executedPlan.collectFirst {
- case s: SortMergeAsOfJoinExec => s
+ // Only numOutputRows here; spillSize is covered in
SortMergeAsOfJoinSuite. Each check runs
+ // with the ASOF join codegen off and on, on a new DataFrame each time,
since a DataFrame
+ // keeps the plan it got first.
+ def checkNumOutputRows(df: => DataFrame, expected: Long): Unit = {
+ // Whether the join runs in a codegen stage, and not only in a stage
below it.
+ def inStage(plan: SparkPlan): Boolean = plan match {
+ case _: SortMergeAsOfJoinExec => true
+ case _: InputAdapter => false
+ case other => other.children.exists(inStage)
+ }
+ 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
+ query.collect()
+ val plan = query.queryExecution.executedPlan
+ val op = plan.collectFirst { case s: SortMergeAsOfJoinExec => s }
+ assert(op.isDefined, "The query plan should have
SortMergeAsOfJoin")
+ val generated = plan.collect {
+ case stage: WholeStageCodegenExec if inStage(stage.child) =>
stage
+ }.nonEmpty
+ assert(generated == codegen, s"Unexpected ASOF join codegen
in:\n$plan")
+ testMetricsInSparkPlanOperator(op.get, Map("numOutputRows" ->
expected))
+ }
+ }
}
- assert(op.isDefined, "The query plan should have SortMergeAsOfJoin")
- testMetricsInSparkPlanOperator(op.get, Map("numOutputRows" -> expected))
}
withSQLConf(SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> "true") {
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]