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


##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/execution/SparkFormatTableFileIndex.scala:
##########
@@ -0,0 +1,416 @@
+/*
+ * 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 = _
+
+  @volatile private var _estimatedSizeInBytes: Long = -1L
+
+  // Leaf partitions sampled to estimate the average partition size.
+  private val SAMPLE_PARTITIONS = 3
+
+  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
+      _estimatedSizeInBytes = -1L
+    }
+  }
+
+  // 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)
+
+  // Used only by the optimizer for broadcast decisions; a full listing would 
defeat lazy pruning,
+  // so estimate cheaply (idempotent, cached) until the full index exists, 
then report its exact size.
+  override def sizeInBytes: Long = {
+    val idx = _fullIndex
+    if (idx != null) {
+      idx.sizeInBytes
+    } else {
+      if (_estimatedSizeInBytes < 0) {
+        _estimatedSizeInBytes = estimateSizeBySampling()
+      }
+      _estimatedSizeInBytes
+    }
+  }
+
+  /**
+   * Cheap whole-table size estimate without a full listing: partition count 
from per-level fan-outs
+   * along one path, times the average size of up to [[SAMPLE_PARTITIONS]] 
sampled leaf partitions.
+   * Falls back to `defaultSizeInBytes` (not broadcast) on empty table / empty 
sample / overflow, so
+   * we never underestimate and wrongly broadcast a large table. Reads via 
`fs.listStatus`, so it
+   * never touches `HiveCatalogMetrics`.
+   */
+  private def estimateSizeBySampling(): Long = {
+    val unknownSize = sparkSession.sessionState.conf.defaultSizeInBytes
+    val levels = _partitionSchema.fields.length
+
+    var path = tableLocations.head
+    var partitionCount = 1L
+    var leafSiblings: Array[FileStatus] = Array.empty
+    var level = 0
+    while (level < levels) {
+      val fs = path.getFileSystem(hadoopConf)
+      val subdirs =
+        try {
+          fs.listStatus(path)
+            .filter(s => s.isDirectory && isDataPath(s.getPath.getName))
+            .filter(_.getPath.getName.contains("="))
+        } catch {
+          case _: java.io.FileNotFoundException => Array.empty[FileStatus]
+        }
+      if (subdirs.isEmpty) {
+        return unknownSize
+      }
+      partitionCount *= subdirs.length
+      leafSiblings = subdirs
+      path = subdirs.head.getPath

Review Comment:
   This estimator can substantially underestimate skewed/non-rectangular 
partition trees because it only follows the first directory at each level. For 
example, with `p1=1/p2=1` containing a 1-byte file and `p1=2/p2=1..100` 
containing 1000-byte files, the current logic sees `p1` fanout 2, follows 
`p1=1`, sees only one `p2` leaf, and returns about 2 bytes while the table is 
about 100 KB. That violates the “never underestimate and wrongly broadcast a 
large table” guarantee and can make Spark broadcast a table that is actually 
above the threshold. Could we either fall back to `defaultSizeInBytes` when the 
sampled path cannot prove the lower levels are representative, or compute a 
conservative upper estimate across sampled/known branches?



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