Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -125,14 +125,16 @@ protected CloseableIterable<ChangelogScanTask> doPlanFiles(
// Build per-snapshot delete file indexes for added deletes
Map<Long, DeleteFileIndex> 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())
Expand All @@ -159,12 +161,16 @@ protected CloseableIterable<ChangelogScanTask> doPlanFiles(
if (cachedExistingDeleteIndex != null) {
return cachedExistingDeleteIndex;
}
return buildExistingDeleteIndexTracked(fromSnapshotIdExclusive);
return buildExistingDeleteIndexTracked(fromSnapshotIdExclusive, toSnapshotIdInclusive);
};

Map<Long, DeleteFileSet> removedDeletesBySnapshot =
buildRemovedDeletesBySnapshot(changelogSnapshots);

// Plan data file tasks (ADDED and DELETED)
Map<Long, List<DeleteFile>> cumulativeDeletesMap =
buildCumulativeDeletesBySnapshot(changelogSnapshots, addedDeletesBySnapshot);
buildCumulativeDeletesBySnapshot(
changelogSnapshots, addedDeletesBySnapshot, removedDeletesBySnapshot);

CloseableIterable<ChangelogScanTask> dataFileTasks =
manifestGroup.plan(
Expand All @@ -179,7 +185,11 @@ protected CloseableIterable<ChangelogScanTask> doPlanFiles(
// Find EXISTING data files affected by newly added delete files and create tasks for them
CloseableIterable<ChangelogScanTask> deletedRowsTasks =
planDeletedRowsTasks(
changelogSnapshots, existingDeleteIndex, addedDeletesBySnapshot, changelogSnapshotIds);
changelogSnapshots,
existingDeleteIndex,
addedDeletesBySnapshot,
removedDeletesBySnapshot,
changelogSnapshotIds);

// Merge tasks from both iterables in order by changeOrdinal
Comparator<ChangelogScanTask> byOrdinal =
Expand Down Expand Up @@ -230,13 +240,21 @@ private static Map<Long, Integer> computeSnapshotOrdinals(Deque<Snapshot> 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<ManifestFile> existingDeleteManifests = fromSnapshot.deleteManifests(table().io());
if (existingDeleteManifests.isEmpty()) {
Expand All @@ -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;
}

Expand Down Expand Up @@ -338,6 +358,7 @@ private CloseableIterable<ChangelogScanTask> planDeletedRowsTasks(
Deque<Snapshot> changelogSnapshots,
DeleteFileIndex existingDeleteIndex,
Map<Long, DeleteFileIndex> addedDeletesBySnapshot,
Map<Long, DeleteFileSet> removedDeletesBySnapshot,
Set<Long> changelogSnapshotIds) {

Map<Long, Integer> snapshotOrdinals = computeSnapshotOrdinals(changelogSnapshots);
Expand All @@ -362,35 +383,40 @@ private CloseableIterable<ChangelogScanTask> 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<String> 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<String> 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);
}
}
}

Expand Down Expand Up @@ -520,29 +546,19 @@ private Expression buildAffectedPartitionExpression(PartitionSet affectedPartiti
* snapshot, PRUNING files that were removed in the middle.
*/
private Map<Long, List<DeleteFile>> buildCumulativeDeletesBySnapshot(
Deque<Snapshot> snapshots, Map<Long, DeleteFileIndex> addedDeletesBySnapshot) {
Deque<Snapshot> snapshots,
Map<Long, DeleteFileIndex> addedDeletesBySnapshot,
Map<Long, DeleteFileSet> removedDeletesBySnapshot) {
Map<Long, List<DeleteFile>> result = Maps.newHashMap();
List<DeleteFile> accumulatedDeletes = Lists.newArrayList();

for (Snapshot snapshot : snapshots) {
// 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<ManifestFile> changedDeletes =
FluentIterable.from(snapshot.deleteManifests(table().io()))
.filter(manifest -> manifest.snapshotId().equals(snapshot.snapshotId()))
.toList();

if (!changedDeletes.isEmpty()) {
Iterable<DeleteFile> removedDeletes =
loadRemovedDeleteFiles(changedDeletes, snapshot.snapshotId());
Set<String> 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());
Expand All @@ -556,6 +572,31 @@ private Map<Long, List<DeleteFile>> 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<Long, DeleteFileSet> buildRemovedDeletesBySnapshot(Deque<Snapshot> snapshots) {
Map<Long, DeleteFileSet> result = Maps.newHashMap();

for (Snapshot snapshot : snapshots) {
DeleteFileSet removedDeletes = DeleteFileSet.create();
List<ManifestFile> 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.
Expand Down
Loading
Loading