From d9fb12eda4ec125f3e619c6245f7e33a3f5c9cf2 Mon Sep 17 00:00:00 2001 From: Ahmed Abualsaud Date: Sun, 22 Nov 2026 22:06:25 -0800 Subject: [PATCH 1/2] [IcebergIO] Compare CDC read primary keys in Iceberg's internal form Iceberg's comparator reads a date key as an Integer, a time or timestamp key as a Long and a fixed key as a ByteBuffer, but generic records hold java.time values and byte arrays. So a CDC read on a date, time, timestamp, timestamptz or fixed key crashed when a snapshot's deletes and inserts overlapped. Without bounds, as with position deletes or metrics turned off, the local resolve path didn't crash, but its map couldn't match equal keys either, so an update came out as a DELETE and an INSERT with no error. Wrap the record's key and the overlap bounds in InternalRecordWrapper before comparing them and before the key goes into the map. --- .../beam/sdk/io/iceberg/cdc/OverlapRange.java | 19 +++-- .../cdc/IncrementalChangelogSourceTest.java | 73 +++++++++++++++++++ 2 files changed, 86 insertions(+), 6 deletions(-) diff --git a/sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/cdc/OverlapRange.java b/sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/cdc/OverlapRange.java index 7de7e13321ce..9a8ee20d8863 100644 --- a/sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/cdc/OverlapRange.java +++ b/sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/cdc/OverlapRange.java @@ -26,7 +26,9 @@ import org.apache.beam.sdk.values.Row; import org.apache.iceberg.Schema; import org.apache.iceberg.StructLike; +import org.apache.iceberg.data.InternalRecordWrapper; import org.apache.iceberg.data.Record; +import org.apache.iceberg.util.StructLikeUtil; import org.apache.iceberg.util.StructProjection; import org.checkerframework.checker.nullness.qual.Nullable; @@ -40,12 +42,15 @@ final class OverlapRange { private final Schema recordIdSchema; private final StructProjection recordIdProjection; + // the PK in Iceberg's internal form (e.g. a date as days since epoch), which idComp expects + private final InternalRecordWrapper recordId; private final Comparator idComp; private OverlapRange( Schema recordIdSchema, StructProjection recordIdProjection, Comparator idComp) { this.recordIdSchema = recordIdSchema; this.recordIdProjection = recordIdProjection; + this.recordId = new InternalRecordWrapper(recordIdSchema.asStruct()); this.idComp = idComp; } @@ -59,8 +64,9 @@ static OverlapRange forScanConfig(IcebergScanConfig scanConfig) { scanConfig.recordIdSchema(), projection, scanConfig.recordIdComparator()); } - StructProjection recordIdProjection() { - return recordIdProjection; + /** The PK of the record last passed to {@link #contains}, in Iceberg's internal form. */ + StructLike recordIdProjection() { + return recordId; } Schema recordIdSchema() { @@ -72,7 +78,9 @@ Schema recordIdSchema() { if (beamBound == null) { return null; } - return IcebergUtils.beamRowToIcebergRecord(recordIdSchema, beamBound); + // copied, so comparisons don't convert the bound again each time + return StructLikeUtil.copy( + recordId.copyFor(IcebergUtils.beamRowToIcebergRecord(recordIdSchema, beamBound))); } /** @@ -90,12 +98,11 @@ Schema recordIdSchema() { *

If either bound is null, we conservatively assume it falls within the overlap. */ boolean contains(Record rec, @Nullable StructLike lower, @Nullable StructLike upper) { - checkStateNotNull(recordIdProjection).wrap(rec); + recordId.wrap(checkStateNotNull(recordIdProjection).wrap(rec)); if (lower == null || upper == null) { return true; } - return idComp.compare(recordIdProjection, lower) >= 0 - && idComp.compare(recordIdProjection, upper) <= 0; + return idComp.compare(recordId, lower) >= 0 && idComp.compare(recordId, upper) <= 0; } } 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 9b4922c2e25f..8680c0fa0604 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 @@ -25,7 +25,10 @@ import static org.junit.Assert.assertEquals; import java.io.IOException; +import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.Arrays; import java.util.List; @@ -94,6 +97,21 @@ public class IncrementalChangelogSourceTest { required(3, "event_time", Types.TimestampType.withoutZone())), ImmutableSet.of(1)); + /** + * A key column of each type that Iceberg compares in its internal form, such as a date as days + * since epoch. + */ + private static final org.apache.iceberg.Schema INTERNAL_FORM_KEY_SCHEMA = + new org.apache.iceberg.Schema( + ImmutableList.of( + required(1, "day", Types.DateType.get()), + required(2, "time", Types.TimeType.get()), + required(3, "ts", Types.TimestampType.withoutZone()), + required(4, "tstz", Types.TimestampType.withZone()), + required(5, "bytes", Types.FixedType.ofLength(2)), + optional(6, "data", Types.StringType.get())), + ImmutableSet.of(1, 2, 3, 4, 5)); + @ClassRule public static final TemporaryFolder TEMPORARY_FOLDER = new TemporaryFolder(); @Rule public TestDataWarehouse warehouse = new TestDataWarehouse(TEMPORARY_FOLDER, "default"); @@ -423,6 +441,45 @@ public void overwriteUpdatePairsAreResolvedWithinSnapshotWindow() throws Excepti PAssert.that(changes).containsInAnyOrder("UPDATE_BEFORE:1:before", "UPDATE_AFTER:1:after"); + // The same update on a key Iceberg compares in its internal form. SPLIT_SIZE=1 resolves it + // through the CoGroupByKey, the default resolves it locally. + for (String splitSize : + ImmutableList.of("1", String.valueOf(TableProperties.SPLIT_SIZE_DEFAULT))) { + TableIdentifier keyedId = + TableIdentifier.of("default", testName.getMethodName() + "_" + splitSize); + Table keyed = + warehouse.createTable( + keyedId, + INTERNAL_FORM_KEY_SCHEMA, + null, + ImmutableMap.of( + TableProperties.FORMAT_VERSION, "2", TableProperties.SPLIT_SIZE, splitSize)); + DataFile oldKeyed = + commitAppend( + keyed, + splitSize + "-old.parquet", + ImmutableList.of( + internalFormKeyRecord(1, "before"), internalFormKeyRecord(2, "same"))); + commitOverwrite( + keyed, + splitSize + "-new.parquet", + oldKeyed, + internalFormKeyRecord(1, "after"), + internalFormKeyRecord(2, "same")); + IcebergScanConfig keyedConfig = + baseConfigBuilder(keyed, keyedId) + .setKeepFields(ImmutableList.of("data")) + .setFromSnapshotInclusive(keyed.currentSnapshot().snapshotId()) + .setToSnapshot(keyed.currentSnapshot().snapshotId()) + .build(); + PAssert.that( + "split size " + splitSize, + pipeline + .apply("Read " + splitSize, new IncrementalChangelogSource(keyedConfig)) + .apply("Format " + splitSize, ParDo.of(new FormatValueKindAndValues()))) + .containsInAnyOrder("UPDATE_BEFORE:[before]", "UPDATE_AFTER:[after]"); + } + pipeline.run().waitUntilFinish(); } @@ -846,6 +903,22 @@ private static Record eventRecord(long id, String data, LocalDateTime eventTime) EVENT_SCHEMA, ImmutableMap.of("id", id, "data", data, "event_time", eventTime)); } + /** + * Every key column grows with {@code n}, so a file's bounds are its first and last keys, and + * comparing a key with its own bound reaches every column. + */ + private static Record internalFormKeyRecord(int n, String data) { + return TestFixtures.createRecord( + INTERNAL_FORM_KEY_SCHEMA, + ImmutableMap.of( + "day", LocalDate.of(2024, 1, n), + "time", LocalTime.of(n, 0), + "ts", LocalDateTime.of(2024, 1, n, 0, 0), + "tstz", OffsetDateTime.of(2024, 1, n, 0, 0, 0, 0, ZoneOffset.UTC), + "bytes", new byte[] {0, (byte) n}, + "data", data)); + } + private static final class FormatValueKindAndRow extends DoFn { @ProcessElement public void process( From a6a1d5a1bf21d98ac088fb12ad19146de650e010 Mon Sep 17 00:00:00 2001 From: Ahmed Abualsaud Date: Fri, 27 Nov 2026 17:18:11 -0800 Subject: [PATCH 2/2] Rename OverlapRange.recordIdProjection() to recordId() and add a CHANGES.md line --- CHANGES.md | 1 + .../apache/beam/sdk/io/iceberg/cdc/LocalResolveDoFn.java | 2 +- .../org/apache/beam/sdk/io/iceberg/cdc/OverlapRange.java | 6 +++--- .../apache/beam/sdk/io/iceberg/cdc/OverlapRangeTest.java | 4 ++-- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index c297265fc5de..36c074e10610 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -161,6 +161,7 @@ * (Python/YAML) Fixed `WindowInto` `'d'` (day) duration unit parsing (`24h` instead of `12h`) and fixed `ExtractWindowingInfo` duplicate field name validation ([#40902](https://github.com/apache/beam/issues/40902)). * (Python) Fixed `GeminiModelHandler` returning only one result per batch: each prompt is now sent as its own request (up to 32 at a time), so every input gets its own result. A custom `request_fn` must now return one response per input ([#40913](https://github.com/apache/beam/issues/40913)). * (Java) IcebergIO now writes `uuid` values as given instead of hashing them, and no longer wraps `Timestamp.MICROS` values outside about 1677 to 2262. This is a breaking change: rows written earlier with this sink will keep the old values, so new CDC writes keyed on a `uuid` column won't match them ([#41250](https://github.com/apache/beam/pull/41250)). +* (Java) Fixed IcebergIO CDC reads on tables with a `date`, `time`, `timestamp`, `timestamptz` or `fixed` column in the primary key, which could crash or split an update into a DELETE and an INSERT ([#41583](https://github.com/apache/beam/pull/41583)). * (Java) BigQuery Storage Write API successful-row output now propagates fused downstream exceptions instead of allowing the bundle to succeed with missing downstream results ([#40004](https://github.com/apache/beam/pull/40004)). * (Python) Fixed `HuggingFaceModelHandlerTensor` passing `inference_args` instead of the device to a custom `inference_fn` ([#41085](https://github.com/apache/beam/issues/41085)). * (Python) The result of `beam.Partition` applied to a list, such as `[1, 2, 3] | beam.Partition(fn, 2)`, can now be indexed with ints (`partitions[0]`) as inside a pipeline, instead of raising `KeyError` ([#19154](https://github.com/apache/beam/issues/19154)). diff --git a/sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/cdc/LocalResolveDoFn.java b/sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/cdc/LocalResolveDoFn.java index 683a7ed86132..d65a61c5eb6f 100644 --- a/sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/cdc/LocalResolveDoFn.java +++ b/sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/cdc/LocalResolveDoFn.java @@ -160,7 +160,7 @@ private void readAndRoute( CdcReadUtils.changelogRecordsForTask(task, table, scanConfig, false)) { for (Record rec : records) { if (ovl.contains(rec, overlapLower, overlapUpper)) { // needs resolution - StructLike pk = StructLikeUtil.copy(ovl.recordIdProjection()); + StructLike pk = StructLikeUtil.copy(ovl.recordId()); PkGroup group = pkGroups.computeIfAbsent(pk, k -> new PkGroup()); if (isInsert) { group.inserts.add(rec); diff --git a/sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/cdc/OverlapRange.java b/sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/cdc/OverlapRange.java index 9a8ee20d8863..d3a6409d773b 100644 --- a/sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/cdc/OverlapRange.java +++ b/sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/cdc/OverlapRange.java @@ -65,7 +65,7 @@ static OverlapRange forScanConfig(IcebergScanConfig scanConfig) { } /** The PK of the record last passed to {@link #contains}, in Iceberg's internal form. */ - StructLike recordIdProjection() { + StructLike recordId() { return recordId; } @@ -85,8 +85,8 @@ Schema recordIdSchema() { /** * Wraps the record to project its Primary Key, then checks if the PK is within the overlap {@code - * [lower, upper]} (inclusive). Can be paired with a subsequent {@link #recordIdProjection()} call - * to fetch the PK value. + * [lower, upper]} (inclusive). Can be paired with a subsequent {@link #recordId()} call to fetch + * the PK value. * *

