This is an automated email from the ASF dual-hosted git repository.
zhouyuan pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gluten.git
The following commit(s) were added to refs/heads/main by this push:
new 0963c3fded [VL] Expand Spark 3.5 Kafka test coverage and add streaming
benchmarks (#13599)
0963c3fded is described below
commit 0963c3fded632f9e01ed41cfc4a75a80162a8fbf
Author: Reema <[email protected]>
AuthorDate: Mon Nov 23 00:50:38 2026 +0300
[VL] Expand Spark 3.5 Kafka test coverage and add streaming benchmarks
(#13599)
Expand Kafka streaming test coverage for Gluten on Spark 3.5 and add a
bounded Structured Streaming benchmark.
---
.github/workflows/velox_kafka.yml | 53 +++
backends-velox/pom.xml | 7 +
.../benchmark/KafkaIntegrationBenchmark.scala | 530 +++++++++++++++++++++
.../benchmark/RateMicroBatchBenchmark.scala | 315 ++++++++++++
.../benchmark/RateMicroBatchBenchmarkResult.scala | 68 +++
.../apache/gluten/execution/OffloadKafkaScan.scala | 26 +-
.../gluten/execution/kafka/KafkaTestUtils.scala | 40 ++
gluten-ut/spark35/pom.xml | 78 +++
.../kafka010/GlutenKafkaHybridSourceSuite.scala | 87 ++++
.../GlutenKafkaMicroBatchV2SourceSuite.scala | 284 +++++++++++
.../kafka010/GlutenKafkaSourceStressSuite.scala} | 11 +-
.../spark/sql/kafka010/GlutenKafkaSourceTest.scala | 139 ++++++
.../gluten/utils/velox/VeloxTestSettings.scala | 11 +
.../org/apache/spark/sql/GlutenSQLQuerySuite.scala | 29 ++
.../sources/GlutenResolvedDataSourceSuite.scala | 12 +-
15 files changed, 1680 insertions(+), 10 deletions(-)
diff --git a/.github/workflows/velox_kafka.yml
b/.github/workflows/velox_kafka.yml
index e65bd4310c..dda215906a 100644
--- a/.github/workflows/velox_kafka.yml
+++ b/.github/workflows/velox_kafka.yml
@@ -40,6 +40,12 @@ on:
branches-ignore:
- main
workflow_dispatch:
+ inputs:
+ run_stress:
+ description: Run the longer Spark Kafka stress suite after correctness
checks
+ required: false
+ type: boolean
+ default: false
permissions:
contents: read
@@ -214,6 +220,15 @@ jobs:
./build/mvn -B -ntp test -pl backends-velox -Pbackends-velox
-Pspark-3.5 \
-Pscala-2.12 -Pjava-17 -Pkafka -Pfast-build \
-Dsuites=org.apache.gluten.execution.kafka.VeloxGlutenKafkaScanSuite
+
+ # PR #13237 is merged upstream. A checkout missing its Velox integration
+ # must fail the native scan assertions, rather than pass on Spark
fallback.
+ # The upstream suites start their own embedded Kafka brokers.
+ - name: Run Spark Kafka correctness and native scan assertions
+ run: |
+ ./build/mvn -B -ntp test -pl gluten-ut/spark35 -Pbackends-velox
-Pspark-3.5 \
+ -Pscala-2.12 -Pjava-17 -Pkafka -Pspark-ut -Pfast-build \
+
-Dsuites=org.apache.spark.sql.kafka010.GlutenKafkaMicroBatchV2SourceSuite
- name: Upload test results
if: always()
uses: actions/upload-artifact@v7
@@ -222,3 +237,41 @@ jobs:
path: |
**/surefire-reports/*
**/target/*.log
+
+ spark35-stress:
+ if: github.event_name == 'workflow_dispatch' && inputs.run_stress
+ # Collect stress results even when the separate correctness job fails.
+ needs: build-native
+ runs-on: ubuntu-22.04
+ timeout-minutes: 120
+ env:
+ SPARK_LOCAL_IP: 127.0.0.1
+ steps:
+ - uses: actions/checkout@v7
+ - name: Setup java
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y openjdk-17-jdk
+ echo "JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64" >> $GITHUB_ENV
+ echo "/usr/lib/jvm/java-17-openjdk-amd64/bin" >> $GITHUB_PATH
+ - uses: actions/download-artifact@v8
+ with:
+ name: velox-kafka-native-${{ github.sha }}
+ path: cpp/build/releases/
+ - name: Install Spark 3.5 modules with Kafka support
+ run: |
+ ./build/mvn -B -ntp install -Pbackends-velox -Pspark-3.5
-Pscala-2.12 \
+ -Pjava-17 -Pkafka -Pspark-ut -Pfast-build -DskipTests
+ - name: Run Spark Kafka stress scenarios
+ run: |
+ ./build/mvn -B -ntp test -pl gluten-ut/spark35 -Pbackends-velox
-Pspark-3.5 \
+ -Pscala-2.12 -Pjava-17 -Pkafka -Pspark-ut -Pfast-build \
+ -Dsuites=org.apache.spark.sql.kafka010.GlutenKafkaSourceStressSuite
+ - name: Upload stress test results
+ if: always()
+ uses: actions/upload-artifact@v7
+ with:
+ name: velox-kafka-spark35-stress-results
+ path: |
+ **/surefire-reports/*
+ **/target/*.log
diff --git a/backends-velox/pom.xml b/backends-velox/pom.xml
index fff0f1fdfe..7f7b169802 100644
--- a/backends-velox/pom.xml
+++ b/backends-velox/pom.xml
@@ -889,6 +889,13 @@
<artifactId>gluten-kafka</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>org.apache.gluten</groupId>
+ <artifactId>gluten-kafka</artifactId>
+ <version>${project.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql-kafka-0-10_${scala.binary.version}</artifactId>
diff --git
a/backends-velox/src-kafka/test/scala/org/apache/spark/sql/execution/benchmark/KafkaIntegrationBenchmark.scala
b/backends-velox/src-kafka/test/scala/org/apache/spark/sql/execution/benchmark/KafkaIntegrationBenchmark.scala
new file mode 100644
index 0000000000..28889f3283
--- /dev/null
+++
b/backends-velox/src-kafka/test/scala/org/apache/spark/sql/execution/benchmark/KafkaIntegrationBenchmark.scala
@@ -0,0 +1,530 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.spark.sql.execution.benchmark
+
+import org.apache.gluten.execution.kafka.KafkaTestUtils
+
+import org.apache.spark.SparkConf
+import org.apache.spark.benchmark.Benchmark
+import org.apache.spark.sql.{DataFrame, SparkSession}
+import org.apache.spark.sql.execution.datasources.v2.MicroBatchScanExec
+import org.apache.spark.sql.streaming.{StreamingQuery, StreamingQueryListener,
Trigger}
+
+import org.apache.kafka.clients.admin.{AdminClient, AdminClientConfig,
NewTopic}
+
+import java.io.File
+import java.time.Duration
+import java.util.{Collections, Properties, UUID}
+import java.util.concurrent.{ConcurrentLinkedQueue, CountDownLatch, TimeUnit}
+
+import scala.collection.JavaConverters._
+
+/**
+ * Benchmark the supported Velox Kafka read integration, fallback, checkpoint
recovery and a bounded
+ * Spark-producer-to-Parquet pipeline. Native reads use micro-batch execution;
Kafka writes and
+ * checkpoint management remain Spark operations.
+ */
+object KafkaIntegrationBenchmark extends SqlBasedBenchmark {
+ private val scenarioNames = Seq("scan", "projection", "headers",
"checkpoint", "pipeline")
+ private val kafkaColumns =
+ Seq("key", "value", "topic", "partition", "offset", "timestamp",
"timestampType")
+
+ private case class Settings(
+ broker: String,
+ rows: Long,
+ partitions: Int,
+ payloadBytes: Int,
+ maxOffsets: Long,
+ iterations: Int,
+ timeoutMs: Long,
+ engines: Seq[Boolean])
+
+ private case class ReadResult(
+ queryId: UUID,
+ runId: UUID,
+ samples: Seq[KafkaBenchmarkSample],
+ elapsedMs: Double,
+ plan: String)
+
+ override def getSparkSession: SparkSession = {
+ val conf = new SparkConf()
+ .setAppName("KafkaIntegrationBenchmark")
+ .setIfMissing("spark.master", "local[2]")
+ .setIfMissing("spark.sql.shuffle.partitions", "2")
+ .setIfMissing("spark.sql.adaptive.enabled", "false")
+ .setIfMissing("spark.sql.streaming.stopTimeout", "10000")
+ if (conf.get("spark.gluten.benchmark.kafka.engine", "both") != "spark") {
+ conf
+ .setIfMissing("spark.plugins", "org.apache.gluten.GlutenPlugin")
+ .setIfMissing(
+ "spark.shuffle.manager",
+ "org.apache.spark.shuffle.sort.ColumnarShuffleManager")
+ .setIfMissing("spark.memory.offHeap.enabled", "true")
+ .setIfMissing("spark.memory.offHeap.size", "1g")
+ }
+ SparkSession.builder().config(conf).getOrCreate()
+ }
+
+ override def runBenchmarkSuite(mainArgs: Array[String]): Unit = {
+ val conf = spark.sparkContext.getConf
+ val engine = conf.get("spark.gluten.benchmark.kafka.engine", "both")
+ require(Set("spark", "gluten", "both").contains(engine), "Engine must be
spark, gluten or both")
+ val settings = Settings(
+ conf.get(
+ "spark.gluten.benchmark.kafka.bootstrapServers",
+ sys.env.getOrElse("KAFKA_BOOTSTRAP_SERVERS", "localhost:9092")),
+ conf.getLong("spark.gluten.benchmark.kafka.rows", 100000L),
+ conf.getInt("spark.gluten.benchmark.kafka.partitions", 2),
+ conf.getInt("spark.gluten.benchmark.kafka.payloadBytes", 128),
+ conf.getLong("spark.gluten.benchmark.kafka.maxOffsetsPerTrigger",
10000L),
+ conf.getInt("spark.gluten.benchmark.kafka.iterations", 3),
+ conf.getLong("spark.gluten.benchmark.kafka.timeoutMs", 120000L),
+ if (engine == "spark") Seq(false) else if (engine == "gluten") Seq(true)
else Seq(false, true)
+ )
+ require(
+ settings.partitions > 0 && settings.partitions <= Int.MaxValue / 2 &&
+ settings.rows >= 2L * settings.partitions && settings.rows <=
Long.MaxValue / 2,
+ "Provide at least two rows per partition and a row count that can be
doubled"
+ )
+ require(settings.payloadBytes >= 21, "Payload size must fit a 20-byte ID
and one binary NUL")
+ require(
+ settings.maxOffsets > 0 && settings.iterations > 0 && settings.timeoutMs
> 0,
+ "Limits must be positive")
+ val selected = conf.get("spark.gluten.benchmark.kafka.scenarios", "all")
match {
+ case "all" => scenarioNames
+ case names => names.split(",").toSeq.map(_.trim)
+ }
+ require(
+ selected.nonEmpty && selected.distinct.size == selected.size &&
+ selected.forall(scenarioNames.contains),
+ s"Choose distinct scenarios from ${scenarioNames.mkString(",")}, or all"
+ )
+
+ val properties = new Properties()
+ properties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, settings.broker)
+ properties.put(AdminClientConfig.DEFAULT_API_TIMEOUT_MS_CONFIG, "30000")
+ val admin = AdminClient.create(properties)
+ try {
+ selected.foreach {
+ case "checkpoint" => benchmarkCheckpoint(admin, settings)
+ case "pipeline" => benchmarkPipeline(admin, settings)
+ case scenario => benchmarkRead(admin, settings, scenario)
+ }
+ } finally {
+ admin.close(Duration.ofSeconds(5))
+ }
+ }
+
+ private def withTopic(admin: AdminClient, settings: Settings)(f: String =>
Unit): Unit = {
+ val topic = "gluten_kafka_benchmark_" +
UUID.randomUUID().toString.replace("-", "")
+ admin
+ .createTopics(Collections.singletonList(new NewTopic(topic,
settings.partitions, 1.toShort)))
+ .all()
+ .get(30, TimeUnit.SECONDS)
+ try {
+ f(topic)
+ } finally {
+ admin.deleteTopics(Collections.singletonList(topic)).all().get(30,
TimeUnit.SECONDS)
+ }
+ }
+
+ private def produce(topic: String, settings: Settings, start: Long, rows:
Long): Unit = {
+ // Use Spark's producer for both engines; this is not a native Kafka write
benchmark.
+ withSQLConf("spark.gluten.enabled" -> "false") {
+ spark
+ .range(start, start + rows, 1L, settings.partitions)
+ .selectExpr(
+ "cast(case when id % 11 = 2 then null when id % 11 = 1 then '' " +
+ "else concat(cast(id as string), chr(0), 'key') end as binary) as
key",
+ "cast(case when id % 11 = 0 then null when id % 11 = 1 then '' " +
+ s"else concat(lpad(cast(id as string), 20, '0'), chr(0), " +
+ s"repeat('x', ${settings.payloadBytes - 21})) end as binary) as
value",
+ s"cast(id % ${settings.partitions} as int) as partition",
+ "array(named_struct('key', 'benchmark', " +
+ "'value', cast(concat('id=', cast(id as string)) as binary))) as
headers"
+ )
+ .write
+ .format("kafka")
+ .option("kafka.bootstrap.servers", settings.broker)
+ .option("topic", topic)
+ .save()
+ }
+ }
+
+ private def readOptions(
+ topic: String,
+ settings: Settings,
+ scenario: String): Map[String, String] = {
+ val base = Map(
+ "kafka.bootstrap.servers" -> settings.broker,
+ "subscribe" -> topic,
+ "startingOffsets" -> "earliest",
+ "includeHeaders" -> (scenario == "headers").toString,
+ "failOnDataLoss" -> "true"
+ )
+ if (scenario == "projection") {
+ val offsets = (0 until settings.partitions).map(p =>
s""""$p":1""").mkString(",")
+ base ++ Map(
+ "startingOffsets" -> s"""{"$topic":{$offsets}}""",
+ "minPartitions" -> (2 * settings.partitions).toString)
+ } else {
+ base
+ }
+ }
+
+ private def project(frame: DataFrame, scenario: String): DataFrame = {
+ val columns = scenario match {
+ case "projection" => Seq("offset", "value", "partition")
+ case "headers" => kafkaColumns :+ "headers"
+ case _ => kafkaColumns
+ }
+ frame.selectExpr(columns: _*)
+ }
+
+ private def runRead(
+ topic: String,
+ settings: Settings,
+ scenario: String,
+ enabled: Boolean,
+ checkpoint: String,
+ parquet: Option[String],
+ timer: Option[Benchmark.Timer] = None,
+ beforeStart: () => Unit = () => (),
+ firstBatchId: Long = 0L): ReadResult = {
+ var result: ReadResult = null
+ withSQLConf("spark.gluten.enabled" -> enabled.toString) {
+ val name = "kafka_benchmark_" + UUID.randomUUID().toString.replace("-",
"")
+ val progress = new KafkaBenchmarkProgress(name)
+ spark.streams.addListener(progress)
+ var query: StreamingQuery = null
+ try {
+ val frame = spark.readStream
+ .format("kafka")
+ .options(readOptions(topic, settings, scenario))
+ .option("maxOffsetsPerTrigger", settings.maxOffsets)
+ .load()
+ val writer = project(frame, scenario).writeStream
+ .format(if (parquet.isDefined) "parquet" else "noop")
+ .queryName(name)
+ .option("checkpointLocation", checkpoint)
+ .trigger(Trigger.AvailableNow())
+ parquet.foreach(path => writer.option("path", path))
+ timer.foreach(_.startTiming())
+ val startNanos = System.nanoTime()
+ var elapsedMs = 0.0
+ try {
+ beforeStart()
+ query = writer.start()
+ require(
+ query.awaitTermination(settings.timeoutMs),
+ "Kafka query exceeded completion timeout")
+ } finally {
+ elapsedMs = (System.nanoTime() - startNanos) / 1e6
+ timer.foreach(_.stopTiming())
+ }
+
+ val plan = KafkaTestUtils.executedPlan(query)
+ // Avoid loading native scan classes when only the Spark baseline is
requested.
+ val nativeScans = plan.collect {
+ case p
+ if p.getClass.getName ==
+ "org.apache.gluten.execution.MicroBatchScanExecTransformer" =>
p
+ }
+ val sparkScans = plan.collect { case p: MicroBatchScanExec => p }
+ try {
+ KafkaBenchmarkResult.validateScanCounts(
+ nativeScans.size,
+ sparkScans.size,
+ enabled && scenario != "headers")
+ } catch {
+ case e: IllegalArgumentException =>
+ throw new IllegalStateException(s"Unexpected Kafka
scan:\n${plan.treeString}", e)
+ }
+ val samples = progress.awaitSamples(settings.timeoutMs)
+ KafkaBenchmarkResult.validateBatchSequence(
+ samples,
+ firstBatchId,
+ KafkaTestUtils.executedBatchId(query))
+ result = ReadResult(query.id, query.runId, samples, elapsedMs,
plan.treeString)
+ } finally {
+ try {
+ if (query != null) query.stop()
+ } finally {
+ spark.streams.removeListener(progress)
+ }
+ }
+ }
+ result
+ }
+
+ private def validateParquet(
+ path: String,
+ topic: String,
+ settings: Settings,
+ scenario: String,
+ rows: Long): Unit = {
+ withSQLConf("spark.gluten.enabled" -> "false") {
+ // Read the root so Spark honors the streaming sink's committed-file
metadata.
+ val actual = spark.read.parquet(path)
+ val expected = project(
+ spark.read.format("kafka").options(readOptions(topic, settings,
scenario)).load(),
+ scenario)
+ require(expected.count() == rows, "Kafka fixture contains missing or
duplicate records")
+ require(actual.count() == rows, s"Expected $rows committed Parquet rows")
+ require(
+ actual.exceptAll(expected).limit(1).count() == 0 &&
+ expected.exceptAll(actual).limit(1).count() == 0,
+ "Kafka values or metadata differ from Spark's reference read"
+ )
+ }
+ }
+
+ private def label(enabled: Boolean, scenario: String): String = {
+ if (!enabled) "Spark"
+ else if (scenario == "headers") "Gluten / Spark scan fallback" else
"Gluten"
+ }
+
+ private def report(benchmark: Benchmark, name: String, result: ReadResult,
rows: Long): Unit = {
+ val statistics = KafkaBenchmarkResult.statistics(result.samples, rows,
result.elapsedMs)
+ benchmark.out.println(
+ f"$name%s: ${result.samples.size}%d completed batches, $rows%d validated
rows, " +
+ f"wallMs=${result.elapsedMs}%.2f,
rows/s=${statistics.rowsPerSecond}%.2f, " +
+ f"meanBatchMs=${statistics.meanBatchMs}%.2f,
p95BatchMs=${statistics.p95BatchMs}%d")
+ benchmark.out.println(result.plan)
+ }
+
+ private def benchmarkRead(admin: AdminClient, settings: Settings, scenario:
String): Unit = {
+ val skipped = if (scenario == "projection") settings.partitions.toLong
else 0L
+ // Validate actual fields on a small fixture before timing the larger noop
workload.
+ val validationRows = math.min(settings.rows, math.max(128L, 2L *
settings.partitions))
+ withTopic(admin, settings) {
+ topic =>
+ produce(topic, settings, 0, validationRows)
+ settings.engines.foreach {
+ enabled =>
+ withTempPath {
+ dir =>
+ val data = new File(dir, "data").getCanonicalPath
+ runRead(
+ topic,
+ settings,
+ scenario,
+ enabled,
+ new File(dir, "checkpoint").getCanonicalPath,
+ Some(data))
+ validateParquet(data, topic, settings, scenario,
validationRows - skipped)
+ }
+ }
+ }
+ withTopic(admin, settings) {
+ topic =>
+ produce(topic, settings, 0, settings.rows)
+ val rows = settings.rows - skipped
+ val benchmark = new Benchmark(s"Kafka integration / $scenario read",
rows, output = output)
+ settings.engines.foreach {
+ enabled =>
+ val name = label(enabled, scenario)
+ benchmark.addTimerCase(name, settings.iterations) {
+ timer =>
+ withTempPath {
+ checkpoint =>
+ val result = runRead(
+ topic,
+ settings,
+ scenario,
+ enabled,
+ checkpoint.getCanonicalPath,
+ None,
+ Some(timer))
+ KafkaBenchmarkResult.validatedRowCount(result.samples,
rows)
+ if (timer.iteration == 0) report(benchmark, name, result,
rows)
+ }
+ }
+ }
+ benchmark.run()
+ }
+ }
+
+ private def benchmarkCheckpoint(admin: AdminClient, settings: Settings):
Unit = {
+ val benchmark =
+ new Benchmark("Kafka integration / checkpoint resume", settings.rows,
output = output)
+ settings.engines.foreach {
+ enabled =>
+ val name = label(enabled, "checkpoint")
+ benchmark.addTimerCase(name, settings.iterations) {
+ timer =>
+ withTopic(admin, settings) {
+ topic =>
+ withTempPath {
+ dir =>
+ val data = new File(dir, "data").getCanonicalPath
+ val checkpoint = new File(dir,
"checkpoint").getCanonicalPath
+ produce(topic, settings, 0, settings.rows)
+ val first = runRead(topic, settings, "scan", enabled,
checkpoint, Some(data))
+ validateParquet(data, topic, settings, "scan",
settings.rows)
+ produce(topic, settings, settings.rows, settings.rows)
+ val resumed = runRead(
+ topic,
+ settings,
+ "scan",
+ enabled,
+ checkpoint,
+ Some(data),
+ Some(timer),
+ firstBatchId = first.samples.last.batchId + 1)
+ require(
+ first.queryId == resumed.queryId && first.runId !=
resumed.runId,
+ "Expected a new run of the same checkpointed query")
+ validateParquet(data, topic, settings, "scan", 2 *
settings.rows)
+ if (timer.iteration == 0) report(benchmark, name, resumed,
settings.rows)
+ }
+ }
+ }
+ }
+ benchmark.run()
+ }
+
+ private def benchmarkPipeline(admin: AdminClient, settings: Settings): Unit
= {
+ val benchmark =
+ new Benchmark("Kafka integration / producer to Parquet", settings.rows,
output = output)
+ settings.engines.foreach {
+ enabled =>
+ val name = label(enabled, "pipeline")
+ benchmark.addTimerCase(name, settings.iterations) {
+ timer =>
+ withTopic(admin, settings) {
+ topic =>
+ withTempPath {
+ dir =>
+ val data = new File(dir, "data").getCanonicalPath
+ // Produce before AvailableNow snapshots offsets. Both
operations are timed.
+ val result = runRead(
+ topic,
+ settings,
+ "scan",
+ enabled,
+ new File(dir, "checkpoint").getCanonicalPath,
+ Some(data),
+ Some(timer),
+ () => produce(topic, settings, 0, settings.rows))
+ validateParquet(data, topic, settings, "scan",
settings.rows)
+ if (timer.iteration == 0) report(benchmark, name, result,
settings.rows)
+ }
+ }
+ }
+ }
+ benchmark.run()
+ }
+}
+
+private[spark] case class KafkaBenchmarkSample(
+ batchId: Long,
+ sourceRows: Long,
+ sinkRows: Long,
+ durationMs: Long = -1L)
+
+private[spark] case class KafkaBenchmarkStatistics(
+ rowsPerSecond: Double,
+ meanBatchMs: Double,
+ p95BatchMs: Long)
+
+private[spark] object KafkaBenchmarkResult {
+ def statistics(
+ samples: Seq[KafkaBenchmarkSample],
+ validatedRows: Long,
+ elapsedMs: Double): KafkaBenchmarkStatistics = {
+ require(validatedRows > 0, "Validated row count must be positive")
+ require(
+ elapsedMs > 0 && !elapsedMs.isNaN && !elapsedMs.isInfinity,
+ "Elapsed time must be positive and finite")
+ require(samples.nonEmpty, "No completed micro-batches were observed")
+ require(samples.forall(_.durationMs >= 0), "Batch durations are
unavailable or negative")
+ val durations = samples.map(_.durationMs).sorted
+ KafkaBenchmarkStatistics(
+ validatedRows * 1000.0 / elapsedMs,
+ durations.map(_.toDouble).sum / durations.size,
+ durations(math.ceil(durations.size * 0.95).toInt - 1))
+ }
+
+ def validateBatchSequence(
+ samples: Seq[KafkaBenchmarkSample],
+ expectedFirstBatchId: Long,
+ expectedLastBatchId: Long): Unit = {
+ require(
+ expectedFirstBatchId >= 0 && expectedLastBatchId >= expectedFirstBatchId,
+ "Expected batch IDs must be nonnegative and ordered")
+ require(samples.nonEmpty, "No completed micro-batches were observed")
+ require(
+ samples.zipWithIndex.forall {
+ case (sample, index) => sample.batchId == expectedFirstBatchId +
index.toLong
+ } && samples.last.batchId == expectedLastBatchId,
+ "Micro-batch progress is incomplete or duplicated"
+ )
+ }
+
+ def validatedRowCount(samples: Seq[KafkaBenchmarkSample], expectedRows:
Long): Long = {
+ require(expectedRows > 0, "Expected row count must be positive")
+ require(samples.nonEmpty, "No completed micro-batches were observed")
+ validateBatchSequence(samples, 0L, samples.last.batchId)
+ require(samples.forall(_.sinkRows >= 0), "Sink row counts are unavailable")
+ // Spark's V2 source metrics recognize MicroBatchScanExec, not Gluten's
replacement node.
+ val rows = samples.map(_.sinkRows).sum
+ require(rows == expectedRows, s"Expected $expectedRows sink rows, observed
$rows")
+ rows
+ }
+
+ def validateScanCounts(nativeScans: Int, sparkScans: Int, nativeExpected:
Boolean): Unit = {
+ require(
+ nativeScans == (if (nativeExpected) 1 else 0) &&
+ sparkScans == (if (nativeExpected) 0 else 1),
+ "Unexpected Kafka scan implementation")
+ }
+}
+
+private class KafkaBenchmarkProgress(name: String) extends
StreamingQueryListener {
+ private val samples = new ConcurrentLinkedQueue[KafkaBenchmarkSample]()
+ private val terminated = new CountDownLatch(1)
+ @volatile private var runId: UUID = _
+
+ override def onQueryStarted(event:
StreamingQueryListener.QueryStartedEvent): Unit = {
+ if (event.name == name) runId = event.runId
+ }
+
+ override def onQueryProgress(event:
StreamingQueryListener.QueryProgressEvent): Unit = {
+ val progress = event.progress
+ // Idle notifications do not execute a batch and may reuse its ID.
+ if (progress.runId == runId &&
progress.durationMs.containsKey("addBatch")) {
+ samples.add(
+ KafkaBenchmarkSample(
+ progress.batchId,
+ progress.numInputRows,
+ progress.sink.numOutputRows,
+ progress.batchDuration))
+ }
+ }
+
+ override def onQueryTerminated(event:
StreamingQueryListener.QueryTerminatedEvent): Unit = {
+ if (event.runId == runId) terminated.countDown()
+ }
+
+ def awaitSamples(timeoutMs: Long): Seq[KafkaBenchmarkSample] = {
+ require(
+ terminated.await(timeoutMs, TimeUnit.MILLISECONDS),
+ "Timed out waiting for query progress")
+ samples.iterator().asScala.toVector
+ }
+}
diff --git
a/backends-velox/src-kafka/test/scala/org/apache/spark/sql/execution/benchmark/RateMicroBatchBenchmark.scala
b/backends-velox/src-kafka/test/scala/org/apache/spark/sql/execution/benchmark/RateMicroBatchBenchmark.scala
new file mode 100644
index 0000000000..9a40275e9f
--- /dev/null
+++
b/backends-velox/src-kafka/test/scala/org/apache/spark/sql/execution/benchmark/RateMicroBatchBenchmark.scala
@@ -0,0 +1,315 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.spark.sql.execution.benchmark
+
+import org.apache.gluten.execution.{MicroBatchScanExecTransformer,
OffloadKafkaScan, ProjectExecTransformerBase, RowToColumnarExecBase}
+import org.apache.gluten.execution.kafka.KafkaTestUtils
+
+import org.apache.spark.SparkConf
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.execution.{ProjectExec, SparkPlan}
+import org.apache.spark.sql.execution.datasources.v2.MicroBatchScanExec
+import org.apache.spark.sql.streaming.{StreamingQuery, StreamingQueryListener,
StreamingQueryProgress, Trigger}
+
+import org.apache.kafka.clients.admin.{AdminClient, AdminClientConfig,
NewTopic}
+
+import java.io.File
+import java.nio.charset.StandardCharsets.UTF_8
+import java.time.{Duration, Instant}
+import java.util.{Collections, Properties, UUID}
+import java.util.concurrent.{ConcurrentLinkedQueue, CountDownLatch, TimeUnit}
+
+import scala.collection.JavaConverters._
+
+/**
+ * A bounded rate -> Kafka -> console pipeline. The producer always uses
Spark; the consumer
+ * compares Spark, a Spark Kafka scan feeding Gluten operators, and a native
Gluten Kafka scan.
+ * Console rendering is included in the measured micro-batch duration.
+ */
+object RateMicroBatchBenchmark extends SqlBasedBenchmark {
+ private def prefix: String = "spark.gluten.benchmark.rate."
+
+ override def getSparkSession: SparkSession = {
+ val conf = new SparkConf()
+ .setAppName("RateMicroBatchBenchmark")
+ .setIfMissing("spark.master", "local[4]")
+ .setIfMissing("spark.sql.adaptive.enabled", "false")
+ .setIfMissing("spark.sql.streaming.stopTimeout", "10000")
+ if (conf.get(prefix + "engine", "spark") != "spark") {
+ conf
+ .setIfMissing("spark.plugins", "org.apache.gluten.GlutenPlugin")
+ .setIfMissing(
+ "spark.shuffle.manager",
+ "org.apache.spark.shuffle.sort.ColumnarShuffleManager")
+ .setIfMissing("spark.memory.offHeap.enabled", "true")
+ .setIfMissing("spark.memory.offHeap.size", "1g")
+ }
+ SparkSession.builder().config(conf).getOrCreate()
+ }
+
+ override def runBenchmarkSuite(mainArgs: Array[String]): Unit = {
+ val conf = spark.sparkContext.getConf
+ val broker = conf.get(
+ prefix + "bootstrapServers",
+ sys.env.getOrElse("KAFKA_BOOTSTRAP_SERVERS", "localhost:9092"))
+ val rowsPerSecond = conf.getLong(prefix + "rowsPerSecond", 10L)
+ val partitions = conf.getInt(prefix + "partitions", 2)
+ val triggerMs = conf.getLong(prefix + "triggerMs", 0L)
+ val warmupMs = conf.getLong(prefix + "warmupMs", 5000L)
+ val durationMs = conf.getLong(prefix + "durationMs", 10000L)
+ val timeoutMs = conf.getLong(prefix + "timeoutMs", 60000L)
+ val iterations = conf.getInt(prefix + "iterations", 3)
+ val engine = conf.get(prefix + "engine", "spark")
+ val engines = engine match {
+ case "all" => Seq("spark", "hybrid", "gluten")
+ case "both" => Seq("spark", "gluten")
+ case "spark" | "hybrid" | "gluten" => Seq(engine)
+ case _ =>
+ throw new IllegalArgumentException("Engine must be spark, hybrid,
gluten, both or all")
+ }
+ require(rowsPerSecond > 0 && partitions > 0, "Rate and partition count
must be positive")
+ require(triggerMs >= 0 && warmupMs >= 0, "Trigger and warm-up must be
nonnegative")
+ require(durationMs > triggerMs, "Measurement duration must exceed the
trigger interval")
+ require(timeoutMs > 0 && iterations > 0, "Timeout and iteration count must
be positive")
+ var nativeProjectionSignature: Option[Seq[Seq[String]]] = None
+
+ val properties = new Properties()
+ properties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, broker)
+ properties.put(AdminClientConfig.DEFAULT_API_TIMEOUT_MS_CONFIG,
timeoutMs.toString)
+ properties.put(
+ AdminClientConfig.REQUEST_TIMEOUT_MS_CONFIG,
+ math.min(timeoutMs, 30000L).toString)
+ val admin = AdminClient.create(properties)
+ try {
+ runBenchmark("Rate -> Kafka -> console") {
+ outputLine(
+ s"source=rate transport=kafka broker=$broker sink=console
rowsPerSecond=$rowsPerSecond partitions=$partitions " +
+ s"triggerMs=$triggerMs warmupMs=$warmupMs durationMs=$durationMs
iterations=$iterations")
+
outputLine("engine\titeration\trows\trows/s\tbatches\twindowMs\tmeanBatchMs\tp95BatchMs")
+ engines.foreach {
+ mode =>
+ (1 to iterations).foreach {
+ iteration =>
+ withSQLConf(
+ "spark.gluten.enabled" -> (mode != "spark").toString,
+ OffloadKafkaScan.ENABLED.key -> (mode == "gluten").toString,
+ "spark.sql.json.enablePartialResults" -> "true",
+ "spark.sql.caseSensitive" -> "false"
+ ) {
+ withTempPath {
+ checkpoint =>
+ val name = "rate_benchmark_" +
UUID.randomUUID().toString.replace("-", "")
+ val topic = name
+ admin.createTopics(Collections.singletonList(
+ new NewTopic(topic, partitions, 1.toShort))).all()
+ .get(timeoutMs, TimeUnit.MILLISECONDS)
+ val producerSession = spark.newSession()
+ producerSession.conf.set("spark.gluten.enabled", "false")
+ val listener = new RateBenchmarkProgress(name)
+ spark.streams.addListener(listener)
+ var query: StreamingQuery = null
+ var producer: StreamingQuery = null
+ try {
+ producer = producerSession.readStream
+ .format("rate")
+ .option("rowsPerSecond", rowsPerSecond)
+ .option("numPartitions", partitions)
+ .load()
+ .selectExpr(
+ "CAST(value AS STRING) AS key",
+ "to_json(struct(timestamp, value)) AS value")
+ .writeStream
+ .format("kafka")
+ .option("kafka.bootstrap.servers", broker)
+ .option("topic", topic)
+ .option(
+ "checkpointLocation",
+ new File(checkpoint, "producer").getCanonicalPath)
+ .trigger(Trigger.ProcessingTime(triggerMs))
+ .start()
+ query = spark.readStream
+ .format("kafka")
+ .option("kafka.bootstrap.servers", broker)
+ .option("subscribe", topic)
+ .option("startingOffsets", "earliest")
+ .option("failOnDataLoss", "true")
+ .load()
+ .selectExpr(
+ "from_json(CAST(value AS STRING), " +
+ "'timestamp STRING, value BIGINT') AS record")
+ .selectExpr(
+ "CAST(record.timestamp AS TIMESTAMP) AS timestamp",
+ "record.value AS value")
+ .writeStream
+ .format("console")
+ .outputMode("append")
+ .queryName(name)
+ .option(
+ "checkpointLocation",
+ new File(checkpoint, "consumer").getCanonicalPath)
+ .trigger(Trigger.ProcessingTime(triggerMs))
+ .start()
+ if (warmupMs > 0) {
+ require(
+ !query.awaitTermination(warmupMs),
+ "Rate query terminated during warm-up")
+ }
+ val startMs = System.currentTimeMillis()
+ val startNanos = System.nanoTime()
+ require(
+ !query.awaitTermination(durationMs),
+ "Rate query terminated during measurement")
+ val elapsedMs = (System.nanoTime() - startNanos) / 1e6
+ val endMs = System.currentTimeMillis()
+ require(producer.isActive, "Rate-to-Kafka producer
terminated")
+ producer.exception.foreach(e => throw e)
+ producer.stop()
+ query.stop()
+ val samples = listener.awaitSamples(timeoutMs)
+ query.exception.foreach(e => throw e)
+ val result = RateMicroBatchBenchmarkResult.summarize(
+ samples,
+ startMs,
+ endMs,
+ elapsedMs)
+ val plan = KafkaTestUtils.executedPlan(query)
+ val label = mode match {
+ case "spark" => "Spark"
+ case "hybrid" => "Gluten (Spark Kafka scan + R2C)"
+ case "gluten" => "Gluten (native Kafka scan)"
+ }
+ outputLine(s"PLAN engine=$mode
iteration=$iteration\n${plan.treeString}")
+ val projections = validatePlan(mode, plan)
+ if (mode != "spark") {
+ nativeProjectionSignature.foreach {
+ expected =>
+ require(
+ projections == expected,
+ "Native downstream projections differ between
runs; " +
+ "do not compare these timings")
+ }
+ nativeProjectionSignature = Some(projections)
+ }
+ // These task-aggregated metrics describe only the
last executed batch.
+ // They are not full-window totals or wall-clock
latency.
+ val conversions = plan.collect { case p:
RowToColumnarExecBase => p }
+ outputLine(
+ s"LAST_BATCH engine=$mode iteration=$iteration " +
+ s"batchId=${KafkaTestUtils.executedBatchId(query)}
" +
+
s"r2cRows=${conversions.map(_.metrics("numInputRows").value).sum} " +
+
s"r2cTaskTimeMs=${conversions.map(_.metrics("convertTime").value).sum}")
+ outputLine(
+
f"$label%s\t$iteration%d\t${result.rows}%d\t${result.rowsPerSecond}%.2f\t" +
+ f"${result.batches}%d\t${result.elapsedMs}%.2f\t" +
+
f"${result.meanBatchMs}%.2f\t${result.p95BatchMs}%d")
+ } finally {
+ try {
+ if (query != null && query.isActive) query.stop()
+ } finally {
+ try {
+ if (producer != null) producer.stop()
+ } finally {
+ spark.streams.removeListener(listener)
+
admin.deleteTopics(Collections.singletonList(topic)).all()
+ .get(timeoutMs, TimeUnit.MILLISECONDS)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ } finally {
+ admin.close(Duration.ofSeconds(5))
+ }
+ }
+
+ private def validatePlan(mode: String, plan: SparkPlan): Seq[Seq[String]] = {
+ val nativeScans = plan.collect { case p: MicroBatchScanExecTransformer =>
p }
+ val sparkScans = plan.collect { case p: MicroBatchScanExec => p }
+ KafkaBenchmarkResult.validateScanCounts(nativeScans.size, sparkScans.size,
mode == "gluten")
+ val projects = plan.collect { case p: ProjectExecTransformerBase => p }
+ val conversions = plan.collect { case p: RowToColumnarExecBase => p }
+ if (mode == "spark") {
+ require(
+ projects.isEmpty && conversions.isEmpty,
+ "Spark baseline unexpectedly contains native projections or R2C")
+ } else {
+ require(
+ projects.nonEmpty && !plan.exists(_.isInstanceOf[ProjectExec]),
+ "Expected all downstream projections, including JSON decoding, to run
natively")
+ if (mode == "hybrid") {
+ require(
+ conversions.size == 1 && projects.exists {
+ _.exists {
+ case conversion: RowToColumnarExecBase =>
+ conversion.child.exists(_.isInstanceOf[MicroBatchScanExec])
+ case _ => false
+ }
+ },
+ "Hybrid plan must contain Spark Kafka scan -> R2C -> native
projection"
+ )
+ } else {
+ require(conversions.isEmpty, "Native Kafka pipeline unexpectedly
contains R2C")
+ }
+ }
+ // SQL rendering omits query-specific expression IDs while retaining the
projection expressions.
+ projects.map(_.list.map(_.sql))
+ }
+
+ private def outputLine(line: String): Unit = {
+ val out = output.getOrElse(System.out)
+ out.write((line + System.lineSeparator()).getBytes(UTF_8))
+ out.flush()
+ }
+}
+
+private class RateBenchmarkProgress(name: String) extends
StreamingQueryListener {
+ private val progress = new ConcurrentLinkedQueue[StreamingQueryProgress]()
+ private val terminated = new CountDownLatch(1)
+ @volatile private var runId: UUID = _
+
+ override def onQueryStarted(event:
StreamingQueryListener.QueryStartedEvent): Unit = {
+ if (event.name == name) runId = event.runId
+ }
+
+ override def onQueryProgress(event:
StreamingQueryListener.QueryProgressEvent): Unit = {
+ // Idle progress events can repeat a batch ID. Only addBatch represents an
executed micro-batch.
+ if (event.progress.runId == runId &&
event.progress.durationMs.containsKey("addBatch")) {
+ progress.add(event.progress)
+ }
+ }
+
+ override def onQueryTerminated(event:
StreamingQueryListener.QueryTerminatedEvent): Unit = {
+ if (event.runId == runId) terminated.countDown()
+ }
+
+ def awaitSamples(timeoutMs: Long): Seq[RateMicroBatchSample] = {
+ require(
+ terminated.await(timeoutMs, TimeUnit.MILLISECONDS),
+ "Timed out waiting for rate progress")
+ progress.iterator().asScala.map {
+ sample =>
+ RateMicroBatchSample(
+ sample.batchId,
+ Instant.parse(sample.timestamp).toEpochMilli,
+ sample.batchDuration,
+ sample.sink.numOutputRows)
+ }.toVector
+ }
+}
diff --git
a/backends-velox/src/test/scala/org/apache/spark/sql/execution/benchmark/RateMicroBatchBenchmarkResult.scala
b/backends-velox/src/test/scala/org/apache/spark/sql/execution/benchmark/RateMicroBatchBenchmarkResult.scala
new file mode 100644
index 0000000000..81a65df077
--- /dev/null
+++
b/backends-velox/src/test/scala/org/apache/spark/sql/execution/benchmark/RateMicroBatchBenchmarkResult.scala
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.spark.sql.execution.benchmark
+
+private[spark] case class RateMicroBatchSample(
+ batchId: Long,
+ startedAtMs: Long,
+ durationMs: Long,
+ rows: Long)
+
+private[spark] case class RateMicroBatchBenchmarkResult(
+ rows: Long,
+ batches: Int,
+ elapsedMs: Double,
+ rowsPerSecond: Double,
+ meanBatchMs: Double,
+ p95BatchMs: Long)
+
+private[spark] object RateMicroBatchBenchmarkResult {
+ def summarize(
+ samples: Seq[RateMicroBatchSample],
+ startMs: Long,
+ endMs: Long,
+ elapsedMs: Double): RateMicroBatchBenchmarkResult = {
+ require(endMs > startMs, "The measurement window must have positive
duration")
+ require(
+ elapsedMs > 0 && !elapsedMs.isInfinity && !elapsedMs.isNaN,
+ "Elapsed time must be positive and finite")
+ require(
+ samples.forall(s => s.batchId >= 0 && s.durationMs >= 0 && s.rows >= 0),
+ "Batch IDs, durations and sink row counts must be nonnegative")
+
+ // Exclude warm-up and batches crossing either boundary. Never prorate a
batch's rows.
+ val measured = samples.filter {
+ sample =>
+ sample.startedAtMs >= startMs && sample.startedAtMs < endMs &&
+ sample.durationMs <= endMs - sample.startedAtMs
+ }
+ require(measured.nonEmpty, "No complete measured batches; increase the
measurement duration")
+ require(
+ measured.map(_.batchId).sliding(2).forall(ids => ids.size < 2 || ids(1)
== ids(0) + 1),
+ "Measured batch progress is missing, duplicated or reordered")
+ val rows = measured.foldLeft(0L)((sum, sample) => Math.addExact(sum,
sample.rows))
+ require(rows > 0, "No measured rows; increase the rate or measurement
duration")
+ val durations = measured.map(_.durationMs).sorted
+ RateMicroBatchBenchmarkResult(
+ rows,
+ measured.size,
+ elapsedMs,
+ rows * 1000.0 / elapsedMs,
+ durations.map(_.toDouble).sum / durations.size,
+ durations(math.ceil(durations.size * 0.95).toInt - 1))
+ }
+}
diff --git
a/gluten-kafka/src/main/scala/org/apache/gluten/execution/OffloadKafkaScan.scala
b/gluten-kafka/src/main/scala/org/apache/gluten/execution/OffloadKafkaScan.scala
index 445ddce769..4ae0f4b51d 100644
---
a/gluten-kafka/src/main/scala/org/apache/gluten/execution/OffloadKafkaScan.scala
+++
b/gluten-kafka/src/main/scala/org/apache/gluten/execution/OffloadKafkaScan.scala
@@ -16,7 +16,7 @@
*/
package org.apache.gluten.execution
-import org.apache.gluten.config.GlutenConfig
+import org.apache.gluten.config.{ConfigEntry, ConfigRegistry, GlutenConfig}
import org.apache.gluten.extension.columnar.heuristic.HeuristicTransform
import org.apache.gluten.extension.columnar.offload.OffloadSingleNode
import org.apache.gluten.extension.columnar.validator.Validators
@@ -24,23 +24,37 @@ import org.apache.gluten.extension.injector.Injector
import org.apache.spark.sql.execution.SparkPlan
import org.apache.spark.sql.execution.datasources.v2.MicroBatchScanExec
+import org.apache.spark.sql.internal.SQLConf
-case class OffloadKafkaScan() extends OffloadSingleNode {
+case class OffloadKafkaScan(enabled: Boolean =
+ OffloadKafkaScan.get.getConf(OffloadKafkaScan.ENABLED))
+ extends OffloadSingleNode {
override def offload(plan: SparkPlan): SparkPlan = plan match {
- case scan: MicroBatchScanExec if
MicroBatchScanExecTransformer.supportsBatchScan(scan.scan) =>
+ case scan: MicroBatchScanExec
+ if enabled &&
MicroBatchScanExecTransformer.supportsBatchScan(scan.scan) =>
MicroBatchScanExecTransformer(scan)
case other => other
}
}
-object OffloadKafkaScan {
+object OffloadKafkaScan extends ConfigRegistry {
+ override def get: GlutenConfig = new GlutenConfig(SQLConf.get)
+
+ val ENABLED: ConfigEntry[Boolean] =
+ buildConf("spark.gluten.sql.columnar.kafkaScan")
+ .doc("Enable native Kafka micro-batch scans. When disabled, Kafka scans
use Spark while " +
+ "downstream operators remain eligible for native execution.")
+ .booleanConf
+ .createWithDefault(true)
+
def inject(injector: Injector): Unit = {
// Inject legacy rule.
injector.gluten.legacy.injectTransform {
c =>
- val offload = Seq(OffloadKafkaScan())
+ val conf = new GlutenConfig(c.sqlConf)
+ val offload = Seq(OffloadKafkaScan(conf.getConf(ENABLED)))
HeuristicTransform.Simple(
- Validators.newValidator(new GlutenConfig(c.sqlConf), offload),
+ Validators.newValidator(conf, offload),
offload
)
}
diff --git
a/gluten-kafka/src/test/scala/org/apache/gluten/execution/kafka/KafkaTestUtils.scala
b/gluten-kafka/src/test/scala/org/apache/gluten/execution/kafka/KafkaTestUtils.scala
new file mode 100644
index 0000000000..1ed62be1a9
--- /dev/null
+++
b/gluten-kafka/src/test/scala/org/apache/gluten/execution/kafka/KafkaTestUtils.scala
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.gluten.execution.kafka
+
+import org.apache.spark.sql.execution.{QueryExecution, SparkPlan}
+import org.apache.spark.sql.streaming.StreamingQuery
+
+object KafkaTestUtils {
+ def executedPlan(query: StreamingQuery): SparkPlan =
lastExecution(query).executedPlan
+
+ def executedBatchId(query: StreamingQuery): Long = {
+ val execution = lastExecution(query)
+ execution.getClass.getMethod("currentBatchId").invoke(execution)
+ .asInstanceOf[java.lang.Long].longValue()
+ }
+
+ private def lastExecution(query: StreamingQuery): QueryExecution = {
+ // Spark 4.1 moved StreamingQueryWrapper into execution.streaming.runtime.
Its accessor methods
+ // remain unchanged, so reflection keeps this test helper independent of
the wrapper's package.
+ val stream = query.getClass.getMethod("streamingQuery").invoke(query)
+ val execution = stream.getClass.getMethod("lastExecution").invoke(stream)
+ .asInstanceOf[QueryExecution]
+ require(execution != null, "The streaming query has not executed a
micro-batch")
+ execution
+ }
+}
diff --git a/gluten-ut/spark35/pom.xml b/gluten-ut/spark35/pom.xml
index 2bb8e7db0c..b25fcce340 100644
--- a/gluten-ut/spark35/pom.xml
+++ b/gluten-ut/spark35/pom.xml
@@ -122,6 +122,84 @@
</dependency>
</dependencies>
</profile>
+ <profile>
+ <id>kafka</id>
+ <properties>
+ <!-- Match the broker used by Spark 3.5.5's Kafka test suites. -->
+ <kafka.test.version>3.4.1</kafka.test.version>
+ </properties>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.gluten</groupId>
+ <artifactId>gluten-kafka</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.spark</groupId>
+ <artifactId>spark-sql-kafka-0-10_${scala.binary.version}</artifactId>
+ <version>${spark.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.spark</groupId>
+ <artifactId>spark-sql-kafka-0-10_${scala.binary.version}</artifactId>
+ <version>${spark.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.spark</groupId>
+
<artifactId>spark-token-provider-kafka-0-10_${scala.binary.version}</artifactId>
+ <version>${spark.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.kafka</groupId>
+ <artifactId>kafka_${scala.binary.version}</artifactId>
+ <version>${kafka.test.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-minikdc</artifactId>
+ <version>${hadoop.version}</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-dependency-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>unpack-spark-kafka-test-resources</id>
+ <goals>
+ <goal>unpack</goal>
+ </goals>
+ <phase>process-test-resources</phase>
+ <configuration>
+ <!-- Spark opens these fixtures as Files, not jar: URLs. -->
+ <artifactItems>
+ <artifactItem>
+ <groupId>org.apache.spark</groupId>
+
<artifactId>spark-sql-kafka-0-10_${scala.binary.version}</artifactId>
+ <version>${spark.version}</version>
+ <classifier>tests</classifier>
+ <type>jar</type>
+
<includes>kafka-source-initial-offset-*.bin,structured-streaming/**</includes>
+
<outputDirectory>${project.build.testOutputDirectory}</outputDirectory>
+ </artifactItem>
+ </artifactItems>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
<profile>
<id>backends-clickhouse</id>
<activation>
diff --git
a/gluten-ut/spark35/src-kafka/test/scala/org/apache/spark/sql/kafka010/GlutenKafkaHybridSourceSuite.scala
b/gluten-ut/spark35/src-kafka/test/scala/org/apache/spark/sql/kafka010/GlutenKafkaHybridSourceSuite.scala
new file mode 100644
index 0000000000..912c353f31
--- /dev/null
+++
b/gluten-ut/spark35/src-kafka/test/scala/org/apache/spark/sql/kafka010/GlutenKafkaHybridSourceSuite.scala
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.spark.sql.kafka010
+
+import org.apache.gluten.execution.{MicroBatchScanExecTransformer,
ProjectExecTransformerBase, RowToColumnarExecBase}
+
+import org.apache.spark.sql.GlutenSQLTestsTrait
+import org.apache.spark.sql.execution.ProjectExec
+import org.apache.spark.sql.execution.datasources.v2.MicroBatchScanExec
+
+class GlutenKafkaHybridSourceSuite extends KafkaSourceTest with
GlutenSQLTestsTrait {
+ import testImplicits._
+
+ testGluten("Kafka scan fallback preserves native projection and restores
native scanning") {
+ val scanEnabled = "spark.gluten.sql.columnar.kafkaScan"
+ val topic = newTopic()
+ testUtils.createTopic(topic, partitions = 2)
+ val values = 0L until 12L
+ testUtils.sendMessages(topic, values.map(_.toString).toArray)
+ var expectedProjects: Option[Seq[Seq[String]]] = None
+
+ def checkScan(nativeScan: Boolean): Unit = {
+ val input = spark.readStream
+ .format("kafka")
+ .option("kafka.bootstrap.servers", testUtils.brokerAddress)
+ .option("subscribe", topic)
+ .option("startingOffsets", "earliest")
+ .load()
+ .selectExpr("CAST(CAST(value AS STRING) AS BIGINT) + 1 AS value")
+
+ testStream(input)(
+ makeSureGetOffsetCalled,
+ CheckAnswer(values.map(_ + 1L): _*),
+ AssertOnQuery {
+ query =>
+ val plan = query.lastExecution.executedPlan
+ withClue(plan.treeString) {
+ val nativeScans = plan.collect { case scan:
MicroBatchScanExecTransformer => scan }
+ val sparkScans = plan.collect { case scan: MicroBatchScanExec =>
scan }
+ val projects = plan.collect { case project:
ProjectExecTransformerBase => project }
+ val conversions = plan.collect { case r2c: RowToColumnarExecBase
=> r2c }
+ assert(nativeScans.size == (if (nativeScan) 1 else 0))
+ assert(sparkScans.size == (if (nativeScan) 0 else 1))
+ assert(projects.nonEmpty, "The projection must remain native in
both modes")
+ assert(!plan.exists(_.isInstanceOf[ProjectExec]))
+ if (nativeScan) {
+ assert(conversions.isEmpty)
+ } else {
+ assert(conversions.size == 1)
+
assert(conversions.head.child.exists(_.isInstanceOf[MicroBatchScanExec]))
+
assert(projects.exists(_.child.exists(_.isInstanceOf[RowToColumnarExecBase])))
+ }
+ val projectExpressions = projects.map(_.list.map(_.sql))
+ expectedProjects match {
+ case Some(expected) => assert(projectExpressions == expected)
+ case None => expectedProjects = Some(projectExpressions)
+ }
+ }
+ true
+ }
+ )
+ }
+
+ withSQLConf("spark.gluten.enabled" -> "true", scanEnabled -> "true") {
+ checkScan(nativeScan = true)
+ withSQLConf(scanEnabled -> "false") {
+ checkScan(nativeScan = false)
+ }
+ assert(spark.conf.get(scanEnabled) == "true")
+ checkScan(nativeScan = true)
+ }
+ }
+}
diff --git
a/gluten-ut/spark35/src-kafka/test/scala/org/apache/spark/sql/kafka010/GlutenKafkaMicroBatchV2SourceSuite.scala
b/gluten-ut/spark35/src-kafka/test/scala/org/apache/spark/sql/kafka010/GlutenKafkaMicroBatchV2SourceSuite.scala
new file mode 100644
index 0000000000..ac9a3ed6f8
--- /dev/null
+++
b/gluten-ut/spark35/src-kafka/test/scala/org/apache/spark/sql/kafka010/GlutenKafkaMicroBatchV2SourceSuite.scala
@@ -0,0 +1,284 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.spark.sql.kafka010
+
+import org.apache.gluten.execution.MicroBatchScanExecTransformer
+
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.execution.datasources.v2.MicroBatchScanExec
+import org.apache.spark.sql.execution.exchange.ReusedExchangeExec
+import org.apache.spark.sql.execution.streaming.{SerializedOffset,
StreamingQueryWrapper}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.streaming.{StreamingQuery, Trigger}
+
+import org.apache.kafka.common.TopicPartition
+
+import java.io.File
+import java.nio.charset.StandardCharsets.UTF_8
+
+import scala.concurrent.duration._
+
+class GlutenKafkaMicroBatchV2SourceSuite
+ extends KafkaMicroBatchV2SourceSuite
+ with GlutenKafkaSourceTest {
+
+ import testImplicits._
+
+ testGluten("rate rows pass through Kafka to console with a native consumer
scan") {
+ val topic = newTopic()
+ testUtils.createTopic(topic, partitions = 2)
+ withTempDir {
+ dir =>
+ val producerSession = spark.newSession()
+ producerSession.conf.set("spark.gluten.enabled", "false")
+ val producer = producerSession.readStream
+ .format("rate")
+ .option("rowsPerSecond", 10)
+ .option("numPartitions", 2)
+ .load()
+ .selectExpr(
+ "CAST(value AS STRING) AS key",
+ "to_json(struct(timestamp, value)) AS value")
+ .writeStream
+ .format("kafka")
+ .option("kafka.bootstrap.servers", testUtils.brokerAddress)
+ .option("topic", topic)
+ .option("checkpointLocation", new File(dir,
"producer").getCanonicalPath)
+ .start()
+ var consumer: StreamingQuery = null
+ try {
+ val deadline = 60.seconds.fromNow
+ while (!producer.recentProgress.exists(_.numInputRows > 0) &&
deadline.hasTimeLeft()) {
+ assert(!producer.awaitTermination(100), "Rate producer terminated
before sending rows")
+ }
+ assert(producer.recentProgress.exists(_.numInputRows > 0))
+ producer.stop()
+ val expectedRows = testUtils.getLatestOffsets(Set(topic)).values.sum
+ assert(expectedRows > 0)
+ consumer = spark.readStream
+ .format("kafka")
+ .option("kafka.bootstrap.servers", testUtils.brokerAddress)
+ .option("subscribe", topic)
+ .option("startingOffsets", "earliest")
+ .load()
+ .selectExpr(
+ "from_json(CAST(value AS STRING), " +
+ "'timestamp TIMESTAMP, value BIGINT') AS record")
+ .select("record.*")
+ .writeStream
+ .format("console")
+ .outputMode("append")
+ .option("checkpointLocation", new File(dir,
"consumer").getCanonicalPath)
+ .trigger(Trigger.AvailableNow())
+ .start()
+ assert(consumer.awaitTermination(streamingTimeout.toMillis), "Kafka
consumer timed out")
+ assert(consumer.recentProgress.map(_.sink.numOutputRows).sum ==
expectedRows)
+ val execution =
consumer.asInstanceOf[StreamingQueryWrapper].streamingQuery
+ assertKafkaScan(execution, requireScan = true)
+ assert(execution.lastExecution.executedPlan
+ .exists(_.isInstanceOf[MicroBatchScanExecTransformer]))
+ } finally {
+ try {
+ if (consumer != null) consumer.stop()
+ } finally {
+ producer.stop()
+ }
+ }
+ }
+ }
+
+ testGluten("Kafka stream-stream self-join preserves output and a single
source offset") {
+ // Preserve Spark's self-join coverage without its unsupported
StreamingQueryProgress row
+ // counts. Spark 3.5 ProgressReporter does not recognize native
micro-batch scan nodes.
+ Seq(false, true).foreach {
+ reuseExchange =>
+ withSQLConf(SQLConf.EXCHANGE_REUSE_ENABLED.key ->
reuseExchange.toString) {
+ val topic = newTopic()
+ testUtils.createTopic(topic, partitions = 2)
+ require(testUtils.getLatestOffsets(Set(topic)).size == 2)
+
+ val values = spark.readStream
+ .format("kafka")
+ .option("subscribe", topic)
+ .option("kafka.bootstrap.servers", testUtils.brokerAddress)
+ .option("kafka.metadata.max.age.ms", "1")
+ .load()
+ .selectExpr(
+ "CAST(CAST(value AS STRING) AS INT) AS value",
+ "CAST(CAST(value AS STRING) AS INT) % 5 AS key")
+
+ testStream(values.join(values, "key"))(
+ makeSureGetOffsetCalled,
+ AddKafkaData(Set(topic), 1, 2),
+ CheckAnswer((1, 1, 1), (2, 2, 2)),
+ AddKafkaData(Set(topic), 6, 3),
+ CheckAnswer((1, 1, 1), (2, 2, 2), (3, 3, 3), (1, 6, 1), (1, 1, 6),
(1, 6, 6)),
+ AssertOnQuery {
+ query =>
+ assert(query.availableOffsets.iterator.size == 1)
+ val expectedOffset =
query.availableOffsets.iterator.next()._2.json
+ val loggedOffsets = query.offsetLog.getLatest
+ .getOrElse(fail("No Kafka offset log entry found"))
+ ._2.offsets
+ // Spark stores one checkpoint entry per logical source
occurrence. Both sides
+ // of this self-join must record the same offset for the
single shared source.
+ assert(loggedOffsets.size == 2)
+ assert(loggedOffsets.forall(_.exists(_.json ==
expectedOffset)))
+ assertKafkaScan(query, requireScan = true)
+ val plan = query.lastExecution.executedPlan
+
assert(plan.exists(_.isInstanceOf[MicroBatchScanExecTransformer]))
+ val reusedExchanges = plan.collect { case exchange:
ReusedExchangeExec => exchange }
+ assert(reusedExchanges.size == (if (reuseExchange) 1 else 0))
+ true
+ }
+ )
+ }
+ }
+ }
+
+ testGluten("Kafka micro-batches consume records through a native scan") {
+ val topic = newTopic()
+ testUtils.createTopic(topic, partitions = 2)
+ val values = (0 until 12).map(_.toString)
+ testUtils.sendMessages(topic, values.toArray)
+
+ val input = spark.readStream
+ .format("kafka")
+ .option("kafka.bootstrap.servers", testUtils.brokerAddress)
+ .option("subscribe", topic)
+ .option("startingOffsets", "earliest")
+ .load()
+ .selectExpr("CAST(value AS STRING)")
+
+ testStream(input)(
+ // Records were sent before testStream, so CheckAnswer has no AddData
offset to await.
+ makeSureGetOffsetCalled,
+ CheckAnswer(values: _*),
+ AssertOnQuery {
+ query =>
+ assertKafkaScan(query, requireScan = true)
+ assert(
+
query.lastExecution.executedPlan.exists(_.isInstanceOf[MicroBatchScanExecTransformer]))
+ true
+ }
+ )
+ }
+
+ testGluten("Kafka retained headers use Spark fallback and preserve their
values") {
+ val topic = newTopic()
+ testUtils.createTopic(topic, partitions = 1)
+ val headerValue = "header-value".getBytes(UTF_8)
+ testUtils.sendMessage(
+ new RecordBuilder(topic, "value")
+ .headers(Seq("header-key" -> headerValue))
+ .build())
+
+ val input = spark.readStream
+ .format("kafka")
+ .option("kafka.bootstrap.servers", testUtils.brokerAddress)
+ .option("subscribe", topic)
+ .option("startingOffsets", "earliest")
+ .option("includeHeaders", "true")
+ .load()
+ .selectExpr("CAST(value AS STRING)", "headers")
+
+ testStream(input)(
+ // Wait for the preloaded record before checking its value and retained
headers.
+ makeSureGetOffsetCalled,
+ CheckAnswer(Row("value", Seq(Row("header-key", headerValue)))),
+ AssertOnQuery {
+ query =>
+ assertKafkaScan(query, requireScan = true)
+ val plan = query.lastExecution.executedPlan
+ assert(!plan.exists(_.isInstanceOf[MicroBatchScanExecTransformer]))
+ assert(plan.exists {
+ case scan: MicroBatchScanExec =>
+ MicroBatchScanExecTransformer.supportsBatchScan(scan.scan)
+ case _ => false
+ })
+ true
+ }
+ )
+ }
+
+ testGluten("Kafka AvailableNow scans write Parquet and restart from the same
checkpoint") {
+ val topic = newTopic()
+ val topicPartition = new TopicPartition(topic, 0)
+ testUtils.createTopic(topic, partitions = 1)
+
+ withTempDir {
+ dir =>
+ val outputPath = new File(dir, "parquet").getCanonicalPath
+ val checkpointPath = new File(dir, "checkpoint").getCanonicalPath
+ val input = spark.readStream
+ .format("kafka")
+ .option("kafka.bootstrap.servers", testUtils.brokerAddress)
+ .option("subscribe", topic)
+ .option("startingOffsets", "earliest")
+ .option("maxOffsetsPerTrigger", 2)
+ .load()
+ .selectExpr("CAST(value AS STRING)")
+
+ def runAvailableNow(startOffset: Long, endOffset: Long): Unit = {
+ val query = input.writeStream
+ .format("parquet")
+ .outputMode("append")
+ .option("checkpointLocation", checkpointPath)
+ .trigger(Trigger.AvailableNow())
+ .start(outputPath)
+ try {
+ assert(query.awaitTermination(streamingTimeout.toMillis),
"AvailableNow timed out")
+ val execution =
query.asInstanceOf[StreamingQueryWrapper].streamingQuery
+ assertKafkaScan(execution, requireScan = true)
+ assert(
+ execution.lastExecution.executedPlan
+ .exists(_.isInstanceOf[MicroBatchScanExecTransformer]))
+
+ // Offset progress remains meaningful even when Spark cannot count
native scan rows.
+ val batchEnds = query.recentProgress
+ .flatMap(_.sources)
+ .map {
+ source =>
+ KafkaSourceOffset(SerializedOffset(source.endOffset))
+ .partitionToOffsets(topicPartition)
+ }
+ .distinct
+ .toSeq
+ assert(batchEnds.nonEmpty, "AvailableNow reported no Kafka offset
progress")
+ assert(batchEnds.last == endOffset)
+ val batchSizes = (Seq(startOffset) ++ batchEnds).sliding(2).map {
+ offsets => offsets.last - offsets.head
+ }.toSeq
+ assert(batchSizes.forall(size => size >= 0 && size <= 2))
+ assert(batchSizes.count(_ > 0) == (endOffset - startOffset + 1) /
2)
+ } finally {
+ query.stop()
+ }
+ }
+
+ val firstValues = (0 until 7).map(_.toString)
+ testUtils.sendMessages(topic, firstValues.toArray, Some(0))
+ runAvailableNow(startOffset = 0, endOffset = 7)
+ checkAnswer(spark.read.parquet(outputPath), firstValues.map(Row(_)))
+
+ val nextValues = (7 until 12).map(_.toString)
+ testUtils.sendMessages(topic, nextValues.toArray, Some(0))
+ runAvailableNow(startOffset = 7, endOffset = 12)
+ checkAnswer(spark.read.parquet(outputPath), (firstValues ++
nextValues).map(Row(_)))
+ }
+ }
+}
diff --git
a/gluten-ut/spark35/src/test/scala/org/apache/spark/sql/sources/GlutenResolvedDataSourceSuite.scala
b/gluten-ut/spark35/src-kafka/test/scala/org/apache/spark/sql/kafka010/GlutenKafkaSourceStressSuite.scala
similarity index 73%
copy from
gluten-ut/spark35/src/test/scala/org/apache/spark/sql/sources/GlutenResolvedDataSourceSuite.scala
copy to
gluten-ut/spark35/src-kafka/test/scala/org/apache/spark/sql/kafka010/GlutenKafkaSourceStressSuite.scala
index ddd06bb3fd..235d52bcd7 100644
---
a/gluten-ut/spark35/src/test/scala/org/apache/spark/sql/sources/GlutenResolvedDataSourceSuite.scala
+++
b/gluten-ut/spark35/src-kafka/test/scala/org/apache/spark/sql/kafka010/GlutenKafkaSourceStressSuite.scala
@@ -14,8 +14,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.spark.sql.sources
+package org.apache.spark.sql.kafka010
-import org.apache.spark.sql.GlutenSQLTestsBaseTrait
+import org.scalatest.DoNotDiscover
-class GlutenResolvedDataSourceSuite extends ResolvedDataSourceSuite with
GlutenSQLTestsBaseTrait {}
+/**
+ * Run explicitly with -Dsuites. Spark's randomized topic/partition stress
test is deliberately
+ * long.
+ */
+@DoNotDiscover
+class GlutenKafkaSourceStressSuite extends KafkaSourceStressSuite with
GlutenKafkaSourceTest
diff --git
a/gluten-ut/spark35/src-kafka/test/scala/org/apache/spark/sql/kafka010/GlutenKafkaSourceTest.scala
b/gluten-ut/spark35/src-kafka/test/scala/org/apache/spark/sql/kafka010/GlutenKafkaSourceTest.scala
new file mode 100644
index 0000000000..acb8786a7b
--- /dev/null
+++
b/gluten-ut/spark35/src-kafka/test/scala/org/apache/spark/sql/kafka010/GlutenKafkaSourceTest.scala
@@ -0,0 +1,139 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.spark.sql.kafka010
+
+import org.apache.gluten.execution.MicroBatchScanExecTransformer
+
+import org.apache.spark.scheduler.{SparkListener, SparkListenerEvent}
+import org.apache.spark.sql.{Dataset, GlutenSQLTestsTrait}
+import org.apache.spark.sql.execution.SparkPlan
+import org.apache.spark.sql.execution.datasources.v2.MicroBatchScanExec
+import org.apache.spark.sql.execution.streaming.{IncrementalExecution,
StreamExecution}
+import org.apache.spark.sql.execution.ui.SparkListenerSQLExecutionEnd
+import org.apache.spark.sql.streaming.OutputMode
+
+import java.util.concurrent.ConcurrentLinkedQueue
+
+import scala.collection.JavaConverters._
+
+/** Reuse Spark's source tests while checking the physical scan after
successful answer checks. */
+private[kafka010] trait GlutenKafkaSourceTest extends KafkaSourceTest with
GlutenSQLTestsTrait {
+
+ private val completedKafkaPlans = new ConcurrentLinkedQueue[SparkPlan]()
+ private var kafkaScanListener: Option[SparkListener] = None
+
+ override protected def beforeEach(): Unit = {
+ super.beforeEach()
+ completedKafkaPlans.clear()
+ val listener = new SparkListener {
+ override def onOtherEvent(event: SparkListenerEvent): Unit = event match
{
+ case end: SparkListenerSQLExecutionEnd if end.executionFailure.isEmpty
=>
+ end.qe match {
+ case execution: IncrementalExecution =>
+ completedKafkaPlans.add(execution.executedPlan)
+ case _ =>
+ }
+ case _ =>
+ }
+ }
+ spark.sparkContext.addSparkListener(listener)
+ kafkaScanListener = Some(listener)
+ }
+
+ override protected def afterEach(): Unit = {
+ try {
+ // Some inherited tests start queries directly instead of using
testStream. Observe every
+ // successful micro-batch, including stopped queries and Kafka sink
writes. A query execution
+ // listener would miss streaming executions without an action name.
+ spark.sparkContext.listenerBus.waitUntilEmpty(streamingTimeout.toMillis)
+ // Assert on the test thread: Spark logs listener failures without
failing the test.
+ assertKafkaScans(completedKafkaPlans.asScala.toSeq)
+ } finally {
+ try {
+ kafkaScanListener.foreach(spark.sparkContext.removeSparkListener)
+ kafkaScanListener = None
+ completedKafkaPlans.clear()
+ } finally {
+ super.afterEach()
+ }
+ }
+ }
+
+ protected def assertKafkaScan(query: StreamExecution, requireScan: Boolean =
false): Boolean = {
+ val execution = Option(query).flatMap(q => Option(q.lastExecution))
+ assertKafkaScans(execution.toSeq.map(_.executedPlan), requireScan)
+ }
+
+ private def assertKafkaScans(
+ plans: Seq[SparkPlan],
+ requireScan: Boolean = false): Boolean = {
+ val nativeScans = plans.flatMap {
+ _.collect { case scan: MicroBatchScanExecTransformer => scan }
+ }
+ val sparkScans = plans.flatMap {
+ _.collect {
+ case scan: MicroBatchScanExec
+ if MicroBatchScanExecTransformer.supportsBatchScan(scan.scan) =>
+ scan
+ }
+ }
+
+ // Empty batches and recovery checks may have no physical scan.
+ // Dedicated scan tests require one.
+ if (requireScan) {
+ assert(
+ nativeScans.nonEmpty || sparkScans.nonEmpty,
+ "No executed Kafka micro-batch scan found")
+ }
+ nativeScans.foreach {
+ scan =>
+ assert(
+ !scan.output.exists(_.name == "headers"),
+ s"Kafka headers must fall back to Spark, but the scan was
native:\n$scan")
+ }
+ sparkScans.foreach {
+ scan =>
+ assert(
+ scan.output.exists(_.name == "headers"),
+ "Kafka micro-batch scan fell back to Spark. Build a Kafka-enabled
native backend " +
+ "and include the Velox Kafka component before running native Kafka
tests. " +
+ s"The merged upstream integration must also exist in this
checkout.\n$scan"
+ )
+ }
+ true
+ }
+
+ override def testStream(
+ stream: Dataset[_],
+ outputMode: OutputMode,
+ extraOptions: Map[String, String])(actions: StreamAction*): Unit = {
+ // Spark's AssertOnQuery uses the current query, or the last stopped query
during recovery.
+ // Do not require isActive: answer checks can inspect a completed or
stopped execution.
+ val checkedActions = actions.flatMap {
+ case action: CheckAnswerRows =>
+ Seq(action, AssertOnQuery(query => assertKafkaScan(query)))
+ case action: CheckAnswerRowsContains =>
+ Seq(action, AssertOnQuery(query => assertKafkaScan(query)))
+ case action: CheckAnswerRowsByFunc =>
+ Seq(action, AssertOnQuery(query => assertKafkaScan(query)))
+ case action: CheckNewAnswerRows =>
+ Seq(action, AssertOnQuery(query => assertKafkaScan(query)))
+ case action => Seq(action)
+ }
+ super.testStream(stream, outputMode, extraOptions)(checkedActions: _*)
+ }
+}
diff --git
a/gluten-ut/spark35/src/test/scala/org/apache/gluten/utils/velox/VeloxTestSettings.scala
b/gluten-ut/spark35/src/test/scala/org/apache/gluten/utils/velox/VeloxTestSettings.scala
index f65652d522..1ae8f00050 100644
---
a/gluten-ut/spark35/src/test/scala/org/apache/gluten/utils/velox/VeloxTestSettings.scala
+++
b/gluten-ut/spark35/src/test/scala/org/apache/gluten/utils/velox/VeloxTestSettings.scala
@@ -47,6 +47,17 @@ import org.apache.spark.sql.sources._
class VeloxTestSettings extends BackendTestSettings {
import SuiteSettings._
+ // Kafka wrappers are compiled only with -Pkafka. Register by name to keep
it optional.
+
enableSuite("org.apache.spark.sql.kafka010.GlutenKafkaMicroBatchV2SourceSuite")
+ // Spark 3.5 ProgressReporter recognizes MicroBatchScanExec, but not the
native transformer,
+ // when attributing input rows to a V2 source. Native reads report zero
numInputRows.
+ .exclude("input row metrics")
+ // Spark's self-join input-row totals have the same unsupported progress
attribution.
+ // The Gluten replacement retains output, offset-log, exchange-reuse and
native-scan checks.
+ .exclude("ensure stream-stream self-join generates only one offset in log
and correct metrics")
+ enableSuite("org.apache.spark.sql.kafka010.GlutenKafkaHybridSourceSuite")
+ // @DoNotDiscover keeps the longer stress run separate; CI selects it
explicitly.
+ enableSuite("org.apache.spark.sql.kafka010.GlutenKafkaSourceStressSuite")
enableSuite[GlutenStringFunctionsSuite]
enableSuite[GlutenBloomFilterAggregateQuerySuite]
enableSuite[GlutenBloomFilterAggregateQuerySuiteCGOff]
diff --git
a/gluten-ut/spark35/src/test/scala/org/apache/spark/sql/GlutenSQLQuerySuite.scala
b/gluten-ut/spark35/src/test/scala/org/apache/spark/sql/GlutenSQLQuerySuite.scala
index e3269994d8..c3bc02478a 100644
---
a/gluten-ut/spark35/src/test/scala/org/apache/spark/sql/GlutenSQLQuerySuite.scala
+++
b/gluten-ut/spark35/src/test/scala/org/apache/spark/sql/GlutenSQLQuerySuite.scala
@@ -24,6 +24,8 @@ import org.apache.spark.SparkException
import org.apache.spark.sql.execution.columnar.InMemoryTableScanExec
import org.apache.spark.sql.internal.SQLConf
+import scala.concurrent.duration._
+
class GlutenSQLQuerySuite extends SQLQuerySuite with GlutenSQLTestsTrait {
import testImplicits._
@@ -181,6 +183,33 @@ class GlutenSQLQuerySuite extends SQLQuerySuite with
GlutenSQLTestsTrait {
}
}
+ testGluten("rate source writes to console in append mode and reports sink
rows") {
+ withTempDir {
+ checkpoint =>
+ val query = spark.readStream
+ .format("rate")
+ .option("rowsPerSecond", 10)
+ .load()
+ .writeStream
+ .format("console")
+ .outputMode("append")
+ .option("checkpointLocation", checkpoint.getCanonicalPath)
+ .start()
+ try {
+ val deadline = 30.seconds.fromNow
+ while (!query.recentProgress.exists(_.sink.numOutputRows > 0) &&
deadline.hasTimeLeft()) {
+ assert(!query.awaitTermination(100), "Rate query terminated before
producing rows")
+ }
+ val progress =
query.recentProgress.filter(_.durationMs.containsKey("addBatch"))
+ assert(progress.exists(_.sink.numOutputRows > 0), "Console sink
reported no rows")
+ assert(progress.forall(_.sink.numOutputRows >= 0))
+ assert(query.exception.isEmpty)
+ } finally {
+ query.stop()
+ }
+ }
+ }
+
ignoreGluten("StreamingQueryProgress.numInputRows should be correct") {
withTempDir {
dir =>
diff --git
a/gluten-ut/spark35/src/test/scala/org/apache/spark/sql/sources/GlutenResolvedDataSourceSuite.scala
b/gluten-ut/spark35/src/test/scala/org/apache/spark/sql/sources/GlutenResolvedDataSourceSuite.scala
index ddd06bb3fd..a601526a66 100644
---
a/gluten-ut/spark35/src/test/scala/org/apache/spark/sql/sources/GlutenResolvedDataSourceSuite.scala
+++
b/gluten-ut/spark35/src/test/scala/org/apache/spark/sql/sources/GlutenResolvedDataSourceSuite.scala
@@ -17,5 +17,15 @@
package org.apache.spark.sql.sources
import org.apache.spark.sql.GlutenSQLTestsBaseTrait
+import org.apache.spark.util.Utils
-class GlutenResolvedDataSourceSuite extends ResolvedDataSourceSuite with
GlutenSQLTestsBaseTrait {}
+class GlutenResolvedDataSourceSuite extends ResolvedDataSourceSuite with
GlutenSQLTestsBaseTrait {
+ override def testNameBlackList: Seq[String] = {
+ // The kafka profile adds the connector, so Spark's missing module check
no longer applies.
+ if
(Utils.classIsLoadable("org.apache.spark.sql.kafka010.KafkaSourceProvider")) {
+ super.testNameBlackList :+ "kafka: show deploy guide for loading the
external kafka module"
+ } else {
+ super.testNameBlackList
+ }
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]