You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by ma...@apache.org on 2026/09/26 07:46:16 UTC

(spark) branch branch-4.x updated: [SPARK-59783][SQL] Keep the caller of split functions JIT-compilable

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

MaxGekk 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 d742af68ce52 [SPARK-59783][SQL] Keep the caller of split functions JIT-compilable
d742af68ce52 is described below

commit d742af68ce520c3874be00f3c8fb426d699a386d
Author: Max Gekk <ma...@gmail.com>
AuthorDate: Sat Sep 26 09:45:52 2026 +0200

    [SPARK-59783][SQL] Keep the caller of split functions JIT-compilable
    
    ### What changes were proposed in this pull request?
    
    `CodegenContext.splitExpressions` splits the generated code of expressions into functions of at most `spark.sql.codegen.methodSplitThreshold` characters, but leaves one call per split function in the calling method, and nothing bounds how many there are. This PR bounds them, in the two places they pile up:
    
    1. **The caller.** A call and its fold compile to at most about 20 bytes plus 2 per argument. When the calls do not fit in half of the 8000 bytes HotSpot compiles, they are put into functions of eight calls each, level by level, until the rest fit. A caller that already compiles is left exactly as it is.
    2. **The merged method of an inner class.** `generateInnerClassesFunctionCalls` merges all of an inner class's split functions into one method, with no limit on how many. Past the same bound it now merges them into several methods instead.
    
    A group is folded with the caller's `foldFunctions` and wrapped with its `makeSplitFunction`. That is what `generateInnerClassesFunctionCalls` already does with an inner class's functions, so every caller of `splitExpressions` supports it. For `CaseWhen`, for example, a group runs its calls inside its own `do { ... } while (false)` and returns the result state, like the split functions themselves.
    
    The groups are small on purpose. The size was chosen with `-XX:+PrintInlining`. With groups of about 180 calls, which still compile, C2 refuses most of the split functions at its inlining budget (361 refused, 80 inlined), and the query below runs about 35% slower. With groups of four, most are inlined (464 inlined, 111 refused).
    
    ### Why are the changes needed?
    
    When an expression's code splits into hundreds of functions, as a `CASE WHEN` of a thousand branches does, the calls alone take the method holding them past the 8000 bytes HotSpot compiles (`-XX:+DontCompileHugeMethods`). That method is the one every row goes through, and it runs interpreted.
    
    With whole-stage codegen off, `SELECT CASE WHEN v = 1 THEN v * 1 ... WHEN v = 1000 THEN v * 1000 ELSE 0 END FROM (SELECT id % 1000 AS v FROM range(2000000))` generates a method holding the calls that is 8060 bytes. Spark logs it as too long to be JIT compiled, and `-XX:+PrintCompilation` shows it is never compiled. A run takes about 11.1 s on a laptop. With this change no generated method is too long, and a run takes about 1.7 s.
    
    Inside whole-stage codegen the same `CASE WHEN` is not split at all today; SPARK-33301 is a separate change for that case, which builds on this one.
    
    ### Does this PR introduce _any_ user-facing change?
    
    No, other than the performance of queries whose expressions split into many functions.
    
    ### How was this patch tested?
    
    New tests in `CodeGenerationSuite`, one per caller of `splitExpressions`: `CASE WHEN`, `COALESCE`, `IN`, the hash expressions (`Murmur3Hash`, `XxHash64`) and `GenerateOrdering`. Each builds the expression wide enough to split into many functions, checks the answer, and asserts that Spark logs no generated method too long to be JIT compiled. Each test fails without this change.
    
    Existing suites: `CodeGenerationSuite`, `CodeGenExprElimSuite`, `ConditionalExpressionSuite`, `HashExpressionsSuite`, `OrderingSuite`, `PredicateSuite`, `NullExpressionsSuite`, `StringExpressionsSuite`, `SubexpressionEliminationSuite`, `WithExpressionEvalSuite`, `GeneratedProjectionSuite`, `UnsafeRowConverterSuite` and `ComplexTypeSuite` in catalyst; `WholeStageCodegenSuite`, `DataFrameSuite`, `SQLQuerySuite`, `DataFrameAggregateSuite`, `TPCDSQuerySuite` and `TPCHQuerySuite` in sql.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Code (Claude Opus 5.5)
    
    Closes #59042 from MaxGekk/SPARK-59783.
    
    Authored-by: Max Gekk <ma...@gmail.com>
    Signed-off-by: Max Gekk <ma...@gmail.com>
    (cherry picked from commit 01bce98c3a25e51d1e2aa2b7e30fe61afdc8c270)
    Signed-off-by: Max Gekk <ma...@gmail.com>
