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 8d704811cb [core] Validate Data Evolution global indexes across schema 
changes (#11348)
8d704811cb is described below

commit 8d704811cb40a7193f0daf73a5d278f10e65e4b6
Author: Jingsong Lee <[email protected]>
AuthorDate: Sun Nov 22 20:51:34 2026 +0800

    [core] Validate Data Evolution global indexes across schema changes (#11348)
---
 docs/docs/concepts/spec/manifest.md                |   5 +
 .../DataEvolutionGlobalIndexCoverage.java          |  22 ++-
 .../DataEvolutionGlobalIndexScanner.java           |  71 +++++---
 .../globalindex/DataEvolutionIndexSchema.java      | 107 ++++++++++++
 .../globalindex/GlobalIndexBuilderUtils.java       |  22 +++
 .../generic/GenericGlobalIndexScanner.java         |  21 ++-
 .../sorted/SortedGlobalIndexScanner.java           |  19 +-
 .../sorted/SortedGlobalIndexWriter.java            |   3 +-
 .../paimon/index/DataEvolutionIndexSourceMeta.java |  29 ++-
 .../table/source/DataEvolutionFullTextRead.java    |  19 +-
 .../table/source/DataEvolutionVectorScan.java      |   6 +-
 .../paimon/globalindex/GlobalIndexQueryTest.java   |   2 +
 .../index/DataEvolutionIndexSourceMetaTest.java    |  47 ++++-
 .../paimon/table/BtreeGlobalIndexTableTest.java    | 194 ++++++++++++++++++++-
 .../flink/globalindex/GenericIndexTopoBuilder.java |   3 +-
 .../index/data_evolution_index_source_meta.py      |  26 ++-
 .../tests/native_sorted_index_build_test.py        |  26 +++
 .../CentroidGlobalIndexTopoBuilder.java            |   2 +-
 .../globalindex/DefaultGlobalIndexTopoBuilder.java |  22 +--
 19 files changed, 564 insertions(+), 82 deletions(-)

diff --git a/docs/docs/concepts/spec/manifest.md 
b/docs/docs/concepts/spec/manifest.md
index a23106c874..71f90eae46 100644
--- a/docs/docs/concepts/spec/manifest.md
+++ b/docs/docs/concepts/spec/manifest.md
@@ -410,6 +410,11 @@ An index manifest describes index files through these 
fields:
 | `_INDEX_META` | BYTES, nullable | Metadata specific to the index 
implementation. |
 | `_SOURCE_META` | BYTES, nullable | Source metadata recorded by the index 
implementation. |
 
+Data Evolution source metadata starts with the four-byte `DEIX` marker and a 
big-endian
+32-bit version. Version 1 contains the 64-bit scan snapshot ID. Version 2 adds 
the 64-bit
+build schema ID after the snapshot ID. Both IDs are big-endian. A build schema 
ID of `-1`
+indicates an unknown build schema.
+
 See [Table Index](./tableindex) for dynamic bucket indexes and deletion 
vectors, and the
 [global index guide](../../primary-key-table/global-index) for query-index 
behavior.
 
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/globalindex/DataEvolutionGlobalIndexCoverage.java
 
b/paimon-core/src/main/java/org/apache/paimon/globalindex/DataEvolutionGlobalIndexCoverage.java
index 072e0a13e1..7d441e7cbe 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/globalindex/DataEvolutionGlobalIndexCoverage.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/globalindex/DataEvolutionGlobalIndexCoverage.java
@@ -60,6 +60,22 @@ public class DataEvolutionGlobalIndexCoverage {
             @Nullable PartitionPredicate partitionFilter,
             Collection<IndexFileMeta> indexFiles,
             GlobalIndexSearchMode searchMode) {
+        this(
+                table,
+                snapshot,
+                partitionFilter,
+                indexFiles,
+                searchMode,
+                new DataEvolutionIndexSchema(table));
+    }
+
+    public DataEvolutionGlobalIndexCoverage(
+            FileStoreTable table,
+            @Nullable Snapshot snapshot,
+            @Nullable PartitionPredicate partitionFilter,
+            Collection<IndexFileMeta> indexFiles,
+            GlobalIndexSearchMode searchMode,
+            DataEvolutionIndexSchema schema) {
         this.table = table;
         this.snapshot = snapshot;
         this.partitionFilter = partitionFilter;
@@ -67,12 +83,10 @@ public class DataEvolutionGlobalIndexCoverage {
         this.coverageByField = new HashMap<>();
         for (IndexFileMeta indexFile : indexFiles) {
             GlobalIndexMeta meta = checkNotNull(indexFile.globalIndexMeta());
-            if 
(!DataEvolutionGlobalIndexScanner.isIndexInSchema(table.rowType(), indexFile)) {
-                continue;
-            }
             // Single-field coverage belongs to single-field index 
definitions. Multi-field
             // query paths supply their actual coverage explicitly.
-            if (meta.extraFieldIds() != null && meta.extraFieldIds().length > 
0) {
+            if ((meta.extraFieldIds() != null && meta.extraFieldIds().length > 
0)
+                    || !schema.isCompatible(indexFile)) {
                 continue;
             }
             addCoverage(meta.indexFieldId(), meta.rowRange());
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/globalindex/DataEvolutionGlobalIndexScanner.java
 
b/paimon-core/src/main/java/org/apache/paimon/globalindex/DataEvolutionGlobalIndexScanner.java
index 0de1ac08d5..9b7e51794e 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/globalindex/DataEvolutionGlobalIndexScanner.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/globalindex/DataEvolutionGlobalIndexScanner.java
@@ -89,7 +89,8 @@ public class DataEvolutionGlobalIndexScanner implements 
Closeable {
             @Nullable PartitionPredicate partitionFilter,
             GlobalIndexSearchMode searchMode,
             Collection<IndexFileMeta> coverageIndexFiles,
-            Collection<IndexFileMeta> indexFiles) {
+            Collection<IndexFileMeta> indexFiles,
+            DataEvolutionIndexSchema schema) {
         this.table = table;
         this.indexFiles = new ArrayList<>(indexFiles);
         this.fileIO = table.fileIO();
@@ -100,7 +101,7 @@ public class DataEvolutionGlobalIndexScanner implements 
Closeable {
         this.indexPathFactory = 
table.store().pathFactory().globalIndexFileFactory();
         this.coverage =
                 new DataEvolutionGlobalIndexCoverage(
-                        table, snapshot, partitionFilter, coverageIndexFiles, 
searchMode);
+                        table, snapshot, partitionFilter, coverageIndexFiles, 
searchMode, schema);
         GlobalIndexFileReader indexFileReader = meta -> 
fileIO.newInputStream(meta.filePath());
         Map<Integer, List<IndexMetaFileGroup>> groupsByField = 
groupIndexFiles(indexFiles);
         IntFunction<Collection<GlobalIndexReader>> readersFunction =
@@ -203,6 +204,22 @@ public class DataEvolutionGlobalIndexScanner implements 
Closeable {
             @Nullable PartitionPredicate partitionFilter,
             Collection<IndexFileMeta> indexFiles,
             GlobalIndexSearchMode searchMode) {
+        return createForScalarFilters(
+                table,
+                pinnedSnapshot,
+                partitionFilter,
+                indexFiles,
+                searchMode,
+                new DataEvolutionIndexSchema(table));
+    }
+
+    public static Optional<DataEvolutionGlobalIndexScanner> 
createForScalarFilters(
+            FileStoreTable table,
+            @Nullable Snapshot pinnedSnapshot,
+            @Nullable PartitionPredicate partitionFilter,
+            Collection<IndexFileMeta> indexFiles,
+            GlobalIndexSearchMode searchMode,
+            DataEvolutionIndexSchema schema) {
         return create(
                 table,
                 pinnedSnapshot,
@@ -210,7 +227,8 @@ public class DataEvolutionGlobalIndexScanner implements 
Closeable {
                 indexFiles.stream()
                         .filter(file -> !isMultiFieldIndex(file))
                         .collect(Collectors.toList()),
-                searchMode);
+                searchMode,
+                schema);
     }
 
     public static Optional<DataEvolutionGlobalIndexScanner> create(
@@ -223,7 +241,8 @@ public class DataEvolutionGlobalIndexScanner implements 
Closeable {
                 pinnedSnapshot,
                 partitionFilter,
                 indexFiles,
-                table.coreOptions().scalarIndexSearchMode());
+                table.coreOptions().scalarIndexSearchMode(),
+                new DataEvolutionIndexSchema(table));
     }
 
     private static Optional<DataEvolutionGlobalIndexScanner> create(
@@ -231,11 +250,10 @@ public class DataEvolutionGlobalIndexScanner implements 
Closeable {
             @Nullable Snapshot pinnedSnapshot,
             @Nullable PartitionPredicate partitionFilter,
             Collection<IndexFileMeta> indexFiles,
-            GlobalIndexSearchMode searchMode) {
+            GlobalIndexSearchMode searchMode,
+            DataEvolutionIndexSchema schema) {
         List<IndexFileMeta> globalIndexFiles =
-                globalIndexFiles(indexFiles).stream()
-                        .filter(file -> isIndexInSchema(table.rowType(), file))
-                        .collect(Collectors.toList());
+                
indexFiles.stream().filter(schema::isCompatible).collect(Collectors.toList());
         if (globalIndexFiles.isEmpty()) {
             return Optional.empty();
         }
@@ -246,7 +264,8 @@ public class DataEvolutionGlobalIndexScanner implements 
Closeable {
                         partitionFilter,
                         searchMode,
                         globalIndexFiles,
-                        globalIndexFiles));
+                        globalIndexFiles,
+                        schema));
     }
 
     public static Optional<DataEvolutionGlobalIndexScanner> create(
@@ -264,9 +283,11 @@ public class DataEvolutionGlobalIndexScanner implements 
Closeable {
         if (snapshot == null) {
             return Optional.empty();
         }
+        DataEvolutionIndexSchema schema = new DataEvolutionIndexSchema(table);
         List<IndexFileMeta> indexFiles =
                 table.store().newIndexFileHandler()
-                        .scan(snapshot, indexFileFilter(table, 
partitionFilter, filter)).stream()
+                        .scan(snapshot, indexFileFilter(table, 
partitionFilter, filter, schema))
+                        .stream()
                         .map(IndexManifestEntry::indexFile)
                         .collect(Collectors.toList());
         if (indexFiles.isEmpty()) {
@@ -279,7 +300,8 @@ public class DataEvolutionGlobalIndexScanner implements 
Closeable {
                         partitionFilter,
                         table.coreOptions().scalarScanSearchMode(),
                         indexFiles,
-                        indexFiles));
+                        indexFiles,
+                        schema));
     }
 
     /**
@@ -307,10 +329,12 @@ public class DataEvolutionGlobalIndexScanner implements 
Closeable {
 
         DataField indexField = 
table.rowType().getField(topN.orders().get(0).field().name());
         int fieldId = indexField.id();
+        DataEvolutionIndexSchema schema = new DataEvolutionIndexSchema(table);
         List<IndexFileMeta> indexFiles =
                 table.store().newIndexFileHandler()
                         .scan(snapshot, topNIndexFileFilter(partitionFilter, 
fieldId)).stream()
                         .map(IndexManifestEntry::indexFile)
+                        .filter(schema::isCompatible)
                         .collect(Collectors.toList());
         if (indexFiles.isEmpty()) {
             return Optional.empty();
@@ -324,7 +348,8 @@ public class DataEvolutionGlobalIndexScanner implements 
Closeable {
                         partitionFilter,
                         table.coreOptions().scalarScanSearchMode(),
                         indexFiles,
-                        selectedIndexFiles));
+                        selectedIndexFiles,
+                        schema));
     }
 
     private static boolean isSupportedTopN(TopN topN) {
@@ -354,6 +379,14 @@ public class DataEvolutionGlobalIndexScanner implements 
Closeable {
             FileStoreTable table,
             @Nullable PartitionPredicate partitionFilter,
             @Nullable Predicate filter) {
+        return indexFileFilter(table, partitionFilter, filter, new 
DataEvolutionIndexSchema(table));
+    }
+
+    private static Filter<IndexManifestEntry> indexFileFilter(
+            FileStoreTable table,
+            @Nullable PartitionPredicate partitionFilter,
+            @Nullable Predicate filter,
+            DataEvolutionIndexSchema schema) {
         if (filter == null) {
             return entry -> false;
         }
@@ -364,11 +397,9 @@ public class DataEvolutionGlobalIndexScanner implements 
Closeable {
                         return false;
                     }
                     GlobalIndexMeta globalIndex = 
entry.indexFile().globalIndexMeta();
-                    if (globalIndex == null
-                            || !isIndexInSchema(table.rowType(), 
entry.indexFile())) {
-                        return false;
-                    }
-                    return filterFieldIds.contains(globalIndex.indexFieldId());
+                    return globalIndex != null
+                            && 
filterFieldIds.contains(globalIndex.indexFieldId())
+                            && schema.isCompatible(entry.indexFile());
                 };
         return indexFileFilter;
     }
@@ -384,12 +415,6 @@ public class DataEvolutionGlobalIndexScanner implements 
Closeable {
                 .allMatch(rowType::containsField);
     }
 
-    private static List<IndexFileMeta> 
globalIndexFiles(Collection<IndexFileMeta> indexFiles) {
-        return indexFiles.stream()
-                .filter(indexFile -> indexFile.globalIndexMeta() != null)
-                .collect(Collectors.toList());
-    }
-
     public Optional<GlobalIndexResult> scan(Predicate predicate) {
         return 
scanWithCoverage(predicate).map(GlobalIndexEvaluator.Evaluation::result);
     }
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/globalindex/DataEvolutionIndexSchema.java
 
b/paimon-core/src/main/java/org/apache/paimon/globalindex/DataEvolutionIndexSchema.java
new file mode 100644
index 0000000000..83e490c744
--- /dev/null
+++ 
b/paimon-core/src/main/java/org/apache/paimon/globalindex/DataEvolutionIndexSchema.java
@@ -0,0 +1,107 @@
+/*
+ * 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.globalindex;
+
+import org.apache.paimon.CoreOptions;
+import org.apache.paimon.index.DataEvolutionIndexSourceMeta;
+import org.apache.paimon.index.GlobalIndexMeta;
+import org.apache.paimon.index.IndexFileMeta;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.types.RowType;
+
+import java.io.FileNotFoundException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import static 
org.apache.paimon.index.DataEvolutionIndexSourceMeta.UNKNOWN_SCHEMA_ID;
+
+/** Checks scalar index key compatibility with the table schema used for a 
Data Evolution scan. */
+public final class DataEvolutionIndexSchema {
+
+    private final FileStoreTable table;
+    private final RowType readType;
+    private final Map<Long, Optional<RowType>> schemas = new HashMap<>();
+    private final Map<Long, Map<Integer, Boolean>> fieldCompatibility = new 
HashMap<>();
+
+    public DataEvolutionIndexSchema(FileStoreTable table) {
+        this.table = table;
+        this.readType = table.rowType();
+    }
+
+    public boolean isCompatible(IndexFileMeta file) {
+        GlobalIndexMeta meta = file.globalIndexMeta();
+        if (meta == null) {
+            return false;
+        }
+        List<Integer> fieldIds = meta.getIndexedFieldIds();
+        long sourceSchemaId = UNKNOWN_SCHEMA_ID;
+        byte[] sourceMeta = meta.sourceMeta();
+        if (table.coreOptions().dataEvolutionEnabled()
+                && !"full-text".equals(file.indexType())
+                && !CoreOptions.isVectorIndexType(file.indexType())
+                && 
DataEvolutionIndexSourceMeta.isDataEvolutionMeta(sourceMeta)) {
+            try {
+                sourceSchemaId =
+                        
DataEvolutionIndexSourceMeta.deserialize(sourceMeta).sourceSchemaId();
+            } catch (IllegalArgumentException e) {
+                // An unrecognized source cannot establish compatible index 
keys.
+                return false;
+            }
+        }
+        if (sourceSchemaId == UNKNOWN_SCHEMA_ID) {
+            return fieldIds.stream().allMatch(readType::containsField);
+        }
+        Optional<RowType> sourceType = schema(sourceSchemaId);
+        if (!sourceType.isPresent()) {
+            return false;
+        }
+        Map<Integer, Boolean> fields =
+                fieldCompatibility.computeIfAbsent(sourceSchemaId, id -> new 
HashMap<>());
+        return fieldIds.stream()
+                .allMatch(
+                        id ->
+                                fields.computeIfAbsent(
+                                        id, fieldId -> 
sameType(sourceType.get(), fieldId)));
+    }
+
+    private boolean sameType(RowType source, int fieldId) {
+        return source.containsField(fieldId)
+                && readType.containsField(fieldId)
+                && source.getField(fieldId)
+                        .type()
+                        
.equalsIgnoreNullable(readType.getField(fieldId).type());
+    }
+
+    private Optional<RowType> schema(long schemaId) {
+        return schemas.computeIfAbsent(
+                schemaId,
+                id -> {
+                    if (id == table.schema().id()) {
+                        return Optional.of(readType);
+                    }
+                    try {
+                        return 
Optional.of(table.schemaManager().tryGetSchema(id).logicalRowType());
+                    } catch (FileNotFoundException e) {
+                        return Optional.empty();
+                    }
+                });
+    }
+}
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/globalindex/GlobalIndexBuilderUtils.java
 
b/paimon-core/src/main/java/org/apache/paimon/globalindex/GlobalIndexBuilderUtils.java
index 0c956c2137..8d6910a63a 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/globalindex/GlobalIndexBuilderUtils.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/globalindex/GlobalIndexBuilderUtils.java
@@ -49,12 +49,15 @@ import javax.annotation.Nullable;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.Comparator;
 import java.util.HashMap;
 import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 import java.util.function.BiFunction;
 import java.util.function.Supplier;
 import java.util.stream.Collectors;
@@ -153,6 +156,25 @@ public class GlobalIndexBuilderUtils {
         return Range.sortAndMergeOverlap(dataRange.exclude(indexedRanges), 
true);
     }
 
+    public static Set<IndexManifestEntry> indexesWithIncompatibleSchema(
+            FileStoreTable table, List<IndexManifestEntry> currentIndexes) {
+        DataEvolutionIndexSchema schema = new DataEvolutionIndexSchema(table);
+        return currentIndexes.stream()
+                .filter(entry -> !schema.isCompatible(entry.indexFile()))
+                .collect(Collectors.toCollection(LinkedHashSet::new));
+    }
+
+    public static List<Range> rowRangesToBuild(
+            Snapshot snapshot,
+            List<IndexManifestEntry> currentIndexes,
+            Collection<IndexManifestEntry> indexesToRefresh) {
+        List<Range> ranges = new ArrayList<>(unindexedRowRanges(snapshot, 
currentIndexes));
+        for (IndexManifestEntry entry : indexesToRefresh) {
+            ranges.add(entry.indexFile().globalIndexMeta().rowRange());
+        }
+        return Range.sortAndMergeOverlap(ranges, true);
+    }
+
     public static List<IndexManifestEntry> currentIndexEntries(
             FileStoreTable table,
             Snapshot snapshot,
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/globalindex/generic/GenericGlobalIndexScanner.java
 
b/paimon-core/src/main/java/org/apache/paimon/globalindex/generic/GenericGlobalIndexScanner.java
index 619467daad..8a2980b3f9 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/globalindex/generic/GenericGlobalIndexScanner.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/globalindex/generic/GenericGlobalIndexScanner.java
@@ -38,9 +38,11 @@ import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 import java.util.Optional;
+import java.util.Set;
 
 import static 
org.apache.paimon.globalindex.GlobalIndexBuilderUtils.currentIndexEntries;
-import static 
org.apache.paimon.globalindex.GlobalIndexBuilderUtils.unindexedRowRanges;
+import static 
org.apache.paimon.globalindex.GlobalIndexBuilderUtils.indexesWithIncompatibleSchema;
+import static 
org.apache.paimon.globalindex.GlobalIndexBuilderUtils.rowRangesToBuild;
 import static org.apache.paimon.utils.Preconditions.checkArgument;
 
 /** Scanner for generic (non-btree) global index. */
@@ -139,24 +141,21 @@ public class GenericGlobalIndexScanner implements 
Serializable {
         List<IndexManifestEntry> currentIndexes =
                 currentIndexEntries(
                         table, scanSnapshot, indexType, indexFields, 
partitionPredicate);
-        List<Range> rangesToBuild =
-                new ArrayList<>(unindexedRowRanges(scanSnapshot, 
currentIndexes));
-        List<IndexManifestEntry> deletedIndexEntries = Collections.emptyList();
+        Set<IndexManifestEntry> deletedIndexEntries =
+                indexesWithIncompatibleSchema(table, currentIndexes);
         Options mergedOptions = new Options(table.options(), options.toMap());
         if (mergedOptions.get(CoreOptions.GLOBAL_INDEX_COLUMN_UPDATE_ACTION)
                 == CoreOptions.GlobalIndexColumnUpdateAction.IGNORE) {
-            deletedIndexEntries =
+            deletedIndexEntries.addAll(
                     
DataEvolutionGlobalIndexRefreshPlanner.findIndexesToRefresh(
                             table.schemaManager(),
                             scanResult.entries(),
                             currentIndexes,
-                            indexFields);
-            for (IndexManifestEntry entry : deletedIndexEntries) {
-                
rangesToBuild.add(entry.indexFile().globalIndexMeta().rowRange());
-            }
+                            indexFields));
         }
 
-        rangesToBuild = Range.sortAndMergeOverlap(rangesToBuild, true);
+        List<Range> rangesToBuild =
+                rowRangesToBuild(scanSnapshot, currentIndexes, 
deletedIndexEntries);
         if (rangesToBuild.isEmpty()) {
             return Optional.empty();
         }
@@ -165,6 +164,6 @@ public class GenericGlobalIndexScanner implements 
Serializable {
                         scanResult.scanSnapshotId(),
                         RowRangeIndex.create(rangesToBuild),
                         scanResult.entries(),
-                        deletedIndexEntries));
+                        new ArrayList<>(deletedIndexEntries)));
     }
 }
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/globalindex/sorted/SortedGlobalIndexScanner.java
 
