codope commented on code in PR #20183:
URL: https://github.com/apache/hudi/pull/20183#discussion_r4162521167


##########
hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/common/TestVectorizedReadDecisionPerScan.scala:
##########
@@ -0,0 +1,127 @@
+/*
+ * 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.hudi.common
+
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.execution.{FileSourceScanExec, 
WholeStageCodegenExec}
+import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
+
+import java.io.File
+
+/**
+ * Spark caches the resolved relation of a table per session, so every 
statement on the table shares one
+ * HoodieFileGroupReaderBasedFileFormat instance, and it asks that instance 
about batch support only for scans
+ * narrower than spark.sql.codegen.maxFields. A wider scan therefore has to 
decide about vectorized reading for
+ * its own schema when its reader is built, and no scan may change 
spark.sql.parquet.enableVectorizedReader,
+ * which Spark reads to decide whether the scan output still needs an 
UnsafeRow conversion.
+ */
+class TestVectorizedReadDecisionPerScan extends HoodieSparkSqlTestBase with 
AdaptiveSparkPlanHelper {
+
+  private val vectorizedReaderConf = "spark.sql.parquet.enableVectorizedReader"
+  // Leaf fields of the payload struct; with them the table exceeds 
spark.sql.codegen.maxFields, so a
+  // select * scan is planned row-based without a supportBatch call
+  private val payloadFieldCount = 120
+
+  Seq("cow", "mor").foreach { tableType =>
+    test(s"Test wide scan after narrow scan decides vectorized read per scan 
for $tableType table") {
+      withSQLConf(vectorizedReaderConf -> "true", 
"spark.sql.codegen.maxFields" -> "100") {
+        withTempDir { tmp =>
+          val tableName = generateTableName
+          createWideTable(tableName, tableType, tmp)
+
+          // The narrow scan is asked supportBatch and may read vectorized
+          checkAnswer(s"select count(*) from $tableName")(Seq(3))
+          assertResult("true")(spark.conf.get(vectorizedReaderConf))
+
+          // The wide scan is never asked, and must not inherit the narrow 
scan's answer
+          assert(!scanIsBatched(s"select * from $tableName"))
+          checkWideScan(tableName)
+          assertResult("true")(spark.conf.get(vectorizedReaderConf))
+
+          // With the vectorized reader disabled Spark skips the UnsafeRow 
conversion of the scan output, so a
+          // wide scan handed a leftover vectorized reader fails with
+          // ClassCastException: ColumnarBatchRow cannot be cast to UnsafeRow
+          withSQLConf(vectorizedReaderConf -> "false") {
+            checkWideScan(tableName)
+            assertResult("false")(spark.conf.get(vectorizedReaderConf))
+          }
+        }
+      }
+    }
+
+    test(s"Test wide scan keeps vectorized reads enabled for later scans for 
$tableType table") {
+      withSQLConf(vectorizedReaderConf -> "true", 
"spark.sql.codegen.maxFields" -> "100") {
+        withTempDir { tmp =>
+          val tableName = generateTableName
+          createWideTable(tableName, tableType, tmp)
+
+          checkWideScan(tableName)
+          assertResult("true")(spark.conf.get(vectorizedReaderConf))
+
+          // Only COW scans return batches; MOR merges rows, so its scans are 
never columnar
+          if (tableType == "cow") {
+            assert(scanIsBatched(s"select count(*) from $tableName"))
+          }
+          checkAnswer(s"select count(*) from $tableName")(Seq(3))
+          assertResult("true")(spark.conf.get(vectorizedReaderConf))
+        }
+      }
+    }
+  }
+
+  private def createWideTable(tableName: String, tableType: String, tmp: 
File): Unit = {
+    val payloadType = (1 to payloadFieldCount).map(i => s"f$i 
int").mkString("struct<", ", ", ">")
+    spark.sql(
+      s"""
+         |create table $tableName (
+         |  id int,
+         |  name string,
+         |  payload $payloadType,
+         |  ts long
+         |) using hudi
+         | location '${tmp.getCanonicalPath}/$tableName'
+         | tblproperties (
+         |  type = '$tableType',
+         |  primaryKey = 'id',
+         |  orderingFields = 'ts'
+         | )
+       """.stripMargin)
+    val rows = (1 to 3).map { id =>
+      val payload = (1 to payloadFieldCount).map(i => s"'f$i', ${id * 1000 + 
i}").mkString("named_struct(", ", ", ")")
+      s"select $id as id, 'a$id' as name, $payload as payload, ${id * 1000}L 
as ts"
+    }
+    spark.sql(s"insert into $tableName ${rows.mkString(" union all ")}")

Review Comment:
   A single insert gives base-only file slices, so the scan never mixes the two 
readers the `buildReader` comment is about: vectorized baseFileReader for 
base-only slices, row `fileGroupBaseFileReader` for base+log slices. Test 
should use >1 file groups (e.g. partitioned), update one, then rerun both 
orderings.



##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/HoodieFileGroupReaderBasedFileFormat.scala:
##########
@@ -346,10 +337,11 @@ class HoodieFileGroupReaderBasedFileFormat(tablePath: 
String,
     val dataStructTypeWithMandatoryPartitionFields = 
StructType(dataStructType.fields ++ partitionSchema.fields.filter(f => 
mandatoryFields.contains(f.name) && !isNestedPartitionField(f.name)))
     val dataSchema = HoodieSchemaUtils.pruneDataSchema(schema, 
HoodieSchemaConversionUtils.convertStructTypeToHoodieSchema(dataStructTypeWithMandatoryPartitionFields,
 sanitizedTableName), exclusionFields)
 
-    
spark.sessionState.conf.setConfString("spark.sql.parquet.enableVectorizedReader",
 supportVectorizedRead.toString)

Review Comment:
   we should explain why the `setConfString` is safe to remove, or test the 
case it was added for. It came in with #14161 (timestamp-millis repair). On 
Spark 3.3/3.4 with a timestamp-millis table, that is the one case where Hudi 
deliberately wrote false while the user had true. After this PR the conf stays 
true, so Spark adds an `UnsafeProjection` over the non-vectorized repaired 
rows. I think dropping it is harmless (Spark just adds a row conversion), but 
#14161 left no comment. Please add a Spark 3.3/3.4 timestamp-millis table case 
(narrow and wide, conf=true) and explain the reasoning.



##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/HoodieFileGroupReaderBasedFileFormat.scala:
##########
@@ -346,10 +337,11 @@ class HoodieFileGroupReaderBasedFileFormat(tablePath: 
String,
     val dataStructTypeWithMandatoryPartitionFields = 
StructType(dataStructType.fields ++ partitionSchema.fields.filter(f => 
mandatoryFields.contains(f.name) && !isNestedPartitionField(f.name)))
     val dataSchema = HoodieSchemaUtils.pruneDataSchema(schema, 
HoodieSchemaConversionUtils.convertStructTypeToHoodieSchema(dataStructTypeWithMandatoryPartitionFields,
 sanitizedTableName), exclusionFields)
 
-    
spark.sessionState.conf.setConfString("spark.sql.parquet.enableVectorizedReader",
 supportVectorizedRead.toString)
+    // Decide per scan: Spark skips supportBatch for scans wider than 
spark.sql.codegen.maxFields
+    val vectorizedRead = canReadVectorized(spark, outputSchema)

Review Comment:
   actually agree with the bot here..  the new per-scan check throws on any 
format other than Parquet, ORC or Lance. Before, that only hit narrow scans; 
now it runs for every scan of a Vortex table. No test reads a Vortex table 
through Spark SQL, so CI won't catch it. For this PR, I think the fix is to 
simply return false for Vortex.



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

Reply via email to