Zouxxyy commented on code in PR #8300: URL: https://github.com/apache/paimon/pull/8300#discussion_r3447788853
########## 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: The 600 files discovered comes from `sizeInBytes` triggered by `DataSourceV2ScanRelation.computeStats()` during planning, not from `listFiles`. With the `_fullIndex != null` check, filtered `listFiles` reuses `fullIndex` for in-memory `prunePartitions` — zero additional FS calls and zero additional `FILES_DISCOVERED`. Without it, `discoverPartitions` would create a `prunedIndex` whose paths miss `FileStatusCache` (keyed by root path, not sub-paths), adding more to the metric (verified: 16 vs 15 in a 5×3 table). To answer your two questions: (1) `FileScan.estimateStatistics()` calls `fileIndex.sizeInBytes` which has no partition filter parameter — to properly fix this we'd need to change Spark's `FileScan` to pass partition filters when computing stats, which is beyond this PR. (2) Keeping filtered `listFiles` lazy after stats are requested would actually be worse — it adds redundant FS calls and increases `FILES_DISCOVERED` due to `FileStatusCache` key mismatch. -- 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]
