From 3ae4bf4da8a42f8509950693442f0d2a7ae06dc9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 13:58:32 -0500 Subject: [PATCH] [IcebergIO] Stop CDC reads reporting a deleted row as deleted again A CDC read reported a DELETE a second time when a snapshot added a position delete or a deletion vector for a row that an earlier snapshot had already deleted. On format v3 tables this happened on every later delete in the same data file, because a new deletion vector repeats the positions of the one it replaces. On format v2 tables it happened when a writer merged a data file's position deletes into a new file, as Spark does with file-granularity deletes. Next to a merge-on-read update, the repeated row came out as an extra DELETE. The changelog scan read a snapshot's added deletes against the deletes committed before it only when the snapshot added equality deletes. Do it for added deletes of any kind. Those earlier deletes come from the snapshot before the scanned range, and table maintenance may have expired it. The scan then failed with "Cannot find starting snapshot". That already happened for snapshots that add equality deletes or remove a data file, and would now have happened for every snapshot that adds deletes. Log a warning instead and read the snapshot without the earlier deletes, so it may report a row as deleted again. A scan over several snapshots, which the source does not use but the public scan class allows, kept the delete files that a snapshot in the range removed when it read later snapshots. A replaced deletion vector then sat next to its replacement and planning failed with "Can't index multiple DVs". Drop them, as the planning of removed data files already did, and match removed files as Iceberg does, by location, content offset and size, because deletion vectors can share a Puffin file. The tests cover a position delete after an equality delete or after another position delete of the same row, successive deletion vectors alone and in merge-on-read updates through both resolve paths, a v2 position delete file that replaces an earlier one, an identity- partitioned v3 table, a v2 table upgraded to v3, a deletion vector and a file deletion whose parent snapshot has expired, and a scan over several snapshots. --- CHANGES.md | 1 + .../BeamBaseIncrementalChangelogScan.java | 151 ++++--- .../cdc/IncrementalChangelogSourceTest.java | 393 +++++++++++++++++- 3 files changed, 485 insertions(+), 60 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 3def22bfb615..7800ecc2dc23 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -205,6 +205,7 @@ * (Python) Fixed the DataFrame API `skew()` and `kurtosis()` failing with `UnboundLocalError` when all of the data is in one partition ([#41283](https://github.com/apache/beam/issues/41283)). * (Python) Fixed anomaly detection `MajorityVote` ignoring a custom `normal_label` when votes tie: `tie_breaker` now defaults to `normal_label` instead of the constant 0 ([#41232](https://github.com/apache/beam/issues/41232)). * (Java) Fixed IcebergIO's CDC sink and AddFiles ignoring a requested `format-version` when creating tables, and AddFiles failing the run when a file adds a v3-only column to a v2 table ([#41582](https://github.com/apache/beam/pull/41582)). +* (Java) Fixed IcebergIO CDC reads reporting a row as deleted again when a later position delete or deletion vector covers it. This happened on every later delete in the same data file of a format v3 table, and on format v2 tables when a writer merged a data file's position deletes into a new file. CDC reads also no longer fail with "Cannot find starting snapshot" when a snapshot's parent has been expired ([#NNNNN](https://github.com/apache/beam/issues/NNNNN)). * (Python) Fixed `FeastFeatureStoreEnrichmentHandler` crashing with `KeyError` in `get_cache_key` when `entity_row_fn` maps a column to a differently-named entity key, ignoring `exception_level` for missing feature values, and leaking the downloaded feature-store YAML temp file on teardown ([#41347](https://github.com/apache/beam/issues/41347)). * (Python) A multi-model `KeyedModelHandler` now retries a model load that failed. Before, one failed `load_model` call made it reload that model on every batch and fail with a `KeyError` when the model was evicted or updated. Evicting or updating a model that is still loading also no longer fails with a `KeyError` ([#41404](https://github.com/apache/beam/issues/41404)). * (Python) Fixed MLTransform embeddings created with `columns=`, the RAG embedding transforms and `VertexAIMultiModalEmbeddings` modifying their input elements, so that other transforms reading the same PCollection could see the embeddings ([#41233](https://github.com/apache/beam/issues/41233)). diff --git a/sdks/java/io/iceberg/src/main/java/org/apache/iceberg/BeamBaseIncrementalChangelogScan.java b/sdks/java/io/iceberg/src/main/java/org/apache/iceberg/BeamBaseIncrementalChangelogScan.java index 922ef38ae28a..60c4e471ea9d 100644 --- a/sdks/java/io/iceberg/src/main/java/org/apache/iceberg/BeamBaseIncrementalChangelogScan.java +++ b/sdks/java/io/iceberg/src/main/java/org/apache/iceberg/BeamBaseIncrementalChangelogScan.java @@ -28,7 +28,6 @@ import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.Supplier; import java.util.stream.Collectors; -import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.FluentIterable; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Lists; @@ -44,6 +43,7 @@ import org.apache.iceberg.expressions.ResidualEvaluator; import org.apache.iceberg.io.CloseableIterable; import org.apache.iceberg.util.ContentFileUtil; +import org.apache.iceberg.util.DeleteFileSet; import org.apache.iceberg.util.Pair; import org.apache.iceberg.util.PartitionMap; import org.apache.iceberg.util.PartitionSet; @@ -125,14 +125,16 @@ protected CloseableIterable doPlanFiles( // Build per-snapshot delete file indexes for added deletes Map addedDeletesBySnapshot = buildAddedDeleteIndexes(changelogSnapshots); - // Check if existing delete index is needed for equality deletes - boolean hasEqualityDeletes = - addedDeletesBySnapshot.values().stream() - .anyMatch(index -> !index.isEmpty() && index.hasEqualityDeletes()); + // A delete of any kind can name a row that an earlier delete already removed (a deletion vector + // repeats the positions of the one it replaces), so added deletes are read against earlier ones + boolean hasAddedDeletes = + addedDeletesBySnapshot.values().stream().anyMatch(index -> !index.isEmpty()); - // Build existing index early if needed for equality deletes, otherwise use lazy initialization + // Build existing index early if needed for added deletes, otherwise use lazy initialization DeleteFileIndex existingDeleteIndex = - hasEqualityDeletes ? buildExistingDeleteIndexTracked(fromSnapshotIdExclusive) : EMPTY; + hasAddedDeletes + ? buildExistingDeleteIndexTracked(fromSnapshotIdExclusive, toSnapshotIdInclusive) + : EMPTY; ManifestGroup manifestGroup = new ManifestGroup(table().io(), newDataManifests, ImmutableList.of()) @@ -159,12 +161,16 @@ protected CloseableIterable doPlanFiles( if (cachedExistingDeleteIndex != null) { return cachedExistingDeleteIndex; } - return buildExistingDeleteIndexTracked(fromSnapshotIdExclusive); + return buildExistingDeleteIndexTracked(fromSnapshotIdExclusive, toSnapshotIdInclusive); }; + Map removedDeletesBySnapshot = + buildRemovedDeletesBySnapshot(changelogSnapshots); + // Plan data file tasks (ADDED and DELETED) Map> cumulativeDeletesMap = - buildCumulativeDeletesBySnapshot(changelogSnapshots, addedDeletesBySnapshot); + buildCumulativeDeletesBySnapshot( + changelogSnapshots, addedDeletesBySnapshot, removedDeletesBySnapshot); CloseableIterable dataFileTasks = manifestGroup.plan( @@ -179,7 +185,11 @@ protected CloseableIterable doPlanFiles( // Find EXISTING data files affected by newly added delete files and create tasks for them CloseableIterable deletedRowsTasks = planDeletedRowsTasks( - changelogSnapshots, existingDeleteIndex, addedDeletesBySnapshot, changelogSnapshotIds); + changelogSnapshots, + existingDeleteIndex, + addedDeletesBySnapshot, + removedDeletesBySnapshot, + changelogSnapshotIds); // Merge tasks from both iterables in order by changeOrdinal Comparator byOrdinal = @@ -230,13 +240,21 @@ private static Map computeSnapshotOrdinals(Deque snapsh * These deletes should be applied to data files but should not generate DELETE changelog rows. * Uses manifest pruning and caching to optimize performance. */ - private DeleteFileIndex buildExistingDeleteIndex(Long fromSnapshotIdExclusive) { + private DeleteFileIndex buildExistingDeleteIndex( + Long fromSnapshotIdExclusive, long toSnapshotIdInclusive) { if (fromSnapshotIdExclusive == null) { return EMPTY; } Snapshot fromSnapshot = table().snapshot(fromSnapshotIdExclusive); - Preconditions.checkState( - fromSnapshot != null, "Cannot find starting snapshot: %s", fromSnapshotIdExclusive); + // the exclusive start may be the expired parent of the oldest snapshot the table keeps + if (fromSnapshot == null) { + LOG.warn( + "Snapshot {} has expired, so the deletes committed up to it cannot be read. The changes" + + " up to snapshot {} may report a row as deleted again.", + fromSnapshotIdExclusive, + toSnapshotIdInclusive); + return EMPTY; + } List existingDeleteManifests = fromSnapshot.deleteManifests(table().io()); if (existingDeleteManifests.isEmpty()) { @@ -262,12 +280,14 @@ private DeleteFileIndex buildExistingDeleteIndex(Long fromSnapshotIdExclusive) { * Wrapper method that tracks build calls and caches the result for reuse. This ensures we only * build the index once even if called from multiple places. */ - private DeleteFileIndex buildExistingDeleteIndexTracked(Long fromSnapshotIdExclusive) { + private DeleteFileIndex buildExistingDeleteIndexTracked( + Long fromSnapshotIdExclusive, long toSnapshotIdInclusive) { if (cachedExistingDeleteIndex != null) { return cachedExistingDeleteIndex; } existingDeleteIndexBuildCallCount++; - cachedExistingDeleteIndex = buildExistingDeleteIndex(fromSnapshotIdExclusive); + cachedExistingDeleteIndex = + buildExistingDeleteIndex(fromSnapshotIdExclusive, toSnapshotIdInclusive); return cachedExistingDeleteIndex; } @@ -338,6 +358,7 @@ private CloseableIterable planDeletedRowsTasks( Deque changelogSnapshots, DeleteFileIndex existingDeleteIndex, Map addedDeletesBySnapshot, + Map removedDeletesBySnapshot, Set changelogSnapshotIds) { Map snapshotOrdinals = computeSnapshotOrdinals(changelogSnapshots); @@ -362,35 +383,40 @@ private CloseableIterable planDeletedRowsTasks( for (Snapshot snapshot : changelogSnapshots) { DeleteFileIndex addedDeleteIndex = addedDeletesBySnapshot.get(snapshot.snapshotId()); - if (addedDeleteIndex.isEmpty()) { - continue; - } + if (!addedDeleteIndex.isEmpty()) { + // Collect partitions of newly added delete files for pruning (important for the current + // snapshot) + for (DeleteFile df : addedDeleteIndex.referencedDeleteFiles()) { + affectedPartitions.add(df.specId(), df.partition()); + } - // Collect partitions of newly added delete files for pruning (important for the current - // snapshot) - for (DeleteFile df : addedDeleteIndex.referencedDeleteFiles()) { - affectedPartitions.add(df.specId(), df.partition()); + DeleteFileIndex cumulativeDeleteIndex = + buildDeleteIndex(accumulatedDeletes, affectedPartitions); + + // Process data files for this snapshot + // Use a local set per snapshot to track processed files + Set alreadyProcessedPaths = Sets.newHashSet(); + processSnapshotForDeletedRowsTasks( + snapshot, + addedDeleteIndex, + cumulativeDeleteIndex, + fileStatusBySnapshot.get(snapshot.snapshotId()), + alreadyProcessedPaths, + snapshotOrdinals, + affectedPartitions, + tasks); } - DeleteFileIndex cumulativeDeleteIndex = - buildDeleteIndex(accumulatedDeletes, affectedPartitions); - - // Process data files for this snapshot - // Use a local set per snapshot to track processed files - Set alreadyProcessedPaths = Sets.newHashSet(); - processSnapshotForDeletedRowsTasks( - snapshot, - addedDeleteIndex, - cumulativeDeleteIndex, - fileStatusBySnapshot.get(snapshot.snapshotId()), - alreadyProcessedPaths, - snapshotOrdinals, - affectedPartitions, - tasks); + // Later snapshots must not see the deletes this one removed: a replaced deletion vector + // indexed next to its replacement fails the index + DeleteFileSet removedDeletes = removedDeletesBySnapshot.get(snapshot.snapshotId()); + accumulatedDeletes.removeIf(removedDeletes::contains); // Accumulate this snapshot's added deletes for subsequent snapshots - for (DeleteFile df : addedDeleteIndex.referencedDeleteFiles()) { - accumulatedDeletes.add(df); + if (!addedDeleteIndex.isEmpty()) { + for (DeleteFile df : addedDeleteIndex.referencedDeleteFiles()) { + accumulatedDeletes.add(df); + } } } @@ -520,7 +546,9 @@ private Expression buildAffectedPartitionExpression(PartitionSet affectedPartiti * snapshot, PRUNING files that were removed in the middle. */ private Map> buildCumulativeDeletesBySnapshot( - Deque snapshots, Map addedDeletesBySnapshot) { + Deque snapshots, + Map addedDeletesBySnapshot, + Map removedDeletesBySnapshot) { Map> result = Maps.newHashMap(); List accumulatedDeletes = Lists.newArrayList(); @@ -528,21 +556,9 @@ private Map> buildCumulativeDeletesBySnapshot( // Save state first, so that this snapshot's tasks can use any deletes active up to this point result.put(snapshot.snapshotId(), Lists.newArrayList(accumulatedDeletes)); - // Check for removed deletes and prune from accumulatedDeletes for FUTURE snapshots - List changedDeletes = - FluentIterable.from(snapshot.deleteManifests(table().io())) - .filter(manifest -> manifest.snapshotId().equals(snapshot.snapshotId())) - .toList(); - - if (!changedDeletes.isEmpty()) { - Iterable removedDeletes = - loadRemovedDeleteFiles(changedDeletes, snapshot.snapshotId()); - Set removedPaths = Sets.newHashSet(); - for (DeleteFile rdf : removedDeletes) { - removedPaths.add(rdf.location()); - } - accumulatedDeletes.removeIf(df -> removedPaths.contains(df.location())); - } + // Prune removed deletes from accumulatedDeletes for FUTURE snapshots + DeleteFileSet removedDeletes = removedDeletesBySnapshot.get(snapshot.snapshotId()); + accumulatedDeletes.removeIf(removedDeletes::contains); // Add new deletes for FUTURE snapshots DeleteFileIndex addedDeleteIndex = addedDeletesBySnapshot.get(snapshot.snapshotId()); @@ -556,6 +572,31 @@ private Map> buildCumulativeDeletesBySnapshot( return result; } + /** + * Builds a map of snapshot ID -> the delete files that snapshot removed. Deletion vectors can + * share a Puffin file, so files are matched as Iceberg matches them, not by location alone. + */ + private Map buildRemovedDeletesBySnapshot(Deque snapshots) { + Map result = Maps.newHashMap(); + + for (Snapshot snapshot : snapshots) { + DeleteFileSet removedDeletes = DeleteFileSet.create(); + List changedDeletes = + FluentIterable.from(snapshot.deleteManifests(table().io())) + .filter(manifest -> manifest.snapshotId().equals(snapshot.snapshotId())) + .toList(); + + if (!changedDeletes.isEmpty()) { + for (DeleteFile rdf : loadRemovedDeleteFiles(changedDeletes, snapshot.snapshotId())) { + removedDeletes.add(rdf); + } + } + result.put(snapshot.snapshotId(), removedDeletes); + } + + return result; + } + /** * Builds a delete index from the accumulated list of delete files, pruning by affected * partitions. diff --git a/sdks/java/io/iceberg/src/test/java/org/apache/beam/sdk/io/iceberg/cdc/IncrementalChangelogSourceTest.java b/sdks/java/io/iceberg/src/test/java/org/apache/beam/sdk/io/iceberg/cdc/IncrementalChangelogSourceTest.java index 8680c0fa0604..a33fdd1980f9 100644 --- a/sdks/java/io/iceberg/src/test/java/org/apache/beam/sdk/io/iceberg/cdc/IncrementalChangelogSourceTest.java +++ b/sdks/java/io/iceberg/src/test/java/org/apache/beam/sdk/io/iceberg/cdc/IncrementalChangelogSourceTest.java @@ -54,23 +54,42 @@ import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet; +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Lists; +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.primitives.Ints; +import org.apache.iceberg.BeamBaseIncrementalChangelogScan; import org.apache.iceberg.ChangelogOperation; +import org.apache.iceberg.ChangelogScanTask; import org.apache.iceberg.DataFile; import org.apache.iceberg.DataFiles; +import org.apache.iceberg.DeleteFile; +import org.apache.iceberg.DeletedRowsScanTask; +import org.apache.iceberg.ExpireSnapshots; +import org.apache.iceberg.FileContent; +import org.apache.iceberg.FileFormat; +import org.apache.iceberg.FileScanTask; import org.apache.iceberg.PartitionSpec; +import org.apache.iceberg.RowDelta; import org.apache.iceberg.Snapshot; import org.apache.iceberg.Table; import org.apache.iceberg.TableProperties; import org.apache.iceberg.catalog.TableIdentifier; +import org.apache.iceberg.data.BaseDeleteLoader; import org.apache.iceberg.data.GenericFileWriterFactory; +import org.apache.iceberg.data.GenericRecord; import org.apache.iceberg.data.Record; +import org.apache.iceberg.deletes.BaseDVFileWriter; import org.apache.iceberg.deletes.EqualityDeleteWriter; import org.apache.iceberg.deletes.PositionDelete; +import org.apache.iceberg.deletes.PositionDeleteIndex; import org.apache.iceberg.deletes.PositionDeleteWriter; import org.apache.iceberg.encryption.EncryptedFiles; import org.apache.iceberg.expressions.Literal; +import org.apache.iceberg.io.CloseableIterable; +import org.apache.iceberg.io.OutputFileFactory; import org.apache.iceberg.types.Types; +import org.apache.iceberg.util.DeleteFileSet; +import org.checkerframework.checker.nullness.qual.Nullable; import org.joda.time.Instant; import org.junit.ClassRule; import org.junit.Rule; @@ -118,6 +137,8 @@ public class IncrementalChangelogSourceTest { @Rule public TestName testName = new TestName(); @Rule public TestPipeline pipeline = TestPipeline.create(); + private int deleteFiles = 0; + @Test public void boundedSnapshotRangeEmitsOnlyRequestedSnapshotsWithProjectedSchema() throws Exception { @@ -573,6 +594,254 @@ public void nestedEqualityDeleteIsFilteredOnColumnLeftOutOfOutput() throws Excep pipeline.run().waitUntilFinish(); } + /** A position delete of a row that an earlier equality delete removed adds no DELETE. */ + @Test + public void positionDeleteOfRowRemovedByEqualityDeleteIsNotReportedAgain() throws Exception { + TableIdentifier tableId = tableId(); + Table table = warehouse.createTable(tableId, CDC_SCHEMA, null, tableProperties()); + DataFile file = commitAppend(table, "data.parquet", records(1L, "a")); + commitEqualityDelete(table, record(1L, "a")); + commitPositionDelete(table, file, 0L); + + PAssert.that(allChanges(table, tableId)).containsInAnyOrder("INSERT:[1, a]", "DELETE:[1, a]"); + pipeline.run().waitUntilFinish(); + } + + /** A second position delete of a row adds no DELETE. */ + @Test + public void secondPositionDeleteOfSameRowIsNotReportedAgain() throws Exception { + TableIdentifier tableId = tableId(); + Table table = warehouse.createTable(tableId, CDC_SCHEMA, null, tableProperties()); + DataFile file = commitAppend(table, "data.parquet", records(3L, "a")); + commitPositionDelete(table, file, 0L); + commitPositionDelete(table, file, 0L); + + PAssert.that(allChanges(table, tableId)).containsInAnyOrder("INSERT:[3, a]", "DELETE:[3, a]"); + pipeline.run().waitUntilFinish(); + } + + /** + * Format v3 keeps one deletion vector per data file, so a new vector also holds the positions of + * the one it replaces. Only the positions it adds are new deletes. + */ + @Test + public void deletionVectorReportsOnlyTheRowsItAdds() throws Exception { + TableIdentifier tableId = tableId(); + Table table = warehouse.createTable(tableId, CDC_SCHEMA, null, tablePropertiesV3()); + DataFile file = + commitAppend(table, "data.parquet", ImmutableList.of(record(2L, "a"), record(3L, "a"))); + commitDeletionVector(table, file, 0L); + commitDeletionVector(table, file, 1L); + + PAssert.that(allChanges(table, tableId)) + .containsInAnyOrder("INSERT:[2, a]", "INSERT:[3, a]", "DELETE:[2, a]", "DELETE:[3, a]"); + pipeline.run().waitUntilFinish(); + } + + /** + * Two merge-on-read updates of rows in one data file of a format v3 table. The second update's + * deletion vector repeats the first one's position, which must not come out as a DELETE beside + * the update. + */ + @Test + public void deletionVectorUpdateReportsOnlyTheRowItUpdates() throws Exception { + // SPLIT_SIZE=1 resolves the update through the CoGroupByKey, the default resolves it locally. + for (String splitSize : + ImmutableList.of("1", String.valueOf(TableProperties.SPLIT_SIZE_DEFAULT))) { + TableIdentifier tableId = + TableIdentifier.of("default", testName.getMethodName() + "_" + splitSize); + Table table = + warehouse.createTable( + tableId, + CDC_SCHEMA, + null, + ImmutableMap.of( + TableProperties.FORMAT_VERSION, "3", TableProperties.SPLIT_SIZE, splitSize)); + DataFile file = + commitAppend( + table, + splitSize + "-old.parquet", + ImmutableList.of(record(1L, "a"), record(2L, "a"))); + commitDeletionVector(table, file, 0L, record(1L, "b")); + commitDeletionVector(table, file, 1L, record(2L, "b")); + IcebergScanConfig scanConfig = + baseConfigBuilder(table, tableId) + .setFromSnapshotInclusive(table.currentSnapshot().snapshotId()) + .setToSnapshot(table.currentSnapshot().snapshotId()) + .build(); + PAssert.that( + "split size " + splitSize, + pipeline + .apply("Read " + splitSize, new IncrementalChangelogSource(scanConfig)) + .apply("Format " + splitSize, ParDo.of(new FormatValueKindAndValues()))) + .containsInAnyOrder("UPDATE_BEFORE:[2, a]", "UPDATE_AFTER:[2, b]"); + } + + pipeline.run().waitUntilFinish(); + } + + /** + * A format v2 writer with file-granularity deletes, such as Spark's, merges a data file's + * position deletes into a new file that repeats the positions of the file it replaces. + */ + @Test + public void mergedPositionDeleteFileReportsOnlyTheRowsItAdds() throws Exception { + TableIdentifier tableId = tableId(); + Table table = warehouse.createTable(tableId, CDC_SCHEMA, null, tableProperties()); + DataFile file = + commitAppend(table, "data.parquet", ImmutableList.of(record(1L, "a"), record(2L, "a"))); + DeleteFile first = commitPositionDelete(table, file, 0L); + table + .newRowDelta() + .addDeletes(writePositionDeletes(table, file, 0L, 1L)) + .removeDeletes(first) + .commit(); + table.refresh(); + + IcebergScanConfig scanConfig = + baseConfigBuilder(table, tableId) + .setFromSnapshotInclusive(table.currentSnapshot().snapshotId()) + .setToSnapshot(table.currentSnapshot().snapshotId()) + .build(); + PAssert.that( + pipeline + .apply(new IncrementalChangelogSource(scanConfig)) + .apply(ParDo.of(new FormatValueKindAndValues()))) + .containsInAnyOrder("DELETE:[2, a]"); + pipeline.run().waitUntilFinish(); + } + + /** + * Earlier deletes are pruned to the partitions of the new ones, and the vector being replaced + * must survive that beside another partition's vector. + */ + @Test + public void deletionVectorOnPartitionedTableReportsOnlyTheRowsItAdds() throws Exception { + TableIdentifier tableId = tableId(); + PartitionSpec spec = PartitionSpec.builderFor(CDC_SCHEMA).identity("data").build(); + Table table = warehouse.createTable(tableId, CDC_SCHEMA, spec, tablePropertiesV3()); + DataFile fileA = + warehouse.writeRecords( + testName.getMethodName() + "-a.parquet", + table.schema(), + spec, + DataFiles.data(spec, "data=a"), + ImmutableList.of(record(1L, "a"), record(2L, "a"))); + DataFile fileB = + warehouse.writeRecords( + testName.getMethodName() + "-b.parquet", + table.schema(), + spec, + DataFiles.data(spec, "data=b"), + ImmutableList.of(record(3L, "b"), record(4L, "b"))); + table.newFastAppend().appendFile(fileA).appendFile(fileB).commit(); + commitDeletionVector(table, fileA, 0L); + commitDeletionVector(table, fileB, 0L); + commitDeletionVector(table, fileA, 1L); + + PAssert.that(allChanges(table, tableId)) + .containsInAnyOrder( + "INSERT:[1, a]", + "INSERT:[2, a]", + "INSERT:[3, b]", + "INSERT:[4, b]", + "DELETE:[1, a]", + "DELETE:[3, b]", + "DELETE:[2, a]"); + pipeline.run().waitUntilFinish(); + } + + /** + * After an upgrade to format v3, a data file's first deletion vector takes in its v2 position + * deletes. + */ + @Test + public void deletionVectorAfterUpgradeToV3ReportsOnlyTheRowsItAdds() throws Exception { + TableIdentifier tableId = tableId(); + Table table = warehouse.createTable(tableId, CDC_SCHEMA, null, tableProperties()); + DataFile file = + commitAppend(table, "data.parquet", ImmutableList.of(record(1L, "a"), record(2L, "a"))); + commitPositionDelete(table, file, 0L); + table.updateProperties().set(TableProperties.FORMAT_VERSION, "3").commit(); + commitDeletionVector(table, file, 1L); + + PAssert.that(allChanges(table, tableId)) + .containsInAnyOrder("INSERT:[1, a]", "INSERT:[2, a]", "DELETE:[1, a]", "DELETE:[2, a]"); + pipeline.run().waitUntilFinish(); + } + + /** + * Maintenance can expire the parent of the oldest snapshot read, which a scan still names as its + * exclusive start. The deletes committed before it are gone, so the deletion vector's older + * position comes out again. + */ + @Test + public void deletionVectorWhoseParentSnapshotExpiredIsRead() throws Exception { + TableIdentifier tableId = tableId(); + Table table = warehouse.createTable(tableId, CDC_SCHEMA, null, tablePropertiesV3()); + DataFile file = + commitAppend(table, "data.parquet", ImmutableList.of(record(2L, "a"), record(3L, "a"))); + long append = table.currentSnapshot().snapshotId(); + commitDeletionVector(table, file, 0L); + long firstVector = table.currentSnapshot().snapshotId(); + commitDeletionVector(table, file, 1L); + expireSnapshots(table, append, firstVector); + + PAssert.that(allChanges(table, tableId)).containsInAnyOrder("DELETE:[2, a]", "DELETE:[3, a]"); + pipeline.run().waitUntilFinish(); + } + + /** The same for a snapshot that removes a data file, whose earlier deletes are read lazily. */ + @Test + public void fileDeletionWhoseParentSnapshotExpiredIsRead() throws Exception { + TableIdentifier tableId = tableId(); + Table table = warehouse.createTable(tableId, CDC_SCHEMA, null, tableProperties()); + DataFile file = commitAppend(table, "a.parquet", records(1L, "a")); + long first = table.currentSnapshot().snapshotId(); + commitAppend(table, "b.parquet", records(2L, "b")); + long second = table.currentSnapshot().snapshotId(); + table.newDelete().deleteFile(file).commit(); + expireSnapshots(table, first, second); + + PAssert.that(allChanges(table, tableId)).containsInAnyOrder("DELETE:[1, a]"); + pipeline.run().waitUntilFinish(); + } + + /** + * The source scans one snapshot at a time, but the scan is public. Over several snapshots, a + * deletion vector is read against the one it replaces and not against the vectors before it. + */ + @Test + public void scanOverSeveralSnapshotsDropsReplacedDeletionVectors() throws Exception { + Table table = warehouse.createTable(tableId(), CDC_SCHEMA, null, tablePropertiesV3()); + DataFile file = + commitAppend( + table, + "data.parquet", + ImmutableList.of(record(1L, "a"), record(2L, "a"), record(3L, "a"))); + commitDeletionVector(table, file, 0L); + long start = table.currentSnapshot().snapshotId(); + DeleteFile firstVector = + Iterables.getOnlyElement(table.currentSnapshot().addedDeleteFiles(table.io())); + commitDeletionVector(table, file, 1L); + DeleteFile secondVector = + Iterables.getOnlyElement(table.currentSnapshot().addedDeleteFiles(table.io())); + commitDeletionVector(table, file, 2L); + + List existingDeletes = Lists.newArrayList(); + try (CloseableIterable tasks = + new BeamBaseIncrementalChangelogScan(table).fromSnapshotExclusive(start).planFiles()) { + for (ChangelogScanTask task : tasks) { + for (DeleteFile delete : ((DeletedRowsScanTask) task).existingDeletes()) { + existingDeletes.add(delete.location()); + } + } + } + + assertEquals( + ImmutableList.of(firstVector.location(), secondVector.location()), existingDeletes); + } + @Test public void watermarkColumnRestampsProjectedRows() throws Exception { TableIdentifier tableId = tableId(); @@ -838,6 +1107,98 @@ private DataFile commitOverwrite( return file; } + /** Every change from the first snapshot to the current one. */ + private PCollection allChanges(Table table, TableIdentifier tableId) { + IcebergScanConfig scanConfig = + baseConfigBuilder(table, tableId) + .setToSnapshot(table.currentSnapshot().snapshotId()) + .build(); + return pipeline + .apply(new IncrementalChangelogSource(scanConfig)) + .apply(ParDo.of(new FormatValueKindAndValues())); + } + + /** Commits an equality delete of the row's key. */ + private void commitEqualityDelete(Table table, Record row) throws IOException { + org.apache.iceberg.Schema keySchema = + table.schema().select(table.schema().identifierFieldNames()); + EqualityDeleteWriter writer = + new GenericFileWriterFactory.Builder(table) + .equalityFieldIds(Ints.toArray(table.schema().identifierFieldIds())) + .equalityDeleteRowSchema(keySchema) + .build() + .newEqualityDeleteWriter( + EncryptedFiles.plainAsEncryptedOutput( + table + .io() + .newOutputFile( + table + .locationProvider() + .newDataLocation( + testName.getMethodName() + + "-" + + deleteFiles++ + + ".eq-deletes.parquet"))), + table.spec(), + null); + Record key = GenericRecord.create(keySchema); + for (Types.NestedField field : keySchema.columns()) { + key.setField(field.name(), row.getField(field.name())); + } + try (writer) { + writer.write(key); + } + table.newRowDelta().addDeletes(writer.toDeleteFile()).commit(); + table.refresh(); + } + + /** + * Commits a deletion vector for the position, with the rows to add in the same row delta. As + * engines do, the new vector also holds the positions of the file's current position deletes and + * replaces the current vector or file-scoped position delete files. + */ + private void commitDeletionVector(Table table, DataFile file, long position, Record... added) + throws IOException { + table.refresh(); + DeleteFileSet current = DeleteFileSet.create(); + try (CloseableIterable tasks = table.newScan().planFiles()) { + for (FileScanTask task : tasks) { + if (task.file().location().equals(file.location())) { + for (DeleteFile delete : task.deletes()) { + if (delete.content() == FileContent.POSITION_DELETES) { + current.add(delete); + } + } + } + } + } + @Nullable PositionDeleteIndex currentPositions = null; + if (!current.isEmpty()) { + BaseDeleteLoader loader = new BaseDeleteLoader(f -> table.io().newInputFile(f.location())); + currentPositions = loader.loadPositionDeletes(current, file.location()); + } + @Nullable PositionDeleteIndex previous = currentPositions; + BaseDVFileWriter writer = + new BaseDVFileWriter( + OutputFileFactory.builderFor(table, 1, deleteFiles++).format(FileFormat.PUFFIN).build(), + path -> previous); + try (writer) { + writer.delete(file.location(), position, table.spec(), file.partition()); + } + RowDelta delta = table.newRowDelta().validateFromSnapshot(table.currentSnapshot().snapshotId()); + writer.result().deleteFiles().forEach(delta::addDeletes); + writer.result().rewrittenDeleteFiles().forEach(delta::removeDeletes); + if (added.length > 0) { + delta.addRows( + warehouse.writeRecords( + testName.getMethodName() + "-" + deleteFiles++ + "-added.parquet", + table.schema(), + Arrays.asList(added))); + } + delta.commit(); + table.refresh(); + } + private TableIdentifier tableId() { return TableIdentifier.of("default", testName.getMethodName()); } @@ -874,20 +1235,42 @@ private DataFile commitAppend(Table table, String fileName, List records return file; } - private void commitPositionDelete(Table table, DataFile file, long position) throws IOException { + /** Expires the snapshots and keeps their files, so that later snapshots can still be read. */ + private static void expireSnapshots(Table table, long... snapshotIds) { + ExpireSnapshots expire = table.expireSnapshots().cleanExpiredFiles(false); + for (long snapshotId : snapshotIds) { + expire = expire.expireSnapshotId(snapshotId); + } + expire.commit(); + table.refresh(); + } + + private DeleteFile commitPositionDelete(Table table, DataFile file, long position) + throws IOException { + DeleteFile deletes = writePositionDeletes(table, file, position); + table.newRowDelta().addDeletes(deletes).commit(); + table.refresh(); + return deletes; + } + + private DeleteFile writePositionDeletes(Table table, DataFile file, long... positions) + throws IOException { PositionDeleteWriter writer = new GenericFileWriterFactory.Builder(table) .build() .newPositionDeleteWriter( EncryptedFiles.plainAsEncryptedOutput( - table.io().newOutputFile(file.location() + ".deletes.parquet")), + table + .io() + .newOutputFile(file.location() + "-" + deleteFiles++ + ".deletes.parquet")), table.spec(), file.partition()); try (writer) { - writer.write(PositionDelete.create().set(file.location(), position)); + for (long position : positions) { + writer.write(PositionDelete.create().set(file.location(), position)); + } } - table.newRowDelta().addDeletes(writer.toDeleteFile()).commit(); - table.refresh(); + return writer.toDeleteFile(); } private static List records(long id, String data) {