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-21072-fa803594d44d1dddcd6f2c699c450edc59b6321b in repository https://gitbox.apache.org/repos/asf/hudi.git
commit b53aaecb6a5e15e59c87ba47cd79f985c6c642ab Author: voonhous <[email protected]> AuthorDate: Fri Dec 4 14:28:19 2026 +0000 fix(spark): skip index lookups for filters on strings of a non-binary collation (#21072) * fix(spark): skip index lookups for filters on strings of a non-binary collation Index stats are byte-ordered and index keys are the values' bytes, while Spark 4 compares a string of a non-binary collation (for ex UTF8_LCASE) under that collation, so data skipping could prune files holding matching rows. Hudi rejects collated columns at write time today, so this cannot be reached yet; guard it before they are accepted. HoodieFileIndex#filterFileSlices now leaves out every data filter that holds such a string, at any depth, from partition and file pruning; Spark still applies those filters to the rows read. The check is a new SparkAdapter#hasNonBinaryCollation, false on Spark 3. Closes #21063 * fix(spark): keep collated partition predicates out of partition path listing - Partition path prefix analysis matched a collated string literal against the path bytes and dropped partitions it equals under its collation (for ex 'cafe' with an accent under UNICODE_AI); such predicates no longer narrow the listing, pruning still applies them - Share the collation check between partition listing and data skipping - Move the adapter detection test next to the other adapter tests, skip it before Spark 4 and cover collated map keys - Fold the data skipping case into testDataSkippingCandidatesAndSparkJobs, which also covers partition stats and a collated filter mixed with a prunable one * test(spark): fold the repeated id > 350 assertion into the mixed filter check * fix(spark): keep the collation of literals rewritten for the timestamp key generator convertFilterForTimestampKeyGenerator rebuilt every string literal of a partition filter as a plain StringType literal, so on Spark 4 a literal of a collated string type lost its collation. With the literal on the left, for ex '2021-jan-01' COLLATE UTF8_LCASE = dt, partition pruning then compared by bytes and dropped the partition 2021-Jan-01. Build the rewritten literals with the incoming data type. --- .../org/apache/spark/sql/hudi/SparkAdapter.scala | 6 ++ .../scala/org/apache/hudi/HoodieFileIndex.scala | 13 ++-- .../apache/hudi/SparkHoodieTableFileIndex.scala | 17 ++++- .../org/apache/hudi/TestHoodieFileIndex.scala | 89 ++++++++++++++++++++++ .../TestSparkAdapterNonBinaryCollation.scala | 42 ++++++++++ .../spark/sql/adapter/BaseSpark4Adapter.scala | 10 ++- 6 files changed, 170 insertions(+), 7 deletions(-) diff --git a/hudi-client/hudi-spark-client/src/main/scala/org/apache/spark/sql/hudi/SparkAdapter.scala b/hudi-client/hudi-spark-client/src/main/scala/org/apache/spark/sql/hudi/SparkAdapter.scala index d88da540558f..3c54acf34902 100644 --- a/hudi-client/hudi-spark-client/src/main/scala/org/apache/spark/sql/hudi/SparkAdapter.scala +++ b/hudi-client/hudi-spark-client/src/main/scala/org/apache/spark/sql/hudi/SparkAdapter.scala @@ -631,6 +631,12 @@ trait SparkAdapter extends Serializable { * Without the error class, it is the given exception. */ def mergeCardinalityViolation(multipleMatches: HoodieMultipleMatchesException): Throwable = multipleMatches + + /** + * Whether the type holds, at any depth, a string whose collation does not compare or order by its UTF-8 bytes, + * for ex `STRING COLLATE UTF8_LCASE`. Spark 3 has no collations. + */ + def hasNonBinaryCollation(dataType: DataType): Boolean = false } /** 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..5fe987f64d2f 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 @@ -261,14 +261,17 @@ case class HoodieFileIndex(spark: SparkSession, def filterFileSlices(dataFilters: Seq[Expression], partitionFilters: Seq[Expression], isPartitionPruneOnly: Boolean = false) : Seq[(Option[BaseHoodieTableFileIndex.PartitionPath], Seq[FileSlice])] = { + // NOTE: Index stats are byte-ordered and index keys are the values' bytes, so a filter over a string of a + // non-binary collation can not use any index. Spark still applies it to the rows read + val indexableDataFilters = dataFilters.filterNot(hasNonBinaryCollation) val (isPruned, prunedPartitionsAndFileSlices) = - prunePartitionsAndGetFileSlices(dataFilters, partitionFilters) + prunePartitionsAndGetFileSlices(indexableDataFilters, partitionFilters) hasPushedDownPartitionPredicates = true // Skip data skipping when: no file slices, no data filters, or partition-prune-only mode // (planning phase — data skipping runs later during execution). - if (prunedPartitionsAndFileSlices.isEmpty || dataFilters.isEmpty || isPartitionPruneOnly) { + if (prunedPartitionsAndFileSlices.isEmpty || indexableDataFilters.isEmpty || isPartitionPruneOnly) { prunedPartitionsAndFileSlices } else { // Look up candidate files names in the col-stats or record level index, if all of the following conditions are true @@ -277,7 +280,7 @@ case class HoodieFileIndex(spark: SparkSession, // - Record-level Index is present // - List of predicates (filters) is present val candidateFilesNamesOpt: Option[Set[String]] = - lookupCandidateFilesInMetadataTable(dataFilters, prunedPartitionsAndFileSlices, isPruned) match { + lookupCandidateFilesInMetadataTable(indexableDataFilters, prunedPartitionsAndFileSlices, isPruned) match { case Success(opt) => opt case Failure(e) => logError("Failed to lookup candidate files in File Index", e) @@ -701,7 +704,7 @@ object HoodieFileIndex extends Logging { case Literal(value, dataType) if dataType.isInstanceOf[StringType] => try { val converted = outDateFormat.format(inDateFormat.parse(value.toString)) - Literal(UTF8String.fromString(converted), StringType) + Literal(UTF8String.fromString(converted), dataType) } catch { case _: java.text.ParseException => try { @@ -709,7 +712,7 @@ object HoodieFileIndex extends Logging { } catch { case e: Exception => throw new HoodieException("Partition filter for TimestampKeyGenerator cannot be converted to format " + outDateFormat.toString, e) } - Literal(UTF8String.fromString(value.toString), StringType) + Literal(UTF8String.fromString(value.toString), dataType) } } } diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/SparkHoodieTableFileIndex.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/SparkHoodieTableFileIndex.scala index 3098dfebbc1b..b2dddb7c31b6 100644 --- a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/SparkHoodieTableFileIndex.scala +++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/SparkHoodieTableFileIndex.scala @@ -296,7 +296,14 @@ class SparkHoodieTableFileIndex(spark: SparkSession, logInfo("Partition path prefix analysis is disabled; falling back to fetching all partitions") getAllQueryPartitionPaths.asScala } else { - tryPushDownPartitionPredicates(partitionColumnNames, partitionPruningPredicates) + // NOTE: Partition paths are matched by their bytes, so a predicate over a string of a non-binary collation + // can not narrow the listing. The pruning below still applies it, under its collation + val pushablePredicates = partitionPruningPredicates.filterNot(hasNonBinaryCollation) + if (pushablePredicates.isEmpty) { + getAllQueryPartitionPaths.asScala + } else { + tryPushDownPartitionPredicates(partitionColumnNames, pushablePredicates) + } } // NOTE: In some cases, like for ex, when non-encoded slash '/' is used w/in the partition column's value, @@ -338,6 +345,14 @@ class SparkHoodieTableFileIndex(spark: SparkSession, // nested_record.level = 'INFO' → GetStructField path "nested_record.level" → true // nested_record.nested_int = 10 → GetStructField path "nested_record.nested_int" → false // IsNotNull(nested_record) → AttributeReference "nested_record" not in partitionColumnNames → false + /** + * Whether the expression holds a string whose collation does not compare or order by its UTF-8 bytes (Spark 4, + * for ex "a" = "A" under UTF8_LCASE). Partition paths, index stats and index keys are byte-ordered, so such a + * predicate can not be matched against them + */ + protected def hasNonBinaryCollation(expr: Expression): Boolean = + expr.find(e => sparkAdapter.hasNonBinaryCollation(e.dataType)).isDefined + private def referencesOnlyPartitionColumns(expr: Expression): Boolean = { val resolve = spark.sessionState.analyzer.resolver val partitionColumnNames = getPartitionColumns diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/TestHoodieFileIndex.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/TestHoodieFileIndex.scala index dd5752525135..c8b3016a38a8 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/TestHoodieFileIndex.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/TestHoodieFileIndex.scala @@ -54,6 +54,7 @@ import org.apache.spark.sql.types._ import org.apache.spark.unsafe.types.UTF8String import org.junit.jupiter.api.{BeforeEach, Test} import org.junit.jupiter.api.Assertions.{assertEquals, assertFalse, assertThrows, assertTrue} +import org.junit.jupiter.api.Assumptions.assumeTrue import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.{Arguments, CsvSource, EnumSource, MethodSource, ValueSource} @@ -905,6 +906,94 @@ class TestHoodieFileIndex extends HoodieSparkClientTestBase with ScalaAssertionS } } } + + // Index stats are byte-ordered, so a filter on a string of a non-binary collation (Spark 4) keeps every + // partition and file group, while the other conjuncts still prune + if (HoodieSparkUtils.gteqSpark4_0) { + val collated = DataType.fromDDL("STRING COLLATE UTF8_LCASE") + val fileIndex = HoodieFileIndex(spark, metaClient, Option.empty, queryOpts ++ Map( + HoodieMetadataConfig.ENABLE.key -> "true", + DataSourceReadOptions.ENABLE_DATA_SKIPPING.key -> "true"), NoopCache, + includeLogFiles = tableType == HoodieTableType.MERGE_ON_READ) + def candidates(filters: Seq[Expression]): (Set[String], Set[String]) = { + val slices = fileIndex.filterFileSlices(filters, Seq.empty) + (slices.map(_._1.get.getPath).toSet, slices.flatMap(_._2).map(_.getFileId).toSet) + } + val collatedName = EqualTo(AttributeReference("name", collated)(), Literal.create(UTF8String.fromString("0120"), collated)) + val idAbove350 = HoodieCatalystExpressionUtils.resolveExpr(spark, "id > 350", fileIndex.schema) + assertEquals((Set("a", "b"), allFileGroups), candidates(Seq(collatedName))) + assertEquals((Set("b"), Set(fileGroupOfId(399))), candidates(Seq(collatedName, idAbove350))) + } + } + + /** + * Partition paths are matched by their bytes, so a partition predicate on a string of a non-binary collation must + * not narrow the listing to the partition path its literal spells: under UNICODE_AI, 'cafe' also matches 'cafe' + * with an accent + */ + @Test + def testPartitionListingIgnoresPredicatesOnNonBinaryCollations(): Unit = { + assumeTrue(HoodieSparkUtils.gteqSpark4_0, "Collations only exist on Spark 4") + val _spark = spark + import _spark.implicits._ + Seq((1, "cafe"), (2, "caf\u00e9"), (3, "tea")).toDF("id", "p") + .write.format("hudi") + .option(HoodieWriteConfig.TBL_NAME.key, "hoodie_test") + .option(RECORDKEY_FIELD.key, "id") + .option(PARTITIONPATH_FIELD.key, "p") + .option(HoodieTableConfig.ORDERING_FIELDS.key, "id") + .mode(SaveMode.Overwrite) + .save(basePath) + metaClient = HoodieTableMetaClient.reload(metaClient) + + val collated = DataType.fromDDL("STRING COLLATE UNICODE_AI") + // NOTE: The literal comes first so that the comparison takes its collation: the table's partition column is a + // plain string, since Hudi does not write collated columns yet + val filter = EqualTo(Literal.create(UTF8String.fromString("cafe"), collated), AttributeReference("p", collated)()) + val fileIndex = HoodieFileIndex(spark, metaClient, None, + queryOpts + (DataSourceReadOptions.FILE_INDEX_LISTING_MODE_OVERRIDE.key -> FILE_INDEX_LISTING_MODE_LAZY)) + assertEquals(Set("cafe", "caf\u00e9"), fileIndex.listFiles(Seq(filter), Seq.empty).map(_.values.getString(0)).toSet) + } + + /** + * The partition filters of a table with the timestamp key generator are rewritten into its output format, and the + * rewritten literals keep their collation: under UTF8_LCASE, '2021-jan-01' matches the partition '2021-Jan-01' + */ + @Test + def testTimestampKeyGeneratorFilterKeepsCollation(): Unit = { + assumeTrue(HoodieSparkUtils.gteqSpark4_0, "Collations only exist on Spark 4") + val _spark = spark + import _spark.implicits._ + Seq((1, "2021-01-01"), (2, "2021-02-01")).toDF("id", "dt") + .write.format("hudi") + .option(HoodieWriteConfig.TBL_NAME.key, "hoodie_test") + .option(RECORDKEY_FIELD.key, "id") + .option(PARTITIONPATH_FIELD.key, "dt") + .option(HoodieTableConfig.ORDERING_FIELDS.key, "id") + .option(KEYGENERATOR_CLASS_NAME.key, "org.apache.hudi.keygen.TimestampBasedKeyGenerator") + .option(TIMESTAMP_TYPE_FIELD.key, TimestampType.DATE_STRING.name()) + .option(TIMESTAMP_INPUT_DATE_FORMAT.key, "yyyy-MM-dd") + .option(TIMESTAMP_OUTPUT_DATE_FORMAT.key, "yyyy-MMM-dd") + .mode(SaveMode.Overwrite) + .save(basePath) + metaClient = HoodieTableMetaClient.reload(metaClient) + + val collated = DataType.fromDDL("STRING COLLATE UTF8_LCASE") + def filterOn(value: String): Expression = + EqualTo(Literal.create(UTF8String.fromString(value), collated), AttributeReference("dt", collated)()) + // '2021-01-01' is converted from the input format, '2021-jan-01' only parses in the output format and is kept + Seq("2021-01-01" -> "2021-Jan-01", "2021-jan-01" -> "2021-jan-01").foreach { case (value, converted) => + val literals = HoodieFileIndex.convertFilterForTimestampKeyGenerator(metaClient, Seq(filterOn(value))) + .flatMap(_.collect { case literal: Literal => literal }) + assertEquals(Seq((UTF8String.fromString(converted), collated)), literals.map(l => (l.value, l.dataType))) + } + + // NOTE: The literal comes first so that the comparison takes its collation. Filters are only converted for a file + // index that embeds file slices, as the one of a Spark query does + val fileIndex = HoodieFileIndex(spark, metaClient, None, + queryOpts + (DataSourceReadOptions.FILE_INDEX_LISTING_MODE_OVERRIDE.key -> FILE_INDEX_LISTING_MODE_LAZY), + shouldEmbedFileSlices = true) + assertEquals(Set("2021-Jan-01"), fileIndex.listFiles(Seq(filterOn("2021-jan-01")), Seq.empty).map(_.values.getString(0)).toSet) } /** diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/adapter/TestSparkAdapterNonBinaryCollation.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/adapter/TestSparkAdapterNonBinaryCollation.scala new file mode 100644 index 000000000000..8019f68e6147 --- /dev/null +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/adapter/TestSparkAdapterNonBinaryCollation.scala @@ -0,0 +1,42 @@ +/* + * 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.adapter + +import org.apache.hudi.{HoodieSparkUtils, SparkAdapterSupport} + +import org.apache.spark.sql.types.{DataType, IntegerType, StringType} +import org.junit.jupiter.api.Assertions.{assertFalse, assertTrue} +import org.junit.jupiter.api.Assumptions.assumeTrue +import org.junit.jupiter.api.Test + +class TestSparkAdapterNonBinaryCollation extends SparkAdapterSupport { + + @Test + def testHasNonBinaryCollation(): Unit = { + assumeTrue(HoodieSparkUtils.gteqSpark4_0, "Collations only exist on Spark 4") + assertFalse(sparkAdapter.hasNonBinaryCollation(StringType)) + assertFalse(sparkAdapter.hasNonBinaryCollation(IntegerType)) + Seq("STRING COLLATE UTF8_BINARY", "ARRAY<STRING>", "STRUCT<f: STRING, g: INT>").foreach { ddl => + assertFalse(sparkAdapter.hasNonBinaryCollation(DataType.fromDDL(ddl)), ddl) + } + Seq("STRING COLLATE UTF8_LCASE", "STRING COLLATE UTF8_BINARY_RTRIM", "ARRAY<STRING COLLATE UNICODE>", + "MAP<STRING COLLATE UTF8_LCASE, INT>", "MAP<STRING, STRUCT<f: STRING COLLATE UTF8_LCASE>>").foreach { ddl => + assertTrue(sparkAdapter.hasNonBinaryCollation(DataType.fromDDL(ddl)), ddl) + } + } +} diff --git a/hudi-spark-datasource/hudi-spark4-common/src/main/scala/org/apache/spark/sql/adapter/BaseSpark4Adapter.scala b/hudi-spark-datasource/hudi-spark4-common/src/main/scala/org/apache/spark/sql/adapter/BaseSpark4Adapter.scala index 5f426bd58fff..9549334781de 100644 --- a/hudi-spark-datasource/hudi-spark4-common/src/main/scala/org/apache/spark/sql/adapter/BaseSpark4Adapter.scala +++ b/hudi-spark-datasource/hudi-spark4-common/src/main/scala/org/apache/spark/sql/adapter/BaseSpark4Adapter.scala @@ -53,7 +53,7 @@ import org.apache.spark.sql.execution.datasources.parquet.{HoodieFormatTrait, Pa import org.apache.spark.sql.hudi.SparkAdapter import org.apache.spark.sql.internal.SQLConf import org.apache.spark.sql.sources.{BaseRelation, Filter} -import org.apache.spark.sql.types.{BinaryType, DataType, StringType, StructField, StructType, VariantType} +import org.apache.spark.sql.types.{ArrayType, BinaryType, DataType, MapType, StringType, StructField, StructType, VariantType} import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnVector} import org.apache.spark.storage.StorageLevel import org.apache.spark.types.variant.Variant @@ -443,4 +443,12 @@ abstract class BaseSpark4Adapter extends SparkAdapter with Logging { violation.addSuppressed(multipleMatches) violation } + + override def hasNonBinaryCollation(dataType: DataType): Boolean = dataType match { + case s: StringType => !(s.supportsBinaryEquality && s.supportsBinaryOrdering) + case ArrayType(elementType, _) => hasNonBinaryCollation(elementType) + case MapType(keyType, valueType, _) => hasNonBinaryCollation(keyType) || hasNonBinaryCollation(valueType) + case StructType(fields) => fields.exists(f => hasNonBinaryCollation(f.dataType)) + case _ => false + } }
