ReemaAlzaid commented on code in PR #13674:
URL: https://github.com/apache/gluten/pull/13674#discussion_r4698396157


##########
backends-velox/src-delta33/test/scala/org/apache/spark/sql/execution/benchmark/DeltaStreamingWriteBenchmark.scala:
##########
@@ -0,0 +1,185 @@
+/*
+ * 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.spark.sql.SparkSession
+import org.apache.spark.sql.delta.DeltaLog
+import org.apache.spark.sql.delta.util.DeltaFileOperations
+import org.apache.spark.sql.execution.streaming.MemoryStream
+
+import com.sun.management.OperatingSystemMXBean
+import org.apache.parquet.hadoop.ParquetFileReader
+import org.apache.parquet.hadoop.util.HadoopInputFile
+
+import java.lang.management.ManagementFactory
+import java.nio.charset.StandardCharsets
+
+import scala.collection.JavaConverters._
+
+/**
+ * Local Spark 3.5 / Delta 3.3.2 streaming append benchmark, with statistics 
enabled.
+ *
+ * Run this main class using spark-submit with the backends-velox test jar, 
the native Gluten
+ * bundle, Delta jars and the Spark test-jar classpath used by 
DeltaPlanningBenchmark. The workload
+ * uses local[2], two input partitions and identical fixed-size batches for 
both writers.
+ *
+ * Reports Spark's triggerExecution duration and JVM process CPU separately. 
CPU covers source
+ * enqueue through processAllAvailable, including MemoryStream encoding and 
local executor work; it
+ * is not cluster CPU or CPU for precisely the triggerExecution interval. 
Input vector creation,
+ * query startup, writer verification and warmup batches are excluded from 
reported samples.
+ *
+ * Set spark.gluten.benchmark.delta.streaming.warmupBatches (default 2) and 
measuredBatches (default
+ * 5) to adjust the repetitions. No performance thresholds are asserted.
+ */
+object DeltaStreamingWriteBenchmark extends SqlBasedBenchmark {
+  override def getSparkSession: SparkSession = {
+    SparkSession
+      .builder()
+      .master("local[2]")
+      .appName("DeltaStreamingWriteBenchmark")
+      .config("spark.sql.extensions", 
"io.delta.sql.DeltaSparkSessionExtension")
+      .config(
+        "spark.sql.catalog.spark_catalog",
+        "org.apache.spark.sql.delta.catalog.DeltaCatalog")
+      .config("spark.plugins", "org.apache.gluten.GlutenPlugin")
+      .config("spark.memory.offHeap.enabled", "true")
+      .config("spark.memory.offHeap.size", "1024MB")
+      .config("spark.ui.enabled", "false")
+      .config("spark.default.parallelism", "2")
+      .config("spark.sql.shuffle.partitions", "2")
+      .config("spark.sql.adaptive.enabled", "false")
+      .config("spark.sql.ansi.enabled", "false")
+      .getOrCreate()
+  }
+
+  private val warmupBatches = spark.sparkContext.conf
+    .getInt("spark.gluten.benchmark.delta.streaming.warmupBatches", 2)
+  private val measuredBatches = spark.sparkContext.conf
+    .getInt("spark.gluten.benchmark.delta.streaming.measuredBatches", 5)
+
+  private val processCpu = ManagementFactory.getOperatingSystemMXBean match {
+    case bean: OperatingSystemMXBean => bean
+    case other =>
+      throw new IllegalStateException(s"JVM process CPU time is unavailable: 
${other.getName}")
+  }
+
+  override def runBenchmarkSuite(mainArgs: Array[String]): Unit = {
+    require(warmupBatches >= 0 && measuredBatches > 0)
+    require(processCpu.getProcessCpuTime >= 0, "JVM process CPU time is 
unavailable")
+    report(s"local[2], input partitions=2, statistics=true, " +
+      s"warmup batches=$warmupBatches, measured batches=$measuredBatches")
+    report("CPU interval: source enqueue through processAllAvailable, in this 
JVM only")
+    
report("mode,rows_per_batch,sample,triggerExecution_ms,local_process_cpu_ms")
+    for (rowsPerBatch <- Seq(10000, 100000, 1000000); nativeWrite <- 
Seq(false, true)) {
+      runStreamingCase(rowsPerBatch, nativeWrite)
+    }
+  }
+
+  private def runStreamingCase(rowsPerBatch: Int, nativeWrite: Boolean): Unit 
= {
+    import spark.implicits._
+    val rows = (0 until rowsPerBatch).map(_.toLong).toVector
+    val mode = if (nativeWrite) "native" else "vanilla"
+    withSQLConf(
+      "spark.gluten.enabled" -> nativeWrite.toString,
+      "spark.gluten.sql.columnar.backend.velox.delta.enableNativeWrite" -> 
nativeWrite.toString,
+      
"spark.gluten.sql.columnar.backend.velox.delta.enableNativeStreamingWrite" ->
+        nativeWrite.toString,
+      "spark.databricks.delta.stats.collect" -> "true",
+      "spark.databricks.delta.optimizeWrite.enabled" -> "false"
+    ) {
+      withTempPath {
+        directory =>
+          val path = directory.getCanonicalPath + "/data"
+          val input = MemoryStream[Long](numPartitions = 2)(implicitly, 
spark.sqlContext)
+          val query = input.toDF()
+            .selectExpr("value AS id", "value * 2 AS doubled", 
"concat('value-', value) AS payload")
+            .writeStream.format("delta").outputMode("append")
+            .option("checkpointLocation", directory.getCanonicalPath + 
"/checkpoint")
+            .start(path)
+          val samples = scala.collection.mutable.ArrayBuffer.empty[(Long, 
Double)]
+          try {
+            query.processAllAvailable()
+            var previousBatchId = 
Option(query.lastProgress).map(_.batchId).getOrElse(-1L)

Review Comment:
   Changed `previousBatchId` to start at -1L and advance only for data-bearing 
progress. The updated benchmark ran successfully.



##########
backends-velox/src-delta33/main/scala/org/apache/spark/sql/delta/sources/OffloadDeltaStreamingWrite.scala:
##########
@@ -0,0 +1,65 @@
+/*
+ * 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.delta.sources
+
+import org.apache.gluten.config.{GlutenConfig, VeloxDeltaConfig}
+
+import org.apache.spark.sql.DataFrame
+import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.streaming.WriteToStream
+import org.apache.spark.sql.execution.datasources.v2.DeltaV2WriteOperators
+import org.apache.spark.sql.execution.streaming.Sink
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.streaming.OutputMode
+
+// Delta's V1 streaming sink starts transactions outside physical write 
command execution
+case class OffloadDeltaStreamingWrite() extends Rule[LogicalPlan] {
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    if (!OffloadDeltaStreamingWrite.enabled(SQLConf.get)) {
+      return plan
+    }
+    plan.resolveOperatorsDown {
+      case write: WriteToStream if write.outputMode == OutputMode.Append() =>
+        write.sink match {
+          case sink: DeltaSink => write.copy(sink = new GlutenDeltaSink(sink))
+          case _ => write
+        }
+    }
+  }
+}
+
+object OffloadDeltaStreamingWrite {
+  private[sources] def enabled(sqlConf: SQLConf): Boolean = {
+    val conf = new GlutenConfig(sqlConf)
+    val deltaConf = new VeloxDeltaConfig(sqlConf)
+    // This sink bypasses physical write command validation, so retain its 
session level gates
+    // Keep these checks in sync with Validators and FallbackOnANSIMode.
+    conf.enableGluten && deltaConf.enableNativeWrite && 
deltaConf.enableNativeStreamingWrite &&
+    !conf.enableScanOnly && !(conf.enableAnsiMode && conf.enableAnsiFallback)
+  }
+}
+
+// Keep Delta's schema checks, epoch deduplication and commit protocol in the 
original sink
+class GlutenDeltaSink(private[delta] val delegate: DeltaSink) extends Sink {
+  override def addBatch(batchId: Long, data: DataFrame): Unit =
+    DeltaV2WriteOperators.withColumnarTransaction {

Review Comment:
   Added the check at transaction write time using the effective Hadoop 
configuration, including table properties. When parquet.crypto.factory.class is 
set, it falls back to Delta’s writer. Tests verified encrypted output, 
including when the table property changes after stream startup.



##########
gluten-ut/spark35/src-delta/test/scala/org/apache/spark/sql/execution/datasources/GlutenDeltaNativePartitionWriteSuite.scala:
##########
@@ -158,4 +166,118 @@ class GlutenDeltaNativePartitionWriteSuite extends 
GlutenQueryTest with SharedSp
       }
     }
   }
+
+  for (
+    partitioned <- Seq(false, true);
+    collectStats <- Seq(false, true);
+    nativeWrite <- Seq(false, true);
+    nativeStreamingWrite <- Seq(false, true)
+  ) {
+    test(s"Delta streaming appends: partitioned=$partitioned, 
stats=$collectStats, " +
+      s"nativeWrite=$nativeWrite, nativeStreamingWrite=$nativeStreamingWrite") 
{
+      assume(BackendTestUtils.isVeloxBackendLoaded())
+      import testImplicits._
+      // Spark 4.x also compiles this suite, but native streaming writes only 
support Spark 3.5.
+      val expectNativeWrite = nativeWrite && nativeStreamingWrite &&
+        SparkVersionUtil.compareMajorMinorVersion((3, 5)) == 0
+      withSQLConf(
+        "spark.gluten.sql.columnar.backend.velox.delta.enableNativeWrite" -> 
nativeWrite.toString,
+        
"spark.gluten.sql.columnar.backend.velox.delta.enableNativeStreamingWrite" ->
+          nativeStreamingWrite.toString,
+        "spark.databricks.delta.stats.collect" -> collectStats.toString,
+        "spark.sql.jsonGenerator.ignoreNullFields" -> "true"
+      ) {
+        withTempDir {
+          dir =>
+            val path = dir.getCanonicalPath + "/data"
+            val input = MemoryStream[(Option[Long], Option[String])]
+            val writer = input.toDF().toDF("id", "part")
+              .filter($"id".isNull || $"id" >= 0L)
+              .writeStream.format("delta").outputMode("append")
+              .option("checkpointLocation", dir.getCanonicalPath + 
"/checkpoint")
+            val query = (if (partitioned) writer.partitionBy("part") else 
writer).start(path)
+            try {
+              input.addData((Some(1L), Some("a")), (None, Some("a")))
+              query.processAllAvailable()
+              input.addData((Some(2L), None), (Some(3L), Some("b")))
+              query.processAllAvailable()
+              val deltaLog = DeltaLog.forTable(spark, path)
+              val versionBeforeEmptyBatch = deltaLog.update().version
+              // Advance the source offset with an empty output batch.
+              input.addData((Some(-1L), Some("discarded")))
+              query.processAllAvailable()
+              assert(deltaLog.update().version > versionBeforeEmptyBatch)
+              assert(query.recentProgress.nonEmpty)
+              assert(query.recentProgress.forall(_.sink.description == 
s"DeltaSink[$path]"))
+            } finally {
+              query.stop()

Review Comment:
   Added a restart test with a replayable file source. It simulates the failure 
window by removing Spark’s commit marker while keeping the source offset and 
Delta commit. Replaying the same epoch adds no rows or AddFiles



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

To unsubscribe, e-mail: [email protected]

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


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

Reply via email to