This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/master/pr-21096-6a68e1cc29ca7a0da975506e8b56f687b64b5163 in repository https://gitbox.apache.org/repos/asf/hudi.git
commit 98b53f2f5ea0be022c93ce03820282ca4568cea0 Author: voonhous <[email protected]> AuthorDate: Sat Dec 5 16:21:21 2026 +0000 fix(trino): skip fields that can only hold null in merge reads (#21096) * fix(trino): skip fields that can only hold null in merge reads A merge read of a table with a field that can only hold null ("null", or a union of nothing but "null") failed with "No null column type support": the full-schema read of a non-projection-compatible merger, the merge-required column recovery and the log-file projection asked for a column type for it. The Parquet writer does not write such a field and Hive sync does not register it. These paths now leave the field out. The file-group reader's records keep it null, its only value. The non-projection-compatible merger fixture gains an always_null field to cover it. * fix(trino): leave out null-only fields nested in a record toColumnHandle typed a record column with its full Avro schema, so a merge read that does not project a record with a null-only member still failed with "No null column type support". It now types the record without such members, at any depth, as Hive sync leaves them out of the struct. - The merger fixture gains a detail record with a null-only member. - Cover null-only ordering and operation fields in appendMissingMergeRequiredColumns. --- .../main/java/io/trino/plugin/hudi/HudiUtil.java | 91 +++++++++++++++++++++- .../plugin/hudi/reader/HudiTrinoReaderContext.java | 10 ++- .../plugin/hudi/TestHudiMergeRequiredColumns.java | 20 +++++ .../TestHudiNonProjectionCompatibleMerger.java | 10 +++ .../plugin/hudi/TestHudiUtilColumnHandles.java | 40 ++++++++++ ...ctionCompatibleMergerHudiTablesInitializer.java | 26 ++++++- 6 files changed, 189 insertions(+), 8 deletions(-) diff --git a/hudi-trino/src/main/java/io/trino/plugin/hudi/HudiUtil.java b/hudi-trino/src/main/java/io/trino/plugin/hudi/HudiUtil.java index ee11b50e244c..e5264086853d 100644 --- a/hudi-trino/src/main/java/io/trino/plugin/hudi/HudiUtil.java +++ b/hudi-trino/src/main/java/io/trino/plugin/hudi/HudiUtil.java @@ -60,6 +60,7 @@ import org.apache.hudi.common.model.HoodieLogFile; import org.apache.hudi.common.model.HoodieRecordMerger; import org.apache.hudi.common.schema.HoodieSchema; import org.apache.hudi.common.schema.HoodieSchemaField; +import org.apache.hudi.common.schema.HoodieSchemaType; import org.apache.hudi.common.table.HoodieTableConfig; import org.apache.hudi.common.table.HoodieTableMetaClient; import org.apache.hudi.common.table.HoodieTableVersion; @@ -84,6 +85,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; @@ -389,7 +391,7 @@ public final class HudiUtil { Type trinoType; try { - trinoType = AVRO_TYPE_HANDLER.typeFor(field.schema().toAvroSchema()); + trinoType = AVRO_TYPE_HANDLER.typeFor(withoutNullOnlyFields(field.schema().toAvroSchema())); } catch (AvroTypeException e) { throw new TrinoException(HUDI_SCHEMA_ERROR, @@ -484,7 +486,7 @@ public final class HudiUtil * Returns {@code projection} extended with a handle for every {@code dataSchema} field it does not * already carry (matched case-insensitively), typed from the field's Avro schema via * {@link #toColumnHandle}. Projection handles keep their order and instances; missing fields are - * appended in schema order. + * appended in schema order. Fields that can only hold null are left out ({@link #isNullOnly}). */ public static List<HiveColumnHandle> appendMissingSchemaColumns(HoodieSchema dataSchema, List<HiveColumnHandle> projection) { @@ -494,13 +496,94 @@ public final class HudiUtil List<HiveColumnHandle> columns = new ArrayList<>(projection); for (HoodieSchemaField field : dataSchema.getFields()) { - if (existingColumns.add(field.name().toLowerCase(Locale.ROOT))) { + if (!isNullOnly(field) && existingColumns.add(field.name().toLowerCase(Locale.ROOT))) { columns.add(toColumnHandle(field)); } } return columns; } + /** + * Whether a field can only hold null: {@code "null"}, or a union of nothing but {@code "null"}. Such a field has no + * Trino type and no column: the Parquet writer does not write it and Hive sync does not register it. The file-group + * reader fills it with null, its only value, so readers leave it out rather than ask for a type it does not have. + * {@link #toColumnHandle} leaves out such fields nested in a record. + */ + public static boolean isNullOnly(HoodieSchemaField field) + { + HoodieSchema schema = field.schema(); + return schema.isSchemaNull() + || (schema.getType() == HoodieSchemaType.UNION && schema.getTypes().stream().allMatch(HoodieSchema::isSchemaNull)); + } + + /** + * {@code schema} without the record fields that can only hold null, at any depth, for typing a column whose record + * schema nests one: Hive sync leaves such a field out of the struct, the Parquet writer does not write it, and Trino + * has no type for it. Returns {@code schema} itself when it nests none. + */ + private static Schema withoutNullOnlyFields(Schema schema) + { + return withoutNullOnlyFields(schema, Collections.newSetFromMap(new IdentityHashMap<>())); + } + + private static Schema withoutNullOnlyFields(Schema schema, Set<Schema> recordsInProgress) + { + return switch (schema.getType()) { + case RECORD -> { + if (!recordsInProgress.add(schema)) { + // A recursive record: left as is, Trino fails to type it either way + yield schema; + } + boolean pruned = false; + List<Schema.Field> fields = new ArrayList<>(); + for (Schema.Field field : schema.getFields()) { + if (isNullOnly(field.schema())) { + pruned = true; + continue; + } + Schema fieldSchema = withoutNullOnlyFields(field.schema(), recordsInProgress); + pruned |= fieldSchema != field.schema(); + // Only typed, so the field's default and doc are not carried + fields.add(new Schema.Field(field.name(), fieldSchema)); + } + recordsInProgress.remove(schema); + if (!pruned) { + yield schema; + } + if (fields.isEmpty()) { + throw new TrinoException(HUDI_SCHEMA_ERROR, "Trino has no row type without fields, and every field of record %s can only hold null" + .formatted(schema.getFullName())); + } + yield Schema.createRecord(schema.getName(), schema.getDoc(), schema.getNamespace(), schema.isError(), fields); + } + case ARRAY -> { + Schema elementType = withoutNullOnlyFields(schema.getElementType(), recordsInProgress); + yield elementType == schema.getElementType() ? schema : Schema.createArray(elementType); + } + case MAP -> { + Schema valueType = withoutNullOnlyFields(schema.getValueType(), recordsInProgress); + yield valueType == schema.getValueType() ? schema : Schema.createMap(valueType); + } + case UNION -> { + List<Schema> types = schema.getTypes().stream() + .map(type -> withoutNullOnlyFields(type, recordsInProgress)) + .toList(); + boolean pruned = false; + for (int i = 0; i < types.size(); i++) { + pruned |= types.get(i) != schema.getTypes().get(i); + } + yield pruned ? Schema.createUnion(types) : schema; + } + default -> schema; + }; + } + + private static boolean isNullOnly(Schema schema) + { + return schema.getType() == Schema.Type.NULL + || (schema.getType() == Schema.Type.UNION && schema.getTypes().stream().allMatch(type -> type.getType() == Schema.Type.NULL)); + } + public static List<HiveColumnHandle> prependHudiMetaAndMergeRequiredColumns(HudiTableHandle tableHandle, List<HiveColumnHandle> dataColumns) { Set<String> existingColumns = dataColumns.stream() @@ -711,7 +794,7 @@ public final class HudiUtil List<HiveColumnHandle> columns = new ArrayList<>(projection); for (String name : requiredNames) { HoodieSchemaField field = schemaFields.get(name.toLowerCase(Locale.ROOT)); - if (field != null && existingColumns.add(field.name().toLowerCase(Locale.ROOT))) { + if (field != null && !isNullOnly(field) && existingColumns.add(field.name().toLowerCase(Locale.ROOT))) { columns.add(toColumnHandle(field)); } } diff --git a/hudi-trino/src/main/java/io/trino/plugin/hudi/reader/HudiTrinoReaderContext.java b/hudi-trino/src/main/java/io/trino/plugin/hudi/reader/HudiTrinoReaderContext.java index 36212bf21d29..ae88197d9808 100644 --- a/hudi-trino/src/main/java/io/trino/plugin/hudi/reader/HudiTrinoReaderContext.java +++ b/hudi-trino/src/main/java/io/trino/plugin/hudi/reader/HudiTrinoReaderContext.java @@ -167,8 +167,10 @@ public class HudiTrinoReaderContext // The base read reuses the pre-built page source, so it can only satisfy requiredSchema fields the // read projection carries. The connector predicts the file-group reader's demands up front // (HudiUtil.getMergeRequiredColumnHandles, HudiPageSourceProvider.requiresFullSchemaRead); if the - // two ever drift, fail loudly here instead of silently merging with null column values. + // two ever drift, fail loudly here instead of silently merging with null column values. A field that can only + // hold null has no column to read; the serializer leaves it null, which is its only value. List<String> missingColumns = requiredSchema.getFields().stream() + .filter(field -> !HudiUtil.isNullOnly(field)) .map(HoodieSchemaField::name) .filter(name -> !baseProjectionNames.contains(name.toLowerCase(Locale.ROOT))) .toList(); @@ -179,7 +181,7 @@ public class HudiTrinoReaderContext + "FileGroupReaderSchemaHandler.generateRequiredSchema.", missingColumns)); } - // Every requiredSchema field is in the base projection (checked above) and every projected column is + // Every requiredSchema field but the null-only ones is in the base projection (checked above) and every projected column is // a requiredSchema field (the file-group reader's required schema always contains the full requested // schema), so the by-name channel mapping resolves in both directions. return createRecordIterator(pageSource, new HudiAvroSerializer(columnHandles, prefilledColumnValues, requiredSchema.toAvroSchema())); @@ -197,6 +199,10 @@ public class HudiTrinoReaderContext { List<HiveColumnHandle> handles = new ArrayList<>(); for (HoodieSchemaField field : requiredSchema.getFields()) { + if (HudiUtil.isNullOnly(field)) { + // No column to read and no Trino type; the serializer leaves the field null + continue; + } // A projection handle may carry the lowercased metastore column name (e.g. 'op' for the // DMS delete key 'Op'); that is fine on this path: parquet columns resolve // case-insensitively, the serializer maps channels into requiredSchema positions diff --git a/hudi-trino/src/test/java/io/trino/plugin/hudi/TestHudiMergeRequiredColumns.java b/hudi-trino/src/test/java/io/trino/plugin/hudi/TestHudiMergeRequiredColumns.java index daa4bdccf99a..d53aede17102 100644 --- a/hudi-trino/src/test/java/io/trino/plugin/hudi/TestHudiMergeRequiredColumns.java +++ b/hudi-trino/src/test/java/io/trino/plugin/hudi/TestHudiMergeRequiredColumns.java @@ -16,6 +16,7 @@ package io.trino.plugin.hudi; import io.trino.metastore.HiveType; import io.trino.plugin.hive.HiveColumnHandle; import io.trino.plugin.hudi.testing.MaxRankRecordMerger; +import org.apache.avro.Schema; import org.apache.avro.SchemaBuilder; import org.apache.hudi.common.config.RecordMergeMode; import org.apache.hudi.common.config.TypedProperties; @@ -144,6 +145,25 @@ class TestHudiMergeRequiredColumns assertThat(extended.getLast().getType()).isEqualTo(VARCHAR); } + @Test + public void testNullOnlyMergeRequiredFieldIsLeftOut() + { + // A merge-required field that can only hold null has no Trino type and no column in the files; it is left + // out, while the other required fields are still recovered + HoodieSchema dataSchema = HoodieSchema.fromAvroSchema(SchemaBuilder.record("rec").fields() + .requiredString("id") + .requiredLong("ts") + .name("seq").type().nullType().noDefault() + .name(OPERATION_METADATA_FIELD).type(Schema.createUnion(Schema.create(Schema.Type.NULL))).noDefault() + .endRecord()); + List<HiveColumnHandle> projection = List.of( + createBaseColumn("id", 0, HiveType.HIVE_STRING, VARCHAR, REGULAR, Optional.empty())); + + assertThat(appendMissingMergeRequiredColumns(dataSchema, projection, eventTimeOrderedOn("ts,seq"), new TypedProperties())) + .extracting(HiveColumnHandle::getName) + .containsExactly("id", "ts"); + } + @Test public void testCustomMergerMandatoryFieldMissingFromProjectionResolvesFromTableSchema() { diff --git a/hudi-trino/src/test/java/io/trino/plugin/hudi/TestHudiNonProjectionCompatibleMerger.java b/hudi-trino/src/test/java/io/trino/plugin/hudi/TestHudiNonProjectionCompatibleMerger.java index 8c239105d721..339a0d9cd4f2 100644 --- a/hudi-trino/src/test/java/io/trino/plugin/hudi/TestHudiNonProjectionCompatibleMerger.java +++ b/hudi-trino/src/test/java/io/trino/plugin/hudi/TestHudiNonProjectionCompatibleMerger.java @@ -109,6 +109,16 @@ public class TestHudiNonProjectionCompatibleMerger + " ('k2', 'k2_base', CAST(100 AS BIGINT), CAST(9 AS BIGINT), CAST(1 AS BIGINT))"); } + @Test + public void testNestedRecordWithNullOnlyMemberMerges() + { + // detail nests a null-only member, which Hive sync leaves out of the struct. Projected, it reads through its + // metastore type; the narrow projections above read it unprojected, typed from the table schema + assertQuery( + "SELECT key, detail.label FROM " + RT_TABLE_NAME + " ORDER BY key", + "VALUES ('k1', 'k1_updated_label'), ('k2', 'k2_base_label')"); + } + @Test public void testPayloadOnlyReadOptimizedTableReturnsBaseFileValues() { diff --git a/hudi-trino/src/test/java/io/trino/plugin/hudi/TestHudiUtilColumnHandles.java b/hudi-trino/src/test/java/io/trino/plugin/hudi/TestHudiUtilColumnHandles.java index ee1fb1473ec1..971ad38d63b4 100644 --- a/hudi-trino/src/test/java/io/trino/plugin/hudi/TestHudiUtilColumnHandles.java +++ b/hudi-trino/src/test/java/io/trino/plugin/hudi/TestHudiUtilColumnHandles.java @@ -115,6 +115,29 @@ class TestHudiUtilColumnHandles assertThat(rowHandle.getHiveType()).isEqualTo(HiveType.valueOf("struct<a:int,b:string>")); } + @Test + public void testNestedNullOnlyFieldsAreLeftOut() + { + // Hive sync leaves a null-only member out of a struct at any depth, and Trino has no type for it + Schema inner = SchemaBuilder.record("inner").fields() + .requiredString("label") + .name("always_null").type().nullType().noDefault() + .endRecord(); + HiveColumnHandle rowHandle = toColumnHandle("rec", SchemaBuilder.record("rec").fields() + .requiredInt("a") + .name("null_union").type(Schema.createUnion(Schema.create(Schema.Type.NULL))).noDefault() + .name("inner").type().optional().type(inner) + .name("inners").type().array().items(inner).noDefault() + .endRecord()); + assertThat(rowHandle.getHiveType()) + .isEqualTo(HiveType.valueOf("struct<a:int,inner:struct<label:string>,inners:array<struct<label:string>>>")); + + assertThatThrownBy(() -> toColumnHandle("rec", SchemaBuilder.record("rec").fields() + .name("always_null").type().nullType().noDefault() + .endRecord())) + .hasMessageContaining("every field of record rec can only hold null"); + } + @Test public void testNullableUnionOfLogicalType() { @@ -155,6 +178,23 @@ class TestHudiUtilColumnHandles assertThat(expanded.get(2).getType()).isEqualTo(INTEGER); } + @Test + public void testAppendMissingSchemaColumnsSkipsNullOnlyFields() + { + HoodieSchema dataSchema = HoodieSchema.fromAvroSchema(SchemaBuilder.record("rec").fields() + .requiredString("col_a") + .name("always_null").type().nullType().noDefault() + .name("null_union").type(Schema.createUnion(Schema.create(Schema.Type.NULL))).noDefault() + .optionalLong("col_b") + .endRecord()); + + // A field that can only hold null has no Trino type and no column in the files; it is left out, not typed. + // A nullable field is not null-only + assertThat(appendMissingSchemaColumns(dataSchema, List.of())) + .extracting(HiveColumnHandle::getName) + .containsExactly("col_a", "col_b"); + } + @Test public void testAppendMissingSchemaColumnsMatchesCaseInsensitively() { diff --git a/hudi-trino/src/test/java/io/trino/plugin/hudi/testing/NonProjectionCompatibleMergerHudiTablesInitializer.java b/hudi-trino/src/test/java/io/trino/plugin/hudi/testing/NonProjectionCompatibleMergerHudiTablesInitializer.java index c007d60607ec..1d030df915a4 100644 --- a/hudi-trino/src/test/java/io/trino/plugin/hudi/testing/NonProjectionCompatibleMergerHudiTablesInitializer.java +++ b/hudi-trino/src/test/java/io/trino/plugin/hudi/testing/NonProjectionCompatibleMergerHudiTablesInitializer.java @@ -15,6 +15,7 @@ package io.trino.plugin.hudi.testing; import com.google.common.collect.ImmutableList; import io.trino.metastore.Column; +import io.trino.metastore.HiveType; import org.apache.avro.Schema; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericRecord; @@ -51,6 +52,7 @@ public class NonProjectionCompatibleMergerHudiTablesInitializer public static final String RT_TABLE_NAME = TABLE_NAME + "_rt"; private static final String RANK_FIELD = NonProjectionCompatibleRankMerger.RANK_COLUMN; + private static final String DETAIL_FIELD = "detail"; public NonProjectionCompatibleMergerHudiTablesInitializer() { @@ -65,7 +67,9 @@ public class NonProjectionCompatibleMergerHudiTablesInitializer new Column("name", HIVE_STRING, Optional.empty(), Map.of()), new Column("value", HIVE_LONG, Optional.empty(), Map.of()), new Column(RANK_FIELD, HIVE_LONG, Optional.empty(), Map.of()), - new Column(ORDERING_FIELD, HIVE_LONG, Optional.empty(), Map.of())); + new Column(ORDERING_FIELD, HIVE_LONG, Optional.empty(), Map.of()), + // Hive sync leaves the null-only member out of the struct + new Column(DETAIL_FIELD, HiveType.valueOf("struct<label:string>"), Optional.empty(), Map.of())); } @Override @@ -76,10 +80,24 @@ public class NonProjectionCompatibleMergerHudiTablesInitializer new Schema.Field("name", Schema.create(Schema.Type.STRING)), new Schema.Field("value", Schema.create(Schema.Type.LONG)), new Schema.Field(RANK_FIELD, Schema.create(Schema.Type.LONG)), - new Schema.Field(ORDERING_FIELD, Schema.create(Schema.Type.LONG))); + new Schema.Field(ORDERING_FIELD, Schema.create(Schema.Type.LONG)), + // Always null, as schema inference gives a column that is null in every row. Hive sync does not + // register it, so dataColumns() leaves it out; the full-schema read this table's merger forces must + // skip it instead of failing to type it + new Schema.Field("always_null", Schema.create(Schema.Type.NULL), null, Schema.Field.NULL_DEFAULT_VALUE), + // A record with a null-only member: a read that does not project it types it from the schema, and must + // leave the member out as well + new Schema.Field(DETAIL_FIELD, detailSchema())); return Schema.createRecord(TABLE_NAME, null, null, false, new ArrayList<>(fields)); } + private static Schema detailSchema() + { + return Schema.createRecord("detail_record", null, null, false, ImmutableList.of( + new Schema.Field("label", Schema.create(Schema.Type.STRING)), + new Schema.Field("always_null", Schema.create(Schema.Type.NULL), null, Schema.Field.NULL_DEFAULT_VALUE))); + } + @Override protected void configureTableConfig(HoodieTableMetaClient.TableBuilder tableBuilder) { @@ -128,6 +146,10 @@ public class NonProjectionCompatibleMergerHudiTablesInitializer record.put("value", value); record.put(RANK_FIELD, rank); record.put(ORDERING_FIELD, ts); + GenericRecord detail = new GenericData.Record(detailSchema()); + // The label follows the name, so a merged row shows which side its detail came from + detail.put("label", name + "_label"); + record.put(DETAIL_FIELD, detail); return avroRecord(record, key); } }
