You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@iceberg.apache.org by "twthorn (via GitHub)" <gi...@apache.org> on 2026/06/15 21:57:32 UTC

[PR] Kafka Connect: evolve table schema when record schema is updated but value is null [iceberg]

twthorn opened a new pull request, #16826:
URL: https://github.com/apache/iceberg/pull/16826

   ## Description
   
   Fix for kafka-connect sink.
   
   Closes https://github.com/apache/iceberg/issues/15395
   
   When the connect record value is not null, table schema is updated and evolved correctly. However, when connect record value is null, no evolution takes place, causing issues reported in https://github.com/apache/iceberg/issues/15395 and https://github.com/apache/iceberg/issues/16212. Fix this behavior by adding a new method for handling the recursive evolution on the connect record schema (only done once a recursive branch reaches a null value, then this call continues on the evolution on just the remaining nested schema).
   
   ## Verification
   Add tests to verify the behavior including the cases:
   - null value with nested evolved schema
   - list/map of structs with evolution
   - type promotion & optionality change


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] Kafka Connect: evolve table schema when record schema is updated but value is null [iceberg]

Posted by "laskoviymishka (via GitHub)" <gi...@apache.org>.
laskoviymishka commented on code in PR #16826:
URL: https://github.com/apache/iceberg/pull/16826#discussion_r3442536156


##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -268,6 +276,74 @@ private GenericRecord convertToStruct(
     return result;
   }
 
+  /**
+   * This method evolves schemas when the value is null. Note: logic should be kept consistent with

Review Comment:
   This "kept consistent" claim isn't actually true, and that's the part that worries me most.
   
   The non-null `convertToStruct` stops at the first level where it emits an update: once `hasSchemaUpdates` is true it skips `convertValue` entirely, so it never walks the nested children in that pass. Here, after emitting an `updateType` or `makeOptional`, we keep recursing into the subtree in the same pass — so the null path can emit events at multiple nesting levels at once where the non-null path emits one and defers. `testSchemaEvolutionForFieldAndNestedFields` exercises exactly this.
   
   It's not incorrect — `UpdateSchema` is atomic, so the end state is the same — but the comment asserts a parity that doesn't hold, and that's the kind of false invariant a future change will lean on. I'd either make the recursion mirror the non-null path (stop descending once an update fires at this level), or rewrite the Javadoc to describe what this actually does, including the precondition that `schemaUpdateConsumer != null` and that it emits add-column / type-promotion / make-optional. wdyt?



##########
kafka-connect/kafka-connect/src/test/java/org/apache/iceberg/connect/data/TestRecordConverter.java:
##########
@@ -859,6 +859,378 @@ private void assertTypesAddedFromStruct(Function<String, Type> fn) {
     assertThat(fn.apply("ma")).isInstanceOf(MapType.class);
   }
 
+  @Test
+  public void testNestedSchemaEvolutionStructWithNullValue() {
+    org.apache.iceberg.Schema nestedStructSchema =
+        new org.apache.iceberg.Schema(

Review Comment:
   There's no test for the most common null-field case: value is null and the Connect schema matches the table exactly, so nothing should be emitted. That's the path that runs on the majority of sparse records, and the one a false-positive regression (spurious `addColumn`/`updateType`) would hit first.
   
   I'd add one with a table like `{id:int, nested:struct<a:int>}`, a matching Connect schema, the nested value null, and assert `addColumns()`, `updateTypes()`, and `makeOptionals()` are all empty and `result.getField("nested")` is null. Without it, an over-eager emission on null values passes silently.



##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -268,6 +276,74 @@ private GenericRecord convertToStruct(
     return result;
   }
 
+  /**
+   * This method evolves schemas when the value is null. Note: logic should be kept consistent with
+   * equivalent method used when value is not null: {@link #convertToStruct(Struct, StructType, int,
+   * SchemaUpdate.Consumer)}
+   */
+  private void evolveSchemaFromConnectSchema(
+      org.apache.kafka.connect.data.Schema recordSchema,
+      Type tableType,
+      int tableFieldId,
+      SchemaUpdate.Consumer schemaUpdateConsumer) {
+    if (recordSchema == null) {
+      return;
+    }
+    switch (recordSchema.type()) {
+      case STRUCT:

Review Comment:
   Each container branch guards its body with `isStructType()` / `isListType()` / `isMapType()`, so if the Connect schema says STRUCT but the table column is a STRING, the whole body is skipped — no evolution, no exception, nothing logged. The non-null path would eventually throw on that mismatch; here it silently succeeds and the column is written null, so an operator gets schema drift with no signal.
   
   I'd add a `LOG.warn` in the else of each type guard naming the field and the two types. Silent is the wrong default 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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] Kafka Connect: evolve table schema when record schema is updated but value is null [iceberg]

Posted by "twthorn (via GitHub)" <gi...@apache.org>.
twthorn commented on PR #16826:
URL: https://github.com/apache/iceberg/pull/16826#issuecomment-4713016849

   @bryanck would appreciate your eyes as well if you can take a look. Looks like you were a reviewer of the previous PR


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] Kafka Connect: evolve table schema when record schema is updated but value is null [iceberg]

Posted by "twthorn (via GitHub)" <gi...@apache.org>.
twthorn commented on code in PR #16826:
URL: https://github.com/apache/iceberg/pull/16826#discussion_r3431775220


##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -255,19 +255,92 @@ private GenericRecord convertToStruct(
                   }
                 }
                 if (!hasSchemaUpdates) {
-                  result.setField(
-                      tableField.name(),
-                      convertValue(
-                          struct.get(recordField),
-                          tableField.type(),
-                          tableField.fieldId(),
-                          schemaUpdateConsumer));
+                  Object recordFieldValue = struct.get(recordField);
+                  // If the value is null and schema evolution is on, then evolve the table schema
+                  // from the connect record schema
+                  if (recordFieldValue == null && schemaUpdateConsumer != null) {

Review Comment:
   Nice catch, updated so that we evolve the schema even regardless of parent evolution.



##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -255,19 +255,92 @@ private GenericRecord convertToStruct(
                   }
                 }
                 if (!hasSchemaUpdates) {
-                  result.setField(
-                      tableField.name(),
-                      convertValue(
-                          struct.get(recordField),
-                          tableField.type(),
-                          tableField.fieldId(),
-                          schemaUpdateConsumer));
+                  Object recordFieldValue = struct.get(recordField);
+                  // If the value is null and schema evolution is on, then evolve the table schema
+                  // from the connect record schema
+                  if (recordFieldValue == null && schemaUpdateConsumer != null) {
+                    evolveSchemaFromConnectSchema(
+                        recordField.schema(),
+                        tableField.type(),
+                        tableField.fieldId(),
+                        schemaUpdateConsumer);
+                  } else {
+                    // If the value is not null, then convert the value (and handle any schema
+                    // updates)
+                    result.setField(
+                        tableField.name(),
+                        convertValue(
+                            recordFieldValue,
+                            tableField.type(),
+                            tableField.fieldId(),
+                            schemaUpdateConsumer));
+                  }
                 }
               }
             });
     return result;
   }
 
