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-20759-ee044982aad8598b84e89c8096b0006bb1996a88
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit c7d3d637126808f3732f4c11587961ef40a0dc64
Author: voonhous <[email protected]>
AuthorDate: Mon Nov 23 13:12:10 2026 +0000

    fix(spark): probe bloom expression index with writer's DATE keys (#20759)
    
    * fix(spark): probe bloom expression index with writer's DATE keys
    
    The bloom filter expression index writer adds toString of the external
    value, so a DATE result is stored as '2023-09-22', while the literal
    holds epoch days. #20540 stopped the wrong results by not probing such
    terms; build the writer's strings for DATE instead, so the index
    prunes again. Both the java.sql.Date and the LocalDate form are probed,
    since the writer's java8 API setting is unknown and they differ for
    edge years. TIMESTAMP, floating point and decimal terms still give no
    keys.
    
    Closes #20567
    
    * fix(spark): probe the next day for a DATE some time zone skipped
    
    A legacy writer prints a java.sql.Date in its executor's JVM time zone,
    which is not known when probing, and prints a day that zone skipped as
    the next day: 2011-12-30 is 2011-12-31 to a Pacific/Apia executor, so a
    reader in another zone pruned files holding that day. A DATE that any
    zone skipped now also probes the next day's keys, which keeps existing
    indexes correct and only keeps more files.
    
    The test now builds the index with an Apia default zone and reads it
    from UTC, and checks a year-zero date, whose java.sql.Date and LocalDate
    keys differ, under both writer settings.
---
 .../org/apache/hudi/ExpressionIndexSupport.scala   | 40 +++++++++++++++++--
 .../hudi/feature/index/TestExpressionIndex.scala   | 45 +++++++++++++++++++---
 2 files changed, 76 insertions(+), 9 deletions(-)

diff --git 
a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/ExpressionIndexSupport.scala
 
b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/ExpressionIndexSupport.scala
index f8f538a90e97..1765e06f7ccb 100644
--- 
a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/ExpressionIndexSupport.scala
+++ 
b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/ExpressionIndexSupport.scala
@@ -43,12 +43,15 @@ import org.apache.spark.sql.{DataFrame, Row, SparkSession}
 import org.apache.spark.sql.catalyst.InternalRow
 import org.apache.spark.sql.catalyst.expressions.{And, Expression, Literal}
 import org.apache.spark.sql.catalyst.expressions.Literal.TrueLiteral
+import org.apache.spark.sql.catalyst.util.DateTimeUtils
 import org.apache.spark.sql.functions.col
 import 
org.apache.spark.sql.hudi.DataSkippingUtils.translateIntoExpressionIndexFilterExpr
 import org.apache.spark.sql.hudi.dataskipping.{ExpressionIndexSource, 
IndexedExpression, Leaf, Op}
 import org.apache.spark.sql.types._
 import org.apache.spark.storage.StorageLevel
 
+import java.time.{LocalDate, ZoneId}
+
 import scala.collection.JavaConverters._
 import scala.collection.immutable.TreeSet
 import scala.collection.mutable.ListBuffer
