This is an automated email from the ASF dual-hosted git repository.

cloud-fan pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/master by this push:
     new 6e62c68b2c75 [SPARK-61505][SQL] Never build the left side of a 
non-equi LeftSingle join
6e62c68b2c75 is described below

commit 6e62c68b2c75e5bee4957cbf1ccdb0e94cf5cf06
Author: Xi Liang <[email protected]>
AuthorDate: Fri Nov 13 10:04:28 2026 +0000

    [SPARK-61505][SQL] Never build the left side of a non-equi LeftSingle join
    
    ### What changes were proposed in this pull request?
    
    A LeftSingle join without equi-join keys fails at execution when the 
planner builds its left side. This PR stops the planner from choosing that side.
    
    `JoinSelectionHelper.getNonEquiJoinBuildSide`, which `JoinSelection` calls 
with and without AQE, chooses the side that a join without equi-join keys 
builds in three steps: the hint pass, then the size pass, then a last resort 
when no side qualifies in either pass. (An inner join may get a Cartesian 
product instead of a build side.) A side qualifies in the hint pass if it has a 
broadcast hint, and in the size pass if its estimated size is at most the 
broadcast threshold (for runtime st [...]
    
    With this PR, the left side never qualifies in either pass when the join 
type is LeftSingle: the left side's qualification test in the shared helper of 
both passes now starts with `joinType == LeftSingle`, which makes it false. A 
LeftSingle join then builds its right side: in the first pass in which the 
right side qualifies, and otherwise in the last resort. Joins of every other 
type keep their build side. The scaladoc of `getNonEquiJoinBuildSide` now says 
that a LeftSingle join alway [...]
    
    ### Why are the changes needed?
    
    With `spark.sql.optimizer.scalarSubqueryUseSingleJoin` on (the default 
since 4.0.0), a correlated scalar subquery that the optimizer can't prove 
returns at most one row becomes a LeftSingle join. Its left side is the outer 
query and its right side is the subquery. When that join has no equi-join keys, 
for example because the correlation is a range predicate such as `id < l.a` 
below, it runs as a `BroadcastNestedLoopJoinExec`, the only operator for such a 
join. `BroadcastNestedLoopJoin [...]
    
    ```sql
    SET spark.sql.autoBroadcastJoinThreshold=1000;
    SET spark.sql.adaptive.autoBroadcastJoinThreshold=1000;
    SELECT a, (SELECT id FROM range(0, 1000) WHERE id < l.a) AS s FROM VALUES 
(0), (1) AS l(a);
    -- expected: (0, NULL), (1, 0)
    -- actual: java.lang.IllegalArgumentException: BroadcastNestedLoopJoin 
should not use the left side as build when executing a LeftSingle join
    ```
    
    In this query, the size pass builds the left side: the outer side is 
estimated at 24 bytes, under the 1000-byte thresholds, and `range(0, 1000)` at 
8000 bytes, over them. The small thresholds only keep the example's data small. 
With the default thresholds (10MB) and no hints, the same happens when the 
outer side is estimated under 10MB and the subquery side over it. The hint pass 
also builds the left side when only the left side has a broadcast hint.
    
    `BroadcastNestedLoopJoinExec` runs every other join type with either build 
side, so only LeftSingle joins fail. The right side is the only build side it 
supports for a LeftSingle join, which must emit NULL for an outer row with no 
match and raise `SCALAR_SUBQUERY_TOO_MANY_ROWS` for an outer row with more than 
one. Its left-build path for outer joins tracks only whether each left row 
matched, so it can't tell one match from several. Choosing the right side in 
the planner is the smaller [...]
    
    SPARK-49653 (#48145) added the LeftSingle join and the check in 
`BroadcastNestedLoopJoinExec` that throws, and made the last resort build the 
right side of a LeftSingle join, but did not change the hint and size passes. 
On master, SPARK-60941 (#60144) then moved the build-side choice for joins 
without equi-join keys, unchanged, from `JoinSelection` into 
`getNonEquiJoinBuildSide`.
    
    The released 4.0.0 and 4.3.0 fail the same way: the query above, run with 
pyspark 4.0.0 and 4.3.0 from PyPI with AQE on and off, throws the same 
`IllegalArgumentException`. In those releases the choice is still inline in 
`JoinSelection`. The 4.1.0 and 4.2.0 sources have the same hint and size 
passes, the same check in `BroadcastNestedLoopJoinExec` and the same conf 
default; the query was not run on them. A backport to the 4.x release branches 
would add the same check to the inline pas [...]
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, a bug fix. The result of `getNonEquiJoinBuildSide` changes only where 
it was `BuildLeft` for a LeftSingle join, and such a join fails whenever it 
runs with that build side. With AQE, re-planning can replace an initial plan 
that builds the left side before the join runs, so such a query could run 
before if re-planning chose the right side. Re-planning calls the same 
function, which now never returns `BuildLeft` for a LeftSingle join, so such a 
query still ends with its join buildi [...]
    
    A LeftSingle join that built its left side now builds its right (subquery) 
side, and the query runs: it returns the correct rows, or fails with 
`SCALAR_SUBQUERY_TOO_MANY_ROWS` when more than one subquery row matches an 
outer row. The subquery side is broadcast whatever its size, as it already is 
in the last resort, so a very large subquery side can now fail at broadcast 
time instead: on the broadcast size or row limits, on 
`spark.sql.broadcastTimeout`, or on driver memory. Such querie [...]
    
    A broadcast hint on the left (outer) side of such a join is now not 
applied, and no warning is logged; before, it made the query fail. The right 
side is built even when it is hinted `NO_BROADCAST_AND_REPLICATION`, as the 
last resort already does; Spark itself sets that internal hint only on the 
target side of a rewritten MERGE. Joins of other types keep their build side.
    
    ### How was this patch tested?
    
    New tests that fail without the fix:
    - `JoinSelectionHelperSuite`: six joins without equi-join keys in which 
only the left side qualifies in the first pass in which any side qualifies. In 
four, the size pass decides: the left side is small by its static size; small 
only by its runtime size (over `spark.sql.autoBroadcastJoinThreshold`, under 
`spark.sql.adaptive.autoBroadcastJoinThreshold`); or small, with a 
`SHUFFLE_HASH` or `NO_BROADCAST_AND_REPLICATION` hint on the large right side, 
which sends the join through the hint [...]
    - `SingleJoinSuite` (an existing suite), with AQE on and off: the query 
above plans a LeftSingle `BroadcastNestedLoopJoinExec` that builds its right 
side, before and after the query runs, and returns (0, NULL), (1, 0). A variant 
in which two subquery rows match one outer row fails with 
`SCALAR_SUBQUERY_TOO_MANY_ROWS`. Without the fix, the plan builds the left 
side, and the variant throws the `IllegalArgumentException`.
    
    A new test in `JoinSelectionHelperSuite` that passes with and without the 
fix: in seven more joins without equi-join keys, a LeftSingle join builds its 
right side. They are: only the right side small; both sides small; neither side 
small; the right side hinted to broadcast; both sides hinted; neither side 
small with a `SHUFFLE_REPLICATE_NL` hint on the left side, which doesn't apply 
to a LeftSingle join; and the left side small but hinted 
`NO_BROADCAST_AND_REPLICATION`.
    
    The query above, with its `SET` statements, was also run on master through 
a temporary test, with AQE on and off: without the fix it throws the 
`IllegalArgumentException`, and with the fix it returns (0, NULL), (1, 0).
    
    Also ran `JoinHintSuite`, `JoinSuite`, `SubquerySuite` and the 
`subquery/scalar-subquery` files of `SQLQueryTestSuite`, which pass. The Python 
UDF tests of `JoinSuite` and `SubquerySuite` were canceled locally for lack of 
Python.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Code (Claude Opus 5.5)
    
    This pull request and its description were written by Isaac.
    
    Closes #60376 from xiliang678/leftsingle-nonequi-build-right.
    
    Authored-by: Xi Liang <[email protected]>
    Signed-off-by: Wenchen Fan <[email protected]>
    
    
    skip-checks: true
---
 .../spark/sql/catalyst/optimizer/joins.scala       | 13 +++-
 .../optimizer/JoinSelectionHelperSuite.scala       | 81 +++++++++++++++++++++-
 .../sql/execution/joins/SingleJoinSuite.scala      | 53 +++++++++++++-
 3 files changed, 141 insertions(+), 6 deletions(-)

diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/joins.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/joins.scala
index 45b27a4a78da..8895f59cab45 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/joins.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/joins.scala
@@ -366,7 +366,8 @@ trait JoinSelectionHelper extends Logging {
    * join requires or prefers, however large. A side hinted 
NO_BROADCAST_AND_REPLICATION is never
    * broadcast by size, and the hint rules out a Cartesian product, so the 
other side is built. Of
    * two candidate sides, it builds the smaller for an inner or full join, the 
left for a right
-   * join, and the right for a left join.
+   * join, and the right for a left join. A LeftSingle join, though, always 
builds its right side,
+   * the only side `BroadcastNestedLoopJoinExec` can build for it, whatever 
the hints and sizes.
    */
   def getNonEquiJoinBuildSide(join: Join, conf: SQLConf): Option[BuildSide] = {
     val Join(left, right, joinType, _, hint) = join
@@ -380,9 +381,15 @@ trait JoinSelectionHelper extends Logging {
       if (canBuildBroadcastLeft(joinType)) BuildLeft else BuildRight
     }
 
-    // The side to broadcast by hint, or by size, if any.
+    // The side to broadcast by hint, or by size, if any. 
`BroadcastNestedLoopJoinExec` can't build
+    // the left side of a LeftSingle join, so that side never qualifies.
+    // TODO: teach `BroadcastNestedLoopJoinExec` to build the left side of a 
LeftSingle join by
+    // detecting more than one match per left row, so a small outer side can 
be broadcast instead
+    // of a large subquery side.
     def broadcastSide(onlyLookingAtHint: Boolean): Option[BuildSide] = {
-      val buildLeft = if (onlyLookingAtHint) {
+      val buildLeft = if (joinType == LeftSingle) {
+        false
+      } else if (onlyLookingAtHint) {
         hintToBroadcastLeft(hint)
       } else {
         canBroadcastBySize(left, conf) && 
!hintToNotBroadcastAndReplicateLeft(hint)
diff --git 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/JoinSelectionHelperSuite.scala
 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/JoinSelectionHelperSuite.scala
index fc8de40dfb1f..e7ec555b6bee 100644
--- 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/JoinSelectionHelperSuite.scala
+++ 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/JoinSelectionHelperSuite.scala
@@ -19,7 +19,7 @@ package org.apache.spark.sql.catalyst.optimizer
 
 import org.apache.spark.sql.catalyst.dsl.expressions._
 import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeMap, 
EqualTo, IsNull, Or}
-import org.apache.spark.sql.catalyst.plans.{Inner, LeftAnti, LeftOuter, 
PlanTest, RightOuter}
+import org.apache.spark.sql.catalyst.plans.{ExistenceJoin, FullOuter, Inner, 
JoinType, LeftAnti, LeftOuter, LeftSemi, LeftSingle, PlanTest, RightOuter}
 import org.apache.spark.sql.catalyst.plans.logical.{BROADCAST, HintInfo, Join, 
JoinHint, LeafNode, LogicalPlan, NO_BROADCAST_AND_REPLICATION, 
NO_BROADCAST_HASH, SHUFFLE_HASH, SHUFFLE_REPLICATE_NL, Statistics}
 import org.apache.spark.sql.catalyst.statsEstimation.StatsTestPlan
 import org.apache.spark.sql.internal.SQLConf
@@ -254,6 +254,85 @@ class JoinSelectionHelperSuite extends PlanTest with 
JoinSelectionHelper {
     }
   }
 
+  // Runs `f` with a 1MB static and a 10MB adaptive broadcast threshold, so 
that `right` (1000
+  // bytes) is small, `left` (20MB) is not, and a side whose runtime size is 
5MB is small too.
+  private def withNonEquiJoinThresholds(f: => Unit): Unit = withSQLConf(
+    SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "1MB",
+    SQLConf.ADAPTIVE_AUTO_BROADCASTJOIN_THRESHOLD.key -> "10MB")(f)
+
+  // Returns a line for each join without equi-join keys, given as (scenario, 
left side, right
+  // side, hint), and each of `joinTypes` whose build side is not 
`expected(joinType)`.
+  private def nonEquiBuildSideMismatches(
+      scenarios: Seq[(String, LogicalPlan, LogicalPlan, JoinHint)],
+      joinTypes: Seq[JoinType])(
+      expected: JoinType => Option[BuildSide]): Seq[String] = {
+    for {
+      (scenario, leftPlan, rightPlan, hint) <- scenarios
+      joinType <- joinTypes
+      actual = getNonEquiJoinBuildSide(Join(leftPlan, rightPlan, joinType, 
None, hint), SQLConf.get)
+      if actual != expected(joinType)
+    } yield s"$scenario, $joinType: $actual, expected ${expected(joinType)}"
+  }
+
+  test("SPARK-61505: getNonEquiJoinBuildSide never builds the left side of a 
LeftSingle join") {
+    case class RuntimeStatsPlan(size: BigInt) extends LeafNode {
+      override def output: Seq[Attribute] = right.output
+      override def computeStats(): Statistics = Statistics(sizeInBytes = size, 
isRuntime = true)
+    }
+    val otherLeft = left.copy(outputList = Seq($"e".int))
+    val hintNoBroadcastAndReplication = 
Some(HintInfo(Some(NO_BROADCAST_AND_REPLICATION)))
+    // Joins in which only the left side qualifies for broadcast: it alone has 
a broadcast hint
+    // or, with no broadcast hint, it alone is small.
+    val scenarios = Seq(
+      ("only the left side is small", right, left, JoinHint.NONE),
+      ("only the left side is small, by its runtime size",
+        RuntimeStatsPlan(5 * 1024 * 1024), left, JoinHint.NONE),
+      ("only the left side is hinted and neither side is small",
+        left, otherLeft, JoinHint(hintBroadcast, None)),
+      ("only the left side is hinted and only the right side is small",
+        left, right, JoinHint(hintBroadcast, None)),
+      ("only the left side is small and the right side has a shuffle hash 
hint",
+        right, left, JoinHint(None, hintShuffleHash)),
+      ("only the left side is small and the right side is hinted 
NO_BROADCAST_AND_REPLICATION",
+        right, left, JoinHint(None, hintNoBroadcastAndReplication)))
+    val joinTypes = Seq(Inner, LeftOuter, RightOuter, FullOuter, LeftSemi, 
LeftAnti,
+      ExistenceJoin($"exists".boolean), LeftSingle)
+    withNonEquiJoinThresholds {
+      // BroadcastNestedLoopJoinExec can't build the left side of a LeftSingle 
join, so a
+      // LeftSingle join builds its right side even here. The other join types 
build their left.
+      val mismatches = nonEquiBuildSideMismatches(scenarios, joinTypes) { 
joinType =>
+        if (joinType == LeftSingle) Some(BuildRight) else Some(BuildLeft)
+      }
+      assert(mismatches.isEmpty, mismatches.mkString("\n"))
+    }
+  }
+
+  test("getNonEquiJoinBuildSide builds the right side of a LeftSingle join 
that can broadcast " +
+      "it or neither side") {
+    val otherLeft = left.copy(outputList = Seq($"e".int))
+    val otherRight = right.copy(outputList = Seq($"f".int))
+    val hintNoBroadcastAndReplication = 
Some(HintInfo(Some(NO_BROADCAST_AND_REPLICATION)))
+    val scenarios = Seq(
+      ("only the right side is small", left, right, JoinHint.NONE),
+      ("both sides are small", right, otherRight, JoinHint.NONE),
+      ("neither side is small", left, otherLeft, JoinHint.NONE),
+      ("only the right side is hinted and only the left side is small",
+        right, left, JoinHint(None, hintBroadcast)),
+      ("both sides are hinted and neither side is small",
+        left, otherLeft, JoinHint(hintBroadcast, hintBroadcast)),
+      // A LeftSingle join can't be a Cartesian product, so the hint doesn't 
apply.
+      ("neither side is small and the left side has a shuffle-replicate hint",
+        left, otherLeft, JoinHint(Some(HintInfo(Some(SHUFFLE_REPLICATE_NL))), 
None)),
+      ("only the left side is small and it is hinted 
NO_BROADCAST_AND_REPLICATION",
+        right, left, JoinHint(hintNoBroadcastAndReplication, None)))
+    withNonEquiJoinThresholds {
+      val mismatches = nonEquiBuildSideMismatches(scenarios, Seq(LeftSingle)) 
{ _ =>
+        Some(BuildRight)
+      }
+      assert(mismatches.isEmpty, mismatches.mkString("\n"))
+    }
+  }
+
   test("NAAJ broadcast threshold is floored by the automatic broadcast 
threshold") {
     val betweenThresholdsRight = right.copy(
       rowCount = 8 * 1024 * 1024,
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/joins/SingleJoinSuite.scala
 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/joins/SingleJoinSuite.scala
index 7183fee3589f..53abb2f12b45 100644
--- 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/joins/SingleJoinSuite.scala
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/joins/SingleJoinSuite.scala
@@ -20,17 +20,19 @@ package org.apache.spark.sql.execution.joins
 import org.apache.spark.SparkRuntimeException
 import org.apache.spark.sql.{QueryTest, Row}
 import org.apache.spark.sql.catalyst.expressions._
-import org.apache.spark.sql.catalyst.optimizer.BuildRight
+import org.apache.spark.sql.catalyst.optimizer.{BuildRight, BuildSide}
 import org.apache.spark.sql.catalyst.planning.ExtractEquiJoinKeys
 import org.apache.spark.sql.catalyst.plans._
 import org.apache.spark.sql.catalyst.plans.logical.{Join, JoinHint, Project}
 import org.apache.spark.sql.classic.DataFrame
 import org.apache.spark.sql.execution.SparkPlan
+import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
 import org.apache.spark.sql.execution.exchange.EnsureRequirements
+import org.apache.spark.sql.internal.SQLConf
 import org.apache.spark.sql.test.SharedSparkSession
 import org.apache.spark.sql.types.{DoubleType, IntegerType, StructType}
 
-class SingleJoinSuite extends SharedSparkSession {
+class SingleJoinSuite extends SharedSparkSession with AdaptiveSparkPlanHelper {
   import testImplicits.toRichColumn
 
   private val EnsureRequirements = new EnsureRequirements()
@@ -202,4 +204,51 @@ class SingleJoinSuite extends SharedSparkSession {
     right,
     Some(EqualTo(emptyFrame.col("c").expr, right.col("c").expr)),
     Seq.empty)
+
+  // Runs `f` with single joins on and both broadcast thresholds at 1000 
bytes. Then in the queries
+  // below the outer side, two rows of `VALUES`, is small enough to broadcast, 
and the subquery
+  // side, `range(0, 1000)` (8000 bytes), is not.
+  private def withNonEquiScalarSubqueryConf(aqeEnabled: Boolean)(f: => Unit): 
Unit = {
+    withSQLConf(
+      SQLConf.SCALAR_SUBQUERY_USE_SINGLE_JOIN.key -> "true",
+      SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqeEnabled.toString,
+      SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "1000",
+      SQLConf.ADAPTIVE_AUTO_BROADCASTJOIN_THRESHOLD.key -> "1000")(f)
+  }
+
+  // The join type and build side of each BroadcastNestedLoopJoinExec in the 
plan of `df`: with
+  // AQE, the initial plan before `df` runs and the final plan after.
+  private def nestedLoopJoins(df: DataFrame): Seq[(JoinType, BuildSide)] =
+    collect(df.queryExecution.executedPlan) {
+      case j: BroadcastNestedLoopJoinExec => (j.joinType, j.buildSide)
+    }
+
+  Seq(true, false).foreach { aqeEnabled =>
+    // A correlated scalar subquery whose correlation is not an equality 
becomes a LeftSingle join
+    // without equi-join keys. Its left side is the outer query, the only side 
small enough to
+    // broadcast, but BroadcastNestedLoopJoinExec can't build the left side of 
a LeftSingle join.
+    test("SPARK-61505: non-equi scalar subquery with a small outer side builds 
the subquery " +
+        s"side, AQE enabled: $aqeEnabled") {
+      withNonEquiScalarSubqueryConf(aqeEnabled) {
+        val df = sql("SELECT a, (SELECT id FROM range(0, 1000) WHERE id < l.a) 
AS s " +
+          "FROM VALUES (0), (1) AS l(a)")
+        assert(nestedLoopJoins(df) === Seq((LeftSingle, BuildRight)))
+        checkAnswer(df, Seq(Row(0, null), Row(1, 0L)))
+        assert(nestedLoopJoins(df) === Seq((LeftSingle, BuildRight)))
+      }
+    }
+
+    test("SPARK-61505: non-equi scalar subquery with a small outer side checks 
for too many " +
+        s"rows, AQE enabled: $aqeEnabled") {
+      withNonEquiScalarSubqueryConf(aqeEnabled) {
+        // For a = 2 the subquery returns the ids 0 and 1.
+        val df = sql("SELECT a, (SELECT id FROM range(0, 1000) WHERE id < l.a) 
AS s " +
+          "FROM VALUES (0), (2) AS l(a)")
+        checkError(
+          exception = intercept[SparkRuntimeException](df.collect()),
+          condition = "SCALAR_SUBQUERY_TOO_MANY_ROWS",
+          parameters = Map.empty)
+      }
+    }
+  }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to