+  private void evolveSchemaFromConnectSchema(
+      org.apache.kafka.connect.data.Schema recordSchema,
+      Type tableType,
+      int tableFieldId,
+      SchemaUpdate.Consumer schemaUpdateConsumer) {
+    if (recordSchema == null) {
+      return;
+    }
+    switch (recordSchema.type()) {
+      case STRUCT:
+        if (tableType.isStructType()) {
+          StructType structType = tableType.asStructType();
+          for (Field field : recordSchema.fields()) {
+            NestedField nestedField = lookupStructField(field.name(), structType, tableFieldId);
+            if (nestedField == null) {
+              String parentFieldName = tableSchema.findColumnName(tableFieldId);

Review Comment:
   Made the change for consistency. Will publish follow up PR to DRY up code to keep things consistent.



##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -255,19 +255,92 @@ private GenericRecord convertToStruct(
                   }
                 }
                 if (!hasSchemaUpdates) {
-                  result.setField(
-                      tableField.name(),
-                      convertValue(
-                          struct.get(recordField),
-                          tableField.type(),
-                          tableField.fieldId(),
-                          schemaUpdateConsumer));
+                  Object recordFieldValue = struct.get(recordField);
+                  // If the value is null and schema evolution is on, then evolve the table schema
+                  // from the connect record schema
+                  if (recordFieldValue == null && schemaUpdateConsumer != null) {
+                    evolveSchemaFromConnectSchema(
+                        recordField.schema(),
+                        tableField.type(),
+                        tableField.fieldId(),
+                        schemaUpdateConsumer);
+                  } else {
+                    // If the value is not null, then convert the value (and handle any schema
+                    // updates)
+                    result.setField(
+                        tableField.name(),
+                        convertValue(
+                            recordFieldValue,
+                            tableField.type(),
+                            tableField.fieldId(),
+                            schemaUpdateConsumer));
+                  }
                 }
               }
             });
     return result;
   }
 
+  private void evolveSchemaFromConnectSchema(

Review Comment:
   Agreed, will put out a follow up PR on this one to align them.



##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -255,19 +255,92 @@ private GenericRecord convertToStruct(
                   }
                 }
                 if (!hasSchemaUpdates) {
-                  result.setField(
-                      tableField.name(),
-                      convertValue(
-                          struct.get(recordField),
-                          tableField.type(),
-                          tableField.fieldId(),
-                          schemaUpdateConsumer));
+                  Object recordFieldValue = struct.get(recordField);
+                  // If the value is null and schema evolution is on, then evolve the table schema
+                  // from the connect record schema
+                  if (recordFieldValue == null && schemaUpdateConsumer != null) {
+                    evolveSchemaFromConnectSchema(
+                        recordField.schema(),
+                        tableField.type(),
+                        tableField.fieldId(),
+                        schemaUpdateConsumer);
+                  } else {
+                    // If the value is not null, then convert the value (and handle any schema
+                    // updates)
+                    result.setField(
+                        tableField.name(),
+                        convertValue(
+                            recordFieldValue,
+                            tableField.type(),
+                            tableField.fieldId(),
+                            schemaUpdateConsumer));
+                  }
                 }
               }
             });
     return result;
   }
 
+  private void evolveSchemaFromConnectSchema(
+      org.apache.kafka.connect.data.Schema recordSchema,
+      Type tableType,
+      int tableFieldId,
+      SchemaUpdate.Consumer schemaUpdateConsumer) {
+    if (recordSchema == null) {
+      return;
+    }
+    switch (recordSchema.type()) {
+      case STRUCT:
+        if (tableType.isStructType()) {
+          StructType structType = tableType.asStructType();
+          for (Field field : recordSchema.fields()) {
+            NestedField nestedField = lookupStructField(field.name(), structType, tableFieldId);
+            if (nestedField == null) {
+              String parentFieldName = tableSchema.findColumnName(tableFieldId);
+              Type type = SchemaUtils.toIcebergType(field.schema(), config);
+              schemaUpdateConsumer.addColumn(parentFieldName, field.name(), type);
+            } else {
+              PrimitiveType evolveDataType =
+                  SchemaUtils.needsDataTypeUpdate(nestedField.type(), field.schema());
+              if (evolveDataType != null) {
+                String fieldName = tableSchema.findColumnName(nestedField.fieldId());
+                schemaUpdateConsumer.updateType(fieldName, evolveDataType);
+              }
+              if (nestedField.isRequired() && field.schema().isOptional()) {

Review Comment:
   Agreed, both should use that config, will handle in that helper method follow up PR.



##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -255,19 +255,92 @@ private GenericRecord convertToStruct(
                   }
                 }
                 if (!hasSchemaUpdates) {
-                  result.setField(
-                      tableField.name(),
-                      convertValue(
-                          struct.get(recordField),
-                          tableField.type(),
-                          tableField.fieldId(),
-                          schemaUpdateConsumer));
+                  Object recordFieldValue = struct.get(recordField);
+                  // If the value is null and schema evolution is on, then evolve the table schema
+                  // from the connect record schema
+                  if (recordFieldValue == null && schemaUpdateConsumer != null) {
+                    evolveSchemaFromConnectSchema(
+                        recordField.schema(),
+                        tableField.type(),
+                        tableField.fieldId(),
+                        schemaUpdateConsumer);
+                  } else {
+                    // If the value is not null, then convert the value (and handle any schema
+                    // updates)
+                    result.setField(
+                        tableField.name(),
+                        convertValue(
+                            recordFieldValue,
+                            tableField.type(),
+                            tableField.fieldId(),
+                            schemaUpdateConsumer));
+                  }
                 }
               }
             });
     return result;
   }
 
+  private void evolveSchemaFromConnectSchema(
+      org.apache.kafka.connect.data.Schema recordSchema,
+      Type tableType,
+      int tableFieldId,
+      SchemaUpdate.Consumer schemaUpdateConsumer) {
+    if (recordSchema == null) {
+      return;
+    }
+    switch (recordSchema.type()) {
+      case STRUCT:
+        if (tableType.isStructType()) {
+          StructType structType = tableType.asStructType();
+          for (Field field : recordSchema.fields()) {
+            NestedField nestedField = lookupStructField(field.name(), structType, tableFieldId);
+            if (nestedField == null) {
+              String parentFieldName = tableSchema.findColumnName(tableFieldId);
+              Type type = SchemaUtils.toIcebergType(field.schema(), config);
+              schemaUpdateConsumer.addColumn(parentFieldName, field.name(), type);
+            } else {
+              PrimitiveType evolveDataType =
+                  SchemaUtils.needsDataTypeUpdate(nestedField.type(), field.schema());
+              if (evolveDataType != null) {
+                String fieldName = tableSchema.findColumnName(nestedField.fieldId());
+                schemaUpdateConsumer.updateType(fieldName, evolveDataType);
+              }
+              if (nestedField.isRequired() && field.schema().isOptional()) {
+                String fieldName = tableSchema.findColumnName(nestedField.fieldId());
+                schemaUpdateConsumer.makeOptional(fieldName);
+              }
+              evolveSchemaFromConnectSchema(
+                  field.schema(), nestedField.type(), nestedField.fieldId(), schemaUpdateConsumer);
+            }
+          }
+        }
+        break;
+      case ARRAY:
+        if (tableType.isListType()) {
+          ListType listType = tableType.asListType();
+          evolveSchemaFromConnectSchema(
+              recordSchema.valueSchema(),
+              listType.elementType(),
+              listType.elementId(),
+              schemaUpdateConsumer);
+        }
+        break;
+      case MAP:

Review Comment:
   Reproduced bug with test, added.



##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -255,19 +255,92 @@ private GenericRecord convertToStruct(
                   }
                 }
                 if (!hasSchemaUpdates) {
-                  result.setField(
-                      tableField.name(),
-                      convertValue(
-                          struct.get(recordField),
-                          tableField.type(),
-                          tableField.fieldId(),
-                          schemaUpdateConsumer));
+                  Object recordFieldValue = struct.get(recordField);
+                  // If the value is null and schema evolution is on, then evolve the table schema
+                  // from the connect record schema
+                  if (recordFieldValue == null && schemaUpdateConsumer != null) {
+                    evolveSchemaFromConnectSchema(
+                        recordField.schema(),
+                        tableField.type(),
+                        tableField.fieldId(),
+                        schemaUpdateConsumer);

Review Comment:
   Updated to maintain existing behavior



##########
kafka-connect/kafka-connect/src/test/java/org/apache/iceberg/connect/data/TestRecordConverter.java:
##########
@@ -859,6 +859,268 @@ private void assertTypesAddedFromStruct(Function<String, Type> fn) {
     assertThat(fn.apply("ma")).isInstanceOf(MapType.class);
   }
 
+  @Test
+  public void testNestedSchemaEvolutionStructWithNullValue() {

Review Comment:
   Updated to assert field value is null.



##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -255,19 +255,92 @@ private GenericRecord convertToStruct(
                   }
                 }
                 if (!hasSchemaUpdates) {
-                  result.setField(
-                      tableField.name(),
-                      convertValue(
-                          struct.get(recordField),
-                          tableField.type(),
-                          tableField.fieldId(),
-                          schemaUpdateConsumer));
+                  Object recordFieldValue = struct.get(recordField);
+                  // If the value is null and schema evolution is on, then evolve the table schema
+                  // from the connect record schema
+                  if (recordFieldValue == null && schemaUpdateConsumer != null) {
+                    evolveSchemaFromConnectSchema(
+                        recordField.schema(),
+                        tableField.type(),
+                        tableField.fieldId(),
+                        schemaUpdateConsumer);
+                  } else {
+                    // If the value is not null, then convert the value (and handle any schema
+                    // updates)
+                    result.setField(
+                        tableField.name(),
+                        convertValue(
+                            recordFieldValue,
+                            tableField.type(),
+                            tableField.fieldId(),
+                            schemaUpdateConsumer));
+                  }
                 }
               }
             });
     return result;
   }
 
