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


##########
backends-velox/src-delta33/main/scala/org/apache/spark/sql/delta/GlutenOptimisticTransaction.scala:
##########
@@ -58,9 +60,25 @@ class GlutenOptimisticTransaction(delegate: 
OptimisticTransaction)
           "falling back to the vanilla Delta write path.")
       return super.writeFiles(inputData, writeOptions, isOptimize, 
additionalConstraints)
     }
-    hasWritten = true
-
     val spark = inputData.sparkSession
+    // Check the current transaction metadata, including table properties 
added after stream startup.
+    // Use the same effective configuration as Delta's writer and the Delta 
4.x native write gate.
+    // scalastyle:off deltahadoopconfiguration
+    val jobHadoopConf =
+      spark.sessionState.newHadoopConfWithOptions(metadata.configuration ++ 
deltaLog.options)
+    // scalastyle:on deltahadoopconfiguration
+    val encrypted =
+      
jobHadoopConf.get(EncryptionPropertiesFactory.CRYPTO_FACTORY_CLASS_PROPERTY_NAME)
 != null
+    val maxRecordsPerFile = writeOptions
+      .flatMap(_.options.get(DeltaOptions.MAX_RECORDS_PER_FILE))
+      .map(_.toLong)
+      .getOrElse(spark.sessionState.conf.maxRecordsPerFile)
+    // Only the partitioned native writer can split a columnar batch across 
output files.
+    if (encrypted || (metadata.partitionColumns.isEmpty && maxRecordsPerFile > 
0)) {

Review Comment:
   I reproduced this on Spark 3.5.5 / Delta 3.3.2 with the streaming code from 
`d713183`. For an unpartitioned append of `DATE '1500-01-01'` under the default 
`spark.sql.parquet.datetimeRebaseModeInWrite=EXCEPTION`, Delta's writer raised 
`WRITE_ANCIENT_DATETIME` and left no commit. Turning on native streaming writes 
committed Delta version 0 and Spark checkpoint `commits/0`. I got the same 
result with statistics on and off. In `LEGACY` mode, parquet-mr wrote physical 
day `-171655` with the legacy calendar marker; Velox wrote `-171664` without it.
   
   Please fall back for DATE data columns when the mode isn't `CORRECTED`, as 
the 4.x write gate does, and add a streaming regression test that checks the 
exception occurs before the commit.



##########
gluten-ut/spark35/src-delta/test/scala/org/apache/spark/sql/execution/datasources/GlutenDeltaNativePartitionWriteSuite.scala:
##########
@@ -158,4 +171,348 @@ 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()
+            }
+            // Read with Spark so native reader behavior cannot hide a write 
error.
+            withSQLConf(GlutenConfig.GLUTEN_ENABLED.key -> "false") {
+              val hadoopConf = spark.sessionState.newHadoopConf()
+              val dataPath = new Path(path)
+              val fileSystem = dataPath.getFileSystem(hadoopConf)
+              val physicalFiles = fileSystem.listFiles(dataPath, true)
+              var emptyFiles = 0
+              // Statistics can exclude empty files from the log, so inspect 
physical files too.
+              while (physicalFiles.hasNext) {
+                val file = physicalFiles.next()
+                if (
+                  file.getPath.getName.endsWith(".parquet") &&
+                  !file.getPath.toString.contains("/_delta_log/")
+                ) {
+                  assert(file.getLen > 0, s"Zero-byte Parquet file: 
${file.getPath}")
+                  val reader = ParquetFileReader.open(
+                    HadoopInputFile.fromPath(file.getPath, hadoopConf))
+                  try {
+                    // Check the physical writer, not only a plan wrapper that 
could fall back.
+                    val createdBy = 
reader.getFooter.getFileMetaData.getCreatedBy
+                    val numRows = 
reader.getFooter.getBlocks.asScala.map(_.getRowCount).sum
+                    assert(createdBy != null, s"Missing writer metadata for 
${file.getPath}")
+                    // Empty tasks use Spark's writer to produce a valid 
schema-only Parquet file.
+                    assert(
+                      createdBy.startsWith("parquet-mr") == 
(!expectNativeWrite || numRows == 0),
+                      s"Unexpected writer for ${file.getPath}: $createdBy")
+                    if (numRows == 0) emptyFiles += 1
+                  } finally {
+                    reader.close()
+                  }
+                }
+              }
+              if (!partitioned) assert(emptyFiles > 0, "Missing schema-only 
empty-batch file")
+              val files = DeltaLog.forTable(spark, 
path).update().allFiles.collect()
+              assert(files.nonEmpty)
+              files.foreach {
+                file =>
+                  val filePath = DeltaFileOperations.absolutePath(path, 
file.path)
+                  assert(file.size > 0, s"Committed zero-byte file: 
${file.path}")
+                  assert(fileSystem.getFileStatus(filePath).getLen == 
file.size, file.path)
+                  if (collectStats) {
+                    val rows = 
spark.read.parquet(filePath.toString).select("id").collect().toSeq
+                    val values = 
rows.filterNot(_.isNullAt(0)).map(_.getLong(0))
+                    val stats = parse(file.stats)
+                    assert((stats \ "numRecords") == JInt(rows.size), 
file.stats)
+                    assert(
+                      (stats \ "nullCount" \ "id") == JInt(rows.size - 
values.size),
+                      file.stats)
+                    assert(
+                      (stats \ "minValues" \ "id") ==
+                        (if (values.isEmpty) JNothing else JInt(values.min)),
+                      file.stats)
+                    assert(
+                      (stats \ "maxValues" \ "id") ==
+                        (if (values.isEmpty) JNothing else JInt(values.max)),
+                      file.stats)
+                  } else {
+                    assert(file.stats == null || file.stats.isEmpty)
+                  }
+              }
+              checkAnswer(
+                spark.read.format("delta").load(path).select("id", "part"),
+                Seq(Row(1L, "a"), Row(null, "a"), Row(2L, null), Row(3L, "b")))
+            }
+        }
+      }
+    }
+  }
+
+  for (
+    (option, sessionLimit, partitioned, expectedNative) <- Seq(
+      (None, 1, false, false),
+      (Some("1"), 0, false, false),
+      (Some("0"), 1, false, true),
+      (Some("-1"), 1, false, true),
+      (Some("1"), 0, true, true));
+    collectStats <- Seq(false, true)
+  ) {
+    test(s"Delta streaming safeguards: file limit option=$option, 
session=$sessionLimit, " +
+      s"partitioned=$partitioned, stats=$collectStats") {
+      assume(BackendTestUtils.isVeloxBackendLoaded())
+      import testImplicits._
+      withSQLConf(
+        
"spark.gluten.sql.columnar.backend.velox.delta.enableNativeStreamingWrite" -> 
"true",
+        "spark.sql.files.maxRecordsPerFile" -> sessionLimit.toString,
+        "spark.databricks.delta.stats.collect" -> collectStats.toString
+      ) {
+        withTempDir {
+          dir =>
+            val path = dir.getCanonicalPath + "/data"
+            val input = MemoryStream[Long](numPartitions = 1)(implicitly, 
spark.sqlContext)
+            val writer = input.toDF().selectExpr("value AS id", "0 AS part")
+              .writeStream.format("delta").outputMode("append")
+              .option("checkpointLocation", dir.getCanonicalPath + 
"/checkpoint")
+            option.foreach(value => writer.option("MaXrEcOrDsPeRfIlE", value))
+            val query = (if (partitioned) writer.partitionBy("part") else 
writer).start(path)
+            try {
+              input.addData(1L, 2L)
+              query.processAllAvailable()
+            } finally {
+              query.stop()
+            }
+            withSQLConf(GlutenConfig.GLUTEN_ENABLED.key -> "false") {
+              val files = DeltaLog.forTable(spark, 
path).update().allFiles.collect()
+              val expectNative = expectedNative &&
+                SparkVersionUtil.compareMajorMinorVersion((3, 5)) == 0
+              val rowCounts = files.map {
+                file =>
+                  assert(file.size > 0, s"Committed zero-byte file: 
${file.path}")
+                  val reader = ParquetFileReader.open(HadoopInputFile.fromPath(
+                    DeltaFileOperations.absolutePath(path, file.path),
+                    spark.sessionState.newHadoopConf()))
+                  try {
+                    assert(reader.getFooter.getFileMetaData.getCreatedBy
+                      .startsWith("parquet-mr") == !expectNative)
+                    reader.getFooter.getBlocks.asScala.map(_.getRowCount).sum
+                  } finally {
+                    reader.close()
+                  }
+              }.sorted.toSeq
+              val limit = option.map(_.toLong).getOrElse(sessionLimit.toLong)
+              assert(rowCounts == (if (limit > 0) Seq(1L, 1L) else Seq(2L)))
+              checkAnswer(
+                spark.read.format("delta").load(path).select("id"),
+                Seq(Row(1L), Row(2L)))
+            }
+        }
+      }
+    }
+  }
+
+  for (setting <- Seq("session", "hadoop", "table", "table-after-start")) {
+    test(s"Delta streaming safeguards: Parquet encryption from $setting") {
+      assume(BackendTestUtils.isVeloxBackendLoaded())
+      import testImplicits._
+      val cryptoKey = "parquet.crypto.factory.class"
+      val factory = classOf[GlutenDeltaStreamingEncryptionFactory].getName
+      val hadoopConf = spark.sparkContext.hadoopConfiguration
+      val previousFactory = Option(hadoopConf.get(cryptoKey))
+      withSQLConf(
+        
"spark.gluten.sql.columnar.backend.velox.delta.enableNativeStreamingWrite" -> 
"true",
+        "spark.databricks.delta.stats.collect" -> "false") {
+        withTempDir {
+          dir =>
+            val path = dir.getCanonicalPath + "/data"
+            // Create metadata only, so no plaintext data files predate 
encryption.
+            spark.sql(s"CREATE TABLE delta.`$path` (id BIGINT) USING delta")
+            if (setting == "table") {
+              spark.sql(s"ALTER TABLE delta.`$path` SET TBLPROPERTIES 
('$cryptoKey'='$factory')")
+            }
+            if (setting == "hadoop") hadoopConf.set(cryptoKey, factory)
+            try {
+              val settings = if (setting == "session") Seq(cryptoKey -> 
factory) else Seq.empty
+              withSQLConf(settings: _*) {
+                val input = MemoryStream[Long](numPartitions = 1)(implicitly, 
spark.sqlContext)
+                val query = input.toDF().toDF("id").writeStream
+                  .format("delta").outputMode("append")
+                  .option("checkpointLocation", dir.getCanonicalPath + 
"/checkpoint").start(path)
+                try {
+                  query.processAllAvailable()
+                  if (setting == "table-after-start") {
+                    spark.sql(
+                      s"ALTER TABLE delta.`$path` SET TBLPROPERTIES 
('$cryptoKey'='$factory')")
+                  }
+                  input.addData(1L, 2L)
+                  query.processAllAvailable()
+                } finally {
+                  query.stop()
+                }
+              }
+            } finally {
+              previousFactory match {
+                case Some(value) => hadoopConf.set(cryptoKey, value)
+                case None => hadoopConf.unset(cryptoKey)
+              }
+            }
+            withSQLConf(GlutenConfig.GLUTEN_ENABLED.key -> "false", cryptoKey 
-> factory) {
+              val files = DeltaLog.forTable(spark, 
path).update().allFiles.collect()
+              assert(files.nonEmpty)
+              files.foreach {
+                file =>
+                  val filePath = DeltaFileOperations.absolutePath(path, 
file.path)
+                  val stream = 
filePath.getFileSystem(spark.sessionState.newHadoopConf())
+                    .open(filePath)
+                  try {
+                    val magic = new Array[Byte](4)
+                    stream.readFully(magic)
+                    assert(
+                      new String(magic, StandardCharsets.US_ASCII) == "PARE",
+                      s"Expected encrypted Parquet file: ${file.path}")
+                  } finally {
+                    stream.close()
+                  }
+              }
+              checkAnswer(spark.read.format("delta").load(path), Seq(Row(1L), 
Row(2L)))
+            }
+        }
+      }
+    }
+  }
+
+  for (collectStats <- Seq(false, true)) {
+    test(s"Delta streaming safeguards: replay committed epoch, 
stats=$collectStats") {
+      assume(BackendTestUtils.isVeloxBackendLoaded())
+      withSQLConf(
+        
"spark.gluten.sql.columnar.backend.velox.delta.enableNativeStreamingWrite" -> 
"true",
+        "spark.databricks.delta.stats.collect" -> collectStats.toString) {
+        withTempDir {
+          dir =>
+            val source = new java.io.File(dir, "source")
+            assert(source.mkdir())
+            def addInput(name: String, ids: Seq[Long]): Unit = {
+              val json = ids.map(id => s"""{"id":$id}""").mkString("\n")
+              Files.write(

Review Comment:
   `Files.write` creates `second.json` in the watched directory before it 
writes the bytes. I forced that scheduling window in the restarted stream: 
Spark committed epoch 1 while the file was empty. After the write finished, the 
table still had only rows 1 and 2; publishing the same JSON by atomic rename 
delivered rows 3 and 4. This is a test reliability issue, not the cause of the 
current CI failures. Please write the file outside `source`, close it, then 
move it into `source` atomically.



##########
docs/backends/velox/get-started/VeloxDelta.md:
##########
@@ -216,7 +216,7 @@ Gluten's CI checks that a partitioned `save(path)` on 3.5 
to 4.1 and OPTIMIZE on
 | `INSERT INTO ... SELECT`, `INSERT OVERWRITE`, `INSERT INTO ... REPLACE 
WHERE` | | PartialOffload | From code. To append natively, use `save(path)` in 
append mode. |
 | | `insertInto(t)`, `saveAsTable(t)` in append mode on an existing table, 
`writeTo(t).append()`, `overwrite(condition)`, `overwritePartitions()` | 
PartialOffload | From code. |
 | `MERGE INTO` | | PartialOffload | Scans, the DML target scan and joins can 
run in Velox. On Spark 3.5 and 4.0, Gluten's tests check that a deletion-vector 
MERGE runs a scan of the target table in Velox. The other cases are from code. 
Native MERGE write is in progress in 
[#13324](https://github.com/apache/gluten/pull/13324). |
-| | `writeStream.format("delta")` | PartialOffload | Inside `foreachBatch`, 
batch writes follow the rows above. From code. |
+| | `writeStream.format("delta")` | Experimental Offload on Spark 3.5 in 
append mode; otherwise PartialOffload | Requires both native write and native 
streaming write on. Column-mapped tables use Delta's writer. Row tracking is 
unvalidated and retains native scan limitations. Inside `foreachBatch`, batch 
writes follow the rows above. From code. |

Review Comment:
   Please update the write-problems and configuration tables to match the new 
transaction guard, too. They still say Spark 3.5 may produce invalid files with 
a positive unpartitioned `maxRecordsPerFile` and describe 
`parquet.crypto.factory.class` fallback only for 4.x. This change makes both 
cases use Delta's writer on 3.5 for batch as well as streaming. The empty-task 
problem is separate.



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