JingsongLi commented on code in PR #8300:
URL: https://github.com/apache/paimon/pull/8300#discussion_r3448011919


##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/execution/SparkFormatTableFileIndex.scala:
##########
@@ -0,0 +1,336 @@
+/*
+ * 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
+
+import org.apache.paimon.CoreOptions
+import org.apache.paimon.spark.catalyst.Compatibility
+import org.apache.paimon.spark.util.OptionUtils
+
+import org.apache.hadoop.fs.{FileStatus, Path}
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.catalog.ExternalCatalogUtils
+import org.apache.spark.sql.catalyst.expressions.{And, AttributeReference, 
BoundReference, Expression, InterpretedPredicate, Literal, Predicate => 
ExprPredicate}
+import org.apache.spark.sql.execution.datasources._
+import org.apache.spark.sql.paimon.shims.SparkShimLoader
+import org.apache.spark.sql.types.{StringType, StructField, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+
+/** Factory for creating partition-aware file indexes for format tables. */
+object SparkFormatTableFileIndex {
+
+  def createFileIndex(
+      options: CaseInsensitiveStringMap,
+      sparkSession: SparkSession,
+      paths: Seq[String],
+      userSpecifiedSchema: Option[StructType],
+      partitionSchema: StructType): PartitioningAwareFileIndex = {
+
+    def globPaths: Boolean = {
+      val entry = options.get(DataSource.GLOB_PATHS_KEY)
+      Option(entry).forall(_ == "true")
+    }
+
+    val caseSensitiveMap = options.asCaseSensitiveMap.asScala.toMap
+    val hadoopConf = 
sparkSession.sessionState.newHadoopConfWithOptions(caseSensitiveMap)
+    if (
+      SparkShimLoader.shim.hasFileStreamSinkMetadata(
+        paths,
+        hadoopConf,
+        sparkSession.sessionState.conf)
+    ) {
+      SparkShimLoader.shim.createPartitionedMetadataLogFileIndex(
+        sparkSession,
+        new Path(paths.head),
+        options.asScala.toMap,
+        userSpecifiedSchema,
+        partitionSchema = partitionSchema)
+    } else {
+      val rootPathsSpecified = DataSource.checkAndGlobPathIfNecessary(
+        paths,
+        hadoopConf,
+        checkEmptyGlobPath = true,
+        checkFilesExist = true,
+        enableGlobbing = globPaths)
+      val fileStatusCache = FileStatusCache.getOrCreate(sparkSession)
+
+      val lazyPruning =
+        partitionSchema.nonEmpty && 
OptionUtils.readFormatTableLazyPartitionPruning()
+
+      if (lazyPruning) {
+        new LazyPartitionPruningFileIndex(
+          sparkSession,
+          rootPathsSpecified,
+          caseSensitiveMap,
+          userSpecifiedSchema,
+          fileStatusCache,
+          partitionSchema)
+      } else {
+        new EagerPartitionListingFileIndex(
+          sparkSession,
+          rootPathsSpecified,
+          caseSensitiveMap,
+          userSpecifiedSchema,
+          fileStatusCache,
+          partitionSchema)
+      }
+    }
+  }
+
+  // Visible to shim-local PartitionedMetadataLogFileIndex subclasses.
+  private[sql] def alignPartitionSpec(
+      inferred: PartitionSpec,
+      partitionSchema: StructType): PartitionSpec = {
+    if (inferred.partitionColumns.isEmpty && partitionSchema.nonEmpty) {
+      PartitionSpec(partitionSchema, inferred.partitions)
+    } else {
+      inferred
+    }
+  }
+}
+
+/** Eagerly lists all files at construction time, like the default 
[[InMemoryFileIndex]]. */
+class EagerPartitionListingFileIndex(
+    sparkSession: SparkSession,
+    rootPathsSpecified: Seq[Path],
+    parameters: Map[String, String],
+    userSpecifiedSchema: Option[StructType],
+    fileStatusCache: FileStatusCache,
+    override val partitionSchema: StructType)
+  extends InMemoryFileIndex(
+    sparkSession,
+    rootPathsSpecified,
+    parameters,
+    userSpecifiedSchema,
+    fileStatusCache) {
+
+  override def partitionSpec(): PartitionSpec =
+    SparkFormatTableFileIndex.alignPartitionSpec(super.partitionSpec(), 
partitionSchema)
+}
+
+/**
+ * A [[PartitioningAwareFileIndex]] that prunes partition directories 
level-by-level using partition
+ * filters, similar to [[CatalogFileIndex]] but discovers partitions from the 
filesystem instead of
+ * the metastore.
+ */
+class LazyPartitionPruningFileIndex(
+    sparkSession: SparkSession,
+    tableLocations: Seq[Path],
+    parameters: Map[String, String],
+    userSpecifiedSchema: Option[StructType],
+    fileStatusCache: FileStatusCache,
+    _partitionSchema: StructType)
+  extends PartitioningAwareFileIndex(sparkSession, parameters, 
userSpecifiedSchema, fileStatusCache)
+  with Logging {
+
+  override val rootPaths: Seq[Path] = tableLocations
+
+  override def partitionSchema: StructType = _partitionSchema
+
+  override def equals(other: Any): Boolean = other match {
+    case o: LazyPartitionPruningFileIndex => rootPaths.toSet == 
o.rootPaths.toSet
+    case _ => false
+  }
+
+  override def hashCode(): Int = rootPaths.toSet.hashCode()
+
+  @volatile private var _fullIndex: InMemoryFileIndex = _
+
+  private def fullIndex: InMemoryFileIndex = {
+    if (_fullIndex == null) {
+      synchronized {
+        if (_fullIndex == null) {
+          _fullIndex = new InMemoryFileIndex(
+            sparkSession,
+            tableLocations,
+            parameters,
+            userSpecifiedSchema,
+            fileStatusCache)
+        }
+      }
+    }
+    _fullIndex
+  }
+
+  override def refresh(): Unit = {
+    fileStatusCache.invalidateAll()
+    synchronized { _fullIndex = null }
+  }
+
+  // Required by PartitioningAwareFileIndex but never accessed — all callers 
are overridden.
+  override protected def leafFiles: mutable.LinkedHashMap[Path, FileStatus] =
+    throw new IllegalStateException()
+  override protected def leafDirToChildrenFiles: Map[Path, Array[FileStatus]] =
+    throw new IllegalStateException()
+
+  override def partitionSpec(): PartitionSpec =
+    PartitionSpec(_partitionSchema, Seq.empty)
+
+  override def sizeInBytes: Long = fullIndex.sizeInBytes

Review Comment:
   Thanks for checking. I agree that once `fullIndex` has already been 
materialized, reusing it in `listFiles` is better than doing another filesystem 
discovery. My remaining concern is the earlier materialization itself: for 
filtered joins, planning still performs the full-table listing before 
execution, so the lazy path does not help that common query shape. Also, 
Spark’s `FileScan.estimateStatistics()` uses the index-wide `sizeInBytes` and 
does not apply the partition filters, so the full listing is not making the 
filtered scan stats partition-aware either. Could the lazy index return a cheap 
unknown/default estimate while `_fullIndex` is still null, and only delegate to 
`fullIndex.sizeInBytes` after an unfiltered scan or `inputFiles` has already 
materialized it? That would preserve lazy pruning for plans that touch stats 
without adding the redundant execution listing you mentioned.



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

To unsubscribe, e-mail: [email protected]

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

Reply via email to