---
 .../expressions/codegen/CodeGenerator.scala        | 103 ++++++++++++++++++++-
 .../catalyst/expressions/CodeGenerationSuite.scala |  85 +++++++++++++++++
 2 files changed, 186 insertions(+), 2 deletions(-)

diff --git a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/codegen/CodeGenerator.scala b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/codegen/CodeGenerator.scala
index 0cf8096081f6..a67e45d3797f 100644
--- a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/codegen/CodeGenerator.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/codegen/CodeGenerator.scala
@@ -1248,7 +1248,72 @@ class CodegenContext extends Logging {
         makeSplitFunction,
         foldFunctions)
 
-      foldFunctions(outerClassFunctionCalls ++ innerClassFunctionCalls)
+      foldFunctions(groupFunctionCalls(
+        (outerClassFunctionCalls ++ innerClassFunctionCalls).toSeq,
+        func,
+        arguments,
+        returnType,
+        makeSplitFunction,
+        foldFunctions))
+    }
+  }
+
+  /**
+   * How many calls to split functions taking `arguments` fit in one method with room to spare
+   * below the 8000 bytes HotSpot compiles; see `groupFunctionCalls`.
+   *
+   * The budget is per call of `splitExpressions`. A method that calls it more than once, as
+   * `ConcatWs` does three times on its vararg path, can hold several sets of calls, each within
+   * the budget, whose sum is not; with a call at about 15 bytes one ungrouped set is at most
+   * about 2500 bytes, so three leave room for the caller's own code, but not much.
+   */
+  private def splitCallsPerMethod(arguments: Seq[(String, String)]): Int = math.max(2,
+    DEFAULT_JVM_HUGE_METHOD_LIMIT / 2 / (MAX_BYTES_PER_SPLIT_CALL + 2 * arguments.length))
+
+  /**
+   * The calls to the functions `splitExpressions` split out, grouped into functions of their own
+   * where there are too many for the calling method to be JIT-compiled, level by level.
+   *
+   * The calls are what is left in the calling method, one per block of code, and a `CASE WHEN`
+   * of a thousand branches has hundreds of blocks: their calls alone take the caller past the
+   * 8000 bytes HotSpot compiles (`CodeGenerator.DEFAULT_JVM_HUGE_METHOD_LIMIT`), so the method
+   * every row goes through runs interpreted. A call and its fold compile to at most about 20 bytes
+   * plus 2 for each argument - the invocation, a load per argument, and the fold's store, test
+   * and branch - so the calls are left as they are while they fit in half of that limit, the rest
+   * being the caller's own code, and grouped otherwise. The groups are small, of
+   * `CodeGenerator.SPLIT_CALLS_PER_GROUP` calls, so that C2 can inline the split functions into
+   * each group within its inlining budget; a group of hundreds of calls stays compilable but has
+   * most of its calls left out of inlining, and runs slower. A group is folded with
+   * `foldFunctions` and wrapped with `makeSplitFunction`, which is what
+   * `generateInnerClassesFunctionCalls` does with the functions of one inner class, so every
+   * caller of `splitExpressions` supports it.
+   */
+  private def groupFunctionCalls(
+      calls: Seq[String],
+      funcName: String,
+      arguments: Seq[(String, String)],
+      returnType: String,
+      makeSplitFunction: String => String,
+      foldFunctions: Seq[String] => String,
+      level: Int = 0): Seq[String] = {
+    val callsPerMethod = splitCallsPerMethod(arguments)
+    if (calls.length <= callsPerMethod) {
+      calls
+    } else {
+      val argDefinitionString = arguments.map { case (t, name) => s"$t $name" }.mkString(", ")
+      val argInvocationString = arguments.map(_._2).mkString(", ")
+      val groupCalls = calls.grouped(SPLIT_CALLS_PER_GROUP).zipWithIndex.map { case (group, i) =>
+        val name = s"${funcName}_group${level}_$i"
+        val code =
+          s"""
+             |private $returnType $name($argDefinitionString) {
+             |  ${makeSplitFunction(foldFunctions(group))}
+             |}
+           """.stripMargin
+        s"${addNewFunction(name, code)}($argInvocationString)"
+      }.toSeq
+      groupFunctionCalls(groupCalls, funcName, arguments, returnType, makeSplitFunction,
+        foldFunctions, level + 1)
     }
   }
 