b/paimon-core/src/main/java/org/apache/paimon/globalindex/sorted/SortedGlobalIndexScanner.java
index 753725793c..3b53d5861b 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/globalindex/sorted/SortedGlobalIndexScanner.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/globalindex/sorted/SortedGlobalIndexScanner.java
@@ -42,10 +42,12 @@ import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 import java.util.Optional;
+import java.util.Set;
 
 import static org.apache.paimon.format.blob.BlobFileFormat.isBlobFile;
 import static 
org.apache.paimon.globalindex.GlobalIndexBuilderUtils.currentIndexEntries;
-import static 
org.apache.paimon.globalindex.GlobalIndexBuilderUtils.unindexedRowRanges;
+import static 
org.apache.paimon.globalindex.GlobalIndexBuilderUtils.indexesWithIncompatibleSchema;
+import static 
org.apache.paimon.globalindex.GlobalIndexBuilderUtils.rowRangesToBuild;
 import static org.apache.paimon.types.VectorType.isVectorStoreFile;
 import static org.apache.paimon.utils.Preconditions.checkArgument;
 
@@ -139,19 +141,16 @@ public class SortedGlobalIndexScanner implements 
Serializable {
         Preconditions.checkArgument(indexFields != null, "indexFields must be 
set before scan.");
         List<IndexManifestEntry> currentIndexes =
                 currentIndexEntries(table, snapshot, indexType, indexFields, 
partitionPredicate);
-        List<Range> rangesToBuild = new 
ArrayList<>(unindexedRowRanges(snapshot, currentIndexes));
-        List<IndexManifestEntry> deletedIndexEntries = Collections.emptyList();
+        Set<IndexManifestEntry> deletedIndexEntries =
+                indexesWithIncompatibleSchema(table, currentIndexes);
         if (detectDataFileChange()) {
             // Scans data manifests through reusable binary views without 
materializing entries.
-            deletedIndexEntries =
+            deletedIndexEntries.addAll(
                     
DataEvolutionGlobalIndexRefreshPlanner.findIndexesToRefresh(
-                            table, snapshot, partitionPredicate, 
currentIndexes, indexFields);
-            for (IndexManifestEntry entry : deletedIndexEntries) {
-                
rangesToBuild.add(entry.indexFile().globalIndexMeta().rowRange());
-            }
+                            table, snapshot, partitionPredicate, 
currentIndexes, indexFields));
         }
 
-        rangesToBuild = Range.sortAndMergeOverlap(rangesToBuild, true);
+        List<Range> rangesToBuild = rowRangesToBuild(snapshot, currentIndexes, 
deletedIndexEntries);
         if (rangesToBuild.isEmpty()) {
             return Optional.empty();
         }
@@ -161,7 +160,7 @@ public class SortedGlobalIndexScanner implements 
Serializable {
                         snapshot.id(),
                         RowRangeIndex.create(rangesToBuild),
                         snapshotReader.read().dataSplits(),
-                        deletedIndexEntries));
+                        new ArrayList<>(deletedIndexEntries)));
     }
 
     private boolean detectDataFileChange() {
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/globalindex/sorted/SortedGlobalIndexWriter.java
 
b/paimon-core/src/main/java/org/apache/paimon/globalindex/sorted/SortedGlobalIndexWriter.java
index 19a8ce4575..568cda3dce 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/globalindex/sorted/SortedGlobalIndexWriter.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/globalindex/sorted/SortedGlobalIndexWriter.java
@@ -159,7 +159,8 @@ public class SortedGlobalIndexWriter implements 
Serializable {
             BinaryRow partition,
             long scanSnapshotId)
             throws IOException {
-        byte[] sourceMeta = new 
DataEvolutionIndexSourceMeta(scanSnapshotId).serialize();
+        byte[] sourceMeta =
+                new DataEvolutionIndexSourceMeta(scanSnapshotId, 
table.schema().id()).serialize();
         List<IndexFileMeta> indexFileMetas =
                 toIndexFileMetas(
                         table.fileIO(),
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/index/DataEvolutionIndexSourceMeta.java
 
b/paimon-core/src/main/java/org/apache/paimon/index/DataEvolutionIndexSourceMeta.java
index fb39bc2f8e..ef585a9efb 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/index/DataEvolutionIndexSourceMeta.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/index/DataEvolutionIndexSourceMeta.java
@@ -27,30 +27,48 @@ import java.io.IOException;
 
 import static org.apache.paimon.utils.Preconditions.checkArgument;
 
-/** Data snapshot scanned to build a global index for a data-evolution table. 
*/
+/** Snapshot and table schema used to build a global index for a Data 
Evolution table. */
 public final class DataEvolutionIndexSourceMeta {
 
+    public static final long UNKNOWN_SCHEMA_ID = -1L;
+
     // "DEIX". The marker distinguishes this metadata from primary-key index 
source metadata.
     private static final int MAGIC = 0x44454958;
-    private static final int VERSION = 1;
+    private static final int LEGACY_VERSION = 1;
+    private static final int VERSION = 2;
 
     private final long scanSnapshotId;
+    private final long sourceSchemaId;
 
     public DataEvolutionIndexSourceMeta(long scanSnapshotId) {
+        this(scanSnapshotId, UNKNOWN_SCHEMA_ID);
+    }
+
+    public DataEvolutionIndexSourceMeta(long scanSnapshotId, long 
sourceSchemaId) {
         checkArgument(scanSnapshotId > 0, "Scan snapshot id must be 
positive.");
+        checkArgument(
+                sourceSchemaId >= UNKNOWN_SCHEMA_ID,
+                "Source schema id must be -1 or non-negative.");
         this.scanSnapshotId = scanSnapshotId;
+        this.sourceSchemaId = sourceSchemaId;
     }
 
     public long scanSnapshotId() {
         return scanSnapshotId;
     }
 
+    public long sourceSchemaId() {
+        return sourceSchemaId;
+    }
+
     public byte[] serialize() {
         try {
-            DataOutputSerializer output = new DataOutputSerializer(16);
+            DataOutputSerializer output =
+                    new DataOutputSerializer(2 * Integer.BYTES + 2 * 
Long.BYTES);
             output.writeInt(MAGIC);
             output.writeInt(VERSION);
             output.writeLong(scanSnapshotId);
+            output.writeLong(sourceSchemaId);
             return output.getCopyOfBuffer();
         } catch (IOException e) {
             throw new RuntimeException(
@@ -76,14 +94,15 @@ public final class DataEvolutionIndexSourceMeta {
             checkArgument(magic == MAGIC, "Not data-evolution index source 
metadata.");
             int version = input.readInt();
             checkArgument(
-                    version == VERSION,
+                    version == LEGACY_VERSION || version == VERSION,
                     "Unsupported data-evolution index source version: %s.",
                     version);
             long scanSnapshotId = input.readLong();
+            long sourceSchemaId = version == VERSION ? input.readLong() : 
UNKNOWN_SCHEMA_ID;
             checkArgument(
                     input.available() == 0,
                     "Unexpected trailing bytes in data-evolution index source 
metadata.");
-            return new DataEvolutionIndexSourceMeta(scanSnapshotId);
+            return new DataEvolutionIndexSourceMeta(scanSnapshotId, 
sourceSchemaId);
         } catch (IOException e) {
             throw new IllegalArgumentException(
                     "Failed to deserialize data-evolution index source 
metadata.", e);
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/table/source/DataEvolutionFullTextRead.java
 
b/paimon-core/src/main/java/org/apache/paimon/table/source/DataEvolutionFullTextRead.java
index 919807a938..e4d7e9d6ce 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/table/source/DataEvolutionFullTextRead.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/table/source/DataEvolutionFullTextRead.java
@@ -22,6 +22,7 @@ import org.apache.paimon.CoreOptions.GlobalIndexSearchMode;
 import org.apache.paimon.Snapshot;
 import org.apache.paimon.globalindex.DataEvolutionGlobalIndexCoverage;
 import org.apache.paimon.globalindex.DataEvolutionGlobalIndexScanner;
+import org.apache.paimon.globalindex.DataEvolutionIndexSchema;
 import org.apache.paimon.globalindex.GlobalIndexEvaluator;
 import org.apache.paimon.globalindex.GlobalIndexIOMeta;
 import org.apache.paimon.globalindex.GlobalIndexReadThreadPool;
@@ -212,13 +213,15 @@ public class DataEvolutionFullTextRead implements 
FullTextRead {
 
         RoaringNavigableMap64 unindexed = new RoaringNavigableMap64();
         GlobalIndexSearchMode prefilterMode = 
table.coreOptions().scalarPrefilterSearchMode();
+        DataEvolutionIndexSchema schema = new DataEvolutionIndexSchema(table);
         for (Range range :
                 new DataEvolutionGlobalIndexCoverage(
                                 table,
                                 planSnapshot,
                                 partitionFilter,
                                 scalarIndexFiles,
-                                prefilterMode)
+                                prefilterMode,
+                                schema)
                         .unindexedRanges(table.rowType(), filter)) {
             unindexed.addRange(range);
         }
@@ -230,7 +233,7 @@ public class DataEvolutionFullTextRead implements 
FullTextRead {
         RoaringNavigableMap64 matched = new RoaringNavigableMap64();
         if (!decidedByIndex.isEmpty()) {
             Optional<GlobalIndexEvaluator.Evaluation> evaluation =
-                    evaluateWithIndexes(scalarIndexFiles, planSnapshot);
+                    evaluateWithIndexes(scalarIndexFiles, planSnapshot, 
prefilterMode, schema);
             if (evaluation.isPresent()) {
                 RoaringNavigableMap64 fromIndex =
                         RoaringNavigableMap64.and(
@@ -268,10 +271,18 @@ public class DataEvolutionFullTextRead implements 
FullTextRead {
     }
 
     private Optional<GlobalIndexEvaluator.Evaluation> evaluateWithIndexes(
-            Set<IndexFileMeta> scalarIndexFiles, @Nullable Snapshot 
planSnapshot) {
+            Set<IndexFileMeta> scalarIndexFiles,
+            @Nullable Snapshot planSnapshot,
+            GlobalIndexSearchMode prefilterMode,
+            DataEvolutionIndexSchema schema) {
         Optional<DataEvolutionGlobalIndexScanner> optionalScanner =
                 DataEvolutionGlobalIndexScanner.createForScalarFilters(
-                        table, planSnapshot, partitionFilter, 
scalarIndexFiles);
+                        table,
+                        planSnapshot,
+                        partitionFilter,
+                        scalarIndexFiles,
+                        prefilterMode,
+                        schema);
         if (!optionalScanner.isPresent()) {
             return Optional.empty();
         }
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/table/source/DataEvolutionVectorScan.java
 
b/paimon-core/src/main/java/org/apache/paimon/table/source/DataEvolutionVectorScan.java
index 8755eacc20..d978fc6381 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/table/source/DataEvolutionVectorScan.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/table/source/DataEvolutionVectorScan.java
@@ -24,6 +24,7 @@ import org.apache.paimon.Snapshot;
 import org.apache.paimon.globalindex.CentroidIndexMeta;
 import org.apache.paimon.globalindex.DataEvolutionGlobalIndexCoverage;
 import org.apache.paimon.globalindex.DataEvolutionGlobalIndexScanner;
+import org.apache.paimon.globalindex.DataEvolutionIndexSchema;
 import org.apache.paimon.globalindex.GlobalIndexEvaluator;
 import org.apache.paimon.index.GlobalIndexMeta;
 import org.apache.paimon.index.IndexFileHandler;
@@ -265,9 +266,10 @@ public class DataEvolutionVectorScan implements VectorScan 
{
         if (searchMode == GlobalIndexSearchMode.FAST) {
             return Collections.emptyList();
         }
+        DataEvolutionIndexSchema schema = new DataEvolutionIndexSchema(table);
         DataEvolutionGlobalIndexCoverage coverage =
                 new DataEvolutionGlobalIndexCoverage(
-                        table, snapshot, partitionFilter, scalarFiles, 
searchMode);
+                        table, snapshot, partitionFilter, scalarFiles, 
searchMode, schema);
         List<Range> dataRanges = 
coverage.unindexedRanges(Collections.emptySet(), null);
         boolean possiblyPartial = false;
         for (int fieldId : filterFieldIds) {
@@ -286,7 +288,7 @@ public class DataEvolutionVectorScan implements VectorScan {
         // use the actual contributing fields so a declined OR arm does not 
generate raw work.
         Optional<DataEvolutionGlobalIndexScanner> optionalScanner =
                 DataEvolutionGlobalIndexScanner.createForScalarFilters(
-                        table, snapshot, partitionFilter, scalarFiles, 
searchMode);
+                        table, snapshot, partitionFilter, scalarFiles, 
searchMode, schema);
         if (!optionalScanner.isPresent()) {
             return Collections.emptyList();
         }
diff --git 
a/paimon-core/src/test/java/org/apache/paimon/globalindex/GlobalIndexQueryTest.java
 
b/paimon-core/src/test/java/org/apache/paimon/globalindex/GlobalIndexQueryTest.java
index a04876c6a0..51dbb53b6f 100644
--- 
a/paimon-core/src/test/java/org/apache/paimon/globalindex/GlobalIndexQueryTest.java
+++ 
b/paimon-core/src/test/java/org/apache/paimon/globalindex/GlobalIndexQueryTest.java
@@ -18,6 +18,7 @@
 
 package org.apache.paimon.globalindex;
 
+import org.apache.paimon.CoreOptions;
 import org.apache.paimon.data.BinaryRow;
 import org.apache.paimon.data.BinaryString;
 import org.apache.paimon.data.Decimal;
@@ -655,6 +656,7 @@ class GlobalIndexQueryTest {
         RowType rowType = RowType.of(DataTypes.INT(), DataTypes.INT());
         FileStoreTable table = mock(FileStoreTable.class);
         when(table.rowType()).thenReturn(rowType);
+        when(table.coreOptions()).thenReturn(new CoreOptions(new Options()));
         PredicateBuilder builder = new PredicateBuilder(rowType);
         int firstId = rowType.getFields().get(0).id();
         int secondId = rowType.getFields().get(1).id();
diff --git 
a/paimon-core/src/test/java/org/apache/paimon/index/DataEvolutionIndexSourceMetaTest.java
 
b/paimon-core/src/test/java/org/apache/paimon/index/DataEvolutionIndexSourceMetaTest.java
index c281ebdd2f..ad4e2d51eb 100644
--- 
a/paimon-core/src/test/java/org/apache/paimon/index/DataEvolutionIndexSourceMetaTest.java
+++ 
b/paimon-core/src/test/java/org/apache/paimon/index/DataEvolutionIndexSourceMetaTest.java
@@ -22,6 +22,7 @@ import org.apache.paimon.io.DataOutputSerializer;
 
 import org.junit.jupiter.api.Test;
 
+import java.nio.ByteBuffer;
 import java.util.Arrays;
 
 import static org.assertj.core.api.Assertions.assertThat;
@@ -39,16 +40,60 @@ class DataEvolutionIndexSourceMetaTest {
         
assertThat(DataEvolutionIndexSourceMeta.isDataEvolutionMeta(serialized)).isTrue();
         
assertThat(DataEvolutionIndexSourceMeta.deserialize(serialized).scanSnapshotId())
                 .isEqualTo(42L);
+        
assertThat(DataEvolutionIndexSourceMeta.deserialize(serialized).sourceSchemaId())
+                .isEqualTo(-1L);
         
assertThat(DataEvolutionIndexSourceMeta.isDataEvolutionMeta(null)).isFalse();
         assertThat(DataEvolutionIndexSourceMeta.isDataEvolutionMeta(new byte[] 
{1})).isFalse();
     }
 
+    @Test
+    void testSourceSchemaIdRoundTrip() {
+        DataEvolutionIndexSourceMeta source = new 
DataEvolutionIndexSourceMeta(42L, 0L);
+        DataEvolutionIndexSourceMeta restored =
+                DataEvolutionIndexSourceMeta.deserialize(source.serialize());
+
+        assertThat(restored.scanSnapshotId()).isEqualTo(42L);
+        assertThat(restored.sourceSchemaId()).isZero();
+        assertThat(source.serialize())
+                .isEqualTo(
+                        ByteBuffer.allocate(24)
+                                .putInt(0x44454958)
+                                .putInt(2)
+                                .putLong(42)
+                                .putLong(0)
+                                .array());
+    }
+
+    @Test
+    void testReadsVersionOneAndWritesVersionTwoWithUnknownSchema() {
+        byte[] legacy = 
ByteBuffer.allocate(16).putInt(0x44454958).putInt(1).putLong(42L).array();
+        DataEvolutionIndexSourceMeta source = 
DataEvolutionIndexSourceMeta.deserialize(legacy);
+
+        assertThat(source.scanSnapshotId()).isEqualTo(42L);
+        assertThat(source.sourceSchemaId()).isEqualTo(-1L);
+        byte[] upgraded =
+                ByteBuffer.allocate(24)
+                        .putInt(0x44454958)
+                        .putInt(2)
+                        .putLong(42L)
+                        .putLong(-1L)
+                        .array();
+        assertThat(source.serialize()).isEqualTo(upgraded);
+        assertThat(new 
DataEvolutionIndexSourceMeta(42L).serialize()).isEqualTo(upgraded);
+    }
+
     @Test
     void testRejectsInvalidSnapshotId() {
         assertThatThrownBy(() -> new DataEvolutionIndexSourceMeta(0L))
                 .hasMessageContaining("snapshot id must be positive");
     }
 
+    @Test
+    void testRejectsInvalidSourceSchemaId() {
+        assertThatThrownBy(() -> new DataEvolutionIndexSourceMeta(1L, -2L))
+                .hasMessageContaining("Source schema id must be -1 or 
non-negative");
+    }
+
     @Test
     void testRejectsWrongMagicAndVersion() throws Exception {
         DataOutputSerializer wrongMagic = new DataOutputSerializer(16);
@@ -62,7 +107,7 @@ class DataEvolutionIndexSourceMetaTest {
                 .hasMessageContaining("Not data-evolution index source 
metadata");
 
         byte[] wrongVersion = new DataEvolutionIndexSourceMeta(1L).serialize();
-        wrongVersion[7] = 2;
+        wrongVersion[7] = 3;
         assertThatThrownBy(() -> 
DataEvolutionIndexSourceMeta.deserialize(wrongVersion))
                 .hasMessageContaining("Unsupported data-evolution index source 
version");
     }
diff --git 
a/paimon-core/src/test/java/org/apache/paimon/table/BtreeGlobalIndexTableTest.java
 
b/paimon-core/src/test/java/org/apache/paimon/table/BtreeGlobalIndexTableTest.java
index 4a2082cefc..238ab154f9 100644
--- 
a/paimon-core/src/test/java/org/apache/paimon/table/BtreeGlobalIndexTableTest.java
+++ 
b/paimon-core/src/test/java/org/apache/paimon/table/BtreeGlobalIndexTableTest.java
@@ -22,17 +22,23 @@ import org.apache.paimon.CoreOptions;
 import org.apache.paimon.Snapshot;
 import org.apache.paimon.data.BinaryString;
 import org.apache.paimon.data.GenericRow;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.fs.local.LocalFileIO;
 import org.apache.paimon.globalindex.DataEvolutionBatchScan;
 import org.apache.paimon.globalindex.DataEvolutionGlobalIndexCoverage;
 import org.apache.paimon.globalindex.DataEvolutionGlobalIndexScanner;
+import org.apache.paimon.globalindex.DataEvolutionIndexSchema;
 import org.apache.paimon.globalindex.GlobalIndexResult;
 import org.apache.paimon.globalindex.IndexedSplit;
 import org.apache.paimon.globalindex.ScanResult;
 import org.apache.paimon.globalindex.btree.BTreeIndexOptions;
 import org.apache.paimon.globalindex.sorted.SortedGlobalIndexScanner;
 import org.apache.paimon.globalindex.sorted.SortedGlobalIndexTestUtils;
+import org.apache.paimon.index.DataEvolutionIndexSourceMeta;
 import org.apache.paimon.index.GlobalIndexMeta;
 import org.apache.paimon.index.IndexFileMeta;
+import org.apache.paimon.io.CompactIncrement;
+import org.apache.paimon.io.DataIncrement;
 import org.apache.paimon.manifest.IndexManifestEntry;
 import org.apache.paimon.partition.PartitionPredicate;
 import org.apache.paimon.predicate.FieldRef;
@@ -45,6 +51,7 @@ import org.apache.paimon.table.sink.BatchTableCommit;
 import org.apache.paimon.table.sink.BatchTableWrite;
 import org.apache.paimon.table.sink.BatchWriteBuilder;
 import org.apache.paimon.table.sink.CommitMessage;
+import org.apache.paimon.table.sink.CommitMessageImpl;
 import org.apache.paimon.table.source.DataSplit;
 import org.apache.paimon.table.source.ReadBuilder;
 import org.apache.paimon.table.source.Split;
@@ -63,6 +70,8 @@ import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.ValueSource;
 
 import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
 import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -70,6 +79,7 @@ import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
 import java.util.stream.Collectors;
 
 import static org.apache.paimon.predicate.SortValue.NullOrdering.NULLS_LAST;
@@ -820,6 +830,163 @@ public class BtreeGlobalIndexTableTest extends 
DataEvolutionTestBase {
         assertThat(result).containsExactly("a200", "a56789");
     }
 
+    @Test
+    public void testRebuildAcrossSchemaChangeWithMultipleGlobalIndexTypes() 
throws Exception {
+        write(8);
+        createIndex("f0");
+        createIndex("f0", null, "bitmap");
+        createIndex("f1", null, "bitmap");
+        FileStoreTable original = (FileStoreTable) 
catalog.getTable(identifier());
+        long originalSnapshotId = original.latestSnapshot().get().id();
+
+        catalog.alterTable(
+                identifier(), SchemaChange.updateColumnType("f0", 
DataTypes.BIGINT()), false);
+        FileStoreTable table = (FileStoreTable) catalog.getTable(identifier());
+        Predicate idFilter = new PredicateBuilder(table.rowType()).equal(0, 
7L);
+        assertThat(
+                        DataEvolutionGlobalIndexScanner.create(
+                                table, PartitionPredicate.ALWAYS_TRUE, 
idFilter))
+                .isEmpty();
+        assertThat(
+                        globalIndexScan(
+                                table,
+                                new PredicateBuilder(table.rowType())
+                                        .equal(1, 
BinaryString.fromString("a7"))))
+                .containsExactly(7L);
+
+        for (boolean queryInReader : new boolean[] {false, true}) {
+            FileStoreTable view =
+                    table.copy(
+                            Collections.singletonMap(
+                                    
CoreOptions.GLOBAL_INDEX_QUERY_IN_READER_ENABLED.key(),
+                                    Boolean.toString(queryInReader)));
+            assertThat(readF1(view, idFilter)).containsExactly("a7");
+        }
+        TopN topN = new TopN(new FieldRef(0, "f0", DataTypes.BIGINT()), 
DESCENDING, NULLS_LAST, 1);
+        assertThat(
+                        DataEvolutionGlobalIndexScanner.createForTopN(
+                                table, PartitionPredicate.ALWAYS_TRUE, topN))
+                .isEmpty();
+        FileStoreTable historical =
+                table.copy(
+                        Collections.singletonMap(
+                                CoreOptions.SCAN_SNAPSHOT_ID.key(),
+                                Long.toString(originalSnapshotId)));
+        assertThat(
+                        globalIndexScan(
+                                historical, new 
PredicateBuilder(historical.rowType()).equal(0, 7)))
+                .containsExactly(7L);
+
+        createIndexIncremental("f0", "btree");
+        createIndexIncremental("f0", "bitmap");
+        FileStoreTable rebuilt = (FileStoreTable) 
catalog.getTable(identifier());
+        assertThat(globalIndexScan(rebuilt, idFilter)).containsExactly(7L);
+        assertThat(rebuilt.store().newIndexFileHandler().scanEntries())
+                .hasSize(3)
+                .allSatisfy(
+                        entry -> {
+                            IndexFileMeta file = entry.indexFile();
+                            DataEvolutionIndexSourceMeta source =
+                                    
DataEvolutionIndexSourceMeta.fromIndexFile(file);
+                            if (file.globalIndexMeta().indexFieldId()
+                                    == rebuilt.rowType().getField("f0").id()) {
+                                assertThat(source.sourceSchemaId())
+                                        .isEqualTo(rebuilt.schema().id());
+                                if ("btree".equals(file.indexType())) {
+                                    // This data snapshot still records the 
pre-ALTER schema.
+                                    assertThat(source.scanSnapshotId())
+                                            .isEqualTo(originalSnapshotId);
+                                }
+                            } else {
+                                assertThat(source.sourceSchemaId())
+                                        .isEqualTo(original.schema().id());
+                            }
+                        });
+    }
+
+    @Test
+    public void testIndexScanReadsHistoricalSchemaOnce() throws Exception {
+        write(1);
+        createIndex("f0");
+        FileStoreTable original = (FileStoreTable) 
catalog.getTable(identifier());
+        String historicalSchemaName = "schema-" + original.schema().id();
+        catalog.alterTable(
+                identifier(), SchemaChange.updateColumnComment("f0", "New 
comment"), false);
+
+        AtomicInteger historicalSchemaReads = new AtomicInteger();
+        LocalFileIO fileIO =
+                new LocalFileIO() {
+                    @Override
+                    public String readFileUtf8(Path path) throws IOException {
+                        if (historicalSchemaName.equals(path.getName())) {
+                            historicalSchemaReads.incrementAndGet();
+                        }
+                        return super.readFileUtf8(path);
+                    }
+                };
+        FileStoreTable evolved = FileStoreTableFactory.create(fileIO, 
original.location());
+        Predicate predicate = new PredicateBuilder(evolved.rowType()).equal(0, 
0);
+        try (DataEvolutionGlobalIndexScanner scanner =
+                DataEvolutionGlobalIndexScanner.create(evolved, null, 
predicate).get()) {
+            assertThat(scanner.scan(predicate))
+                    .hasValueSatisfying(
+                            result -> 
assertThat(result.results().contains(0L)).isTrue());
+        }
+        assertThat(historicalSchemaReads.get()).isEqualTo(1);
+    }
+
+    @Test
+    public void testIndexSchemaCompatibilityUsesRecordedSchemaAndField() 
throws Exception {
+        write(1);
+        FileStoreTable original = (FileStoreTable) 
catalog.getTable(identifier());
+        long snapshotId = original.latestSnapshot().get().id();
+        catalog.alterTable(
+                identifier(), SchemaChange.updateColumnType("f0", 
DataTypes.BIGINT()), false);
+        FileStoreTable evolved = (FileStoreTable) 
catalog.getTable(identifier());
+        int changedField = evolved.rowType().getField("f0").id();
+        int unchangedField = evolved.rowType().getField("f1").id();
+        DataEvolutionIndexSchema schema = new 
DataEvolutionIndexSchema(evolved);
+        byte[] oldSource =
+                new DataEvolutionIndexSourceMeta(snapshotId, 
original.schema().id()).serialize();
+        byte[] newSource =
+                new DataEvolutionIndexSourceMeta(snapshotId, 
evolved.schema().id()).serialize();
+
+        assertThat(schema.isCompatible(indexFileWithSource("btree", 
changedField, oldSource)))
+                .isFalse();
+        assertThat(schema.isCompatible(indexFileWithSource("btree", 
unchangedField, oldSource)))
+                .isTrue();
+        assertThat(schema.isCompatible(indexFileWithSource("btree", 
changedField, newSource)))
+                .isTrue();
+        assertThat(schema.isCompatible(indexFileWithSource("btree", 
changedField, oldSource)))
+                .isFalse();
+        for (String indexType : Arrays.asList("full-text", "ivf-pq")) {
+            assertThat(schema.isCompatible(indexFileWithSource(indexType, 
changedField, oldSource)))
+                    .as("index type %s", indexType)
+                    .isTrue();
+        }
+
+        byte[] legacy =
+                
ByteBuffer.allocate(16).putInt(0x44454958).putInt(1).putLong(snapshotId).array();
+        byte[] unknown = new 
DataEvolutionIndexSourceMeta(snapshotId).serialize();
+        for (byte[] source : Arrays.asList(null, legacy, unknown)) {
+            assertThat(schema.isCompatible(indexFileWithSource("btree", 
changedField, source)))
+                    .isTrue();
+            assertThat(schema.isCompatible(indexFileWithSource("btree", 
Integer.MAX_VALUE, source)))
+                    .isFalse();
+        }
+    }
+
+    private static IndexFileMeta indexFileWithSource(
+            String indexType, int fieldId, byte[] sourceMeta) {
+        return new IndexFileMeta(
+                indexType,
+                "index",
+                1,
+                1,
+                new GlobalIndexMeta(0, 0, fieldId, null, null, sourceMeta),
+                null);
+    }
+
     @Test
     public void testBTreeGlobalIndexOnAddedColumnContainsOldRowsAsNull() 
throws Exception {
         long oldRowCount = 10L;
@@ -894,9 +1061,13 @@ public class BtreeGlobalIndexTableTest extends 
DataEvolutionTestBase {
     }
 
     private void createIndexIncremental(String fieldName) throws Exception {
+        createIndexIncremental(fieldName, "btree");
+    }
+
+    private void createIndexIncremental(String fieldName, String indexType) 
throws Exception {
         FileStoreTable table = (FileStoreTable) catalog.getTable(identifier());
         SortedGlobalIndexScanner builder =
-                new SortedGlobalIndexScanner(table, "btree")
+                new SortedGlobalIndexScanner(table, indexType)
                         .withIndexFields(Collections.singletonList(fieldName));
         ScanResult<DataSplit> scanResult =
                 builder.incrementalScan()
@@ -908,7 +1079,17 @@ public class BtreeGlobalIndexTableTest extends 
DataEvolutionTestBase {
         for (DataSplit dataSplit : scanResult.entries()) {
             commitMessages.addAll(
                     SortedGlobalIndexTestUtils.buildIndex(
-                            table, "btree", fieldName, dataSplit, 
scanResult.scanSnapshotId()));
+                            table, indexType, fieldName, dataSplit, 
scanResult.scanSnapshotId()));
+        }
+        for (IndexManifestEntry entry : scanResult.deletedIndexEntries()) {
+            commitMessages.add(
+                    new CommitMessageImpl(
+                            entry.partition(),
+                            entry.bucket(),
+                            null,
+                            DataIncrement.deleteIndexIncrement(
+                                    
Collections.singletonList(entry.indexFile())),
+                            CompactIncrement.emptyIncrement()));
         }
         try (BatchTableCommit commit = 
table.newBatchWriteBuilder().newCommit()) {
             commit.commit(commitMessages);
@@ -920,9 +1101,14 @@ public class BtreeGlobalIndexTableTest extends 
DataEvolutionTestBase {
     }
 
     private void createIndex(String fieldName, List<Range> rowRanges) throws 
Exception {
+        createIndex(fieldName, rowRanges, "btree");
+    }
+
+    private void createIndex(String fieldName, List<Range> rowRanges, String 
indexType)
+            throws Exception {
         FileStoreTable table = (FileStoreTable) catalog.getTable(identifier());
         SortedGlobalIndexScanner builder =
-                new SortedGlobalIndexScanner(table, "btree")
+                new SortedGlobalIndexScanner(table, indexType)
                         .withIndexFields(Collections.singletonList(fieldName));
         ScanResult<DataSplit> scanResult =
                 builder.scan()
@@ -934,7 +1120,7 @@ public class BtreeGlobalIndexTableTest extends 
DataEvolutionTestBase {
         for (DataSplit dataSplit : indexSplits(table, rowRanges, 
scanResult.entries())) {
             commitMessages.addAll(
                     SortedGlobalIndexTestUtils.buildIndex(
-                            table, "btree", fieldName, dataSplit, 
scanResult.scanSnapshotId()));
+                            table, indexType, fieldName, dataSplit, 
scanResult.scanSnapshotId()));
         }
         try (BatchTableCommit commit = 
table.newBatchWriteBuilder().newCommit()) {
             commit.commit(commitMessages);
diff --git 
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/globalindex/GenericIndexTopoBuilder.java
 
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/globalindex/GenericIndexTopoBuilder.java
index 352bc76942..30a63b6284 100644
--- 
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/globalindex/GenericIndexTopoBuilder.java
+++ 
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/globalindex/GenericIndexTopoBuilder.java
@@ -229,7 +229,8 @@ public class GenericIndexTopoBuilder {
 
         Options mergedOptions = new Options(table.options(), userOptions);
         byte[] sourceMeta =
-                new 
DataEvolutionIndexSourceMeta(scanResult.scanSnapshotId()).serialize();
+                new DataEvolutionIndexSourceMeta(scanResult.scanSnapshotId(), 
table.schema().id())
+                        .serialize();
 
         long rowsPerShard = 
mergedOptions.get(CoreOptions.GLOBAL_INDEX_ROW_COUNT_PER_SHARD);
         checkArgument(
diff --git a/paimon-python/pypaimon/index/data_evolution_index_source_meta.py 
b/paimon-python/pypaimon/index/data_evolution_index_source_meta.py
index 5bdd7d77f0..fc6713303c 100644
--- a/paimon-python/pypaimon/index/data_evolution_index_source_meta.py
+++ b/paimon-python/pypaimon/index/data_evolution_index_source_meta.py
@@ -18,21 +18,31 @@
 
 import struct
 from dataclasses import dataclass
+from typing import Optional
 
 
 @dataclass(frozen=True)
 class DataEvolutionIndexSourceMeta:
     scan_snapshot_id: int
+    source_schema_id: Optional[int] = None
 
     MAGIC = 0x44454958
     VERSION = 1
+    VERSION_WITH_SCHEMA = 2
+    _SNAPSHOT = struct.Struct('>iiq')
+    _SNAPSHOT_AND_SCHEMA = struct.Struct('>iiqq')
 
     def __post_init__(self):
         if self.scan_snapshot_id <= 0:
             raise ValueError('Scan snapshot id must be positive.')
+        if self.source_schema_id is not None and self.source_schema_id < -1:
+            raise ValueError('Source schema id must be -1 or non-negative.')
 
     def serialize(self):
-        return struct.pack('>iiq', self.MAGIC, self.VERSION, 
self.scan_snapshot_id)
+        if self.source_schema_id is None:
+            return self._SNAPSHOT.pack(self.MAGIC, self.VERSION, 
self.scan_snapshot_id)
+        return self._SNAPSHOT_AND_SCHEMA.pack(
+            self.MAGIC, self.VERSION_WITH_SCHEMA, self.scan_snapshot_id, 
self.source_schema_id)
 
     @classmethod
     def is_data_evolution_meta(cls, data):
@@ -40,9 +50,15 @@ class DataEvolutionIndexSourceMeta:
 
     @classmethod
     def deserialize(cls, data):
-        if len(data) != 16 or not cls.is_data_evolution_meta(data):
+        if not cls.is_data_evolution_meta(data) or len(data) < 8:
             raise ValueError('Invalid data-evolution index source metadata.')
-        _, version, snapshot_id = struct.unpack('>iiq', data)
-        if version != cls.VERSION:
+        _, version = struct.unpack_from('>ii', data)
+        if version == cls.VERSION:
+            codec = cls._SNAPSHOT
+        elif version == cls.VERSION_WITH_SCHEMA:
+            codec = cls._SNAPSHOT_AND_SCHEMA
+        else:
             raise ValueError('Unsupported data-evolution index source version: 
{}.'.format(version))
-        return cls(snapshot_id)
+        if len(data) != codec.size:
+            raise ValueError('Invalid data-evolution index source metadata.')
+        return cls(*codec.unpack(data)[2:])
diff --git a/paimon-python/pypaimon/tests/native_sorted_index_build_test.py 
b/paimon-python/pypaimon/tests/native_sorted_index_build_test.py
index 13fce8767c..6f2ef18dee 100644
--- a/paimon-python/pypaimon/tests/native_sorted_index_build_test.py
+++ b/paimon-python/pypaimon/tests/native_sorted_index_build_test.py
@@ -31,9 +31,12 @@ from pypaimon.catalog.catalog_exception import 
TableNoPermissionException
 from pypaimon.globalindex.create_global_index import GlobalIndexBuilder
 from pypaimon.execution.python.globalindex.create_global_index import 
PythonGlobalIndexBuilder
 from pypaimon.execution.python.globalindex.data_evolution_global_index_scanner 
import DataEvolutionGlobalIndexScanner
+from pypaimon.globalindex.indexed_split import IndexedSplit
+from pypaimon.index.data_evolution_index_source_meta import 
DataEvolutionIndexSourceMeta
 from pypaimon.index.index_file_handler import IndexFileHandler
 from pypaimon.execution.native.table import (_native_table)
 from pypaimon.execution.native.read.builder import (_predicate_to_native)
+from pypaimon.execution.native.read.plan import native_plan
 from pypaimon.execution.native.runtime import (native_runtime_available)
 from pypaimon.snapshot.table_snapshot import TableSnapshot
 from pypaimon.schema.schema_change import SchemaChange
@@ -400,6 +403,29 @@ def 
test_both_index_types_can_share_one_explicit_commit(rest_catalog):
     assert _ids(table, 
table.new_read_builder().new_predicate_builder().equal('name', 'a')) == [1, 5]
 
 
[email protected]('kind', ['btree', 'bitmap'])
[email protected]('source_schema_id', [0, -1])
+def test_native_query_reads_index_with_version_two_source_meta(rest_catalog, 
kind, source_schema_id):
+    catalog, _ = rest_catalog
+    table = _create(catalog)
+    _append(table, ROWS)
+    messages = _build(table, kind)
+    for file in _message_files(messages):
+        meta = file.global_index_meta
+        source = DataEvolutionIndexSourceMeta.deserialize(meta.source_meta)
+        meta.source_meta = DataEvolutionIndexSourceMeta(
+            source.scan_snapshot_id, source_schema_id).serialize()
+    _commit(table, messages)
+
+    files = _files(table)
+    assert files
+    assert all(file.global_index_meta.source_meta == struct.pack('>iiqq', 
0x44454958, 2, 1, source_schema_id)
+               for file in files)
+    predicate = table.new_read_builder().new_predicate_builder().equal('name', 
'a')
+    assert any(isinstance(split, IndexedSplit) for split in native_plan(table, 
predicate=predicate).splits())
+    assert _ids(table, predicate) == [1, 5]
+
+
 @pytest.mark.parametrize('kind', ['btree', 'bitmap'])
 def test_commit_response_failure_keeps_published_index_files(rest_catalog, 
kind):
     catalog, _ = rest_catalog
diff --git 
a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/globalindex/CentroidGlobalIndexTopoBuilder.java
 
b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/globalindex/CentroidGlobalIndexTopoBuilder.java
index d672e44c4b..9d5ca48535 100644
--- 
a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/globalindex/CentroidGlobalIndexTopoBuilder.java
+++ 
b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/globalindex/CentroidGlobalIndexTopoBuilder.java
@@ -764,7 +764,7 @@ public class CentroidGlobalIndexTopoBuilder implements 
GlobalIndexTopologyBuilde
         }
 
         byte[] sourceMeta() {
-            return new DataEvolutionIndexSourceMeta(snapshotId).serialize();
+            return new DataEvolutionIndexSourceMeta(snapshotId, 
schemaId).serialize();
         }
 
         CommitMessageImpl message(List<IndexFileMeta> files) {
diff --git 
a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/globalindex/DefaultGlobalIndexTopoBuilder.java
 
b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/globalindex/DefaultGlobalIndexTopoBuilder.java
index 7e5a401df3..dfc22a23d4 100644
--- 
a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/globalindex/DefaultGlobalIndexTopoBuilder.java
+++ 
b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/globalindex/DefaultGlobalIndexTopoBuilder.java
@@ -56,6 +56,7 @@ import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 import java.util.function.BiFunction;
 import java.util.stream.Collectors;
 
@@ -115,10 +116,13 @@ public class DefaultGlobalIndexTopoBuilder implements 
GlobalIndexTopologyBuilder
         List<IndexManifestEntry> currentIndexes =
                 GlobalIndexBuilderUtils.currentIndexEntries(
                         table, snapshot, indexType, indexFields, 
partitionPredicate);
+        Set<IndexManifestEntry> indexesToRefresh =
+                GlobalIndexBuilderUtils.indexesWithIncompatibleSchema(table, 
currentIndexes);
         List<Range> rowRangesToBuild =
-                new ArrayList<>(
-                        GlobalIndexBuilderUtils.unindexedRowRanges(snapshot, 
currentIndexes));
-        byte[] sourceMeta = new 
DataEvolutionIndexSourceMeta(snapshot.id()).serialize();
+                GlobalIndexBuilderUtils.rowRangesToBuild(
+                        snapshot, currentIndexes, indexesToRefresh);
+        byte[] sourceMeta =
+                new DataEvolutionIndexSourceMeta(snapshot.id(), 
table.schema().id()).serialize();
         boolean detectDataFileChange =
                 new Options(table.options(), 
options.toMap()).get(GLOBAL_INDEX_COLUMN_UPDATE_ACTION)
                         == IGNORE;
@@ -132,16 +136,14 @@ public class DefaultGlobalIndexTopoBuilder implements 
GlobalIndexTopologyBuilder
                         .withPartitionFilter(partitionPredicate)
                         .plan()
                         .files();
-        List<IndexManifestEntry> indexesToRefresh = Collections.emptyList();
         if (detectDataFileChange) {
-            indexesToRefresh =
+            indexesToRefresh.addAll(
                     
DataEvolutionGlobalIndexRefreshPlanner.findIndexesToRefresh(
-                            table.schemaManager(), entries, currentIndexes, 
indexFields);
-            for (IndexManifestEntry index : indexesToRefresh) {
-                
rowRangesToBuild.add(index.indexFile().globalIndexMeta().rowRange());
-            }
+                            table.schemaManager(), entries, currentIndexes, 
indexFields));
+            rowRangesToBuild =
+                    GlobalIndexBuilderUtils.rowRangesToBuild(
+                            snapshot, currentIndexes, indexesToRefresh);
         }
-        rowRangesToBuild = Range.sortAndMergeOverlap(rowRangesToBuild, true);
         if (rowRangesToBuild.isEmpty()) {
             return Collections.emptyList();
         }

Reply via email to