@@ -409,8 +412,8 @@ class ExpressionIndexSupport(spark: SparkSession,
   /**
    * Bloom filter keys: the values of `f(col) = v` and `f(col) IN (...)`, as 
strings like the writer added them. A file
    * passes if it may hold any key, which is conservative across conjuncts. A 
conjunct with a value that is not a
-   * non-null literal gives no keys, and is skipped. So does a term whose 
values the writer and the literal print
-   * differently, for ex a DATE is `2023-01-02` to the writer and `19359` here 
(#20567).
+   * non-null literal gives no keys, and is skipped. So does a term whose keys 
cannot be rebuilt here, see
+   * [[hasWriterKeys]].
    */
   private def bloomFilterKeys(use: IndexUse): List[String] =
     use.conjuncts.flatMap(Leaf.parse).filter(leaf => 
use.indexed.matches(leaf.term) && hasWriterKeys(leaf.term.dataType)).flatMap { 
leaf =>
@@ -418,14 +421,35 @@ class ExpressionIndexSupport(spark: SparkSession,
         case Literal(value, _) => value
         case _ => null
       }
-      if (values.isEmpty || values.contains(null)) Seq.empty else 
values.map(_.toString)
+      if (values.isEmpty || values.contains(null)) Seq.empty else 
values.flatMap(writerKeys(_, leaf.term.dataType))
     }.toList
 
+  /**
+   * Whether the writer's keys, `toString` of the external value, can be 
rebuilt from a literal of this type.
+   *
+   * NOTE: Not TIMESTAMP: the writer prints a `java.sql.Timestamp` in the 
executor's default time zone, or an `Instant`
+   * with `spark.sql.datetime.java8API.enabled`, which cannot be rebuilt here.
+   * NOTE: Not FLOAT/DOUBLE: `-0.0` and `0.0` print apart though they compare 
equal. Not DECIMAL: it prints its scale.
+   */
   private def hasWriterKeys(dataType: DataType): Boolean = dataType match {
-    case _: StringType | ByteType | ShortType | IntegerType | LongType => true
+    case _: StringType | ByteType | ShortType | IntegerType | LongType | 
DateType => true
     case _ => false
   }
 
+  /**
+   * The writer's keys for an internal literal value. A DATE is epoch days 
here, and the writer prints a `java.sql.Date`,
+   * or a `LocalDate` with `spark.sql.datetime.java8API.enabled`; both are 
probed, as they differ for edge years.
+   * A `java.sql.Date` prints in the writer's JVM time zone, which is not 
known here, and a day that zone skipped prints
+   * as the next one (2011-12-30 is `2011-12-31` in Pacific/Apia). So a day 
some zone skipped also probes the next day.
+   */
+  private def writerKeys(value: Any, dataType: DataType): Seq[String] = 
dataType match {
+    case DateType =>
+      val days = value.asInstanceOf[Int]
+      val probedDays = if (isSkippedInSomeZone(days)) Seq(days, days + 1) else 
Seq(days)
+      probedDays.flatMap(day => Seq(DateTimeUtils.toJavaDate(day).toString, 
DateTimeUtils.daysToLocalDate(day).toString)).distinct
+    case _ => Seq(value.toString)
+  }
+
   private def loadExpressionIndexRecords(indexPartition: String,
                                          prunedPartitions: Set[String],
                                          shouldReadInMemory: Boolean): 
HoodieData[HoodieMetadataColumnStats] = {
@@ -567,6 +591,14 @@ object ExpressionIndexSupport {
 
   val INDEX_NAME = "EXPRESSION"
 
+  private lazy val allZones: Seq[ZoneId] = 
ZoneId.getAvailableZoneIds.asScala.toSeq.map(id => ZoneId.of(id))
+
+  /** Whether some time zone skipped this whole day: its earliest local time 
is then on a later day. */
+  private def isSkippedInSomeZone(days: Int): Boolean = {
+    val date = LocalDate.ofEpochDay(days)
+    allZones.exists(zone => date.atStartOfDay(zone).toLocalDate != date)
+  }
+
   /** One expression index, and the query conjuncts that read it. */
   private case class IndexUse(definition: HoodieIndexDefinition, indexed: 
IndexedExpression, conjuncts: Seq[Expression]) {
     /** Type of the stored min / max: the matched term's, since the writer 
applied the same function to the same column. */
diff --git 
a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/feature/index/TestExpressionIndex.scala
 
b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/feature/index/TestExpressionIndex.scala
index 5b5adc90a770..902da89e58c6 100644
--- 
a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/feature/index/TestExpressionIndex.scala
+++ 
b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/feature/index/TestExpressionIndex.scala
@@ -61,6 +61,7 @@ import org.apache.spark.sql.hudi.common.HoodieSparkSqlTestBase
 import org.apache.spark.sql.types._
 import org.junit.jupiter.api.Assertions.{assertEquals, assertFalse, assertTrue}
 
+import java.util.TimeZone
 import java.util.stream.Collectors
 
 import scala.collection.JavaConverters
@@ -1923,26 +1924,60 @@ class TestExpressionIndex extends 
HoodieSparkSqlTestBase with SparkAdapterSuppor
   test("Test Expression Index Leaves A Filter It Cannot Prune To Column 
Stats") {
     withTempDir { tmp =>
       val tableName = generateTableName
-      // One base file per insert, so that column stats prune inside the 
partition
+      // One base file per insert, so that column stats prune inside the 
partition. Instant times in UTC, so that moving
+      // the JVM time zone below does not put an instant hours ahead of the 
next one
       withSQLConf("hoodie.metadata.index.column.stats.enable" -> "true", 
"hoodie.parquet.small.file.limit" -> "0") {
         spark.sql(
           s"""CREATE TABLE $tableName (ts STRING, uuid STRING, rider STRING, 
fare DOUBLE, city STRING) USING HUDI
              |PARTITIONED BY (city)
              |LOCATION '${tmp.getCanonicalPath}/$tableName'
-             |TBLPROPERTIES (primaryKey = 'uuid', preCombineField = 'ts')
+             |TBLPROPERTIES (primaryKey = 'uuid', preCombineField = 'ts', 
'hoodie.table.timeline.timezone' = 'UTC')
              |""".stripMargin)
         spark.sql(s"INSERT INTO $tableName VALUES ('2023-09-23 
09:42:17','u1','rider-F',34.15,'sao_paulo')")
         spark.sql(s"INSERT INTO $tableName VALUES ('2023-09-24 
09:00:00','u2','rider-Z',12.50,'sao_paulo')")
         spark.sql(s"CREATE INDEX ts_year ON $tableName USING column_stats(ts) 
options(expr='date_format', format='yyyy')")
-        spark.sql(s"CREATE INDEX ts_two_days ON $tableName USING 
bloom_filters(ts) options(expr='date_add', days='2')")
 
         withSQLConf(DataSourceReadOptions.ENABLE_DATA_SKIPPING.key -> "true", 
HoodieMetadataConfig.ENABLE.key -> "true",
           "spark.sql.adaptive.enabled" -> "false") {
           // Spark casts the indexed string to INT here, which no rule ranges: 
the index cannot prune this filter
           assertScan(tableName, "date_format(ts, 'yyyy') = 2023 AND fare = 
12.5", Seq("rider-Z"), expectedFiles = 1)
-          // A bloom filter holds a DATE as the writer's string, not as the 
epoch days of the literal: it cannot answer this
-          assertScan(tableName, "date_add(ts, 2) IN (DATE'2023-09-25', 
DATE'2023-09-27')", Seq("rider-F"), expectedFiles = 2)
         }
+
+        // Year 0 prints as 0001 in a java.sql.Date and as 0000 in a 
LocalDate; 2011-12-30 is a day Pacific/Apia skipped
+        spark.sql(s"INSERT INTO $tableName VALUES ('0000-01-01 
10:00:00','u3','rider-Y',7.25,'sao_paulo')")
+        spark.sql(s"INSERT INTO $tableName VALUES ('2011-12-28 
10:00:00','u4','rider-X',8.75,'sao_paulo')")
+
+        // A bloom filter holds a DATE as the writer's string, a java.sql.Date 
or, with the java8 API, a LocalDate,
+        // not as the epoch days of the literal (#20567)
+        Seq("false", "true").foreach { java8Api =>
+          withSQLConf("spark.sql.datetime.java8API.enabled" -> java8Api) {
+            spark.sql(s"CREATE INDEX ts_two_days ON $tableName USING 
bloom_filters(ts) options(expr='date_add', days='2')")
+          }
+          withSQLConf(DataSourceReadOptions.ENABLE_DATA_SKIPPING.key -> 
"true", HoodieMetadataConfig.ENABLE.key -> "true",
+            "spark.sql.adaptive.enabled" -> "false") {
+            assertScan(tableName, "date_add(ts, 2) = DATE'2023-09-25'", 
Seq("rider-F"), expectedFiles = 1)
+            assertScan(tableName, "date_add(ts, 2) IN (DATE'2023-09-25', 
DATE'2023-09-27')", Seq("rider-F"), expectedFiles = 1)
+            assertScan(tableName, "date_add(ts, 2) = DATE'0000-01-03'", 
Seq("rider-Y"), expectedFiles = 1)
+          }
+          spark.sql(s"DROP INDEX ts_two_days ON $tableName")
+        }
+
+        // A java.sql.Date prints in the writer's JVM time zone: an executor 
in Pacific/Apia, which skipped 2011-12-30,
+        // stores that day as 2011-12-31, which a reader in another zone must 
still probe
+        withSQLConf("spark.sql.datetime.java8API.enabled" -> "false") {
+          val defaultZone = TimeZone.getDefault
+          TimeZone.setDefault(TimeZone.getTimeZone("Pacific/Apia"))
+          try {
+            spark.sql(s"CREATE INDEX ts_two_days ON $tableName USING 
bloom_filters(ts) options(expr='date_add', days='2')")
+          } finally {
+            TimeZone.setDefault(defaultZone)
+          }
+        }
+        withSQLConf(DataSourceReadOptions.ENABLE_DATA_SKIPPING.key -> "true", 
HoodieMetadataConfig.ENABLE.key -> "true",
+          "spark.sql.adaptive.enabled" -> "false") {
+          assertScan(tableName, "date_add(ts, 2) = DATE'2011-12-30'", 
Seq("rider-X"), expectedFiles = 1)
+        }
+        spark.sql(s"DROP INDEX ts_two_days ON $tableName")
       }
     }
   }

Reply via email to