LuciferYang commented on code in PR #59841:
URL: https://github.com/apache/spark/pull/59841#discussion_r4559904723


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeJoinExec.scala:
##########
@@ -548,69 +614,152 @@ case class SortMergeJoinExec(
     val conditionForCodegen = if (streamedOnlyGuard.isDefined) restCondition 
else condition
 
     val (streamedBeforeLoop, condCheck, loadStreamed) = if 
(conditionForCodegen.isDefined) {
-      // Split the code of creating variables based on whether it's used by 
condition or not.
       val loaded = ctx.freshName("loaded")
-      val (streamedBefore, streamedAfter) = 
splitVarsByCondition(streamedOutput, streamedVars)
-      val (bufferedBefore, bufferedAfter) = 
splitVarsByCondition(bufferedOutput, bufferedVars)
-      // Generate code for condition
-      ctx.currentVars = streamedVars ++ bufferedVars
-      val cond = BindReferences.bindReference(
-        conditionForCodegen.get, streamedPlan.output ++ 
bufferedPlan.output).genCode(ctx)
-      // Evaluate the columns those used by condition before loop
-      val before = joinType match {
-        case LeftAnti =>
-          // No need to initialize `loaded` variable for Left Anti join.
-          streamedBefore.trim
-        case _ =>
-          s"""
-             |boolean $loaded = false;
-             |$streamedBefore
-         """.stripMargin
-      }
+      // Use the FULL condition's references (including streamedOnlyCondition) 
to determine
+      // which columns to extract before the condition check. streamedOnlyPre 
reads columns
+      // from streamedOnlyCondition before the match loop, so those must be 
extracted early.
+      val condExprRefs = condition.get.references
+
+      if (useFieldBasedExtraction) {
+        // Field-based path: partition per-column snippets by condition 
references.
+        val (sCondSnippets, sRestSnippets) =
+          streamedOutput.zip(streamedSnippets).partition { case (a, _) =>
+            condExprRefs.contains(a)
+          }
+        val (bCondSnippets, bRestSnippets) =
+          bufferedOutput.zip(bufferedSnippets).partition { case (a, _) =>
+            condExprRefs.contains(a)
+          }
 
-      val loadStreamedAfterCondition = joinType match {
-        case LeftAnti =>
-          // No need to evaluate columns not used by condition from streamed 
side, as for Left Anti
-          // join, streamed row with match is not outputted.
-          ""
-        case _ =>
+        val sCondExtract = ctx.splitExpressions(
+          sCondSnippets.map(_._2), "extractStreamCondVars", Seq.empty)
+        val sRestExtract = ctx.splitExpressions(
+          sRestSnippets.map(_._2), "extractStreamRestVars", Seq.empty)
+        val bCondExtract = ctx.splitExpressions(
+          bCondSnippets.map(_._2), "extractJoinCondVars",
+          Seq(("InternalRow", bufferedRow)))
+        val bRestExtract = ctx.splitExpressions(
+          bRestSnippets.map(_._2), "extractJoinRestVars",
+          Seq(("InternalRow", bufferedRow)))
+
+        ctx.currentVars = streamedVars ++ bufferedVars
+        val cond = BindReferences.bindReference(
+          conditionForCodegen.get,
+          streamedPlan.output ++ bufferedPlan.output).genCode(ctx)
+
+        val before = joinType match {
+          case LeftAnti =>
+            s"$sCondExtract".trim
+          case _ =>
+            s"""
+               |boolean $loaded = false;
+               |$sCondExtract
+             """.stripMargin
+        }
+
+        val loadStreamedAfterCond = joinType match {
+          case LeftAnti => ""
+          case _ =>
+            s"""
+               |if (!$loaded) {
+               |  $loaded = true;
+               |  $sRestExtract
+               |}
+             """.stripMargin
+        }
+        val loadBufferedAfterCond = joinType match {
+          case LeftExistence(_) => ""
+          case _ => bRestExtract
+        }
+
+        val checking =
           s"""
-             |if (!$loaded) {
-             |  $loaded = true;
-             |  $streamedAfter
+             |$bCondExtract
+             |if ($bufferedRow != null) {
+             |  ${cond.code}
+             |  if (${cond.isNull} || !${cond.value}) {
+             |    continue;
+             |  }
              |}
-         """.stripMargin
-      }
+             |$loadStreamedAfterCond
+             |$loadBufferedAfterCond
+           """.stripMargin
+        (before, checking.trim,
+          if (joinType == LeftAnti) "" else sRestExtract.trim)

Review Comment:
   On the field path, LeftAnti with an extra join condition never emits 
`sRestExtract`: `before` holds only `sCondExtract`, and `loadStreamedAfterCond` 
and `loadStreamed` are both empty. So for a streamed row with no passing match, 
`codegenAnti` outputs every column the condition doesn't reference with its 
field's initial value. The local-variable path returns `streamedAfter.trim` 
here, as master does.
   
   It reproduces at default `maxFields`: a 99-column left side, the right side 
pruned to `r_k, r_c0`, `l_k = r_k AND (l_c0 + r_c0) % 3 != 0`, broadcast and 
AQE off. With string columns the task fails with an NPE in 
`UnsafeWriter.write`. With long columns, every column except `l_c0` comes back 
as `-1`, the key included.
   
   Could you return `sRestExtract.trim` for LeftAnti too, and add LeftAnti, 
LeftSemi and existence tests with a cross-side condition that take the field 
path? The current ones prune the right side to `id` and run the local path.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeJoinExec.scala:
##########
@@ -497,11 +541,33 @@ case class SortMergeJoinExec(
 
     val (findNextJoinRowsFuncName, streamedRow, matches) = genScanner(ctx)
 
-    // Create variables for row from both sides.
-    val (streamedVars, streamedVarDecl) = createStreamedVars(ctx, streamedRow)
     val bufferedRow = ctx.freshName("bufferedRow")
     val setDefaultValue = joinType == LeftOuter || joinType == RightOuter
-    val bufferedVars = genOneSideJoinVars(ctx, bufferedRow, bufferedPlan, 
setDefaultValue)
+
+    // Decide whether to use field-based extraction based on estimated 
extraction code size.
+    // Each column generates ~80 source chars of extraction code (nullable 
check + getValue).
+    // The streamed side extracts once per row, the buffered side once per 
matched pair.
+    // When the total extraction code would push processNext() toward the 
JVM's 8K JIT limit
+    // (DEFAULT_JVM_HUGE_METHOD_LIMIT), we use field-based extraction so 
splitExpressions
+    // can move it into helper methods. The 8K limit is in bytecode bytes; 
source chars are
+    // a conservative proxy (bytecode is typically 1.0-1.3x source length for 
generated code).
+    val estimatedExtractionChars =
+      (streamedPlan.output.length + bufferedPlan.output.length) * 80
+    val useFieldBasedExtraction =
+      estimatedExtractionChars > CodeGenerator.DEFAULT_JVM_HUGE_METHOD_LIMIT

Review Comment:
   The gate switches at 101 total columns, but master's `processNext()` reaches 
8000 bytes much later. With `maxFields` raised, an inner SMJ with the tests' 
column mix compiles to 4,114 bytes on master at 102 columns, 6,253 at 152 and 
8,641 at 202, about 44 bytes per column. Joins in that range pay the field 
writes for nothing. For semi/anti/existence the count also includes buffered 
columns that aren't output, and those joins are codegen'd at default 
`maxFields`, so a 99 + 2 column LeftAnti takes the field path today.
   
   Could you base the threshold on measured bytecode and count only the columns 
the join outputs? Gating on the compiled size, as `chooseCode` does, would 
avoid a constant per type mix. The tests' `WIDE_COLS` then has to move above 
the new threshold.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -2814,4 +2814,198 @@ class WholeStageCodegenSuite extends SharedSparkSession
       }
     }
   }
+
+  // 
---------------------------------------------------------------------------
+  // SPARK-59787: wide join field-based extraction tests
+  // 
---------------------------------------------------------------------------
+
+  // Helper: build a DataFrame with `numCols` columns, mixing nullable and 
non-nullable types.
+  // Even-indexed columns are non-nullable Long (id + i), odd-indexed are 
nullable String
+  // (cast to string, with null when id % 7 == i % 3 to exercise null 
propagation).
+  private def wideDF(rows: Int, numCols: Int, prefix: String): DataFrame = {
+    val base = spark.range(rows).toDF("id")
+    (0 until numCols).foldLeft(base) { (df, i) =>
+      if (i % 2 == 0) {
+        // Non-nullable Long
+        df.withColumn(s"${prefix}_c$i", $"id" + i)
+      } else {
+        // Nullable String -- null when id % 7 == i % 3
+        df.withColumn(s"${prefix}_c$i",
+          when($"id" % 7 === lit(i % 3), lit(null: String))
+            .otherwise(concat(lit(s"${prefix}_"), $"id".cast(StringType))))
+      }
+    }
+  }
+
+  // Shared config for SMJ tests: disable broadcast, raise maxFields so codegen
+  // stays on for wide schemas. The field-based extraction threshold is based 
on
+  // estimated extraction chars vs DEFAULT_JVM_HUGE_METHOD_LIMIT (8000), which
+  // triggers at ~100 total output columns (50 per side). Using 55 per side 
(110 total)
+  // ensures tests exercise the field-based path.
+  private val wideSMJConf = Seq(
+    SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+    SQLConf.WHOLESTAGE_MAX_NUM_FIELDS.key -> "250"
+  )
+
+  // Number of columns per side for wide join tests. 55+55=110 total output 
columns
+  // exceeds the field-based extraction threshold (8000 / 80 = 100 cols).
+  private val WIDE_COLS = 55
+
+  // Assert that a SortMergeJoinExec is inside a WholeStageCodegenExec in the 
plan.
+  // This proves codegen compiled successfully -- a silent fallback would show
+  // SortMergeJoinExec outside WholeStageCodegenExec.
+  private def assertSMJCodegenUsed(df: DataFrame): Unit = {
+    val plan = df.queryExecution.executedPlan
+    val codegenWithSMJ = plan.collect {
+      case ws: WholeStageCodegenExec if 
ws.find(_.isInstanceOf[SortMergeJoinExec]).isDefined => ws
+    }
+    assert(codegenWithSMJ.nonEmpty,
+      s"Expected SortMergeJoinExec inside WholeStageCodegenExec, but plan 
was:\n$plan")
+  }
+
+  test("SPARK-59787: wide inner SortMergeJoin with mixed nullable columns") {
+    withSQLConf(wideSMJConf: _*) {
+      val left = wideDF(100, WIDE_COLS, "l")
+      val right = wideDF(100, WIDE_COLS, "r")
+      val joined = left.join(right, left("id") === right("id"))
+      assertSMJCodegenUsed(joined)
+      checkAnswer(joined, withoutWholeStage(joined))
+    }
+  }
+
+  test("SPARK-59787: wide left outer SortMergeJoin with null output rows") {
+    withSQLConf(wideSMJConf: _*) {
+      val left = wideDF(100, WIDE_COLS, "l")
+      val right = wideDF(100, WIDE_COLS, "r").where($"id" >= 50)
+      val joined = left.join(right, left("id") === right("id"), "left_outer")
+      assertSMJCodegenUsed(joined)
+      checkAnswer(joined, withoutWholeStage(joined))
+      val nullCount = joined.where(right("id").isNull).count()
+      assert(nullCount == 50, s"Expected 50 null-output rows, got $nullCount")
+    }
+  }
+
+  test("SPARK-59787: wide right outer SortMergeJoin with null output rows") {
+    withSQLConf(wideSMJConf: _*) {
+      val left = wideDF(100, WIDE_COLS, "l").where($"id" >= 50)
+      val right = wideDF(100, WIDE_COLS, "r")
+      val joined = left.join(right, left("id") === right("id"), "right_outer")
+      assertSMJCodegenUsed(joined)
+      checkAnswer(joined, withoutWholeStage(joined))
+      val nullCount = joined.where(left("id").isNull).count()
+      assert(nullCount == 50, s"Expected 50 null-output rows, got $nullCount")
+    }
+  }
+
+  test("SPARK-59787: wide left semi SortMergeJoin") {
+    withSQLConf(wideSMJConf: _*) {
+      val left = wideDF(100, WIDE_COLS, "l")
+      val right = wideDF(100, WIDE_COLS, "r").where($"id" >= 50)
+      val joined = left.join(right, left("id") === right("id"), "left_semi")
+      assertSMJCodegenUsed(joined)
+      checkAnswer(joined, withoutWholeStage(joined))
+      assert(joined.count() == 50)
+    }
+  }
+
+  test("SPARK-59787: wide left anti SortMergeJoin") {
+    withSQLConf(wideSMJConf: _*) {
+      val left = wideDF(100, WIDE_COLS, "l")
+      val right = wideDF(100, WIDE_COLS, "r").where($"id" >= 50)
+      val joined = left.join(right, left("id") === right("id"), "left_anti")
+      assertSMJCodegenUsed(joined)
+      checkAnswer(joined, withoutWholeStage(joined))
+      assert(joined.count() == 50)
+    }
+  }
+
+  test("SPARK-59787: wide existence SortMergeJoin") {
+    withSQLConf(
+      (wideSMJConf :+ (SQLConf.ENABLE_EXISTENCE_SORT_MERGE_JOIN_CODEGEN.key -> 
"true")): _*
+    ) {
+      val left = wideDF(100, WIDE_COLS, "l")
+      val right = wideDF(100, WIDE_COLS, "r").where($"id" >= 50)
+      left.createOrReplaceTempView("wide_left")
+      right.createOrReplaceTempView("wide_right")
+      val joined = spark.sql(
+        "SELECT wide_left.*, EXISTS (SELECT 1 FROM wide_right WHERE 
wide_left.id = wide_right.id)" +
+        " AS has_match FROM wide_left")
+      checkAnswer(joined, withoutWholeStage(joined))
+      val matchCount = joined.where($"has_match").count()
+      assert(matchCount == 50)
+    }
+  }
+
+  test("SPARK-59787: wide inner SortMergeJoin with extra join condition") {
+    withSQLConf(wideSMJConf: _*) {
+      val left = wideDF(100, WIDE_COLS, "l")
+      val right = wideDF(100, WIDE_COLS, "r")
+      // Condition references both sides and rejects ~1/3 of pairs
+      val joined = left.join(right,
+        left("id") === right("id") && (left("l_c0") + right("r_c0")) % 3 =!= 0)
+      assertSMJCodegenUsed(joined)
+      checkAnswer(joined, withoutWholeStage(joined))
+      // Verify some pairs were actually rejected
+      assert(joined.count() < 100, "Condition should reject some pairs")
+      assert(joined.count() > 0, "Condition should accept some pairs")
+    }
+  }
+
+  test("SPARK-59787: wide left outer SortMergeJoin with extra join condition") 
{
+    withSQLConf(wideSMJConf: _*) {
+      val left = wideDF(100, WIDE_COLS, "l")
+      val right = wideDF(100, WIDE_COLS, "r")
+      // Cross-side condition that rejects some matched pairs
+      val joined = left.join(right,
+        left("id") === right("id") && (left("l_c0") + right("r_c0")) % 3 =!= 0,
+        "left_outer")
+      assertSMJCodegenUsed(joined)
+      checkAnswer(joined, withoutWholeStage(joined))
+      // All 100 left rows present (outer join), but some with null right side
+      assert(joined.count() == 100)
+      val nullCount = joined.where(right("r_c0").isNull).count()
+      assert(nullCount > 0, "Some pairs should be rejected, producing null 
right side")
+    }
+  }
+
+  test("SPARK-59787: wide SortMergeJoin without join condition (equi-only)") {
+    withSQLConf(wideSMJConf: _*) {
+      val left = wideDF(50, WIDE_COLS, "l")
+      val right = wideDF(50, WIDE_COLS, "r")
+      val joined = left.join(right, Seq("id"))
+      assertSMJCodegenUsed(joined)
+      checkAnswer(joined, withoutWholeStage(joined))
+    }
+  }
+
+  test("SPARK-59787: wide SMJ with large CASE WHEN compiles with EmptyBlock") {
+    // Regression test for using EmptyBlock vs code"" in field-based ExprCodes.
+    // Without EmptyBlock, collectInputs refuses the whole-stage expression 
split and the
+    // 2000-branch CASE WHEN stays inline in processNext(), exceeding 64KB.
+    withSQLConf(wideSMJConf: _*) {
+      withSplitAlways {
+        val left = spark.range(10).toDF("k").withColumn("c1", $"k")

Review Comment:
   This test doesn't reach the field path: each side has two columns, so the 
join has 4 and stays on local variables. I changed the four `EmptyBlock` in 
`createStreamedVarsAsFields` and `genOneSideJoinVarsAsFields` back to `code""` 
and the test still passed; it also passes with both main files reverted to 
master.
   
   Could you make both sides wide enough to take the field path, wherever the 
gate ends up, keep the join without an extra condition, and check the test 
fails with `code""`? With `wideDF` sides, `largeCaseWhen` needs a long column 
such as `r.r_c0`.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeJoinExec.scala:
##########
@@ -548,69 +614,152 @@ case class SortMergeJoinExec(
     val conditionForCodegen = if (streamedOnlyGuard.isDefined) restCondition 
else condition
 
     val (streamedBeforeLoop, condCheck, loadStreamed) = if 
(conditionForCodegen.isDefined) {
-      // Split the code of creating variables based on whether it's used by 
condition or not.
       val loaded = ctx.freshName("loaded")
-      val (streamedBefore, streamedAfter) = 
splitVarsByCondition(streamedOutput, streamedVars)
-      val (bufferedBefore, bufferedAfter) = 
splitVarsByCondition(bufferedOutput, bufferedVars)
-      // Generate code for condition
-      ctx.currentVars = streamedVars ++ bufferedVars
-      val cond = BindReferences.bindReference(
-        conditionForCodegen.get, streamedPlan.output ++ 
bufferedPlan.output).genCode(ctx)
-      // Evaluate the columns those used by condition before loop
-      val before = joinType match {
-        case LeftAnti =>
-          // No need to initialize `loaded` variable for Left Anti join.
-          streamedBefore.trim
-        case _ =>
-          s"""
-             |boolean $loaded = false;
-             |$streamedBefore
-         """.stripMargin
-      }
+      // Use the FULL condition's references (including streamedOnlyCondition) 
to determine
+      // which columns to extract before the condition check. streamedOnlyPre 
reads columns
+      // from streamedOnlyCondition before the match loop, so those must be 
extracted early.
+      val condExprRefs = condition.get.references
+
+      if (useFieldBasedExtraction) {
+        // Field-based path: partition per-column snippets by condition 
references.
+        val (sCondSnippets, sRestSnippets) =
+          streamedOutput.zip(streamedSnippets).partition { case (a, _) =>
+            condExprRefs.contains(a)
+          }
+        val (bCondSnippets, bRestSnippets) =
+          bufferedOutput.zip(bufferedSnippets).partition { case (a, _) =>
+            condExprRefs.contains(a)
+          }
 
-      val loadStreamedAfterCondition = joinType match {
-        case LeftAnti =>
-          // No need to evaluate columns not used by condition from streamed 
side, as for Left Anti
-          // join, streamed row with match is not outputted.
-          ""
-        case _ =>
+        val sCondExtract = ctx.splitExpressions(
+          sCondSnippets.map(_._2), "extractStreamCondVars", Seq.empty)
+        val sRestExtract = ctx.splitExpressions(
+          sRestSnippets.map(_._2), "extractStreamRestVars", Seq.empty)
+        val bCondExtract = ctx.splitExpressions(
+          bCondSnippets.map(_._2), "extractJoinCondVars",
+          Seq(("InternalRow", bufferedRow)))
+        val bRestExtract = ctx.splitExpressions(
+          bRestSnippets.map(_._2), "extractJoinRestVars",
+          Seq(("InternalRow", bufferedRow)))
+
+        ctx.currentVars = streamedVars ++ bufferedVars
+        val cond = BindReferences.bindReference(
+          conditionForCodegen.get,
+          streamedPlan.output ++ bufferedPlan.output).genCode(ctx)
+
+        val before = joinType match {
+          case LeftAnti =>
+            s"$sCondExtract".trim
+          case _ =>
+            s"""
+               |boolean $loaded = false;
+               |$sCondExtract
+             """.stripMargin
+        }
+
+        val loadStreamedAfterCond = joinType match {
+          case LeftAnti => ""
+          case _ =>
+            s"""
+               |if (!$loaded) {
+               |  $loaded = true;
+               |  $sRestExtract
+               |}
+             """.stripMargin
+        }
+        val loadBufferedAfterCond = joinType match {
+          case LeftExistence(_) => ""
+          case _ => bRestExtract
+        }
+
+        val checking =
           s"""
-             |if (!$loaded) {
-             |  $loaded = true;
-             |  $streamedAfter
+             |$bCondExtract
+             |if ($bufferedRow != null) {
+             |  ${cond.code}
+             |  if (${cond.isNull} || !${cond.value}) {
+             |    continue;
+             |  }
              |}
-         """.stripMargin
-      }
+             |$loadStreamedAfterCond
+             |$loadBufferedAfterCond
+           """.stripMargin
+        (before, checking.trim,
+          if (joinType == LeftAnti) "" else sRestExtract.trim)
+      } else {
+        // Local variable path: use splitVarsByCondition (original approach).
+        val (streamedBefore, streamedAfter) =
+          splitVarsByCondition(streamedOutput, streamedVars)
+        val (bufferedBefore, bufferedAfter) =
+          splitVarsByCondition(bufferedOutput, bufferedVars)
+        ctx.currentVars = streamedVars ++ bufferedVars
+        val cond = BindReferences.bindReference(
+          conditionForCodegen.get,
+          streamedPlan.output ++ bufferedPlan.output).genCode(ctx)
+
+        val streamedVarDecl = streamedDecls.mkString("\n")
+        val before = joinType match {
+          case LeftAnti =>
+            s"""
+               |$streamedVarDecl
+               |$streamedBefore
+             """.stripMargin.trim
+          case _ =>
+            s"""
+               |boolean $loaded = false;
+               |$streamedVarDecl
+               |$streamedBefore
+             """.stripMargin
+        }
 
-      val loadBufferedAfterCondition = joinType match {
-        case LeftExistence(_) =>
-          // No need to evaluate columns not used by condition from buffered 
side
-          ""
-        case _ => bufferedAfter
-      }
+        val loadStreamedAfterCond = joinType match {
+          case LeftAnti => ""
+          case _ =>
+            s"""
+               |if (!$loaded) {
+               |  $loaded = true;
+               |  $streamedAfter
+               |}
+             """.stripMargin
+        }
+        val loadBufferedAfterCond = joinType match {
+          case LeftExistence(_) => ""
+          case _ => bufferedAfter
+        }
 
-      val checking =
-        s"""
-           |$bufferedBefore
-           |if ($bufferedRow != null) {
-           |  ${cond.code}
-           |  if (${cond.isNull} || !${cond.value}) {
-           |    continue;
-           |  }
-           |}
-           |$loadStreamedAfterCondition
-           |$loadBufferedAfterCondition
-         """.stripMargin
-      (before, checking.trim, streamedAfter.trim)
+        val checking =
+          s"""
+             |$bufferedBefore
+             |if ($bufferedRow != null) {
+             |  ${cond.code}
+             |  if (${cond.isNull} || !${cond.value}) {
+             |    continue;
+             |  }
+             |}
+             |$loadStreamedAfterCond
+             |$loadBufferedAfterCond
+           """.stripMargin
+        (before, checking.trim, streamedAfter.trim)
+      }
     } else {
-      (evaluateVariables(streamedVars), "", "")
+      if (useFieldBasedExtraction) {
+        val sAllExtract = ctx.splitExpressions(
+          streamedSnippets, "extractStreamVars", Seq.empty)
+        val bAllExtract = ctx.splitExpressions(
+          bufferedSnippets, "extractJoinVars", Seq(("InternalRow", 
bufferedRow)))
+        (sAllExtract, bAllExtract, "")
+      } else {
+        val streamedVarDecl = streamedDecls.mkString("\n")
+        val streamedEval = evaluateVariables(streamedVars)
+        val bufferedEval = evaluateVariables(bufferedVars)
+        (s"$streamedVarDecl\n$streamedEval", bufferedEval, "")

Review Comment:
   Without an extra condition, this branch isn't master's code: master returned 
`""` as `condCheck` and left the buffered columns to `consume`, which reads 
them only where the parent uses them. Now every buffered column is read for 
every matched pair, and this is the path every narrow non-full-outer SMJ takes. 
With a selective broadcast hash join above the SMJ in the same stage, for 
example, master read the columns the BHJ doesn't reference only for rows the 
BHJ matched.
   
   Could you drop the `evaluateVariables(bufferedVars)` call and return 
`(s"$streamedVarDecl\n$streamedEval", "", "")`, so `condCheck` is `""` as on 
master? The call has to go as well, because it clears each ExprCode's code, and 
the buffered variables would then never be declared. The guard branch builds 
its own `defaultBufferedVars`, so nothing relies on the eager read.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -2814,4 +2814,198 @@ class WholeStageCodegenSuite extends SharedSparkSession
       }
     }
   }
+
+  // 
---------------------------------------------------------------------------
+  // SPARK-59787: wide join field-based extraction tests
+  // 
---------------------------------------------------------------------------
+
+  // Helper: build a DataFrame with `numCols` columns, mixing nullable and 
non-nullable types.
+  // Even-indexed columns are non-nullable Long (id + i), odd-indexed are 
nullable String
+  // (cast to string, with null when id % 7 == i % 3 to exercise null 
propagation).
+  private def wideDF(rows: Int, numCols: Int, prefix: String): DataFrame = {
+    val base = spark.range(rows).toDF("id")
+    (0 until numCols).foldLeft(base) { (df, i) =>
+      if (i % 2 == 0) {
+        // Non-nullable Long
+        df.withColumn(s"${prefix}_c$i", $"id" + i)
+      } else {
+        // Nullable String -- null when id % 7 == i % 3
+        df.withColumn(s"${prefix}_c$i",
+          when($"id" % 7 === lit(i % 3), lit(null: String))
+            .otherwise(concat(lit(s"${prefix}_"), $"id".cast(StringType))))
+      }
+    }
+  }
+
+  // Shared config for SMJ tests: disable broadcast, raise maxFields so codegen
+  // stays on for wide schemas. The field-based extraction threshold is based 
on
+  // estimated extraction chars vs DEFAULT_JVM_HUGE_METHOD_LIMIT (8000), which
+  // triggers at ~100 total output columns (50 per side). Using 55 per side 
(110 total)
+  // ensures tests exercise the field-based path.
+  private val wideSMJConf = Seq(
+    SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+    SQLConf.WHOLESTAGE_MAX_NUM_FIELDS.key -> "250"
+  )
+
+  // Number of columns per side for wide join tests. 55+55=110 total output 
columns
+  // exceeds the field-based extraction threshold (8000 / 80 = 100 cols).
+  private val WIDE_COLS = 55
+
+  // Assert that a SortMergeJoinExec is inside a WholeStageCodegenExec in the 
plan.
+  // This proves codegen compiled successfully -- a silent fallback would show
+  // SortMergeJoinExec outside WholeStageCodegenExec.
+  private def assertSMJCodegenUsed(df: DataFrame): Unit = {
+    val plan = df.queryExecution.executedPlan
+    val codegenWithSMJ = plan.collect {
+      case ws: WholeStageCodegenExec if 
ws.find(_.isInstanceOf[SortMergeJoinExec]).isDefined => ws
+    }
+    assert(codegenWithSMJ.nonEmpty,
+      s"Expected SortMergeJoinExec inside WholeStageCodegenExec, but plan 
was:\n$plan")
+  }
+
+  test("SPARK-59787: wide inner SortMergeJoin with mixed nullable columns") {
+    withSQLConf(wideSMJConf: _*) {
+      val left = wideDF(100, WIDE_COLS, "l")
+      val right = wideDF(100, WIDE_COLS, "r")
+      val joined = left.join(right, left("id") === right("id"))
+      assertSMJCodegenUsed(joined)
+      checkAnswer(joined, withoutWholeStage(joined))
+    }
+  }
+
+  test("SPARK-59787: wide left outer SortMergeJoin with null output rows") {
+    withSQLConf(wideSMJConf: _*) {
+      val left = wideDF(100, WIDE_COLS, "l")
+      val right = wideDF(100, WIDE_COLS, "r").where($"id" >= 50)
+      val joined = left.join(right, left("id") === right("id"), "left_outer")
+      assertSMJCodegenUsed(joined)
+      checkAnswer(joined, withoutWholeStage(joined))
+      val nullCount = joined.where(right("id").isNull).count()
+      assert(nullCount == 50, s"Expected 50 null-output rows, got $nullCount")
+    }
+  }
+
+  test("SPARK-59787: wide right outer SortMergeJoin with null output rows") {
+    withSQLConf(wideSMJConf: _*) {
+      val left = wideDF(100, WIDE_COLS, "l").where($"id" >= 50)
+      val right = wideDF(100, WIDE_COLS, "r")
+      val joined = left.join(right, left("id") === right("id"), "right_outer")
+      assertSMJCodegenUsed(joined)
+      checkAnswer(joined, withoutWholeStage(joined))
+      val nullCount = joined.where(left("id").isNull).count()
+      assert(nullCount == 50, s"Expected 50 null-output rows, got $nullCount")
+    }
+  }
+
+  test("SPARK-59787: wide left semi SortMergeJoin") {
+    withSQLConf(wideSMJConf: _*) {
+      val left = wideDF(100, WIDE_COLS, "l")
+      val right = wideDF(100, WIDE_COLS, "r").where($"id" >= 50)
+      val joined = left.join(right, left("id") === right("id"), "left_semi")
+      assertSMJCodegenUsed(joined)
+      checkAnswer(joined, withoutWholeStage(joined))
+      assert(joined.count() == 50)
+    }
+  }
+
+  test("SPARK-59787: wide left anti SortMergeJoin") {
+    withSQLConf(wideSMJConf: _*) {
+      val left = wideDF(100, WIDE_COLS, "l")
+      val right = wideDF(100, WIDE_COLS, "r").where($"id" >= 50)
+      val joined = left.join(right, left("id") === right("id"), "left_anti")
+      assertSMJCodegenUsed(joined)
+      checkAnswer(joined, withoutWholeStage(joined))
+      assert(joined.count() == 50)
+    }
+  }
+
+  test("SPARK-59787: wide existence SortMergeJoin") {
+    withSQLConf(
+      (wideSMJConf :+ (SQLConf.ENABLE_EXISTENCE_SORT_MERGE_JOIN_CODEGEN.key -> 
"true")): _*
+    ) {
+      val left = wideDF(100, WIDE_COLS, "l")
+      val right = wideDF(100, WIDE_COLS, "r").where($"id" >= 50)
+      left.createOrReplaceTempView("wide_left")
+      right.createOrReplaceTempView("wide_right")
+      val joined = spark.sql(
+        "SELECT wide_left.*, EXISTS (SELECT 1 FROM wide_right WHERE 
wide_left.id = wide_right.id)" +
+        " AS has_match FROM wide_left")
+      checkAnswer(joined, withoutWholeStage(joined))
+      val matchCount = joined.where($"has_match").count()
+      assert(matchCount == 50)
+    }
+  }
+
+  test("SPARK-59787: wide inner SortMergeJoin with extra join condition") {
+    withSQLConf(wideSMJConf: _*) {
+      val left = wideDF(100, WIDE_COLS, "l")
+      val right = wideDF(100, WIDE_COLS, "r")
+      // Condition references both sides and rejects ~1/3 of pairs
+      val joined = left.join(right,
+        left("id") === right("id") && (left("l_c0") + right("r_c0")) % 3 =!= 0)
+      assertSMJCodegenUsed(joined)
+      checkAnswer(joined, withoutWholeStage(joined))
+      // Verify some pairs were actually rejected
+      assert(joined.count() < 100, "Condition should reject some pairs")
+      assert(joined.count() > 0, "Condition should accept some pairs")
+    }
+  }
+
+  test("SPARK-59787: wide left outer SortMergeJoin with extra join condition") 
{
+    withSQLConf(wideSMJConf: _*) {
+      val left = wideDF(100, WIDE_COLS, "l")
+      val right = wideDF(100, WIDE_COLS, "r")
+      // Cross-side condition that rejects some matched pairs
+      val joined = left.join(right,
+        left("id") === right("id") && (left("l_c0") + right("r_c0")) % 3 =!= 0,
+        "left_outer")
+      assertSMJCodegenUsed(joined)
+      checkAnswer(joined, withoutWholeStage(joined))
+      // All 100 left rows present (outer join), but some with null right side
+      assert(joined.count() == 100)
+      val nullCount = joined.where(right("r_c0").isNull).count()
+      assert(nullCount > 0, "Some pairs should be rejected, producing null 
right side")
+    }
+  }
+
+  test("SPARK-59787: wide SortMergeJoin without join condition (equi-only)") {
+    withSQLConf(wideSMJConf: _*) {
+      val left = wideDF(50, WIDE_COLS, "l")
+      val right = wideDF(50, WIDE_COLS, "r")
+      val joined = left.join(right, Seq("id"))
+      assertSMJCodegenUsed(joined)
+      checkAnswer(joined, withoutWholeStage(joined))
+    }
+  }
+
+  test("SPARK-59787: wide SMJ with large CASE WHEN compiles with EmptyBlock") {
+    // Regression test for using EmptyBlock vs code"" in field-based ExprCodes.
+    // Without EmptyBlock, collectInputs refuses the whole-stage expression 
split and the
+    // 2000-branch CASE WHEN stays inline in processNext(), exceeding 64KB.
+    withSQLConf(wideSMJConf: _*) {
+      withSplitAlways {
+        val left = spark.range(10).toDF("k").withColumn("c1", $"k")
+        val right = spark.range(5, 15).toDF("k").withColumn("c1", $"k")
+        left.createOrReplaceTempView("smj_emptyblock_l")
+        right.createOrReplaceTempView("smj_emptyblock_r")
+        val caseWhen = largeCaseWhen("r.c1", 2000)
+        val df = spark.sql(
+          s"SELECT /*+ MERGE(r) */ l.*, r.*, $caseWhen AS v " +
+          "FROM smj_emptyblock_l l JOIN smj_emptyblock_r r ON l.k = r.k")
+        checkAnswer(df, withoutWholeStage(df))
+      }
+    }
+  }
+
+  test("SPARK-59787: field-based extraction keeps processNext under JIT 
limit") {
+    withSQLConf(wideSMJConf: _*) {
+      val left = wideDF(10, WIDE_COLS, "l")
+      val right = wideDF(10, WIDE_COLS, "r")
+      val joined = left.join(right, left("id") === right("id"))
+      assertSMJCodegenUsed(joined)
+      assert(maxStageMethodSize(joined) <= 
CodeGenerator.DEFAULT_JVM_HUGE_METHOD_LIMIT,

Review Comment:
   This assertion holds on master as well: the 56 + 56 column join (`WIDE_COLS 
= 55` plus `id`) compiles to 4,483 bytes there, and the test passes with both 
main files reverted. On master an inner join with this column mix only goes 
over 8000 at about 200 columns (8,641 bytes at 101 per side), where this PR 
gives 3,771.
   
   Could you use a width that is over the limit on master, so the test fails 
without the change? `WIDE_COLS = 100` is only about 640 bytes over, so 
something like 120 leaves margin and still fits `maxFields = 250`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to