Both ends are inclusive because the bounds are Iceberg file statistics (actual min/max PK * values), making the overlap an intersection of two closed ranges. Note the error directions are diff --git a/sdks/java/io/iceberg/src/test/java/org/apache/beam/sdk/io/iceberg/cdc/OverlapRangeTest.java b/sdks/java/io/iceberg/src/test/java/org/apache/beam/sdk/io/iceberg/cdc/OverlapRangeTest.java index 69e47182e173..b1842be584ab 100644 --- a/sdks/java/io/iceberg/src/test/java/org/apache/beam/sdk/io/iceberg/cdc/OverlapRangeTest.java +++ b/sdks/java/io/iceberg/src/test/java/org/apache/beam/sdk/io/iceberg/cdc/OverlapRangeTest.java @@ -115,8 +115,8 @@ public void recordIdProjectionUsesIdentifierFieldsFromFullRecord() throws Except assertTrue(range.contains(compositePkRecord("acct", 7), lower, upper)); - assertEquals("acct", range.recordIdProjection().get(0, String.class)); - assertEquals(7, (int) range.recordIdProjection().get(1, Integer.class)); + assertEquals("acct", range.recordId().get(0, String.class)); + assertEquals(7, (int) range.recordId().get(1, Integer.class)); } private OverlapRange overlapRange(org.apache.iceberg.Schema schema) throws IOException {