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 413d7cc8df [core] Fix legacy BTree reads with empty keys and nulls 
(#11126)
413d7cc8df is described below

commit 413d7cc8dfec8cbad437d9e52cc041cb0f9efefb
Author: YueZhang <[email protected]>
AuthorDate: Fri Nov 13 18:54:18 2026 +0800

    [core] Fix legacy BTree reads with empty keys and nulls (#11126)
---
 .../paimon/globalindex/SortedIndexFileMeta.java    |  35 +++-
 .../paimon/globalindex/btree/BTreeIndexReader.java |  35 +++-
 .../globalindex/SortedIndexFileMetaTest.java       |   8 +-
 .../globalindex/btree/BTreeIndexReaderTest.java    |  55 +++++
 .../globalindex/BTreeTopNIndexFileSelector.java    |  12 +-
 .../table/LegacyBTreeGlobalIndexTableTest.java     | 224 +++++++++++++++++++++
 6 files changed, 346 insertions(+), 23 deletions(-)

diff --git 
a/paimon-common/src/main/java/org/apache/paimon/globalindex/SortedIndexFileMeta.java
 
b/paimon-common/src/main/java/org/apache/paimon/globalindex/SortedIndexFileMeta.java
index cd40dd7a4f..c3052aaba0 100644
--- 
a/paimon-common/src/main/java/org/apache/paimon/globalindex/SortedIndexFileMeta.java
+++ 
b/paimon-common/src/main/java/org/apache/paimon/globalindex/SortedIndexFileMeta.java
@@ -34,9 +34,19 @@ public class SortedIndexFileMeta {
     @Nullable private final byte[] firstKey;
     @Nullable private final byte[] lastKey;
     private final boolean hasNulls;
+    private final boolean ambiguousNullBounds;
 
     public SortedIndexFileMeta(
             @Nullable byte[] firstKey, @Nullable byte[] lastKey, boolean 
hasNulls) {
+        this(firstKey, lastKey, hasNulls, false);
+    }
+
+    private SortedIndexFileMeta(
+            @Nullable byte[] firstKey,
+            @Nullable byte[] lastKey,
+            boolean hasNulls,
+            boolean ambiguousNullBounds) {
+        this.ambiguousNullBounds = ambiguousNullBounds;
         this.firstKey = firstKey;
         this.lastKey = lastKey;
         this.hasNulls = hasNulls;
@@ -67,13 +77,18 @@ public class SortedIndexFileMeta {
     }
 
     public boolean onlyNulls() {
-        return firstKey() == null && lastKey() == null;
+        return !ambiguousNullBounds && firstKey() == null && lastKey() == null;
+    }
+
+    /** Legacy zero-length bounds cannot distinguish all-null files from empty 
keys plus nulls. */
+    public boolean hasAmbiguousNullBounds() {
+        return ambiguousNullBounds;
     }
 
     private int memorySize() {
         return (firstKey == null ? 0 : firstKey.length)
                 + (lastKey == null ? 0 : lastKey.length)
-                + 11;
+                + (ambiguousNullBounds ? 9 : 11);
     }
 
     public byte[] serialize() {
@@ -94,8 +109,11 @@ public class SortedIndexFileMeta {
             nullKeyFlags |= LAST_KEY_IS_NULL;
         }
         sliceOutput.writeByte(hasNulls ? 1 : 0);
-        sliceOutput.writeByte(FORMAT_VERSION_WITH_NULL_FLAGS);
-        sliceOutput.writeByte(nullKeyFlags);
+        // Preserve unknown legacy bounds when metadata is serialized again.
+        if (!ambiguousNullBounds) {
+            sliceOutput.writeByte(FORMAT_VERSION_WITH_NULL_FLAGS);
+            sliceOutput.writeByte(nullKeyFlags);
+        }
         return sliceOutput.toSlice().getHeapMemory();
     }
 
@@ -115,12 +133,9 @@ public class SortedIndexFileMeta {
                 lastKey = (nullKeyFlags & LAST_KEY_IS_NULL) != 0 ? null : 
lastKey;
             }
         } else if (firstKeyLength == 0 && lastKeyLength == 0 && hasNulls) {
-            // Compatibility with old metadata which used zero length to 
represent null keys.
-            // A legacy all-null index file can be identified by both key 
lengths being zero with
-            // null bitmap. When only one length is zero, the zero-length key 
is a valid serialized
-            // key, for example an empty string.
-            firstKey = null;
-            lastKey = null;
+            // These bytes also represent empty non-null keys together with 
nulls. Readers must
+            // inspect the index file instead of treating this metadata as 
proof of all-null data.
+            return new SortedIndexFileMeta(null, null, true, true);
         }
         return new SortedIndexFileMeta(firstKey, lastKey, hasNulls);
     }
diff --git 
a/paimon-common/src/main/java/org/apache/paimon/globalindex/btree/BTreeIndexReader.java
 
b/paimon-common/src/main/java/org/apache/paimon/globalindex/btree/BTreeIndexReader.java
index ce0ed043de..b8cb7a3ead 100644
--- 
a/paimon-common/src/main/java/org/apache/paimon/globalindex/btree/BTreeIndexReader.java
+++ 
b/paimon-common/src/main/java/org/apache/paimon/globalindex/btree/BTreeIndexReader.java
@@ -151,15 +151,8 @@ public class BTreeIndexReader implements Closeable {
         this.rowIdFilter = rowIdFilter;
         SortedIndexFileMeta indexMeta =
                 SortedIndexFileMeta.deserialize(globalIndexIOMeta.metadata());
-        if (indexMeta.getFirstKey() != null) {
-            this.minKey = 
keySerializer.deserialize(MemorySlice.wrap(indexMeta.getFirstKey()));
-            this.maxKey = 
keySerializer.deserialize(MemorySlice.wrap(indexMeta.getLastKey()));
-        } else {
-            // this is possible if this btree index file only stores nulls.
-            this.minKey = null;
-            this.maxKey = null;
-        }
         this.input = fileReader.getInputStream(globalIndexIOMeta);
+        SstFileReader openedReader = null;
         try {
             // prepare file footer
             long fileSize = globalIndexIOMeta.fileSize();
@@ -185,8 +178,27 @@ public class BTreeIndexReader implements Closeable {
                             blockCache,
                             footer.getIndexBlockHandle(),
                             bloomFilter);
-        } catch (RuntimeException e) {
-            // nothing else holds a reference to input yet, so this is the 
only chance to release it
+            openedReader = this.reader;
+            if (indexMeta.hasAmbiguousNullBounds()) {
+                // Both legacy bounds have zero length. If the SST has a 
non-null key, it is the
+                // empty key and is both bounds; otherwise this really is an 
all-null file.
+                BlockIterator firstBlock = reader.createIterator().readBatch();
+                this.minKey =
+                        firstBlock == null
+                                ? null
+                                : 
keySerializer.deserialize(firstBlock.next().getKey());
+                this.maxKey = minKey;
+            } else if (indexMeta.getFirstKey() != null) {
+                this.minKey = 
keySerializer.deserialize(MemorySlice.wrap(indexMeta.getFirstKey()));
+                this.maxKey = 
keySerializer.deserialize(MemorySlice.wrap(indexMeta.getLastKey()));
+            } else {
+                // this is possible if this btree index file only stores nulls.
+                this.minKey = null;
+                this.maxKey = null;
+            }
+        } catch (IOException | RuntimeException e) {
+            // Bound recovery can fail after the SST reader has been opened.
+            IOUtils.closeQuietly(openedReader);
             IOUtils.closeQuietly(input);
             throw e;
         }
@@ -549,6 +561,9 @@ public class BTreeIndexReader implements Closeable {
      */
     private RoaringNavigableMap64 rangeQuery(
             Object from, Object to, boolean fromInclusive, boolean 
toInclusive) throws IOException {
+        if (minKey == null) {
+            return new RoaringNavigableMap64();
+        }
         SstFileReader.SstFileIterator fileIter = reader.createIterator();
         fileIter.seekTo(keySerializer.serialize(from));
 
diff --git 
a/paimon-common/src/test/java/org/apache/paimon/globalindex/SortedIndexFileMetaTest.java
 
b/paimon-common/src/test/java/org/apache/paimon/globalindex/SortedIndexFileMetaTest.java
index 960b98bcf4..9973ee4f36 100644
--- 
a/paimon-common/src/test/java/org/apache/paimon/globalindex/SortedIndexFileMetaTest.java
+++ 
b/paimon-common/src/test/java/org/apache/paimon/globalindex/SortedIndexFileMetaTest.java
@@ -92,14 +92,18 @@ class SortedIndexFileMetaTest {
     }
 
     @Test
-    void testLegacyOnlyNulls() {
+    void testLegacyAmbiguousNullBounds() {
         SortedIndexFileMeta meta =
                 SortedIndexFileMeta.deserialize(legacyMetaBytes(new byte[0], 
new byte[0], true));
 
         assertThat(meta.getFirstKey()).isNull();
         assertThat(meta.getLastKey()).isNull();
         assertThat(meta.hasNulls()).isTrue();
-        assertThat(meta.onlyNulls()).isTrue();
+        assertThat(meta.onlyNulls()).isFalse();
+        assertThat(meta.hasAmbiguousNullBounds()).isTrue();
+        assertThat(meta.serialize())
+                .containsExactly(legacyMetaBytes(new byte[0], new byte[0], 
true));
+        assertThat(roundTrip(meta).hasAmbiguousNullBounds()).isTrue();
     }
 
     @Test
diff --git 
a/paimon-common/src/test/java/org/apache/paimon/globalindex/btree/BTreeIndexReaderTest.java
 
b/paimon-common/src/test/java/org/apache/paimon/globalindex/btree/BTreeIndexReaderTest.java
index 560b92c609..069c5c24d1 100644
--- 
a/paimon-common/src/test/java/org/apache/paimon/globalindex/btree/BTreeIndexReaderTest.java
+++ 
b/paimon-common/src/test/java/org/apache/paimon/globalindex/btree/BTreeIndexReaderTest.java
@@ -18,16 +18,21 @@
 
 package org.apache.paimon.globalindex.btree;
 
+import org.apache.paimon.data.BinaryString;
 import org.apache.paimon.fs.SeekableInputStream;
 import org.apache.paimon.globalindex.GlobalIndexIOMeta;
 import org.apache.paimon.globalindex.GlobalIndexReader;
 import org.apache.paimon.globalindex.GlobalIndexResult;
 import org.apache.paimon.memory.MemorySlice;
 import org.apache.paimon.memory.MemorySliceOutput;
+import org.apache.paimon.options.Options;
 import org.apache.paimon.predicate.FieldRef;
 import org.apache.paimon.predicate.TopN;
 import 
org.apache.paimon.testutils.junit.parameterized.ParameterizedTestExtension;
+import org.apache.paimon.types.DataField;
+import org.apache.paimon.types.DataTypeFamily;
 import org.apache.paimon.utils.IOUtils;
+import org.apache.paimon.utils.Pair;
 import org.apache.paimon.utils.Range;
 import org.apache.paimon.utils.RoaringNavigableMap64;
 
@@ -64,6 +69,56 @@ public class BTreeIndexReaderTest extends 
AbstractIndexReaderTest {
                 newDirectExecutorService());
     }
 
+    @TestTemplate
+    public void testLegacyNullBounds() throws Exception {
+        boolean stringType = dataType.is(DataTypeFamily.CHARACTER_STRING);
+        for (boolean onlyNulls : new boolean[] {true, false}) {
+            if (!stringType && !onlyNulls) {
+                continue;
+            }
+            Object key = stringType ? BinaryString.EMPTY_UTF8 : 
data.get(0).getKey();
+            Object value = onlyNulls ? null : key;
+            Options options = new Options();
+            options.set(BTreeIndexOptions.BTREE_INDEX_FILE_VERSION, 1);
+            BTreeGlobalIndexer indexer =
+                    new BTreeGlobalIndexer(
+                            Collections.singletonList(new DataField(1, 
"testField", dataType)),
+                            options);
+            GlobalIndexIOMeta written =
+                    writeData(
+                            Arrays.asList(
+                                    Pair.of(value, 0L), Pair.of(null, 1L), 
Pair.of(value, 2L)),
+                            indexer.createWriter(fileWriter));
+            MemorySliceOutput legacyMeta = new MemorySliceOutput(9);
+            legacyMeta.writeInt(0);
+            legacyMeta.writeInt(0);
+            legacyMeta.writeByte(1);
+            GlobalIndexIOMeta legacy =
+                    new GlobalIndexIOMeta(
+                            written.filePath(),
+                            written.fileSize(),
+                            written.rowCount(),
+                            legacyMeta.toSlice().copyBytes());
+            List<Long> expected = onlyNulls ? Collections.emptyList() : 
Arrays.asList(0L, 2L);
+            try (BTreeIndexReader reader =
+                    new BTreeIndexReader(keySerializer, fileReader, legacy, 
CACHE_MANAGER, null)) {
+                assertResult(reader.visitEqual(key).get(), expected);
+                assertResult(reader.visitGreaterOrEqual(key).get(), expected);
+                assertResult(reader.visitLessOrEqual(key).get(), expected);
+                assertResult(reader.visitIsNotNull().get(), expected);
+                assertResult(
+                        reader.visitIsNull().get(),
+                        onlyNulls ? Arrays.asList(0L, 1L, 2L) : 
Collections.singletonList(1L));
+                if (stringType) {
+                    
assertResult(reader.visitStartsWith(BinaryString.EMPTY_UTF8).get(), expected);
+                }
+                TopN topN =
+                        new TopN(new FieldRef(1, "testField", dataType), 
ASCENDING, NULLS_LAST, 1);
+                
assertThat(reader.visitTopN(topN).get().results()).containsExactly(0L);
+            }
+        }
+    }
+
     @TestTemplate
     public void testLocalRowRanges() throws Exception {
         for (int index = dataNum - 100; index < dataNum; index++) {
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/globalindex/BTreeTopNIndexFileSelector.java
 
b/paimon-core/src/main/java/org/apache/paimon/globalindex/BTreeTopNIndexFileSelector.java
index 69b52276c4..ef9b3f6acb 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/globalindex/BTreeTopNIndexFileSelector.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/globalindex/BTreeTopNIndexFileSelector.java
@@ -66,7 +66,13 @@ class BTreeTopNIndexFileSelector {
         List<IndexFileMeta> selected = new ArrayList<>();
         List<RankedIndexFile> rankedFiles = new ArrayList<>();
         for (IndexFileMeta file : files) {
-            rankedFiles.add(selector.rank(file));
+            RankedIndexFile ranked = selector.rank(file);
+            if (ranked == null) {
+                // A legacy file may contain empty keys as well as nulls. 
Without exact bounds,
+                // ranking it could exclude a file containing the actual TopN 
value.
+                return files;
+            }
+            rankedFiles.add(ranked);
         }
 
         rankedFiles.sort(selector::compare);
@@ -84,6 +90,7 @@ class BTreeTopNIndexFileSelector {
         return selected;
     }
 
+    @Nullable
     private RankedIndexFile rank(IndexFileMeta file) {
         GlobalIndexMeta globalIndex =
                 checkNotNull(
@@ -96,6 +103,9 @@ class BTreeTopNIndexFileSelector {
                         "BTree index file '%s' is missing sorted metadata.",
                         file.fileName());
         SortedIndexFileMeta sortedMeta = 
SortedIndexFileMeta.deserialize(indexMeta);
+        if (sortedMeta.hasAmbiguousNullBounds()) {
+            return null;
+        }
         byte[] firstKey = sortedMeta.firstKey();
         byte[] lastKey = sortedMeta.lastKey();
         boolean hasNonNulls = lastKey != null;
diff --git 
a/paimon-core/src/test/java/org/apache/paimon/table/LegacyBTreeGlobalIndexTableTest.java
 
b/paimon-core/src/test/java/org/apache/paimon/table/LegacyBTreeGlobalIndexTableTest.java
new file mode 100644
index 0000000000..9e1db99888
--- /dev/null
+++ 
b/paimon-core/src/test/java/org/apache/paimon/table/LegacyBTreeGlobalIndexTableTest.java
@@ -0,0 +1,224 @@
+/*
+ * 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.table;
+
+import org.apache.paimon.data.BinaryString;
+import org.apache.paimon.data.GenericRow;
+import org.apache.paimon.globalindex.DataEvolutionGlobalIndexScanner;
+import org.apache.paimon.globalindex.ScanResult;
+import org.apache.paimon.globalindex.SortedIndexFileMeta;
+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.GlobalIndexMeta;
+import org.apache.paimon.index.IndexFileMeta;
+import org.apache.paimon.memory.MemorySliceOutput;
+import org.apache.paimon.predicate.FieldRef;
+import org.apache.paimon.predicate.Predicate;
+import org.apache.paimon.predicate.PredicateBuilder;
+import org.apache.paimon.predicate.SortValue;
+import org.apache.paimon.predicate.TopN;
+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.utils.Range;
+
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Compatibility tests for BTree metadata written before explicit null-bound 
flags. */
+class LegacyBTreeGlobalIndexTableTest extends DataEvolutionTestBase {
+
+    @ParameterizedTest
+    @CsvSource({"false,false", "false,true", "true,false", "true,true"})
+    void testPredicates(boolean legacy, boolean onlyNulls) throws Exception {
+        FileStoreTable table = prepare(legacy, onlyNulls);
+        PredicateBuilder builder = new PredicateBuilder(table.rowType());
+        for (Predicate predicate :
+                Arrays.asList(
+                        builder.equal(1, BinaryString.EMPTY_UTF8),
+                        builder.lessThan(1, BinaryString.fromString("a")),
+                        builder.greaterOrEqual(1, BinaryString.EMPTY_UTF8),
+                        builder.startsWith(1, BinaryString.EMPTY_UTF8),
+                        builder.isNotNull(1))) {
+            ReadBuilder read = table.newReadBuilder().withFilter(predicate);
+            List<Integer> actual = new ArrayList<>();
+            read.newRead()
+                    .executeFilter()
+                    .createReader(read.newScan().plan())
+                    .forEachRemaining(row -> actual.add(row.getInt(0)));
+            assertThat(actual)
+                    .as("%s", predicate)
+                    .containsExactlyInAnyOrderElementsOf(
+                            onlyNulls ? Collections.emptyList() : 
Arrays.asList(0, 2));
+        }
+        ReadBuilder read = 
table.newReadBuilder().withFilter(builder.isNull(1));
+        List<Integer> nulls = new ArrayList<>();
+        read.newRead()
+                .executeFilter()
+                .createReader(read.newScan().plan())
+                .forEachRemaining(row -> nulls.add(row.getInt(0)));
+        assertThat(nulls)
+                .containsExactlyInAnyOrderElementsOf(
+                        onlyNulls ? Arrays.asList(0, 1, 2) : 
Collections.singletonList(1));
+    }
+
+    @ParameterizedTest
+    @CsvSource({"false,false", "false,true", "true,false", "true,true"})
+    void testTopNAcrossLegacyAndModernRanges(boolean legacy, boolean 
onlyNulls) throws Exception {
+        FileStoreTable table = prepare(legacy, onlyNulls);
+        writeRows(table, GenericRow.of(3, BinaryString.fromString("a"), null));
+        buildIndex(getTableDefault(), false, true);
+        table = getTableDefault();
+        for (SortValue.SortDirection direction : 
SortValue.SortDirection.values()) {
+            for (SortValue.NullOrdering nullOrdering : 
SortValue.NullOrdering.values()) {
+                TopN topN =
+                        new TopN(
+                                new FieldRef(1, "f1", 
table.rowType().getTypeAt(1)),
+                                direction,
+                                nullOrdering,
+                                1);
+                ReadBuilder read = table.newReadBuilder().withTopN(topN);
+                List<Integer> candidates = new ArrayList<>();
+                read.newRead()
+                        .createReader(read.newScan().plan())
+                        .forEachRemaining(row -> 
candidates.add(row.getInt(0)));
+                if (nullOrdering == SortValue.NullOrdering.NULLS_FIRST) {
+                    assertThat(candidates).anyMatch(id -> onlyNulls ? id < 3 : 
id == 1);
+                } else if (onlyNulls || direction == 
SortValue.SortDirection.DESCENDING) {
+                    assertThat(candidates).contains(3);
+                } else {
+                    assertThat(candidates).anyMatch(id -> id == 0 || id == 2);
+                }
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @CsvSource({"false,false", "false,true", "true,false", "true,true"})
+    void testScalarPrefilter(boolean legacy, boolean onlyNulls) throws 
Exception {
+        FileStoreTable table = prepare(legacy, onlyNulls);
+        List<IndexFileMeta> files =
+                table.store().newIndexFileHandler().scanEntries().stream()
+                        .map(entry -> entry.indexFile())
+                        .collect(Collectors.toList());
+        try (DataEvolutionGlobalIndexScanner scanner =
+                DataEvolutionGlobalIndexScanner.createForScalarFilters(table, 
null, null, files)
+                        .get()) {
+            Predicate filter =
+                    new PredicateBuilder(table.rowType()).equal(1, 
BinaryString.EMPTY_UTF8);
+            assertThat(scanner.scan(filter).get().results().toRangeList())
+                    .containsExactlyElementsOf(
+                            onlyNulls
+                                    ? Collections.emptyList()
+                                    : Arrays.asList(new Range(0, 0), new 
Range(2, 2)));
+        }
+    }
+
+    private FileStoreTable prepare(boolean legacy, boolean onlyNulls) throws 
Exception {
+        createTableDefault();
+        FileStoreTable table = getTableDefault();
+        BinaryString value = onlyNulls ? null : BinaryString.EMPTY_UTF8;
+        writeRows(
+                table,
+                GenericRow.of(0, value, null),
+                GenericRow.of(1, null, null),
+                GenericRow.of(2, value, null));
+        buildIndex(getTableDefault(), legacy, false);
+        return getTableDefault();
+    }
+
+    private void writeRows(FileStoreTable table, GenericRow... rows) throws 
Exception {
+        BatchWriteBuilder builder = table.newBatchWriteBuilder();
+        try (BatchTableWrite write = builder.newWrite();
+                BatchTableCommit commit = builder.newCommit()) {
+            for (GenericRow row : rows) {
+                write.write(row);
+            }
+            commit.commit(write.prepareCommit());
+        }
+    }
+
+    private void buildIndex(FileStoreTable table, boolean legacy, boolean 
incremental)
+            throws Exception {
+        table =
+                table.copy(
+                        Collections.singletonMap(
+                                
BTreeIndexOptions.BTREE_INDEX_FILE_VERSION.key(), "1"));
+        SortedGlobalIndexScanner scanner =
+                new SortedGlobalIndexScanner(table, "btree")
+                        .withIndexFields(Collections.singletonList("f1"));
+        ScanResult<DataSplit> scan =
+                (incremental ? scanner.incrementalScan() : 
scanner.scan()).get();
+        List<CommitMessage> messages = new ArrayList<>();
+        for (DataSplit split : scan.entries()) {
+            messages.addAll(
+                    SortedGlobalIndexTestUtils.buildIndex(
+                            table, "btree", "f1", split, 
scan.scanSnapshotId()));
+        }
+        if (legacy) {
+            for (CommitMessage message : messages) {
+                List<IndexFileMeta> files =
+                        ((CommitMessageImpl) 
message).newFilesIncrement().newIndexFiles();
+                for (int i = 0; i < files.size(); i++) {
+                    IndexFileMeta file = files.get(i);
+                    GlobalIndexMeta global = file.globalIndexMeta();
+                    SortedIndexFileMeta meta = 
SortedIndexFileMeta.deserialize(global.indexMeta());
+                    assertThat(meta.hasNulls()).isTrue();
+                    assertThat(meta.firstKey() == null || 
meta.firstKey().length == 0).isTrue();
+                    assertThat(meta.lastKey() == null || meta.lastKey().length 
== 0).isTrue();
+                    // Legacy BTreeIndexMeta wrote zero lengths for both null 
and empty keys.
+                    MemorySliceOutput out = new MemorySliceOutput(9);
+                    out.writeInt(0);
+                    out.writeInt(0);
+                    out.writeByte(1);
+                    files.set(
+                            i,
+                            new IndexFileMeta(
+                                    file.indexType(),
+                                    file.fileName(),
+                                    file.fileSize(),
+                                    file.rowCount(),
+                                    new GlobalIndexMeta(
+                                            global.rowRangeStart(),
+                                            global.rowRangeEnd(),
+                                            global.indexFieldId(),
+                                            global.extraFieldIds(),
+                                            out.toSlice().copyBytes()),
+                                    file.externalPath()));
+                }
+            }
+        }
+        try (BatchTableCommit commit = 
table.newBatchWriteBuilder().newCommit()) {
+            commit.commit(messages);
+        }
+    }
+}

Reply via email to