JingsongLi commented on code in PR #9822: URL: https://github.com/apache/paimon/pull/9822#discussion_r4376128747
########## paimon-core/src/main/java/org/apache/paimon/table/system/ChangelogEventMetadata.java: ########## @@ -0,0 +1,461 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.paimon.table.system; + +import org.apache.paimon.CoreOptions; +import org.apache.paimon.CoreOptions.ChangelogProducer; +import org.apache.paimon.data.variant.VariantMetadataUtils; +import org.apache.paimon.table.SpecialFields; +import org.apache.paimon.types.ArrayType; +import org.apache.paimon.types.DataField; +import org.apache.paimon.types.DataType; +import org.apache.paimon.types.MapType; +import org.apache.paimon.types.MultisetType; +import org.apache.paimon.types.RowType; +import org.apache.paimon.utils.NestedProjectedRow; + +import javax.annotation.Nullable; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; + +/** Shared validation and row-type construction for changelog event metadata fields. */ +public final class ChangelogEventMetadata { + + private ChangelogEventMetadata() {} + + /** + * Validates the event metadata configuration against the physical value type. + * + * <p>The fields are appended to records produced by the lookup changelog wrapper. They must not + * be enabled for another changelog producer because those producers share the ordinary writer + * and do not emit the appended values. + */ + public static void validate(RowType valueType, CoreOptions options) { + List<String> preserveColumns = options.changelogEventMetadataFields(); + if (preserveColumns.isEmpty()) { + return; + } + + if (options.changelogProducer() != ChangelogProducer.LOOKUP) { + throw new IllegalArgumentException( + String.format( + "Option '%s' can only be used when '%s' is '%s', but it is '%s'.", + CoreOptions.CHANGELOG_PRODUCER_EVENT_METADATA_FIELDS.key(), + CoreOptions.CHANGELOG_PRODUCER.key(), + ChangelogProducer.LOOKUP, + options.changelogProducer())); + } + + Set<String> valueFieldNames = new HashSet<>(valueType.getFieldNames()); + Set<String> preservedColumns = new HashSet<>(); + Set<String> metadataFieldNames = new HashSet<>(); + Map<String, String> metadataFieldSources = new HashMap<>(); + Map<String, String> storageFieldSources = new HashMap<>(); + for (String preserveColumn : preserveColumns) { + if (!preservedColumns.add(preserveColumn)) { + throw new IllegalArgumentException( + String.format( + "Column '%s' is specified more than once in '%s'.", + preserveColumn, + CoreOptions.CHANGELOG_PRODUCER_EVENT_METADATA_FIELDS.key())); + } + + if (!valueFieldNames.contains(preserveColumn)) { + throw new IllegalArgumentException( + String.format( + "Column '%s' specified in '%s' not found in value type. Available columns: %s", + preserveColumn, + CoreOptions.CHANGELOG_PRODUCER_EVENT_METADATA_FIELDS.key(), + valueType.getFieldNames())); + } + + DataField physicalField = valueType.getField(preserveColumn); + String metadataFieldName = metadataFieldName(preserveColumn, options); + if (valueFieldNames.contains(metadataFieldName)) { + throw new IllegalArgumentException( + String.format( + "Metadata field '%s' created by '%s' conflicts with an existing value column.", + metadataFieldName, + CoreOptions.CHANGELOG_PRODUCER_EVENT_METADATA_FIELDS.key())); + } + if (SpecialFields.isSystemField(metadataFieldName)) { + throw new IllegalArgumentException( + String.format( + "Metadata field '%s' created by '%s' conflicts with a system field.", + metadataFieldName, + CoreOptions.CHANGELOG_PRODUCER_EVENT_METADATA_FIELDS.key())); + } + if (!metadataFieldNames.add(metadataFieldName)) { + throw new IllegalArgumentException( + String.format( + "Metadata field '%s' is created more than once by '%s'.", + metadataFieldName, + CoreOptions.CHANGELOG_PRODUCER_EVENT_METADATA_FIELDS.key())); + } + + String storageFieldName = storageMetadataFieldName(physicalField, options); + if (valueFieldNames.contains(storageFieldName)) { + throw new IllegalArgumentException( + String.format( + "Storage metadata field '%s' created by '%s' " + + "conflicts with an existing value column.", + storageFieldName, + CoreOptions.CHANGELOG_PRODUCER_EVENT_METADATA_FIELDS.key())); + } + if (SpecialFields.isSystemField(storageFieldName)) { + throw new IllegalArgumentException( + String.format( + "Storage metadata field '%s' created by '%s' " + + "conflicts with a system field.", + storageFieldName, + CoreOptions.CHANGELOG_PRODUCER_EVENT_METADATA_FIELDS.key())); + } + if (storageFieldSources.put(storageFieldName, preserveColumn) != null) { + throw new IllegalArgumentException( + String.format( + "Storage metadata field '%s' is created more than once by '%s'.", + storageFieldName, + CoreOptions.CHANGELOG_PRODUCER_EVENT_METADATA_FIELDS.key())); + } + metadataFieldSources.put(metadataFieldName, preserveColumn); + } + + for (Map.Entry<String, String> metadataField : metadataFieldSources.entrySet()) { + String storageSource = storageFieldSources.get(metadataField.getKey()); + if (storageSource != null && !storageSource.equals(metadataField.getValue())) { + throw new IllegalArgumentException( + String.format( + "Metadata field '%s' created by '%s' conflicts with the storage " + + "metadata field for column '%s'.", + metadataField.getKey(), + CoreOptions.CHANGELOG_PRODUCER_EVENT_METADATA_FIELDS.key(), + storageSource)); + } + } + } + + /** + * Returns the nullable public metadata fields appended to a table row. + * + * <p>{@code highestFieldId} must be the table schema's highest field ID, which also covers + * dropped fields, so that metadata field IDs never alias a field of a historical schema. + */ + public static List<DataField> extraValueFields( + RowType valueType, int highestFieldId, CoreOptions options) { + validate(valueType, options); + return metadataValueFields( + valueType, + highestFieldId, + options, + physicalField -> metadataFieldName(physicalField.name(), options)); + } + + /** + * Returns the nullable fields used to store event metadata in changelog files. + * + * <p>Storage names use the configured prefix and source field ID, so they remain stable when + * the source column is renamed. + */ + public static List<DataField> storageValueFields( + RowType valueType, int highestFieldId, CoreOptions options) { + validate(valueType, options); + return metadataValueFields( + valueType, + highestFieldId, + options, + physicalField -> storageMetadataFieldName(physicalField, options)); + } + + /** + * Resolves storage metadata fields against the value fields of the schema a data file was + * written with. + * + * <p>The metadata values were written with the source field's type at that time, so each field + * takes the historical source field type. This lets schema evolution cast the values like the + * source field itself. Fields whose source field did not exist yet keep the current type. + */ + public static List<DataField> storageValueFieldsForDataSchema( + List<DataField> storageFields, + RowType valueType, + List<DataField> dataValueFields, + List<String> preserveColumns) { + List<DataField> fields = new ArrayList<>(storageFields.size()); + for (int i = 0; i < storageFields.size(); i++) { + DataField storageField = storageFields.get(i); + if (i >= preserveColumns.size() || !valueType.containsField(preserveColumns.get(i))) { + fields.add(storageField); + continue; + } + int sourceFieldId = valueType.getField(preserveColumns.get(i)).id(); + DataField dataSourceField = null; + for (DataField dataField : dataValueFields) { + if (dataField.id() == sourceFieldId) { + dataSourceField = dataField; + break; + } + } + fields.add( + dataSourceField == null + ? storageField + : storageField.newType(dataSourceField.type().copy(true))); + } + return fields; + } + + /** Returns the physical value-field positions copied into event metadata columns. */ + @Nullable + public static int[] preserveFieldIndices(RowType valueType, CoreOptions options) { + List<String> preserveColumns = options.changelogEventMetadataFields(); + if (preserveColumns.isEmpty()) { + return null; + } + validate(valueType, options); + int[] indices = new int[preserveColumns.size()]; + for (int i = 0; i < preserveColumns.size(); i++) { + indices[i] = valueType.getFieldIndex(preserveColumns.get(i)); + } + return indices; + } + + /** + * Appends event metadata fields to a row type while resolving their source fields from the + * physical value type. + * + * <p>The two row types intentionally differ for system tables such as {@code audit_log}, whose + * base row prepends system fields to the physical value fields. + */ + public static RowType appendMetadataFields( + RowType baseRowType, RowType valueType, int highestFieldId, CoreOptions options) { + return appendFields(baseRowType, extraValueFields(valueType, highestFieldId, options)); + } + + /** Appends the internal storage metadata fields to a row type. */ + public static RowType appendStorageMetadataFields( + RowType baseRowType, RowType valueType, int highestFieldId, CoreOptions options) { + return appendFields(baseRowType, storageValueFields(valueType, highestFieldId, options)); + } + + private static RowType appendFields(RowType baseRowType, List<DataField> extraFields) { + if (extraFields.isEmpty()) { + return baseRowType; + } + + boolean hasExistingMetadata = false; + for (DataField extraField : extraFields) { + if (baseRowType.containsField(extraField.name())) { + hasExistingMetadata = true; + } + } + if (hasExistingMetadata) { + boolean allExisting = + extraFields.stream().allMatch(field -> baseRowType.containsField(field.name())); + if (allExisting) { + return baseRowType; + } + throw new IllegalArgumentException( + "Changelog event metadata fields conflict with the requested row type."); + } + + List<DataField> fields = new ArrayList<>(baseRowType.getFields()); + fields.addAll(extraFields); + return new RowType(fields); + } + + /** + * Adds the physical fields that back requested metadata fields when reading data files. + * + * <p>Data files do not store metadata fields, so readers copy each metadata value from its + * source field. A source field that is not requested is appended; one that is requested is + * widened when its nested children do not cover those of the metadata field. Both cases use the + * union of the requested nested children, so callers must project their output back to the + * requested read type. Returns {@code readType} itself when no change is needed. + */ + public static RowType withMetadataDependencies( + RowType readType, RowType logicalRowType, CoreOptions options) { + List<String> preserveColumns = options.changelogEventMetadataFields(); + if (preserveColumns.isEmpty()) { + return readType; + } + + List<DataField> fields = new ArrayList<>(readType.getFields()); + boolean changed = false; + for (String preserveColumn : preserveColumns) { + String metadataName = metadataFieldName(preserveColumn, options); + if (!readType.containsField(metadataName) + || !logicalRowType.containsField(preserveColumn)) { + continue; + } + DataField sourceField = logicalRowType.getField(preserveColumn); + DataType metadataType = readType.getField(metadataName).type(); + int sourceIndex = readType.getFieldIndex(preserveColumn); + if (sourceIndex < 0) { + fields.add(sourceField.newType(metadataType.copy(sourceField.type().isNullable()))); + changed = true; + continue; + } + DataType requestedType = fields.get(sourceIndex).type(); + DataType dependencyType = + unionPrunedType(sourceField.type(), requestedType, metadataType); + if (!dependencyType.equals(requestedType)) { + fields.set(sourceIndex, fields.get(sourceIndex).newType(dependencyType)); + changed = true; + } + } + return changed ? new RowType(readType.isNullable(), fields) : readType; + } + + /** + * Creates a view of a row read with {@link #withMetadataDependencies} in which each source + * field mapped by {@code fallbackMapping} has the nested shape of its metadata field. Returns + * null if no nested projection is needed. + */ + @Nullable + public static NestedProjectedRow createFallbackProjection( + RowType readType, int[] fallbackMapping) { + List<DataField> fields = new ArrayList<>(readType.getFields()); + for (int i = 0; i < fallbackMapping.length; i++) { + int sourceIndex = fallbackMapping[i]; + if (sourceIndex < 0) { + continue; + } + DataField sourceField = fields.get(sourceIndex); + DataType metadataType = readType.getFields().get(i).type(); + if (sourceField.type().getTypeRoot() != metadataType.getTypeRoot()) { + continue; + } + fields.set( + sourceIndex, + sourceField.newType(metadataType.copy(sourceField.type().isNullable()))); + } + return NestedProjectedRow.create(readType, new RowType(readType.isNullable(), fields)); + } + + /** + * Returns the type of {@code fullType} pruned to the nested children requested by either {@code + * left} or {@code right}, keeping the declared child order of {@code fullType}. + */ + private static DataType unionPrunedType(DataType fullType, DataType left, DataType right) { + // An engine may read a column as a different kind of type, for example a selected-key MAP + // pushdown reads a ROW. Such a type cannot be merged with the metadata field's type. + if (left.getTypeRoot() != fullType.getTypeRoot() + || right.getTypeRoot() != fullType.getTypeRoot()) { + return left; Review Comment: [P2] Retain a full MAP dependency beside selected-key physical reads Returning the physical selected-key ROW here leaves a full MAP metadata field backed by that ROW. With a shared-shredding payload MAP and event-metadata-fields=payload, real Spark 3.5 SQL SELECT payload['a'], __internal__payload FROM T pushes PushedMapSelectedKeys:[payload=[a]] and then fails with ClassCastException (CastedRowColumnVector to MapColumnVector) through FallbackMappingRow.getMap. Selecting the full physical map plus metadata, or only payload['a'], both succeeds. I reproduced this on real compacted Parquet files using the exact current Spark 3.5 optimizer implementation, in addition to a Core read-type probe. Please retain an independent full source-map dependency or prevent this selected-key pruning when full metadata needs that source, rather than reusing the incompatible ROW fallback. ########## paimon-core/src/main/java/org/apache/paimon/io/KeyValueDataFileRecordReader.java: ########## @@ -67,6 +82,15 @@ public FileRecordIterator<KeyValue> readBatch() throws IOException { return null; } KeyValue kv = serializer.fromRow(internalRow).setLevel(level); + if (metadataFallbackRow != null) { Review Comment: [P2] Populate ordinary-file fallback metadata after merging values This copies metadata from each input file before the merge engine runs. For an aggregation table, the synthetic field does not inherit its source's aggregation function, so it is merged using the default last_non_null_value. With legal lookup/event-metadata=amount, fields.amount.aggregate-function=sum and write-only=true, two commits of amount 10 and 20 return an ordinary snapshot row amount=30, __internal__amount=20. Full compaction changes only the file layout and then the same row reads 30,30; the last_non_null_value control remains 20,20 throughout. Independent real-file runs also reproduce it with metadata-only projection. Please derive fallback values from the final merged physical row (or preserve the source merge semantics), while retaining the actual event metadata stored in changelog files. ########## paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonSparkTableBase.scala: ########## @@ -48,6 +49,16 @@ abstract class PaimonSparkTableBase(val table: Table) lazy val coreOptions = new CoreOptions(table.options()) + override lazy val schema: org.apache.spark.sql.types.StructType = { + val baseRowType = table.rowType() + val extendedRowType = table match { + case fst: FileStoreTable if !coreOptions.changelogEventMetadataFields().isEmpty => + ChangelogEventMetadataTable.computeExtendedRowType(fst, baseRowType) Review Comment: [P2] Keep synthetic metadata out of MERGE target assignment alignment Exposing these read-only fields through schema also adds them to DataSourceV2Relation.output, but the MERGE resolver still expands and aligns assignments against that full output. Under the default merge-schema=false, an ordinary physical-only source now fails both WHEN MATCHED THEN UPDATE SET * and WHEN NOT MATCHED THEN INSERT * with "source is missing" __internal__event_ts. Actual Spark SQL controls show that explicit physical assignments succeed on the same metadata-enabled table, and both stars succeed on the same lookup table without this option. The new INSERT/V2 write filtering happens later and does not cover MERGE analysis. Please align MERGE stars against physical target fields while continuing to expose metadata for reads. ########## paimon-core/src/main/java/org/apache/paimon/table/source/splitread/IncrementalDiffSplitRead.java: ########## @@ -76,6 +77,9 @@ public SplitRead<InternalRow> withIOManager(@Nullable IOManager ioManager) { @Override public SplitRead<InternalRow> withReadType(RowType readType) { this.readType = readType; + // Let the merge read add its internal dependencies, such as sequence fields and the + // source fields of event metadata, so the diff is computed on a consistent value layout. + mergeRead.withReadType(readType); Review Comment: [P1] Compute diff membership before applying the requested projection Pushing the requested columns into both merge readers makes DiffMerger compare only those columns. A key whose unselected value changed is therefore dropped as unchanged. This also affects ordinary PK tables without event metadata: after committing (id=1,v=10), updating to v=20 and full-compacting, the same incremental diff returns [1,20] with the full schema but no rows when projected to id; the merge-base implementation returns [1] for the latter. The existing IncrementalTableTest.testTagIncremental also fails locally and in both exact-head JDK 8/11 CI jobs (expected [2,6], actual [6]). Please retain all values needed to decide whether the row changed and project only after computing the diff, while adding metadata dependencies separately. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
