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 26abd6dbab [core] Do not push down MIN/MAX or TopN on stats 
invalidated by a column type change (#10901)
26abd6dbab is described below

commit 26abd6dbabc8650a620c3523f9aa400e577eec79
Author: jackylee <[email protected]>
AuthorDate: Sun Nov 1 22:53:10 2026 +0800

    [core] Do not push down MIN/MAX or TopN on stats invalidated by a column 
type change (#10901)
---
 .../apache/paimon/stats/SimpleStatsEvolution.java  |  7 +++++
 .../apache/paimon/table/source/PushDownUtils.java  | 33 ++++++++++++++++++----
 .../table/source/TopNDataSplitEvaluator.java       | 11 +++++++-
 .../apache/paimon/table/source/TableScanTest.java  | 33 ++++++++++++++++++++++
 .../apache/paimon/flink/BatchFileStoreITCase.java  | 21 ++++++++++++++
 .../paimon/spark/sql/PushDownAggregatesTest.scala  | 22 +++++++++++++++
 6 files changed, 121 insertions(+), 6 deletions(-)

diff --git 
a/paimon-core/src/main/java/org/apache/paimon/stats/SimpleStatsEvolution.java 
b/paimon-core/src/main/java/org/apache/paimon/stats/SimpleStatsEvolution.java
index 906d97501f..4031fe15d0 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/stats/SimpleStatsEvolution.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/stats/SimpleStatsEvolution.java
@@ -45,6 +45,7 @@ import java.util.concurrent.ConcurrentHashMap;
 /** Converter for array of {@link SimpleColStats}. */
 public class SimpleStatsEvolution {
 
+    private final RowType dataRowType;
     private final List<String> fieldNames;
     @Nullable private final int[] indexMapping;
     @Nullable private final CastFieldGetter[] castFieldGetters;
@@ -58,6 +59,7 @@ public class SimpleStatsEvolution {
             RowType rowType,
             @Nullable int[] indexMapping,
             @Nullable CastFieldGetter[] castFieldGetters) {
+        this.dataRowType = rowType;
         this.fieldNames = rowType.getFieldNames();
         this.indexMapping = indexMapping;
         this.castFieldGetters = castFieldGetters;
@@ -66,6 +68,11 @@ public class SimpleStatsEvolution {
         this.emptyNullCounts = new GenericArray(new Object[fieldNames.size()]);
     }
 
+    /** The row type of the files whose statistics this evolution reads, 
before any cast. */
+    public RowType dataRowType() {
+        return dataRowType;
+    }
+
     public InternalRow evolution(InternalRow row, @Nullable List<String> 
denseFields) {
         InternalRow result = row;
 
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/table/source/PushDownUtils.java 
b/paimon-core/src/main/java/org/apache/paimon/table/source/PushDownUtils.java
index fd3946705a..38c5ee0ac2 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/table/source/PushDownUtils.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/table/source/PushDownUtils.java
@@ -25,6 +25,7 @@ import org.apache.paimon.types.BigIntType;
 import org.apache.paimon.types.BooleanType;
 import org.apache.paimon.types.DataField;
 import org.apache.paimon.types.DataType;
+import org.apache.paimon.types.DataTypeCasts;
 import org.apache.paimon.types.DataTypes;
 import org.apache.paimon.types.DateType;
 import org.apache.paimon.types.DoubleType;
@@ -92,7 +93,8 @@ public class PushDownUtils {
      * split to carry a min and a max for each column, or to hold only nulls 
in that column. A file
      * written with {@code stats-mode} {@code counts} for the column is listed 
in its {@code
      * valueStatsCols} but has no min and max, and {@link DataSplit#minValue} 
could not tell it
-     * apart from a column that is null in every row.
+     * apart from a column that is null in every row. A file written before an 
order-breaking change
+     * of the column type, such as STRING to INT, does not qualify either.
      */
     public static boolean minmaxAvailable(
             Split split, Set<String> columns, RowType rowType, 
SimpleStatsEvolutions evolutions) {
@@ -107,11 +109,13 @@ public class PushDownUtils {
                 if (file.rowCount() == 0) {
                     continue;
                 }
+                SimpleStatsEvolution evolution = 
evolutions.getOrCreate(file.schemaId());
+                if (!evolvedMinMaxAvailable(evolution, field)) {
+                    return false;
+                }
                 SimpleStatsEvolution.Result stats =
-                        evolutions
-                                .getOrCreate(file.schemaId())
-                                .evolution(
-                                        file.valueStats(), file.rowCount(), 
file.valueStatsCols());
+                        evolution.evolution(
+                                file.valueStats(), file.rowCount(), 
file.valueStatsCols());
                 Object min = InternalRowUtils.get(stats.minValues(), 
fieldIndex, field.type());
                 Object max = InternalRowUtils.get(stats.maxValues(), 
fieldIndex, field.type());
                 if (min != null && max != null) {
@@ -129,6 +133,25 @@ public class PushDownUtils {
         return true;
     }
 
+    /**
+     * Whether the min and max of {@code field} kept by the files that {@code 
evolution} reads still
+     * bound the field's values. Stats evolution casts min and max separately 
to the current type.
+     * Implicit casts between min/max types only widen numbers and keep their 
order; explicit casts
+     * may not: as strings '100' sorts before '2', and INT to TINYINT turns 
200 into -56. Unlike
+     * filter literals in {@code CastExecutors#castLiteralsWithEvolution}, 
nothing is cast back to
+     * the old type here, as the bounds take the same cast as the rows.
+     */
+    static boolean evolvedMinMaxAvailable(SimpleStatsEvolution evolution, 
DataField field) {
+        RowType dataRowType = evolution.dataRowType();
+        if (!dataRowType.containsField(field.id())) {
+            // written before the field was added, so the file holds only 
nulls for it
+            return true;
+        }
+        DataType dataType = dataRowType.getField(field.id()).type().copy(true);
+        return minmaxAvailable(dataType)
+                && DataTypeCasts.supportsCast(dataType, 
field.type().copy(true), false);
+    }
+
     public static boolean tightBoundsAvailable(Split split) {
         if (!(split instanceof DataSplit)) {
             return false;
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/table/source/TopNDataSplitEvaluator.java
 
b/paimon-core/src/main/java/org/apache/paimon/table/source/TopNDataSplitEvaluator.java
index c010256f76..c84bd91a0c 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/table/source/TopNDataSplitEvaluator.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/table/source/TopNDataSplitEvaluator.java
@@ -40,6 +40,7 @@ import java.util.stream.Collectors;
 
 import static org.apache.paimon.predicate.SortValue.NullOrdering.NULLS_FIRST;
 import static org.apache.paimon.predicate.SortValue.SortDirection.ASCENDING;
+import static 
org.apache.paimon.table.source.PushDownUtils.evolvedMinMaxAvailable;
 import static org.apache.paimon.table.source.PushDownUtils.minmaxAvailable;
 import static 
org.apache.paimon.table.source.PushDownUtils.tightBoundsAvailable;
 
@@ -85,7 +86,8 @@ public class TopNDataSplitEvaluator {
             if (!stats.usableForPruning()) {
                 // Some file of the split lacks min/max/null-count statistics 
for the sort
                 // column (stats.mode=counts/none, or files written before the 
column was
-                // added). The aggregate bound is then not a true bound, so 
ordering the
+                // added), or wrote them before an order-breaking change of 
the column type.
+                // The aggregate bound is then not a true bound, so ordering 
the
                 // split against the others could drop a split holding a top 
row — read it.
                 results.add(dataSplit);
                 continue;
@@ -152,6 +154,13 @@ public class TopNDataSplitEvaluator {
                 continue;
             }
 
+            if (!evolvedMinMaxAvailable(evolution, field)) {
+                // the column type changed in a way that breaks the order of 
values since
+                // this file was written, so its cast min/max bound nothing
+                complete = false;
+                continue;
+            }
+
             Object fileMin =
                     InternalRowUtils.get(
                             evolution.evolution(
diff --git 
a/paimon-core/src/test/java/org/apache/paimon/table/source/TableScanTest.java 
b/paimon-core/src/test/java/org/apache/paimon/table/source/TableScanTest.java
index 9839bd5cdd..8754ae96b3 100644
--- 
a/paimon-core/src/test/java/org/apache/paimon/table/source/TableScanTest.java
+++ 
b/paimon-core/src/test/java/org/apache/paimon/table/source/TableScanTest.java
@@ -1067,6 +1067,39 @@ public class TableScanTest extends ScannerTestBase {
                 .isEqualTo(10L);
     }
 
+    @Test
+    public void testPushDownTopNAfterOrderBreakingTypeChange() throws 
Exception {
+        createAppendOnlyTable();
+
+        // one file of partition 1 holds b = 1 and b = 200
+        StreamTableWrite write = table.newWrite(commitUser);
+        StreamTableCommit commit = table.newCommit(commitUser);
+        write.write(rowData(1, 10, 1L));
+        write.write(rowData(1, 20, 200L));
+        commit.commit(0, write.prepareCommit(true, 0));
+        write.close();
+        commit.close();
+
+        // BIGINT to TINYINT turns 200 into -56, so the file's cast max is no 
upper bound
+        updateColumn("b", DataTypes.TINYINT());
+        write = table.newWrite(commitUser);
+        commit = table.newCommit(commitUser);
+        write.write(rowData(2, 30, (byte) -10));
+        commit.commit(1, write.prepareCommit(true, 1));
+        write.close();
+        commit.close();
+
+        // partition 1 holds both the max (1) and the min (-56), so no 
direction may drop it
+        DataField field = table.schema().fields().get(2);
+        FieldRef ref = new FieldRef(2, field.name(), field.type());
+        TableScan.Plan desc =
+                table.newScan().withTopN(new TopN(ref, DESCENDING, NULLS_LAST, 
1)).plan();
+        assertThat(desc.splits()).hasSize(2);
+        TableScan.Plan asc =
+                table.newScan().withTopN(new TopN(ref, ASCENDING, NULLS_LAST, 
1)).plan();
+        assertThat(asc.splits()).hasSize(2);
+    }
+
     @Test
     public void testPushDownTopNOnlyNull() throws Exception {
         createAppendOnlyTable();
diff --git 
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/BatchFileStoreITCase.java
 
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/BatchFileStoreITCase.java
index 288f72518e..06125e0a4b 100644
--- 
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/BatchFileStoreITCase.java
+++ 
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/BatchFileStoreITCase.java
@@ -953,6 +953,27 @@ public class BatchFileStoreITCase extends 
CatalogITCaseBase {
         validateAggregateNotPushDown(sql, "MinAggFunction", "MaxAggFunction");
     }
 
+    @Test
+    public void testMinMaxNotPushDownAfterOrderBreakingTypeChange() {
+        // one writer, so one file holds '100' and '2': as strings its min is 
'100', its max '2'
+        sql(
+                "CREATE TABLE min_max_type_change (f0 STRING, f1 INT) "
+                        + "WITH ('sink.parallelism' = '1')");
+        sql("INSERT INTO min_max_type_change VALUES ('100', 1), ('2', 2)");
+        sql("ALTER TABLE min_max_type_change MODIFY f0 INT");
+        sql("INSERT INTO min_max_type_change VALUES (50, 3)");
+
+        String sql = "SELECT MIN(f0), MAX(f0) FROM min_max_type_change";
+        assertThat(sql(sql)).containsOnly(Row.of(2, 100));
+        validateAggregateNotPushDown(sql, "MinAggFunction", "MaxAggFunction");
+
+        // a widening keeps the order of values, so the aggregate is still 
pushed down
+        sql("ALTER TABLE min_max_type_change MODIFY f1 BIGINT");
+        sql = "SELECT MIN(f1), MAX(f1) FROM min_max_type_change";
+        assertThat(sql(sql)).containsOnly(Row.of(1L, 3L));
+        validateAggregatePushDown(sql, "MinAggFunction", "MaxAggFunction");
+    }
+
     @Test
     public void testMinMaxPKNotPushDown() {
         sql("CREATE TABLE min_max_pk (f0 INT PRIMARY KEY NOT ENFORCED, f1 
INT)");
diff --git 
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/PushDownAggregatesTest.scala
 
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/PushDownAggregatesTest.scala
index 33f4afad10..b51f35067b 100644
--- 
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/PushDownAggregatesTest.scala
+++ 
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/PushDownAggregatesTest.scala
@@ -18,7 +18,10 @@
 
 package org.apache.paimon.spark.sql
 
+import org.apache.paimon.catalog.Identifier
+import org.apache.paimon.schema.SchemaChange
 import org.apache.paimon.spark.PaimonSparkTestBase
+import org.apache.paimon.types.DataTypes
 
 import org.apache.spark.sql.Row
 import org.apache.spark.sql.catalyst.plans.logical.Aggregate
@@ -253,6 +256,25 @@ class PushDownAggregatesTest extends PaimonSparkTestBase 
with AdaptiveSparkPlanH
     }
   }
 
+  test("Push down aggregate - column type change that breaks ordering") {
+    withTable("T") {
+      spark.sql("CREATE TABLE T (c1 STRING, c2 INT)")
+      // one file holds '100' and '2', so as strings its min is '100' and its 
max is '2'
+      spark.sql("INSERT INTO T SELECT /*+ COALESCE(1) */ * FROM VALUES ('100', 
1), ('2', 2)")
+      // Spark only up-casts in ALTER TABLE, so change the type as Flink or 
the Java API would
+      paimonCatalog.alterTable(
+        Identifier.create(dbName0, "T"),
+        SchemaChange.updateColumnType("c1", DataTypes.INT()),
+        false)
+      spark.sql("INSERT INTO T VALUES (50, 3)")
+      runAndCheckAggregate("SELECT MIN(c1), MAX(c1) FROM T", Row(2, 100) :: 
Nil, 2)
+
+      // a widening keeps the order of values, so the aggregate is still 
pushed down
+      spark.sql("ALTER TABLE T ALTER COLUMN c2 TYPE BIGINT")
+      runAndCheckAggregate("SELECT MIN(c2), MAX(c2) FROM T", Row(1L, 3L) :: 
Nil, 0)
+    }
+  }
+
   test("Push down aggregate - primary key table with deletion vector") {
     Seq(true, false).foreach(
       deletionVectorsEnabled => {

Reply via email to