This is an automated email from the ASF dual-hosted git repository.

JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git


The following commit(s) were added to refs/heads/master by this push:
     new cb2024b34b [spark] Add conservative statistics pruning for Catalyst 
partition predicates (#11158)
cb2024b34b is described below

commit cb2024b34b4eb03e73ee723e4a3b3562783426bd
Author: Zouxxyy <[email protected]>
AuthorDate: Sun Nov 15 16:21:51 2026 +0800

    [spark] Add conservative statistics pruning for Catalyst partition 
predicates (#11158)
---
 .../filter/SparkCatalystPartitionPredicate.scala   |  35 +-
 .../filter/SparkCatalystPartitionStats.scala       | 292 ++++++++++++
 .../predicate/SparkCatalystPartitionScanTest.scala | 201 ++++++++
 .../SparkCatalystPartitionStatsTest.scala          | 522 +++++++++++++++++++++
 4 files changed, 1047 insertions(+), 3 deletions(-)

diff --git 
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/filter/SparkCatalystPartitionPredicate.scala
 
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/filter/SparkCatalystPartitionPredicate.scala
index f030a67d24..4d34104c94 100644
--- 
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/filter/SparkCatalystPartitionPredicate.scala
+++ 
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/filter/SparkCatalystPartitionPredicate.scala
@@ -27,8 +27,11 @@ import org.apache.paimon.types.RowType
 import org.apache.spark.sql.catalyst.expressions.{And, Attribute, 
BasePredicate, BoundReference, Expression, Predicate, PythonUDF, 
SubqueryExpression}
 import org.apache.spark.sql.catalyst.util.CharVarcharUtils
 import org.apache.spark.sql.execution.datasources.DataSourceUtils
+import org.apache.spark.sql.internal.SQLConf
 import org.apache.spark.sql.types.StructType
 
+import scala.util.control.NonFatal
+
 /**
  * A [[PartitionPredicate]] that applies Spark Catalyst partition filters to a 
partition
  * [[BinaryRow]].
@@ -40,20 +43,46 @@ case class SparkCatalystPartitionPredicate(
 
   private val partitionSchema: StructType = 
CharVarcharUtils.replaceCharVarcharWithStringInSchema(
     SparkTypeUtils.fromPaimonRowType(partitionRowType))
+  // Expression copies and lazy evaluators can consult SQLConf again (e.g. 
empty IN semantics).
+  // Preserve the query context across asynchronous scans and serialization, 
for both test paths.
+  private val evaluationSettings: Map[String, String] = SQLConf.get.getAllConfs
+  // SQLConf supports concurrent reads. Populate it once per predicate, then 
keep it read-only;
+  // only the mutable expression evaluators need thread-local instances.
+  @transient private lazy val evaluationConf: SQLConf = {
+    val conf = new SQLConf
+    evaluationSettings.foreach { case (key, value) => conf.setConfString(key, 
value) }
+    conf
+  }
   @transient private lazy val predicateThreadLocal: ThreadLocal[BasePredicate] 
=
     ThreadLocal.withInitial(
       () => new StructExpressionFilters(partitionFilter, 
partitionSchema).toPredicate)
 
+  @transient private lazy val statisticsThreadLocal: 
ThreadLocal[SparkCatalystPartitionStats] =
+    ThreadLocal.withInitial(
+      () => new SparkCatalystPartitionStats(partitionFilter, partitionRowType, 
partitionSchema))
+
   override def test(partition: BinaryRow): Boolean = {
-    val predicate = predicateThreadLocal.get()
-    
predicate.eval(SparkInternalRow.create(partitionRowType).replace(partition))
+    SQLConf.withExistingConf(evaluationConf) {
+      val predicate = predicateThreadLocal.get()
+      
predicate.eval(SparkInternalRow.create(partitionRowType).replace(partition))
+    }
   }
 
   override def test(
       rowCount: Long,
       minValues: PaimonInternalRow,
       maxValues: PaimonInternalRow,
-      nullCounts: InternalArray): Boolean = true
+      nullCounts: InternalArray): Boolean = {
+    try {
+      SQLConf.withExistingConf(evaluationConf) {
+        statisticsThreadLocal.get().test(rowCount, minValues, maxValues, 
nullCounts)
+      }
+    } catch {
+      // An evaluation failure is unknown, never proof that no partition 
matches. Keep it for
+      // ordinary scanning; independent pushed predicates may still prune the 
same manifest.
+      case NonFatal(_) => true
+    }
+  }
 
   override def toString: String = partitionFilter.toString()
 
diff --git 
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/filter/SparkCatalystPartitionStats.scala
 
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/filter/SparkCatalystPartitionStats.scala
new file mode 100644
index 0000000000..b9a5658679
--- /dev/null
+++ 
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/filter/SparkCatalystPartitionStats.scala
@@ -0,0 +1,292 @@
+/*
+ * 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.catalyst.filter
+
+import org.apache.paimon.data.{InternalArray, InternalRow => PaimonInternalRow}
+import org.apache.paimon.predicate.{Predicate => PaimonPredicate}
+import org.apache.paimon.spark.SparkV2FilterConverter
+import org.apache.paimon.spark.data.SparkInternalRow
+import org.apache.paimon.types.RowType
+
+import org.apache.spark.sql.PaimonUtils
+import org.apache.spark.sql.catalyst.expressions.{And, Attribute, 
BasePredicate, BinaryComparison, BoundReference, Contains, EndsWith, 
Expression, GenericInternalRow, In, InSet, IsNotNull, IsNull, Literal, Not, Or, 
Predicate, StartsWith}
+import org.apache.spark.sql.catalyst.util.TypeUtils
+import org.apache.spark.sql.types.{BooleanType, ByteType, DataType, DateType, 
DecimalType, IntegerType, LongType, ShortType, StringType, StructType}
+import org.apache.spark.unsafe.types.UTF8String
+
+import scala.util.control.NonFatal
+
+/**
+ * Conservative statistics evaluator for a Catalyst partition predicate. 
Instances are thread-local.
+ *
+ * Direct field predicates reuse Paimon's statistics functions. Other 
expressions are evaluated with
+ * Spark semantics only if statistics prove a finite input domain: a constant 
non-null value, NULL,
+ * or both. We enumerate the Cartesian product, not just the min/max rows, 
since statistics contain
+ * no cross-column correlation. A bounded superset of the real partitions is 
sufficient: we may
+ * prune only when none of its rows satisfies the original expression.
+ *
+ * No CAST is applied to interval endpoints. In particular, even digit-only 
STRING endpoints do not
+ * prove a numeric interval or a fixed string length for the values between 
them. Merging manifests
+ * across different values of a CAST-referenced field therefore limits this 
optimization. Merging a
+ * single value across other partition columns does not. Native direct-field 
predicates can still
+ * prune non-singleton intervals.
+ */
+final private[filter] class SparkCatalystPartitionStats(
+    filter: Expression,
+    partitionType: RowType,
+    schema: StructType) {
+
+  // A work bound, not a correctness assumption. Larger domains are left to 
ordinary scanning.
+  private val maxCombinations = 64
+  private val root = new StatisticsPredicate(filter)
+
+  def test(
+      rowCount: Long,
+      min: PaimonInternalRow,
+      max: PaimonInternalRow,
+      nullCounts: InternalArray): Boolean = {
+    if (
+      rowCount <= 0 || min == null || max == null || nullCounts == null ||
+      min.getFieldCount < partitionType.getFieldCount ||
+      max.getFieldCount < partitionType.getFieldCount ||
+      nullCounts.size() < partitionType.getFieldCount
+    ) {
+      true
+    } else {
+      root.mayMatch(new Statistics(rowCount, min, max, 
nullCounts)).getOrElse(true)
+    }
+  }
+
+  private case class Field(index: Int, dataType: DataType)
+
+  private class Statistics(
+      val rowCount: Long,
+      val min: PaimonInternalRow,
+      val max: PaimonInternalRow,
+      val nullCounts: InternalArray) {
+
+    private val sparkMin = SparkInternalRow.create(partitionType).replace(min)
+    private val sparkMax = SparkInternalRow.create(partitionType).replace(max)
+
+    def nullCount(field: Field): Option[Long] =
+      if (nullCounts.isNullAt(field.index)) None else 
Some(nullCounts.getLong(field.index))
+
+    def minimum(field: Field): Any = sparkMin.get(field.index, field.dataType)
+    def maximum(field: Field): Any = sparkMax.get(field.index, field.dataType)
+
+    def valid(field: Field): Boolean = {
+      if (!supportedType(field.dataType)) {
+        return false
+      }
+      val count = nullCount(field)
+      val lower = minimum(field)
+      val upper = maximum(field)
+      if (count.exists(n => n < 0 || n > rowCount) || (lower == null) != 
(upper == null)) {
+        false
+      } else if (count.contains(rowCount)) {
+        lower == null && upper == null
+      } else if (lower == null) {
+        // Unknown bounds: let Paimon's native leaf predicates handle them 
conservatively.
+        true
+      } else {
+        TypeUtils.getInterpretedOrdering(field.dataType).lteq(lower, upper)
+      }
+    }
+
+    def domain(field: Field): Option[Seq[Any]] = {
+      nullCount(field).flatMap {
+        count =>
+          if (count == rowCount) {
+            Some(Seq(null))
+          } else {
+            val lower = minimum(field)
+            val upper = maximum(field)
+            if (
+              lower != null && upper != null &&
+              TypeUtils.getInterpretedOrdering(field.dataType).equiv(lower, 
upper)
+            ) {
+              Some(if (count == 0) Seq(lower) else Seq(lower, null))
+            } else {
+              None
+            }
+          }
+      }
+    }
+  }
+
+  private class StatisticsPredicate(expression: Expression) {
+    private val attributes = expression.references.toSeq
+    private val fields = attributes.flatMap {
+      attribute =>
+        schema
+          .getFieldIndex(attribute.name)
+          .filter(index => schema(index).dataType == attribute.dataType)
+          .map(index => Field(index, attribute.dataType))
+    }
+    private val eligible =
+      expression.resolved && expression.deterministic && fields.size == 
attributes.size &&
+        expression.dataType == BooleanType
+
+    // Do not introduce planning-time execution of UDFs or other non-foldable 
expressions.
+    private val finiteEvaluationAllowed = eligible && expression.transform {
+      case a: Attribute => Literal.default(a.dataType)
+    }.foldable
+
+    private lazy val exactPredicate: BasePredicate = 
Predicate.create(expression.transform {
+      case a: Attribute =>
+        val index = schema.fieldIndex(a.name)
+        BoundReference(index, schema(index).dataType, schema(index).nullable)
+    })
+
+    private val nativePredicate: Option[PaimonPredicate] = {
+      if (eligible && nativeLeaf(expression) && 
nativeLiteralsSafe(expression)) {
+        try {
+          PaimonUtils
+            .translateFilterV2(expression)
+            .flatMap(SparkV2FilterConverter(partitionType).convert(_))
+        } catch {
+          case NonFatal(_) => None
+        }
+      } else {
+        None
+      }
+    }
+
+    private val children: Option[(Boolean, StatisticsPredicate, 
StatisticsPredicate)] =
+      expression match {
+        case And(left, right) =>
+          Some((true, new StatisticsPredicate(left), new 
StatisticsPredicate(right)))
+        case Or(left, right) =>
+          Some((false, new StatisticsPredicate(left), new 
StatisticsPredicate(right)))
+        // SQL three-valued De Morgan laws are safe. Never negate a may-match 
result itself.
+        case Not(And(left, right)) =>
+          Some((false, new StatisticsPredicate(Not(left)), new 
StatisticsPredicate(Not(right))))
+        case Not(Or(left, right)) =>
+          Some((true, new StatisticsPredicate(Not(left)), new 
StatisticsPredicate(Not(right))))
+        case _ => None
+      }
+    private val doubleNegation = expression match {
+      case Not(Not(child)) => Some(new StatisticsPredicate(child))
+      case _ => None
+    }
+
+    // None also covers expressions whose evaluation/error behavior cannot be 
proven from stats.
+    // In an AND, do not discard this uncertainty just because another child 
cannot match.
+    // This is local conservatism, not an error guarantee across independently 
pushed predicates.
+    def mayMatch(statistics: Statistics): Option[Boolean] = {
+      if (!eligible || !fields.forall(statistics.valid)) {
+        return None
+      }
+      finiteMatch(statistics)
+        .orElse {
+          nativePredicate.map {
+            predicate =>
+              predicate.test(
+                statistics.rowCount,
+                statistics.min,
+                statistics.max,
+                statistics.nullCounts)
+          }
+        }
+        .orElse {
+          children.flatMap {
+            case (isAnd, left, right) =>
+              val l = left.mayMatch(statistics)
+              val r = right.mayMatch(statistics)
+              for (a <- l; b <- r) yield if (isAnd) a && b else a || b
+          }
+        }
+        .orElse(doubleNegation.flatMap(_.mayMatch(statistics)))
+    }
+
+    private def finiteMatch(statistics: Statistics): Option[Boolean] = {
+      if (!finiteEvaluationAllowed) {
+        return None
+      }
+      val domains = fields.map(statistics.domain)
+      if (domains.exists(_.isEmpty)) {
+        return None
+      }
+      val values = domains.map(_.get)
+      // Avoid product overflow and exponential planning work before 
enumerating any rows.
+      var combinations = 1
+      values.foreach {
+        domain =>
+          if (combinations > maxCombinations / domain.size) {
+            return None
+          }
+          combinations *= domain.size
+      }
+      val row = new GenericInternalRow(schema.length)
+      def matches(index: Int): Boolean = {
+        if (index == fields.size) {
+          exactPredicate.eval(row)
+        } else {
+          values(index).exists {
+            value =>
+              row.update(fields(index).index, value)
+              matches(index + 1)
+          }
+        }
+      }
+      Some(matches(0))
+    }
+  }
+
+  private def supportedType(dataType: DataType): Boolean = dataType match {
+    case BooleanType | ByteType | ShortType | IntegerType | LongType | 
StringType | DateType =>
+      true
+    case _: DecimalType => true
+    // FLOAT/DOUBLE: NaN ordering and signed zero need a separate proof; 
BINARY ordering differs
+    // between Spark and Paimon. TIMESTAMP may lose sub-microsecond precision 
or involve a
+    // time-zone conversion. Do not delegate those comparisons or infer 
singleton domains.
+    case _ => false
+  }
+
+  private def nativeLeaf(expression: Expression): Boolean = expression match {
+    case comparison: BinaryComparison =>
+      (comparison.left, comparison.right) match {
+        case (_: Attribute, _: Literal) | (_: Literal, _: Attribute) => true
+        case _ => false
+      }
+    case In(_: Attribute, list) => list.forall(_.isInstanceOf[Literal])
+    case InSet(_: Attribute, _) => true
+    case IsNull(_: Attribute) | IsNotNull(_: Attribute) => true
+    case StartsWith(_: Attribute, _: Literal) | EndsWith(_: Attribute, _: 
Literal) |
+        Contains(_: Attribute, _: Literal) =>
+      true
+    case Not(child) => nativeLeaf(child)
+    // In particular, never convert a Spark CAST to Paimon's CastExecutors for 
this optimization.
+    case _ => false
+  }
+
+  private def nativeLiteralsSafe(expression: Expression): Boolean = {
+    // SparkExpressionConverter converts UTF8String literals through a Java 
String. Malformed
+    // UTF-8 would be replaced during that round trip and could move a literal 
outside the range.
+    def lossless(value: Any): Boolean = value match {
+      case string: UTF8String => UTF8String.fromString(string.toString) == 
string
+      case _ => true
+    }
+    !expression.exists {
+      case literal: Literal => !lossless(literal.value)
+      case InSet(_, set) => !set.forall(lossless)
+      case _ => false
+    }
+  }
+}
diff --git 
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/predicate/SparkCatalystPartitionScanTest.scala
 
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/predicate/SparkCatalystPartitionScanTest.scala
new file mode 100644
index 0000000000..044c279cf4
--- /dev/null
+++ 
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/predicate/SparkCatalystPartitionScanTest.scala
@@ -0,0 +1,201 @@
+/*
+ * 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.paimon.spark.predicate
+
+import org.apache.paimon.data.{BinaryRow, InternalArray, InternalRow}
+import org.apache.paimon.metrics.{Gauge, MetricGroup, MetricGroupImpl, 
MetricRegistry}
+import org.apache.paimon.operation.metrics.ScanMetrics
+import org.apache.paimon.partition.PartitionPredicate
+import org.apache.paimon.spark.PaimonSparkTestBase
+import org.apache.paimon.spark.catalyst.Compatibility
+
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.expressions.{And, AttributeReference, 
EqualTo, Expression, GreaterThanOrEqual, In, LessThan, LessThanOrEqual, 
Literal, Not}
+import org.apache.spark.sql.catalyst.filter.SparkCatalystPartitionPredicate
+import org.apache.spark.sql.types.{IntegerType, StringType}
+
+import java.util.{Collections, Map => JMap}
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable.ArrayBuffer
+
+/**
+ * Exercise the Catalyst predicate through the public Paimon scan API. This 
does not install a
+ * Catalyst-filter pushdown rule in Spark's SQL scan builder.
+ */
+class SparkCatalystPartitionScanTest extends PaimonSparkTestBase {
+
+  private val dt = AttributeReference("dt", StringType)()
+  private def cast(ansi: Boolean = false): Expression =
+    Compatibility.cast(dt, IntegerType, ansiEnabled = ansi)
+
+  private case class ScanResult(ids: Seq[Int], manifests: Long)
+
+  private def scan(
+      tableName: String,
+      expression: Expression,
+      useStatistics: Boolean = true): ScanResult = {
+    val table = loadTable(tableName)
+    val predicate =
+      SparkCatalystPartitionPredicate(expression, 
table.rowType().project(table.partitionKeys()))
+    // Baseline: the same exact partition evaluation with the former 
always-true statistics path.
+    val filter =
+      if (useStatistics) predicate
+      else
+        new PartitionPredicate {
+          override def test(partition: BinaryRow): Boolean = 
predicate.test(partition)
+          override def test(
+              rowCount: Long,
+              min: InternalRow,
+              max: InternalRow,
+              nullCounts: InternalArray): Boolean = true
+        }
+    val group = new MetricGroupImpl(ScanMetrics.GROUP_NAME, 
Collections.emptyMap[String, String]())
+    val registry = new MetricRegistry {
+      override def createMetricGroup(name: String, variables: JMap[String, 
String]): MetricGroup =
+        group
+    }
+    val builder = table.newReadBuilder().withPartitionFilter(filter)
+    val plan = builder.newScan().withMetricRegistry(registry).plan()
+    val read = builder.newRead()
+    val ids = ArrayBuffer.empty[Int]
+    plan.splits().asScala.foreach {
+      split =>
+        val reader = read.createReader(split)
+        try {
+          reader.forEachRemaining((row: InternalRow) => { ids += 
row.getInt(0); () })
+        } finally {
+          reader.close()
+        }
+    }
+    val manifests = group.getMetrics
+      .get(ScanMetrics.LAST_SCANNED_MANIFESTS)
+      .asInstanceOf[Gauge[Long]]
+      .getValue
+    ScanResult(ids.sorted.toSeq, manifests)
+  }
+
+  for (format <- Seq("parquet", "orc"); ansi <- Seq(false, true)) {
+    test(s"CAST comparison and compound statistics prune real manifests: 
$format, ANSI=$ansi") {
+      withSparkSQLConf("spark.sql.ansi.enabled" -> ansi.toString) {
+        withTable("stats_dates") {
+          sql(s"""CREATE TABLE stats_dates (id INT, dt STRING) USING paimon 
PARTITIONED BY (dt)
+                 |TBLPROPERTIES ('bucket'='-1', 'write-only'='true',
+                 |'manifest.merge-min-count'='100', 
'file.format'='$format')""".stripMargin)
+          Seq("20261112", "20261113", "20261114", 
"020261113").zipWithIndex.foreach {
+            case (value, id) => sql(s"INSERT INTO stats_dates VALUES 
($id,'$value')")
+          }
+          val converted = cast(ansi)
+          Seq(
+            (EqualTo(converted, Literal(20261113)), Seq(1, 3)),
+            (GreaterThanOrEqual(converted, Literal(20261114)), Seq(2)),
+            (LessThan(converted, Literal(20261113)), Seq(0)),
+            (In(converted, Seq(Literal(20261112), Literal(20261114))), Seq(0, 
2)),
+            (Not(EqualTo(converted, Literal(20261113))), Seq(0, 2)),
+            (
+              And(
+                GreaterThanOrEqual(converted, Literal(20261113)),
+                LessThanOrEqual(converted, Literal(20261113))),
+              Seq(1, 3))
+          ).foreach {
+            case (expression, expected) =>
+              val optimized = scan("stats_dates", expression)
+              val baseline = scan("stats_dates", expression, useStatistics = 
false)
+              assert(optimized.ids == expected)
+              assert(optimized.ids == baseline.ids)
+              assert(optimized.manifests == expected.size)
+              assert(baseline.manifests == 4L)
+          }
+          checkAnswer(
+            sql("SELECT id FROM stats_dates WHERE CAST(dt AS INT) = 20261113"),
+            Seq(Row(1), Row(3)))
+        }
+      }
+    }
+  }
+
+  for (format <- Seq("parquet", "orc"); singleDate <- Seq(false, true)) {
+    test(s"statistics pruning after actual manifest merging: $format, 
singleDate=$singleDate") {
+      withTable("merged_dates") {
+        sql(s"""CREATE TABLE merged_dates (id INT, dt STRING, region STRING)
+               |USING paimon PARTITIONED BY (region, dt)
+               |TBLPROPERTIES ('bucket'='-1', 'write-only'='true',
+               |'manifest.merge-min-count'='2', 
'file.format'='$format')""".stripMargin)
+        sql("INSERT INTO merged_dates VALUES (1,'10','a')")
+        val secondDate = if (singleDate) "10" else "100"
+        sql(s"INSERT INTO merged_dates VALUES (2,'$secondDate','z')")
+        def manifestNames: Set[String] =
+          sql("SELECT file_name FROM 
`merged_dates$manifests`").collect().map(_.getString(0)).toSet
+        val before = manifestNames
+        assert(before.size == 2)
+        sql("INSERT INTO merged_dates VALUES (3,'2','b')")
+        val after = manifestNames
+        assert(after.size == 2)
+        assert(before.intersect(after).isEmpty)
+
+        val missing = EqualTo(cast(), Literal(50))
+        val matching = EqualTo(cast(), Literal(10))
+        val expected = if (singleDate) Seq(1, 2) else Seq(1)
+        val optimized = scan("merged_dates", missing)
+        val baseline = scan("merged_dates", missing, useStatistics = false)
+        assert(optimized.ids.isEmpty)
+        assert(optimized.ids == baseline.ids)
+        assert(optimized.manifests == (if (singleDate) 0L else 1L))
+        assert(baseline.manifests == 2L)
+        assert(scan("merged_dates", matching).ids == expected)
+        assert(scan("merged_dates", matching, useStatistics = false).ids == 
expected)
+        // Direct field predicates retain interval pruning, unlike CAST over 
string intervals.
+        assert(scan("merged_dates", EqualTo(dt, Literal("50"))).manifests == 
0L)
+      }
+    }
+  }
+
+  test("statistics pruning preserves primary-key merge reads") {
+    withTable("pk_dates") {
+      sql("""CREATE TABLE pk_dates (id INT, value STRING, dt STRING) USING 
paimon
+            |PARTITIONED BY (dt) TBLPROPERTIES ('bucket'='1', 
'primary-key'='id,dt',
+            |'write-only'='true', 
'manifest.merge-min-count'='100')""".stripMargin)
+      sql("INSERT INTO pk_dates VALUES (1,'unrelated','20261112')")
+      sql("INSERT INTO pk_dates VALUES (2,'old','20261113')")
+      sql("INSERT INTO pk_dates VALUES (2,'new','20261113')")
+      val expression = EqualTo(cast(), Literal(20261113))
+      val optimized = scan("pk_dates", expression)
+      assert(optimized.ids == Seq(2))
+      assert(optimized.ids == scan("pk_dates", expression, useStatistics = 
false).ids)
+      assert(optimized.manifests == 2L)
+      checkAnswer(sql("SELECT id, value FROM pk_dates WHERE dt = '20261113'"), 
Seq(Row(2, "new")))
+    }
+  }
+
+  test("statistics pruning preserves overwrite ADD and DELETE entries") {
+    withTable("overwrite_dates") {
+      sql("""CREATE TABLE overwrite_dates (id INT, dt STRING) USING paimon 
PARTITIONED BY (dt)
+            |TBLPROPERTIES ('bucket'='-1', 
'manifest.merge-min-count'='100')""".stripMargin)
+      sql("INSERT INTO overwrite_dates VALUES (1,'20261112'), (2,'20261113')")
+      sql("INSERT OVERWRITE overwrite_dates PARTITION (dt='20261113') SELECT 
3")
+      Seq(20261112 -> Seq(1), 20261113 -> Seq(3)).foreach {
+        case (date, expected) =>
+          val expression = EqualTo(cast(), Literal(date))
+          val optimized = scan("overwrite_dates", expression)
+          assert(optimized.ids == expected)
+          assert(optimized.ids == scan("overwrite_dates", expression, 
useStatistics = false).ids)
+      }
+    }
+  }
+}
diff --git 
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/predicate/SparkCatalystPartitionStatsTest.scala
 
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/predicate/SparkCatalystPartitionStatsTest.scala
new file mode 100644
index 0000000000..69633536f7
--- /dev/null
+++ 
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/predicate/SparkCatalystPartitionStatsTest.scala
@@ -0,0 +1,522 @@
+/*
+ * 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.paimon.spark.predicate
+
+import org.apache.paimon.data.{BinaryRow, BinaryString, Decimal => 
PaimonDecimal, GenericArray, GenericRow, InternalArray, InternalRow, Timestamp 
=> PaimonTimestamp}
+import org.apache.paimon.data.serializer.InternalRowSerializer
+import org.apache.paimon.format.SimpleStatsCollector
+import org.apache.paimon.spark.PaimonSparkTestBase
+import org.apache.paimon.spark.catalyst.Compatibility
+import org.apache.paimon.stats.SimpleStatsConverter
+import org.apache.paimon.types.{DataType => PaimonType, DataTypes, RowType}
+import org.apache.paimon.utils.InstantiationUtil
+
+import org.apache.spark.sql.catalyst.expressions.{And, AttributeReference, 
Coalesce, Contains, EqualNullSafe, EqualTo, Expression, GreaterThan, 
GreaterThanOrEqual, In, IsNotNull, IsNull, LessThan, LessThanOrEqual, Literal, 
Not, Or, ScalaUDF, StartsWith, Upper}
+import org.apache.spark.sql.catalyst.filter.SparkCatalystPartitionPredicate
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{BinaryType, BooleanType, ByteType, 
DataType, DateType, Decimal, DecimalType, DoubleType, IntegerType, LongType, 
ShortType, StringType, TimestampType}
+
+import java.util.concurrent.{Callable, ConcurrentHashMap, CyclicBarrier, 
Executors, TimeUnit}
+
+import scala.util.control.NonFatal
+
+/** No false-negative pruning: actual matches or evaluation errors must 
survive statistics. */
+class SparkCatalystPartitionStatsTest extends PaimonSparkTestBase {
+
+  private val partitionType = RowType.of(
+    Array[PaimonType](DataTypes.STRING(), DataTypes.STRING(), DataTypes.INT()),
+    Array("dt", "region", "n"))
+  private val dt = AttributeReference("dt", StringType)()
+  private val region = AttributeReference("region", StringType)()
+  private val n = AttributeReference("n", IntegerType)()
+
+  private def cast(ansi: Boolean = false): Expression =
+    Compatibility.cast(dt, IntegerType, ansiEnabled = ansi)
+
+  private def row(value: String, area: String = "a", number: Int = 0): 
GenericRow = {
+    GenericRow.of(
+      if (value == null) null else BinaryString.fromString(value),
+      if (area == null) null else BinaryString.fromString(area),
+      Int.box(number))
+  }
+
+  private case class Sample(
+      count: Long,
+      min: InternalRow,
+      max: InternalRow,
+      nulls: InternalArray,
+      partitions: Seq[BinaryRow]) {
+    def mayMatch(predicate: SparkCatalystPartitionPredicate): Boolean =
+      predicate.test(count, min, max, nulls)
+  }
+
+  private def sample(rows: Seq[GenericRow], rowType: RowType = partitionType): 
Sample = {
+    val collector = new SimpleStatsCollector(rowType)
+    rows.foreach(collector.collect)
+    val stats = new 
SimpleStatsConverter(rowType).toBinaryAllMode(collector.extract())
+    val serializer = new InternalRowSerializer(rowType)
+    Sample(
+      rows.size,
+      stats.minValues(),
+      stats.maxValues(),
+      stats.nullCounts(),
+      rows.map(r => serializer.toBinaryRow(r).copy()))
+  }
+
+  private def mayMatch(expression: Expression, rows: GenericRow*): Boolean =
+    sample(rows).mayMatch(SparkCatalystPartitionPredicate(expression, 
partitionType))
+
+  test("native leaf statistics handle non-singleton intervals") {
+    val data = Seq(row("10", number = 10), row("20", number = 20))
+    Seq[Expression](
+      EqualTo(n, Literal(30)),
+      GreaterThan(n, Literal(20)),
+      GreaterThanOrEqual(n, Literal(21)),
+      LessThan(n, Literal(10)),
+      LessThanOrEqual(n, Literal(9)),
+      GreaterThan(Literal(10), n),
+      In(n, Seq(Literal(1), Literal(30))),
+      IsNull(n),
+      Not(GreaterThanOrEqual(n, Literal(10))),
+      Not(In(n, Seq(Literal(10), Literal(20), Literal.create(null, 
IntegerType))))
+    )
+      .foreach(e => assert(!mayMatch(e, data: _*), e.toString))
+    assert(mayMatch(EqualTo(n, Literal(15)), data: _*)) // range overlap is 
only a possibility
+    assert(mayMatch(EqualTo(dt, Literal("15")), data: _*))
+    assert(!mayMatch(EqualTo(dt, Literal("30")), data: _*))
+    assert(!mayMatch(StartsWith(dt, Literal("z")), data: _*))
+    // No substring inference from just the endpoints.
+    assert(mayMatch(Contains(dt, Literal("x")), data: _*))
+  }
+
+  test("all comparison operators, IN and NOT retain original CAST semantics on 
finite domains") {
+    Seq[Expression](
+      EqualTo(cast(), Literal(9)),
+      GreaterThan(cast(), Literal(10)),
+      GreaterThanOrEqual(cast(), Literal(11)),
+      LessThan(cast(), Literal(10)),
+      LessThanOrEqual(cast(), Literal(9)),
+      Not(EqualTo(cast(), Literal(10))),
+      In(cast(), Seq(Literal(8), Literal(9))),
+      Not(In(cast(), Seq(Literal(10), Literal.create(null, IntegerType))))
+    )
+      .foreach(e => assert(!mayMatch(e, row("10"), row(null)), e.toString))
+    Seq("010", "+10", " 10 ").foreach {
+      value => assert(mayMatch(EqualTo(cast(), Literal(10)), row(value)))
+    }
+  }
+
+  test("foldable Spark functions are not limited to casts or single referenced 
columns") {
+    assert(!mayMatch(EqualTo(Upper(dt), Literal("B")), row("a")))
+    assert(mayMatch(EqualTo(Upper(dt), Literal("A")), row("a")))
+    val coalesced = Coalesce(Seq(dt, region, Literal("fallback")))
+    assert(!mayMatch(EqualTo(coalesced, Literal("z")), row("a", null), 
row(null, "b")))
+    assert(mayMatch(EqualTo(coalesced, Literal("fallback")), row(null, null)))
+    assert(!mayMatch(EqualTo(cast(), Literal(11)), row("10", "a"), row("10", 
"z")))
+  }
+
+  test("NULL combinations are enumerated, not replaced by a single min/max 
row") {
+    val data = Seq(row("a", null), row(null, "b"))
+    assert(mayMatch(And(IsNotNull(dt), IsNull(region)), data: _*))
+    assert(mayMatch(And(IsNull(dt), IsNotNull(region)), data: _*))
+    // The Cartesian superset also contains (a,b) and (NULL,NULL). No 
correlation is assumed.
+    assert(mayMatch(And(IsNotNull(dt), IsNotNull(region)), data: _*))
+    assert(mayMatch(EqualNullSafe(dt, region), data: _*))
+    assert(!mayMatch(EqualTo(dt, region), data: _*))
+    assert(!mayMatch(Not(EqualTo(dt, Literal("a"))), data: _*))
+    assert(mayMatch(Not(EqualNullSafe(dt, Literal("a"))), data: _*))
+    assert(mayMatch(IsNull(cast()), row("invalid"), row(null)))
+    assert(!mayMatch(IsNotNull(cast()), row("invalid"), row(null)))
+  }
+
+  test("AND OR NOT use conservative logic, never boolean negation of 
may-match") {
+    val data = Seq(row("10", number = 1), row("10", number = 3))
+    val impossible = GreaterThan(cast(), Literal(50))
+    val possible = EqualTo(n, Literal(2))
+    assert(!mayMatch(And(impossible, possible), data: _*))
+    assert(mayMatch(Or(impossible, possible), data: _*))
+    assert(mayMatch(Not(possible), data: _*))
+    assert(mayMatch(Not(Not(possible)), data: _*))
+    assert(!mayMatch(Not(Or(EqualTo(cast(), Literal(10)), possible)), data: 
_*))
+    assert(mayMatch(Not(And(impossible, possible)), data: _*))
+  }
+
+  test("string intervals never become numeric intervals, even with digit-only 
endpoints") {
+    val data = Seq(row("10"), row("100"), row("20"))
+    assert(mayMatch(EqualTo(cast(), Literal(100)), data: _*))
+    assert(mayMatch(GreaterThanOrEqual(cast(), Literal(50)), data: _*))
+    // All endpoint strings have 8 digits; the interior value does not.
+    val dates = Seq(row("20261112"), row("202611120"), row("20261114"))
+    assert(mayMatch(GreaterThan(cast(), Literal(30000000)), dates: _*))
+  }
+
+  test("ANSI failures are not hidden by statistics or an unrelated impossible 
conjunct") {
+    val bad = EqualTo(cast(ansi = true), Literal(10))
+    Seq("invalid", "2147483648").foreach {
+      value =>
+        assert(mayMatch(bad, row(value)))
+        assert(mayMatch(And(bad, EqualTo(n, Literal(100))), row(value, number 
= 1)))
+        assert(!mayMatch(EqualTo(cast(), Literal(10)), row(value)))
+    }
+    // Unknown interval values might throw too; an unrelated child is not 
permission to hide it.
+    assert(
+      mayMatch(And(bad, EqualTo(n, Literal(100))), row("10", number = 1), 
row("20", number = 2)))
+  }
+
+  test("missing inconsistent and unsupported statistics conservatively retain 
manifests") {
+    val predicate =
+      SparkCatalystPartitionPredicate(GreaterThanOrEqual(cast(), Literal(10)), 
partitionType)
+    val data = sample(Seq(row("1"), row("2")))
+    assert(predicate.test(0, data.min, data.max, data.nulls))
+    assert(predicate.test(-1, data.min, data.max, data.nulls))
+    assert(predicate.test(data.count, null, data.max, data.nulls))
+    assert(predicate.test(data.count, data.min, data.max, null))
+    assert(predicate.test(data.count, data.max, data.min, data.nulls))
+    Seq[AnyRef](null, Long.box(-1), Long.box(3)).foreach {
+      count =>
+        val counts = new GenericArray(Array[AnyRef](count, Long.box(0), 
Long.box(0)))
+        assert(predicate.test(data.count, data.min, data.max, counts))
+    }
+    val floats = RowType.of(Array[PaimonType](DataTypes.DOUBLE()), Array("x"))
+    val floatPredicate = SparkCatalystPartitionPredicate(
+      LessThan(AttributeReference("x", DoubleType)(), Literal(0.0)),
+      floats)
+    assert(sample(Seq(GenericRow.of(Double.box(Double.NaN))), 
floats).mayMatch(floatPredicate))
+    val binary = RowType.of(Array[PaimonType](DataTypes.BYTES()), Array("x"))
+    val binaryPredicate = SparkCatalystPartitionPredicate(
+      EqualTo(AttributeReference("x", BinaryType)(), Literal(Array[Byte](1))),
+      binary)
+    assert(sample(Seq(GenericRow.of(Array[Byte](-1))), 
binary).mayMatch(binaryPredicate))
+  }
+
+  test("finite-domain work limit is a fallback, never a reason to drop a 
manifest") {
+    val names = (0 until 7).map(i => s"p$i").toArray
+    val rowType = RowType.of(names.map(_ => DataTypes.STRING(): PaimonType), 
names)
+    val nonNull = GenericRow.of(names.map(_ => BinaryString.fromString("a"): 
AnyRef): _*)
+    val nulls = new GenericRow(names.length)
+    val expression = EqualTo(
+      Coalesce(names.map(name => AttributeReference(name, 
StringType)()).toSeq),
+      Literal("z"))
+    assert(
+      sample(Seq(nonNull, nulls), rowType)
+        .mayMatch(SparkCatalystPartitionPredicate(expression, rowType)))
+  }
+
+  test("short statistics retain manifests even when the referenced field is 
present") {
+    val data = sample(Seq(row("10")))
+    val predicate = SparkCatalystPartitionPredicate(EqualTo(cast(), 
Literal(11)), partitionType)
+    assert(!data.mayMatch(predicate))
+    for (size <- 0 until partitionType.getFieldCount) {
+      val shortType = partitionType.project((0 until size).toArray)
+      val shortRow = new GenericRow(size)
+      if (size > 0) shortRow.setField(0, BinaryString.fromString("10"))
+      if (size > 1) shortRow.setField(1, BinaryString.fromString("a"))
+      val shortBinary = new 
InternalRowSerializer(shortType).toBinaryRow(shortRow).copy()
+      Seq[InternalRow](shortRow, shortBinary).foreach {
+        short =>
+          assert(predicate.test(data.count, short, data.max, data.nulls))
+          assert(predicate.test(data.count, data.min, short, data.nulls))
+      }
+      val shortNulls = new GenericArray(Array.fill[AnyRef](size)(Long.box(0)))
+      assert(predicate.test(data.count, data.min, data.max, shortNulls))
+    }
+  }
+
+  test("query SQLConf is initialized once and shared read-only across worker 
threads") {
+    val observed = ConcurrentHashMap.newKeySet[SQLConf]()
+    val expression = ScalaUDF(
+      (_: String) => {
+        observed.add(SQLConf.get)
+        SQLConf.get.sessionLocalTimeZone == "UTC"
+      },
+      BooleanType,
+      Seq(dt))
+    var predicate: SparkCatalystPartitionPredicate = null
+    withSparkSQLConf(
+      "spark.sql.session.timeZone" -> "UTC",
+      "spark.sql.codegen.factoryMode" -> "NO_CODEGEN") {
+      predicate = SparkCatalystPartitionPredicate(expression, partitionType)
+    }
+    val data = sample(Seq(row("10")))
+    val executor = Executors.newFixedThreadPool(4)
+    val barrier = new CyclicBarrier(4)
+    try {
+      val results = (1 to 4).map {
+        _ =>
+          executor.submit(new Callable[Boolean] {
+            override def call(): Boolean = {
+              val caller = new SQLConf
+              caller.setConfString("spark.sql.session.timeZone", 
"Asia/Shanghai")
+              SQLConf.withExistingConf(caller) {
+                barrier.await(30, TimeUnit.SECONDS)
+                (1 to 10).forall {
+                  _ => data.partitions.forall(predicate.test) && (SQLConf.get 
eq caller)
+                }
+              }
+            }
+          })
+      }
+      results.foreach(result => assert(result.get(30, TimeUnit.SECONDS)))
+      assert(observed.size() == 1)
+    } finally {
+      executor.shutdownNow()
+      executor.awaitTermination(30, TimeUnit.SECONDS)
+    }
+  }
+
+  test("timestamp precision, signed zero and binary ordering are not blindly 
delegated") {
+    val timestampType = RowType.of(Array[PaimonType](DataTypes.TIMESTAMP(9)), 
Array("x"))
+    val timestamps = sample(
+      Seq(
+        GenericRow.of(PaimonTimestamp.fromEpochMillis(1000, 1)),
+        GenericRow.of(PaimonTimestamp.fromEpochMillis(2000))),
+      timestampType)
+    val timestampPredicate = SparkCatalystPartitionPredicate(
+      EqualTo(AttributeReference("x", TimestampType)(), 
Literal.create(1000000L, TimestampType)),
+      timestampType)
+    // The first partition becomes exactly 1 second in Spark, despite a larger 
Paimon min.
+    assert(timestamps.partitions.exists(timestampPredicate.test))
+    assert(timestamps.mayMatch(timestampPredicate))
+    val floatType = RowType.of(Array[PaimonType](DataTypes.DOUBLE()), 
Array("x"))
+    val negativeZero =
+      sample(Seq(GenericRow.of(Double.box(-0.0)), 
GenericRow.of(Double.box(0.0))), floatType)
+    assert(
+      negativeZero.mayMatch(
+        SparkCatalystPartitionPredicate(
+          GreaterThan(AttributeReference("x", DoubleType)(), Literal(1.0)),
+          floatType)))
+  }
+
+  test("native reuse agrees with Spark for each enabled statistics type") {
+    val decimalType = DecimalType(10, 2)
+    val cases: Seq[(PaimonType, DataType, AnyRef, AnyRef, Any)] = Seq(
+      (DataTypes.BOOLEAN(), BooleanType, Boolean.box(false), 
Boolean.box(true), true),
+      (DataTypes.TINYINT(), ByteType, Byte.box(-10), Byte.box(10), 20.toByte),
+      (DataTypes.SMALLINT(), ShortType, Short.box(-10), Short.box(10), 
20.toShort),
+      (
+        DataTypes.INT(),
+        IntegerType,
+        Int.box(Int.MinValue),
+        Int.box(Int.MaxValue - 1),
+        Int.MaxValue),
+      (
+        DataTypes.BIGINT(),
+        LongType,
+        Long.box(Long.MinValue),
+        Long.box(Long.MaxValue - 1),
+        Long.MaxValue),
+      (DataTypes.DATE(), DateType, Int.box(-10), Int.box(10), 20),
+      (
+        DataTypes.DECIMAL(10, 2),
+        decimalType,
+        PaimonDecimal.fromBigDecimal(new java.math.BigDecimal("-1.25"), 10, 2),
+        PaimonDecimal.fromBigDecimal(new java.math.BigDecimal("1.25"), 10, 2),
+        Decimal(new java.math.BigDecimal("2.25"), 10, 2)),
+      (
+        DataTypes.STRING(),
+        StringType,
+        BinaryString.fromString("海信"),
+        BinaryString.fromString("\uD83D\uDE00"),
+        org.apache.spark.unsafe.types.UTF8String.fromString("\uFFFF"))
+    )
+    cases.foreach {
+      case (paimonType, sparkType, lower, upper, value) =>
+        val rowType = RowType.of(Array(paimonType), Array("x"))
+        val data =
+          sample(Seq(GenericRow.of(lower), GenericRow.of(upper), 
GenericRow.of(null)), rowType)
+        val attribute = AttributeReference("x", sparkType)()
+        val literal = Literal.create(value, sparkType)
+        Seq[Expression](
+          EqualTo(attribute, literal),
+          LessThan(attribute, literal),
+          GreaterThanOrEqual(attribute, literal),
+          Not(EqualTo(attribute, literal)),
+          IsNull(attribute))
+          .foreach {
+            expression =>
+              val predicate = SparkCatalystPartitionPredicate(expression, 
rowType)
+              assert(
+                !data.partitions.exists(predicate.test) || 
data.mayMatch(predicate),
+                expression.toString)
+          }
+    }
+  }
+
+  test("malformed UTF-8 literals are not changed by native conversion") {
+    val rowType = RowType.of(Array[PaimonType](DataTypes.STRING()), Array("x"))
+    val data = sample(
+      Seq(0xfd, 0xfe, 0xff).map(b => 
GenericRow.of(BinaryString.fromBytes(Array(b.toByte)))),
+      rowType)
+    val literal = Literal.create(
+      org.apache.spark.unsafe.types.UTF8String.fromBytes(Array(0xfe.toByte)),
+      StringType)
+    val predicate = SparkCatalystPartitionPredicate(
+      EqualTo(AttributeReference("x", StringType)(), literal),
+      rowType)
+    assert(data.partitions.exists(predicate.test))
+    assert(data.mayMatch(predicate))
+  }
+
+  test("serialized statistics evaluator preserves compound predicate results") 
{
+    val original = SparkCatalystPartitionPredicate(
+      Or(GreaterThan(cast(), Literal(50)), LessThan(n, Literal(0))),
+      partitionType)
+    val data = sample(Seq(row("10", number = 1), row(null, number = 2)))
+    assert(!data.mayMatch(original))
+    val restored = 
InstantiationUtil.deserializeObject[SparkCatalystPartitionPredicate](
+      InstantiationUtil.serializeObject(original),
+      getClass.getClassLoader)
+    assert(!data.mayMatch(restored))
+  }
+
+  if (gteqSpark3_5) {
+    test("statistics retain query SQLConf when lazy evaluation happens under 
another context") {
+      val key = "spark.sql.legacy.nullInEmptyListBehavior"
+      val data = sample(Seq(row(null)))
+      var predicate: SparkCatalystPartitionPredicate = null
+      withSparkSQLConf(key -> "false") {
+        predicate = SparkCatalystPartitionPredicate(Not(In(dt, Seq.empty)), 
partitionType)
+        // With modern semantics, NULL NOT IN an empty set is true.
+        assert(data.partitions.forall(predicate.test))
+      }
+      withSparkSQLConf(key -> "true") {
+        assert(data.mayMatch(predicate))
+        assert(SQLConf.get.getConfString(key) == "true")
+      }
+    }
+
+    test("query SQLConf survives serialization and cold evaluation on worker 
threads") {
+      val key = "spark.sql.legacy.nullInEmptyListBehavior"
+      val data = sample(Seq(row(null)))
+      val queries = for {
+        legacy <- Seq(false, true)
+        mode <- Seq("CODEGEN_ONLY", "NO_CODEGEN")
+      } yield {
+        var predicate: SparkCatalystPartitionPredicate = null
+        withSparkSQLConf(key -> legacy.toString, 
"spark.sql.codegen.factoryMode" -> mode) {
+          predicate = SparkCatalystPartitionPredicate(Not(In(dt, Seq.empty)), 
partitionType)
+        }
+        val restored = 
InstantiationUtil.deserializeObject[SparkCatalystPartitionPredicate](
+          InstantiationUtil.serializeObject(predicate),
+          getClass.getClassLoader)
+        (legacy, restored)
+      }
+      val executor = Executors.newFixedThreadPool(2)
+      try {
+        val results = queries.map {
+          case (legacy, predicate) =>
+            executor.submit(new Callable[Boolean] {
+              override def call(): Boolean = {
+                val caller = new SQLConf
+                caller.setConfString(key, (!legacy).toString)
+                SQLConf.withExistingConf(caller) {
+                  val expected = !legacy
+                  (1 to 5).forall {
+                    _ =>
+                      data.mayMatch(predicate) == expected &&
+                      data.partitions.forall(predicate.test) == expected &&
+                      SQLConf.get.getConfString(key) == (!legacy).toString
+                  }
+                }
+              }
+            })
+        }
+        results.foreach(result => assert(result.get(30, TimeUnit.SECONDS)))
+      } finally {
+        executor.shutdownNow()
+        executor.awaitTermination(30, TimeUnit.SECONDS)
+      }
+    }
+  }
+
+  test("exhaustive bounded partitions never prune an actual match or Spark 
evaluation error") {
+    val values = Seq[String](
+      null,
+      "",
+      "-2",
+      "0",
+      "00",
+      "+0",
+      " 0 ",
+      "1",
+      "1.5",
+      "2",
+      "10",
+      "100",
+      "20",
+      "invalid",
+      "2147483648")
+    val samples = for {
+      a <- values.indices
+      b <- a until values.size
+      c <- b until values.size
+    } yield sample(Seq(
+      row(values(a), if (a % 2 == 0) null else "a", a),
+      row(values(b), "a", b),
+      row(values(c), "a", c)))
+    val comparisons: Seq[Expression => Expression] = Seq(
+      e => EqualTo(e, Literal(1)),
+      e => EqualNullSafe(e, Literal(1)),
+      e => GreaterThan(e, Literal(1)),
+      e => GreaterThanOrEqual(e, Literal(1)),
+      e => LessThan(e, Literal(1)),
+      e => LessThanOrEqual(e, Literal(1)),
+      e => In(e, Seq(Literal(0), Literal(1), Literal.create(null, 
IntegerType))),
+      e => IsNull(e),
+      e => IsNotNull(e)
+    )
+    val expressions = comparisons.flatMap {
+      comparison =>
+        val plain = comparison(n)
+        Seq(plain, Not(plain)) ++ Seq(false, true).flatMap {
+          ansi =>
+            val converted = comparison(cast(ansi))
+            Seq(
+              converted,
+              Not(converted),
+              And(converted, EqualTo(region, Literal("a"))),
+              Or(converted, IsNull(region)))
+        }
+    }
+    var checked = 0
+    var pruned = 0
+    expressions.foreach {
+      expression =>
+        val predicate = SparkCatalystPartitionPredicate(expression, 
partitionType)
+        samples.foreach {
+          data =>
+            val mustKeep = data.partitions.exists {
+              partition =>
+                try predicate.test(partition)
+                catch { case NonFatal(_) => true }
+            }
+            val keep = data.mayMatch(predicate)
+            assert(
+              !mustKeep || keep,
+              s"Unsafe pruning: $expression, min=${data.min}, max=${data.max}")
+            if (!keep) pruned += 1
+            checked += 1
+        }
+    }
+    assert(checked > 50000)
+    assert(pruned > 100)
+    info(s"No-false-negative checks: $checked; safely pruned cases: $pruned")
+  }
+
+}

Reply via email to