This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/master/pr-21071-85628e08a923add24944cfab82629d0c867d730c in repository https://gitbox.apache.org/repos/asf/hudi.git
commit 70ad3825f8650ff3432309498376a9beb93ca3cb Author: voonhous <[email protected]> AuthorDate: Fri Dec 4 15:10:19 2026 +0000 fix(spark): fall back to listing all partitions when partition stats pruning fails (#21071) * fix(spark): fall back to listing all partitions when partition stats pruning fails Column stats pruning honors hoodie.fileIndex.dataSkippingFailureMode, but partition stats and expression index partition pruning were called outside of it, so any error while reading or evaluating the partition stats failed the query even in the default fallback mode. Apply the failure mode there too: fallback lists all partitions, strict rethrows the error as before. Closes #21062 * fix(spark): cover expression index pruning failure and log the fallback once - Test the fallback when the expression index can not be read, alongside partition stats - Assert that strict mode surfaces the error of the corrupted index - Fall back to listing all partitions when the expression index returns partition values that can not be parsed, as the partition stats branch does - Log the fallback cause at warn and its stack trace at debug, since pruning runs twice per query - Use the shared createMetaClient helper in the test suite * fix(spark): drop the unreachable partition path fallback in the expression index branch Listing all partitions converts the same partition path again, so the fallback could not recover. Note that only the partition stats case pins that strict mode rethrows a partition pruning failure * fix(spark): match dataSkippingFailureMode case-insensitively and fail clearly on unknown values hoodie.fileIndex.dataSkippingFailureMode was matched against the exact strings fallback and strict with no default case, so STRICT or a typo surfaced as a scala.MatchError naming the value once an index lookup failed, and the index error was lost. Read the mode through DataSkippingFailureMode.fromConf, which matches it case-insensitively and throws a HoodieException naming the config and its valid values, with the index error as the cause, for an unknown value. Use it in SparkBaseIndexSupport#computeCandidateIsStrict, and in HoodieFileIndex for the candidate file lookup and partition pruning. * test(spark): check partition and file pruning failure modes separately - For a corrupted index that fails partition pruning, also call prunePartitionsAndGetFileSlices directly, so strict and unknown modes are pinned at that stage and not only by the file pruning lookup that reads the same expression index - Add a case that corrupts column_stats with partition_stats intact, so the failure goes through both file pruning handlers --- .../scala/org/apache/hudi/HoodieFileIndex.scala | 46 ++++++- .../org/apache/hudi/SparkBaseIndexSupport.scala | 6 +- .../TestPartitionStatsIndexWithSql.scala | 135 ++++++++++++++++----- 3 files changed, 152 insertions(+), 35 deletions(-) diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieFileIndex.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieFileIndex.scala index 559a4d41475e..9b4d69fa345e 100644 --- a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieFileIndex.scala +++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieFileIndex.scala @@ -282,9 +282,9 @@ case class HoodieFileIndex(spark: SparkSession, case Failure(e) => logError("Failed to lookup candidate files in File Index", e) - spark.sqlContext.getConf(DataSkippingFailureMode.configName, DataSkippingFailureMode.Fallback.value) match { - case DataSkippingFailureMode.Fallback.value => Option.empty - case DataSkippingFailureMode.Strict.value => throw new HoodieException(e); + DataSkippingFailureMode.fromConf(spark, e) match { + case DataSkippingFailureMode.Fallback => Option.empty + case DataSkippingFailureMode.Strict => throw new HoodieException(e); } } @@ -354,7 +354,9 @@ case class HoodieFileIndex(spark: SparkSession, } } else if (isPartitionedTable && isDataSkippingEnabled && partitionStatsIndexSupport.supportsQueryType(options)) { // Both PARTITION_STATS and the expression index fallback use latest-snapshot partition statistics. - val prunedPartitionPaths = partitionStatsIndexSupport.prunePartitions(this, dataFilters) + val prunedPartitionPaths = pruneWithFailureMode("partition stats") { + partitionStatsIndexSupport.prunePartitions(this, dataFilters) + } if (prunedPartitionPaths.nonEmpty) { try { (true, prunedPartitionPaths.get.map(e => convertToPartitionPath(e)).toSeq) @@ -366,7 +368,9 @@ case class HoodieFileIndex(spark: SparkSession, } else if (isExpressionIndexEnabled) { val expressionIndexSupport = getExpressionIndexSupport lazy val filterReferencedColumns = collectReferencedColumns(spark, dataFilters, schema) - val exprIndexPrunedPartitionsOpt = expressionIndexSupport.prunePartitions(this, dataFilters, filterReferencedColumns) + val exprIndexPrunedPartitionsOpt = pruneWithFailureMode("expression") { + expressionIndexSupport.prunePartitions(this, dataFilters, filterReferencedColumns) + } if (exprIndexPrunedPartitionsOpt.nonEmpty) { (true, exprIndexPrunedPartitionsOpt.get.map(e => convertToPartitionPath(e)).toSeq) } else { @@ -390,6 +394,28 @@ case class HoodieFileIndex(spark: SparkSession, (Option.apply(partition), fileSlices.asScala.map(f => f.withLogFiles(includeLogFiles)).toSeq) }).toSeq) } + /** + * Applies [[DataSkippingFailureMode]] to partition pruning, as [[SparkBaseIndexSupport.computeCandidateIsStrict]] + * does to file pruning: on a failure, no pruning (all partitions are listed) in fallback mode, and the + * error in strict mode + */ + private def pruneWithFailureMode(indexName: String)(prune: => Option[Set[String]]): Option[Set[String]] = { + try { + prune + } catch { + case NonFatal(e) => + DataSkippingFailureMode.fromConf(spark, e) match { + case DataSkippingFailureMode.Fallback => + // NOTE: Partitions are pruned at planning and again when listing files, so the stack trace is + // logged at debug level only + logWarning(s"Failed to prune partitions with the $indexName index, listing all partitions: $e") + logDebug(s"Failed to prune partitions with the $indexName index", e) + Option.empty + case DataSkippingFailureMode.Strict => throw e + } + } + } + private def getExpressionIndexSupport: ExpressionIndexSupport = { indicesSupport.find(indexSupport => indexSupport.isInstanceOf[ExpressionIndexSupport]).get.asInstanceOf[ExpressionIndexSupport] } @@ -537,6 +563,16 @@ object HoodieFileIndex extends Logging { val Fallback: Val = Val("fallback") val Strict: Val = Val("strict") + + /** + * Returns the failure mode set in the session, matched case-insensitively. An unknown value fails with + * `indexError`, the error of the failed index lookup, as the cause + */ + def fromConf(spark: SparkSession, indexError: Throwable): DataSkippingFailureMode = { + val mode = spark.sqlContext.getConf(configName, Fallback.value) + values.find(_.toString.equalsIgnoreCase(mode)).getOrElse(throw new HoodieException( + s"Invalid value '$mode' for $configName, expected one of: ${values.mkString(", ")}", indexError)) + } } /** diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/SparkBaseIndexSupport.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/SparkBaseIndexSupport.scala index 92f4c040596f..bb44c43295fb 100644 --- a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/SparkBaseIndexSupport.scala +++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/SparkBaseIndexSupport.scala @@ -71,9 +71,9 @@ abstract class SparkBaseIndexSupport(spark: SparkSession, computeCandidateFileNames(fileIndex, queryFilters, queryReferencedColumns, prunedPartitionsAndFileSlices, shouldPushDownFilesFilter) } catch { case NonFatal(e) => - spark.sqlContext.getConf(DataSkippingFailureMode.configName, DataSkippingFailureMode.Fallback.value) match { - case DataSkippingFailureMode.Fallback.value => Option.empty - case DataSkippingFailureMode.Strict.value => throw e; + DataSkippingFailureMode.fromConf(spark, e) match { + case DataSkippingFailureMode.Fallback => Option.empty + case DataSkippingFailureMode.Strict => throw e; } } } diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestPartitionStatsIndexWithSql.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestPartitionStatsIndexWithSql.scala index 1e10ce1c8618..e0468447ac47 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestPartitionStatsIndexWithSql.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestPartitionStatsIndexWithSql.scala @@ -20,23 +20,30 @@ package org.apache.hudi.functional import org.apache.hudi.{DataSourceReadOptions, HoodieFileIndex} +import org.apache.hudi.HoodieFileIndex.DataSkippingFailureMode import org.apache.hudi.client.common.HoodieSparkEngineContext import org.apache.hudi.common.config.HoodieMetadataConfig import org.apache.hudi.common.model.{FileSlice, WriteOperationType} import org.apache.hudi.common.table.{HoodieTableConfig, HoodieTableMetaClient} import org.apache.hudi.common.table.view.HoodieTableFileSystemView import org.apache.hudi.common.testutils.HoodieTestUtils +import org.apache.hudi.exception.HoodieException import org.apache.hudi.metadata.{HoodieBackedTableMetadata, MetadataPartitionType} -import org.apache.hudi.metadata.HoodieTableMetadataUtil.getPartitionStatsIndexKey -import org.apache.hudi.metadata.MetadataPartitionType.PARTITION_STATS +import org.apache.hudi.metadata.HoodieTableMetadataUtil.{getPartitionStatsIndexKey, PARTITION_NAME_EXPRESSION_INDEX_PREFIX} +import org.apache.hudi.metadata.MetadataPartitionType.{COLUMN_STATS, PARTITION_STATS} +import org.apache.hudi.testutils.HoodieClientTestUtils.createMetaClient import org.apache.hudi.util.JFunction -import org.apache.spark.sql.catalyst.expressions.{And, AttributeReference, Expression, GreaterThan, IsNotNull, LessThan, Literal, Or} +import org.apache.spark.sql.catalyst.expressions.{And, AttributeReference, EqualTo, Expression, GreaterThan, IsNotNull, LessThan, Literal, Or, Upper} import org.apache.spark.sql.hudi.common.HoodieSparkSqlTestBase import org.apache.spark.sql.types.{IntegerType, StringType} import org.junit.jupiter.api.{BeforeAll, Tag} import org.junit.jupiter.api.Assertions.{assertFalse, assertTrue} +import java.io.File +import java.nio.charset.StandardCharsets +import java.nio.file.Files + import scala.collection.JavaConverters._ @Tag("functional") @@ -88,17 +95,11 @@ class TestPartitionStatsIndexWithSql extends HoodieSparkSqlTestBase { Seq("2", s"dt=$partitionValue", 2, "a2", 10, 1000, partitionValue) ) - var metaClient = HoodieTableMetaClient.builder() - .setBasePath(tablePath) - .setConf(HoodieTestUtils.getDefaultStorageConf) - .build() + var metaClient = createMetaClient(spark, tablePath) // Validate partition_stats index exists assertTrue(metaClient.getTableConfig.getMetadataPartitions.contains(PARTITION_STATS.getPartitionPath)) spark.sql(s"drop index partition_stats on $tableName") - metaClient = HoodieTableMetaClient.builder() - .setBasePath(tablePath) - .setConf(HoodieTestUtils.getDefaultStorageConf) - .build() + metaClient = createMetaClient(spark, tablePath) // Validate partition_stats index does not exist assertFalse(metaClient.getTableConfig.getMetadataPartitions.contains(PARTITION_STATS.getPartitionPath)) } @@ -139,10 +140,7 @@ class TestPartitionStatsIndexWithSql extends HoodieSparkSqlTestBase { val partitionValue = "2021-05-06" // Check the missing properties for spark sql - val metaClient = HoodieTableMetaClient.builder() - .setBasePath(tablePath) - .setConf(HoodieTestUtils.getDefaultStorageConf) - .build() + val metaClient = createMetaClient(spark, tablePath) val properties = metaClient.getTableConfig.getProps.asScala.toMap assertResult(true)(properties.contains(HoodieTableConfig.CREATE_SCHEMA.key)) assertResult("dt")(properties(HoodieTableConfig.PARTITION_FIELDS.key)) @@ -237,10 +235,7 @@ class TestPartitionStatsIndexWithSql extends HoodieSparkSqlTestBase { ) // Validate partition_stats index exists - val metaClient = HoodieTableMetaClient.builder() - .setBasePath(tablePath) - .setConf(HoodieTestUtils.getDefaultStorageConf) - .build() + val metaClient = createMetaClient(spark, tablePath) assertResult(tableName)(metaClient.getTableConfig.getTableName) assertTrue(metaClient.getTableConfig.getMetadataPartitions.contains(PARTITION_STATS.getPartitionPath)) val fileIndex = HoodieFileIndex(spark, metaClient, None, Map("path" -> metaClient.getBasePath.toString)) @@ -446,10 +441,7 @@ class TestPartitionStatsIndexWithSql extends HoodieSparkSqlTestBase { Seq(getPartitionStatsIndexKey("ts=30", "price"), 3000, 4000, true) ) // verify file pruning - var metaClient = HoodieTableMetaClient.builder() - .setBasePath(tablePath) - .setConf(HoodieTestUtils.getDefaultStorageConf) - .build() + var metaClient = createMetaClient(spark, tablePath) verifyFilePruning(Map.apply(DataSourceReadOptions.ENABLE_DATA_SKIPPING.key -> "true", HoodieMetadataConfig.ENABLE.key -> "true"), GreaterThan(AttributeReference("price", IntegerType)(), Literal(3000)), metaClient, isDataSkippingExpected = true) @@ -618,10 +610,7 @@ class TestPartitionStatsIndexWithSql extends HoodieSparkSqlTestBase { ) // Validate partition_stats index exists - val metaClient = HoodieTableMetaClient.builder() - .setBasePath(tablePath) - .setConf(HoodieTestUtils.getDefaultStorageConf) - .build() + val metaClient = createMetaClient(spark, tablePath) assertResult(tableName)(metaClient.getTableConfig.getTableName) assertTrue(metaClient.getTableConfig.getMetadataPartitions.contains(PARTITION_STATS.getPartitionPath)) @@ -688,6 +677,98 @@ class TestPartitionStatsIndexWithSql extends HoodieSparkSqlTestBase { } } + test("Test index read failure honors the data skipping failure mode") { + val rider = AttributeReference("rider", StringType)() + Seq( + // partition stats prune `rider > ...`, so corrupting them fails partition pruning + (PARTITION_STATS.getPartitionPath, "rider > 'rider-D'", GreaterThan(rider, Literal("rider-D")), false, true), + // partition stats skip `upper(rider) = ...`, which the expression index prunes instead. File pruning reads the + // same corrupted partition, so partition pruning is also checked on its own below + (s"${PARTITION_NAME_EXPRESSION_INDEX_PREFIX}idx_upper_rider", "upper(rider) = 'RIDER-E'", + EqualTo(Upper(rider), Literal("RIDER-E")), true, true), + // partition stats are intact, so partition pruning succeeds and file pruning fails on the column stats read + (COLUMN_STATS.getPartitionPath, "rider > 'rider-D'", GreaterThan(rider, Literal("rider-D")), false, false) + ).foreach { case (corruptedPartition, filter, dataFilter, withExpressionIndex, failsPartitionPruning) => + withTempDir { tmp => + val tableName = generateTableName + val tablePath = s"${tmp.getCanonicalPath}/$tableName" + spark.sql( + s""" + | create table $tableName ( + | ts BIGINT, + | uuid STRING, + | rider STRING, + | state STRING + |) using hudi + | options( + | type = 'cow', + | primaryKey ='uuid', + | orderingFields = 'ts', + | hoodie.metadata.index.partition.stats.enable = 'true', + | hoodie.metadata.index.column.stats.enable = 'true', + | hoodie.metadata.index.column.stats.column.list = 'rider' + |) + |PARTITIONED BY (state) + |location '$tablePath' + """.stripMargin + ) + spark.sql(s"INSERT INTO $tableName VALUES (1, 'u1', 'rider-A', 'california'), (2, 'u2', 'rider-E', 'texas')") + if (withExpressionIndex) { + spark.sql(s"create index idx_upper_rider on $tableName using column_stats(rider) options(expr='upper')") + } + assertTrue(createMetaClient(spark, tablePath).getTableConfig.getMetadataPartitions.contains(corruptedPartition)) + + // Corrupt the index so that reading it fails + val indexFiles = new File(s"$tablePath/.hoodie/metadata/$corruptedPartition").listFiles() + .filter(f => f.isFile && !f.getName.startsWith(".")) + assertTrue(indexFiles.nonEmpty) + indexFiles.foreach(f => Files.write(f.toPath, "not an index file".getBytes(StandardCharsets.UTF_8))) + + val query = s"select uuid, rider, state from $tableName where $filter" + // Runs the query, and when the corrupted index fails partition pruning, partition pruning on its own + val failingRuns = Seq[() => Unit](() => spark.sql(query).collect()) ++ + (if (failsPartitionPruning) Seq[() => Unit](() => prunePartitions(tablePath, dataFilter)) else Seq.empty) + val readConfs = Seq("hoodie.metadata.enable" -> "true", "hoodie.enable.data.skipping" -> "true") + withSQLConf(readConfs :+ (DataSkippingFailureMode.configName -> "fallback"): _*) { + checkAnswer(query)(Seq("u2", "rider-E", "texas")) + // Partition pruning lists all partitions if the corrupted index fails it, and prunes to texas otherwise + val (isPruned, prunedPartitions) = prunePartitions(tablePath, dataFilter) + assertResult(!failsPartitionPruning)(isPruned) + assertResult(if (failsPartitionPruning) 2 else 1)(prunedPartitions.size) + } + // The mode is matched case-insensitively + Seq("strict", "STRICT").foreach { strictMode => + withSQLConf(readConfs :+ (DataSkippingFailureMode.configName -> strictMode): _*) { + // The error of the corrupted index read surfaces as is + failingRuns.foreach(failingRun => checkExceptionContain(new Runnable { + override def run(): Unit = failingRun() + })(corruptedPartition)) + } + } + withSQLConf(readConfs :+ (DataSkippingFailureMode.configName -> "unknown"): _*) { + // An unknown mode names the config and keeps the error of the corrupted index read as the cause + failingRuns.foreach { failingRun => + val e = intercept[HoodieException](failingRun()) + assertTrue(e.getMessage.contains( + s"Invalid value 'unknown' for ${DataSkippingFailureMode.configName}, expected one of: fallback, strict"), e.getMessage) + assertTrue(HoodieTestUtils.getRootCause(e).getMessage.contains(corruptedPartition), e.getMessage) + } + } + } + } + } + + private def prunePartitions(tablePath: String, dataFilter: Expression): (Boolean, Seq[_]) = { + val opts = Map("path" -> tablePath, DataSourceReadOptions.ENABLE_DATA_SKIPPING.key -> "true", + HoodieMetadataConfig.ENABLE.key -> "true") + val fileIndex = HoodieFileIndex(spark, createMetaClient(spark, tablePath), None, opts, includeLogFiles = true) + try { + fileIndex.prunePartitionsAndGetFileSlices(Seq(dataFilter), Seq.empty) + } finally { + fileIndex.close() + } + } + private def getLatestDataFilesCount(includeLogFiles: Boolean = true, metaClient: HoodieTableMetaClient) = { var totalLatestDataFiles = 0L val fsView: HoodieTableFileSystemView = getTableFileSystemView(metaClient)
