You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hudi.apache.org by "yihua (via GitHub)" <gi...@apache.org> on 2026/09/26 21:24:24 UTC

[PR] perf(spark): ship file group reader scan state once per executor [hudi]

yihua opened a new pull request, #20077:
URL: https://github.com/apache/hudi/pull/20077

   ### Describe the issue this Pull Request addresses
   
   closes #20073
   part of #20064
   
   The Spark file group reader function captured the whole file format and a driver-built meta client with a full Hadoop configuration, so every task deserialized both and re-parsed the schemas. It also wrote read options into the live table config for every file.
   
   ### Summary and Changelog
   
   The reader function is now `HoodieFileGroupReaderFunction`, which holds only broadcast handles. The scan state (the relation's meta client with the timeline the scan was planned against, schemas, reader properties) is broadcast as Java-serialized bytes and deserialized once per executor. Read options are merged into a copy of the table properties on the driver, and per-file properties are copied before use, so nothing shared is mutated on executors. The relation factory passes its meta client to the file format instead of the format building a second one.
   
   Tests: `TestHoodieFileGroupReaderFunction` serializes the function for COW and MOR tables and asserts no meta client, file format or Hadoop configuration is reachable, within a size budget. `TestReadOptionsDoNotOverrideTableConfig` checks that read options named like table config keys change neither merge results nor the relation's table config.
   
   This PR is independent of the parquet per-file configuration change (#20075) and can be cherry-picked on its own. The table state change (#20074) stacks on it.
   
   ### Impact
   
   Per-task deserialization drops from the file format plus meta client to a few broadcast handles.
   
   Behavior change: a read option whose key is a table config key (`hoodie.record.merge.mode`, `hoodie.table.ordering.fields`, `hoodie.compaction.payload.class`, `hoodie.table.partial.update.mode`, and similar) no longer overrides the persisted table config on the read path. Before, such an option could change merge results, and with several files per task the result could depend on which file a task read first. The write-side keys (`hoodie.datasource.write.payload.class`, `hoodie.write.record.merge.mode`, `hoodie.datasource.write.precombine.field`) still reach the reader through the reader properties.
   
   ### Risk Level
   
   medium. The per-file read logic is unchanged (the same reader builders and projections move into the new class), but the payload of every Spark scan task changes, and the scan state is shared by concurrent tasks on an executor. Covered by the new tests plus the existing COW/MOR data source and file group reader suites.
   
   ### Documentation Update
   
   none. The read option behavior change goes in the release notes.
   
   ### Contributor's checklist
   
   - [ ] Read through [contributor's guide](https://hudi.apache.org/contribute/how-to-contribute)
   - [ ] Enough context is provided in the sections above
   - [ ] Adequate tests were added if applicable
   


-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(spark): ship file group reader scan state once per executor [hudi]

Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua commented on code in PR #20077:
URL: https://github.com/apache/hudi/pull/20077#discussion_r4169418686


##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/HoodieFileGroupReaderBasedFileFormat.scala:
##########
@@ -356,97 +339,35 @@ class HoodieFileGroupReaderBasedFileFormat(tablePath: String,
     }
 
     val broadcastedStorageConf = spark.sparkContext.broadcast(new SerializableConfiguration(augmentedStorageConf.unwrap()))
-    val fileIndexProps: TypedProperties = HoodieFileIndex.getConfigProperties(spark, options, null)
+    val cdcProps: TypedProperties = HoodieFileIndex.getConfigProperties(spark, options, null)
+    cdcProps.setProperty(HoodieTableConfig.HOODIE_TABLE_NAME_KEY, tableName)

Review Comment:
   Why is this needed now?



##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/HoodieFileGroupReaderFunction.scala:
##########
@@ -0,0 +1,374 @@
+/*
+ * 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.datasources.parquet
+
+import org.apache.hudi.{HoodiePartitionCDCFileGroupMapping, HoodiePartitionFileSliceMapping, HoodieTableSchema, SparkAdapterSupport, SparkFileFormatInternalRowReaderContext}
+import org.apache.hudi.cdc.{CDCFileGroupIterator, HoodieCDCFileGroupSplit, HoodieCDCFileIndex}
+import org.apache.hudi.common.config.{HoodieReaderConfig, TypedProperties}
+import org.apache.hudi.common.fs.FSUtils
+import org.apache.hudi.common.schema.HoodieSchema
+import org.apache.hudi.common.schema.internal.InternalSchema
+import org.apache.hudi.common.table.{HoodieTableMetaClient, ParquetTableSchemaResolver}
+import org.apache.hudi.common.table.log.InstantRange
+import org.apache.hudi.common.table.read.{HoodieFileGroupReader, HoodieRecordReader}
+import org.apache.hudi.common.table.read.lsm.{HoodieLsmFileGroupReader, LsmReaderUtils}
+import org.apache.hudi.common.util.{ConfigUtils, Option => HOption}
+import org.apache.hudi.common.util.collection.ClosableIterator
+import org.apache.hudi.data.CloseableIteratorListener
+import org.apache.hudi.io.storage.HoodieSparkParquetReader.ENABLE_LOGICAL_TIMESTAMP_REPAIR
+import org.apache.hudi.io.storage.VectorConversionUtils
+import org.apache.hudi.storage.StorageConfiguration
+import org.apache.hudi.storage.hadoop.HadoopStorageConfiguration
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.parquet.schema.MessageType
+import org.apache.spark.SparkEnv
+import org.apache.spark.broadcast.Broadcast
+import org.apache.spark.sql.HoodieCatalystExpressionUtils.generateUnsafeProjection
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{JoinedRow, UnsafeProjection}
+import org.apache.spark.sql.execution.datasources.{PartitionedFile, SparkColumnarFileReader, SparkSchemaTransformUtils}
+import org.apache.spark.sql.sources.Filter
+import org.apache.spark.sql.types.StructType
+import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnarBatchUtils}
+import org.apache.spark.util.{SerializableConfiguration, Utils}
+
+import java.io.Closeable
+import java.nio.ByteBuffer
+
+import scala.collection.JavaConverters.mapAsJavaMapConverter
+import scala.reflect.ClassTag
+
+/**
+ * Read-only state of one scan of [[HoodieFileGroupReaderBasedFileFormat]], built on the driver and shared by every
+ * task of an executor through [[HoodieFileGroupReaderFunction]]. Executors only fill thread-safe lazy caches in it;
+ * per-file state such as reader properties is copied before use.
+ */
+private[parquet] class HoodieFileGroupReadState(val metaClient: HoodieTableMetaClient,
+                                                 val tableSchema: HoodieTableSchema,
+                                                 val queryTimestamp: String,
+                                                 val readerProps: TypedProperties,
+                                                 val cdcProps: TypedProperties,
+                                                 val dataSchema: HoodieSchema,
+                                                 val requestedSchema: HoodieSchema,
+                                                 val internalSchemaOpt: HOption[InternalSchema],
+                                                 val instantRangeOpt: HOption[InstantRange],
+                                                 val shouldUseRecordPosition: Boolean,
+                                                 val isCount: Boolean,
+                                                 val filters: Seq[Filter],
+                                                 val requiredFilters: Seq[Filter],
+                                                 val requiredSchema: StructType,
+                                                 val partitionSchema: StructType,
+                                                 val remainingPartitionSchema: StructType,
+                                                 val fixedPartitionIndexes: Set[Int],
+                                                 val outputSchema: StructType,
+                                                 val projectionInputSchema: StructType,
+                                                 val baseFileReadSchemas: BaseFileReadSchemas) extends Serializable {
+
+  /**
+   * Parquet form of the table schema for base file reads. The conversion reads Hadoop's default resources, so it is
+   * done once per executor rather than per task or file.
+   */
+  @transient lazy val tableSchemaAsMessageType: HOption[MessageType] =
+    HOption.ofNullable(ParquetTableSchemaResolver.convertAvroSchemaToParquet(tableSchema.schema, new Configuration()))
+}
+
+/**
+ * Base file read schemas with VECTOR columns rewritten to BinaryType, plus the ordinals of those columns.
+ */
+private[parquet] case class BaseFileReadSchemas(readRequiredSchema: StructType,
+                                                readVectorColumns: Map[Int, HoodieSchema.Vector],
+                                                outputSchema: StructType,
+                                                outputVectorColumns: Map[Int, HoodieSchema.Vector],
+                                                requestedSchema: StructType)
+
+/**
+ * Holds a value as Java-serialized bytes and deserializes it at most once per JVM instance of the holder.
+ *
+ * <p>Broadcasting this holder instead of the value keeps the broadcast independent of `spark.serializer`: Kryo
+ * would otherwise serialize the value field by field and ignore the custom Java serialization of types such as
+ * [[HoodieSchema]] and [[HadoopStorageConfiguration]].
+ */
+private[parquet] class JavaSerializedValue[T: ClassTag] private(bytes: Array[Byte]) extends Serializable {
+
+  @transient lazy val value: T = SparkEnv.get.closureSerializer.newInstance()
+    .deserialize[T](ByteBuffer.wrap(bytes), Utils.getContextOrSparkClassLoader)
+}
+
+private[parquet] object JavaSerializedValue {
+
+  def apply[T: ClassTag](value: T): JavaSerializedValue[T] = {
+    val buffer = SparkEnv.get.closureSerializer.newInstance().serialize(value)
+    val bytes = new Array[Byte](buffer.remaining())
+    buffer.get(bytes)
+    new JavaSerializedValue[T](bytes)
+  }
+}
+
+/**
+ * The per-file read function returned by [[HoodieFileGroupReaderBasedFileFormat.buildReaderWithPartitionValues]].
+ *
+ * <p>Spark deserializes this function once per task, so it holds only broadcast handles. The scan state behind
+ * `state` is deserialized once per executor.
+ */
+private[parquet] class HoodieFileGroupReaderFunction(baseFileReader: Broadcast[SparkColumnarFileReader],
+                                                     fileGroupBaseFileReader: Broadcast[SparkColumnarFileReader],
+                                                     storageConf: Broadcast[SerializableConfiguration],
+                                                     state: Broadcast[JavaSerializedValue[HoodieFileGroupReadState]])
+  extends (PartitionedFile => Iterator[InternalRow]) with Serializable {
+
+  import HoodieFileGroupReaderFunction._
+
+  private def sparkAdapter = SparkAdapterSupport.sparkAdapter
+
+  override def apply(file: PartitionedFile): Iterator[InternalRow] = {
+    val s = state.value.value
+    val conf = new HadoopStorageConfiguration(storageConf.value.value)
+    val iter = file.partitionValues match {
+      // Snapshot or incremental queries.
+      case fileSliceMapping: HoodiePartitionFileSliceMapping =>
+        val fileGroupName = FSUtils.getFileIdFromFilePath(sparkAdapter
+          .getSparkPartitionedFileUtils.getPathFromPartitionedFile(file))
+        fileSliceMapping.getSlice(fileGroupName) match {
+          case Some(fileSlice) if !s.isCount && (s.requiredSchema.nonEmpty || fileSlice.getLogFiles.findAny().isPresent) =>
+            val tableConfig = s.metaClient.getTableConfig
+            // requiredFilters preserve Spark's row-level filtering semantics, while instantRangeOpt
+            // keeps out-of-range records from participating in the file-group merge itself.
+            val readerContext = new SparkFileFormatInternalRowReaderContext(
+              fileGroupBaseFileReader.value, s.filters, s.requiredFilters, conf, tableConfig,
+              sparkRequiredSchema = Some(s.requiredSchema), instantRangeOpt = s.instantRangeOpt)
+            readerContext.enableLogicalTimestampFieldRepair(conf.getBoolean(ENABLE_LOGICAL_TIMESTAMP_REPAIR, true))
+            val props = TypedProperties.copy(s.readerProps)
+            val baseFileLength = if (fileSlice.getBaseFile.isPresent) {
+              fileSlice.getBaseFile.get.getFileSize
+            } else {
+              0
+            }
+            val reader: HoodieRecordReader[InternalRow] =
+              if (LsmReaderUtils.shouldUseLsmReader(
+                tableConfig,
+                ConfigUtils.getStringWithAltKeys(props, HoodieReaderConfig.MERGE_TYPE, true))) {
+                HoodieLsmFileGroupReader.builder[InternalRow]()
+                  .withReaderContext(readerContext)
+                  .withHoodieTableMetaClient(s.metaClient)
+                  .withLatestCommitTime(s.queryTimestamp)
+                  .withBaseFileOption(fileSlice.getBaseFile)
+                  .withLogFiles(fileSlice.getLogFiles)
+                  .withPartitionPath(fileSlice.getPartitionPath)
+                  .withDataSchema(s.dataSchema)
+                  .withRequestedSchema(s.requestedSchema)
+                  .withInternalSchemaOpt(s.internalSchemaOpt)
+                  .withProps(props)
+                  .withStart(file.start)
+                  .withLength(baseFileLength)
+                  .build()
+              } else {
+                HoodieFileGroupReader.builder[InternalRow]()
+                  .withReaderContext(readerContext)
+                  .withHoodieTableMetaClient(s.metaClient)
+                  .withLatestCommitTime(s.queryTimestamp)
+                  .withBaseFileOption(fileSlice.getBaseFile)
+                  .withLogFiles(fileSlice.getLogFiles)
+                  .withPartitionPath(fileSlice.getPartitionPath)
+                  .withDataSchema(s.dataSchema)
+                  .withRequestedSchema(s.requestedSchema)
+                  .withInternalSchemaOpt(s.internalSchemaOpt)
+                  .withProps(props)
+                  .withStart(file.start)
+                  .withLength(baseFileLength)
+                  .withShouldUseRecordPosition(s.shouldUseRecordPosition)
+                  .build()
+              }
+            // Append partition values to rows and project to output schema
+            appendPartitionAndProject(
+              reader.getClosableIterator,
+              s.projectionInputSchema,
+              s.remainingPartitionSchema,
+              s.outputSchema,
+              fileSliceMapping.getPartitionValues,
+              s.fixedPartitionIndexes)
+
+          case _ =>
+            readBaseFile(file, s, conf)
+        }
+      // CDC queries.
+      case cdcFileGroupMapping: HoodiePartitionCDCFileGroupMapping =>
+        new CDCFileGroupIterator(
+          HoodieCDCFileGroupSplit(cdcFileGroupMapping.getFileSplits().toArray),
+          s.metaClient,
+          conf,
+          fileGroupBaseFileReader.value,
+          s.tableSchema,
+          HoodieCDCFileIndex.FULL_CDC_SPARK_SCHEMA,
+          s.requiredSchema,
+          TypedProperties.copy(s.cdcProps))

Review Comment:
   Is the copy here still needed?



-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(spark): ship file group reader scan state once per executor [hudi]

Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #20077:
URL: https://github.com/apache/hudi/pull/20077#issuecomment-5961940418

   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "c20a93fef79c2f20dde27dfed4e9f55139aead64",
       "status" : "SUCCESS",
       "url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=17295",
       "triggerID" : "c20a93fef79c2f20dde27dfed4e9f55139aead64",
       "triggerType" : "PUSH"
     }, {
       "hash" : "e0e6f8f69682c1a4af2d88824d537c8e641f68ae",
       "status" : "PENDING",
       "url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=17426",
       "triggerID" : "e0e6f8f69682c1a4af2d88824d537c8e641f68ae",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * c20a93fef79c2f20dde27dfed4e9f55139aead64 Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=17295) 
   * e0e6f8f69682c1a4af2d88824d537c8e641f68ae Azure: [PENDING](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=17426) 
   
   <details>
   <summary>Bot commands</summary>
     @hudi-bot supports the following commands:
   
    - `@hudi-bot run azure` re-run the last Azure build
   </details>


-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(spark): ship file group reader scan state once per executor [hudi]

Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #20077:
URL: https://github.com/apache/hudi/pull/20077#issuecomment-5961847477

   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "c20a93fef79c2f20dde27dfed4e9f55139aead64",
       "status" : "SUCCESS",
       "url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=17295",
       "triggerID" : "c20a93fef79c2f20dde27dfed4e9f55139aead64",
       "triggerType" : "PUSH"
     }, {
       "hash" : "e0e6f8f69682c1a4af2d88824d537c8e641f68ae",
       "status" : "UNKNOWN",
       "url" : "TBD",
       "triggerID" : "e0e6f8f69682c1a4af2d88824d537c8e641f68ae",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * c20a93fef79c2f20dde27dfed4e9f55139aead64 Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=17295) 
   * e0e6f8f69682c1a4af2d88824d537c8e641f68ae UNKNOWN
   
   <details>
   <summary>Bot commands</summary>
     @hudi-bot supports the following commands:
   
    - `@hudi-bot run azure` re-run the last Azure build
   </details>


-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(spark): ship file group reader scan state once per executor [hudi]

Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #20077:
URL: https://github.com/apache/hudi/pull/20077#issuecomment-5851218723

   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "c20a93fef79c2f20dde27dfed4e9f55139aead64",
       "status" : "SUCCESS",
       "url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=17295",
       "triggerID" : "c20a93fef79c2f20dde27dfed4e9f55139aead64",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * c20a93fef79c2f20dde27dfed4e9f55139aead64 Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=17295) 
   
   <details>
   <summary>Bot commands</summary>
     @hudi-bot supports the following commands:
   
    - `@hudi-bot run azure` re-run the last Azure build
   </details>


-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(spark): ship file group reader scan state once per executor [hudi]

Posted by "voonhous (via GitHub)" <gi...@apache.org>.
voonhous commented on PR #20077:
URL: https://github.com/apache/hudi/pull/20077#issuecomment-5978428479

   No comments on this PR. Agree with @nsivabalan's comments. Address those and we should be good.


-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(spark): ship file group reader scan state once per executor [hudi]

Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #20077:
URL: https://github.com/apache/hudi/pull/20077#issuecomment-5850109556

   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "c20a93fef79c2f20dde27dfed4e9f55139aead64",
       "status" : "PENDING",
       "url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=17295",
       "triggerID" : "c20a93fef79c2f20dde27dfed4e9f55139aead64",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * c20a93fef79c2f20dde27dfed4e9f55139aead64 Azure: [PENDING](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=17295) 
   
   <details>
   <summary>Bot commands</summary>
     @hudi-bot supports the following commands:
   
    - `@hudi-bot run azure` re-run the last Azure build
   </details>


-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(spark): ship file group reader scan state once per executor [hudi]

Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #20077:
URL: https://github.com/apache/hudi/pull/20077#issuecomment-5850063541

   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "c20a93fef79c2f20dde27dfed4e9f55139aead64",
       "status" : "UNKNOWN",
       "url" : "TBD",
       "triggerID" : "c20a93fef79c2f20dde27dfed4e9f55139aead64",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * c20a93fef79c2f20dde27dfed4e9f55139aead64 UNKNOWN
   
   <details>
   <summary>Bot commands</summary>
     @hudi-bot supports the following commands:
   
    - `@hudi-bot run azure` re-run the last Azure build
   </details>


-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(spark): ship file group reader scan state once per executor [hudi]

Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua commented on code in PR #20077:
URL: https://github.com/apache/hudi/pull/20077#discussion_r4187801048


##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/HoodieFileGroupReaderFunction.scala:
##########
@@ -0,0 +1,376 @@
+/*
+ * 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.datasources.parquet
+
+import org.apache.hudi.{HoodiePartitionCDCFileGroupMapping, HoodiePartitionFileSliceMapping, HoodieTableSchema, SparkAdapterSupport, SparkFileFormatInternalRowReaderContext}
+import org.apache.hudi.cdc.{CDCFileGroupIterator, HoodieCDCFileGroupSplit, HoodieCDCFileIndex}
+import org.apache.hudi.common.config.{HoodieReaderConfig, TypedProperties}
+import org.apache.hudi.common.fs.FSUtils
+import org.apache.hudi.common.schema.HoodieSchema
+import org.apache.hudi.common.schema.internal.InternalSchema
+import org.apache.hudi.common.table.{HoodieTableMetaClient, ParquetTableSchemaResolver}
+import org.apache.hudi.common.table.log.InstantRange
+import org.apache.hudi.common.table.read.{HoodieFileGroupReader, HoodieRecordReader}
+import org.apache.hudi.common.table.read.lsm.{HoodieLsmFileGroupReader, LsmReaderUtils}
+import org.apache.hudi.common.util.{ConfigUtils, Option => HOption}
+import org.apache.hudi.common.util.collection.ClosableIterator
+import org.apache.hudi.data.CloseableIteratorListener
+import org.apache.hudi.io.storage.HoodieSparkParquetReader.ENABLE_LOGICAL_TIMESTAMP_REPAIR
+import org.apache.hudi.io.storage.VectorConversionUtils
+import org.apache.hudi.storage.StorageConfiguration
+import org.apache.hudi.storage.hadoop.HadoopStorageConfiguration
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.parquet.schema.MessageType
+import org.apache.spark.SparkEnv
+import org.apache.spark.broadcast.Broadcast
+import org.apache.spark.sql.HoodieCatalystExpressionUtils.generateUnsafeProjection
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{JoinedRow, UnsafeProjection}
+import org.apache.spark.sql.execution.datasources.{PartitionedFile, SparkColumnarFileReader, SparkSchemaTransformUtils}
+import org.apache.spark.sql.sources.Filter
+import org.apache.spark.sql.types.StructType
+import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnarBatchUtils}
+import org.apache.spark.util.{SerializableConfiguration, Utils}
+
+import java.io.Closeable
+import java.nio.ByteBuffer
+
+import scala.collection.JavaConverters.mapAsJavaMapConverter
+import scala.reflect.ClassTag
+
+/**
+ * Read-only state of one scan of [[HoodieFileGroupReaderBasedFileFormat]], built on the driver and shared by every
+ * task of an executor through [[HoodieFileGroupReaderFunction]]. Executors only fill thread-safe lazy caches in it;

Review Comment:
   `getStorage()` is only used as a factory here (`getStorage().newInstance(...)` per file) and `HoodieHadoopStorage` has final fields, so a race at worst builds one extra wrapper. #20078, stacked on this PR, replaces the meta client in the broadcast state with `FileGroupReaderTableState`, so this call goes away there. The `InternalSchema` caches are not new exposure: `InternalSchemaCache` already shares instances across concurrent tasks, and #20078 makes all four maps volatile.



##########
hudi-common/src/main/java/org/apache/hudi/common/table/HoodieTableMetaClient.java:
##########
@@ -388,6 +389,7 @@ private void readObject(java.io.ObjectInputStream in) throws IOException, ClassN
     in.defaultReadObject();
 
     storage = null; // will be lazily initialized

Review Comment:
   Same as above: the call is factory-only, and #20078 drops the meta client from the Spark reader path.



##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/HoodieFileGroupReaderBasedFileFormat.scala:
##########
@@ -356,97 +339,35 @@ class HoodieFileGroupReaderBasedFileFormat(tablePath: String,
     }
 
     val broadcastedStorageConf = spark.sparkContext.broadcast(new SerializableConfiguration(augmentedStorageConf.unwrap()))
-    val fileIndexProps: TypedProperties = HoodieFileIndex.getConfigProperties(spark, options, null)
+    val cdcProps: TypedProperties = HoodieFileIndex.getConfigProperties(spark, options, null)
+    cdcProps.setProperty(HoodieTableConfig.HOODIE_TABLE_NAME_KEY, tableName)
 
     val engineContext = new HoodieSparkEngineContext(new JavaSparkContext(spark.sparkContext))
     val maxMemoryPerCompaction = MergeUtils.getMaxMemoryPerCompaction(engineContext.getTaskContextSupplier, options.asJava)
 
-    // Create metaclient on driver to avoid expensive operations on executors
-    val metaClient: HoodieTableMetaClient = HoodieTableMetaClient
-      .builder().setConf(augmentedStorageConf).setBasePath(tablePath).build
-
-    (file: PartitionedFile) => {
-      // executor
-      val storageConf = new HadoopStorageConfiguration(broadcastedStorageConf.value.value)
-      val iter = file.partitionValues match {
-        // Snapshot or incremental queries.
-        case fileSliceMapping: HoodiePartitionFileSliceMapping =>
-          val fileGroupName = FSUtils.getFileIdFromFilePath(sparkAdapter
-            .getSparkPartitionedFileUtils.getPathFromPartitionedFile(file))
-          fileSliceMapping.getSlice(fileGroupName) match {
-            case Some(fileSlice) if !isCount && (requiredSchema.nonEmpty || fileSlice.getLogFiles.findAny().isPresent) =>
-              // requiredFilters preserve Spark's row-level filtering semantics, while instantRangeOpt
-              // keeps out-of-range records from participating in the file-group merge itself.
-              val readerContext = new SparkFileFormatInternalRowReaderContext(
-                fileGroupBaseFileReader.value, filters, requiredFilters, storageConf, metaClient.getTableConfig,
-                sparkRequiredSchema = Some(requiredSchema), instantRangeOpt = instantRangeOpt)
-              readerContext.enableLogicalTimestampFieldRepair(storageConf.getBoolean(ENABLE_LOGICAL_TIMESTAMP_REPAIR, true))
-              val props = metaClient.getTableConfig.getProps
-              options.foreach(kv => props.setProperty(kv._1, kv._2))
-              props.put(HoodieMemoryConfig.MAX_MEMORY_FOR_MERGE.key(), String.valueOf(maxMemoryPerCompaction))
-              val baseFileLength = if (fileSlice.getBaseFile.isPresent) {
-                fileSlice.getBaseFile.get.getFileSize
-              } else {
-                0
-              }
-              val reader: HoodieRecordReader[InternalRow] =
-                if (LsmReaderUtils.shouldUseLsmReader(
-                  metaClient.getTableConfig,
-                  ConfigUtils.getStringWithAltKeys(props, HoodieReaderConfig.MERGE_TYPE, true))) {
-                  HoodieLsmFileGroupReader.builder[InternalRow]()
-                    .withReaderContext(readerContext)
-                    .withHoodieTableMetaClient(metaClient)
-                    .withLatestCommitTime(queryTimestamp)
-                    .withBaseFileOption(fileSlice.getBaseFile)
-                    .withLogFiles(fileSlice.getLogFiles)
-                    .withPartitionPath(fileSlice.getPartitionPath)
-                    .withDataSchema(dataSchema)
-                    .withRequestedSchema(requestedSchema)
-                    .withInternalSchemaOpt(internalSchemaOpt)
-                    .withProps(props)
-                    .withStart(file.start)
-                    .withLength(baseFileLength)
-                    .build()
-                } else {
-                  HoodieFileGroupReader.builder[InternalRow]()
-                    .withReaderContext(readerContext)
-                    .withHoodieTableMetaClient(metaClient)
-                    .withLatestCommitTime(queryTimestamp)
-                    .withBaseFileOption(fileSlice.getBaseFile)
-                    .withLogFiles(fileSlice.getLogFiles)
-                    .withPartitionPath(fileSlice.getPartitionPath)
-                    .withDataSchema(dataSchema)
-                    .withRequestedSchema(requestedSchema)
-                    .withInternalSchemaOpt(internalSchemaOpt)
-                    .withProps(props)
-                    .withStart(file.start)
-                    .withLength(baseFileLength)
-                    .withShouldUseRecordPosition(shouldUseRecordPosition)
-                    .build()
-                }
-              // Append partition values to rows and project to output schema
-              appendPartitionAndProject(
-                reader.getClosableIterator,
-                projectionInputSchema,
-                remainingPartitionSchema,
-                outputSchema,
-                fileSliceMapping.getPartitionValues,
-                fixedPartitionIndexes)
-
-            case _ =>
-              readBaseFile(file, baseFileReader.value, requestedStructType, remainingPartitionSchema, fixedPartitionIndexes,
-                readRequiredSchema, partitionSchema, outputSchema, filters ++ requiredFilters, storageConf)
-          }
-        // CDC queries.
-        case hoodiePartitionCDCFileGroupSliceMapping: HoodiePartitionCDCFileGroupMapping =>
-          buildCDCRecordIterator(hoodiePartitionCDCFileGroupSliceMapping, fileGroupBaseFileReader.value, storageConf, fileIndexProps, requiredSchema, metaClient)
-
-        case _ =>
-          readBaseFile(file, baseFileReader.value, requestedStructType, remainingPartitionSchema, fixedPartitionIndexes,
-            readRequiredSchema, partitionSchema, outputSchema, filters ++ requiredFilters, storageConf)
-      }
-      CloseableIteratorListener.addListener(iter)
+    // The relation's meta client carries the timeline the scan was planned against; build one only when the

Review Comment:
   Added it to the description. Yes, the relation factory passes the same meta client to `HoodieFileIndex`, and `refresh()` calls `reloadActiveTimeline()` on it, so the next execution ships the reloaded timeline.



##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/HoodieFileGroupReaderBasedFileFormat.scala:
##########
@@ -356,97 +339,35 @@ class HoodieFileGroupReaderBasedFileFormat(tablePath: String,
     }
 
     val broadcastedStorageConf = spark.sparkContext.broadcast(new SerializableConfiguration(augmentedStorageConf.unwrap()))
-    val fileIndexProps: TypedProperties = HoodieFileIndex.getConfigProperties(spark, options, null)
+    val cdcProps: TypedProperties = HoodieFileIndex.getConfigProperties(spark, options, null)
+    cdcProps.setProperty(HoodieTableConfig.HOODIE_TABLE_NAME_KEY, tableName)
 
     val engineContext = new HoodieSparkEngineContext(new JavaSparkContext(spark.sparkContext))
     val maxMemoryPerCompaction = MergeUtils.getMaxMemoryPerCompaction(engineContext.getTaskContextSupplier, options.asJava)
 
-    // Create metaclient on driver to avoid expensive operations on executors
-    val metaClient: HoodieTableMetaClient = HoodieTableMetaClient
-      .builder().setConf(augmentedStorageConf).setBasePath(tablePath).build
-
-    (file: PartitionedFile) => {
-      // executor
-      val storageConf = new HadoopStorageConfiguration(broadcastedStorageConf.value.value)
-      val iter = file.partitionValues match {
-        // Snapshot or incremental queries.
-        case fileSliceMapping: HoodiePartitionFileSliceMapping =>
-          val fileGroupName = FSUtils.getFileIdFromFilePath(sparkAdapter
-            .getSparkPartitionedFileUtils.getPathFromPartitionedFile(file))
-          fileSliceMapping.getSlice(fileGroupName) match {
-            case Some(fileSlice) if !isCount && (requiredSchema.nonEmpty || fileSlice.getLogFiles.findAny().isPresent) =>
-              // requiredFilters preserve Spark's row-level filtering semantics, while instantRangeOpt
-              // keeps out-of-range records from participating in the file-group merge itself.
-              val readerContext = new SparkFileFormatInternalRowReaderContext(
-                fileGroupBaseFileReader.value, filters, requiredFilters, storageConf, metaClient.getTableConfig,
-                sparkRequiredSchema = Some(requiredSchema), instantRangeOpt = instantRangeOpt)
-              readerContext.enableLogicalTimestampFieldRepair(storageConf.getBoolean(ENABLE_LOGICAL_TIMESTAMP_REPAIR, true))
-              val props = metaClient.getTableConfig.getProps
-              options.foreach(kv => props.setProperty(kv._1, kv._2))
-              props.put(HoodieMemoryConfig.MAX_MEMORY_FOR_MERGE.key(), String.valueOf(maxMemoryPerCompaction))
-              val baseFileLength = if (fileSlice.getBaseFile.isPresent) {
-                fileSlice.getBaseFile.get.getFileSize
-              } else {
-                0
-              }
-              val reader: HoodieRecordReader[InternalRow] =
-                if (LsmReaderUtils.shouldUseLsmReader(
-                  metaClient.getTableConfig,
-                  ConfigUtils.getStringWithAltKeys(props, HoodieReaderConfig.MERGE_TYPE, true))) {
-                  HoodieLsmFileGroupReader.builder[InternalRow]()
-                    .withReaderContext(readerContext)
-                    .withHoodieTableMetaClient(metaClient)
-                    .withLatestCommitTime(queryTimestamp)
-                    .withBaseFileOption(fileSlice.getBaseFile)
-                    .withLogFiles(fileSlice.getLogFiles)
-                    .withPartitionPath(fileSlice.getPartitionPath)
-                    .withDataSchema(dataSchema)
-                    .withRequestedSchema(requestedSchema)
-                    .withInternalSchemaOpt(internalSchemaOpt)
-                    .withProps(props)
-                    .withStart(file.start)
-                    .withLength(baseFileLength)
-                    .build()
-                } else {
-                  HoodieFileGroupReader.builder[InternalRow]()
-                    .withReaderContext(readerContext)
-                    .withHoodieTableMetaClient(metaClient)
-                    .withLatestCommitTime(queryTimestamp)
-                    .withBaseFileOption(fileSlice.getBaseFile)
-                    .withLogFiles(fileSlice.getLogFiles)
-                    .withPartitionPath(fileSlice.getPartitionPath)
-                    .withDataSchema(dataSchema)
-                    .withRequestedSchema(requestedSchema)
-                    .withInternalSchemaOpt(internalSchemaOpt)
-                    .withProps(props)
-                    .withStart(file.start)
-                    .withLength(baseFileLength)
-                    .withShouldUseRecordPosition(shouldUseRecordPosition)
-                    .build()
-                }
-              // Append partition values to rows and project to output schema
-              appendPartitionAndProject(
-                reader.getClosableIterator,
-                projectionInputSchema,
-                remainingPartitionSchema,
-                outputSchema,
-                fileSliceMapping.getPartitionValues,
-                fixedPartitionIndexes)
-
-            case _ =>
-              readBaseFile(file, baseFileReader.value, requestedStructType, remainingPartitionSchema, fixedPartitionIndexes,
-                readRequiredSchema, partitionSchema, outputSchema, filters ++ requiredFilters, storageConf)
-          }
-        // CDC queries.
-        case hoodiePartitionCDCFileGroupSliceMapping: HoodiePartitionCDCFileGroupMapping =>
-          buildCDCRecordIterator(hoodiePartitionCDCFileGroupSliceMapping, fileGroupBaseFileReader.value, storageConf, fileIndexProps, requiredSchema, metaClient)
-
-        case _ =>
-          readBaseFile(file, baseFileReader.value, requestedStructType, remainingPartitionSchema, fixedPartitionIndexes,
-            readRequiredSchema, partitionSchema, outputSchema, filters ++ requiredFilters, storageConf)
-      }
-      CloseableIteratorListener.addListener(iter)
+    // The relation's meta client carries the timeline the scan was planned against; build one only when the
+    // format is used without a relation. The field is null rather than None on a deserialized format.
+    val metaClient: HoodieTableMetaClient = Option(tableMetaClient).flatten.getOrElse(HoodieTableMetaClient
+      .builder().setConf(augmentedStorageConf).setBasePath(tablePath).build)
+    val readerProps = TypedProperties.copy(metaClient.getTableConfig.getProps)
+    options.foreach(kv => readerProps.setProperty(kv._1, kv._2))

Review Comment:
   The override was a bug whose result could depend on file order, so I would rather not keep a path for it. It is called out as a behavior change in the description and release notes.



-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(spark): ship file group reader scan state once per executor [hudi]

Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #20077:
URL: https://github.com/apache/hudi/pull/20077#issuecomment-5850122037

   ## [Codecov](https://app.codecov.io/gh/apache/hudi/pull/20077?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :white_check_mark: All modified and coverable lines are covered by tests.
   :white_check_mark: Project coverage is 80.38%. Comparing base ([`463b615`](https://app.codecov.io/gh/apache/hudi/commit/463b6159fe7fae8f9132acda3f473233fd265a5d?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`c20a93f`](https://app.codecov.io/gh/apache/hudi/commit/c20a93fef79c2f20dde27dfed4e9f55139aead64?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 1 commits behind head on master.
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@             Coverage Diff              @@
   ##             master   #20077      +/-   ##
   ============================================
   - Coverage     80.40%   80.38%   -0.03%     
   - Complexity    34863    34889      +26     
   ============================================
     Files          2546     2546              
     Lines        142888   142901      +13     
     Branches      17373    17386      +13     
   ============================================
   - Hits         114891   114868      -23     
   - Misses        20079    20118      +39     
   + Partials       7918     7915       -3     
   ```
   
   | [Components](https://app.codecov.io/gh/apache/hudi/pull/20077/components?src=pr&el=components&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [hudi-common](https://app.codecov.io/gh/apache/hudi/pull/20077/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `83.90% <ø> (-0.07%)` | :arrow_down: |
   | [hudi-client](https://app.codecov.io/gh/apache/hudi/pull/20077/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `83.46% <ø> (+<0.01%)` | :arrow_up: |
   | [hudi-flink](https://app.codecov.io/gh/apache/hudi/pull/20077/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `85.73% <ø> (ø)` | |
   | [hudi-spark-datasource](https://app.codecov.io/gh/apache/hudi/pull/20077/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `73.71% <ø> (-0.14%)` | :arrow_down: |
   | [hudi-utilities](https://app.codecov.io/gh/apache/hudi/pull/20077/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `78.17% <ø> (ø)` | |
   | [hudi-cli](https://app.codecov.io/gh/apache/hudi/pull/20077/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `69.87% <ø> (ø)` | |
   | [hudi-hadoop](https://app.codecov.io/gh/apache/hudi/pull/20077/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `70.98% <ø> (ø)` | |
   | [hudi-sync](https://app.codecov.io/gh/apache/hudi/pull/20077/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `76.02% <ø> (ø)` | |
   | [hudi-io](https://app.codecov.io/gh/apache/hudi/pull/20077/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `81.53% <ø> (ø)` | |
   | [hudi-timeline-service](https://app.codecov.io/gh/apache/hudi/pull/20077/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `83.06% <ø> (ø)` | |
   | [hudi-cloud](https://app.codecov.io/gh/apache/hudi/pull/20077/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `81.00% <ø> (ø)` | |
   | [hudi-kafka-connect](https://app.codecov.io/gh/apache/hudi/pull/20077/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `53.96% <ø> (ø)` | |
   
   | [Flag](https://app.codecov.io/gh/apache/hudi/pull/20077/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [hadoop-mr-java-client](https://app.codecov.io/gh/apache/hudi/pull/20077/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `43.98% <ø> (-0.01%)` | :arrow_down: |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/hudi/pull/20077?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [...rg/apache/hudi/HoodieHadoopFsRelationFactory.scala](https://app.codecov.io/gh/apache/hudi/pull/20077?src=pr&el=tree&filepath=hudi-spark-datasource%2Fhudi-spark-common%2Fsrc%2Fmain%2Fscala%2Forg%2Fapache%2Fhudi%2FHoodieHadoopFsRelationFactory.scala&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-aHVkaS1zcGFyay1kYXRhc291cmNlL2h1ZGktc3BhcmstY29tbW9uL3NyYy9tYWluL3NjYWxhL29yZy9hcGFjaGUvaHVkaS9Ib29kaWVIYWRvb3BGc1JlbGF0aW9uRmFjdG9yeS5zY2FsYQ==) | `82.85% <ø> (-0.07%)` | :arrow_down: |
   | [...parquet/HoodieFileGroupReaderBasedFileFormat.scala](https://app.codecov.io/gh/apache/hudi/pull/20077?src=pr&el=tree&filepath=hudi-spark-datasource%2Fhudi-spark-common%2Fsrc%2Fmain%2Fscala%2Forg%2Fapache%2Fspark%2Fsql%2Fexecution%2Fdatasources%2Fparquet%2FHoodieFileGroupReaderBasedFileFormat.scala&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-aHVkaS1zcGFyay1kYXRhc291cmNlL2h1ZGktc3BhcmstY29tbW9uL3NyYy9tYWluL3NjYWxhL29yZy9hcGFjaGUvc3Bhcmsvc3FsL2V4ZWN1dGlvbi9kYXRhc291cmNlcy9wYXJxdWV0L0hvb2RpZUZpbGVHcm91cFJlYWRlckJhc2VkRmlsZUZvcm1hdC5zY2FsYQ==) | `75.47% <ø> (-8.89%)` | :arrow_down: |
   
   ... and [2 files with indirect coverage changes](https://app.codecov.io/gh/apache/hudi/pull/20077/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)
   </details>
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(spark): ship file group reader scan state once per executor [hudi]

Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua commented on code in PR #20077:
URL: https://github.com/apache/hudi/pull/20077#discussion_r4169894931


##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/HoodieFileGroupReaderFunction.scala:
##########
@@ -0,0 +1,374 @@
+/*
+ * 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.datasources.parquet
+
+import org.apache.hudi.{HoodiePartitionCDCFileGroupMapping, HoodiePartitionFileSliceMapping, HoodieTableSchema, SparkAdapterSupport, SparkFileFormatInternalRowReaderContext}
+import org.apache.hudi.cdc.{CDCFileGroupIterator, HoodieCDCFileGroupSplit, HoodieCDCFileIndex}
+import org.apache.hudi.common.config.{HoodieReaderConfig, TypedProperties}
+import org.apache.hudi.common.fs.FSUtils
+import org.apache.hudi.common.schema.HoodieSchema
+import org.apache.hudi.common.schema.internal.InternalSchema
+import org.apache.hudi.common.table.{HoodieTableMetaClient, ParquetTableSchemaResolver}
+import org.apache.hudi.common.table.log.InstantRange
+import org.apache.hudi.common.table.read.{HoodieFileGroupReader, HoodieRecordReader}
+import org.apache.hudi.common.table.read.lsm.{HoodieLsmFileGroupReader, LsmReaderUtils}
+import org.apache.hudi.common.util.{ConfigUtils, Option => HOption}
+import org.apache.hudi.common.util.collection.ClosableIterator
+import org.apache.hudi.data.CloseableIteratorListener
+import org.apache.hudi.io.storage.HoodieSparkParquetReader.ENABLE_LOGICAL_TIMESTAMP_REPAIR
+import org.apache.hudi.io.storage.VectorConversionUtils
+import org.apache.hudi.storage.StorageConfiguration
+import org.apache.hudi.storage.hadoop.HadoopStorageConfiguration
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.parquet.schema.MessageType
+import org.apache.spark.SparkEnv
+import org.apache.spark.broadcast.Broadcast
+import org.apache.spark.sql.HoodieCatalystExpressionUtils.generateUnsafeProjection
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{JoinedRow, UnsafeProjection}
+import org.apache.spark.sql.execution.datasources.{PartitionedFile, SparkColumnarFileReader, SparkSchemaTransformUtils}
+import org.apache.spark.sql.sources.Filter
+import org.apache.spark.sql.types.StructType
+import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnarBatchUtils}
+import org.apache.spark.util.{SerializableConfiguration, Utils}
+
+import java.io.Closeable
+import java.nio.ByteBuffer
+
+import scala.collection.JavaConverters.mapAsJavaMapConverter
+import scala.reflect.ClassTag
+
+/**
+ * Read-only state of one scan of [[HoodieFileGroupReaderBasedFileFormat]], built on the driver and shared by every
+ * task of an executor through [[HoodieFileGroupReaderFunction]]. Executors only fill thread-safe lazy caches in it;
+ * per-file state such as reader properties is copied before use.
+ */
+private[parquet] class HoodieFileGroupReadState(val metaClient: HoodieTableMetaClient,
+                                                 val tableSchema: HoodieTableSchema,
+                                                 val queryTimestamp: String,
+                                                 val readerProps: TypedProperties,
+                                                 val cdcProps: TypedProperties,
+                                                 val dataSchema: HoodieSchema,
+                                                 val requestedSchema: HoodieSchema,
+                                                 val internalSchemaOpt: HOption[InternalSchema],
+                                                 val instantRangeOpt: HOption[InstantRange],
+                                                 val shouldUseRecordPosition: Boolean,
+                                                 val isCount: Boolean,
+                                                 val filters: Seq[Filter],
+                                                 val requiredFilters: Seq[Filter],
+                                                 val requiredSchema: StructType,
+                                                 val partitionSchema: StructType,
+                                                 val remainingPartitionSchema: StructType,
+                                                 val fixedPartitionIndexes: Set[Int],
+                                                 val outputSchema: StructType,
+                                                 val projectionInputSchema: StructType,
+                                                 val baseFileReadSchemas: BaseFileReadSchemas) extends Serializable {
+
+  /**
+   * Parquet form of the table schema for base file reads. The conversion reads Hadoop's default resources, so it is
+   * done once per executor rather than per task or file.
+   */
+  @transient lazy val tableSchemaAsMessageType: HOption[MessageType] =
+    HOption.ofNullable(ParquetTableSchemaResolver.convertAvroSchemaToParquet(tableSchema.schema, new Configuration()))
+}
+
+/**
+ * Base file read schemas with VECTOR columns rewritten to BinaryType, plus the ordinals of those columns.
+ */
+private[parquet] case class BaseFileReadSchemas(readRequiredSchema: StructType,
+                                                readVectorColumns: Map[Int, HoodieSchema.Vector],
+                                                outputSchema: StructType,
+                                                outputVectorColumns: Map[Int, HoodieSchema.Vector],
+                                                requestedSchema: StructType)
+
+/**
+ * Holds a value as Java-serialized bytes and deserializes it at most once per JVM instance of the holder.
+ *
+ * <p>Broadcasting this holder instead of the value keeps the broadcast independent of `spark.serializer`: Kryo
+ * would otherwise serialize the value field by field and ignore the custom Java serialization of types such as
+ * [[HoodieSchema]] and [[HadoopStorageConfiguration]].
+ */
+private[parquet] class JavaSerializedValue[T: ClassTag] private(bytes: Array[Byte]) extends Serializable {
+
+  @transient lazy val value: T = SparkEnv.get.closureSerializer.newInstance()
+    .deserialize[T](ByteBuffer.wrap(bytes), Utils.getContextOrSparkClassLoader)
+}
+
+private[parquet] object JavaSerializedValue {
+
+  def apply[T: ClassTag](value: T): JavaSerializedValue[T] = {
+    val buffer = SparkEnv.get.closureSerializer.newInstance().serialize(value)
+    val bytes = new Array[Byte](buffer.remaining())
+    buffer.get(bytes)
+    new JavaSerializedValue[T](bytes)
+  }
+}
+
+/**
+ * The per-file read function returned by [[HoodieFileGroupReaderBasedFileFormat.buildReaderWithPartitionValues]].
+ *
+ * <p>Spark deserializes this function once per task, so it holds only broadcast handles. The scan state behind
+ * `state` is deserialized once per executor.
+ */
+private[parquet] class HoodieFileGroupReaderFunction(baseFileReader: Broadcast[SparkColumnarFileReader],
+                                                     fileGroupBaseFileReader: Broadcast[SparkColumnarFileReader],
+                                                     storageConf: Broadcast[SerializableConfiguration],
+                                                     state: Broadcast[JavaSerializedValue[HoodieFileGroupReadState]])

Review Comment:
   Done, renamed to broadcastedState.



##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/HoodieFileGroupReaderFunction.scala:
##########
@@ -0,0 +1,374 @@
+/*
+ * 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.datasources.parquet
+
+import org.apache.hudi.{HoodiePartitionCDCFileGroupMapping, HoodiePartitionFileSliceMapping, HoodieTableSchema, SparkAdapterSupport, SparkFileFormatInternalRowReaderContext}
+import org.apache.hudi.cdc.{CDCFileGroupIterator, HoodieCDCFileGroupSplit, HoodieCDCFileIndex}
+import org.apache.hudi.common.config.{HoodieReaderConfig, TypedProperties}
+import org.apache.hudi.common.fs.FSUtils
+import org.apache.hudi.common.schema.HoodieSchema
+import org.apache.hudi.common.schema.internal.InternalSchema
+import org.apache.hudi.common.table.{HoodieTableMetaClient, ParquetTableSchemaResolver}
+import org.apache.hudi.common.table.log.InstantRange
+import org.apache.hudi.common.table.read.{HoodieFileGroupReader, HoodieRecordReader}
+import org.apache.hudi.common.table.read.lsm.{HoodieLsmFileGroupReader, LsmReaderUtils}
+import org.apache.hudi.common.util.{ConfigUtils, Option => HOption}
+import org.apache.hudi.common.util.collection.ClosableIterator
+import org.apache.hudi.data.CloseableIteratorListener
+import org.apache.hudi.io.storage.HoodieSparkParquetReader.ENABLE_LOGICAL_TIMESTAMP_REPAIR
+import org.apache.hudi.io.storage.VectorConversionUtils
+import org.apache.hudi.storage.StorageConfiguration
+import org.apache.hudi.storage.hadoop.HadoopStorageConfiguration
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.parquet.schema.MessageType
+import org.apache.spark.SparkEnv
+import org.apache.spark.broadcast.Broadcast
+import org.apache.spark.sql.HoodieCatalystExpressionUtils.generateUnsafeProjection
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{JoinedRow, UnsafeProjection}
+import org.apache.spark.sql.execution.datasources.{PartitionedFile, SparkColumnarFileReader, SparkSchemaTransformUtils}
+import org.apache.spark.sql.sources.Filter
+import org.apache.spark.sql.types.StructType
+import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnarBatchUtils}
+import org.apache.spark.util.{SerializableConfiguration, Utils}
+
+import java.io.Closeable
+import java.nio.ByteBuffer
+
+import scala.collection.JavaConverters.mapAsJavaMapConverter
+import scala.reflect.ClassTag
+
+/**
+ * Read-only state of one scan of [[HoodieFileGroupReaderBasedFileFormat]], built on the driver and shared by every
+ * task of an executor through [[HoodieFileGroupReaderFunction]]. Executors only fill thread-safe lazy caches in it;
+ * per-file state such as reader properties is copied before use.
+ */
+private[parquet] class HoodieFileGroupReadState(val metaClient: HoodieTableMetaClient,
+                                                 val tableSchema: HoodieTableSchema,
+                                                 val queryTimestamp: String,
+                                                 val readerProps: TypedProperties,
+                                                 val cdcProps: TypedProperties,
+                                                 val dataSchema: HoodieSchema,
+                                                 val requestedSchema: HoodieSchema,
+                                                 val internalSchemaOpt: HOption[InternalSchema],
+                                                 val instantRangeOpt: HOption[InstantRange],
+                                                 val shouldUseRecordPosition: Boolean,
+                                                 val isCount: Boolean,
+                                                 val filters: Seq[Filter],
+                                                 val requiredFilters: Seq[Filter],
+                                                 val requiredSchema: StructType,
+                                                 val partitionSchema: StructType,
+                                                 val remainingPartitionSchema: StructType,
+                                                 val fixedPartitionIndexes: Set[Int],
+                                                 val outputSchema: StructType,
+                                                 val projectionInputSchema: StructType,
+                                                 val baseFileReadSchemas: BaseFileReadSchemas) extends Serializable {
+
+  /**
+   * Parquet form of the table schema for base file reads. The conversion reads Hadoop's default resources, so it is
+   * done once per executor rather than per task or file.
+   */
+  @transient lazy val tableSchemaAsMessageType: HOption[MessageType] =
+    HOption.ofNullable(ParquetTableSchemaResolver.convertAvroSchemaToParquet(tableSchema.schema, new Configuration()))
+}
+
+/**
+ * Base file read schemas with VECTOR columns rewritten to BinaryType, plus the ordinals of those columns.
+ */
+private[parquet] case class BaseFileReadSchemas(readRequiredSchema: StructType,
+                                                readVectorColumns: Map[Int, HoodieSchema.Vector],
+                                                outputSchema: StructType,
+                                                outputVectorColumns: Map[Int, HoodieSchema.Vector],
+                                                requestedSchema: StructType)
+
+/**
+ * Holds a value as Java-serialized bytes and deserializes it at most once per JVM instance of the holder.
+ *
+ * <p>Broadcasting this holder instead of the value keeps the broadcast independent of `spark.serializer`: Kryo
+ * would otherwise serialize the value field by field and ignore the custom Java serialization of types such as
+ * [[HoodieSchema]] and [[HadoopStorageConfiguration]].
+ */
+private[parquet] class JavaSerializedValue[T: ClassTag] private(bytes: Array[Byte]) extends Serializable {
+
+  @transient lazy val value: T = SparkEnv.get.closureSerializer.newInstance()
+    .deserialize[T](ByteBuffer.wrap(bytes), Utils.getContextOrSparkClassLoader)
+}
+
+private[parquet] object JavaSerializedValue {
+
+  def apply[T: ClassTag](value: T): JavaSerializedValue[T] = {
+    val buffer = SparkEnv.get.closureSerializer.newInstance().serialize(value)
+    val bytes = new Array[Byte](buffer.remaining())
+    buffer.get(bytes)
+    new JavaSerializedValue[T](bytes)
+  }
+}
+
+/**
+ * The per-file read function returned by [[HoodieFileGroupReaderBasedFileFormat.buildReaderWithPartitionValues]].
+ *
+ * <p>Spark deserializes this function once per task, so it holds only broadcast handles. The scan state behind
+ * `state` is deserialized once per executor.
+ */
+private[parquet] class HoodieFileGroupReaderFunction(baseFileReader: Broadcast[SparkColumnarFileReader],
+                                                     fileGroupBaseFileReader: Broadcast[SparkColumnarFileReader],
+                                                     storageConf: Broadcast[SerializableConfiguration],
+                                                     state: Broadcast[JavaSerializedValue[HoodieFileGroupReadState]])
+  extends (PartitionedFile => Iterator[InternalRow]) with Serializable {
+
+  import HoodieFileGroupReaderFunction._
+
+  private def sparkAdapter = SparkAdapterSupport.sparkAdapter
+
+  override def apply(file: PartitionedFile): Iterator[InternalRow] = {
+    val s = state.value.value

Review Comment:
   Done, the local is now state.



##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/HoodieFileGroupReaderFunction.scala:
##########
@@ -0,0 +1,374 @@
+/*
+ * 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.datasources.parquet
+
+import org.apache.hudi.{HoodiePartitionCDCFileGroupMapping, HoodiePartitionFileSliceMapping, HoodieTableSchema, SparkAdapterSupport, SparkFileFormatInternalRowReaderContext}
+import org.apache.hudi.cdc.{CDCFileGroupIterator, HoodieCDCFileGroupSplit, HoodieCDCFileIndex}
+import org.apache.hudi.common.config.{HoodieReaderConfig, TypedProperties}
+import org.apache.hudi.common.fs.FSUtils
+import org.apache.hudi.common.schema.HoodieSchema
+import org.apache.hudi.common.schema.internal.InternalSchema
+import org.apache.hudi.common.table.{HoodieTableMetaClient, ParquetTableSchemaResolver}
+import org.apache.hudi.common.table.log.InstantRange
+import org.apache.hudi.common.table.read.{HoodieFileGroupReader, HoodieRecordReader}
+import org.apache.hudi.common.table.read.lsm.{HoodieLsmFileGroupReader, LsmReaderUtils}
+import org.apache.hudi.common.util.{ConfigUtils, Option => HOption}
+import org.apache.hudi.common.util.collection.ClosableIterator
+import org.apache.hudi.data.CloseableIteratorListener
+import org.apache.hudi.io.storage.HoodieSparkParquetReader.ENABLE_LOGICAL_TIMESTAMP_REPAIR
+import org.apache.hudi.io.storage.VectorConversionUtils
+import org.apache.hudi.storage.StorageConfiguration
+import org.apache.hudi.storage.hadoop.HadoopStorageConfiguration
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.parquet.schema.MessageType
+import org.apache.spark.SparkEnv
+import org.apache.spark.broadcast.Broadcast
+import org.apache.spark.sql.HoodieCatalystExpressionUtils.generateUnsafeProjection
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{JoinedRow, UnsafeProjection}
+import org.apache.spark.sql.execution.datasources.{PartitionedFile, SparkColumnarFileReader, SparkSchemaTransformUtils}
+import org.apache.spark.sql.sources.Filter
+import org.apache.spark.sql.types.StructType
+import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnarBatchUtils}
+import org.apache.spark.util.{SerializableConfiguration, Utils}
+
+import java.io.Closeable
+import java.nio.ByteBuffer
+
+import scala.collection.JavaConverters.mapAsJavaMapConverter
+import scala.reflect.ClassTag
+
+/**
+ * Read-only state of one scan of [[HoodieFileGroupReaderBasedFileFormat]], built on the driver and shared by every
+ * task of an executor through [[HoodieFileGroupReaderFunction]]. Executors only fill thread-safe lazy caches in it;
+ * per-file state such as reader properties is copied before use.
+ */
+private[parquet] class HoodieFileGroupReadState(val metaClient: HoodieTableMetaClient,
+                                                 val tableSchema: HoodieTableSchema,
+                                                 val queryTimestamp: String,
+                                                 val readerProps: TypedProperties,
+                                                 val cdcProps: TypedProperties,
+                                                 val dataSchema: HoodieSchema,
+                                                 val requestedSchema: HoodieSchema,
+                                                 val internalSchemaOpt: HOption[InternalSchema],
+                                                 val instantRangeOpt: HOption[InstantRange],
+                                                 val shouldUseRecordPosition: Boolean,
+                                                 val isCount: Boolean,
+                                                 val filters: Seq[Filter],
+                                                 val requiredFilters: Seq[Filter],
+                                                 val requiredSchema: StructType,
+                                                 val partitionSchema: StructType,
+                                                 val remainingPartitionSchema: StructType,
+                                                 val fixedPartitionIndexes: Set[Int],
+                                                 val outputSchema: StructType,
+                                                 val projectionInputSchema: StructType,
+                                                 val baseFileReadSchemas: BaseFileReadSchemas) extends Serializable {
+
+  /**
+   * Parquet form of the table schema for base file reads. The conversion reads Hadoop's default resources, so it is
+   * done once per executor rather than per task or file.
+   */
+  @transient lazy val tableSchemaAsMessageType: HOption[MessageType] =
+    HOption.ofNullable(ParquetTableSchemaResolver.convertAvroSchemaToParquet(tableSchema.schema, new Configuration()))
+}
+
+/**
+ * Base file read schemas with VECTOR columns rewritten to BinaryType, plus the ordinals of those columns.
+ */
+private[parquet] case class BaseFileReadSchemas(readRequiredSchema: StructType,
+                                                readVectorColumns: Map[Int, HoodieSchema.Vector],
+                                                outputSchema: StructType,
+                                                outputVectorColumns: Map[Int, HoodieSchema.Vector],
+                                                requestedSchema: StructType)
+
+/**
+ * Holds a value as Java-serialized bytes and deserializes it at most once per JVM instance of the holder.
+ *
+ * <p>Broadcasting this holder instead of the value keeps the broadcast independent of `spark.serializer`: Kryo
+ * would otherwise serialize the value field by field and ignore the custom Java serialization of types such as
+ * [[HoodieSchema]] and [[HadoopStorageConfiguration]].
+ */
+private[parquet] class JavaSerializedValue[T: ClassTag] private(bytes: Array[Byte]) extends Serializable {
+
+  @transient lazy val value: T = SparkEnv.get.closureSerializer.newInstance()
+    .deserialize[T](ByteBuffer.wrap(bytes), Utils.getContextOrSparkClassLoader)
+}
+
+private[parquet] object JavaSerializedValue {
+
+  def apply[T: ClassTag](value: T): JavaSerializedValue[T] = {
+    val buffer = SparkEnv.get.closureSerializer.newInstance().serialize(value)
+    val bytes = new Array[Byte](buffer.remaining())
+    buffer.get(bytes)
+    new JavaSerializedValue[T](bytes)
+  }
+}
+
+/**
+ * The per-file read function returned by [[HoodieFileGroupReaderBasedFileFormat.buildReaderWithPartitionValues]].
+ *
+ * <p>Spark deserializes this function once per task, so it holds only broadcast handles. The scan state behind
+ * `state` is deserialized once per executor.
+ */
+private[parquet] class HoodieFileGroupReaderFunction(baseFileReader: Broadcast[SparkColumnarFileReader],
+                                                     fileGroupBaseFileReader: Broadcast[SparkColumnarFileReader],
+                                                     storageConf: Broadcast[SerializableConfiguration],
+                                                     state: Broadcast[JavaSerializedValue[HoodieFileGroupReadState]])
+  extends (PartitionedFile => Iterator[InternalRow]) with Serializable {
+
+  import HoodieFileGroupReaderFunction._
+
+  private def sparkAdapter = SparkAdapterSupport.sparkAdapter
+
+  override def apply(file: PartitionedFile): Iterator[InternalRow] = {
+    val s = state.value.value
+    val conf = new HadoopStorageConfiguration(storageConf.value.value)
+    val iter = file.partitionValues match {
+      // Snapshot or incremental queries.
+      case fileSliceMapping: HoodiePartitionFileSliceMapping =>
+        val fileGroupName = FSUtils.getFileIdFromFilePath(sparkAdapter
+          .getSparkPartitionedFileUtils.getPathFromPartitionedFile(file))
+        fileSliceMapping.getSlice(fileGroupName) match {
+          case Some(fileSlice) if !s.isCount && (s.requiredSchema.nonEmpty || fileSlice.getLogFiles.findAny().isPresent) =>
+            val tableConfig = s.metaClient.getTableConfig
+            // requiredFilters preserve Spark's row-level filtering semantics, while instantRangeOpt
+            // keeps out-of-range records from participating in the file-group merge itself.
+            val readerContext = new SparkFileFormatInternalRowReaderContext(
+              fileGroupBaseFileReader.value, s.filters, s.requiredFilters, conf, tableConfig,
+              sparkRequiredSchema = Some(s.requiredSchema), instantRangeOpt = s.instantRangeOpt)
+            readerContext.enableLogicalTimestampFieldRepair(conf.getBoolean(ENABLE_LOGICAL_TIMESTAMP_REPAIR, true))
+            val props = TypedProperties.copy(s.readerProps)
+            val baseFileLength = if (fileSlice.getBaseFile.isPresent) {
+              fileSlice.getBaseFile.get.getFileSize
+            } else {
+              0
+            }
+            val reader: HoodieRecordReader[InternalRow] =
+              if (LsmReaderUtils.shouldUseLsmReader(
+                tableConfig,
+                ConfigUtils.getStringWithAltKeys(props, HoodieReaderConfig.MERGE_TYPE, true))) {
+                HoodieLsmFileGroupReader.builder[InternalRow]()
+                  .withReaderContext(readerContext)
+                  .withHoodieTableMetaClient(s.metaClient)
+                  .withLatestCommitTime(s.queryTimestamp)
+                  .withBaseFileOption(fileSlice.getBaseFile)
+                  .withLogFiles(fileSlice.getLogFiles)
+                  .withPartitionPath(fileSlice.getPartitionPath)
+                  .withDataSchema(s.dataSchema)
+                  .withRequestedSchema(s.requestedSchema)
+                  .withInternalSchemaOpt(s.internalSchemaOpt)
+                  .withProps(props)
+                  .withStart(file.start)
+                  .withLength(baseFileLength)
+                  .build()
+              } else {
+                HoodieFileGroupReader.builder[InternalRow]()
+                  .withReaderContext(readerContext)
+                  .withHoodieTableMetaClient(s.metaClient)
+                  .withLatestCommitTime(s.queryTimestamp)
+                  .withBaseFileOption(fileSlice.getBaseFile)
+                  .withLogFiles(fileSlice.getLogFiles)
+                  .withPartitionPath(fileSlice.getPartitionPath)
+                  .withDataSchema(s.dataSchema)
+                  .withRequestedSchema(s.requestedSchema)
+                  .withInternalSchemaOpt(s.internalSchemaOpt)
+                  .withProps(props)
+                  .withStart(file.start)
+                  .withLength(baseFileLength)
+                  .withShouldUseRecordPosition(s.shouldUseRecordPosition)
+                  .build()
+              }
+            // Append partition values to rows and project to output schema
+            appendPartitionAndProject(
+              reader.getClosableIterator,
+              s.projectionInputSchema,
+              s.remainingPartitionSchema,
+              s.outputSchema,
+              fileSliceMapping.getPartitionValues,
+              s.fixedPartitionIndexes)
+
+          case _ =>
+            readBaseFile(file, s, conf)
+        }
+      // CDC queries.
+      case cdcFileGroupMapping: HoodiePartitionCDCFileGroupMapping =>
+        new CDCFileGroupIterator(
+          HoodieCDCFileGroupSplit(cdcFileGroupMapping.getFileSplits().toArray),
+          s.metaClient,
+          conf,
+          fileGroupBaseFileReader.value,
+          s.tableSchema,
+          HoodieCDCFileIndex.FULL_CDC_SPARK_SCHEMA,
+          s.requiredSchema,
+          TypedProperties.copy(s.cdcProps))

Review Comment:
   Yes, kept: CDCFileGroupIterator hands these props to BufferedRecordMergerFactory, whose CustomPayloadRecordMerger writes the payload class into them. Added a comment at both copy sites.



-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(spark): ship file group reader scan state once per executor [hudi]

Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua commented on code in PR #20077:
URL: https://github.com/apache/hudi/pull/20077#discussion_r4169747631


##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/HoodieFileGroupReaderBasedFileFormat.scala:
##########
@@ -356,97 +339,35 @@ class HoodieFileGroupReaderBasedFileFormat(tablePath: String,
     }
 
     val broadcastedStorageConf = spark.sparkContext.broadcast(new SerializableConfiguration(augmentedStorageConf.unwrap()))
-    val fileIndexProps: TypedProperties = HoodieFileIndex.getConfigProperties(spark, options, null)
+    val cdcProps: TypedProperties = HoodieFileIndex.getConfigProperties(spark, options, null)
+    cdcProps.setProperty(HoodieTableConfig.HOODIE_TABLE_NAME_KEY, tableName)

Review Comment:
   I confirmed that this is existing behavior for CDC query.



-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(spark): ship file group reader scan state once per executor [hudi]

Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua commented on code in PR #20077:
URL: https://github.com/apache/hudi/pull/20077#discussion_r4169376703


##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/HoodieFileGroupReaderFunction.scala:
##########
@@ -0,0 +1,374 @@
+/*
+ * 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.datasources.parquet
+
+import org.apache.hudi.{HoodiePartitionCDCFileGroupMapping, HoodiePartitionFileSliceMapping, HoodieTableSchema, SparkAdapterSupport, SparkFileFormatInternalRowReaderContext}
+import org.apache.hudi.cdc.{CDCFileGroupIterator, HoodieCDCFileGroupSplit, HoodieCDCFileIndex}
+import org.apache.hudi.common.config.{HoodieReaderConfig, TypedProperties}
+import org.apache.hudi.common.fs.FSUtils
+import org.apache.hudi.common.schema.HoodieSchema
+import org.apache.hudi.common.schema.internal.InternalSchema
+import org.apache.hudi.common.table.{HoodieTableMetaClient, ParquetTableSchemaResolver}
+import org.apache.hudi.common.table.log.InstantRange
+import org.apache.hudi.common.table.read.{HoodieFileGroupReader, HoodieRecordReader}
+import org.apache.hudi.common.table.read.lsm.{HoodieLsmFileGroupReader, LsmReaderUtils}
+import org.apache.hudi.common.util.{ConfigUtils, Option => HOption}
+import org.apache.hudi.common.util.collection.ClosableIterator
+import org.apache.hudi.data.CloseableIteratorListener
+import org.apache.hudi.io.storage.HoodieSparkParquetReader.ENABLE_LOGICAL_TIMESTAMP_REPAIR
+import org.apache.hudi.io.storage.VectorConversionUtils
+import org.apache.hudi.storage.StorageConfiguration
+import org.apache.hudi.storage.hadoop.HadoopStorageConfiguration
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.parquet.schema.MessageType
+import org.apache.spark.SparkEnv
+import org.apache.spark.broadcast.Broadcast
+import org.apache.spark.sql.HoodieCatalystExpressionUtils.generateUnsafeProjection
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{JoinedRow, UnsafeProjection}
+import org.apache.spark.sql.execution.datasources.{PartitionedFile, SparkColumnarFileReader, SparkSchemaTransformUtils}
+import org.apache.spark.sql.sources.Filter
+import org.apache.spark.sql.types.StructType
+import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnarBatchUtils}
+import org.apache.spark.util.{SerializableConfiguration, Utils}
+
+import java.io.Closeable
+import java.nio.ByteBuffer
+
+import scala.collection.JavaConverters.mapAsJavaMapConverter
+import scala.reflect.ClassTag
+
+/**
+ * Read-only state of one scan of [[HoodieFileGroupReaderBasedFileFormat]], built on the driver and shared by every
+ * task of an executor through [[HoodieFileGroupReaderFunction]]. Executors only fill thread-safe lazy caches in it;
+ * per-file state such as reader properties is copied before use.
+ */
+private[parquet] class HoodieFileGroupReadState(val metaClient: HoodieTableMetaClient,
+                                                 val tableSchema: HoodieTableSchema,
+                                                 val queryTimestamp: String,
+                                                 val readerProps: TypedProperties,
+                                                 val cdcProps: TypedProperties,
+                                                 val dataSchema: HoodieSchema,
+                                                 val requestedSchema: HoodieSchema,
+                                                 val internalSchemaOpt: HOption[InternalSchema],
+                                                 val instantRangeOpt: HOption[InstantRange],
+                                                 val shouldUseRecordPosition: Boolean,
+                                                 val isCount: Boolean,
+                                                 val filters: Seq[Filter],
+                                                 val requiredFilters: Seq[Filter],
+                                                 val requiredSchema: StructType,
+                                                 val partitionSchema: StructType,
+                                                 val remainingPartitionSchema: StructType,
+                                                 val fixedPartitionIndexes: Set[Int],
+                                                 val outputSchema: StructType,
+                                                 val projectionInputSchema: StructType,
+                                                 val baseFileReadSchemas: BaseFileReadSchemas) extends Serializable {
+
+  /**
+   * Parquet form of the table schema for base file reads. The conversion reads Hadoop's default resources, so it is
+   * done once per executor rather than per task or file.
+   */
+  @transient lazy val tableSchemaAsMessageType: HOption[MessageType] =
+    HOption.ofNullable(ParquetTableSchemaResolver.convertAvroSchemaToParquet(tableSchema.schema, new Configuration()))
+}
+
+/**
+ * Base file read schemas with VECTOR columns rewritten to BinaryType, plus the ordinals of those columns.
+ */
+private[parquet] case class BaseFileReadSchemas(readRequiredSchema: StructType,
+                                                readVectorColumns: Map[Int, HoodieSchema.Vector],
+                                                outputSchema: StructType,
+                                                outputVectorColumns: Map[Int, HoodieSchema.Vector],
+                                                requestedSchema: StructType)
+
+/**
+ * Holds a value as Java-serialized bytes and deserializes it at most once per JVM instance of the holder.
+ *
+ * <p>Broadcasting this holder instead of the value keeps the broadcast independent of `spark.serializer`: Kryo
+ * would otherwise serialize the value field by field and ignore the custom Java serialization of types such as
+ * [[HoodieSchema]] and [[HadoopStorageConfiguration]].
+ */
+private[parquet] class JavaSerializedValue[T: ClassTag] private(bytes: Array[Byte]) extends Serializable {
+
+  @transient lazy val value: T = SparkEnv.get.closureSerializer.newInstance()
+    .deserialize[T](ByteBuffer.wrap(bytes), Utils.getContextOrSparkClassLoader)
+}
+
+private[parquet] object JavaSerializedValue {
+
+  def apply[T: ClassTag](value: T): JavaSerializedValue[T] = {
+    val buffer = SparkEnv.get.closureSerializer.newInstance().serialize(value)
+    val bytes = new Array[Byte](buffer.remaining())
+    buffer.get(bytes)
+    new JavaSerializedValue[T](bytes)
+  }
+}
+
+/**
+ * The per-file read function returned by [[HoodieFileGroupReaderBasedFileFormat.buildReaderWithPartitionValues]].
+ *
+ * <p>Spark deserializes this function once per task, so it holds only broadcast handles. The scan state behind
+ * `state` is deserialized once per executor.
+ */
+private[parquet] class HoodieFileGroupReaderFunction(baseFileReader: Broadcast[SparkColumnarFileReader],
+                                                     fileGroupBaseFileReader: Broadcast[SparkColumnarFileReader],
+                                                     storageConf: Broadcast[SerializableConfiguration],
+                                                     state: Broadcast[JavaSerializedValue[HoodieFileGroupReadState]])

Review Comment:
   ```suggestion
                                                        broadcastedState: Broadcast[JavaSerializedValue[HoodieFileGroupReadState]])
   ```



##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/HoodieFileGroupReaderFunction.scala:
##########
@@ -0,0 +1,374 @@
+/*
+ * 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.datasources.parquet
+
+import org.apache.hudi.{HoodiePartitionCDCFileGroupMapping, HoodiePartitionFileSliceMapping, HoodieTableSchema, SparkAdapterSupport, SparkFileFormatInternalRowReaderContext}
+import org.apache.hudi.cdc.{CDCFileGroupIterator, HoodieCDCFileGroupSplit, HoodieCDCFileIndex}
+import org.apache.hudi.common.config.{HoodieReaderConfig, TypedProperties}
+import org.apache.hudi.common.fs.FSUtils
+import org.apache.hudi.common.schema.HoodieSchema
+import org.apache.hudi.common.schema.internal.InternalSchema
+import org.apache.hudi.common.table.{HoodieTableMetaClient, ParquetTableSchemaResolver}
+import org.apache.hudi.common.table.log.InstantRange
+import org.apache.hudi.common.table.read.{HoodieFileGroupReader, HoodieRecordReader}
+import org.apache.hudi.common.table.read.lsm.{HoodieLsmFileGroupReader, LsmReaderUtils}
+import org.apache.hudi.common.util.{ConfigUtils, Option => HOption}
+import org.apache.hudi.common.util.collection.ClosableIterator
+import org.apache.hudi.data.CloseableIteratorListener
+import org.apache.hudi.io.storage.HoodieSparkParquetReader.ENABLE_LOGICAL_TIMESTAMP_REPAIR
+import org.apache.hudi.io.storage.VectorConversionUtils
+import org.apache.hudi.storage.StorageConfiguration
+import org.apache.hudi.storage.hadoop.HadoopStorageConfiguration
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.parquet.schema.MessageType
+import org.apache.spark.SparkEnv
+import org.apache.spark.broadcast.Broadcast
+import org.apache.spark.sql.HoodieCatalystExpressionUtils.generateUnsafeProjection
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{JoinedRow, UnsafeProjection}
+import org.apache.spark.sql.execution.datasources.{PartitionedFile, SparkColumnarFileReader, SparkSchemaTransformUtils}
+import org.apache.spark.sql.sources.Filter
+import org.apache.spark.sql.types.StructType
+import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnarBatchUtils}
+import org.apache.spark.util.{SerializableConfiguration, Utils}
+
+import java.io.Closeable
+import java.nio.ByteBuffer
+
+import scala.collection.JavaConverters.mapAsJavaMapConverter
+import scala.reflect.ClassTag
+
+/**
+ * Read-only state of one scan of [[HoodieFileGroupReaderBasedFileFormat]], built on the driver and shared by every
+ * task of an executor through [[HoodieFileGroupReaderFunction]]. Executors only fill thread-safe lazy caches in it;
+ * per-file state such as reader properties is copied before use.
+ */
+private[parquet] class HoodieFileGroupReadState(val metaClient: HoodieTableMetaClient,
+                                                 val tableSchema: HoodieTableSchema,
+                                                 val queryTimestamp: String,
+                                                 val readerProps: TypedProperties,
+                                                 val cdcProps: TypedProperties,
+                                                 val dataSchema: HoodieSchema,
+                                                 val requestedSchema: HoodieSchema,
+                                                 val internalSchemaOpt: HOption[InternalSchema],
+                                                 val instantRangeOpt: HOption[InstantRange],
+                                                 val shouldUseRecordPosition: Boolean,
+                                                 val isCount: Boolean,
+                                                 val filters: Seq[Filter],
+                                                 val requiredFilters: Seq[Filter],
+                                                 val requiredSchema: StructType,
+                                                 val partitionSchema: StructType,
+                                                 val remainingPartitionSchema: StructType,
+                                                 val fixedPartitionIndexes: Set[Int],
+                                                 val outputSchema: StructType,
+                                                 val projectionInputSchema: StructType,
+                                                 val baseFileReadSchemas: BaseFileReadSchemas) extends Serializable {
+
+  /**
+   * Parquet form of the table schema for base file reads. The conversion reads Hadoop's default resources, so it is
+   * done once per executor rather than per task or file.
+   */
+  @transient lazy val tableSchemaAsMessageType: HOption[MessageType] =
+    HOption.ofNullable(ParquetTableSchemaResolver.convertAvroSchemaToParquet(tableSchema.schema, new Configuration()))
+}
+
+/**
+ * Base file read schemas with VECTOR columns rewritten to BinaryType, plus the ordinals of those columns.
+ */
+private[parquet] case class BaseFileReadSchemas(readRequiredSchema: StructType,
+                                                readVectorColumns: Map[Int, HoodieSchema.Vector],
+                                                outputSchema: StructType,
+                                                outputVectorColumns: Map[Int, HoodieSchema.Vector],
+                                                requestedSchema: StructType)
+
+/**
+ * Holds a value as Java-serialized bytes and deserializes it at most once per JVM instance of the holder.
+ *
+ * <p>Broadcasting this holder instead of the value keeps the broadcast independent of `spark.serializer`: Kryo
+ * would otherwise serialize the value field by field and ignore the custom Java serialization of types such as
+ * [[HoodieSchema]] and [[HadoopStorageConfiguration]].
+ */
+private[parquet] class JavaSerializedValue[T: ClassTag] private(bytes: Array[Byte]) extends Serializable {
+
+  @transient lazy val value: T = SparkEnv.get.closureSerializer.newInstance()
+    .deserialize[T](ByteBuffer.wrap(bytes), Utils.getContextOrSparkClassLoader)
+}
+
+private[parquet] object JavaSerializedValue {
+
+  def apply[T: ClassTag](value: T): JavaSerializedValue[T] = {
+    val buffer = SparkEnv.get.closureSerializer.newInstance().serialize(value)
+    val bytes = new Array[Byte](buffer.remaining())
+    buffer.get(bytes)
+    new JavaSerializedValue[T](bytes)
+  }
+}
+
+/**
+ * The per-file read function returned by [[HoodieFileGroupReaderBasedFileFormat.buildReaderWithPartitionValues]].
+ *
+ * <p>Spark deserializes this function once per task, so it holds only broadcast handles. The scan state behind
+ * `state` is deserialized once per executor.
+ */
+private[parquet] class HoodieFileGroupReaderFunction(baseFileReader: Broadcast[SparkColumnarFileReader],
+                                                     fileGroupBaseFileReader: Broadcast[SparkColumnarFileReader],
+                                                     storageConf: Broadcast[SerializableConfiguration],
+                                                     state: Broadcast[JavaSerializedValue[HoodieFileGroupReadState]])
+  extends (PartitionedFile => Iterator[InternalRow]) with Serializable {
+
+  import HoodieFileGroupReaderFunction._
+
+  private def sparkAdapter = SparkAdapterSupport.sparkAdapter
+
+  override def apply(file: PartitionedFile): Iterator[InternalRow] = {
+    val s = state.value.value

Review Comment:
   ```suggestion
       val state = broadcastedState.value.value
   ```



##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/HoodieFileGroupReaderFunction.scala:
##########
@@ -0,0 +1,374 @@
+/*
+ * 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.datasources.parquet
+
+import org.apache.hudi.{HoodiePartitionCDCFileGroupMapping, HoodiePartitionFileSliceMapping, HoodieTableSchema, SparkAdapterSupport, SparkFileFormatInternalRowReaderContext}
+import org.apache.hudi.cdc.{CDCFileGroupIterator, HoodieCDCFileGroupSplit, HoodieCDCFileIndex}
+import org.apache.hudi.common.config.{HoodieReaderConfig, TypedProperties}
+import org.apache.hudi.common.fs.FSUtils
+import org.apache.hudi.common.schema.HoodieSchema
+import org.apache.hudi.common.schema.internal.InternalSchema
+import org.apache.hudi.common.table.{HoodieTableMetaClient, ParquetTableSchemaResolver}
+import org.apache.hudi.common.table.log.InstantRange
+import org.apache.hudi.common.table.read.{HoodieFileGroupReader, HoodieRecordReader}
+import org.apache.hudi.common.table.read.lsm.{HoodieLsmFileGroupReader, LsmReaderUtils}
+import org.apache.hudi.common.util.{ConfigUtils, Option => HOption}
+import org.apache.hudi.common.util.collection.ClosableIterator
+import org.apache.hudi.data.CloseableIteratorListener
+import org.apache.hudi.io.storage.HoodieSparkParquetReader.ENABLE_LOGICAL_TIMESTAMP_REPAIR
+import org.apache.hudi.io.storage.VectorConversionUtils
+import org.apache.hudi.storage.StorageConfiguration
+import org.apache.hudi.storage.hadoop.HadoopStorageConfiguration
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.parquet.schema.MessageType
+import org.apache.spark.SparkEnv
+import org.apache.spark.broadcast.Broadcast
+import org.apache.spark.sql.HoodieCatalystExpressionUtils.generateUnsafeProjection
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{JoinedRow, UnsafeProjection}
+import org.apache.spark.sql.execution.datasources.{PartitionedFile, SparkColumnarFileReader, SparkSchemaTransformUtils}
+import org.apache.spark.sql.sources.Filter
+import org.apache.spark.sql.types.StructType
+import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnarBatchUtils}
+import org.apache.spark.util.{SerializableConfiguration, Utils}
+
+import java.io.Closeable
+import java.nio.ByteBuffer
+
+import scala.collection.JavaConverters.mapAsJavaMapConverter
+import scala.reflect.ClassTag
+
+/**
+ * Read-only state of one scan of [[HoodieFileGroupReaderBasedFileFormat]], built on the driver and shared by every
+ * task of an executor through [[HoodieFileGroupReaderFunction]]. Executors only fill thread-safe lazy caches in it;
+ * per-file state such as reader properties is copied before use.
+ */
+private[parquet] class HoodieFileGroupReadState(val metaClient: HoodieTableMetaClient,
+                                                 val tableSchema: HoodieTableSchema,
+                                                 val queryTimestamp: String,
+                                                 val readerProps: TypedProperties,
+                                                 val cdcProps: TypedProperties,
+                                                 val dataSchema: HoodieSchema,
+                                                 val requestedSchema: HoodieSchema,
+                                                 val internalSchemaOpt: HOption[InternalSchema],
+                                                 val instantRangeOpt: HOption[InstantRange],
+                                                 val shouldUseRecordPosition: Boolean,
+                                                 val isCount: Boolean,
+                                                 val filters: Seq[Filter],
+                                                 val requiredFilters: Seq[Filter],
+                                                 val requiredSchema: StructType,
+                                                 val partitionSchema: StructType,
+                                                 val remainingPartitionSchema: StructType,
+                                                 val fixedPartitionIndexes: Set[Int],
+                                                 val outputSchema: StructType,
+                                                 val projectionInputSchema: StructType,
+                                                 val baseFileReadSchemas: BaseFileReadSchemas) extends Serializable {
+
+  /**
+   * Parquet form of the table schema for base file reads. The conversion reads Hadoop's default resources, so it is
+   * done once per executor rather than per task or file.
+   */
+  @transient lazy val tableSchemaAsMessageType: HOption[MessageType] =
+    HOption.ofNullable(ParquetTableSchemaResolver.convertAvroSchemaToParquet(tableSchema.schema, new Configuration()))
+}
+
+/**
+ * Base file read schemas with VECTOR columns rewritten to BinaryType, plus the ordinals of those columns.
+ */
+private[parquet] case class BaseFileReadSchemas(readRequiredSchema: StructType,
+                                                readVectorColumns: Map[Int, HoodieSchema.Vector],
+                                                outputSchema: StructType,
+                                                outputVectorColumns: Map[Int, HoodieSchema.Vector],
+                                                requestedSchema: StructType)
+
+/**
+ * Holds a value as Java-serialized bytes and deserializes it at most once per JVM instance of the holder.
+ *
+ * <p>Broadcasting this holder instead of the value keeps the broadcast independent of `spark.serializer`: Kryo
+ * would otherwise serialize the value field by field and ignore the custom Java serialization of types such as
+ * [[HoodieSchema]] and [[HadoopStorageConfiguration]].
+ */
+private[parquet] class JavaSerializedValue[T: ClassTag] private(bytes: Array[Byte]) extends Serializable {
+
+  @transient lazy val value: T = SparkEnv.get.closureSerializer.newInstance()
+    .deserialize[T](ByteBuffer.wrap(bytes), Utils.getContextOrSparkClassLoader)
+}
+
+private[parquet] object JavaSerializedValue {
+
+  def apply[T: ClassTag](value: T): JavaSerializedValue[T] = {
+    val buffer = SparkEnv.get.closureSerializer.newInstance().serialize(value)
+    val bytes = new Array[Byte](buffer.remaining())
+    buffer.get(bytes)
+    new JavaSerializedValue[T](bytes)
+  }
+}
+
+/**
+ * The per-file read function returned by [[HoodieFileGroupReaderBasedFileFormat.buildReaderWithPartitionValues]].
+ *
+ * <p>Spark deserializes this function once per task, so it holds only broadcast handles. The scan state behind
+ * `state` is deserialized once per executor.
+ */
+private[parquet] class HoodieFileGroupReaderFunction(baseFileReader: Broadcast[SparkColumnarFileReader],
+                                                     fileGroupBaseFileReader: Broadcast[SparkColumnarFileReader],
+                                                     storageConf: Broadcast[SerializableConfiguration],
+                                                     state: Broadcast[JavaSerializedValue[HoodieFileGroupReadState]])
+  extends (PartitionedFile => Iterator[InternalRow]) with Serializable {
+
+  import HoodieFileGroupReaderFunction._
+
+  private def sparkAdapter = SparkAdapterSupport.sparkAdapter
+
+  override def apply(file: PartitionedFile): Iterator[InternalRow] = {
+    val s = state.value.value

Review Comment:
   So `state` is easier to read.



-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(spark): ship file group reader scan state once per executor [hudi]

Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua merged PR #20077:
URL: https://github.com/apache/hudi/pull/20077


-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(spark): ship file group reader scan state once per executor [hudi]

Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #20077:
URL: https://github.com/apache/hudi/pull/20077#issuecomment-5963142583

   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "c20a93fef79c2f20dde27dfed4e9f55139aead64",
       "status" : "DELETED",
       "url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=17295",
       "triggerID" : "c20a93fef79c2f20dde27dfed4e9f55139aead64",
       "triggerType" : "PUSH"
     }, {
       "hash" : "e0e6f8f69682c1a4af2d88824d537c8e641f68ae",
       "status" : "SUCCESS",
       "url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=17426",
       "triggerID" : "e0e6f8f69682c1a4af2d88824d537c8e641f68ae",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * e0e6f8f69682c1a4af2d88824d537c8e641f68ae Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=17426) 
   
   <details>
   <summary>Bot commands</summary>
     @hudi-bot supports the following commands:
   
    - `@hudi-bot run azure` re-run the last Azure build
   </details>


-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(spark): ship file group reader scan state once per executor [hudi]

Posted by "nsivabalan (via GitHub)" <gi...@apache.org>.
nsivabalan commented on code in PR #20077:
URL: https://github.com/apache/hudi/pull/20077#discussion_r4171022177


##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/HoodieFileGroupReaderBasedFileFormat.scala:
##########
@@ -356,97 +339,35 @@ class HoodieFileGroupReaderBasedFileFormat(tablePath: String,
     }
 
     val broadcastedStorageConf = spark.sparkContext.broadcast(new SerializableConfiguration(augmentedStorageConf.unwrap()))
-    val fileIndexProps: TypedProperties = HoodieFileIndex.getConfigProperties(spark, options, null)
+    val cdcProps: TypedProperties = HoodieFileIndex.getConfigProperties(spark, options, null)
+    cdcProps.setProperty(HoodieTableConfig.HOODIE_TABLE_NAME_KEY, tableName)
 
     val engineContext = new HoodieSparkEngineContext(new JavaSparkContext(spark.sparkContext))
     val maxMemoryPerCompaction = MergeUtils.getMaxMemoryPerCompaction(engineContext.getTaskContextSupplier, options.asJava)
 
-    // Create metaclient on driver to avoid expensive operations on executors
-    val metaClient: HoodieTableMetaClient = HoodieTableMetaClient
-      .builder().setConf(augmentedStorageConf).setBasePath(tablePath).build
-
-    (file: PartitionedFile) => {
-      // executor
-      val storageConf = new HadoopStorageConfiguration(broadcastedStorageConf.value.value)
-      val iter = file.partitionValues match {
-        // Snapshot or incremental queries.
-        case fileSliceMapping: HoodiePartitionFileSliceMapping =>
-          val fileGroupName = FSUtils.getFileIdFromFilePath(sparkAdapter
-            .getSparkPartitionedFileUtils.getPathFromPartitionedFile(file))
-          fileSliceMapping.getSlice(fileGroupName) match {
-            case Some(fileSlice) if !isCount && (requiredSchema.nonEmpty || fileSlice.getLogFiles.findAny().isPresent) =>
-              // requiredFilters preserve Spark's row-level filtering semantics, while instantRangeOpt
-              // keeps out-of-range records from participating in the file-group merge itself.
-              val readerContext = new SparkFileFormatInternalRowReaderContext(
-                fileGroupBaseFileReader.value, filters, requiredFilters, storageConf, metaClient.getTableConfig,
-                sparkRequiredSchema = Some(requiredSchema), instantRangeOpt = instantRangeOpt)
-              readerContext.enableLogicalTimestampFieldRepair(storageConf.getBoolean(ENABLE_LOGICAL_TIMESTAMP_REPAIR, true))
-              val props = metaClient.getTableConfig.getProps
-              options.foreach(kv => props.setProperty(kv._1, kv._2))
-              props.put(HoodieMemoryConfig.MAX_MEMORY_FOR_MERGE.key(), String.valueOf(maxMemoryPerCompaction))
-              val baseFileLength = if (fileSlice.getBaseFile.isPresent) {
-                fileSlice.getBaseFile.get.getFileSize
-              } else {
-                0
-              }
-              val reader: HoodieRecordReader[InternalRow] =
-                if (LsmReaderUtils.shouldUseLsmReader(
-                  metaClient.getTableConfig,
-                  ConfigUtils.getStringWithAltKeys(props, HoodieReaderConfig.MERGE_TYPE, true))) {
-                  HoodieLsmFileGroupReader.builder[InternalRow]()
-                    .withReaderContext(readerContext)
-                    .withHoodieTableMetaClient(metaClient)
-                    .withLatestCommitTime(queryTimestamp)
-                    .withBaseFileOption(fileSlice.getBaseFile)
-                    .withLogFiles(fileSlice.getLogFiles)
-                    .withPartitionPath(fileSlice.getPartitionPath)
-                    .withDataSchema(dataSchema)
-                    .withRequestedSchema(requestedSchema)
-                    .withInternalSchemaOpt(internalSchemaOpt)
-                    .withProps(props)
-                    .withStart(file.start)
-                    .withLength(baseFileLength)
-                    .build()
-                } else {
-                  HoodieFileGroupReader.builder[InternalRow]()
-                    .withReaderContext(readerContext)
-                    .withHoodieTableMetaClient(metaClient)
-                    .withLatestCommitTime(queryTimestamp)
-                    .withBaseFileOption(fileSlice.getBaseFile)
-                    .withLogFiles(fileSlice.getLogFiles)
-                    .withPartitionPath(fileSlice.getPartitionPath)
-                    .withDataSchema(dataSchema)
-                    .withRequestedSchema(requestedSchema)
-                    .withInternalSchemaOpt(internalSchemaOpt)
-                    .withProps(props)
-                    .withStart(file.start)
-                    .withLength(baseFileLength)
-                    .withShouldUseRecordPosition(shouldUseRecordPosition)
-                    .build()
-                }
-              // Append partition values to rows and project to output schema
-              appendPartitionAndProject(
-                reader.getClosableIterator,
-                projectionInputSchema,
-                remainingPartitionSchema,
-                outputSchema,
-                fileSliceMapping.getPartitionValues,
-                fixedPartitionIndexes)
-
-            case _ =>
-              readBaseFile(file, baseFileReader.value, requestedStructType, remainingPartitionSchema, fixedPartitionIndexes,
-                readRequiredSchema, partitionSchema, outputSchema, filters ++ requiredFilters, storageConf)
-          }
-        // CDC queries.
-        case hoodiePartitionCDCFileGroupSliceMapping: HoodiePartitionCDCFileGroupMapping =>
-          buildCDCRecordIterator(hoodiePartitionCDCFileGroupSliceMapping, fileGroupBaseFileReader.value, storageConf, fileIndexProps, requiredSchema, metaClient)
-
-        case _ =>
-          readBaseFile(file, baseFileReader.value, requestedStructType, remainingPartitionSchema, fixedPartitionIndexes,
-            readRequiredSchema, partitionSchema, outputSchema, filters ++ requiredFilters, storageConf)
-      }
-      CloseableIteratorListener.addListener(iter)
+    // The relation's meta client carries the timeline the scan was planned against; build one only when the

Review Comment:
   Worth stating in the PR description and release note: this is a behavior change on executors, not only a serde one.
   
   `BaseHoodieLogRecordReader` (line ~303) and `LogReaderUtils` (line ~81) call `getCommitsTimeline()` / `getActiveTimeline()` on the meta client the task received. Before, the driver built a fresh client with no loaded timeline, so each task listed the timeline on the executor and could see commits that completed after planning. Now tasks see the timeline the file index planned against. That is the better behavior (consistent snapshot, no per-task listing), but it changes which log blocks count as committed, so it belongs next to the read-option note.
   
   Could you also confirm `HoodieFileIndex.refresh()` reloads this same meta client instance, so a long-lived relation (cached DataFrame, temp view) keeps the file index and the reader timeline in sync?



##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/HoodieFileGroupReaderBasedFileFormat.scala:
##########
@@ -356,97 +339,35 @@ class HoodieFileGroupReaderBasedFileFormat(tablePath: String,
     }
 
     val broadcastedStorageConf = spark.sparkContext.broadcast(new SerializableConfiguration(augmentedStorageConf.unwrap()))
-    val fileIndexProps: TypedProperties = HoodieFileIndex.getConfigProperties(spark, options, null)
+    val cdcProps: TypedProperties = HoodieFileIndex.getConfigProperties(spark, options, null)
+    cdcProps.setProperty(HoodieTableConfig.HOODIE_TABLE_NAME_KEY, tableName)
 
     val engineContext = new HoodieSparkEngineContext(new JavaSparkContext(spark.sparkContext))
     val maxMemoryPerCompaction = MergeUtils.getMaxMemoryPerCompaction(engineContext.getTaskContextSupplier, options.asJava)
 
-    // Create metaclient on driver to avoid expensive operations on executors
-    val metaClient: HoodieTableMetaClient = HoodieTableMetaClient
-      .builder().setConf(augmentedStorageConf).setBasePath(tablePath).build
-
-    (file: PartitionedFile) => {
-      // executor
-      val storageConf = new HadoopStorageConfiguration(broadcastedStorageConf.value.value)
-      val iter = file.partitionValues match {
-        // Snapshot or incremental queries.
-        case fileSliceMapping: HoodiePartitionFileSliceMapping =>
-          val fileGroupName = FSUtils.getFileIdFromFilePath(sparkAdapter
-            .getSparkPartitionedFileUtils.getPathFromPartitionedFile(file))
-          fileSliceMapping.getSlice(fileGroupName) match {
-            case Some(fileSlice) if !isCount && (requiredSchema.nonEmpty || fileSlice.getLogFiles.findAny().isPresent) =>
-              // requiredFilters preserve Spark's row-level filtering semantics, while instantRangeOpt
-              // keeps out-of-range records from participating in the file-group merge itself.
-              val readerContext = new SparkFileFormatInternalRowReaderContext(
-                fileGroupBaseFileReader.value, filters, requiredFilters, storageConf, metaClient.getTableConfig,
-                sparkRequiredSchema = Some(requiredSchema), instantRangeOpt = instantRangeOpt)
-              readerContext.enableLogicalTimestampFieldRepair(storageConf.getBoolean(ENABLE_LOGICAL_TIMESTAMP_REPAIR, true))
-              val props = metaClient.getTableConfig.getProps
-              options.foreach(kv => props.setProperty(kv._1, kv._2))
-              props.put(HoodieMemoryConfig.MAX_MEMORY_FOR_MERGE.key(), String.valueOf(maxMemoryPerCompaction))
-              val baseFileLength = if (fileSlice.getBaseFile.isPresent) {
-                fileSlice.getBaseFile.get.getFileSize
-              } else {
-                0
-              }
-              val reader: HoodieRecordReader[InternalRow] =
-                if (LsmReaderUtils.shouldUseLsmReader(
-                  metaClient.getTableConfig,
-                  ConfigUtils.getStringWithAltKeys(props, HoodieReaderConfig.MERGE_TYPE, true))) {
-                  HoodieLsmFileGroupReader.builder[InternalRow]()
-                    .withReaderContext(readerContext)
-                    .withHoodieTableMetaClient(metaClient)
-                    .withLatestCommitTime(queryTimestamp)
-                    .withBaseFileOption(fileSlice.getBaseFile)
-                    .withLogFiles(fileSlice.getLogFiles)
-                    .withPartitionPath(fileSlice.getPartitionPath)
-                    .withDataSchema(dataSchema)
-                    .withRequestedSchema(requestedSchema)
-                    .withInternalSchemaOpt(internalSchemaOpt)
-                    .withProps(props)
-                    .withStart(file.start)
-                    .withLength(baseFileLength)
-                    .build()
-                } else {
-                  HoodieFileGroupReader.builder[InternalRow]()
-                    .withReaderContext(readerContext)
-                    .withHoodieTableMetaClient(metaClient)
-                    .withLatestCommitTime(queryTimestamp)
-                    .withBaseFileOption(fileSlice.getBaseFile)
-                    .withLogFiles(fileSlice.getLogFiles)
-                    .withPartitionPath(fileSlice.getPartitionPath)
-                    .withDataSchema(dataSchema)
-                    .withRequestedSchema(requestedSchema)
-                    .withInternalSchemaOpt(internalSchemaOpt)
-                    .withProps(props)
-                    .withStart(file.start)
-                    .withLength(baseFileLength)
-                    .withShouldUseRecordPosition(shouldUseRecordPosition)
-                    .build()
-                }
-              // Append partition values to rows and project to output schema
-              appendPartitionAndProject(
-                reader.getClosableIterator,
-                projectionInputSchema,
-                remainingPartitionSchema,
-                outputSchema,
-                fileSliceMapping.getPartitionValues,
-                fixedPartitionIndexes)
-
-            case _ =>
-              readBaseFile(file, baseFileReader.value, requestedStructType, remainingPartitionSchema, fixedPartitionIndexes,
-                readRequiredSchema, partitionSchema, outputSchema, filters ++ requiredFilters, storageConf)
-          }
-        // CDC queries.
-        case hoodiePartitionCDCFileGroupSliceMapping: HoodiePartitionCDCFileGroupMapping =>
-          buildCDCRecordIterator(hoodiePartitionCDCFileGroupSliceMapping, fileGroupBaseFileReader.value, storageConf, fileIndexProps, requiredSchema, metaClient)
-
-        case _ =>
-          readBaseFile(file, baseFileReader.value, requestedStructType, remainingPartitionSchema, fixedPartitionIndexes,
-            readRequiredSchema, partitionSchema, outputSchema, filters ++ requiredFilters, storageConf)
-      }
-      CloseableIteratorListener.addListener(iter)
+    // The relation's meta client carries the timeline the scan was planned against; build one only when the
+    // format is used without a relation. The field is null rather than None on a deserialized format.
+    val metaClient: HoodieTableMetaClient = Option(tableMetaClient).flatten.getOrElse(HoodieTableMetaClient
+      .builder().setConf(augmentedStorageConf).setBasePath(tablePath).build)
+    val readerProps = TypedProperties.copy(metaClient.getTableConfig.getProps)
+    options.foreach(kv => readerProps.setProperty(kv._1, kv._2))

Review Comment:
   Non-blocking: a user who relied on the accidental override (passing e.g. merge mode or payload class as a read option) now gets different results with no signal. A one-time driver-side warning here, when an option key is a table config key and its value differs from the persisted one, would make the migration visible.



##########
hudi-common/src/main/java/org/apache/hudi/common/table/HoodieTableMetaClient.java:
##########
@@ -388,6 +389,7 @@ private void readObject(java.io.ObjectInputStream in) throws IOException, ClassN
     in.defaultReadObject();
 
     storage = null; // will be lazily initialized

Review Comment:
   Related to the blocking thread on `HoodieFileGroupReadState`: `getStorage()` (line ~480) is the lazy init that every task on an executor will now hit concurrently on this shared, deserialized instance. Please make it `synchronized` or volatile double-checked.



##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/HoodieFileGroupReaderFunction.scala:
##########
@@ -0,0 +1,376 @@
+/*
+ * 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.datasources.parquet
+
+import org.apache.hudi.{HoodiePartitionCDCFileGroupMapping, HoodiePartitionFileSliceMapping, HoodieTableSchema, SparkAdapterSupport, SparkFileFormatInternalRowReaderContext}
+import org.apache.hudi.cdc.{CDCFileGroupIterator, HoodieCDCFileGroupSplit, HoodieCDCFileIndex}
+import org.apache.hudi.common.config.{HoodieReaderConfig, TypedProperties}
+import org.apache.hudi.common.fs.FSUtils
+import org.apache.hudi.common.schema.HoodieSchema
+import org.apache.hudi.common.schema.internal.InternalSchema
+import org.apache.hudi.common.table.{HoodieTableMetaClient, ParquetTableSchemaResolver}
+import org.apache.hudi.common.table.log.InstantRange
+import org.apache.hudi.common.table.read.{HoodieFileGroupReader, HoodieRecordReader}
+import org.apache.hudi.common.table.read.lsm.{HoodieLsmFileGroupReader, LsmReaderUtils}
+import org.apache.hudi.common.util.{ConfigUtils, Option => HOption}
+import org.apache.hudi.common.util.collection.ClosableIterator
+import org.apache.hudi.data.CloseableIteratorListener
+import org.apache.hudi.io.storage.HoodieSparkParquetReader.ENABLE_LOGICAL_TIMESTAMP_REPAIR
+import org.apache.hudi.io.storage.VectorConversionUtils
+import org.apache.hudi.storage.StorageConfiguration
+import org.apache.hudi.storage.hadoop.HadoopStorageConfiguration
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.parquet.schema.MessageType
+import org.apache.spark.SparkEnv
+import org.apache.spark.broadcast.Broadcast
+import org.apache.spark.sql.HoodieCatalystExpressionUtils.generateUnsafeProjection
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{JoinedRow, UnsafeProjection}
+import org.apache.spark.sql.execution.datasources.{PartitionedFile, SparkColumnarFileReader, SparkSchemaTransformUtils}
+import org.apache.spark.sql.sources.Filter
+import org.apache.spark.sql.types.StructType
+import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnarBatchUtils}
+import org.apache.spark.util.{SerializableConfiguration, Utils}
+
+import java.io.Closeable
+import java.nio.ByteBuffer
+
+import scala.collection.JavaConverters.mapAsJavaMapConverter
+import scala.reflect.ClassTag
+
+/**
+ * Read-only state of one scan of [[HoodieFileGroupReaderBasedFileFormat]], built on the driver and shared by every
+ * task of an executor through [[HoodieFileGroupReaderFunction]]. Executors only fill thread-safe lazy caches in it;

Review Comment:
   🚨 **Blocking: this claim does not hold yet for everything the state reaches.**
   
   Before this PR each task deserialized its own copy of the format and meta client, so these lazy initializers were effectively single-threaded. Now every concurrent task on an executor hits the same instances through `state`, and two of them are not written for that:
   
   - `HoodieTableMetaClient.getStorage()` is a plain `if (storage == null) storage = ...` with no `volatile` or `synchronized`. `HoodieFileGroupReader` (line 160) and `HoodieLsmFileGroupReader` (line 137) call it for every file. Threads will race to build and overwrite the instance.
   - `InternalSchema` builds `idToName`, `nameToId`, `idToField` and `nameToPosition` lazily (lines ~99-131 and ~267) and the fields are not `volatile`, so the `HashMap` is published unsafely to other threads. `state.internalSchemaOpt` is what schema-on-read column resolution runs through, so a torn read there is a data correctness problem rather than a perf one. `HoodieSchema` already handles its equivalent caches with a documented volatile benign race; `InternalSchema` should match.
   
   Suggested fix, both small and local: `synchronized` (or volatile double-checked init) on `getStorage()`, and `volatile` on the four `InternalSchema` caches. With that, this doc comment becomes true.



-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org