You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by ag...@apache.org on 2026/08/16 16:32:51 UTC

(datafusion-comet) branch main updated: test: make expression benchmark harness fair and reproducible (#5371)

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

andygrove pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/datafusion-comet.git


The following commit(s) were added to refs/heads/main by this push:
     new 4b60dcad9d test: make expression benchmark harness fair and reproducible (#5371)
4b60dcad9d is described below

commit 4b60dcad9d85d6148da8e74fc3d377a47d1e31c3
Author: Andy Grove <ag...@apache.org>
AuthorDate: Sun Aug 16 09:32:45 2026 -0700

    test: make expression benchmark harness fair and reproducible (#5371)
    
    * test: make expression benchmark harness fair and reproducible
    
    `runExpressionBenchmark` backs 27 benchmark suites. Four defects made its
    output untrustworthy.
    
    Apply `spark.sql.optimizer.excludedRules` to both arms rather than the Comet
    arm only, and append to the existing value instead of overwriting it. Excluding
    `ConstantFolding` for Comet alone let Spark fold expressions over literal
    arguments away entirely: for `select space(2) from parquetV1Table` the Spark
    plan was `Project [   AS space(2)]`, doing no per-row work, so that row reported
    a Comet regression that does not exist.
    
    Warn when the Spark baseline plan does no work beyond scanning and projecting
    bare attributes or literals, which means the optimizer removed the benchmarked
    expression. Any other node counts as work, so the join and aggregate suites are
    unaffected.
    
    Route both that warning and the existing not-fully-native warning to `output`,
    so they land in the results file above the affected table rather than scrolling
    past on the console. Running the suites with this in place shows `translate` in
    `CometStringExpressionBenchmark` and eight `c_short` cases in
    `CometCastNumericToNumericBenchmark` falling back to a JVM `Project`, meaning
    those rows labelled "Comet" were measuring Spark.
    
    Generate the base table from a pure function of the row id instead of an
    unseeded `scala.util.Random`, so runs are comparable. Seeding a driver-side
    `Random` would not have worked: the closure runs per row on the executor.
    
    Part of #5363.
    
    * refactor: simplify benchmark harness plan checks and warning output
    
    Write warnings through `Benchmark.out`, which already tees the console and
    the results file, instead of hand-rolling the tee. This also keeps the warning
    ordered against the results table, since both now go through the same stream.
    
    Collapse `isTrivialPlan` to a single negated `exists` over the plan, dropping
    the mid-method `return`, the second traversal and the one-use `unwrapAlias`.
    
    Drop the untimed `noop()` from the Spark baseline check. Before execution
    `stripAQEPlan` already yields the initial physical plan, which carries the
    projections the check inspects; the nodes missing pre-execution are the
    codegen and columnar-transition wrappers the check classifies as no-work
    anyway. The Comet check keeps its execution, because AQE can re-plan a join
    after the first stage completes.
    
    Use `ConstantFolding.ruleName` rather than a hardcoded class name, and
    `Utils.stringToSeq` rather than an open-coded comma-list parser.
    
    * test: benchmark space over a column, and flag row-invariant projections
    
    Excluding `ConstantFolding` on both arms made the `space(2)` plans symmetric
    but not the work. Given a literal, Comet's native `space` receives a
    `ColumnarValue::Scalar`, builds one string per batch and lets DataFusion
    broadcast it, while Spark's `StringSpace` calls `UTF8String.blankString` once
    per row. Benchmark `space(c2)` over a new non-negative integer column instead,
    so both engines evaluate the expression on every row.
    
    The plan check could not catch this, because the retained `ProjectExec` looks
    like real work either way. Add a second check for projections that reference no
    input column: their value is the same for every row, so an engine is free to
    evaluate them once per batch, and engines differ on whether they do.
    Nondeterministic expressions are excluded, since `rand()` also references no
    column but genuinely evaluates per row.
    
    Verified that the old query trips the new warning, that the new one does not,
    and that `floor(rand() * 100)` does not.
    
    * fix: drop unused string interpolator flagged by scalafix
---
 .../spark/sql/benchmark/CometBenchmarkBase.scala   | 164 +++++++++++++++++----
 .../benchmark/CometStringExpressionBenchmark.scala |  13 +-
 2 files changed, 145 insertions(+), 32 deletions(-)

diff --git a/spark/src/test/scala/org/apache/spark/sql/benchmark/CometBenchmarkBase.scala b/spark/src/test/scala/org/apache/spark/sql/benchmark/CometBenchmarkBase.scala
index 5c5f84ebbb..1254da3491 100644
--- a/spark/src/test/scala/org/apache/spark/sql/benchmark/CometBenchmarkBase.scala
+++ b/spark/src/test/scala/org/apache/spark/sql/benchmark/CometBenchmarkBase.scala
@@ -23,15 +23,17 @@ import java.io.File
 import java.nio.charset.StandardCharsets
 import java.util.Base64
 
-import scala.util.Random
-
 import org.apache.parquet.crypto.DecryptionPropertiesFactory
 import org.apache.parquet.crypto.keytools.{KeyToolkit, PropertiesDrivenCryptoFactory}
 import org.apache.parquet.crypto.keytools.mocks.InMemoryKMS
 import org.apache.spark.SparkConf
 import org.apache.spark.benchmark.Benchmark
 import org.apache.spark.sql.{DataFrame, DataFrameWriter, Row, SparkSession}
+import org.apache.spark.sql.catalyst.expressions.{Alias, AttributeReference, Expression, Literal}
+import org.apache.spark.sql.catalyst.optimizer.ConstantFolding
 import org.apache.spark.sql.comet.CometPlanChecker
+import org.apache.spark.sql.comet.util.Utils
+import org.apache.spark.sql.execution.{ColumnarToRowExec, InputAdapter, LeafExecNode, ProjectExec, SparkPlan, WholeStageCodegenExec}
 import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
 import org.apache.spark.sql.execution.benchmark.SqlBasedBenchmark
 import org.apache.spark.sql.internal.SQLConf
@@ -97,9 +99,13 @@ trait CometBenchmarkBase
       useDictionary: Boolean = false)(f: Int => Any): Unit = {
     withTempTable(tbl) {
       import spark.implicits._
+      // Derive the values from the row id with a pure function rather than a random number
+      // generator, so that results are comparable across runs. Seeding a driver-side `Random`
+      // would not work here: the closure runs per row on the executor.
       spark
         .range(values)
-        .map(_ => if (useDictionary) Random.nextLong() % 5 else Random.nextLong())
+        .map(i =>
+          if (useDictionary) CometBenchmarkBase.mix64(i) % 5 else CometBenchmarkBase.mix64(i))
         .createOrReplaceTempView(tbl)
       runBenchmark(benchmarkName)(f(values))
     }
@@ -125,43 +131,69 @@ trait CometBenchmarkBase
       extraCometConfigs: Map[String, String] = Map.empty): Unit = {
     val benchmark = new Benchmark(name, cardinality, output = output)
 
-    benchmark.addCase("Spark") { _ =>
-      withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
-        spark.sql(query).noop()
-      }
-    }
+    // Constant folding is excluded so that expressions over literal arguments are still evaluated
+    // per row. It must be excluded for both arms: if only Comet excludes it, Spark folds the
+    // expression away and does no per-row work, and the comparison is meaningless.
+    val noConstantFolding =
+      SQLConf.OPTIMIZER_EXCLUDED_RULES.key -> excludedRulesWith(ConstantFolding.ruleName)
 
-    val cometExecConfigs = Map(
+    val sparkConfigs = Seq(noConstantFolding, CometConf.COMET_ENABLED.key -> "false")
+
+    val cometConfigs = Seq(
+      noConstantFolding,
       CometConf.COMET_ENABLED.key -> "true",
-      CometConf.COMET_EXEC_ENABLED.key -> "true",
-      "spark.sql.optimizer.excludedRules" ->
-        "org.apache.spark.sql.catalyst.optimizer.ConstantFolding") ++ extraCometConfigs
+      CometConf.COMET_EXEC_ENABLED.key -> "true") ++ extraCometConfigs
+
+    // Check that the benchmarked expression survives optimization into the Spark baseline plan.
+    // The query is not executed: before execution `stripAQEPlan` yields the initial physical
+    // plan, which already carries the projections this check inspects.
+    withSQLConf(sparkConfigs: _*) {
+      val plan = stripAQEPlan(spark.sql(query).queryExecution.executedPlan)
+      if (isTrivialPlan(plan)) {
+        warn(
+          benchmark,
+          """WARNING: the Spark baseline plan does no work beyond scanning and projecting
+            |columns, so this case is not measuring an expression. The expression was most
+            |likely removed by the optimizer.
+            |Spark plan:""".stripMargin + "\n" + plan.treeString)
+      }
+      val rowInvariant = rowInvariantProjections(plan)
+      if (rowInvariant.nonEmpty) {
+        warn(
+          benchmark,
+          s"""WARNING: these projections reference no input column, so their value is the same
+             |for every row: ${rowInvariant.mkString(", ")}
+             |An engine may evaluate them once per batch and broadcast the result rather than
+             |per row, so the two arms are not necessarily doing comparable work. Benchmark the
+             |expression over a column instead.""".stripMargin)
+      }
+    }
 
-    // Check that the plan is fully Comet native before running the benchmark
-    withSQLConf(cometExecConfigs.toSeq: _*) {
+    // Check that the plan is fully Comet native before running the benchmark. Unlike the check
+    // above this one does execute the query, because AQE can re-plan a join after the first
+    // stage completes and the Comet operators are what we are checking for.
+    withSQLConf(cometConfigs: _*) {
       val df = spark.sql(query)
       df.noop()
       val plan = stripAQEPlan(df.queryExecution.executedPlan)
-      findFirstNonCometOperator(plan) match {
-        case Some(op) =>
-          // scalastyle:off println
-          println()
-          println("=" * 80)
-          println("WARNING: Benchmark plan is NOT fully Comet native!")
-          println(s"First non-Comet operator: ${op.nodeName}")
-          println("=" * 80)
-          println("Query plan:")
-          println(plan.treeString)
-          println("=" * 80)
-          println()
-        // scalastyle:on println
-        case None =>
-        // All operators are Comet native, no warning needed
+      findFirstNonCometOperator(plan).foreach { op =>
+        warn(
+          benchmark,
+          s"""WARNING: the Comet plan is NOT fully Comet native, so the Comet case below is
+             |partly or wholly measuring Spark.
+             |First non-Comet operator: ${op.nodeName}
+             |Comet plan:""".stripMargin + "\n" + plan.treeString)
+      }
+    }
+
+    benchmark.addCase("Spark") { _ =>
+      withSQLConf(sparkConfigs: _*) {
+        spark.sql(query).noop()
       }
     }
 
     benchmark.addCase("Comet") { _ =>
-      withSQLConf(cometExecConfigs.toSeq: _*) {
+      withSQLConf(cometConfigs: _*) {
         spark.sql(query).noop()
       }
     }
@@ -169,6 +201,62 @@ trait CometBenchmarkBase
     benchmark.run()
   }
 
+  /**
+   * Returns the value of `spark.sql.optimizer.excludedRules` with `rule` appended, so that
+   * benchmark-specific exclusions do not clobber exclusions already configured by the caller.
+   */
+  private def excludedRulesWith(rule: String): String =
+    (Utils.stringToSeq(spark.conf.get(SQLConf.OPTIMIZER_EXCLUDED_RULES.key, "")) :+ rule).distinct
+      .mkString(",")
+
+  /**
+   * Returns true if the plan does nothing but scan and emit columns, which means the benchmarked
+   * expression was removed by the optimizer and the case measures nothing.
+   *
+   * Any node other than a scan, projection or row conversion counts as real work, so joins,
+   * aggregates and filters are never reported as trivial even when they project bare attributes.
+   */
+  private def isTrivialPlan(plan: SparkPlan): Boolean = !plan.exists {
+    case p: ProjectExec => p.projectList.exists(expr => !isTrivialExpr(expr))
+    case _: ColumnarToRowExec | _: WholeStageCodegenExec | _: InputAdapter | _: LeafExecNode =>
+      false
+    case _ => true
+  }
+
+  /** A projection that copies a column or emits a constant, doing no per-row work. */
+  private def isTrivialExpr(expr: Expression): Boolean = expr match {
+    case _: AttributeReference | _: Literal => true
+    case Alias(_: AttributeReference | _: Literal, _) => true
+    case _ => false
+  }
+
+  /**
+   * Projections whose value is the same for every row, because they reference no input column.
+   *
+   * An engine is free to evaluate these once per batch and broadcast the result, and engines
+   * differ on whether they do. Comet's native `space` takes a `ColumnarValue::Scalar` and builds
+   * one string per batch, while Spark's `StringSpace` calls `UTF8String.blankString` per row. The
+   * two plans look identical, so nothing else here can tell them apart.
+   *
+   * Nondeterministic expressions are excluded: `rand()` also references no column but genuinely
+   * evaluates per row.
+   */
+  private def rowInvariantProjections(plan: SparkPlan): Seq[Expression] =
+    plan
+      .collect { case p: ProjectExec => p }
+      .flatMap(_.projectList)
+      .filter(expr => expr.references.isEmpty && expr.deterministic && !isTrivialExpr(expr))
+
+  /**
+   * Writes a warning to the benchmark results file as well as the console. `Benchmark.out` tees
+   * the two, and writing through it keeps the warning ordered against the results table that
+   * `Benchmark.run` writes to the same stream.
+   */
+  private def warn(benchmark: Benchmark, message: String): Unit = {
+    val border = "=" * 80
+    benchmark.out.println(s"\n$border\n$message\n$border")
+  }
+
   protected def addParquetScanCases(
       benchmark: Benchmark,
       query: String,
@@ -291,3 +379,19 @@ trait CometBenchmarkBase
       .select((($"value" - 500) / 100.0) cast decimal as Symbol("dec"))
   }
 }
+
+object CometBenchmarkBase {
+
+  /**
+   * SplitMix64 finalizer, used to turn a row id into a well distributed pseudo-random value.
+   *
+   * This lives in the companion object rather than the trait because referencing a trait method
+   * from a Dataset closure captures `this`, which is not serializable.
+   */
+  def mix64(value: Long): Long = {
+    var z = value + 0x9e3779b97f4a7c15L
+    z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L
+    z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL
+    z ^ (z >>> 31)
+  }
+}
diff --git a/spark/src/test/scala/org/apache/spark/sql/benchmark/CometStringExpressionBenchmark.scala b/spark/src/test/scala/org/apache/spark/sql/benchmark/CometStringExpressionBenchmark.scala
index 2b862f9e60..af76ecc76f 100644
--- a/spark/src/test/scala/org/apache/spark/sql/benchmark/CometStringExpressionBenchmark.scala
+++ b/spark/src/test/scala/org/apache/spark/sql/benchmark/CometStringExpressionBenchmark.scala
@@ -75,7 +75,11 @@ object CometStringExpressionBenchmark extends CometBenchmarkBase {
     StringExprConfig("rlike", "select c1 rlike '[0-9]+' from parquetV1Table"),
     StringExprConfig("rpad", "select rpad(c1, 150, 'x') from parquetV1Table"),
     StringExprConfig("rtrim", "select rtrim(c1) from parquetV1Table"),
-    StringExprConfig("space", "select space(2) from parquetV1Table"),
+    // `space` takes its length from a column rather than a literal. Given a literal, Comet's
+    // native `space` receives a `ColumnarValue::Scalar`, builds one string per batch and lets
+    // DataFusion broadcast it, while Spark's `StringSpace` calls `UTF8String.blankString` once
+    // per row. The plans look symmetric but the work is not.
+    StringExprConfig("space", "select space(c2) from parquetV1Table"),
     StringExprConfig("startswith", "select startswith(c1, '1') from parquetV1Table"),
     StringExprConfig("substring", "select substring(c1, 1, 100) from parquetV1Table"),
     StringExprConfig("translate", "select translate(c1, '123456', 'aBcDeF') from parquetV1Table"),
@@ -86,9 +90,14 @@ object CometStringExpressionBenchmark extends CometBenchmarkBase {
     runBenchmarkWithTable("String expressions", 1024) { v =>
       withTempPath { dir =>
         withTempTable("parquetV1Table") {
+          // c2 gives expressions that take a length or a count something to vary over per row.
+          // `pmod` keeps it non-negative, so `space(c2)` builds a string on every row rather
+          // than returning empty for the negative half of the input.
           prepareTable(
             dir,
-            spark.sql(s"SELECT REPEAT(CAST(value AS STRING), 10) AS c1 FROM $tbl"))
+            spark.sql(
+              "SELECT REPEAT(CAST(value AS STRING), 10) AS c1," +
+                s" CAST(PMOD(value, 200) AS INT) AS c2 FROM $tbl"))
 
           val extraConfigs = Map(
             CometConf.getExprAllowIncompatConfigKey("Upper") -> "true",


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