diff --git a/docs/docs/multimodal-table/data-evolution.mdx b/docs/docs/multimodal-table/data-evolution.mdx index e9ba024f5ab5..a887f897c755 100644 --- a/docs/docs/multimodal-table/data-evolution.mdx +++ b/docs/docs/multimodal-table/data-evolution.mdx @@ -486,6 +486,28 @@ 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. +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. DIFF rejects unbound external global-index +results. Use `withRowRanges` to select explicit RowIDs in DIFF. DELTA, including +AUTO when it selects DELTA, accepts caller-supplied RowIDs and scores from +an external global-index result. Ordinary snapshot reads retain their index +optimizations. + ## 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/DataEvolutionBatchScan.java b/paimon-core/src/main/java/org/apache/paimon/globalindex/DataEvolutionBatchScan.java index 764720b8eb12..f72dd33054fb 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 @@ -283,11 +283,16 @@ public DataEvolutionBatchScan withGlobalIndexResult(GlobalIndexResult globalInde return this; } - /** Applies a row-ID selection against the snapshot on which it was evaluated. */ + /** Applies a single-snapshot search result, pinning its source snapshot when available. */ public DataEvolutionBatchScan withGlobalIndexResult( - GlobalIndexResult globalIndexResult, Snapshot snapshot) { + GlobalIndexResult globalIndexResult, @Nullable Snapshot snapshot) { + Preconditions.checkArgument( + table.coreOptions().startupMode() != CoreOptions.StartupMode.INCREMENTAL, + "A single-snapshot global-index result cannot replace an incremental scan."); withGlobalIndexResult(globalIndexResult); - batchScan.withStartingSnapshot(snapshot); + if (snapshot != null) { + batchScan.withStartingSnapshot(snapshot); + } return this; } @@ -511,6 +516,14 @@ private boolean queryAuthEnabled() { } private Optional evalGlobalIndex() { + CoreOptions options = table.coreOptions(); + boolean incremental = options.startupMode() == CoreOptions.StartupMode.INCREMENTAL; + if (incremental && globalIndexResult != null) { + Preconditions.checkArgument( + !batchScan.usesSnapshotDiff(), + "Unbound global-index results are not supported for incremental DIFF reads; " + + "use withRowRanges for explicit row-id selections."); + } // 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. @@ -523,7 +536,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/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/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/operation/DataEvolutionFileStoreScan.java b/paimon-core/src/main/java/org/apache/paimon/operation/DataEvolutionFileStoreScan.java index db85e3d953a1..287f2bbbaa18 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 @@ -143,6 +143,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) { @@ -217,6 +234,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 1ad245039dc1..75de83c7d1c2 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 @@ -29,6 +29,7 @@ import org.apache.paimon.schema.TableSchema; import org.apache.paimon.table.BucketMode; import org.apache.paimon.table.source.snapshot.FullStartingScanner; +import org.apache.paimon.table.source.snapshot.IncrementalDiffStartingScanner; import org.apache.paimon.table.source.snapshot.ReadPlanStartingScanner; import org.apache.paimon.table.source.snapshot.SnapshotReader; import org.apache.paimon.table.source.snapshot.StartingScanner; @@ -115,15 +116,12 @@ public InnerTableScan withTopN(TopN topN) { /** Selects the snapshot for a single-snapshot scan before planning its data splits. */ @Nullable public Snapshot prepareSnapshot() { - if (startingScanner == null) { - startingScanner = createStartingScanner(false); - } - if (!(startingScanner instanceof ReadPlanStartingScanner)) { + StartingScanner scanner = startingScanner(); + if (!(scanner instanceof ReadPlanStartingScanner)) { return null; } - SnapshotReader configured = - ((ReadPlanStartingScanner) startingScanner).prepareRead(snapshotReader); + SnapshotReader configured = ((ReadPlanStartingScanner) scanner).prepareRead(snapshotReader); return configured == null ? null : configured.specifiedSnapshot(); } @@ -144,9 +142,7 @@ protected final TableScan.Plan planWithoutAuth() { return preProcessedPlan; } - if (startingScanner == null) { - startingScanner = createStartingScanner(false); - } + StartingScanner scanner = startingScanner(); StartingScanner.Result result; Optional pushed = applyPushDownLimit(); @@ -154,7 +150,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) { @@ -179,10 +175,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 @@ -191,6 +184,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 3a59d94f4877..8422f6d15bb2 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; @@ -107,6 +110,7 @@ public class SnapshotReaderImpl implements SnapshotReader { private ScanMode scanMode = ScanMode.ALL; @Nullable private Snapshot specifiedSnapshot; private boolean hasNonPartitionFilter; + @Nullable private RowRangeIndex rowRangeIndex; private RecordComparator lazyPartitionComparator; private CacheMetrics dvMetaCacheMetrics; @@ -341,12 +345,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; } @@ -648,13 +655,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), @@ -664,6 +675,81 @@ 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) { + DataEvolutionFileStoreScan evolutionScan = (DataEvolutionFileStoreScan) scan; + Map>> selected = new HashMap<>(); + Map, RowRangeIndex> 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) { + // 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()) { + selected.computeIfAbsent(part.getKey(), ignored -> new HashMap<>()) + .put(bucket.getKey(), dependencies); + changedRanges.put( + Pair.of(part.getKey(), bucket.getKey()), + RowRangeIndex.create(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())); + 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)); + } + } + 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/table/DataEvolutionIncrementalDiffTest.java b/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java new file mode 100644 index 000000000000..a1a6ace2cc89 --- /dev/null +++ b/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalDiffTest.java @@ -0,0 +1,695 @@ +/* + * 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.Snapshot; +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.globalindex.DataEvolutionBatchScan; +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.ScoredGlobalIndexResult; +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; +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.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; +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.types.RowType; +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; +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; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** 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); + + 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 + 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)); + + 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 + 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)); + 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 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(); + 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)); + } + + @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")); + 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"); + } + DataEvolutionBatchScan diffScan = (DataEvolutionBatchScan) diff(table, "1,2").newScan(); + assertThatThrownBy( + () -> + diffScan.withGlobalIndexResult( + GlobalIndexResult.createEmpty(), + table.snapshotManager().snapshot(2))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("cannot replace an incremental scan"); + assertThatThrownBy( + () -> diffScan.withGlobalIndexResult(GlobalIndexResult.createEmpty(), null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("cannot replace an incremental scan"); + 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 + 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); + 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")); + } + + @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 { + 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( + 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-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 2358e02c6f19..e768b12d898f 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 @@ -216,7 +216,7 @@ object PaimonBaseScan { scan: InnerTableScan, result: GlobalIndexResult, snapshot: Snapshot): InnerTableScan = scan match { - case dataEvolution: DataEvolutionBatchScan if snapshot != null => + case dataEvolution: DataEvolutionBatchScan => dataEvolution.withGlobalIndexResult(result, snapshot) case _ => scan.withGlobalIndexResult(result) } 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 79a475ff5258..ba37a8c76d33 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 @@ -449,6 +449,15 @@ case class LateralVectorSearchExec( private def createSearchContext( rightProjection: UnsafeProjection, readerTracker: LateralVectorSearchReaderTracker): LateralVectorSearchContext = { + val metaColumnsOnly = + VectorSearchResultUtils.isVectorSearchMetaOnly(vectorSearchOutput.map(_.name)) + val coreOptions = CoreOptions.fromMap(innerTable.options()) + // Metadata-only results return directly, without the row scan's snapshot validation. + require( + !metaColumnsOnly || !coreOptions.dataEvolutionEnabled() || + coreOptions.startupMode() != CoreOptions.StartupMode.INCREMENTAL, + "Spark index search requires a single snapshot for Data Evolution tables." + ) val rowType = innerTable.rowType() val readFieldNames = vectorSearchOutput .filterNot( @@ -489,8 +498,7 @@ case class LateralVectorSearchExec( pushSearchFilters(Seq(readBuilder, physicalReadBuilder), vectorSearchBuilder) val vectorPlan = vectorSearchBuilder.newVectorScan().scan() - val batchSize = - Math.max(1, new CoreOptions(innerTable.options()).vectorSearchLateralJoinBatchSize()) + val batchSize = Math.max(1, coreOptions.vectorSearchLateralJoinBatchSize()) LateralVectorSearchContext( readBuilder, @@ -500,8 +508,7 @@ case class LateralVectorSearchExec( scoreMetadataColumns, sparkRow, rowIdOrdinal = resultRowType.getFieldIndex(SpecialFields.ROW_ID.name()), - metaColumnsOnly = - VectorSearchResultUtils.isVectorSearchMetaOnly(vectorSearchOutput.map(_.name)), + metaColumnsOnly = metaColumnsOnly, projectionInputOrdinals = vectorSearchOutput.map { attr => if (attr.name == PaimonMetadataColumn.SEARCH_SCORE_COLUMN) { 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..8871332f4b10 --- /dev/null +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionIncrementalDiffTest.scala @@ -0,0 +1,113 @@ +/* + * 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.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 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))) + val survivors = Seq(Row(1, 10, 101), Row(3, 30, 301)) + checkAnswer(diff, survivors) + checkAnswer(diff.where("b=101").select("a"), Seq(Row(10))) + checkAnswer(diff.orderBy("id").limit(1), survivors.take(1)) + assert(diff.limit(1).collect().length == 1) + checkAnswer(sql("SELECT * FROM t"), survivors) + } + } +} 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 562a0a9654f7..48601e55785e 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 @@ -28,7 +28,7 @@ import org.apache.paimon.fs.{Path, SeekableInputStream} import org.apache.paimon.fs.local.LocalFileIO import org.apache.paimon.index.IndexFileMeta import org.apache.paimon.io.{CompactIncrement, DataFileMeta} -import org.apache.paimon.manifest.FileSource +import org.apache.paimon.manifest.{FileKind, FileSource} import org.apache.paimon.operation.LocalOrphanFilesClean import org.apache.paimon.operation.commit.DataEvolutionRowRangeConflictException import org.apache.paimon.partition.PartitionPredicate @@ -40,7 +40,7 @@ import org.apache.paimon.spark.utils.SparkProcedureUtils import org.apache.paimon.table.{AppendOnlyFileStoreTable, FileStoreTable} import org.apache.paimon.table.BucketMode.UNAWARE_BUCKET import org.apache.paimon.table.sink.{CommitMessage, CommitMessageImpl, TableCommitImpl} -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 @@ -3326,7 +3326,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(""" @@ -3338,16 +3337,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. */ @@ -3355,7 +3345,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""" @@ -3367,14 +3356,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 } 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..868766d8ac8e 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 @@ -217,13 +217,14 @@ class MultiVectorSearchTest extends PaimonSparkTestBase { spark.sql("CREATE TABLE Q (id INT, v ARRAY)") spark.sql("INSERT INTO Q VALUES (1, array(1D, 0D)), (2, array(0D, 1D))") def search(expr: String) = - s"""SELECT q.id, r.id FROM Q AS q, LATERAL ( - | SELECT id FROM vector_search('T', 'chunks', $expr, 1)) AS r ORDER BY q.id""".stripMargin + 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 Seq("q.v", "CAST(q.v AS ARRAY)").foreach { expr => + val rows = spark.sql(search(expr)).collect() assert( - spark.sql(search(expr)).collect().map(r => (r.getInt(0), r.getInt(1))).toSeq == - Seq((1, 1), (2, 2))) + rows.map(r => (r.getInt(0), r.getInt(1), r.getFloat(2))).toSeq == + Seq((1, 1, 1f), (2, 2, 1f))) } val error = intercept[IllegalArgumentException] { spark.sql(search("CAST(q.v AS ARRAY)")).queryExecution.analyzed