From 4a78a8340515a649c4b8050cdb0491175547b3f3 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 13:11:16 -0500 Subject: [PATCH] [IcebergIO] Fix CDC reads on tables with a string primary key A CDC read of a table whose primary key has a string column failed with "ClassCastException: java.nio.HeapCharBuffer cannot be cast to java.lang.String" as soon as one snapshot deleted and added rows in overlapping key ranges, as an upsert or a copy-on-write update or delete does. Iceberg decodes a string column's file bound as a CharBuffer, and the overlap bounds went into the changelog descriptor's Beam Row unchanged, where the String coder failed. Turn a decoded string bound into a String. A string bound may be truncated, to 16 characters by default, but both ends stay conservative, so the overlap check still holds; the OverlapRange comment now says so. The new tests resolve an upsert and a copy-on-write overwrite on a string key alone and on a string and a long, through both the local and the CoGroupByKey resolve paths, and an upsert on keys whose stored bounds are truncated. ChangelogScannerTest no longer hides the CharBuffer behind toString() and round-trips the overlap bounds through the descriptor's coder. --- CHANGES.md | 1 + .../sdk/io/iceberg/cdc/ChangelogScanner.java | 4 + .../beam/sdk/io/iceberg/cdc/OverlapRange.java | 8 +- .../io/iceberg/cdc/ChangelogScannerTest.java | 21 +- .../cdc/IncrementalChangelogSourceTest.java | 196 ++++++++++++++++++ 5 files changed, 224 insertions(+), 6 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 3def22bfb615..a6ebda956ffc 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -188,6 +188,7 @@ * (Python/Dataflow) Fixed metric queries raising `KeyError` when a metric has only tentative or committed data ([#41076](https://github.com/apache/beam/issues/41076)). * (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) Fixed IcebergIO CDC reads failing with a `ClassCastException` on tables with a `string` column in the primary key when a snapshot deletes and adds rows in overlapping key ranges, as an upsert or a copy-on-write update or delete does ([#NNNNN](https://github.com/apache/beam/issues/NNNNN)). * (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) `SklearnModelHandlerPandas` now passes `inference_args` to the model's `predict`, as `SklearnModelHandlerNumpy` does. Before, they were dropped without an error. Both handlers now raise a clear error when `predict` returns several outputs, for example with `return_std=True`, instead of mixing them up across examples ([#41385](https://github.com/apache/beam/issues/41385)). diff --git a/sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/cdc/ChangelogScanner.java b/sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/cdc/ChangelogScanner.java index e7e412dee044..8597f52f19af 100644 --- a/sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/cdc/ChangelogScanner.java +++ b/sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/cdc/ChangelogScanner.java @@ -824,6 +824,10 @@ private static GenericRecord createRecId(Schema recIdSchema, MapBoth 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 - * not symmetric: being over-inclusive only costs extra buffering, since an unmatched record + *

Both ends are inclusive because the bounds come from Iceberg file metrics, making the + * overlap an intersection of two closed ranges. The metrics may be truncated (a string bound to + * 16 characters by default), so a bound need not be an actual PK, but both ends are conservative: + * no PK in the file is below the lower bound or above the upper bound. Note the error directions + * are not symmetric: being over-inclusive only costs extra buffering, since an unmatched record * resolves to the same {@code INSERT} / {@code DELETE} it would have been emitted as, whereas * excluding a boundary PK would split a genuine update into a spurious {@code INSERT} + {@code * DELETE}. diff --git a/sdks/java/io/iceberg/src/test/java/org/apache/beam/sdk/io/iceberg/cdc/ChangelogScannerTest.java b/sdks/java/io/iceberg/src/test/java/org/apache/beam/sdk/io/iceberg/cdc/ChangelogScannerTest.java index afb536278941..328aea183355 100644 --- a/sdks/java/io/iceberg/src/test/java/org/apache/beam/sdk/io/iceberg/cdc/ChangelogScannerTest.java +++ b/sdks/java/io/iceberg/src/test/java/org/apache/beam/sdk/io/iceberg/cdc/ChangelogScannerTest.java @@ -31,7 +31,9 @@ import java.util.Comparator; import java.util.List; import java.util.Map; +import org.apache.beam.sdk.io.iceberg.IcebergUtils; import org.apache.beam.sdk.io.iceberg.SerializableDataFile; +import org.apache.beam.sdk.testing.CoderProperties; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.OutputBuilder; @@ -144,7 +146,7 @@ public void analyzeFilesFindsOverlapDespiteInputOrder() { } @Test - public void analyzeFilesUsesLexicographicCompositePrimaryKeyRanges() { + public void analyzeFilesUsesLexicographicCompositePrimaryKeyRanges() throws Exception { FakeAddedRowsTask insert = new FakeAddedRowsTask( dataFile( @@ -182,10 +184,23 @@ public void analyzeFilesUsesLexicographicCompositePrimaryKeyRanges() { assertThat(result.unidirectional, contains(farDelete)); assertThat(result.bidirectional, containsInAnyOrder(insert, overlappingDelete)); - assertEquals("acct-a", record(result.overlapLower).getField("account").toString()); + assertEquals("acct-a", record(result.overlapLower).getField("account")); assertEquals(5, record(result.overlapLower).getField("sequence")); - assertEquals("acct-a", record(result.overlapUpper).getField("account").toString()); + assertEquals("acct-a", record(result.overlapUpper).getField("account")); assertEquals(8, record(result.overlapUpper).getField("sequence")); + + // the bounds travel to the resolvers in the descriptor + org.apache.beam.sdk.schemas.Schema idBeamSchema = + IcebergUtils.icebergSchemaToBeamSchema(COMPOSITE_RECORD_ID_SCHEMA); + ChangelogDescriptor descriptor = + ChangelogDescriptor.builder() + .setTableIdentifierString("default.table") + .setSnapshotSequenceNumber(1L) + .setCommitSnapshotId(1L) + .setOverlapLower(result.overlapLowerRow(idBeamSchema)) + .setOverlapUpper(result.overlapUpperRow(idBeamSchema)) + .build(); + CoderProperties.coderDecodeEncodeEqual(ChangelogDescriptor.coder(idBeamSchema), descriptor); } @Test 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..71298571967e 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 @@ -33,6 +33,7 @@ import java.util.Arrays; import java.util.List; import java.util.Map; +import java.util.Set; import org.apache.beam.sdk.io.iceberg.IcebergCatalogConfig; import org.apache.beam.sdk.io.iceberg.IcebergIO; import org.apache.beam.sdk.io.iceberg.IcebergIO.ReadRows.StartingStrategy; @@ -54,8 +55,11 @@ 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.ChangelogOperation; +import org.apache.iceberg.ContentFile; import org.apache.iceberg.DataFile; import org.apache.iceberg.DataFiles; import org.apache.iceberg.PartitionSpec; @@ -64,12 +68,14 @@ import org.apache.iceberg.TableProperties; import org.apache.iceberg.catalog.TableIdentifier; import org.apache.iceberg.data.GenericFileWriterFactory; +import org.apache.iceberg.data.GenericRecord; import org.apache.iceberg.data.Record; import org.apache.iceberg.deletes.EqualityDeleteWriter; import org.apache.iceberg.deletes.PositionDelete; import org.apache.iceberg.deletes.PositionDeleteWriter; import org.apache.iceberg.encryption.EncryptedFiles; import org.apache.iceberg.expressions.Literal; +import org.apache.iceberg.types.Conversions; import org.apache.iceberg.types.Types; import org.joda.time.Instant; import org.junit.ClassRule; @@ -112,6 +118,13 @@ public class IncrementalChangelogSourceTest { optional(6, "data", Types.StringType.get())), ImmutableSet.of(1, 2, 3, 4, 5)); + /** Columns for a key of {@code name} alone or of {@code name} and {@code id}. */ + private static final org.apache.iceberg.Schema STRING_KEY_SCHEMA = + new org.apache.iceberg.Schema( + required(1, "name", Types.StringType.get()), + required(2, "id", Types.LongType.get()), + optional(3, "data", Types.StringType.get())); + @ClassRule public static final TemporaryFolder TEMPORARY_FOLDER = new TemporaryFolder(); @Rule public TestDataWarehouse warehouse = new TestDataWarehouse(TEMPORARY_FOLDER, "default"); @@ -483,6 +496,146 @@ public void overwriteUpdatePairsAreResolvedWithinSnapshotWindow() throws Excepti pipeline.run().waitUntilFinish(); } + /** + * An upsert, one row delta of an equality delete and the new row, on a string key alone and on a + * string and a long. Iceberg decodes a string bound as a {@link java.nio.CharBuffer}. + */ + @Test + public void upsertOnStringKeyIsResolvedAsUpdate() throws Exception { + // SPLIT_SIZE=1 resolves the update through the CoGroupByKey, the default resolves it locally. + for (Set key : ImmutableList.of(ImmutableSet.of(1), ImmutableSet.of(1, 2))) { + for (String splitSize : + ImmutableList.of("1", String.valueOf(TableProperties.SPLIT_SIZE_DEFAULT))) { + String name = key.size() + "_key_" + splitSize; + TableIdentifier tableId = + TableIdentifier.of("default", testName.getMethodName() + "_" + name); + Table table = + warehouse.createTable( + tableId, + new org.apache.iceberg.Schema(STRING_KEY_SCHEMA.columns(), key), + null, + ImmutableMap.of( + TableProperties.FORMAT_VERSION, "2", TableProperties.SPLIT_SIZE, splitSize)); + commitAppend( + table, name + "-old.parquet", ImmutableList.of(stringKeyRecord("a", 1L, "before"))); + commitUpsert(table, name + "-new.parquet", stringKeyRecord("a", 1L, "after")); + IcebergScanConfig scanConfig = + baseConfigBuilder(table, tableId) + .setFromSnapshotInclusive(table.currentSnapshot().snapshotId()) + .setToSnapshot(table.currentSnapshot().snapshotId()) + .build(); + PAssert.that( + name, + pipeline + .apply("Read " + name, new IncrementalChangelogSource(scanConfig)) + .apply("Format " + name, ParDo.of(new FormatValueKindAndValues()))) + .containsInAnyOrder("UPDATE_BEFORE:[a, 1, before]", "UPDATE_AFTER:[a, 1, after]"); + } + } + + pipeline.run().waitUntilFinish(); + } + + /** + * A copy-on-write update, one file replacing another, on a string key alone and on a string and a + * long. The bounds come from the data files here, not from an equality delete. + */ + @Test + public void overwriteOnStringKeyIsResolvedAsUpdate() throws Exception { + // SPLIT_SIZE=1 resolves the update through the CoGroupByKey, the default resolves it locally. + for (Set key : ImmutableList.of(ImmutableSet.of(1), ImmutableSet.of(1, 2))) { + for (String splitSize : + ImmutableList.of("1", String.valueOf(TableProperties.SPLIT_SIZE_DEFAULT))) { + String name = key.size() + "_key_" + splitSize; + TableIdentifier tableId = + TableIdentifier.of("default", testName.getMethodName() + "_" + name); + Table table = + warehouse.createTable( + tableId, + new org.apache.iceberg.Schema(STRING_KEY_SCHEMA.columns(), key), + null, + ImmutableMap.of( + TableProperties.FORMAT_VERSION, "2", TableProperties.SPLIT_SIZE, splitSize)); + DataFile oldFile = + commitAppend( + table, + name + "-old.parquet", + ImmutableList.of( + stringKeyRecord("a", 1L, "before"), stringKeyRecord("b", 2L, "same"))); + commitOverwrite( + table, + name + "-new.parquet", + oldFile, + stringKeyRecord("a", 1L, "after"), + stringKeyRecord("b", 2L, "same")); + IcebergScanConfig scanConfig = + baseConfigBuilder(table, tableId) + .setFromSnapshotInclusive(table.currentSnapshot().snapshotId()) + .setToSnapshot(table.currentSnapshot().snapshotId()) + .build(); + PAssert.that( + name, + pipeline + .apply("Read " + name, new IncrementalChangelogSource(scanConfig)) + .apply("Format " + name, ParDo.of(new FormatValueKindAndValues()))) + .containsInAnyOrder("UPDATE_BEFORE:[a, 1, before]", "UPDATE_AFTER:[a, 1, after]"); + } + } + + pipeline.run().waitUntilFinish(); + } + + /** + * An upsert on string keys longer than the 16 characters Iceberg keeps in a string bound by + * default, so the stored upper bound is a bumped prefix, not a key. + */ + @Test + public void upsertOnStringKeyWithTruncatedBoundsIsResolvedAsUpdate() 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, + new org.apache.iceberg.Schema(STRING_KEY_SCHEMA.columns(), ImmutableSet.of(1)), + null, + ImmutableMap.of( + TableProperties.FORMAT_VERSION, "2", TableProperties.SPLIT_SIZE, splitSize)); + commitAppend( + table, + splitSize + "-old.parquet", + ImmutableList.of( + stringKeyRecord("customer-000000000001", 1L, "same"), + stringKeyRecord("customer-000000000002", 2L, "before"))); + commitUpsert( + table, splitSize + "-new.parquet", stringKeyRecord("customer-000000000002", 2L, "after")); + Snapshot upsert = table.currentSnapshot(); + assertEquals( + "customer-0000000..customer-0000001", + nameBounds(Iterables.getOnlyElement(upsert.addedDataFiles(table.io())))); + assertEquals( + "customer-0000000..customer-0000001", + nameBounds(Iterables.getOnlyElement(upsert.addedDeleteFiles(table.io())))); + IcebergScanConfig scanConfig = + baseConfigBuilder(table, tableId) + .setFromSnapshotInclusive(upsert.snapshotId()) + .setToSnapshot(upsert.snapshotId()) + .build(); + PAssert.that( + "split size " + splitSize, + pipeline + .apply("Read " + splitSize, new IncrementalChangelogSource(scanConfig)) + .apply("Format " + splitSize, ParDo.of(new FormatValueKindAndValues()))) + .containsInAnyOrder( + "UPDATE_BEFORE:[customer-000000000002, 2, before]", + "UPDATE_AFTER:[customer-000000000002, 2, after]"); + } + + pipeline.run().waitUntilFinish(); + } + /** A merge-on-read delete is filtered on a partition column that 'keep' leaves out. */ @Test public void mergeOnReadDeleteIsFilteredOnColumnLeftOutOfOutput() throws Exception { @@ -890,6 +1043,34 @@ private void commitPositionDelete(Table table, DataFile file, long position) thr table.refresh(); } + /** Commits one row delta that deletes the row's key with an equality delete and adds the row. */ + private void commitUpsert(Table table, String fileName, Record row) throws IOException { + DataFile file = + warehouse.writeRecords( + testName.getMethodName() + "-" + fileName, table.schema(), ImmutableList.of(row)); + 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(file.location() + ".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().addRows(file).addDeletes(writer.toDeleteFile()).commit(); + table.refresh(); + } + private static List records(long id, String data) { return ImmutableList.of(record(id, data)); } @@ -919,6 +1100,21 @@ private static Record internalFormKeyRecord(int n, String data) { "data", data)); } + private static Record stringKeyRecord(String name, long id, String data) { + return TestFixtures.createRecord( + STRING_KEY_SCHEMA, ImmutableMap.of("name", name, "id", id, "data", data)); + } + + /** The {@code name} column's stored bounds, as {@code lower..upper}. */ + private static String nameBounds(ContentFile file) { + int nameId = STRING_KEY_SCHEMA.findField("name").fieldId(); + CharSequence lower = + Conversions.fromByteBuffer(Types.StringType.get(), file.lowerBounds().get(nameId)); + CharSequence upper = + Conversions.fromByteBuffer(Types.StringType.get(), file.upperBounds().get(nameId)); + return lower + ".." + upper; + } + private static final class FormatValueKindAndRow extends DoFn { @ProcessElement public void process(