You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by we...@apache.org on 2026/09/25 09:14:12 UTC

(spark) branch branch-4.x updated: [SPARK-59673][SQL] Floor the NAAJ broadcast threshold

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 66a76eb2c120 [SPARK-59673][SQL] Floor the NAAJ broadcast threshold
66a76eb2c120 is described below

commit 66a76eb2c1204528f0cce1cd2944f3737e5f9841
Author: Wenchen Fan <we...@databricks.com>
AuthorDate: Fri Sep 25 09:13:39 2026 +0000

    [SPARK-59673][SQL] Floor the NAAJ broadcast threshold
    
    ### What changes were proposed in this pull request?
    
    For a nonnegative `spark.sql.optimizeNullAwareAntiJoin.broadcastThreshold`, this PR allows the
    specialized null-aware broadcast hash join when either the dedicated threshold or the applicable
    automatic broadcast threshold admits the right side. Regular planning uses
    `spark.sql.adaptive.autoBroadcastJoinThreshold` for runtime statistics when it is set, and
    `spark.sql.autoBroadcastJoinThreshold` otherwise. A negative dedicated threshold remains
    unlimited.
    
    Threshold eligibility is evaluated before join hints, matching the existing precedence of the
    dedicated threshold. Hints affect the fallback only when the specialized NAAJ is not eligible.
    The same shared eligibility decision intentionally controls aggregate pushdown: the optimizer
    uses estimated statistics before adaptive execution, while join selection may reevaluate the
    decision with runtime statistics.
    
    ### Why are the changes needed?
    
    If the dedicated NAAJ threshold is lower than the automatic broadcast threshold, it can reject the
    specialized null-aware broadcast hash join even though automatic join planning will broadcast the
    right side. That fallback uses a nested-loop representation and changes hash lookup from
    `O(M + N)` to `O(M * N)` without avoiding the broadcast.
    
    Using the applicable automatic threshold as a floor avoids that regression while preserving the
    dedicated threshold as a way to allow the specialized NAAJ above the automatic threshold.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, on unreleased branches and for an internal configuration. A nonnegative dedicated NAAJ
    threshold can no longer disable the specialized hash optimization for inputs admitted by the
    applicable automatic broadcast threshold.
    
    To disable the specialized optimization without changing automatic broadcast thresholds, set
    `spark.sql.optimizeNullAwareAntiJoin=false`. A negative dedicated threshold does not disable the
    optimization; it makes the threshold unlimited.
    
    ### How was this patch tested?
    
    The patch is covered by the following focused suites:
    
    ```
    build/sbt \
      "catalyst/testOnly org.apache.spark.sql.catalyst.optimizer.JoinSelectionHelperSuite" \
      "catalyst/testOnly org.apache.spark.sql.catalyst.optimizer.LeftSemiAntiJoinPushDownSuite" \
      "sql/testOnly org.apache.spark.sql.JoinSuite -- -z SPARK-36082"
    ```
    
    The latest local rerun was blocked before compilation because the isolated environment could not
    resolve the updated SBT plugins. Whitespace, changed-line length, and non-ASCII checks passed. The
    focused suites will run in GitHub Actions.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: OpenAI Codex (GPT-5)
    
    Closes #58870 from cloud-fan/cloud-fan/naaj-broadcast-threshold-floor.
    
    Authored-by: Wenchen Fan <we...@databricks.com>
    Signed-off-by: Wenchen Fan <we...@databricks.com>
    (cherry picked from commit 5ffc3e912e0446d0c501bb7471af41e5d198874c)
    Signed-off-by: Wenchen Fan <we...@databricks.com>
---
 .../spark/sql/catalyst/optimizer/joins.scala       |  31 +++---
 .../org/apache/spark/sql/internal/SQLConf.scala    |  24 +++--
 .../optimizer/JoinSelectionHelperSuite.scala       | 118 ++++++++++++++++-----
 .../optimizer/LeftSemiAntiJoinPushDownSuite.scala  |  45 ++++++++
 .../scala/org/apache/spark/sql/JoinSuite.scala     |  62 +++++++----
 5 files changed, 212 insertions(+), 68 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 4628fc32ea34..b1cb873509fc 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
