mxm commented on code in PR #18739:
URL: https://github.com/apache/iceberg/pull/18739#discussion_r4751850042
##########
flink/v2.3/flink/src/main/java/org/apache/iceberg/flink/sink/dynamic/CompareSchemasVisitor.java:
##########
@@ -57,11 +57,15 @@ private CompareSchemasVisitor(
public static Result visit(
Schema dataSchema, Schema tableSchema, boolean caseSensitive, boolean
dropUnusedColumns) {
- return visit(
- dataSchema,
- -1,
- new CompareSchemasVisitor(tableSchema, caseSensitive,
dropUnusedColumns),
- new PartnerIdByNameAccessors(tableSchema, caseSensitive));
+ try {
+ return visit(
+ dataSchema,
+ -1,
+ new CompareSchemasVisitor(tableSchema, caseSensitive,
dropUnusedColumns),
+ new PartnerIdByNameAccessors(tableSchema, caseSensitive));
+ } catch (IllegalArgumentException e) {
+ throw new DynamicRecordException(e.getMessage(), e);
Review Comment:
Could we throw `DynamicRecordException` where the conflict is detected,
instead of wrapping every `IllegalArgumentException` of the visit?
##########
flink/v2.3/flink/src/test/java/org/apache/iceberg/flink/sink/dynamic/TestTableUpdater.java:
##########
@@ -514,4 +522,205 @@ void testTableCreatedForCatalogWithoutNamespaceSupport() {
assertThat(catalog.tableExists(tableIdentifier)).isTrue();
}
+
+ @ParameterizedTest
+ @ValueSource(booleans = {DROP_COLUMNS, PRESERVE_COLUMNS})
+ void omittingIdentifierColumnIsRecordException(boolean dropUnusedColumns) {
+ Catalog catalog = CATALOG_EXTENSION.catalog();
+ TableIdentifier tableIdentifier = TableIdentifier.parse("myTable");
+ catalog.createTable(
+ tableIdentifier,
+ new Schema(
+ List.of(
+ Types.NestedField.required(1, "id", Types.IntegerType.get()),
+ Types.NestedField.required(2, "data", Types.StringType.get())),
+ Set.of(2)));
+ TableUpdater tableUpdater = tableUpdater(catalog, dropUnusedColumns);
+
+ assertThatThrownBy(
+ () ->
+ tableUpdater.update(
+ tableIdentifier,
+ SnapshotRef.MAIN_BRANCH,
+ new Schema(Types.NestedField.required(1, "id",
Types.IntegerType.get())),
+ PartitionSpec.unpartitioned(),
+ TableCreator.DEFAULT))
+ .isInstanceOf(DynamicRecordException.class)
+ .hasMessageContaining("identifier field");
+ }
+
+ @Test
+ void makingIdentifierColumnOptionalIsRecordException() {
+ Catalog catalog = CATALOG_EXTENSION.catalog();
+ TableIdentifier tableIdentifier = TableIdentifier.parse("myTable");
+ catalog.createTable(
+ tableIdentifier,
+ new Schema(
+ List.of(
+ Types.NestedField.required(1, "id", Types.IntegerType.get()),
+ Types.NestedField.optional(2, "data", Types.StringType.get())),
+ Set.of(1)));
+ TableUpdater tableUpdater = tableUpdater(catalog, PRESERVE_COLUMNS);
+
+ assertThatThrownBy(
+ () ->
+ tableUpdater.update(
+ tableIdentifier,
+ SnapshotRef.MAIN_BRANCH,
+ SCHEMA,
+ PartitionSpec.unpartitioned(),
+ TableCreator.DEFAULT))
+ .isInstanceOf(DynamicRecordException.class)
+ .hasMessageContaining("not a required field");
+ }
+
+ @Test
+ void changingMapKeyTypeIsRecordException() {
+ Catalog catalog = CATALOG_EXTENSION.catalog();
+ TableIdentifier tableIdentifier = TableIdentifier.parse("myTable");
+ catalog.createTable(
+ tableIdentifier,
+ new Schema(
+ Types.NestedField.optional(
+ 1,
+ "a",
+ Types.MapType.ofOptional(2, 3, Types.IntegerType.get(),
Types.IntegerType.get()))));
+ TableUpdater tableUpdater = tableUpdater(catalog, PRESERVE_COLUMNS);
+
+ assertThatThrownBy(
+ () ->
+ tableUpdater.update(
+ tableIdentifier,
+ SnapshotRef.MAIN_BRANCH,
+ new Schema(
+ Types.NestedField.optional(
+ 1,
+ "a",
+ Types.MapType.ofOptional(
+ 2, 3, Types.LongType.get(),
Types.IntegerType.get()))),
+ PartitionSpec.unpartitioned(),
+ TableCreator.DEFAULT))
+ .isInstanceOf(DynamicRecordException.class)
+ .hasMessageContaining("Cannot update map keys");
+ }
+
+ @Test
+ void addingColumnOfTypeNotSupportedByFormatVersionIsRecordException() {
+ Catalog catalog = CATALOG_EXTENSION.catalog();
+ TableIdentifier tableIdentifier = TableIdentifier.parse("myTable");
+ catalog.createTable(
+ tableIdentifier,
+ new Schema(Types.NestedField.optional(1, "id",
Types.IntegerType.get())),
+ PartitionSpec.unpartitioned(),
+ Map.of(TableProperties.FORMAT_VERSION, "2"));
+ TableUpdater tableUpdater = tableUpdater(catalog, PRESERVE_COLUMNS);
+
+ assertThatThrownBy(
+ () ->
+ tableUpdater.update(
+ tableIdentifier,
+ SnapshotRef.MAIN_BRANCH,
+ new Schema(
+ Types.NestedField.optional(1, "id",
Types.IntegerType.get()),
+ Types.NestedField.optional(2, "payload",
Types.VariantType.get())),
+ PartitionSpec.unpartitioned(),
+ TableCreator.DEFAULT))
+ .isInstanceOf(DynamicRecordException.class)
+ .hasMessageContaining("Invalid schema for v2");
+ }
+
+ @Test
+ void specOnColumnMissingFromTableIsRecordException() {
+ Catalog catalog = CATALOG_EXTENSION.catalog();
+ TableIdentifier tableIdentifier = TableIdentifier.parse("myTable");
+ catalog.createTable(tableIdentifier, SCHEMA);
+ Schema schemaWithExtra =
+ new Schema(
+ Types.NestedField.optional(1, "id", Types.IntegerType.get()),
+ Types.NestedField.optional(2, "data", Types.StringType.get()),
+ Types.NestedField.optional(3, "extra", Types.StringType.get()));
+ TableUpdater tableUpdater = tableUpdater(catalog, PRESERVE_COLUMNS);
+
+ assertThatThrownBy(
+ () ->
+ tableUpdater.update(
+ tableIdentifier,
+ SnapshotRef.MAIN_BRANCH,
+ SCHEMA,
+
PartitionSpec.builderFor(schemaWithExtra).identity("extra").build(),
+ TableCreator.DEFAULT))
+ .isInstanceOf(DynamicRecordException.class)
+ .hasMessageContaining("Cannot find field 'extra'");
+ }
+
+ @Test
+ void commitFailureIsNotRecordException() {
+ CommitFailingCatalog catalog = new CommitFailingCatalog();
+ catalog.initialize("catalog", Map.of());
+ TableIdentifier tableIdentifier = TableIdentifier.of(Namespace.of("db"),
"myTable");
+ catalog.createNamespace(tableIdentifier.namespace());
+ catalog.createTable(tableIdentifier, SCHEMA);
+ catalog.commitFailure = new IllegalStateException("Connection pool shut
down");
Review Comment:
The schema update only wraps `IllegalArgumentException`, so with an
`IllegalStateException` the test still passes if `commit()` moves into the
wrapped block. The REST client can throw `IllegalArgumentException` for an HTTP
400. Should this be:
```suggestion
catalog.commitFailure = new IllegalArgumentException("Malformed
request");
```
##########
flink/v2.3/flink/src/main/java/org/apache/iceberg/flink/sink/dynamic/DynamicRecordExceptionFilter.java:
##########
@@ -0,0 +1,48 @@
+/*
+ * 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.iceberg.flink.sink.dynamic;
+
+import java.io.Serializable;
+import org.apache.flink.annotation.Experimental;
+
+/**
+ * Classifies a failure raised while processing a {@link DynamicRecord} as
divertable or not. Keeps
+ * error handling fail-safe: only failures this filter whitelists are diverted
to the error stream
+ * set via {@link DynamicIcebergSink.Builder#errorStreamConsumer}; every other
failure propagates
+ * and fails the job so Flink's restart strategy can retry it.
+ *
+ * <p>Whitelist only deterministic, record-scoped failures (bad data, for
example a value that
+ * cannot be encoded for its table, or an upsert record whose partition source
is not an equality
+ * field). Return {@code false} for transient or systemic failures (an
unreachable catalog,
+ * object-store errors, an interrupt) so a sustained outage does not silently
drain the whole
+ * stream.
+ */
+@Experimental
+@FunctionalInterface
+public interface DynamicRecordExceptionFilter extends Serializable {
+
+ /**
+ * Classifies a failure as divertable or not.
+ *
+ * @param error the cause thrown while processing a record
+ * @return {@code true} to divert the record, {@code false} to propagate the
failure and fail the
+ * job
+ */
+ boolean shouldDivert(Exception error);
Review Comment:
With the discussion in
https://github.com/apache/iceberg/pull/18739#discussion_r4552292084, the filter
is the remaining on/off switch: `e -> true` still diverts catalog and commit
failures, and none of the tests use `instanceof DynamicRecordException`. Could
we drop `errorStreamFilter` and divert `DynamicRecordException` whenever a
consumer is set?
##########
flink/v2.3/flink/src/main/java/org/apache/iceberg/flink/sink/dynamic/TableUpdater.java:
##########
@@ -153,8 +153,12 @@ private TableMetadataCache.ResolvedSchemaInfo
findOrCreateSchema(
LOG.info(
"Triggering schema update for table {} {} to {}", identifier,
tableSchema, schema);
UpdateSchema updateApi = table.updateSchema();
- EvolveSchemaVisitor.visit(
- identifier, updateApi, tableSchema, schema, caseSensitive,
dropUnusedColumns);
+ try {
+ EvolveSchemaVisitor.visit(
+ identifier, updateApi, tableSchema, schema, caseSensitive,
dropUnusedColumns);
+ } catch (IllegalArgumentException e) {
+ throw new DynamicRecordException(e.getMessage(), e);
Review Comment:
Thanks, classifying by step is much easier to follow. Dropping a partition
source column isn't covered yet (your reply has a placeholder there). With
`drop-unused-columns`, a record without the source column of the current
partition field or sort field still fails in `commit()` with a
`ValidationException`. Could we also bind the current spec and sort order to
the schema from `apply()`, e.g. `table.spec().toUnbound().bind(applied)`, and
catch `ValidationException` like `findOrCreateSpec` does? Leaving out table
creation makes sense, since we can't know the format version before the catalog
creates the table.
##########
flink/v2.3/flink/src/main/java/org/apache/iceberg/flink/sink/dynamic/DataConverter.java:
##########
@@ -64,6 +68,42 @@ static DataConverter identity() {
return object -> object;
}
+ /** Passes data that has the schema of the table on, after checking its
required columns. */
+ static DataConverter identity(Schema tableSchema) {
+ List<Types.NestedField> columns = tableSchema.columns();
+ int count = 0;
+ for (Types.NestedField column : columns) {
+ if (column.isRequired()) {
+ count++;
+ }
+ }
+
+ if (count == 0) {
+ return identity();
+ }
+
+ int[] indices = new int[count];
+ String[] names = new String[count];
+ int next = 0;
+ for (int i = 0; i < columns.size(); i++) {
+ if (columns.get(i).isRequired()) {
+ indices[next] = i;
+ names[next] = columns.get(i).name();
+ next++;
+ }
+ }
+
+ return new RequiredColumnsConverter(indices, names);
+ }
+
+ /**
+ * The writers only read the key of rows that delete, so only rows that
write a record must carry
+ * values for the required columns.
+ */
+ static boolean writesRecord(RowKind kind) {
+ return kind == RowKind.INSERT || kind == RowKind.UPDATE_AFTER;
Review Comment:
Makes sense. A few points for the helper:
1. Could we compute the required column indices once per resolved schema?
This is the hot path, so we shouldn't scan the schema for every record.
2. For an upsert DELETE only the equality fields matter, since the key
writer reads those. We could check just those columns for it.
3. The check covers top-level columns only. That's fine, but let's say so in
the Javadoc.
4. Are we missing `UPDATE_BEFORE` here?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]