From 2b13da27d1747a717a920c0225ea5c58e7e1ac94 Mon Sep 17 00:00:00 2001 From: yangjiabin <706948683@qq.com> Date: Fri, 20 Nov 2026 09:52:15 +0800 Subject: [PATCH 1/8] [core] Preserve Data Evolution dependencies in incremental diff reads --- docs/docs/multimodal-table/data-evolution.mdx | 15 + .../paimon/globalindex/IndexedSplit.java | 4 + .../operation/DataEvolutionFileStoreScan.java | 17 + .../source/snapshot/SnapshotReaderImpl.java | 76 +++- .../paimon/globalindex/IndexedSplitTest.java | 25 ++ .../DataEvolutionIncrementalDiffTest.java | 352 ++++++++++++++++++ .../DataEvolutionIncrementalDiffTest.scala | 52 +++ 7 files changed, 539 insertions(+), 2 deletions(-) create mode 100644 paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java create mode 100644 paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionIncrementalDiffTest.scala diff --git a/docs/docs/multimodal-table/data-evolution.mdx b/docs/docs/multimodal-table/data-evolution.mdx index e9ba024f5ab5..8e9096c9af42 100644 --- a/docs/docs/multimodal-table/data-evolution.mdx +++ b/docs/docs/multimodal-table/data-evolution.mdx @@ -486,6 +486,21 @@ when the commit contains existing-row BLOB or VECTOR staged files. It does not suppress logical concurrent-update conflicts. If recovery is unavailable, re-plan the operation against the latest snapshot. +## Batch Incremental DIFF Reads + +With `incremental-between-scan-mode=diff`, Data Evolution compares the live file +identities in the two snapshots, including their RowID metadata. It returns the +visible end-snapshot rows in the RowID ranges of file entries absent from the +starting snapshot. Files shared with the starting snapshot +still supply unchanged columns and the end-snapshot deletion-vector anchor. +Projecting only unchanged columns does not remove the corresponding updates. + +This is a file incremental read, not a row-level changelog. A range can contain +rows whose values did not change, and compaction can cause rows to be returned +again. A deletion without newly added data files produces no rows; deleted rows +are excluded when a new column file covers their range. Tag-to-tag DIFF reads +use the same semantics. DIFF planning still materializes snapshot metadata. + ## Compaction and Row-ID Lifetime Repeated updates add column files. Ordinary compaction consolidates them while diff --git a/paimon-core/src/main/java/org/apache/paimon/globalindex/IndexedSplit.java b/paimon-core/src/main/java/org/apache/paimon/globalindex/IndexedSplit.java index 49802d5d4c0c..05f367e3bd4c 100644 --- a/paimon-core/src/main/java/org/apache/paimon/globalindex/IndexedSplit.java +++ b/paimon-core/src/main/java/org/apache/paimon/globalindex/IndexedSplit.java @@ -80,6 +80,10 @@ public long rowCount() { @Override public OptionalLong mergedRowCount() { + if (split.deletionFiles().isPresent() + && split.deletionFiles().get().stream().anyMatch(Objects::nonNull)) { + return OptionalLong.empty(); + } return OptionalLong.of(rowCount()); } diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/DataEvolutionFileStoreScan.java b/paimon-core/src/main/java/org/apache/paimon/operation/DataEvolutionFileStoreScan.java index 8bc55a0e3dbb..bed792c99a03 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/DataEvolutionFileStoreScan.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/DataEvolutionFileStoreScan.java @@ -141,6 +141,23 @@ public FileStoreScan withReadType(RowType readType) { return this; } + /** Reads complete file identities and dependencies before computing a snapshot difference. */ + public Plan planForIncrementalDiff() { + Predicate savedFilter = inputFilter; + RowType savedReadType = readType; + Long savedLimit = limit; + try { + withFilter(null); + readType = null; + limit = null; + return plan(); + } finally { + withFilter(savedFilter); + readType = savedReadType; + limit = savedLimit; + } + } + @Override public Iterator readManifestEntries( List manifestFiles, boolean useSequential) { diff --git a/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReaderImpl.java b/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReaderImpl.java index 934e8d39e525..0e838bd5ce10 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReaderImpl.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReaderImpl.java @@ -26,6 +26,7 @@ import org.apache.paimon.data.BinaryRow; import org.apache.paimon.deletionvectors.DeletionVectorsIndexFile; import org.apache.paimon.fs.Path; +import org.apache.paimon.globalindex.IndexedSplit; import org.apache.paimon.index.DeletionVectorMeta; import org.apache.paimon.index.IndexFileHandler; import org.apache.paimon.index.IndexFileMeta; @@ -36,6 +37,7 @@ import org.apache.paimon.manifest.ManifestFileMeta; import org.apache.paimon.manifest.PartitionEntry; import org.apache.paimon.metrics.MetricRegistry; +import org.apache.paimon.operation.DataEvolutionFileStoreScan; import org.apache.paimon.operation.FileStoreScan; import org.apache.paimon.operation.ManifestsReader; import org.apache.paimon.operation.metrics.CacheMetrics; @@ -62,6 +64,7 @@ import org.apache.paimon.utils.LazyField; import org.apache.paimon.utils.Pair; import org.apache.paimon.utils.Range; +import org.apache.paimon.utils.RangeHelper; import org.apache.paimon.utils.RowRangeIndex; import org.apache.paimon.utils.SnapshotManager; @@ -641,13 +644,17 @@ private Plan toIncrementalPlan( @Override public Plan readIncrementalDiff(Snapshot before) { withMode(ScanMode.ALL); - FileStoreScan.Plan plan = scan.plan(); + FileStoreScan.Plan plan = planForIncrementalDiff(); Map>> afterFiles = groupByPartFiles(plan.files(FileKind.ADD)); + scan.withSnapshot(before); Map>> beforeFiles = - groupByPartFiles(scan.withSnapshot(before).plan().files(FileKind.ADD)); + groupByPartFiles(planForIncrementalDiff().files(FileKind.ADD)); TimeTravelUtil.checkRescaleBucketForIncrementalDiffQuery( tableSchema, before, beforeFiles, plan.snapshot(), afterFiles); + if (options.dataEvolutionEnabled()) { + return toDataEvolutionIncrementalPlan(beforeFiles, plan, afterFiles); + } return toIncrementalPlan( false, new LazyField<>(() -> before), @@ -657,6 +664,71 @@ public Plan readIncrementalDiff(Snapshot before) { afterFiles); } + private FileStoreScan.Plan planForIncrementalDiff() { + return options.dataEvolutionEnabled() + ? ((DataEvolutionFileStoreScan) scan).planForIncrementalDiff() + : scan.plan(); + } + + private Plan toDataEvolutionIncrementalPlan( + Map>> beforeFiles, + FileStoreScan.Plan afterPlan, + Map>> afterFiles) { + Map>> selected = new HashMap<>(); + Map, List> changedRanges = new HashMap<>(); + RangeHelper ranges = + new RangeHelper<>(entry -> entry.file().nonNullRowIdRange()); + for (Map.Entry>> part : afterFiles.entrySet()) { + for (Map.Entry> bucket : part.getValue().entrySet()) { + Set oldFiles = + new HashSet<>( + beforeFiles + .getOrDefault(part.getKey(), Collections.emptyMap()) + .getOrDefault(bucket.getKey(), Collections.emptyList())); + List addedRanges = new ArrayList<>(); + List dependencies = new ArrayList<>(); + for (List group : ranges.mergeOverlappingRanges(bucket.getValue())) { + boolean changed = false; + for (ManifestEntry entry : group) { + if (!oldFiles.contains(entry)) { + addedRanges.add(entry.file().nonNullRowIdRange()); + changed = true; + } + } + if (changed) { + // Shared files still supply untouched columns and the current DV anchor. + dependencies.addAll(group); + } + } + if (!addedRanges.isEmpty()) { + selected.computeIfAbsent(part.getKey(), ignored -> new HashMap<>()) + .put(bucket.getKey(), dependencies); + changedRanges.put( + Pair.of(part.getKey(), bucket.getKey()), + Range.sortAndMergeOverlap(addedRanges)); + } + } + } + List splits = new ArrayList<>(); + for (DataSplit split : + generateSplits(afterPlan.snapshot(), false, splitGenerator, selected)) { + List splitRanges = + Range.sortAndMergeOverlap( + split.dataFiles().stream() + .map(DataFileMeta::nonNullRowIdRange) + .collect(Collectors.toList())); + splits.add( + new IndexedSplit( + split, + Range.and( + splitRanges, + changedRanges.get(Pair.of(split.partition(), split.bucket()))), + null)); + } + return new PlanImpl( + afterPlan.watermark(), afterPlan.snapshot().id(), afterPlan.snapshot(), splits); + } + private RecordComparator partitionComparator() { if (lazyPartitionComparator == null) { lazyPartitionComparator = diff --git a/paimon-core/src/test/java/org/apache/paimon/globalindex/IndexedSplitTest.java b/paimon-core/src/test/java/org/apache/paimon/globalindex/IndexedSplitTest.java index 6b50efc61e80..0b3f828a7195 100644 --- a/paimon-core/src/test/java/org/apache/paimon/globalindex/IndexedSplitTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/globalindex/IndexedSplitTest.java @@ -24,6 +24,7 @@ import org.apache.paimon.io.DataInputViewStreamWrapper; import org.apache.paimon.io.DataOutputViewStreamWrapper; import org.apache.paimon.table.source.DataSplit; +import org.apache.paimon.table.source.DeletionFile; import org.apache.paimon.utils.InstantiationUtil; import org.apache.paimon.utils.Range; @@ -194,6 +195,30 @@ public void testRowCount() { assertThat(split3.rowCount()).isEqualTo(1); } + @Test + public void testMergedRowCountWithDeletionVector() throws Exception { + DataSplit.Builder builder = + DataSplit.builder() + .withSnapshot(1L) + .withPartition(BinaryRow.EMPTY_ROW) + .withBucket(0) + .withBucketPath("bucket-0") + .withDataFiles( + Collections.singletonList( + DataFileTestUtils.newFile("file1", 0, 1, 100, 1000L))); + List ranges = Collections.singletonList(new Range(20, 29)); + assertThat(new IndexedSplit(builder.build(), ranges, null).mergedRowCount()).hasValue(10); + builder.withDataDeletionFiles(Collections.singletonList(null)); + assertThat(new IndexedSplit(builder.build(), ranges, null).mergedRowCount()).hasValue(10); + builder.withDataDeletionFiles(Collections.singletonList(new DeletionFile("dv", 0, 10, 1L))); + IndexedSplit split = new IndexedSplit(builder.build(), ranges, null); + assertThat(split.mergedRowCount()).isEmpty(); + IndexedSplit restored = + InstantiationUtil.deserializeObject( + InstantiationUtil.serializeObject(split), getClass().getClassLoader()); + assertThat(restored.mergedRowCount()).isEmpty(); + } + @Test public void testEmptyRanges() throws IOException { DataFileMeta file = DataFileTestUtils.newFile("file1", 0, 1, 100, 1000L); diff --git a/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java b/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java new file mode 100644 index 000000000000..58b3ffda4145 --- /dev/null +++ b/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java @@ -0,0 +1,352 @@ +/* + * 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.CoreOptions; +import org.apache.paimon.catalog.Catalog; +import org.apache.paimon.catalog.CatalogContext; +import org.apache.paimon.catalog.CatalogFactory; +import org.apache.paimon.data.BinaryRow; +import org.apache.paimon.data.BinaryString; +import org.apache.paimon.data.BlobData; +import org.apache.paimon.data.GenericRow; +import org.apache.paimon.data.InternalRow; +import org.apache.paimon.data.serializer.InternalRowSerializer; +import org.apache.paimon.deletionvectors.BitmapDeletionVector; +import org.apache.paimon.deletionvectors.DeletionVector; +import org.apache.paimon.deletionvectors.append.BaseAppendDeleteFileMaintainer; +import org.apache.paimon.fs.Path; +import org.apache.paimon.index.IndexFileMeta; +import org.apache.paimon.io.CompactIncrement; +import org.apache.paimon.io.DataFileMeta; +import org.apache.paimon.io.DataIncrement; +import org.apache.paimon.manifest.FileKind; +import org.apache.paimon.manifest.IndexManifestEntry; +import org.apache.paimon.manifest.ManifestEntry; +import org.apache.paimon.predicate.PredicateBuilder; +import org.apache.paimon.reader.RecordReader; +import org.apache.paimon.schema.Schema; +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.ReadBuilder; +import org.apache.paimon.table.source.Split; +import org.apache.paimon.types.DataTypes; +import org.apache.paimon.utils.InstantiationUtil; +import org.apache.paimon.utils.RangeHelper; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static org.apache.paimon.utils.DataEvolutionUtils.retrieveAnchorFile; +import static org.assertj.core.api.Assertions.assertThat; + +/** Actual snapshot differences must preserve end-snapshot column and deletion dependencies. */ +class DataEvolutionIncrementalDiffTest extends DataEvolutionTestBase { + + @Override + @BeforeEach + public void beforeEach() throws Catalog.DatabaseAlreadyExistException { + database = "default"; + warehouse = new Path(tempPath.toUri()); + catalog = CatalogFactory.createCatalog(CatalogContext.create(warehouse)); + catalog.createDatabase(database, true); + } + + @Override + protected Schema schemaDefault() { + return Schema.newBuilder() + .column("f0", DataTypes.INT()) + .column("f1", DataTypes.STRING()) + .column("f2", DataTypes.STRING()) + .column("f3", DataTypes.BLOB()) + .option(CoreOptions.BUCKET.key(), "-1") + .option(CoreOptions.ROW_TRACKING_ENABLED.key(), "true") + .option(CoreOptions.DATA_EVOLUTION_ENABLED.key(), "true") + .option(CoreOptions.DELETION_VECTORS_ENABLED.key(), "true") + .option(CoreOptions.WRITE_ONLY.key(), "true") + .option(CoreOptions.BLOB_TARGET_FILE_SIZE.key(), "1 b") + .build(); + } + + @Test + void testSnapshotAndImplicitTagDiffKeepDuplicatesAndNulls() throws Exception { + FileStoreTable table = create(); + write(table, row(1, "old", null)); + table.createTag("before", 1); + write(table, row(2, null, "new"), row(2, null, "new")); + table.createTag("after", 2); + assertThat(collect(diff(table, "1,2"))) + .containsExactly(row(2, null, "new"), row(2, null, "new")); + Map tags = Collections.singletonMap("incremental-between", "before,after"); + assertThat(collect(table.copy(tags).newReadBuilder())) + .containsExactly(row(2, null, "new"), row(2, null, "new")); + assertThat(collect(table.newReadBuilder())).hasSize(3); + } + + @Test + void testPartialUpdatesReconstructUntouchedColumns() throws Exception { + FileStoreTable table = create(); + write(table, row(0, "old-0", "base-0"), row(1, "old-1", "base-1")); + update( + table, + new String[] {"f2"}, + 0, + GenericRow.of(text("new-0")), + GenericRow.of((Object) null)); + update( + table, + new String[] {"f1"}, + 0, + GenericRow.of(text("name-0")), + GenericRow.of(text("name-1"))); + assertThat(collect(diff(table, "1,3"))) + .containsExactly(row(0, "name-0", "new-0"), row(1, "name-1", null)); + assertThat(collect(diff(table, "2,3"))) + .containsExactly(row(0, "name-0", "new-0"), row(1, "name-1", null)); + assertThat(collect(diff(table, "1,3").withProjection(new int[] {0}))) + .containsExactly(GenericRow.of(0), GenericRow.of(1)); + } + + @Test + void testSharedAnchorUsesEndSnapshotDeletionVector() throws Exception { + FileStoreTable table = create(); + write(table, row(0, "a", "old"), row(1, "b", "old"), row(2, "c", "old")); + deleteRows(table, 1); + update( + table, + new String[] {"f2"}, + 0, + GenericRow.of(text("new")), + GenericRow.of(text("new")), + GenericRow.of(text("new"))); + deleteRows(table, 2); + assertThat(collect(diff(table, "1,4"))).containsExactly(row(0, "a", "new")); + assertThat(collect(diff(table, "1,4").withProjection(new int[] {0}))) + .containsExactly(GenericRow.of(0)); + } + + @Test + void testDedicatedBlobSubrangeRetainsAnchorAndSurvivesSerialization() throws Exception { + FileStoreTable table = create(); + List initial = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + initial.add( + GenericRow.of( + i, + text("name-" + i), + text("base-" + i), + new BlobData(new byte[] {(byte) i}))); + } + write(table, initial.toArray(new InternalRow[0])); + deleteRows(table, 2, 4); + FileStoreTable blobWriter = + table.copy( + Collections.singletonMap( + CoreOptions.BLOB_TARGET_FILE_SIZE.key(), "128 mb")); + update( + blobWriter, + new String[] {"f3"}, + 2, + GenericRow.of(new BlobData(new byte[] {102})), + GenericRow.of(new BlobData(new byte[] {103}))); + List rows = collect(diff(table, "1,3")); + assertThat(rows).hasSize(1); + assertThat(rows.get(0).getInt(0)).isEqualTo(3); + assertThat(rows.get(0).getString(1).toString()).isEqualTo("name-3"); + assertThat(rows.get(0).getString(2).toString()).isEqualTo("base-3"); + assertThat(rows.get(0).getBlob(3).toData()).containsExactly((byte) 103); + assertThat(collect(diff(table, "1,3").withProjection(new int[] {0}))) + .containsExactly(GenericRow.of(3)); + } + + @Test + void testPureDeletionAndEmptyDiffDoNotReturnOldRows() throws Exception { + FileStoreTable table = create(); + write(table, row(0, "a", "old")); + deleteRows(table, 0); + assertThat(collect(diff(table, "1,2"))).isEmpty(); + assertThat(collect(diff(table, "2,2"))).isEmpty(); + } + + @Test + void testProjectionAndFilterDoNotChangeEventDiscovery() throws Exception { + FileStoreTable table = create(); + write(table, row(0, "a", "old"), row(1, "b", "old")); + write(table, row(2, "untouched", "match")); + update( + table, + new String[] {"f2"}, + 0, + GenericRow.of(text("match")), + GenericRow.of(text("other"))); + ReadBuilder builder = diff(table, "2,3"); + builder.withFilter(new PredicateBuilder(table.rowType()).equal(2, text("match"))); + builder.withProjection(new int[] {0, 1}); + assertThat(collect(builder)).containsExactly(GenericRow.of(0, text("a"))); + } + + @Test + void testLimitReadsPastAnEntirelyDeletedSplit() throws Exception { + FileStoreTable table = create(); + write(table, row(0, "a", "old")); + write(table, row(1, "b", "old")); + update(table, new String[] {"f2"}, 0, GenericRow.of(text("new"))); + update(table, new String[] {"f2"}, 1, GenericRow.of(text("new"))); + deleteRows(table, 0); + Map options = new HashMap<>(); + options.put(CoreOptions.SOURCE_SPLIT_TARGET_SIZE.key(), "1 b"); + options.put(CoreOptions.SOURCE_SPLIT_OPEN_FILE_COST.key(), "1 b"); + table = table.copy(options); + assertThat(diff(table, "2,5").newScan().plan().splits()).hasSize(2); + assertThat(collect(diff(table, "2,5").withLimit(1))).containsExactly(row(1, "b", "new")); + } + + @Test + void testOrdinaryAppendAndPrimaryKeyDiffStillWork() throws Exception { + for (boolean primaryKey : new boolean[] {false, true}) { + Schema.Builder schema = + Schema.newBuilder() + .column("id", DataTypes.INT()) + .column("v", DataTypes.STRING()); + if (primaryKey) { + schema.primaryKey("id").option(CoreOptions.BUCKET.key(), "1"); + } + catalog.createTable(identifier("control" + primaryKey), schema.build(), false); + FileStoreTable table = + (FileStoreTable) catalog.getTable(identifier("control" + primaryKey)); + write(table, GenericRow.of(1, text("old"))); + write(table, GenericRow.of(primaryKey ? 1 : 2, text("new"))); + List rows = collect(diff(table, "1,2")); + assertThat(rows).hasSize(1); + assertThat(rows.get(0).getString(1).toString()).isEqualTo("new"); + } + } + + private FileStoreTable create() throws Exception { + createTableDefault(); + return getTableDefault(); + } + + private ReadBuilder diff(FileStoreTable table, String between) { + Map options = new HashMap<>(); + options.put("incremental-between", between); + options.put("incremental-between-scan-mode", "diff"); + return table.copy(options).newReadBuilder(); + } + + private List collect(ReadBuilder builder) throws Exception { + List splits = builder.newScan().plan().splits(); + // Exercise the same split transfer used between planning and physical readers. + splits = + InstantiationUtil.deserializeObject( + InstantiationUtil.serializeObject(splits), getClass().getClassLoader()); + InternalRowSerializer serializer = new InternalRowSerializer(builder.readType()); + List result = new ArrayList<>(); + try (RecordReader reader = + builder.newRead().executeFilter().createReader(splits)) { + reader.forEachRemaining(row -> result.add(serializer.copy(row))); + } + return result; + } + + private void update( + FileStoreTable table, String[] columns, long firstRowId, InternalRow... rows) + throws Exception { + BatchWriteBuilder builder = table.newBatchWriteBuilder(); + try (BatchTableWrite write = + builder.newWrite() + .withWriteType(table.rowType().project(Arrays.asList(columns))); + BatchTableCommit commit = builder.newCommit()) { + for (InternalRow row : rows) { + write.write(row); + } + List messages = write.prepareCommit(); + setFirstRowId(messages, firstRowId); + commit.commit(messages); + } + } + + private void deleteRows(FileStoreTable table, long... rowIds) throws Exception { + List files = + table.store().newScan().plan().files(FileKind.ADD).stream() + .map(ManifestEntry::file) + .collect(Collectors.toList()); + BaseAppendDeleteFileMaintainer maintainer = + BaseAppendDeleteFileMaintainer.forUnawareAppend( + table.store().newIndexFileHandler(), + table.latestSnapshot().get(), + BinaryRow.EMPTY_ROW); + for (List group : + new RangeHelper<>(DataFileMeta::nonNullRowIdRange).mergeOverlappingRanges(files)) { + DataFileMeta anchor = retrieveAnchorFile(group, Function.identity()); + DeletionVector vector = new BitmapDeletionVector(); + boolean changed = false; + for (long rowId : rowIds) { + if (anchor.nonNullRowIdRange().from <= rowId + && rowId <= anchor.nonNullRowIdRange().to) { + vector.delete(rowId - anchor.nonNullFirstRowId()); + changed = true; + } + } + if (changed) { + maintainer.notifyNewDeletionVector(anchor.fileName(), vector); + } + } + List added = new ArrayList<>(); + List deleted = new ArrayList<>(); + for (IndexManifestEntry entry : maintainer.persist()) { + (entry.kind() == FileKind.ADD ? added : deleted).add(entry.indexFile()); + } + try (BatchTableCommit commit = table.newBatchWriteBuilder().newCommit()) { + commit.commit( + Collections.singletonList( + new CommitMessageImpl( + BinaryRow.EMPTY_ROW, + 0, + null, + new DataIncrement( + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList(), + added, + deleted), + CompactIncrement.emptyIncrement()))); + } + } + + private static BinaryString text(String value) { + return value == null ? null : BinaryString.fromString(value); + } + + private static InternalRow row(int id, String f1, String f2) { + return GenericRow.of(id, text(f1), text(f2), null); + } +} diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionIncrementalDiffTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionIncrementalDiffTest.scala new file mode 100644 index 000000000000..ad8011f90675 --- /dev/null +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionIncrementalDiffTest.scala @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.paimon.spark.commands + +import org.apache.paimon.spark.PaimonSparkTestBase + +import org.apache.spark.sql.Row + +class DataEvolutionIncrementalDiffTest extends PaimonSparkTestBase { + + test("DE diff preserves untouched columns and deletion visibility after SQL updates") { + withTable("t") { + sql("""CREATE TABLE t (id INT, a INT, b INT) TBLPROPERTIES ( + |'bucket'='-1','row-tracking.enabled'='true', + |'data-evolution.enabled'='true','deletion-vectors.enabled'='true', + |'write-only'='true')""".stripMargin) + sql("INSERT INTO t VALUES (1,10,100),(2,20,200),(3,30,300)") + val before = loadTable("t").snapshotManager().latestSnapshot().id() + sql("DELETE FROM t WHERE id=2") + sql("UPDATE t SET b=b+1 WHERE id IN (1,3)") + val after = loadTable("t").snapshotManager().latestSnapshot().id() + + def diff = spark.read + .option("incremental-between", s"$before,$after") + .option("incremental-between-scan-mode", "diff") + .table("t") + + checkAnswer(diff, Seq(Row(1, 10, 101), Row(3, 30, 301))) + checkAnswer(diff.select("a"), Seq(Row(10), Row(30))) + checkAnswer(diff.where("b=101").select("a"), Seq(Row(10))) + checkAnswer(diff.orderBy("id").limit(1), Seq(Row(1, 10, 101))) + assert(diff.limit(1).collect().length == 1) + checkAnswer(sql("SELECT * FROM t"), Seq(Row(1, 10, 101), Row(3, 30, 301))) + } + } +} From adad80e29526d65fced45b8aeece5b53afdb83ba Mon Sep 17 00:00:00 2001 From: yangjiabin <706948683@qq.com> Date: Fri, 20 Nov 2026 10:50:02 +0800 Subject: [PATCH 2/8] [test] Inspect commit metadata directly in compact race fixtures --- .../procedure/CompactProcedureTestBase.scala | 32 ++++++++----------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/procedure/CompactProcedureTestBase.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/procedure/CompactProcedureTestBase.scala index 8671762798e1..75532a45671a 100644 --- a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/procedure/CompactProcedureTestBase.scala +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/procedure/CompactProcedureTestBase.scala @@ -26,7 +26,7 @@ import org.apache.paimon.deletionvectors.DeletionVectorsIndexFile.DELETION_VECTO import org.apache.paimon.format.blob.BlobFileFormat import org.apache.paimon.fs.Path import org.apache.paimon.io.DataFileMeta -import org.apache.paimon.manifest.FileSource +import org.apache.paimon.manifest.{FileKind, FileSource} import org.apache.paimon.operation.commit.DataEvolutionRowRangeConflictException import org.apache.paimon.partition.PartitionPredicate import org.apache.paimon.spark.PaimonSparkTestBase @@ -36,7 +36,7 @@ import org.apache.paimon.spark.commands.CompactRowIdRangeIndex import org.apache.paimon.spark.utils.SparkProcedureUtils import org.apache.paimon.table.FileStoreTable import org.apache.paimon.table.sink.CommitMessageImpl -import org.apache.paimon.table.source.{DataSplit, IncrementalSplit} +import org.apache.paimon.table.source.{DataSplit, ScanMode} import org.apache.paimon.table.source.snapshot.SnapshotReader import org.apache.paimon.utils.Range @@ -3037,7 +3037,6 @@ abstract class CompactProcedureTestBase extends PaimonSparkTestBase with StreamT } private def partialUpdate(table: FileStoreTable, sourceQuery: String): DataFileMeta = { - val beforeMerge = table.latestSnapshot().get() sql(sourceQuery).createOrReplaceTempView("merge_source") try { sql(""" @@ -3049,16 +3048,7 @@ abstract class CompactProcedureTestBase extends PaimonSparkTestBase with StreamT } finally { spark.catalog.dropTempView("merge_source") } - table - .newSnapshotReader() - .withSnapshot(table.latestSnapshot().get()) - .readIncrementalDiff(beforeMerge) - .splits() - .asScala - .collect { case split: IncrementalSplit => split } - .flatMap(_.afterFiles().asScala) - .find(file => !BlobFileFormat.isBlobFile(file.fileName())) - .get + latestNormalDataFile(table) } /** Like [[partialUpdate]] but with an explicit SET list, so sub-field targets can be used. */ @@ -3066,7 +3056,6 @@ abstract class CompactProcedureTestBase extends PaimonSparkTestBase with StreamT table: FileStoreTable, setList: String, sourceQuery: String): DataFileMeta = { - val beforeMerge = table.latestSnapshot().get() sql(sourceQuery).createOrReplaceTempView("merge_source") try { sql(s""" @@ -3078,14 +3067,19 @@ abstract class CompactProcedureTestBase extends PaimonSparkTestBase with StreamT } finally { spark.catalog.dropTempView("merge_source") } + latestNormalDataFile(table) + } + + private def latestNormalDataFile(table: FileStoreTable): DataFileMeta = { table - .newSnapshotReader() + .store() + .newScan() .withSnapshot(table.latestSnapshot().get()) - .readIncrementalDiff(beforeMerge) - .splits() + .withKind(ScanMode.DELTA) + .plan() + .files(FileKind.ADD) .asScala - .collect { case split: IncrementalSplit => split } - .flatMap(_.afterFiles().asScala) + .map(_.file()) .find(file => !BlobFileFormat.isBlobFile(file.fileName())) .get } From 8a51ed6ac543315e27e18242c39ba53f8bb43c19 Mon Sep 17 00:00:00 2001 From: yangjiabin <706948683@qq.com> Date: Fri, 20 Nov 2026 12:26:08 +0800 Subject: [PATCH 3/8] [core] Honor requested DIFF rows and avoid unpinned indexes --- docs/docs/multimodal-table/data-evolution.mdx | 5 + .../globalindex/DataEvolutionBatchScan.java | 11 +- .../source/snapshot/SnapshotReaderImpl.java | 25 ++- .../DataEvolutionIncrementalDiffTest.java | 191 +++++++++++++++++- 4 files changed, 221 insertions(+), 11 deletions(-) diff --git a/docs/docs/multimodal-table/data-evolution.mdx b/docs/docs/multimodal-table/data-evolution.mdx index 8e9096c9af42..16b17957c87c 100644 --- a/docs/docs/multimodal-table/data-evolution.mdx +++ b/docs/docs/multimodal-table/data-evolution.mdx @@ -500,6 +500,11 @@ rows whose values did not change, and compaction can cause rows to be returned again. A deletion without newly added data files produces no rows; deleted rows are excluded when a new column file covers their range. Tag-to-tag DIFF reads use the same semantics. DIFF planning still materializes snapshot metadata. +Requested RowID ranges further restrict the selected ranges. Automatic global-index +pruning is disabled for incremental scans until the index and data plan can be bound +to the same historical endpoint. Supplying an external global-index result to an +incremental scan is rejected; use `withRowRanges` for explicit RowID selections. +Ordinary snapshot reads retain their index optimizations. ## Compaction and Row-ID Lifetime diff --git a/paimon-core/src/main/java/org/apache/paimon/globalindex/DataEvolutionBatchScan.java b/paimon-core/src/main/java/org/apache/paimon/globalindex/DataEvolutionBatchScan.java index d63fbb46cccb..245fa1353180 100644 --- a/paimon-core/src/main/java/org/apache/paimon/globalindex/DataEvolutionBatchScan.java +++ b/paimon-core/src/main/java/org/apache/paimon/globalindex/DataEvolutionBatchScan.java @@ -364,6 +364,7 @@ private static boolean hasMixedSpatialDisjunction(Predicate predicate, boolean u /** Plan complete data splits while deferring index evaluation to readers. */ private Plan planWithIndexQuery() { if (queryAuthEnabled() + || table.coreOptions().startupMode() == CoreOptions.StartupMode.INCREMENTAL || filter == null // Partition-only scans may apply LIMIT/TopN before deferred index filtering. || !batchScan.snapshotReader().hasNonPartitionFilter() @@ -497,6 +498,15 @@ private boolean queryAuthEnabled() { } private Optional evalGlobalIndex() { + CoreOptions options = table.coreOptions(); + // Incremental endpoints are resolved by batchScan, not by the independent index scanner. + if (options.startupMode() == CoreOptions.StartupMode.INCREMENTAL) { + Preconditions.checkArgument( + globalIndexResult == null, + "Unbound global-index results are not supported for incremental reads; " + + "use withRowRanges for explicit row-id selections."); + return Optional.empty(); + } // the index ranks raw values, which a mask may invalidate; fall back to a full scan. // Checked before the supplied result too: withGlobalIndexResult is public, so a caller // can hand in one that was computed off the raw values. @@ -509,7 +519,6 @@ private Optional evalGlobalIndex() { if (filter == null) { return Optional.empty(); } - CoreOptions options = table.coreOptions(); if (!options.globalIndexEnabled()) { return Optional.empty(); } diff --git a/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReaderImpl.java b/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReaderImpl.java index 0e838bd5ce10..1567dd1ec920 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReaderImpl.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReaderImpl.java @@ -109,6 +109,7 @@ public class SnapshotReaderImpl implements SnapshotReader { private ScanMode scanMode = ScanMode.ALL; private boolean hasNonPartitionFilter; + @Nullable private RowRangeIndex rowRangeIndex; private RecordComparator lazyPartitionComparator; private CacheMetrics dvMetaCacheMetrics; @@ -337,12 +338,15 @@ public SnapshotReader withMetricRegistry(MetricRegistry registry) { @Override public SnapshotReader withRowRanges(List sortedPushdownRowRanges) { - scan.withRowRanges(sortedPushdownRowRanges); - return this; + return withRowRangeIndex( + sortedPushdownRowRanges == null + ? null + : RowRangeIndex.create(sortedPushdownRowRanges)); } @Override public SnapshotReader withRowRangeIndex(RowRangeIndex rowRangeIndex) { + this.rowRangeIndex = rowRangeIndex; scan.withRowRangeIndex(rowRangeIndex); return this; } @@ -717,13 +721,16 @@ private Plan toDataEvolutionIncrementalPlan( split.dataFiles().stream() .map(DataFileMeta::nonNullRowIdRange) .collect(Collectors.toList())); - splits.add( - new IndexedSplit( - split, - Range.and( - splitRanges, - changedRanges.get(Pair.of(split.partition(), split.bucket()))), - null)); + List selectedRanges = + Range.and( + splitRanges, + changedRanges.get(Pair.of(split.partition(), split.bucket()))); + if (rowRangeIndex != null) { + selectedRanges = Range.and(selectedRanges, rowRangeIndex.ranges()); + } + if (!selectedRanges.isEmpty()) { + splits.add(new IndexedSplit(split, selectedRanges, null)); + } } return new PlanImpl( afterPlan.watermark(), afterPlan.snapshot().id(), afterPlan.snapshot(), splits); diff --git a/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java b/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java index 58b3ffda4145..f15aeb3ee760 100644 --- a/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java @@ -19,6 +19,7 @@ package org.apache.paimon.table; import org.apache.paimon.CoreOptions; +import org.apache.paimon.Snapshot; import org.apache.paimon.catalog.Catalog; import org.apache.paimon.catalog.CatalogContext; import org.apache.paimon.catalog.CatalogFactory; @@ -32,6 +33,12 @@ import org.apache.paimon.deletionvectors.DeletionVector; import org.apache.paimon.deletionvectors.append.BaseAppendDeleteFileMaintainer; import org.apache.paimon.fs.Path; +import org.apache.paimon.globalindex.GlobalIndexResult; +import org.apache.paimon.globalindex.IndexQuerySplit; +import org.apache.paimon.globalindex.IndexedSplit; +import org.apache.paimon.globalindex.ScanResult; +import org.apache.paimon.globalindex.sorted.SortedGlobalIndexScanner; +import org.apache.paimon.globalindex.sorted.SortedGlobalIndexTestUtils; import org.apache.paimon.index.IndexFileMeta; import org.apache.paimon.io.CompactIncrement; import org.apache.paimon.io.DataFileMeta; @@ -47,14 +54,20 @@ 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; +import org.apache.paimon.table.source.snapshot.SnapshotReader; import org.apache.paimon.types.DataTypes; import org.apache.paimon.utils.InstantiationUtil; +import org.apache.paimon.utils.Range; import org.apache.paimon.utils.RangeHelper; +import org.apache.paimon.utils.RowRangeIndex; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import java.util.ArrayList; import java.util.Arrays; @@ -67,6 +80,7 @@ import static org.apache.paimon.utils.DataEvolutionUtils.retrieveAnchorFile; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Actual snapshot differences must preserve end-snapshot column and deletion dependencies. */ class DataEvolutionIncrementalDiffTest extends DataEvolutionTestBase { @@ -185,6 +199,178 @@ void testDedicatedBlobSubrangeRetainsAnchorAndSurvivesSerialization() throws Exc assertThat(rows.get(0).getBlob(3).toData()).containsExactly((byte) 103); assertThat(collect(diff(table, "1,3").withProjection(new int[] {0}))) .containsExactly(GenericRow.of(3)); + assertThat( + collect( + diff(table, "1,3") + .withRowRanges(Collections.singletonList(new Range(2, 2))))) + .isEmpty(); + } + + @Test + void testRequestedRowRangeRestrictsAppendsAndPartialUpdates() throws Exception { + FileStoreTable table = create(); + write(table, row(100, "a", "old")); + write(table, row(200, "b", "old"), row(300, "c", "old")); + List requested = Collections.singletonList(new Range(2, 2)); + assertThat(collect(table.newReadBuilder().withRowRanges(requested))) + .containsExactly(row(300, "c", "old")); + ReadBuilder appendDiff = diff(table, "1,2").withRowRanges(requested); + assertThat(((IndexedSplit) appendDiff.newScan().plan().splits().get(0)).rowRanges()) + .isEqualTo(requested); + assertThat(collect(appendDiff)).containsExactly(row(300, "c", "old")); + update( + table, + new String[] {"f2"}, + 1, + GenericRow.of(text("new-200")), + GenericRow.of(text("new-300"))); + assertThat(collect(diff(table, "2,3").withRowRanges(requested))) + .containsExactly(row(300, "c", "new-300")); + assertThat( + collect( + diff(table, "2,3") + .withRowRanges(Collections.singletonList(new Range(0, 0))))) + .isEmpty(); + } + + @Test + void testDeletedRequestedRowDoesNotReturnAnUnrequestedLiveRow() throws Exception { + FileStoreTable table = create(); + write(table, row(100, "a", "old"), row(200, "b", "old")); + update( + table, + new String[] {"f2"}, + 0, + GenericRow.of(text("new")), + GenericRow.of(text("new"))); + deleteRows(table, 0); + assertThat( + collect( + diff(table, "1,3") + .withRowRanges(Collections.singletonList(new Range(0, 0))))) + .isEmpty(); + } + + @Test + void testSnapshotReaderRangeSettersShareAndClearState() throws Exception { + FileStoreTable table = create(); + write(table, row(100, "a", "old")); + Snapshot start = table.latestSnapshot().get(); + write(table, row(200, "b", "new"), row(300, "c", "new")); + Snapshot end = table.latestSnapshot().get(); + SnapshotReader reader = table.newSnapshotReader(); + List requested = Collections.singletonList(new Range(2, 2)); + assertThat( + collect( + table.newReadBuilder(), + reader.withSnapshot(end) + .withRowRanges(requested) + .readIncrementalDiff(start) + .splits())) + .containsExactly(row(300, "c", "new")); + reader.withRowRangeIndex(RowRangeIndex.create(Collections.singletonList(new Range(1, 1)))); + assertThat( + collect( + table.newReadBuilder(), + reader.withSnapshot(end) + .withRowRanges(requested) + .readIncrementalDiff(start) + .splits())) + .containsExactly(row(300, "c", "new")); + assertThat( + collect( + table.newReadBuilder(), + reader.withSnapshot(end) + .withRowRanges(Collections.emptyList()) + .readIncrementalDiff(start) + .splits())) + .isEmpty(); + assertThat( + collect( + table.newReadBuilder(), + reader.withSnapshot(end) + .withRowRanges(null) + .readIncrementalDiff(start) + .splits())) + .containsExactly(row(200, "b", "new"), row(300, "c", "new")); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void testHistoricalDiffDoesNotUseALaterGlobalIndex(boolean indexInReader) throws Exception { + catalog.createTable( + identifier(), + Schema.newBuilder() + .column("id", DataTypes.INT()) + .column("v", DataTypes.INT()) + .option(CoreOptions.BUCKET.key(), "-1") + .option(CoreOptions.ROW_TRACKING_ENABLED.key(), "true") + .option(CoreOptions.DATA_EVOLUTION_ENABLED.key(), "true") + .option(CoreOptions.WRITE_ONLY.key(), "true") + .build(), + false); + FileStoreTable table = getTableDefault(); + write(table, GenericRow.of(100, 10)); + table.createTag("before", 1); + write(table, GenericRow.of(200, 20)); + table.createTag("end", 2); + update(table, new String[] {"v"}, 1, GenericRow.of(30)); + ScanResult scan = + new SortedGlobalIndexScanner(table, "btree") + .withIndexFields(Collections.singletonList("v")) + .scan() + .get(); + List indexes = new ArrayList<>(); + for (DataSplit split : scan.entries()) { + indexes.addAll( + SortedGlobalIndexTestUtils.buildIndex( + table, "btree", "v", split, scan.scanSnapshotId())); + } + try (BatchTableCommit commit = table.newBatchWriteBuilder().newCommit()) { + commit.commit(indexes); + } + table = + table.copy( + Collections.singletonMap( + CoreOptions.GLOBAL_INDEX_QUERY_IN_READER_ENABLED.key(), + Boolean.toString(indexInReader))); + PredicateBuilder predicates = new PredicateBuilder(table.rowType()); + FileStoreTable withoutIndex = + table.copy( + Collections.singletonMap(CoreOptions.GLOBAL_INDEX_ENABLED.key(), "false")); + assertThat(collect(diff(withoutIndex, "1,2").withFilter(predicates.equal(1, 20)))) + .containsExactly(GenericRow.of(200, 20)); + for (String range : Arrays.asList("1,2", "before,end")) { + assertThat(collect(diff(table, range).withFilter(predicates.equal(1, 20)))) + .containsExactly(GenericRow.of(200, 20)); + } + ReadBuilder latest = table.newReadBuilder().withFilter(predicates.equal(1, 30)); + assertThat(latest.newScan().plan().splits().get(0)) + .isInstanceOf(indexInReader ? IndexQuerySplit.class : IndexedSplit.class); + assertThat(collect(latest)).containsExactly(GenericRow.of(200, 30)); + } + + @Test + void testIncrementalRejectsUnboundExternalIndexResults() throws Exception { + FileStoreTable table = create(); + write(table, row(100, "a", "old")); + write(table, row(200, "b", "new")); + assertThatThrownBy( + () -> + diff(table, "1,2") + .newScan() + .withGlobalIndexResult(GlobalIndexResult.createEmpty()) + .plan()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("incremental") + .hasMessageContaining("withRowRanges"); + ReadBuilder latest = table.newReadBuilder(); + List selected = + latest.newScan() + .withGlobalIndexResult(GlobalIndexResult.fromRange(new Range(1, 1))) + .plan() + .splits(); + assertThat(collect(latest, selected)).containsExactly(row(200, "b", "new")); } @Test @@ -263,7 +449,10 @@ private ReadBuilder diff(FileStoreTable table, String between) { } private List collect(ReadBuilder builder) throws Exception { - List splits = builder.newScan().plan().splits(); + return collect(builder, builder.newScan().plan().splits()); + } + + private List collect(ReadBuilder builder, List splits) throws Exception { // Exercise the same split transfer used between planning and physical readers. splits = InstantiationUtil.deserializeObject( From 07987830f36e7d8c7dbb48e4a3c3b9db38223ea8 Mon Sep 17 00:00:00 2001 From: yangjiabin <706948683@qq.com> Date: Sat, 21 Nov 2026 00:12:57 +0800 Subject: [PATCH 4/8] [core] Index DIFF range lookups and preserve file and score metadata --- .../globalindex/IndexedSplitRecordReader.java | 119 ++++++++++---- .../source/snapshot/SnapshotReaderImpl.java | 21 ++- .../IndexedSplitRecordReaderTest.java | 145 ++++++++++++++++++ .../DataEvolutionIncrementalDiffTest.java | 53 +++++++ .../DataEvolutionIncrementalDiffTest.scala | 52 +++++++ .../spark/sql/MultiVectorSearchTest.scala | 9 ++ 6 files changed, 362 insertions(+), 37 deletions(-) diff --git a/paimon-core/src/main/java/org/apache/paimon/globalindex/IndexedSplitRecordReader.java b/paimon-core/src/main/java/org/apache/paimon/globalindex/IndexedSplitRecordReader.java index 3d5bc89e00e9..d43ef61065d3 100644 --- a/paimon-core/src/main/java/org/apache/paimon/globalindex/IndexedSplitRecordReader.java +++ b/paimon-core/src/main/java/org/apache/paimon/globalindex/IndexedSplitRecordReader.java @@ -19,11 +19,14 @@ package org.apache.paimon.globalindex; import org.apache.paimon.data.InternalRow; +import org.apache.paimon.fs.Path; +import org.apache.paimon.reader.FileRecordIterator; import org.apache.paimon.reader.RecordReader; import org.apache.paimon.reader.ScoreRecordIterator; import org.apache.paimon.reader.ScoreRecordReader; import org.apache.paimon.table.SpecialFields; import org.apache.paimon.types.RowType; +import org.apache.paimon.utils.Filter; import org.apache.paimon.utils.ProjectedRow; import org.apache.paimon.utils.Range; @@ -32,6 +35,7 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; +import java.util.function.Function; import static org.apache.paimon.utils.Preconditions.checkArgument; @@ -57,42 +61,99 @@ public ScoreRecordIterator readBatch() throws IOException { if (iterator == null) { return null; } - return new ScoreRecordIterator() { + ScoreRecordIterator scored = + new ScoreRecordIterator() { - private float score = Float.NaN; - private long rowId; + private float score = Float.NaN; + private long rowId; - @Override - public float returnedScore() { - return score; - } + @Override + public float returnedScore() { + return score; + } - @Override - public long returnedRowId() { - return rowId; - } + @Override + public long returnedRowId() { + return rowId; + } - @Override - public InternalRow next() throws IOException { - InternalRow row = iterator.next(); - if (row != null && rowIdIndex >= 0) { - this.rowId = row.getLong(rowIdIndex); - if (rowIdToScore != null) { - this.score = rowIdToScore.get(rowId); + @Override + public InternalRow next() throws IOException { + InternalRow row = iterator.next(); + if (row != null && rowIdIndex >= 0) { + this.rowId = row.getLong(rowIdIndex); + if (rowIdToScore != null) { + this.score = rowIdToScore.get(rowId); + } + if (projectedRow != null) { + projectedRow.replaceRow(row); + return projectedRow; + } + } + return row; } - if (projectedRow != null) { - projectedRow.replaceRow(row); - return projectedRow; + + @Override + public void releaseBatch() { + iterator.releaseBatch(); } - } - return row; - } + }; + return iterator instanceof FileRecordIterator + ? new FileScoreRecordIterator<>(scored, (FileRecordIterator) iterator) + : scored; + } - @Override - public void releaseBatch() { - iterator.releaseBatch(); - } - }; + private static class FileScoreRecordIterator + implements FileRecordIterator, ScoreRecordIterator { + + private final ScoreRecordIterator scored; + private final FileRecordIterator file; + + private FileScoreRecordIterator(ScoreRecordIterator scored, FileRecordIterator file) { + this.scored = scored; + this.file = file; + } + + @Override + public long returnedPosition() { + return file.returnedPosition(); + } + + @Override + public Path filePath() { + return file.filePath(); + } + + @Override + public float returnedScore() { + return scored.returnedScore(); + } + + @Override + public long returnedRowId() { + return scored.returnedRowId(); + } + + @Nullable + @Override + public T next() throws IOException { + return scored.next(); + } + + @Override + public void releaseBatch() { + scored.releaseBatch(); + } + + @Override + public FileScoreRecordIterator transform(Function function) { + return new FileScoreRecordIterator<>(scored.transform(function), file); + } + + @Override + public FileScoreRecordIterator filter(Filter filter) { + return new FileScoreRecordIterator<>(scored.filter(filter), file); + } } @Override diff --git a/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReaderImpl.java b/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReaderImpl.java index 1567dd1ec920..91bc0697f7d1 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReaderImpl.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReaderImpl.java @@ -679,7 +679,7 @@ private Plan toDataEvolutionIncrementalPlan( FileStoreScan.Plan afterPlan, Map>> afterFiles) { Map>> selected = new HashMap<>(); - Map, List> changedRanges = new HashMap<>(); + Map, RowRangeIndex> changedRanges = new HashMap<>(); RangeHelper ranges = new RangeHelper<>(entry -> entry.file().nonNullRowIdRange()); for (Map.Entry>> part : afterFiles.entrySet()) { @@ -709,7 +709,7 @@ private Plan toDataEvolutionIncrementalPlan( .put(bucket.getKey(), dependencies); changedRanges.put( Pair.of(part.getKey(), bucket.getKey()), - Range.sortAndMergeOverlap(addedRanges)); + RowRangeIndex.create(addedRanges)); } } } @@ -721,12 +721,17 @@ private Plan toDataEvolutionIncrementalPlan( split.dataFiles().stream() .map(DataFileMeta::nonNullRowIdRange) .collect(Collectors.toList())); - List selectedRanges = - Range.and( - splitRanges, - changedRanges.get(Pair.of(split.partition(), split.bucket()))); - if (rowRangeIndex != null) { - selectedRanges = Range.and(selectedRanges, rowRangeIndex.ranges()); + RowRangeIndex changed = changedRanges.get(Pair.of(split.partition(), split.bucket())); + List selectedRanges = new ArrayList<>(); + for (Range splitRange : splitRanges) { + for (Range range : changed.intersectedRanges(splitRange.from, splitRange.to)) { + if (rowRangeIndex == null) { + selectedRanges.add(range); + } else { + selectedRanges.addAll( + rowRangeIndex.intersectedRanges(range.from, range.to)); + } + } } if (!selectedRanges.isEmpty()) { splits.add(new IndexedSplit(split, selectedRanges, null)); diff --git a/paimon-core/src/test/java/org/apache/paimon/globalindex/IndexedSplitRecordReaderTest.java b/paimon-core/src/test/java/org/apache/paimon/globalindex/IndexedSplitRecordReaderTest.java index 695010e4daa0..f75a74a7f86c 100644 --- a/paimon-core/src/test/java/org/apache/paimon/globalindex/IndexedSplitRecordReaderTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/globalindex/IndexedSplitRecordReaderTest.java @@ -22,16 +22,32 @@ import org.apache.paimon.data.BinaryString; import org.apache.paimon.data.GenericRow; import org.apache.paimon.data.InternalRow; +import org.apache.paimon.fs.Path; +import org.apache.paimon.fs.local.LocalFileIO; import org.apache.paimon.io.DataFileMeta; import org.apache.paimon.io.DataFileTestUtils; +import org.apache.paimon.predicate.PredicateBuilder; +import org.apache.paimon.reader.FileRecordIterator; import org.apache.paimon.reader.RecordReader; import org.apache.paimon.reader.ScoreRecordIterator; +import org.apache.paimon.reader.ScoreRecordReader; +import org.apache.paimon.schema.FileSystemSchemaManager; +import org.apache.paimon.schema.Schema; +import org.apache.paimon.table.FileStoreTable; +import org.apache.paimon.table.FileStoreTableFactory; +import org.apache.paimon.table.SpecialFields; +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.source.DataSplit; +import org.apache.paimon.table.source.ReadBuilder; +import org.apache.paimon.table.source.Split; import org.apache.paimon.types.DataTypes; import org.apache.paimon.types.RowType; import org.apache.paimon.utils.Range; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import javax.annotation.Nullable; @@ -47,6 +63,112 @@ /** Test for {@link IndexedSplitRecordReader}. */ public class IndexedSplitRecordReaderTest { + @Test + public void testUnscoredRangeReadPreservesFileMetadata(@TempDir java.nio.file.Path tempDir) + throws Exception { + FileStoreTable table = createDataEvolutionTable(tempDir); + ReadBuilder readBuilder = + table.newReadBuilder() + .withFilter(new PredicateBuilder(table.rowType()).notEqual(0, 12)); + List splits = readBuilder.newScan().plan().splits(); + assertThat(splits).hasSize(1); + DataSplit dataSplit = (DataSplit) splits.get(0); + assertThat(dataSplit.dataFiles()).hasSize(1); + Path expectedPath = + new Path(dataSplit.bucketPath(), dataSplit.dataFiles().get(0).fileName()); + IndexedSplit split = + new IndexedSplit(dataSplit, Arrays.asList(new Range(1, 2), new Range(4, 5)), null); + + List ids = new ArrayList<>(); + List positions = new ArrayList<>(); + try (RecordReader reader = + readBuilder.newRead().executeFilter().createReader(split)) { + RecordReader.RecordIterator batch; + while ((batch = reader.readBatch()) != null) { + try { + assertThat(batch).isInstanceOf(FileRecordIterator.class); + FileRecordIterator fileBatch = + (FileRecordIterator) batch; + assertThat(fileBatch.filePath()).isEqualTo(expectedPath); + InternalRow row; + while ((row = fileBatch.next()) != null) { + ids.add(row.getInt(0)); + positions.add(fileBatch.returnedPosition()); + } + } finally { + batch.releaseBatch(); + } + } + } + assertThat(ids).containsExactly(11, 14, 15); + assertThat(positions).containsExactly(1L, 4L, 5L); + } + + @Test + public void testUnscoredRowIdAndFileMetadataSurviveFilterAndTransform( + @TempDir java.nio.file.Path tempDir) throws Exception { + FileStoreTable table = createDataEvolutionTable(tempDir); + BatchWriteBuilder writeBuilder = table.newBatchWriteBuilder(); + try (BatchTableWrite write = writeBuilder.newWrite(); + BatchTableCommit commit = writeBuilder.newCommit()) { + for (int id = 20; id < 26; id++) { + write.write(GenericRow.of(id)); + } + commit.commit(write.prepareCommit()); + } + + ReadBuilder readBuilder = + table.newReadBuilder() + .withReadType(SpecialFields.rowTypeWithRowId(table.rowType())); + List splits = readBuilder.newScan().plan().splits(); + assertThat(splits).hasSize(1); + DataSplit dataSplit = (DataSplit) splits.get(0); + DataFileMeta file = + dataSplit.dataFiles().stream() + .filter(f -> f.nonNullFirstRowId() == 6L) + .findFirst() + .get(); + Path expectedPath = new Path(dataSplit.bucketPath(), file.fileName()); + IndexedSplit split = + new IndexedSplit( + dataSplit, Arrays.asList(new Range(7, 8), new Range(10, 11)), null); + + List ids = new ArrayList<>(); + List rowIds = new ArrayList<>(); + List positions = new ArrayList<>(); + try (RecordReader reader = readBuilder.newRead().createReader(split)) { + assertThat(reader).isInstanceOf(ScoreRecordReader.class); + RecordReader.RecordIterator batch; + while ((batch = reader.readBatch()) != null) { + RecordReader.RecordIterator projected = + batch.filter(row -> row.getInt(0) != 22) + .transform(row -> GenericRow.of(row.getInt(0) * 10)); + try { + assertThat(projected) + .isInstanceOf(FileRecordIterator.class) + .isInstanceOf(ScoreRecordIterator.class); + FileRecordIterator fileBatch = + (FileRecordIterator) projected; + ScoreRecordIterator scoredBatch = + (ScoreRecordIterator) projected; + assertThat(fileBatch.filePath()).isEqualTo(expectedPath); + InternalRow row; + while ((row = projected.next()) != null) { + ids.add(row.getInt(0)); + rowIds.add(scoredBatch.returnedRowId()); + positions.add(fileBatch.returnedPosition()); + assertThat(Float.isNaN(scoredBatch.returnedScore())).isTrue(); + } + } finally { + projected.releaseBatch(); + } + } + } + assertThat(ids).containsExactly(210, 240, 250); + assertThat(rowIds).containsExactly(7L, 10L, 11L); + assertThat(positions).containsExactly(1L, 4L, 5L); + } + @Test public void testReadWithScores() throws IOException { // Create rows with ROW_ID at position 2 @@ -380,6 +502,29 @@ public void testClose() throws IOException { assertThat(mockReader.isClosed()).isTrue(); } + private FileStoreTable createDataEvolutionTable(java.nio.file.Path tempDir) throws Exception { + Path tablePath = new Path(tempDir.toUri()); + new FileSystemSchemaManager(LocalFileIO.create(), tablePath) + .createTable( + Schema.newBuilder() + .column("id", DataTypes.INT()) + .option("bucket", "-1") + .option("row-tracking.enabled", "true") + .option("data-evolution.enabled", "true") + .option("write-only", "true") + .build()); + FileStoreTable table = FileStoreTableFactory.create(LocalFileIO.create(), tablePath); + BatchWriteBuilder writeBuilder = table.newBatchWriteBuilder(); + try (BatchTableWrite write = writeBuilder.newWrite(); + BatchTableCommit commit = writeBuilder.newCommit()) { + for (int id = 10; id < 16; id++) { + write.write(GenericRow.of(id)); + } + commit.commit(write.prepareCommit()); + } + return table; + } + private IndexedSplit createIndexedSplit(List ranges, @Nullable float[] scores) { DataFileMeta file = DataFileTestUtils.newFile("test-file", 0, 1, 100, 1000L); DataSplit dataSplit = diff --git a/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java b/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java index f15aeb3ee760..3fcc033aec47 100644 --- a/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java @@ -233,6 +233,59 @@ void testRequestedRowRangeRestrictsAppendsAndPartialUpdates() throws Exception { .isEmpty(); } + @Test + void testDisjointUpdatesKeepExactRangesAcrossPackedGroups() throws Exception { + FileStoreTable table = create(); + for (int start = 0; start < 9; start += 3) { + write( + table, + row(start, "untouched", "old"), + row(start + 1, "untouched", "old"), + row(start + 2, "untouched", "old")); + } + update( + table, + new String[] {"f2"}, + 0, + GenericRow.of(text("new")), + GenericRow.of(text("new")), + GenericRow.of(text("new"))); + update( + table, + new String[] {"f2"}, + 6, + GenericRow.of(text("new")), + GenericRow.of(text("new")), + GenericRow.of(text("new"))); + List splits = diff(table, "3,5").newScan().plan().splits(); + assertThat(splits).hasSize(1); + assertThat(((IndexedSplit) splits.get(0)).rowRanges()) + .containsExactly(new Range(0, 2), new Range(6, 8)); + assertThat(collect(diff(table, "3,5"))) + .containsExactlyInAnyOrder( + row(0, "untouched", "new"), + row(1, "untouched", "new"), + row(2, "untouched", "new"), + row(6, "untouched", "new"), + row(7, "untouched", "new"), + row(8, "untouched", "new")); + assertThat( + collect( + diff(table, "3,5") + .withRowRanges(Collections.singletonList(new Range(1, 7))))) + .containsExactlyInAnyOrder( + row(1, "untouched", "new"), + row(2, "untouched", "new"), + row(6, "untouched", "new"), + row(7, "untouched", "new")); + assertThat( + collect( + diff(table, "3,5") + .withRowRanges( + Arrays.asList(new Range(1, 1), new Range(7, 7))))) + .containsExactlyInAnyOrder(row(1, "untouched", "new"), row(7, "untouched", "new")); + } + @Test void testDeletedRequestedRowDoesNotReturnAnUnrequestedLiveRow() throws Exception { FileStoreTable table = create(); diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionIncrementalDiffTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionIncrementalDiffTest.scala index ad8011f90675..0aa5a4f76cfc 100644 --- a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionIncrementalDiffTest.scala +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionIncrementalDiffTest.scala @@ -18,12 +18,64 @@ package org.apache.paimon.spark.commands +import org.apache.paimon.data.BinaryRow import org.apache.paimon.spark.PaimonSparkTestBase import org.apache.spark.sql.Row +import scala.collection.JavaConverters._ + class DataEvolutionIncrementalDiffTest extends PaimonSparkTestBase { + test("DE diff preserves file path and physical row index through deletion and filtering") { + withTable("t") { + sql("""CREATE TABLE t (id INT) TBLPROPERTIES ( + |'bucket'='-1','row-tracking.enabled'='true', + |'data-evolution.enabled'='true','deletion-vectors.enabled'='true', + |'write-only'='true')""".stripMargin) + sql("INSERT INTO t VALUES (0)") + val before = loadTable("t").snapshotManager().latestSnapshot().id() + sql("INSERT INTO t SELECT CAST(id AS INT) FROM range(10, 16, 1, 1)") + val table = loadTable("t") + val files = table + .store() + .newScan() + .plan() + .files() + .asScala + .map(_.file()) + .filter(_.nonNullFirstRowId() == 1L) + assert(files.size == 1) + assert(files.head.rowCount() == 6L) + val filePath = table + .store() + .pathFactory() + .createDataFilePathFactory(BinaryRow.EMPTY_ROW, 0) + .toPath(files.head) + .toString + + sql("DELETE FROM t WHERE id=11") + val after = loadTable("t").snapshotManager().latestSnapshot().id() + val diff = spark.read + .option("incremental-between", s"$before,$after") + .option("incremental-between-scan-mode", "diff") + .table("t") + + checkAnswer( + diff.select("id", "__paimon_file_path", "__paimon_row_index"), + Seq( + Row(10, filePath, 0L), + Row(12, filePath, 2L), + Row(13, filePath, 3L), + Row(14, filePath, 4L), + Row(15, filePath, 5L)) + ) + checkAnswer( + diff.where("id IN (12,15)").select("__paimon_file_path", "__paimon_row_index"), + Seq(Row(filePath, 2L), Row(filePath, 5L))) + } + } + test("DE diff preserves untouched columns and deletion visibility after SQL updates") { withTable("t") { sql("""CREATE TABLE t (id INT, a INT, b INT) TBLPROPERTIES ( diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/MultiVectorSearchTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/MultiVectorSearchTest.scala index a23e738e2a44..3b220c719228 100644 --- a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/MultiVectorSearchTest.scala +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/MultiVectorSearchTest.scala @@ -224,6 +224,15 @@ class MultiVectorSearchTest extends PaimonSparkTestBase { assert( spark.sql(search(expr)).collect().map(r => (r.getInt(0), r.getInt(1))).toSeq == Seq((1, 1), (2, 2))) + val scored = spark + .sql(s"""SELECT q.id, r.id, r.__paimon_search_score FROM Q AS q, LATERAL ( + | SELECT id, __paimon_search_score + | FROM vector_search('T', 'chunks', $expr, 1)) AS r + | ORDER BY q.id""".stripMargin) + .collect() + .map(r => (r.getInt(0), r.getInt(1), r.getFloat(2))) + .toSeq + assert(scored == Seq((1, 1, 1f), (2, 2, 1f))) } val error = intercept[IllegalArgumentException] { spark.sql(search("CAST(q.v AS ARRAY)")).queryExecution.analyzed From f54602c46d0428122a7114c3ec88fcec0e4be74f Mon Sep 17 00:00:00 2001 From: yangjiabin <706948683@qq.com> Date: Sat, 21 Nov 2026 00:56:34 +0800 Subject: [PATCH 5/8] [build] Supply shared test fixtures to Spark 4.3 --- paimon-spark/paimon-spark-4.3/pom.xml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/paimon-spark/paimon-spark-4.3/pom.xml b/paimon-spark/paimon-spark-4.3/pom.xml index 201e3d3e31f6..0a75f0ff0fcb 100644 --- a/paimon-spark/paimon-spark-4.3/pom.xml +++ b/paimon-spark/paimon-spark-4.3/pom.xml @@ -108,6 +108,19 @@ under the License. spark-hive_${scala.binary.version} ${spark.version} + + org.apache.paimon + paimon-spark-ut_${scala.binary.version} + ${project.version} + tests + test + + + * + * + + + org.apache.spark spark-sql_${scala.binary.version} From e5c67566ca182e6a7ec631e5c499f3553a3bff79 Mon Sep 17 00:00:00 2001 From: yangjiabin <706948683@qq.com> Date: Sat, 21 Nov 2026 22:12:30 +0800 Subject: [PATCH 6/8] [ci] Retry after JDK download infrastructure failure From 2245fd1f9116e75b33ac86cb38119ad1302ee97b Mon Sep 17 00:00:00 2001 From: yangjiabin <706948683@qq.com> Date: Sun, 22 Nov 2026 22:37:56 +0800 Subject: [PATCH 7/8] [core][spark] Preserve Data Evolution DIFF metadata and DELTA scores --- .../globalindex/DataEvolutionBatchScan.java | 12 ++-- .../operation/DataEvolutionFileStoreScan.java | 9 +++ .../table/source/AbstractBatchTableScan.java | 24 ++++--- .../source/snapshot/SnapshotReaderImpl.java | 6 +- .../DataEvolutionIncrementalDiffTest.java | 68 ++++++++++++++++--- .../apache/paimon/spark/PaimonBaseScan.scala | 12 ++++ .../spark/execution/PaimonStrategy.scala | 2 + .../DataEvolutionIncrementalDiffTest.scala | 30 ++++++++ 8 files changed, 138 insertions(+), 25 deletions(-) diff --git a/paimon-core/src/main/java/org/apache/paimon/globalindex/DataEvolutionBatchScan.java b/paimon-core/src/main/java/org/apache/paimon/globalindex/DataEvolutionBatchScan.java index 245fa1353180..8b16fccd78ab 100644 --- a/paimon-core/src/main/java/org/apache/paimon/globalindex/DataEvolutionBatchScan.java +++ b/paimon-core/src/main/java/org/apache/paimon/globalindex/DataEvolutionBatchScan.java @@ -499,13 +499,12 @@ private boolean queryAuthEnabled() { private Optional evalGlobalIndex() { CoreOptions options = table.coreOptions(); - // Incremental endpoints are resolved by batchScan, not by the independent index scanner. - if (options.startupMode() == CoreOptions.StartupMode.INCREMENTAL) { + boolean incremental = options.startupMode() == CoreOptions.StartupMode.INCREMENTAL; + if (incremental && globalIndexResult != null) { Preconditions.checkArgument( - globalIndexResult == null, - "Unbound global-index results are not supported for incremental reads; " + !batchScan.usesSnapshotDiff(), + "Unbound global-index results are not supported for incremental DIFF reads; " + "use withRowRanges for explicit row-id selections."); - return Optional.empty(); } // the index ranks raw values, which a mask may invalidate; fall back to a full scan. // Checked before the supplied result too: withGlobalIndexResult is public, so a caller @@ -516,7 +515,8 @@ private Optional evalGlobalIndex() { if (this.globalIndexResult != null) { return Optional.of(globalIndexResult); } - if (filter == null) { + // Historical endpoints are resolved by batchScan, separately from automatic index lookup. + if (incremental || filter == null) { return Optional.empty(); } if (!options.globalIndexEnabled()) { diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/DataEvolutionFileStoreScan.java b/paimon-core/src/main/java/org/apache/paimon/operation/DataEvolutionFileStoreScan.java index bed792c99a03..6116ddf5e61c 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/DataEvolutionFileStoreScan.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/DataEvolutionFileStoreScan.java @@ -232,6 +232,15 @@ private boolean filterByStats(List entries) { stats.rowCount(), stats.minValues(), stats.maxValues(), stats.nullCounts()); } + /** Prunes a complete dependency group after identifying the changed RowIDs. */ + public List pruneIncrementalDiffDependencies(List group) { + if (readType != null && readType.containsField(SpecialFields.SEQUENCE_NUMBER.name())) { + // The newest file can supply the sequence number without any projected data columns. + return group; + } + return pruneByReadType(group); + } + /** * Per-file column pruning within a row-id-range group: drop files whose physical columns have * no overlap with the query's {@code readType} or filter. Necessary for columnar-split DE diff --git a/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractBatchTableScan.java b/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractBatchTableScan.java index 0a19f5326ce9..defed821a28f 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractBatchTableScan.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractBatchTableScan.java @@ -27,6 +27,7 @@ import org.apache.paimon.schema.SchemaManager; import org.apache.paimon.schema.TableSchema; import org.apache.paimon.table.BucketMode; +import org.apache.paimon.table.source.snapshot.IncrementalDiffStartingScanner; import org.apache.paimon.table.source.snapshot.SnapshotReader; import org.apache.paimon.table.source.snapshot.StartingScanner; import org.apache.paimon.table.source.snapshot.StartingScanner.ScannedResult; @@ -121,9 +122,7 @@ protected final TableScan.Plan planWithoutAuth() { return preProcessedPlan; } - if (startingScanner == null) { - startingScanner = createStartingScanner(false); - } + StartingScanner scanner = startingScanner(); StartingScanner.Result result; Optional pushed = applyPushDownLimit(); @@ -131,7 +130,7 @@ protected final TableScan.Plan planWithoutAuth() { result = pushed.get(); } else { pushed = applyPushDownTopN(); - result = pushed.orElseGet(() -> startingScanner.scan(snapshotReader)); + result = pushed.orElseGet(() -> scanner.scan(snapshotReader)); } if (result instanceof ScannedResult) { @@ -156,10 +155,7 @@ public List listPartitionEntries() { // it would report partitions the caller cannot read, and pushing a filter on a masked // column against raw partition values would drop partitions the query matches applyAuthRules(); - if (startingScanner == null) { - startingScanner = createStartingScanner(false); - } - return startingScanner.scanPartitions(snapshotReader); + return startingScanner().scanPartitions(snapshotReader); } @Override @@ -168,6 +164,18 @@ public List topNPartitions(int num, int partitionFieldCount) { listPartitionEntries(), schema.logicalPartitionType(), num, partitionFieldCount); } + /** Whether the resolved starting scanner compares two complete snapshots. */ + public boolean usesSnapshotDiff() { + return startingScanner() instanceof IncrementalDiffStartingScanner; + } + + private StartingScanner startingScanner() { + if (startingScanner == null) { + startingScanner = createStartingScanner(false); + } + return startingScanner; + } + private Optional applyPushDownLimit() { // A read-time filter (WHERE or auth) drops rows after scanning, so only push the limit down // when neither is present. diff --git a/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReaderImpl.java b/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReaderImpl.java index 91bc0697f7d1..118d867efe8f 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReaderImpl.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReaderImpl.java @@ -678,6 +678,7 @@ private Plan toDataEvolutionIncrementalPlan( Map>> beforeFiles, FileStoreScan.Plan afterPlan, Map>> afterFiles) { + DataEvolutionFileStoreScan evolutionScan = (DataEvolutionFileStoreScan) scan; Map>> selected = new HashMap<>(); Map, RowRangeIndex> changedRanges = new HashMap<>(); RangeHelper ranges = @@ -700,8 +701,9 @@ private Plan toDataEvolutionIncrementalPlan( } } if (changed) { - // Shared files still supply untouched columns and the current DV anchor. - dependencies.addAll(group); + // Keep changed RowIDs from the full group, even when a changed file + // supplies neither projected columns nor filter columns. + dependencies.addAll(evolutionScan.pruneIncrementalDiffDependencies(group)); } } if (!addedRanges.isEmpty()) { diff --git a/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java b/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java index 3fcc033aec47..4ae6daf09f29 100644 --- a/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java @@ -37,6 +37,7 @@ import org.apache.paimon.globalindex.IndexQuerySplit; import org.apache.paimon.globalindex.IndexedSplit; import org.apache.paimon.globalindex.ScanResult; +import org.apache.paimon.globalindex.ScoredGlobalIndexResult; import org.apache.paimon.globalindex.sorted.SortedGlobalIndexScanner; import org.apache.paimon.globalindex.sorted.SortedGlobalIndexTestUtils; import org.apache.paimon.index.IndexFileMeta; @@ -48,6 +49,7 @@ import org.apache.paimon.manifest.ManifestEntry; import org.apache.paimon.predicate.PredicateBuilder; import org.apache.paimon.reader.RecordReader; +import org.apache.paimon.reader.ScoreRecordIterator; import org.apache.paimon.schema.Schema; import org.apache.paimon.table.sink.BatchTableCommit; import org.apache.paimon.table.sink.BatchTableWrite; @@ -59,6 +61,7 @@ import org.apache.paimon.table.source.Split; import org.apache.paimon.table.source.snapshot.SnapshotReader; import org.apache.paimon.types.DataTypes; +import org.apache.paimon.types.RowType; import org.apache.paimon.utils.InstantiationUtil; import org.apache.paimon.utils.Range; import org.apache.paimon.utils.RangeHelper; @@ -147,6 +150,17 @@ void testPartialUpdatesReconstructUntouchedColumns() throws Exception { .containsExactly(row(0, "name-0", "new-0"), row(1, "name-1", null)); assertThat(collect(diff(table, "1,3").withProjection(new int[] {0}))) .containsExactly(GenericRow.of(0), GenericRow.of(1)); + + RowType tracking = SpecialFields.rowTypeWithRowTracking(table.rowType()); + List projected = + collect( + diff(table, "2,3") + .withReadType( + tracking.project( + Arrays.asList( + "f0", + SpecialFields.SEQUENCE_NUMBER.name())))); + assertThat(projected).containsExactly(GenericRow.of(0, 3L), GenericRow.of(1, 3L)); } @Test @@ -403,20 +417,56 @@ void testHistoricalDiffDoesNotUseALaterGlobalIndex(boolean indexInReader) throws assertThat(collect(latest)).containsExactly(GenericRow.of(200, 30)); } + @ParameterizedTest + @ValueSource(strings = {"delta", "auto"}) + void testDeltaPreservesSuppliedScores(String mode) throws Exception { + FileStoreTable table = create(); + write(table, row(100, "a", "old")); + write(table, row(200, "b", "new"), row(300, "c", "new")); + Map options = new HashMap<>(); + options.put("incremental-between", "1,2"); + options.put("incremental-between-scan-mode", mode); + ReadBuilder builder = table.copy(options).newReadBuilder(); + ScoredGlobalIndexResult result = + ScoredGlobalIndexResult.create( + GlobalIndexResult.fromRange(new Range(2, 2)).results(), id -> 0.42f); + List splits = builder.newScan().withGlobalIndexResult(result).plan().splits(); + assertThat(splits).hasSize(1); + assertThat(((IndexedSplit) splits.get(0)).scores()).containsExactly(0.42f); + assertThat(collect(builder, splits)).containsExactly(row(300, "c", "new")); + try (RecordReader reader = builder.newRead().createReader(splits.get(0))) { + ScoreRecordIterator batch = + (ScoreRecordIterator) reader.readBatch(); + try { + assertThat(batch.next().getInt(0)).isEqualTo(300); + assertThat(batch.returnedRowId()).isEqualTo(2L); + assertThat(batch.returnedScore()).isEqualTo(0.42f); + } finally { + batch.releaseBatch(); + } + } + } + @Test void testIncrementalRejectsUnboundExternalIndexResults() throws Exception { FileStoreTable table = create(); write(table, row(100, "a", "old")); write(table, row(200, "b", "new")); - assertThatThrownBy( - () -> - diff(table, "1,2") - .newScan() - .withGlobalIndexResult(GlobalIndexResult.createEmpty()) - .plan()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("incremental") - .hasMessageContaining("withRowRanges"); + table.createTag("before", 1); + table.createTag("end", 2); + ReadBuilder tagDiff = + table.copy(Collections.singletonMap("incremental-between", "before,end")) + .newReadBuilder(); + for (ReadBuilder builder : Arrays.asList(diff(table, "1,2"), tagDiff)) { + assertThatThrownBy( + () -> + builder.newScan() + .withGlobalIndexResult(GlobalIndexResult.createEmpty()) + .plan()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("incremental DIFF") + .hasMessageContaining("withRowRanges"); + } ReadBuilder latest = table.newReadBuilder(); List selected = latest.newScan() diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonBaseScan.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonBaseScan.scala index 9e1430a03130..97b65955a5a0 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonBaseScan.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonBaseScan.scala @@ -78,6 +78,9 @@ abstract class PaimonBaseScan(table: InnerTable) throw new UnsupportedOperationException( "Cannot push down vector search, hybrid search and full-text search simultaneously.") } + if (globalSearchCount > 0) { + PaimonBaseScan.checkIncrementalSearch(table) + } if (pushedVectorSearch.isDefined) { return evalVectorSearch() } @@ -208,6 +211,15 @@ abstract class PaimonBaseScan(table: InnerTable) object PaimonBaseScan { + private[spark] def checkIncrementalSearch(table: InnerTable): Unit = { + val options = CoreOptions.fromMap(table.options()) + require( + !options + .dataEvolutionEnabled() || options.startupMode() != CoreOptions.StartupMode.INCREMENTAL, + "Spark index search requires a single snapshot for Data Evolution tables." + ) + } + private[spark] def evalVectorSearch( table: InnerTable, vectorSearch: VectorSearch, diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/execution/PaimonStrategy.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/execution/PaimonStrategy.scala index d045281c5acb..9f998a6bb4dc 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/execution/PaimonStrategy.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/execution/PaimonStrategy.scala @@ -25,6 +25,7 @@ import org.apache.paimon.partition.PartitionPredicate import org.apache.paimon.partition.PartitionPredicate.splitPartitionPredicatesAndDataPredicates import org.apache.paimon.predicate.{Predicate, PredicateBuilder} import org.apache.paimon.spark.{PaimonRecordReaderIterator, PaimonScan, PostponeMergeInputScan, PostponeMergeOnRead, SparkCatalog, SparkGenericCatalog, SparkTable, SparkUtils} +import org.apache.paimon.spark.PaimonBaseScan import org.apache.paimon.spark.catalog.{SparkBaseCatalog, SupportView} import org.apache.paimon.spark.catalyst.analysis.ResolvedPaimonView import org.apache.paimon.spark.catalyst.optimizer.PushDownMapSelectedKeys @@ -449,6 +450,7 @@ case class LateralVectorSearchExec( private def createSearchContext( rightProjection: UnsafeProjection, readerTracker: LateralVectorSearchReaderTracker): LateralVectorSearchContext = { + PaimonBaseScan.checkIncrementalSearch(innerTable) val rowType = innerTable.rowType() val readFieldNames = vectorSearchOutput .filterNot( diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionIncrementalDiffTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionIncrementalDiffTest.scala index 0aa5a4f76cfc..b2eb1c53468a 100644 --- a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionIncrementalDiffTest.scala +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionIncrementalDiffTest.scala @@ -76,6 +76,36 @@ class DataEvolutionIncrementalDiffTest extends PaimonSparkTestBase { } } + test("DE diff preserves physical metadata for an untouched column after a partial update") { + withTable("t") { + sql("""CREATE TABLE t (id INT, a INT, b INT) TBLPROPERTIES ( + |'bucket'='-1','row-tracking.enabled'='true', + |'data-evolution.enabled'='true','deletion-vectors.enabled'='true', + |'write-only'='true')""".stripMargin) + sql( + "INSERT INTO t SELECT CAST(id AS INT), CAST(id * 10 AS INT), " + + "CAST(id * 100 AS INT) FROM range(1, 4, 1, 1)") + val before = loadTable("t").snapshotManager().latestSnapshot().id() + val latest = spark.table("t").select("a", "__paimon_file_path", "__paimon_row_index") + val original = latest.orderBy("a").collect() + assert(original.map(_.getLong(2)).toSeq == Seq(0L, 1L, 2L)) + val filePath = original.head.getString(1) + assert(original.forall(_.getString(1) == filePath)) + sql("UPDATE t SET b=b+1") + sql("DELETE FROM t WHERE id=2") + val after = loadTable("t").snapshotManager().latestSnapshot().id() + val diff = spark.read + .option("incremental-between", s"$before,$after") + .option("incremental-between-scan-mode", "diff") + .table("t") + + checkAnswer( + diff.select("a", "__paimon_file_path", "__paimon_row_index"), + Seq(Row(10, filePath, 0L), Row(30, filePath, 2L))) + checkAnswer(diff.select("a", "b"), Seq(Row(10, 101), Row(30, 301))) + } + } + test("DE diff preserves untouched columns and deletion visibility after SQL updates") { withTable("t") { sql("""CREATE TABLE t (id INT, a INT, b INT) TBLPROPERTIES ( From 4f87eb679eaf3fbb1c7775e9b6a429c069af6c59 Mon Sep 17 00:00:00 2001 From: yangjiabin <706948683@qq.com> Date: Mon, 23 Nov 2026 22:55:21 +0800 Subject: [PATCH 8/8] [test] Reuse Data Evolution DIFF fixtures for indexed split checks --- .../IndexedSplitRecordReaderTest.java | 145 ------------------ .../paimon/globalindex/IndexedSplitTest.java | 25 --- .../DataEvolutionIncrementalDiffTest.java | 40 ++++- 3 files changed, 39 insertions(+), 171 deletions(-) diff --git a/paimon-core/src/test/java/org/apache/paimon/globalindex/IndexedSplitRecordReaderTest.java b/paimon-core/src/test/java/org/apache/paimon/globalindex/IndexedSplitRecordReaderTest.java index f75a74a7f86c..695010e4daa0 100644 --- a/paimon-core/src/test/java/org/apache/paimon/globalindex/IndexedSplitRecordReaderTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/globalindex/IndexedSplitRecordReaderTest.java @@ -22,32 +22,16 @@ import org.apache.paimon.data.BinaryString; import org.apache.paimon.data.GenericRow; import org.apache.paimon.data.InternalRow; -import org.apache.paimon.fs.Path; -import org.apache.paimon.fs.local.LocalFileIO; import org.apache.paimon.io.DataFileMeta; import org.apache.paimon.io.DataFileTestUtils; -import org.apache.paimon.predicate.PredicateBuilder; -import org.apache.paimon.reader.FileRecordIterator; import org.apache.paimon.reader.RecordReader; import org.apache.paimon.reader.ScoreRecordIterator; -import org.apache.paimon.reader.ScoreRecordReader; -import org.apache.paimon.schema.FileSystemSchemaManager; -import org.apache.paimon.schema.Schema; -import org.apache.paimon.table.FileStoreTable; -import org.apache.paimon.table.FileStoreTableFactory; -import org.apache.paimon.table.SpecialFields; -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.source.DataSplit; -import org.apache.paimon.table.source.ReadBuilder; -import org.apache.paimon.table.source.Split; import org.apache.paimon.types.DataTypes; import org.apache.paimon.types.RowType; import org.apache.paimon.utils.Range; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; import javax.annotation.Nullable; @@ -63,112 +47,6 @@ /** Test for {@link IndexedSplitRecordReader}. */ public class IndexedSplitRecordReaderTest { - @Test - public void testUnscoredRangeReadPreservesFileMetadata(@TempDir java.nio.file.Path tempDir) - throws Exception { - FileStoreTable table = createDataEvolutionTable(tempDir); - ReadBuilder readBuilder = - table.newReadBuilder() - .withFilter(new PredicateBuilder(table.rowType()).notEqual(0, 12)); - List splits = readBuilder.newScan().plan().splits(); - assertThat(splits).hasSize(1); - DataSplit dataSplit = (DataSplit) splits.get(0); - assertThat(dataSplit.dataFiles()).hasSize(1); - Path expectedPath = - new Path(dataSplit.bucketPath(), dataSplit.dataFiles().get(0).fileName()); - IndexedSplit split = - new IndexedSplit(dataSplit, Arrays.asList(new Range(1, 2), new Range(4, 5)), null); - - List ids = new ArrayList<>(); - List positions = new ArrayList<>(); - try (RecordReader reader = - readBuilder.newRead().executeFilter().createReader(split)) { - RecordReader.RecordIterator batch; - while ((batch = reader.readBatch()) != null) { - try { - assertThat(batch).isInstanceOf(FileRecordIterator.class); - FileRecordIterator fileBatch = - (FileRecordIterator) batch; - assertThat(fileBatch.filePath()).isEqualTo(expectedPath); - InternalRow row; - while ((row = fileBatch.next()) != null) { - ids.add(row.getInt(0)); - positions.add(fileBatch.returnedPosition()); - } - } finally { - batch.releaseBatch(); - } - } - } - assertThat(ids).containsExactly(11, 14, 15); - assertThat(positions).containsExactly(1L, 4L, 5L); - } - - @Test - public void testUnscoredRowIdAndFileMetadataSurviveFilterAndTransform( - @TempDir java.nio.file.Path tempDir) throws Exception { - FileStoreTable table = createDataEvolutionTable(tempDir); - BatchWriteBuilder writeBuilder = table.newBatchWriteBuilder(); - try (BatchTableWrite write = writeBuilder.newWrite(); - BatchTableCommit commit = writeBuilder.newCommit()) { - for (int id = 20; id < 26; id++) { - write.write(GenericRow.of(id)); - } - commit.commit(write.prepareCommit()); - } - - ReadBuilder readBuilder = - table.newReadBuilder() - .withReadType(SpecialFields.rowTypeWithRowId(table.rowType())); - List splits = readBuilder.newScan().plan().splits(); - assertThat(splits).hasSize(1); - DataSplit dataSplit = (DataSplit) splits.get(0); - DataFileMeta file = - dataSplit.dataFiles().stream() - .filter(f -> f.nonNullFirstRowId() == 6L) - .findFirst() - .get(); - Path expectedPath = new Path(dataSplit.bucketPath(), file.fileName()); - IndexedSplit split = - new IndexedSplit( - dataSplit, Arrays.asList(new Range(7, 8), new Range(10, 11)), null); - - List ids = new ArrayList<>(); - List rowIds = new ArrayList<>(); - List positions = new ArrayList<>(); - try (RecordReader reader = readBuilder.newRead().createReader(split)) { - assertThat(reader).isInstanceOf(ScoreRecordReader.class); - RecordReader.RecordIterator batch; - while ((batch = reader.readBatch()) != null) { - RecordReader.RecordIterator projected = - batch.filter(row -> row.getInt(0) != 22) - .transform(row -> GenericRow.of(row.getInt(0) * 10)); - try { - assertThat(projected) - .isInstanceOf(FileRecordIterator.class) - .isInstanceOf(ScoreRecordIterator.class); - FileRecordIterator fileBatch = - (FileRecordIterator) projected; - ScoreRecordIterator scoredBatch = - (ScoreRecordIterator) projected; - assertThat(fileBatch.filePath()).isEqualTo(expectedPath); - InternalRow row; - while ((row = projected.next()) != null) { - ids.add(row.getInt(0)); - rowIds.add(scoredBatch.returnedRowId()); - positions.add(fileBatch.returnedPosition()); - assertThat(Float.isNaN(scoredBatch.returnedScore())).isTrue(); - } - } finally { - projected.releaseBatch(); - } - } - } - assertThat(ids).containsExactly(210, 240, 250); - assertThat(rowIds).containsExactly(7L, 10L, 11L); - assertThat(positions).containsExactly(1L, 4L, 5L); - } - @Test public void testReadWithScores() throws IOException { // Create rows with ROW_ID at position 2 @@ -502,29 +380,6 @@ public void testClose() throws IOException { assertThat(mockReader.isClosed()).isTrue(); } - private FileStoreTable createDataEvolutionTable(java.nio.file.Path tempDir) throws Exception { - Path tablePath = new Path(tempDir.toUri()); - new FileSystemSchemaManager(LocalFileIO.create(), tablePath) - .createTable( - Schema.newBuilder() - .column("id", DataTypes.INT()) - .option("bucket", "-1") - .option("row-tracking.enabled", "true") - .option("data-evolution.enabled", "true") - .option("write-only", "true") - .build()); - FileStoreTable table = FileStoreTableFactory.create(LocalFileIO.create(), tablePath); - BatchWriteBuilder writeBuilder = table.newBatchWriteBuilder(); - try (BatchTableWrite write = writeBuilder.newWrite(); - BatchTableCommit commit = writeBuilder.newCommit()) { - for (int id = 10; id < 16; id++) { - write.write(GenericRow.of(id)); - } - commit.commit(write.prepareCommit()); - } - return table; - } - private IndexedSplit createIndexedSplit(List ranges, @Nullable float[] scores) { DataFileMeta file = DataFileTestUtils.newFile("test-file", 0, 1, 100, 1000L); DataSplit dataSplit = diff --git a/paimon-core/src/test/java/org/apache/paimon/globalindex/IndexedSplitTest.java b/paimon-core/src/test/java/org/apache/paimon/globalindex/IndexedSplitTest.java index 0b3f828a7195..6b50efc61e80 100644 --- a/paimon-core/src/test/java/org/apache/paimon/globalindex/IndexedSplitTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/globalindex/IndexedSplitTest.java @@ -24,7 +24,6 @@ import org.apache.paimon.io.DataInputViewStreamWrapper; import org.apache.paimon.io.DataOutputViewStreamWrapper; import org.apache.paimon.table.source.DataSplit; -import org.apache.paimon.table.source.DeletionFile; import org.apache.paimon.utils.InstantiationUtil; import org.apache.paimon.utils.Range; @@ -195,30 +194,6 @@ public void testRowCount() { assertThat(split3.rowCount()).isEqualTo(1); } - @Test - public void testMergedRowCountWithDeletionVector() throws Exception { - DataSplit.Builder builder = - DataSplit.builder() - .withSnapshot(1L) - .withPartition(BinaryRow.EMPTY_ROW) - .withBucket(0) - .withBucketPath("bucket-0") - .withDataFiles( - Collections.singletonList( - DataFileTestUtils.newFile("file1", 0, 1, 100, 1000L))); - List ranges = Collections.singletonList(new Range(20, 29)); - assertThat(new IndexedSplit(builder.build(), ranges, null).mergedRowCount()).hasValue(10); - builder.withDataDeletionFiles(Collections.singletonList(null)); - assertThat(new IndexedSplit(builder.build(), ranges, null).mergedRowCount()).hasValue(10); - builder.withDataDeletionFiles(Collections.singletonList(new DeletionFile("dv", 0, 10, 1L))); - IndexedSplit split = new IndexedSplit(builder.build(), ranges, null); - assertThat(split.mergedRowCount()).isEmpty(); - IndexedSplit restored = - InstantiationUtil.deserializeObject( - InstantiationUtil.serializeObject(split), getClass().getClassLoader()); - assertThat(restored.mergedRowCount()).isEmpty(); - } - @Test public void testEmptyRanges() throws IOException { DataFileMeta file = DataFileTestUtils.newFile("file1", 0, 1, 100, 1000L); diff --git a/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java b/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java index 1ce7a8de1102..a1a6ace2cc89 100644 --- a/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java @@ -49,8 +49,10 @@ import org.apache.paimon.manifest.IndexManifestEntry; import org.apache.paimon.manifest.ManifestEntry; import org.apache.paimon.predicate.PredicateBuilder; +import org.apache.paimon.reader.FileRecordIterator; import org.apache.paimon.reader.RecordReader; import org.apache.paimon.reader.ScoreRecordIterator; +import org.apache.paimon.reader.ScoreRecordReader; import org.apache.paimon.schema.Schema; import org.apache.paimon.table.sink.BatchTableCommit; import org.apache.paimon.table.sink.BatchTableWrite; @@ -127,6 +129,38 @@ void testSnapshotAndImplicitTagDiffKeepDuplicatesAndNulls() throws Exception { assertThat(collect(table.copy(tags).newReadBuilder())) .containsExactly(row(2, null, "new"), row(2, null, "new")); assertThat(collect(table.newReadBuilder())).hasSize(3); + + ReadBuilder builder = + diff(table, "1,2") + .withReadType( + SpecialFields.rowTypeWithRowId(table.rowType()) + .project(Arrays.asList("f0", SpecialFields.ROW_ID.name()))); + IndexedSplit split = (IndexedSplit) builder.newScan().plan().splits().get(0); + DataSplit data = split.dataSplit(); + Path expectedPath = new Path(data.bucketPath(), data.dataFiles().get(0).fileName()); + try (RecordReader reader = builder.newRead().createReader(split)) { + assertThat(reader).isInstanceOf(ScoreRecordReader.class); + int rowId = builder.readType().getFieldIndex(SpecialFields.ROW_ID.name()); + RecordReader.RecordIterator selected = + reader.readBatch() + .filter(row -> row.getLong(rowId) == 2) + .transform(row -> row.getInt(0)); + try { + assertThat(selected) + .isInstanceOf(FileRecordIterator.class) + .isInstanceOf(ScoreRecordIterator.class); + FileRecordIterator file = (FileRecordIterator) selected; + ScoreRecordIterator score = (ScoreRecordIterator) selected; + assertThat(selected.next()).isEqualTo(2); + assertThat(file.filePath()).isEqualTo(expectedPath); + assertThat(file.returnedPosition()).isEqualTo(1L); + assertThat(score.returnedRowId()).isEqualTo(2L); + assertThat(score.returnedScore()).isNaN(); + assertThat(selected.next()).isNull(); + } finally { + selected.releaseBatch(); + } + } } @Test @@ -527,7 +561,11 @@ void testLimitReadsPastAnEntirelyDeletedSplit() throws Exception { options.put(CoreOptions.SOURCE_SPLIT_TARGET_SIZE.key(), "1 b"); options.put(CoreOptions.SOURCE_SPLIT_OPEN_FILE_COST.key(), "1 b"); table = table.copy(options); - assertThat(diff(table, "2,5").newScan().plan().splits()).hasSize(2); + List splits = diff(table, "2,5").newScan().plan().splits(); + assertThat(splits).hasSize(2); + assertThat(splits) + .anySatisfy(split -> assertThat(split.mergedRowCount()).isEmpty()) + .anySatisfy(split -> assertThat(split.mergedRowCount()).hasValue(1)); assertThat(collect(diff(table, "2,5").withLimit(1))).containsExactly(row(1, "b", "new")); }