@@ -417,14 +417,13 @@ trait JoinSelectionHelper extends Logging {
 
   /**
    * The build side a broadcast hash join would use, or `None` when one is ruled out by the join
-   * shape or by a hint.
+   * shape, a hint, or its size.
    *
-   * `Some` does not promise the planner picks a broadcast hash join: a `SHUFFLE_MERGE` or
-   * `SHUFFLE_REPLICATE_NL` hint is tried before the sizes are consulted, join keys no hash join
-   * supports send it to a sort merge join, and AQE re-estimates the sizes at runtime. Within the
-   * broadcast decision itself this does follow the planner's precedence: a hinted broadcast first,
-   * a hinted shuffle hash join as a veto, then the sizes. Callers that only need to know whether a
-   * broadcast hash join is possible should use `canPlanAsBroadcastHashJoin`.
+   * For equi-joins, `Some` does not promise the planner picks a broadcast hash join: other hints,
+   * unsupported join keys, or AQE can select another strategy. For a single-column null-aware anti
+   * join, the dedicated and automatic broadcast thresholds determine eligibility before hints.
+   * Callers that only need to know whether a broadcast hash join is possible should use
+   * `canPlanAsBroadcastHashJoin`.
    */
   def getBroadcastHashJoinBuildSide(join: Join, conf: SQLConf): Option[BuildSide] = join match {
     case ExtractEquiJoinKeys(_, leftKeys, rightKeys, _, _, _, _, _) =>
@@ -438,12 +437,20 @@ trait JoinSelectionHelper extends Logging {
       getBroadcastBuildSide(join, hintOnly = true, conf).orElse {
         if (noShufflePlannedBefore) getBroadcastBuildSide(join, hintOnly = false, conf) else None
       }
-    // `JoinSelection` always builds from the right for this shape. A negative threshold preserves
-    // the original unbounded NAAJ behavior, while zero disables the broadcast hash optimization.
+    // `JoinSelection` always builds from the right for this shape. The applicable automatic
+    // broadcast threshold floors a nonnegative dedicated threshold. As before, threshold
+    // eligibility takes precedence over join hints. This same decision intentionally controls
+    // aggregate pushdown. If neither threshold admits the hash join, regular planning may still
+    // broadcast the right side for a nested-loop join. The thresholds limit hash relation
+    // construction, not all broadcasts.
     case j @ ExtractSingleColumnNullAwareAntiJoin(_, _) =>
-      val threshold = conf.nullAwareAntiJoinBroadcastThreshold
-      val rightSize = j.right.stats.sizeInBytes
-      if (threshold < 0 || (threshold > 0 && rightSize >= 0 && rightSize <= threshold)) {
+      val dedicatedThreshold = conf.nullAwareAntiJoinBroadcastThreshold
+      val canBroadcast = dedicatedThreshold < 0 ||
+        (dedicatedThreshold > 0 && {
+          val rightSize = j.right.stats.sizeInBytes
+          rightSize >= 0 && rightSize <= dedicatedThreshold
+        }) || canBroadcastBySize(j.right, conf)
+      if (canBroadcast) {
         Some(BuildRight)
       } else {
         None
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 5adff7c469ea..a77e27e8ab5b 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
@@ -7463,16 +7463,20 @@ object SQLConf {
   val NULL_AWARE_ANTI_JOIN_BROADCAST_THRESHOLD =
     buildConf("spark.sql.optimizeNullAwareAntiJoin.broadcastThreshold")
       .internal()
-      .doc("Configures the maximum estimated size in bytes of the right side of a " +
-        "single-column null-aware anti join for which Spark uses the broadcast hash join " +
-        "optimization. This configuration takes effect only when " +
-        "spark.sql.optimizeNullAwareAntiJoin is enabled. A negative value allows the " +
-        "optimization regardless of the estimated size, while zero disables it. If the " +
-        "estimated size exceeds a positive value, Spark falls back to regular join planning. " +
-        "The fallback may still broadcast the right side with a nested-loop representation " +
-        "that uses more memory and runs in O(M * N) time. Join hints do not override this " +
-        "configuration when the broadcast hash optimization is selected. This configuration " +
-        "also controls whether a null-aware anti join can be pushed below an aggregate.")
+      .doc(s"Configures a dedicated broadcast threshold for the right side of a single-column " +
+        "null-aware anti join. This configuration takes effect only when " +
+        s"${OPTIMIZE_NULL_AWARE_ANTI_JOIN.key} is enabled. A negative value allows the " +
+        "broadcast hash join optimization regardless of the estimated size. For a nonnegative " +
+        "value, the applicable automatic broadcast threshold acts as a floor: " +
+        s"${ADAPTIVE_AUTO_BROADCASTJOIN_THRESHOLD.key} is used for runtime statistics when set, " +
+        s"and ${AUTO_BROADCASTJOIN_THRESHOLD.key} is used otherwise. Once either threshold " +
+        "admits the right side, the optimization takes precedence over join hints. The same " +
+        "eligibility decision controls aggregate pushdown, which runs before adaptive execution " +
+        "and uses estimated statistics; join selection may reevaluate it with runtime " +
+        "statistics. A lower adaptive threshold can leave a pushed-down join using a " +
+        s"nested-loop plan. Thus, zero alone does not disable the optimization. Set " +
+        s"${OPTIMIZE_NULL_AWARE_ANTI_JOIN.key} to false to disable it without changing automatic " +
+        "broadcast thresholds.")
       .version("4.2.1")
       .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
       .bytesConf(ByteUnit.BYTE)
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 71fa91f5c37e..b3f74687329e 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
@@ -18,9 +18,9 @@
 package org.apache.spark.sql.catalyst.optimizer
 
 import org.apache.spark.sql.catalyst.dsl.expressions._
-import org.apache.spark.sql.catalyst.expressions.{AttributeMap, EqualTo, IsNull, Or}
+import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeMap, EqualTo, IsNull, Or}
 import org.apache.spark.sql.catalyst.plans.{Inner, LeftAnti, PlanTest}
-import org.apache.spark.sql.catalyst.plans.logical.{BROADCAST, HintInfo, Join, JoinHint, NO_BROADCAST_HASH, SHUFFLE_HASH}
+import org.apache.spark.sql.catalyst.plans.logical.{BROADCAST, HintInfo, Join, JoinHint, LeafNode, LogicalPlan, NO_BROADCAST_HASH, SHUFFLE_HASH, Statistics}
 import org.apache.spark.sql.catalyst.statsEstimation.StatsTestPlan
 import org.apache.spark.sql.internal.SQLConf
 
@@ -40,6 +40,11 @@ class JoinSelectionHelperSuite extends PlanTest with JoinSelectionHelper {
 
   private val join = Join(left, right, Inner, None, JoinHint(None, None))
 
+  private def nullAwareAntiJoin(rightPlan: LogicalPlan = right): Join = {
+    val equality = EqualTo(left.output.head, rightPlan.output.head)
+    Join(left, rightPlan, LeftAnti, Some(Or(equality, IsNull(equality))), JoinHint.NONE)
+  }
+
   private val hintBroadcast = Some(HintInfo(Some(BROADCAST)))
   private val hintNotToBroadcast = Some(HintInfo(Some(NO_BROADCAST_HASH)))
   private val hintShuffleHash = Some(HintInfo(Some(SHUFFLE_HASH)))
@@ -195,48 +200,109 @@ class JoinSelectionHelperSuite extends PlanTest with JoinSelectionHelper {
     }
   }
 
-  test("getBroadcastHashJoinBuildSide uses the null-aware anti join broadcast threshold") {
-    val leftKey = left.output.head
-    val rightKey = right.output.head
-    val condition = Or(EqualTo(leftKey, rightKey), IsNull(EqualTo(leftKey, rightKey)))
-    val nullAwareAntiJoin = Join(left, right, LeftAnti, Some(condition), JoinHint.NONE)
-    val largeRight = right.copy(rowCount = 20000000, size = Some(20000000))
-    val negativeSizeRight = right.copy(size = Some(-1))
-    val overLongMaxRight = right.copy(
-      rowCount = BigInt(Long.MaxValue) + 1,
-      size = Some(BigInt(Long.MaxValue) + 1))
+  test("NAAJ broadcast threshold is floored by the automatic broadcast threshold") {
+    val betweenThresholdsRight = right.copy(
+      rowCount = 8 * 1024 * 1024,
+      size = Some(8 * 1024 * 1024))
+    val largeRight = right.copy(
+      rowCount = 20 * 1024 * 1024,
+      size = Some(20 * 1024 * 1024))
+    val overDedicatedThresholdRight = right.copy(
+      rowCount = 21 * 1024 * 1024,
+      size = Some(21 * 1024 * 1024))
 
     withSQLConf(
       SQLConf.OPTIMIZE_NULL_AWARE_ANTI_JOIN.key -> "true",
-      SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "10MB") {
-      assert(getBroadcastHashJoinBuildSide(nullAwareAntiJoin, SQLConf.get) === Some(BuildRight))
+      SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "10MB",
+      SQLConf.NULL_AWARE_ANTI_JOIN_BROADCAST_THRESHOLD.key -> "0") {
+      assert(getBroadcastHashJoinBuildSide(nullAwareAntiJoin(), SQLConf.get) === Some(BuildRight))
       assert(getBroadcastHashJoinBuildSide(
-        nullAwareAntiJoin.copy(right = largeRight), SQLConf.get) === Some(BuildRight))
+        nullAwareAntiJoin().copy(hint = JoinHint(hintBroadcast, None)),
+        SQLConf.get) === Some(BuildRight))
       assert(getBroadcastHashJoinBuildSide(
-        nullAwareAntiJoin.copy(right = overLongMaxRight), SQLConf.get) === Some(BuildRight))
+        nullAwareAntiJoin(largeRight).copy(
+          hint = JoinHint(None, hintBroadcast)), SQLConf.get).isEmpty)
     }
 
-    withSQLConf(SQLConf.NULL_AWARE_ANTI_JOIN_BROADCAST_THRESHOLD.key -> "-2") {
+    withSQLConf(
+      SQLConf.OPTIMIZE_NULL_AWARE_ANTI_JOIN.key -> "true",
+      SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "10MB",
+      SQLConf.NULL_AWARE_ANTI_JOIN_BROADCAST_THRESHOLD.key -> "5MB") {
+      assert(getBroadcastHashJoinBuildSide(
+        nullAwareAntiJoin(betweenThresholdsRight), SQLConf.get) === Some(BuildRight))
+    }
+
+    withSQLConf(
+      SQLConf.OPTIMIZE_NULL_AWARE_ANTI_JOIN.key -> "true",
+      SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "10MB",
+      SQLConf.NULL_AWARE_ANTI_JOIN_BROADCAST_THRESHOLD.key -> "20MB") {
+      assert(getBroadcastHashJoinBuildSide(
+        nullAwareAntiJoin(largeRight), SQLConf.get) === Some(BuildRight))
+      assert(getBroadcastHashJoinBuildSide(
+        nullAwareAntiJoin(overDedicatedThresholdRight), SQLConf.get).isEmpty)
+    }
+
+    withSQLConf(
+      SQLConf.OPTIMIZE_NULL_AWARE_ANTI_JOIN.key -> "true",
+      SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+      SQLConf.NULL_AWARE_ANTI_JOIN_BROADCAST_THRESHOLD.key -> "0") {
+      assert(getBroadcastHashJoinBuildSide(nullAwareAntiJoin(), SQLConf.get).isEmpty)
+    }
+  }
+
+  test("NAAJ broadcast threshold preserves the existing controls") {
+    val overLongMaxRight = right.copy(
+      rowCount = BigInt(Long.MaxValue) + 1,
+      size = Some(BigInt(Long.MaxValue) + 1))
+
+    withSQLConf(
+      SQLConf.OPTIMIZE_NULL_AWARE_ANTI_JOIN.key -> "true",
+      SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1") {
       assert(getBroadcastHashJoinBuildSide(
-        nullAwareAntiJoin.copy(right = overLongMaxRight), SQLConf.get) === Some(BuildRight))
+        nullAwareAntiJoin(overLongMaxRight), SQLConf.get) === Some(BuildRight))
     }
 
-    withSQLConf(SQLConf.NULL_AWARE_ANTI_JOIN_BROADCAST_THRESHOLD.key -> "0") {
-      assert(getBroadcastHashJoinBuildSide(nullAwareAntiJoin, SQLConf.get).isEmpty)
+    withSQLConf(
+      SQLConf.OPTIMIZE_NULL_AWARE_ANTI_JOIN.key -> "true",
+      SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+      SQLConf.NULL_AWARE_ANTI_JOIN_BROADCAST_THRESHOLD.key -> "10MB") {
+      assert(getBroadcastHashJoinBuildSide(nullAwareAntiJoin(), SQLConf.get) === Some(BuildRight))
+      assert(getBroadcastHashJoinBuildSide(
+        nullAwareAntiJoin(right.copy(size = Some(-1))), SQLConf.get).isEmpty)
+      assert(getBroadcastHashJoinBuildSide(
+        nullAwareAntiJoin(overLongMaxRight), SQLConf.get).isEmpty)
     }
 
     withSQLConf(
       SQLConf.OPTIMIZE_NULL_AWARE_ANTI_JOIN.key -> "false",
       SQLConf.NULL_AWARE_ANTI_JOIN_BROADCAST_THRESHOLD.key -> "-1") {
-      assert(getBroadcastHashJoinBuildSide(nullAwareAntiJoin, SQLConf.get).isEmpty)
+      assert(getBroadcastHashJoinBuildSide(nullAwareAntiJoin(), SQLConf.get).isEmpty)
     }
+  }
 
-    withSQLConf(SQLConf.NULL_AWARE_ANTI_JOIN_BROADCAST_THRESHOLD.key -> "10MB") {
-      assert(getBroadcastHashJoinBuildSide(nullAwareAntiJoin, SQLConf.get) === Some(BuildRight))
-      assert(getBroadcastHashJoinBuildSide(
-        nullAwareAntiJoin.copy(right = largeRight), SQLConf.get).isEmpty)
+  test("NAAJ broadcast threshold uses the adaptive threshold for runtime statistics") {
+    case class RuntimeStatsPlan(size: BigInt) extends LeafNode {
+      override def output: Seq[Attribute] = right.output
+      override def computeStats(): Statistics = Statistics(sizeInBytes = size, isRuntime = true)
+    }
+    val runtimeRight = RuntimeStatsPlan(5 * 1024 * 1024)
+
+    withSQLConf(
+      SQLConf.OPTIMIZE_NULL_AWARE_ANTI_JOIN.key -> "true",
+      SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "10MB",
+      SQLConf.ADAPTIVE_AUTO_BROADCASTJOIN_THRESHOLD.key -> "1MB",
+      SQLConf.NULL_AWARE_ANTI_JOIN_BROADCAST_THRESHOLD.key -> "0") {
+      assert(getBroadcastHashJoinBuildSide(nullAwareAntiJoin(runtimeRight), SQLConf.get).isEmpty)
+    }
+
+    withSQLConf(
+      SQLConf.OPTIMIZE_NULL_AWARE_ANTI_JOIN.key -> "true",
+      SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "1MB",
+      SQLConf.ADAPTIVE_AUTO_BROADCASTJOIN_THRESHOLD.key -> "10MB",
+      SQLConf.NULL_AWARE_ANTI_JOIN_BROADCAST_THRESHOLD.key -> "0") {
       assert(getBroadcastHashJoinBuildSide(
-        nullAwareAntiJoin.copy(right = negativeSizeRight), SQLConf.get).isEmpty)
+        nullAwareAntiJoin(runtimeRight), SQLConf.get) === Some(BuildRight))
     }
+
   }
 }