+  private void evolveSchemaFromConnectSchema(
+      org.apache.kafka.connect.data.Schema recordSchema,
+      Type tableType,
+      int tableFieldId,
+      SchemaUpdate.Consumer schemaUpdateConsumer) {
+    if (recordSchema == null) {
+      return;
+    }
+    switch (recordSchema.type()) {
+      case STRUCT:
+        if (tableType.isStructType()) {
+          StructType structType = tableType.asStructType();
+          for (Field field : recordSchema.fields()) {
+            NestedField nestedField = lookupStructField(field.name(), structType, tableFieldId);
+            if (nestedField == null) {
+              String parentFieldName = tableSchema.findColumnName(tableFieldId);
+              Type type = SchemaUtils.toIcebergType(field.schema(), config);
+              schemaUpdateConsumer.addColumn(parentFieldName, field.name(), type);
+            } else {
+              PrimitiveType evolveDataType =
+                  SchemaUtils.needsDataTypeUpdate(nestedField.type(), field.schema());
+              if (evolveDataType != null) {
+                String fieldName = tableSchema.findColumnName(nestedField.fieldId());
+                schemaUpdateConsumer.updateType(fieldName, evolveDataType);
+              }
+              if (nestedField.isRequired() && field.schema().isOptional()) {
+                String fieldName = tableSchema.findColumnName(nestedField.fieldId());
+                schemaUpdateConsumer.makeOptional(fieldName);
+              }
+              evolveSchemaFromConnectSchema(
+                  field.schema(), nestedField.type(), nestedField.fieldId(), schemaUpdateConsumer);
+            }
+          }
+        }
+        break;
+      case ARRAY:
+        if (tableType.isListType()) {
+          ListType listType = tableType.asListType();
+          evolveSchemaFromConnectSchema(
+              recordSchema.valueSchema(),
+              listType.elementType(),
+              listType.elementId(),
+              schemaUpdateConsumer);
+        }
+        break;
+      case MAP:
+        if (tableType.isMapType()) {
+          MapType mapType = tableType.asMapType();
+          evolveSchemaFromConnectSchema(
+              recordSchema.valueSchema(),

Review Comment:
   Reproduced with test, fixed



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] Kafka Connect: evolve table schema when record schema is updated but value is null [iceberg]

Posted by "laskoviymishka (via GitHub)" <gi...@apache.org>.
laskoviymishka commented on code in PR #16826:
URL: https://github.com/apache/iceberg/pull/16826#discussion_r3424815257


##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -255,19 +255,92 @@ private GenericRecord convertToStruct(
                   }
                 }
                 if (!hasSchemaUpdates) {
-                  result.setField(
-                      tableField.name(),
-                      convertValue(
-                          struct.get(recordField),
-                          tableField.type(),
-                          tableField.fieldId(),
-                          schemaUpdateConsumer));
+                  Object recordFieldValue = struct.get(recordField);
+                  // If the value is null and schema evolution is on, then evolve the table schema
+                  // from the connect record schema
+                  if (recordFieldValue == null && schemaUpdateConsumer != null) {

Review Comment:
   The null-value evolution only fires inside the `if (!hasSchemaUpdates)` block, so it's suppressed exactly when a field needs both a top-level update and a nested walk.
   
   If `tableField` itself needs a type promotion or required→optional change, `hasSchemaUpdates` is true and this whole branch is skipped — so a record whose field is a null struct carrying a new sub-column (table field FLOAT→DOUBLE, value null, nested schema gained a column) never reaches `evolveSchemaFromConnectSchema` and the addColumn is lost for that cycle. The value path has the same shape, but the null path makes it much likelier to hit in production: a CDC delete nulls every non-PK field precisely when schemas are drifting, so there's no guarantee a later non-null record recovers the missed update.
   
   Lift the null-value call out of the `!hasSchemaUpdates` gate so it always runs when the value is null and a consumer is present. It only queues updates and never touches `result`, so it's safe to run regardless of `hasSchemaUpdates`. This is the one blocker for me.



##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -255,19 +255,92 @@ private GenericRecord convertToStruct(
                   }
                 }
                 if (!hasSchemaUpdates) {
-                  result.setField(
-                      tableField.name(),
-                      convertValue(
-                          struct.get(recordField),
-                          tableField.type(),
-                          tableField.fieldId(),
-                          schemaUpdateConsumer));
+                  Object recordFieldValue = struct.get(recordField);
+                  // If the value is null and schema evolution is on, then evolve the table schema
+                  // from the connect record schema
+                  if (recordFieldValue == null && schemaUpdateConsumer != null) {
+                    evolveSchemaFromConnectSchema(
+                        recordField.schema(),
+                        tableField.type(),
+                        tableField.fieldId(),
+                        schemaUpdateConsumer);
+                  } else {
+                    // If the value is not null, then convert the value (and handle any schema
+                    // updates)
+                    result.setField(
+                        tableField.name(),
+                        convertValue(
+                            recordFieldValue,
+                            tableField.type(),
+                            tableField.fieldId(),
+                            schemaUpdateConsumer));
+                  }
                 }
               }
             });
     return result;
   }
 
