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


##########
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:
   All three batches advance normally in one run. Please add a replay case for 
the failure window after Delta commits an epoch but before Spark records it in 
the checkpoint. Restart from that checkpoint with a replayable source and 
verify the same epoch adds no rows or `AddFile`s, then verify the next epoch 
can commit. The observer test starts a transaction but never commits one, so it 
doesn't cover this exactly-once guarantee.



##########
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:
   This switches even an encrypted Delta table to the 3.5 Velox writer. That 
writer doesn't use the Parquet crypto factory from the job's Hadoop 
configuration, so a streaming append that parquet-mr would encrypt can commit 
plaintext files. Please check the effective write configuration (including 
table properties) and fall back to Delta's writer when 
`parquet.crypto.factory.class` is set, as the 4.x `GlutenDeltaNativeWriteGate` 
does.



##########
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))

Review Comment:
   An unpartitioned stream with `maxRecordsPerFile=1` also gets wrapped. For a 
two-row Velox batch, Spark rotates the file after the placeholder row, but 
Velox only writes data on the terminal row: one file gets no footer and the 
other gets both rows. With stats off, Delta commits both. The empty-task fix in 
#13390 doesn't cover this because the task has input. Please fall back for a 
positive effective file limit on unpartitioned writes, or split the batch at 
the file boundary.



##########
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:
   The first `processAllAvailable()` runs on an empty `MemoryStream`. Spark 3.5 
can publish idle progress with `batchId == 0` without advancing the batch ID. 
If `lastProgress` sees that event, the first real batch is also 0 and the 
`p.batchId > previousBatchId` filter rejects it, aborting the benchmark with 
“Expected one data trigger, found 0”. This is a fresh checkpoint, so initialize 
`previousBatchId` to `-1L` and advance it only for data-bearing progress.



-- 
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