diff --git a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/LeftSemiAntiJoinPushDownSuite.scala b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/LeftSemiAntiJoinPushDownSuite.scala
index ba7386f8c9b5..acc03addbb05 100644
--- a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/LeftSemiAntiJoinPushDownSuite.scala
+++ b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/LeftSemiAntiJoinPushDownSuite.scala
@@ -24,6 +24,7 @@ import org.apache.spark.sql.catalyst.expressions._
 import org.apache.spark.sql.catalyst.plans._
 import org.apache.spark.sql.catalyst.plans.logical._
 import org.apache.spark.sql.catalyst.rules._
+import org.apache.spark.sql.catalyst.statsEstimation.StatsTestPlan
 import org.apache.spark.sql.internal.SQLConf
 import org.apache.spark.sql.types.IntegerType
 
@@ -142,6 +143,50 @@ class LeftSemiAntiJoinPushDownSuite extends PlanTest {
     comparePlans(optimized, originalQuery.analyze)
   }
 
+  test("Aggregate: NAAJ pushdown follows the effective broadcast threshold") {
+    val aggregate = testRelation.groupBy($"b")($"b")
+    val equality = $"b" === $"d"
+    val smallRight = StatsTestPlan(
+      outputList = testRelation1.output,
+      rowCount = 5 * 1024 * 1024,
+      attributeStats = AttributeMap.empty,
+      size = Some(5 * 1024 * 1024))
+    val originalQuery = aggregate.join(
+      smallRight,
+      joinType = LeftAnti,
+      condition = Some(equality || IsNull(equality)))
+    val pushedDownQuery = testRelation
+      .join(
+        smallRight,
+        joinType = LeftAnti,
+        condition = Some(equality || IsNull(equality)))
+      .groupBy($"b")($"b")
+    val largeRight = StatsTestPlan(
+      outputList = testRelation1.output,
+      rowCount = 20 * 1024 * 1024,
+      attributeStats = AttributeMap.empty,
+      size = Some(20 * 1024 * 1024))
+    val largeRightQuery = aggregate.join(
+      largeRight,
+      joinType = LeftAnti,
+      condition = Some(equality || IsNull(equality)))
+
+    withSQLConf(
+      SQLConf.OPTIMIZE_NULL_AWARE_ANTI_JOIN.key -> "true",
+      SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "10MB",
+      SQLConf.NULL_AWARE_ANTI_JOIN_BROADCAST_THRESHOLD.key -> "0") {
+      comparePlans(Optimize.execute(originalQuery.analyze), pushedDownQuery.analyze)
+      comparePlans(Optimize.execute(largeRightQuery.analyze), largeRightQuery.analyze)
+    }
+
+    withSQLConf(
+      SQLConf.OPTIMIZE_NULL_AWARE_ANTI_JOIN.key -> "true",
+      SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+      SQLConf.NULL_AWARE_ANTI_JOIN_BROADCAST_THRESHOLD.key -> "0") {
+      comparePlans(Optimize.execute(originalQuery.analyze), originalQuery.analyze)
+    }
+  }
+
   test("Aggregate: LeftSemi join no pushdown") {
     val originalQuery = testRelation
       .groupBy($"b")($"b", sum($"c").as("sum"))
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/JoinSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/JoinSuite.scala
index 642fcfde3420..c7f9a9cb1b0c 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/JoinSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/JoinSuite.scala
@@ -27,7 +27,7 @@ import org.apache.spark.internal.config.SHUFFLE_SPILL_NUM_ELEMENTS_FORCE_SPILL_T
 import org.apache.spark.sql.catalyst.TableIdentifier
 import org.apache.spark.sql.catalyst.analysis.UnresolvedRelation
 import org.apache.spark.sql.catalyst.expressions.{Ascending, GenericRow, SortOrder}
-import org.apache.spark.sql.catalyst.optimizer.{BuildLeft, BuildRight, JoinSelectionHelper}
+import org.apache.spark.sql.catalyst.optimizer.{BuildLeft, BuildRight, BuildSide, JoinSelectionHelper}
 import org.apache.spark.sql.catalyst.plans.logical.{Filter, HintInfo, Join, JoinHint, NO_BROADCAST_AND_REPLICATION}
 import org.apache.spark.sql.execution.{BinaryExecNode, FilterExec, ProjectExec, SortExec, SparkPlan, WholeStageCodegenExec}
 import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
@@ -66,6 +66,9 @@ class JoinSuite extends SharedSparkSession with AdaptiveSparkPlanHelper
     val c = pair._2
     val df = sql(sqlString)
     val optimized = df.queryExecution.optimizedPlan
+    val optimizedJoin = optimized.collectFirst { case join: Join => join }.getOrElse {
+      fail(s"No join in optimized plan:\n$optimized")
+    }
     val physical = df.queryExecution.sparkPlan
     val operators = physical.collect {
       case j: BroadcastHashJoinExec => j
@@ -80,13 +83,13 @@ class JoinSuite extends SharedSparkSession with AdaptiveSparkPlanHelper
       fail(s"$sqlString expected operator: $c, but got ${operators.head}\n physical: \n$physical")
     }
     assert(
-      canPlanAsBroadcastHashJoin(optimized.asInstanceOf[Join], conf) ===
+      canPlanAsBroadcastHashJoin(optimizedJoin, conf) ===
         operators.head.isInstanceOf[BroadcastHashJoinExec],
       "canPlanAsBroadcastHashJoin not in sync with join selection codepath!")
     operators.head match {
       case bhj: BroadcastHashJoinExec =>
         assert(
-          getBroadcastHashJoinBuildSide(optimized.asInstanceOf[Join], conf)
+          getBroadcastHashJoinBuildSide(optimizedJoin, conf)
             .contains(bhj.buildSide),
           "getBroadcastHashJoinBuildSide not in sync with join selection codepath!")
       case _ =>
@@ -1308,34 +1311,53 @@ class JoinSuite extends SharedSparkSession with AdaptiveSparkPlanHelper
     }
   }
 