+  private void evolveSchemaFromConnectSchema(
+      org.apache.kafka.connect.data.Schema recordSchema,
+      Type tableType,
+      int tableFieldId,
+      SchemaUpdate.Consumer schemaUpdateConsumer) {
+    if (recordSchema == null) {
+      return;
+    }
+    switch (recordSchema.type()) {
+      case STRUCT:
+        if (tableType.isStructType()) {
+          StructType structType = tableType.asStructType();
+          for (Field field : recordSchema.fields()) {
+            NestedField nestedField = lookupStructField(field.name(), structType, tableFieldId);
+            if (nestedField == null) {
+              String parentFieldName = tableSchema.findColumnName(tableFieldId);
+              Type type = SchemaUtils.toIcebergType(field.schema(), config);
+              schemaUpdateConsumer.addColumn(parentFieldName, field.name(), type);
+            } else {
+              PrimitiveType evolveDataType =
+                  SchemaUtils.needsDataTypeUpdate(nestedField.type(), field.schema());
+              if (evolveDataType != null) {
+                String fieldName = tableSchema.findColumnName(nestedField.fieldId());
+                schemaUpdateConsumer.updateType(fieldName, evolveDataType);
+              }
+              if (nestedField.isRequired() && field.schema().isOptional()) {
+                String fieldName = tableSchema.findColumnName(nestedField.fieldId());
+                schemaUpdateConsumer.makeOptional(fieldName);
+              }
+              evolveSchemaFromConnectSchema(
+                  field.schema(), nestedField.type(), nestedField.fieldId(), schemaUpdateConsumer);
+            }
+          }
+        }
+        break;
+      case ARRAY:
+        if (tableType.isListType()) {
+          ListType listType = tableType.asListType();
+          evolveSchemaFromConnectSchema(
+              recordSchema.valueSchema(),
+              listType.elementType(),
+              listType.elementId(),
+              schemaUpdateConsumer);
+        }
+        break;
+      case MAP:

Review Comment:
   This walks the map value but never the key, so new fields inside a struct key are dropped on the null path. Iceberg allows struct map keys, and the existing `convertMapValue` processes both key and value through `convertValue` — so this is an asymmetry the null path introduces versus the value path it mirrors.
   
   Not blocking, but since you're in here I'd add the parallel key recursion:
   
   ```java
   evolveSchemaFromConnectSchema(
       recordSchema.keySchema(),
       mapType.keyType(),
       mapType.keyId(),
       schemaUpdateConsumer);
   ```



##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -255,19 +255,92 @@ private GenericRecord convertToStruct(
                   }
                 }
                 if (!hasSchemaUpdates) {
-                  result.setField(
-                      tableField.name(),
-                      convertValue(
-                          struct.get(recordField),
-                          tableField.type(),
-                          tableField.fieldId(),
-                          schemaUpdateConsumer));
+                  Object recordFieldValue = struct.get(recordField);
+                  // If the value is null and schema evolution is on, then evolve the table schema
+                  // from the connect record schema
+                  if (recordFieldValue == null && schemaUpdateConsumer != null) {
+                    evolveSchemaFromConnectSchema(
+                        recordField.schema(),
+                        tableField.type(),
+                        tableField.fieldId(),
+                        schemaUpdateConsumer);
+                  } else {
+                    // If the value is not null, then convert the value (and handle any schema
+                    // updates)
+                    result.setField(
+                        tableField.name(),
+                        convertValue(
+                            recordFieldValue,
+                            tableField.type(),
+                            tableField.fieldId(),
+                            schemaUpdateConsumer));
+                  }
                 }
               }
             });
     return result;
   }
 
+  private void evolveSchemaFromConnectSchema(
+      org.apache.kafka.connect.data.Schema recordSchema,
+      Type tableType,
+      int tableFieldId,
+      SchemaUpdate.Consumer schemaUpdateConsumer) {
+    if (recordSchema == null) {
+      return;
+    }
+    switch (recordSchema.type()) {
+      case STRUCT:
+        if (tableType.isStructType()) {
+          StructType structType = tableType.asStructType();
+          for (Field field : recordSchema.fields()) {
+            NestedField nestedField = lookupStructField(field.name(), structType, tableFieldId);
+            if (nestedField == null) {
+              String parentFieldName = tableSchema.findColumnName(tableFieldId);
+              Type type = SchemaUtils.toIcebergType(field.schema(), config);
+              schemaUpdateConsumer.addColumn(parentFieldName, field.name(), type);
+            } else {
+              PrimitiveType evolveDataType =
+                  SchemaUtils.needsDataTypeUpdate(nestedField.type(), field.schema());
+              if (evolveDataType != null) {
+                String fieldName = tableSchema.findColumnName(nestedField.fieldId());
+                schemaUpdateConsumer.updateType(fieldName, evolveDataType);
+              }
+              if (nestedField.isRequired() && field.schema().isOptional()) {

Review Comment:
   This `makeOptional` guard doesn't consult `config.schemaForceOptional()`, so with that flag set an existing required field won't be made optional through the null path. The value path has the identical limitation, so this is pre-existing and consistent rather than a regression — flagging so it's a deliberate choice, not an oversight. If you want them aligned, `config.schemaForceOptional() || field.schema().isOptional()` in both guards does it. Fine for a follow-up.



##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -255,19 +255,92 @@ private GenericRecord convertToStruct(
                   }
                 }
                 if (!hasSchemaUpdates) {
-                  result.setField(
-                      tableField.name(),
-                      convertValue(
-                          struct.get(recordField),
-                          tableField.type(),
-                          tableField.fieldId(),
-                          schemaUpdateConsumer));
+                  Object recordFieldValue = struct.get(recordField);
+                  // If the value is null and schema evolution is on, then evolve the table schema
+                  // from the connect record schema
+                  if (recordFieldValue == null && schemaUpdateConsumer != null) {
+                    evolveSchemaFromConnectSchema(
+                        recordField.schema(),
+                        tableField.type(),
+                        tableField.fieldId(),
+                        schemaUpdateConsumer);
+                  } else {
+                    // If the value is not null, then convert the value (and handle any schema
+                    // updates)
+                    result.setField(
+                        tableField.name(),
+                        convertValue(
+                            recordFieldValue,
+                            tableField.type(),
+                            tableField.fieldId(),
+                            schemaUpdateConsumer));
+                  }
                 }
               }
             });
     return result;
   }
 