@@ -1314,13 +1379,31 @@ class CodegenContext extends Logging {
 
     val argDefinitionString = arguments.map { case (t, name) => s"$t $name" }.mkString(", ")
     val argInvocationString = arguments.map(_._2).mkString(", ")
+    val callsPerMethod = splitCallsPerMethod(arguments)
 
     innerClassToFunctions.flatMap {
       case ((innerClassName, innerClassInstance), innerClassFunctions) =>
         // for performance reasons, the functions are prepended, instead of appended,
         // thus here they are in reversed order
         val orderedFunctions = innerClassFunctions.reverse
-        if (orderedFunctions.size > MERGE_SPLIT_METHODS_THRESHOLD) {
+        if (orderedFunctions.size > callsPerMethod) {
+          // Too many calls for one method to stay JIT-compilable: one merged method per part of
+          // `SPLIT_CALLS_PER_GROUP` calls, the size C2 inlines within its budget (see
+          // `groupFunctionCalls`), whose calls the caller groups further. Each part adds one
+          // method reference to the outer class's constant pool, which the merge exists to
+          // keep small (SPARK-22226): a few entries per part, against the pool's 65535.
+          orderedFunctions.grouped(SPLIT_CALLS_PER_GROUP).zipWithIndex.map { case (part, i) =>
+            val name = s"${funcName}_part$i"
+            val body = foldFunctions(part.map(f => s"$f($argInvocationString)"))
+            val code = s"""
+                |private $returnType $name($argDefinitionString) {
+                |  ${makeSplitFunction(body)}
+                |}
+              """.stripMargin
+            addNewFunctionToClass(name, code, innerClassName)
+            s"$innerClassInstance.$name($argInvocationString)"
+          }.toSeq
+        } else if (orderedFunctions.size > MERGE_SPLIT_METHODS_THRESHOLD) {
           // Adding a new function to each inner class which contains the invocation of all the
           // ones which have been added to that inner class. For example,
           //   private class NestedClass {
@@ -1740,6 +1823,22 @@ object CodeGenerator extends Logging {
   // method which is going to be called by the outer class instead of the many small ones
   final val MERGE_SPLIT_METHODS_THRESHOLD = 3
 
+  /**
+   * The most bytecode a call to a split function and its fold take in the calling method,
+   * besides a load per argument; see `CodegenContext.groupFunctionCalls`. Measured with
+   * `javap -c` on generated classes: a `CASE WHEN` call with its fold (invoke, loads, store,
+   * compare and branch) is about 15 bytes, and a call into another nested class, with the
+   * instance loaded through two `getfield`s, is 13 to 15 bytes.
+   */
+  final val MAX_BYTES_PER_SPLIT_CALL = 20
+
+  /**
+   * How many calls to split functions `CodegenContext.groupFunctionCalls` puts in one group: few
+   * enough that the split functions, each of at most `spark.sql.codegen.methodSplitThreshold`
+   * characters of code, can all be inlined into the group by C2.
+   */
+  final val SPLIT_CALLS_PER_GROUP = 8
+
   // The number of named constants that can exist in the class is limited by the Constant Pool
   // limit, 65,536. We cannot know how many constants will be inserted for a class, so we use a
   // threshold of 1000k bytes to determine when a function should be inlined to a private, inner
diff --git a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/CodeGenerationSuite.scala b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/CodeGenerationSuite.scala
index 4dc761a04b1f..0059f35cba39 100644
--- a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/CodeGenerationSuite.scala
+++ b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/CodeGenerationSuite.scala
@@ -102,6 +102,91 @@ class CodeGenerationSuite extends SparkFunSuite with ExpressionEvalHelper {
     assert(actual.head == cases)
   }
 
+  /**
+   * Runs `body` and fails if the code it generates has a method past the 8000 bytes HotSpot
+   * compiles, which `CodeGenerator` logs as it compiles the class.
+   */
+  private def assertJitCompilable(body: => Unit): Unit = {
+    val appender = new LogAppender("methods too long to be JIT compiled")
+    withLogAppender(appender,
+        loggerNames = Seq(classOf[CodeGenerator[_, _]].getName), level = Some(Level.INFO)) {
+      body
+    }
+    val tooLong = appender.loggingEvents.map(_.getMessage.getFormattedMessage)
+      .filter(_.contains("too long to be JIT compiled"))
+    assert(tooLong.isEmpty, tooLong.mkString("\n"))
+  }
+
+  // The tests below pin SPARK-59783: an expression split into hundreds of functions left one call
+  // per function in the method holding them, and the calls alone took that method past the
+  // 8000 bytes HotSpot compiles, so every row ran it interpreted. Each test covers one caller of
+  // `splitExpressions`, with as many children as it takes for that method to cross the limit
+  // without the grouping: fewer where one child generates more code.
+
+  test("SPARK-59783: the calls to the functions CASE WHEN splits into are JIT-compilable") {
+    val wide = 3000
+    val input = BoundReference(0, IntegerType, nullable = false)
+    val expression = CaseWhen(
+      (1 to wide).map(k => (EqualTo(input, Literal(k)), Multiply(input, Literal(k)))), Literal(0))
+    assertJitCompilable {
+      val projection = GenerateMutableProjection.generate(Seq(expression))
+      Seq(7 -> 49, wide -> wide * wide, wide + 1 -> 0).foreach { case (in, out) =>
+        assert(projection(new GenericInternalRow(Array[Any](in))).getInt(0) == out)
+      }
+    }
+  }
+
+  test("SPARK-59783: the calls to the functions COALESCE splits into are JIT-compilable") {
+    val wide = 10000
+    val expression = Coalesce((0 until wide).map(i => BoundReference(i, IntegerType, true)))
+    assertJitCompilable {
+      val projection = GenerateMutableProjection.generate(Seq(expression))
+      val values = new Array[Any](wide)
+      assert(projection(new GenericInternalRow(values)).isNullAt(0))
+      values(wide - 1) = 42
+      assert(projection(new GenericInternalRow(values)).getInt(0) == 42)
+    }
+  }
+
+  test("SPARK-59783: the calls to the functions IN splits into are JIT-compilable") {
+    val wide = 10000
+    val input = BoundReference(0, IntegerType, nullable = false)
+    val expression = In(input, (1 to wide).map(k => Literal(k * 2)))
+    assertJitCompilable {
+      val projection = GenerateMutableProjection.generate(Seq(expression))
+      Seq(2 -> true, wide * 2 -> true, 3 -> false).foreach { case (in, out) =>
+        assert(projection(new GenericInternalRow(Array[Any](in))).getBoolean(0) == out)
+      }
+    }
+  }
+
+  test("SPARK-59783: the calls to the functions a hash splits into are JIT-compilable") {
+    val wide = 30000
+    val children = (0 until wide).map(i => BoundReference(i, IntegerType, true))
+    val row = new GenericInternalRow(Array.tabulate[Any](wide)(identity))
+    Seq(Murmur3Hash(children, 42), XxHash64(children, 42L)).foreach { expression =>
+      assertJitCompilable {
+        val projection = GenerateMutableProjection.generate(Seq(expression))
+        assert(projection(row).get(0, expression.dataType) == expression.eval(row))
+      }
+    }
+  }
+
+  test("SPARK-59783: the calls to the functions an ordering splits into are JIT-compilable") {
+    val wide = 3000
+    val sortOrder = (0 until wide).map(i => SortOrder(BoundReference(i, IntegerType, true),
+      Ascending))
+    val small = new GenericInternalRow(Array.tabulate[Any](wide)(identity))
+    val large = new GenericInternalRow(
+      Array.tabulate[Any](wide)(i => if (i == wide - 1) i + 1 else i))
+    assertJitCompilable {
+      val ordering = GenerateOrdering.generate(sortOrder)
+      assert(ordering.compare(small, large) < 0)
+      assert(ordering.compare(large, small) > 0)
+      assert(ordering.compare(small, small) == 0)
+    }
+  }
+
   test("SPARK-22543: split large if expressions into blocks due to JVM code size limit") {
     var strExpr: Expression = Literal("abc")
     for (_ <- 1 to 150) {


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