-  test("SPARK-36082: left-broadcast NAAJ fallback uses nested-loop join") {
+  test("SPARK-36082, SPARK-59673: NAAJ threshold eligibility precedes broadcast hints") {
     withSQLConf(
       SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
-      SQLConf.OPTIMIZE_NULL_AWARE_ANTI_JOIN.key -> "true",
-      SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> Long.MaxValue.toString,
-      SQLConf.NULL_AWARE_ANTI_JOIN_BROADCAST_THRESHOLD.key -> "0") {
+      SQLConf.OPTIMIZE_NULL_AWARE_ANTI_JOIN.key -> "true") {
       withTempView("naajHintedLeft", "naajHintedRight") {
         Seq[java.lang.Double](-0.0d, 2.0d, null).toDF("key")
           .createOrReplaceTempView("naajHintedLeft")
         Seq[java.lang.Double](0.0d, 1.0d).toDF("key")
           .createOrReplaceTempView("naajHintedRight")
 
-        val result = sql(
-          "select /*+ BROADCAST(naajHintedLeft) */ naajHintedLeft.* " +
-            "from naajHintedLeft left anti join naajHintedRight on " +
+        val querySuffix =
+          "* from naajHintedLeft left anti join naajHintedRight on " +
             "naajHintedLeft.key = naajHintedRight.key or " +
-            "isnull(naajHintedLeft.key = naajHintedRight.key)")
-        val plan = result.queryExecution.sparkPlan
-        val nestedLoopJoins = plan.collect {
-          case join: BroadcastNestedLoopJoinExec => join
+            "isnull(naajHintedLeft.key = naajHintedRight.key)"
+        val leftHintedQuery = "select /*+ BROADCAST(naajHintedLeft) */ " + querySuffix
+        val rightHintedQuery = "select /*+ BROADCAST(naajHintedRight) */ " + querySuffix
+        val unhintedQuery = "select " + querySuffix
+
+        def checkNAAJ(
+            query: String,
+            expectedClass: Class[_ <: BinaryExecNode],
+            expectedBuildSide: BuildSide): Unit = {
+          assertJoin((query, expectedClass)) match {
+            case join: BroadcastHashJoinExec =>
+              assert(join.isNullAwareAntiJoin)
+              assert(join.buildSide === expectedBuildSide)
+            case join: BroadcastNestedLoopJoinExec =>
+              assert(join.buildSide === expectedBuildSide)
+            case join =>
+              fail(s"Unexpected join: $join")
+          }
+          checkAnswer(sql(query), Row(2.0d))
         }
-        val nullAwareHashJoins = plan.collect {
-          case join: BroadcastHashJoinExec if join.isNullAwareAntiJoin => join
+
+        withSQLConf(
+          SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> Long.MaxValue.toString,
+          SQLConf.NULL_AWARE_ANTI_JOIN_BROADCAST_THRESHOLD.key -> "0") {
+          checkNAAJ(leftHintedQuery, classOf[BroadcastHashJoinExec], BuildRight)
+          checkNAAJ(unhintedQuery, classOf[BroadcastHashJoinExec], BuildRight)
+        }
+
+        withSQLConf(
+          SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "0",
+          SQLConf.NULL_AWARE_ANTI_JOIN_BROADCAST_THRESHOLD.key -> "0") {
+          checkNAAJ(leftHintedQuery, classOf[BroadcastNestedLoopJoinExec], BuildLeft)
+          checkNAAJ(rightHintedQuery, classOf[BroadcastNestedLoopJoinExec], BuildRight)
         }
-        assert(nestedLoopJoins.size === 1)
-        assert(nestedLoopJoins.head.buildSide === BuildLeft)
-        assert(nullAwareHashJoins.isEmpty)
-        checkAnswer(result, Row(2.0d))
       }
     }
   }


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org