+  private void evolveSchemaFromConnectSchema(
+      org.apache.kafka.connect.data.Schema recordSchema,
+      Type tableType,
+      int tableFieldId,
+      SchemaUpdate.Consumer schemaUpdateConsumer) {
+    if (recordSchema == null) {
+      return;
+    }
+    switch (recordSchema.type()) {
+      case STRUCT:
+        if (tableType.isStructType()) {
+          StructType structType = tableType.asStructType();
+          for (Field field : recordSchema.fields()) {
+            NestedField nestedField = lookupStructField(field.name(), structType, tableFieldId);
+            if (nestedField == null) {
+              String parentFieldName = tableSchema.findColumnName(tableFieldId);
+              Type type = SchemaUtils.toIcebergType(field.schema(), config);
+              schemaUpdateConsumer.addColumn(parentFieldName, field.name(), type);
+            } else {
+              PrimitiveType evolveDataType =
+                  SchemaUtils.needsDataTypeUpdate(nestedField.type(), field.schema());
+              if (evolveDataType != null) {
+                String fieldName = tableSchema.findColumnName(nestedField.fieldId());
+                schemaUpdateConsumer.updateType(fieldName, evolveDataType);
+              }
+              if (nestedField.isRequired() && field.schema().isOptional()) {
+                String fieldName = tableSchema.findColumnName(nestedField.fieldId());
+                schemaUpdateConsumer.makeOptional(fieldName);
+              }
+              evolveSchemaFromConnectSchema(
+                  field.schema(), nestedField.type(), nestedField.fieldId(), schemaUpdateConsumer);
+            }
+          }
+        }
+        break;
+      case ARRAY:
+        if (tableType.isListType()) {
+          ListType listType = tableType.asListType();
+          evolveSchemaFromConnectSchema(
+              recordSchema.valueSchema(),
+              listType.elementType(),
+              listType.elementId(),
+              schemaUpdateConsumer);
+        }
+        break;
+      case MAP:
+        if (tableType.isMapType()) {
+          MapType mapType = tableType.asMapType();
+          evolveSchemaFromConnectSchema(
+              recordSchema.valueSchema(),

Review Comment:
   For a schema-less map `recordSchema.valueSchema()` can be null, and `SchemaUtils.toIcebergType(null)` down the STRUCT recursion can NPE. The method already guards `recordSchema == null` at the top — the same guard on the recursion arg here (and on the ARRAY case above) keeps it consistent. Not blocking.



##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -255,19 +255,92 @@ private GenericRecord convertToStruct(
                   }
                 }
                 if (!hasSchemaUpdates) {
-                  result.setField(
-                      tableField.name(),
-                      convertValue(
-                          struct.get(recordField),
-                          tableField.type(),
-                          tableField.fieldId(),
-                          schemaUpdateConsumer));
+                  Object recordFieldValue = struct.get(recordField);
+                  // If the value is null and schema evolution is on, then evolve the table schema
+                  // from the connect record schema
+                  if (recordFieldValue == null && schemaUpdateConsumer != null) {
+                    evolveSchemaFromConnectSchema(
+                        recordField.schema(),
+                        tableField.type(),
+                        tableField.fieldId(),
+                        schemaUpdateConsumer);
+                  } else {
+                    // If the value is not null, then convert the value (and handle any schema
+                    // updates)
+                    result.setField(
+                        tableField.name(),
+                        convertValue(
+                            recordFieldValue,
+                            tableField.type(),
+                            tableField.fieldId(),
+                            schemaUpdateConsumer));
+                  }
                 }
               }
             });
     return result;
   }
 
+  private void evolveSchemaFromConnectSchema(
+      org.apache.kafka.connect.data.Schema recordSchema,
+      Type tableType,
+      int tableFieldId,
+      SchemaUpdate.Consumer schemaUpdateConsumer) {
+    if (recordSchema == null) {
+      return;
+    }
+    switch (recordSchema.type()) {
+      case STRUCT:
+        if (tableType.isStructType()) {
+          StructType structType = tableType.asStructType();
+          for (Field field : recordSchema.fields()) {
+            NestedField nestedField = lookupStructField(field.name(), structType, tableFieldId);
+            if (nestedField == null) {
+              String parentFieldName = tableSchema.findColumnName(tableFieldId);

Review Comment:
   `findColumnName` can return null, and there's no `tableFieldId < 0 ? null` guard like `convertToStruct(Map)` has. If `parentFieldName` comes back null, `addColumn(null, field.name(), type)` adds the column at the root instead of nested — silent schema corruption rather than a failure.
   
   It's unreachable in the current call graph since `tableFieldId` is always a valid field id here, so not blocking, but it's a latent trap for any future caller. I'd mirror the existing `structFieldId < 0` guard.



##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -255,19 +255,92 @@ private GenericRecord convertToStruct(
                   }
                 }
                 if (!hasSchemaUpdates) {
-                  result.setField(
-                      tableField.name(),
-                      convertValue(
-                          struct.get(recordField),
-                          tableField.type(),
-                          tableField.fieldId(),
-                          schemaUpdateConsumer));
+                  Object recordFieldValue = struct.get(recordField);
+                  // If the value is null and schema evolution is on, then evolve the table schema
+                  // from the connect record schema
+                  if (recordFieldValue == null && schemaUpdateConsumer != null) {
+                    evolveSchemaFromConnectSchema(
+                        recordField.schema(),
+                        tableField.type(),
+                        tableField.fieldId(),
+                        schemaUpdateConsumer);
+                  } else {
+                    // If the value is not null, then convert the value (and handle any schema
+                    // updates)
+                    result.setField(
+                        tableField.name(),
+                        convertValue(
+                            recordFieldValue,
+                            tableField.type(),
+                            tableField.fieldId(),
+                            schemaUpdateConsumer));
+                  }
                 }
               }
             });
     return result;
   }
 
+  private void evolveSchemaFromConnectSchema(

Review Comment:
   This duplicates the three evolution ops (addColumn/updateType/makeOptional) that already live in the value path around the `convertToStruct` switch — the rules now live in two places and any future change has to land in both. The minimal-fix framing is defensible and I wouldn't block on extracting a shared helper, but a short comment here pointing at the value-path counterpart would save the next person from forgetting the second site.



##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -255,19 +255,92 @@ private GenericRecord convertToStruct(
                   }
                 }
                 if (!hasSchemaUpdates) {
-                  result.setField(
-                      tableField.name(),
-                      convertValue(
-                          struct.get(recordField),
-                          tableField.type(),
-                          tableField.fieldId(),
-                          schemaUpdateConsumer));
+                  Object recordFieldValue = struct.get(recordField);
+                  // If the value is null and schema evolution is on, then evolve the table schema
+                  // from the connect record schema
+                  if (recordFieldValue == null && schemaUpdateConsumer != null) {
+                    evolveSchemaFromConnectSchema(
+                        recordField.schema(),
+                        tableField.type(),
+                        tableField.fieldId(),
+                        schemaUpdateConsumer);

Review Comment:
   Before this change the null branch still called `result.setField(name, convertValue(null, ...))`, which set the field to null. Now it skips `setField` entirely. `GenericRecord` defaults fields to null so the observable result is the same today, but the two paths diverge and it's fragile if the record impl ever changes its defaults. I'd call `result.setField(tableField.name(), null)` after the evolve call to keep the behavior identical. Not blocking.



##########
kafka-connect/kafka-connect/src/test/java/org/apache/iceberg/connect/data/TestRecordConverter.java:
##########
@@ -859,6 +859,268 @@ private void assertTypesAddedFromStruct(Function<String, Type> fn) {
     assertThat(fn.apply("ma")).isInstanceOf(MapType.class);
   }
 
+  @Test
+  public void testNestedSchemaEvolutionStructWithNullValue() {

Review Comment:
   All six new tests assert only on `consumer.addColumns()` (and updateTypes/makeOptionals) and never on the Record returned by `convert`. That leaves the `result.setField(name, null)` omission unverified — none of these would fail if the field were left unset versus set to null.
   
   I'd have at least this test capture the returned Record and assert the null-valued field is actually null on it, so the output-value contract is pinned and not just the schema-update side effect. Worth adding alongside the blocker fix — a test for a field that needs both a top-level update and a null nested struct would also pin the case that's currently dropped.



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] Kafka Connect: evolve table schema when record schema is updated but value is null [iceberg]

Posted by "twthorn (via GitHub)" <gi...@apache.org>.
twthorn commented on PR #16826:
URL: https://github.com/apache/iceberg/pull/16826#issuecomment-4724413893

   Perhaps @laskoviymishka saw you active on some recent PRs, could you take a look when you get the chance? Thanks!


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] Kafka Connect: evolve table schema when record schema is updated but value is null [iceberg]

Posted by "twthorn (via GitHub)" <gi...@apache.org>.
twthorn commented on code in PR #16826:
URL: https://github.com/apache/iceberg/pull/16826#discussion_r3444144441


##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -268,6 +276,74 @@ private GenericRecord convertToStruct(
     return result;
   }
 
