Zouxxyy commented on code in PR #8300: URL: https://github.com/apache/paimon/pull/8300#discussion_r3449458816
########## 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: Went a step beyond a flat default. A constant `defaultSizeInBytes` keeps it lazy but means a small partitioned table is *never* broadcast. So while `_fullIndex` is null, `sizeInBytes` now returns a **cheap estimate**: partition count from per-level fan-outs along one path × average size of a few sampled leaf partitions. It uses `fs.listStatus` directly — no full index, no `HiveCatalogMetrics`. Falls back to `defaultSizeInBytes` on empty table / empty sample / overflow so we never underestimate and wrongly broadcast a large table. The exact size is used once `_fullIndex` is materialized (unfiltered scan / `inputFiles`). Added tests in `FormatTableTestBase`: a small partitioned table is now broadcast (planned as SMJ before), filtered-join file discovery stays at the pruned count, and empty-table joins don't misfire. -- 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]