+  /**
+   * This method evolves schemas when the value is null. Note: logic should be kept consistent with
+   * equivalent method used when value is not null: {@link #convertToStruct(Struct, StructType, int,
+   * SchemaUpdate.Consumer)}
+   */
+  private void evolveSchemaFromConnectSchema(
+      org.apache.kafka.connect.data.Schema recordSchema,
+      Type tableType,
+      int tableFieldId,
+      SchemaUpdate.Consumer schemaUpdateConsumer) {
+    if (recordSchema == null) {
+      return;
+    }
+    switch (recordSchema.type()) {
+      case STRUCT:

Review Comment:
   Agreed, added a small helper for logging since it's the same message/format in each, and each branch calls that to keep the code DRY.



##########
kafka-connect/kafka-connect/src/test/java/org/apache/iceberg/connect/data/TestRecordConverter.java:
##########
@@ -859,6 +859,378 @@ private void assertTypesAddedFromStruct(Function<String, Type> fn) {
     assertThat(fn.apply("ma")).isInstanceOf(MapType.class);
   }
 
+  @Test
+  public void testNestedSchemaEvolutionStructWithNullValue() {
+    org.apache.iceberg.Schema nestedStructSchema =
+        new org.apache.iceberg.Schema(

Review Comment:
   Nice catch, I added the test for that null value no evolution case.



##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -268,6 +276,74 @@ private GenericRecord convertToStruct(
     return result;
   }
 
+  /**
+   * This method evolves schemas when the value is null. Note: logic should be kept consistent with

Review Comment:
   Good point. There are only certain parts of the method that mirror the other function, but overall behaves fundamentally different. I have updated the java doc to clarify this.



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] Kafka Connect: evolve table schema when record schema is updated but value is null [iceberg]

Posted by "twthorn (via GitHub)" <gi...@apache.org>.
twthorn commented on code in PR #16826:
URL: https://github.com/apache/iceberg/pull/16826#discussion_r3449223773


##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -268,6 +280,89 @@ private GenericRecord convertToStruct(
     return result;
   }
 
+  /**
+   * Recursively traverses the Connect schema and emits all evolution events (addColumn, updateType,
+   * and makeOptional) at every nested level.
+   *
+   * <p>Unlike {@link #convertToStruct(Struct, StructType, int, SchemaUpdate.Consumer)} which skips
+   * a field's children once an update is detected (deferring nested discovery to re-conversion),
+   * this method always recurses through the full schema.
+   */
+  private void evolveSchemaFromConnectSchema(
+      org.apache.kafka.connect.data.Schema recordSchema,
+      Type tableType,
+      int tableFieldId,
+      SchemaUpdate.Consumer schemaUpdateConsumer) {
+    if (recordSchema == null) {
+      return;
+    }
+    switch (recordSchema.type()) {
+      case STRUCT:
+        if (tableType.isStructType()) {
+          StructType structType = tableType.asStructType();
+          for (Field field : recordSchema.fields()) {
+            NestedField nestedField = lookupStructField(field.name(), structType, tableFieldId);
+            if (nestedField == null) {
+              String parentFieldName =
+                  tableFieldId < 0 ? null : tableSchema.findColumnName(tableFieldId);
+              Type type = SchemaUtils.toIcebergType(field.schema(), config);
+              schemaUpdateConsumer.addColumn(parentFieldName, field.name(), type);
+            } else {
+              PrimitiveType evolveDataType =
+                  SchemaUtils.needsDataTypeUpdate(nestedField.type(), field.schema());
+              if (evolveDataType != null) {
+                String fieldName = tableSchema.findColumnName(nestedField.fieldId());
+                schemaUpdateConsumer.updateType(fieldName, evolveDataType);
+              }
+              if (nestedField.isRequired() && field.schema().isOptional()) {
+                String fieldName = tableSchema.findColumnName(nestedField.fieldId());
+                schemaUpdateConsumer.makeOptional(fieldName);
+              }
+              evolveSchemaFromConnectSchema(
+                  field.schema(), nestedField.type(), nestedField.fieldId(), schemaUpdateConsumer);
+            }
+          }
+        } else {
+          logMismatchedType(recordSchema.type(), tableType);
+        }
+        break;
+      case ARRAY:
+        if (tableType.isListType()) {
+          ListType listType = tableType.asListType();
+          evolveSchemaFromConnectSchema(
+              recordSchema.valueSchema(),
+              listType.elementType(),
+              listType.elementId(),
+              schemaUpdateConsumer);
+        } else {
+          logMismatchedType(recordSchema.type(), tableType);
+        }
+        break;
+      case MAP:
+        if (tableType.isMapType()) {
+          MapType mapType = tableType.asMapType();
+          evolveSchemaFromConnectSchema(
+              recordSchema.keySchema(), mapType.keyType(), mapType.keyId(), schemaUpdateConsumer);

Review Comment:
   Good to know, updated to reflect this.



##########
kafka-connect/kafka-connect/src/test/java/org/apache/iceberg/connect/data/TestRecordConverter.java:
##########
@@ -859,6 +859,411 @@ private void assertTypesAddedFromStruct(Function<String, Type> fn) {
     assertThat(fn.apply("ma")).isInstanceOf(MapType.class);
   }
 
+  @Test
+  public void testNestedSchemaEvolutionStructWithNullValue() {
+    org.apache.iceberg.Schema nestedStructSchema =
+        new org.apache.iceberg.Schema(
+            NestedField.required(1, "id", IntegerType.get()),
+            NestedField.optional(
+                2, "nested", StructType.of(NestedField.required(3, "a", IntegerType.get()))));
+
+    Table table = mock(Table.class);
+    when(table.schema()).thenReturn(nestedStructSchema);
+    RecordConverter converter = new RecordConverter(table, config);
+
+    Schema connectNestedSchema =
+        SchemaBuilder.struct()
+            .optional()
+            .field("a", Schema.INT32_SCHEMA)
+            .field("b", Schema.OPTIONAL_STRING_SCHEMA)
+            .build();
+    Schema connectSchema =
+        SchemaBuilder.struct()
+            .field("id", Schema.INT32_SCHEMA)
+            .field("nested", connectNestedSchema)
+            .build();
+    Struct data = new Struct(connectSchema).put("id", 1).put("nested", null);
+
+    SchemaUpdate.Consumer consumer = new SchemaUpdate.Consumer();
+    Record result = converter.convert(data, consumer);
+
+    assertThat(result.getField("id")).isEqualTo(1);
+    assertThat(result.getField("nested")).isNull();
+
+    Collection<AddColumn> addCols = consumer.addColumns();
+    assertThat(addCols).hasSize(1);
+    AddColumn addCol = addCols.iterator().next();
+    assertThat(addCol.parentName()).isEqualTo("nested");
+    assertThat(addCol.name()).isEqualTo("b");
+    assertThat(addCol.type()).isInstanceOf(StringType.class);
+  }
+
+  @Test
+  public void testNoSchemaEvolutionStructWithNullValue() {
+    org.apache.iceberg.Schema nestedStructSchema =
+        new org.apache.iceberg.Schema(
+            NestedField.required(1, "id", IntegerType.get()),
+            NestedField.optional(
+                2, "nested", StructType.of(NestedField.required(3, "a", IntegerType.get()))));
+
+    Table table = mock(Table.class);
+    when(table.schema()).thenReturn(nestedStructSchema);
+    RecordConverter converter = new RecordConverter(table, config);
+
+    Schema connectNestedSchema =
+        SchemaBuilder.struct().optional().field("a", Schema.INT32_SCHEMA).build();
+    Schema connectSchema =
+        SchemaBuilder.struct()
+            .field("id", Schema.INT32_SCHEMA)
+            .field("nested", connectNestedSchema)
+            .build();
+    Struct data = new Struct(connectSchema).put("id", 1).put("nested", null);
+
+    SchemaUpdate.Consumer consumer = new SchemaUpdate.Consumer();
+    Record result = converter.convert(data, consumer);
+
+    assertThat(result.getField("id")).isEqualTo(1);
+    assertThat(result.getField("nested")).isNull();
+
+    assertThat(consumer.addColumns()).isEmpty();
+    assertThat(consumer.makeOptionals()).isEmpty();
+    assertThat(consumer.updateTypes()).isEmpty();
+    assertThat(consumer.empty()).isTrue();
+  }
+
+  @Test
+  public void testNestedSchemaEvolutionListOfStructsWithNullValue() {
+    org.apache.iceberg.Schema tableSchema =
+        new org.apache.iceberg.Schema(
+            NestedField.required(
+                1,
+                "items",
+                ListType.ofRequired(
+                    2,
+                    StructType.of(
+                        NestedField.required(3, "product_id", IntegerType.get()),
+                        NestedField.optional(
+                            4,
+                            "details",
+                            StructType.of(NestedField.required(5, "name", StringType.get())))))));
+
+    Table table = mock(Table.class);
+    when(table.schema()).thenReturn(tableSchema);
+    RecordConverter converter = new RecordConverter(table, config);
+
+    Schema detailsSchema =
+        SchemaBuilder.struct()
+            .optional()
+            .field("name", Schema.OPTIONAL_STRING_SCHEMA)
+            .field("price", Schema.OPTIONAL_FLOAT64_SCHEMA)
+            .build();
+    Schema itemSchema =
+        SchemaBuilder.struct()
+            .field("product_id", Schema.INT32_SCHEMA)
+            .field("details", detailsSchema)
+            .build();
+    Schema connectSchema =
+        SchemaBuilder.struct().field("items", SchemaBuilder.array(itemSchema).build()).build();
+
+    Struct item = new Struct(itemSchema).put("product_id", 101).put("details", null);
+    Struct data = new Struct(connectSchema).put("items", ImmutableList.of(item));
+
+    SchemaUpdate.Consumer consumer = new SchemaUpdate.Consumer();
+    Record result = converter.convert(data, consumer);
+
+    List<Record> items = (List<Record>) result.getField("items");

Review Comment:
   Updated as well



##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -254,11 +258,19 @@ private GenericRecord convertToStruct(
                     hasSchemaUpdates = true;
                   }
                 }
+                Object recordFieldValue = struct.get(recordField);
+                if (recordFieldValue == null && schemaUpdateConsumer != null) {

Review Comment:
   Good catch, updated to align, and reflected this in tests as well.



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] Kafka Connect: evolve table schema when record schema is updated but value is null [iceberg]

Posted by "laskoviymishka (via GitHub)" <gi...@apache.org>.
laskoviymishka commented on code in PR #16826:
URL: https://github.com/apache/iceberg/pull/16826#discussion_r3449074931


##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -254,11 +258,19 @@ private GenericRecord convertToStruct(
                     hasSchemaUpdates = true;
                   }
                 }
+                Object recordFieldValue = struct.get(recordField);
+                if (recordFieldValue == null && schemaUpdateConsumer != null) {

Review Comment:
   Small one: this fires the null-walk even when `hasSchemaUpdates` is already true for the field, so when the field itself needs an updateType/makeOptional we end up emitting at this level twice. It's harmless today because `SchemaUpdate.Consumer` dedups by name, but it's leaning on that implicitly. Adding `&& !hasSchemaUpdates` here keeps this consistent with the non-null branch (which defers child discovery to the next record) and drops the redundant walk.



##########
kafka-connect/kafka-connect/src/main/java/org/apache/iceberg/connect/data/RecordConverter.java:
##########
@@ -268,6 +280,89 @@ private GenericRecord convertToStruct(
     return result;
   }
 
+  /**
+   * Recursively traverses the Connect schema and emits all evolution events (addColumn, updateType,
+   * and makeOptional) at every nested level.
+   *
+   * <p>Unlike {@link #convertToStruct(Struct, StructType, int, SchemaUpdate.Consumer)} which skips
+   * a field's children once an update is detected (deferring nested discovery to re-conversion),
+   * this method always recurses through the full schema.
+   */
+  private void evolveSchemaFromConnectSchema(
+      org.apache.kafka.connect.data.Schema recordSchema,
+      Type tableType,
+      int tableFieldId,
+      SchemaUpdate.Consumer schemaUpdateConsumer) {
+    if (recordSchema == null) {
+      return;
+    }
+    switch (recordSchema.type()) {
+      case STRUCT:
+        if (tableType.isStructType()) {
+          StructType structType = tableType.asStructType();
+          for (Field field : recordSchema.fields()) {
+            NestedField nestedField = lookupStructField(field.name(), structType, tableFieldId);
+            if (nestedField == null) {
+              String parentFieldName =
+                  tableFieldId < 0 ? null : tableSchema.findColumnName(tableFieldId);
+              Type type = SchemaUtils.toIcebergType(field.schema(), config);
+              schemaUpdateConsumer.addColumn(parentFieldName, field.name(), type);
+            } else {
+              PrimitiveType evolveDataType =
+                  SchemaUtils.needsDataTypeUpdate(nestedField.type(), field.schema());
+              if (evolveDataType != null) {
+                String fieldName = tableSchema.findColumnName(nestedField.fieldId());
+                schemaUpdateConsumer.updateType(fieldName, evolveDataType);
+              }
+              if (nestedField.isRequired() && field.schema().isOptional()) {
+                String fieldName = tableSchema.findColumnName(nestedField.fieldId());
+                schemaUpdateConsumer.makeOptional(fieldName);
+              }
+              evolveSchemaFromConnectSchema(
+                  field.schema(), nestedField.type(), nestedField.fieldId(), schemaUpdateConsumer);
+            }
+          }
+        } else {
+          logMismatchedType(recordSchema.type(), tableType);
+        }
+        break;
+      case ARRAY:
+        if (tableType.isListType()) {
+          ListType listType = tableType.asListType();
+          evolveSchemaFromConnectSchema(
+              recordSchema.valueSchema(),
+              listType.elementType(),
+              listType.elementId(),
+              schemaUpdateConsumer);
+        } else {
+          logMismatchedType(recordSchema.type(), tableType);
+        }
+        break;
+      case MAP:
+        if (tableType.isMapType()) {
+          MapType mapType = tableType.asMapType();
+          evolveSchemaFromConnectSchema(
+              recordSchema.keySchema(), mapType.keyType(), mapType.keyId(), schemaUpdateConsumer);

Review Comment:
   This is the one thing I'd fix before merge, and it's a small change. Recursing into `keySchema()`/`keyId()` here emits evolution events against the map *key* struct, but Iceberg treats map keys as immutable — `SchemaUpdate.commit()` rejects add/update/makeOptional on anything inside a key struct ("Cannot add fields to map keys" / "Cannot update map keys" / "Cannot alter map keys").
   
   So a null map field whose Connect key struct gained a field emits `addColumn(parent="...key", ...)`, and the next `IcebergWriter` flush runs `applySchemaUpdates` → `commit()`:
   
   ```
   addColumn(parent="data.key", name="k2", StringType)
     -> SchemaUpdate.commit()
        -> map(): parentToAddedIds.containsKey(keyId)
           -> throw IllegalArgumentException("Cannot add fields to map keys")
   ```
   
   which takes the record (and the task) down. `testNestedSchemaEvolutionMapKeyWithNullValue` doesn't catch it because it inspects the consumer directly and never calls `applySchemaUpdates`.
   
   I'd just recurse into the value subtree only (drop the key recursion) — that mirrors how `SchemaUpdate.internalAddColumn` already redirects map column adds to the value type — and flip that test to assert we emit nothing for the key (or to expect the throw through `applySchemaUpdates`). The rest of the recursion looks great.



##########
kafka-connect/kafka-connect/src/test/java/org/apache/iceberg/connect/data/TestRecordConverter.java:
##########
@@ -859,6 +859,411 @@ private void assertTypesAddedFromStruct(Function<String, Type> fn) {
     assertThat(fn.apply("ma")).isInstanceOf(MapType.class);
   }
 
+  @Test
+  public void testNestedSchemaEvolutionStructWithNullValue() {
+    org.apache.iceberg.Schema nestedStructSchema =
+        new org.apache.iceberg.Schema(
+            NestedField.required(1, "id", IntegerType.get()),
+            NestedField.optional(
+                2, "nested", StructType.of(NestedField.required(3, "a", IntegerType.get()))));
+
+    Table table = mock(Table.class);
+    when(table.schema()).thenReturn(nestedStructSchema);
+    RecordConverter converter = new RecordConverter(table, config);
+
+    Schema connectNestedSchema =
+        SchemaBuilder.struct()
+            .optional()
+            .field("a", Schema.INT32_SCHEMA)
+            .field("b", Schema.OPTIONAL_STRING_SCHEMA)
+            .build();
+    Schema connectSchema =
+        SchemaBuilder.struct()
+            .field("id", Schema.INT32_SCHEMA)
+            .field("nested", connectNestedSchema)
+            .build();
+    Struct data = new Struct(connectSchema).put("id", 1).put("nested", null);
+
+    SchemaUpdate.Consumer consumer = new SchemaUpdate.Consumer();
+    Record result = converter.convert(data, consumer);
+
+    assertThat(result.getField("id")).isEqualTo(1);
+    assertThat(result.getField("nested")).isNull();
+
+    Collection<AddColumn> addCols = consumer.addColumns();
+    assertThat(addCols).hasSize(1);
+    AddColumn addCol = addCols.iterator().next();
+    assertThat(addCol.parentName()).isEqualTo("nested");
+    assertThat(addCol.name()).isEqualTo("b");
+    assertThat(addCol.type()).isInstanceOf(StringType.class);
+  }
+
+  @Test
+  public void testNoSchemaEvolutionStructWithNullValue() {
+    org.apache.iceberg.Schema nestedStructSchema =
+        new org.apache.iceberg.Schema(
+            NestedField.required(1, "id", IntegerType.get()),
+            NestedField.optional(
+                2, "nested", StructType.of(NestedField.required(3, "a", IntegerType.get()))));
+
+    Table table = mock(Table.class);
+    when(table.schema()).thenReturn(nestedStructSchema);
+    RecordConverter converter = new RecordConverter(table, config);
+
+    Schema connectNestedSchema =
+        SchemaBuilder.struct().optional().field("a", Schema.INT32_SCHEMA).build();
+    Schema connectSchema =
+        SchemaBuilder.struct()
+            .field("id", Schema.INT32_SCHEMA)
+            .field("nested", connectNestedSchema)
+            .build();
+    Struct data = new Struct(connectSchema).put("id", 1).put("nested", null);
+
+    SchemaUpdate.Consumer consumer = new SchemaUpdate.Consumer();
+    Record result = converter.convert(data, consumer);
+
+    assertThat(result.getField("id")).isEqualTo(1);
+    assertThat(result.getField("nested")).isNull();
+
+    assertThat(consumer.addColumns()).isEmpty();
+    assertThat(consumer.makeOptionals()).isEmpty();
+    assertThat(consumer.updateTypes()).isEmpty();
+    assertThat(consumer.empty()).isTrue();
+  }
+
+  @Test
+  public void testNestedSchemaEvolutionListOfStructsWithNullValue() {
+    org.apache.iceberg.Schema tableSchema =
+        new org.apache.iceberg.Schema(
+            NestedField.required(
+                1,
+                "items",
+                ListType.ofRequired(
+                    2,
+                    StructType.of(
+                        NestedField.required(3, "product_id", IntegerType.get()),
+                        NestedField.optional(
+                            4,
+                            "details",
+                            StructType.of(NestedField.required(5, "name", StringType.get())))))));
+
+    Table table = mock(Table.class);
+    when(table.schema()).thenReturn(tableSchema);
+    RecordConverter converter = new RecordConverter(table, config);
+
+    Schema detailsSchema =
+        SchemaBuilder.struct()
+            .optional()
+            .field("name", Schema.OPTIONAL_STRING_SCHEMA)
+            .field("price", Schema.OPTIONAL_FLOAT64_SCHEMA)
+            .build();
+    Schema itemSchema =
+        SchemaBuilder.struct()
+            .field("product_id", Schema.INT32_SCHEMA)
+            .field("details", detailsSchema)
+            .build();
+    Schema connectSchema =
+        SchemaBuilder.struct().field("items", SchemaBuilder.array(itemSchema).build()).build();
+
+    Struct item = new Struct(itemSchema).put("product_id", 101).put("details", null);
+    Struct data = new Struct(connectSchema).put("items", ImmutableList.of(item));
+
+    SchemaUpdate.Consumer consumer = new SchemaUpdate.Consumer();
+    Record result = converter.convert(data, consumer);
+
+    List<Record> items = (List<Record>) result.getField("items");

Review Comment:
   These unchecked casts (this one and the `(Map<String, Record>)` cast in `testNestedSchemaEvolutionMapOfStructsWithNullValue`) will warn under `-Xlint:unchecked` and can fail CI where warnings are errors. The existing `testMapToString`/`testStructToString` in this file already carry `@SuppressWarnings("unchecked")` — adding the same annotation to these two keeps the build clean.



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] Kafka Connect: evolve table schema when record schema is updated but value is null [iceberg]

Posted by "laskoviymishka (via GitHub)" <gi...@apache.org>.
laskoviymishka merged PR #16826:
URL: https://github.com/apache/iceberg/pull/16826


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] Kafka Connect: evolve table schema when record schema is updated but value is null [iceberg]

Posted by "twthorn (via GitHub)" <gi...@apache.org>.
twthorn commented on PR #16826:
URL: https://github.com/apache/iceberg/pull/16826#issuecomment-4712997181

   @kzajaczkowski Could you take a look at this when you get the chance? Looks like you have context from previous PR/closing a duplicate ticket.
   
   The integration test failure appears flakey for azure and is unrelated to these changes.


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] Kafka Connect: evolve table schema when record schema is updated but value is null [iceberg]

Posted by "laskoviymishka (via GitHub)" <gi...@apache.org>.
laskoviymishka commented on PR #16826:
URL: https://github.com/apache/iceberg/pull/16826#issuecomment-4724693721

   @twthorn i'll take a look, but can you plz ping me once tests aregreen?


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] Kafka Connect: evolve table schema when record schema is updated but value is null [iceberg]

Posted by "twthorn (via GitHub)" <gi...@apache.org>.
twthorn commented on PR #16826:
URL: https://github.com/apache/iceberg/pull/16826#issuecomment-4724786145

   @laskoviymishka Thanks. For the build failure, it is from azure integration tests, which appear flakey and are failing on other PRs. Unrelated to these changes. I don't have permissions to rerun the jobs


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org