gustavodemorais commented on code in PR #29967: URL: https://github.com/apache/flink/pull/29967#discussion_r4589307434
########## flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/Deduplicate.java: ########## @@ -0,0 +1,59 @@ +/* + * 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.flink.table.runtime.functions.ptf; + +import org.apache.flink.annotation.Internal; +import org.apache.flink.table.functions.BuiltInFunctionDefinitions; +import org.apache.flink.table.functions.UserDefinedFunction; +import org.apache.flink.table.runtime.functions.BuiltInSpecializedFunction; +import org.apache.flink.table.types.inference.CallContext; +import org.apache.flink.table.types.inference.strategies.DeduplicateTypeStrategy; +import org.apache.flink.table.types.inference.strategies.DeduplicateTypeStrategyUtils.Keep; + +/** + * Runtime implementation of {@link BuiltInFunctionDefinitions#DEDUPLICATE}. + * + * <pre> + * keep sequence_by implementation + * first absent {@link DeduplicateFirstArrivalFunction} + * first present {@link DeduplicateKeptRowFunction} + * last any {@link DeduplicateKeptRowFunction} + * </pre> + */ +@Internal +public class Deduplicate extends BuiltInSpecializedFunction { + + public Deduplicate() { + super(BuiltInFunctionDefinitions.DEDUPLICATE); + } + + @Override + public UserDefinedFunction specialize(final SpecializedContext context) { + final CallContext callContext = context.getCallContext(); + final boolean isKeepFirst = DeduplicateTypeStrategy.keep(callContext) == Keep.FIRST; + final boolean hasSequenceBy = + DeduplicateTypeStrategy.sequenceByOutputIndices(callContext).length > 0; + + if (isKeepFirst && !hasSequenceBy) { + return new DeduplicateFirstArrivalFunction(context); Review Comment: Could we find shorter, more intuitive names for the two variants? Naming them after what they do might help, e.g. one that never replaces the first row and one that can replace the kept row (`DeduplicateFirstSeenFunction` / `DeduplicateReplacingFunction`, or similar). ########## flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/DeduplicateTypeStrategy.java: ########## @@ -0,0 +1,176 @@ +/* + * 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.flink.table.types.inference.strategies; + +import org.apache.flink.annotation.Internal; +import org.apache.flink.table.api.DataTypes; +import org.apache.flink.table.api.ValidationException; +import org.apache.flink.table.connector.ChangelogMode; +import org.apache.flink.table.functions.ChangelogFunction.ChangelogContext; +import org.apache.flink.table.functions.ChangelogModeStrategy; +import org.apache.flink.table.functions.TableSemantics; +import org.apache.flink.table.types.DataType; +import org.apache.flink.table.types.inference.CallContext; +import org.apache.flink.table.types.inference.InputTypeStrategy; +import org.apache.flink.table.types.inference.TypeStrategy; +import org.apache.flink.table.types.inference.strategies.DeduplicateTypeStrategyUtils.Keep; +import org.apache.flink.types.ColumnList; +import org.apache.flink.types.RowKind; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.apache.flink.table.types.inference.SystemTypeInference.PROCESS_TABLE_FUNCTION_ARG_ON_TIME_OFFSET; + +/** + * Type strategies for the {@code DEDUPLICATE} process table function. + * + * <p>The output is updating and keyed by the PARTITION BY columns: the PARTITION BY columns + * followed by the remaining input columns, without time attributes. + */ +@Internal +public final class DeduplicateTypeStrategy { + + public static final int ARG_INPUT = 0; + public static final int ARG_KEEP = 1; + public static final int ARG_SEQUENCE_BY = 2; + public static final int ARG_STATE_TTL = 3; + public static final int ARG_RESET_TTL_ON_DUPLICATE = 4; + private static final int DECLARED_ARG_COUNT = ARG_RESET_TTL_ON_DUPLICATE + 1; + private static final String NAME = "DEDUPLICATE"; + + public static final InputTypeStrategy INPUT_TYPE_STRATEGY = + new ValidationOnlyInputTypeStrategy() { + @Override + public Optional<List<DataType>> inferInputTypes( + final CallContext callContext, final boolean throwOnFailure) { + final Optional<String> error = validate(callContext); + if (error.isPresent()) { + return callContext.fail(throwOnFailure, "%s", error.get()); + } + return Optional.of(callContext.getArgumentDataTypes()); + } + }; + + public static final TypeStrategy OUTPUT_TYPE_STRATEGY = + callContext -> + Optional.of( + DataTypes.ROW( + DeduplicateTypeStrategyUtils.outputFields( + tableSemantics(callContext))) + .notNull()); + + public static final ChangelogModeStrategy CHANGELOG_MODE_STRATEGY = + DeduplicateTypeStrategy::inferChangelogMode; + + /** Returns the {@code keep} argument, or {@link Keep#FIRST} when it is omitted. */ + public static Keep keep(final CallContext callContext) { + return DeduplicateTypeStrategyUtils.keep(callContext, ARG_KEEP); + } + + /** + * Returns the positions of the {@code sequence_by} columns, in the listed order, within the + * output row without the PARTITION BY columns. + */ + public static int[] sequenceByOutputIndices(final CallContext callContext) { + return DeduplicateTypeStrategyUtils.sequenceByOutputIndices( + callContext, tableSemantics(callContext), ARG_SEQUENCE_BY); + } + + private static Optional<String> validate(final CallContext callContext) { + final TableSemantics tableSemantics = tableSemantics(callContext); + return validateNoOrderBy(tableSemantics) + .or( + () -> + DeduplicateTypeStrategyUtils.validatePartitionByNoTimeAttribute( + tableSemantics, NAME)) + .or(() -> validateOnTime(callContext)) + .or(() -> DeduplicateTypeStrategyUtils.validateKeep(callContext, ARG_KEEP, NAME)) + .or( + () -> + DeduplicateTypeStrategyUtils.validateSequenceBy( + callContext, tableSemantics, ARG_SEQUENCE_BY, NAME)) + .or(() -> DeduplicateTypeStrategyUtils.validateStateTtl(callContext, ARG_STATE_TTL)) + .or( + () -> + DeduplicateTypeStrategyUtils.validateResetTtlOnDuplicate( + callContext, ARG_RESET_TTL_ON_DUPLICATE)); + } + + private static Optional<String> validateNoOrderBy(final TableSemantics tableSemantics) { + if (tableSemantics.orderByColumns().length == 0) { + return Optional.empty(); + } + final List<String> fieldNames = DataType.getFieldNames(tableSemantics.dataType()); + final String columns = + Arrays.stream(tableSemantics.orderByColumns()) + .mapToObj(fieldNames::get) + .collect(Collectors.joining(", ")); + return Optional.of( + String.format( + "DEDUPLICATE does not support ORDER BY on its input, but received " + + "ORDER BY %s. Use sequence_by => DESCRIPTOR(%s) to order the " + + "records of a key.", + columns, columns)); + } + + private static Optional<String> validateOnTime(final CallContext callContext) { Review Comment: I see why this is needed today: `on_time` is a system argument added to every PTF, and `disableSystemArguments()` would also remove `uid`. But every PTF without event time has the same issue. Could you look into a general solution in the framework, e.g. disabling only `on_time` while keeping `uid`? Then no PTF needs a custom check for it. ########## flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/DeduplicateTypeStrategyUtils.java: ########## @@ -0,0 +1,257 @@ +/* + * 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.flink.table.types.inference.strategies; + +import org.apache.flink.annotation.Internal; +import org.apache.flink.table.api.DataTypes; +import org.apache.flink.table.api.DataTypes.Field; +import org.apache.flink.table.functions.TableSemantics; +import org.apache.flink.table.types.DataType; +import org.apache.flink.table.types.inference.CallContext; +import org.apache.flink.table.types.logical.LogicalType; +import org.apache.flink.table.types.logical.LogicalTypeFamily; +import org.apache.flink.table.types.logical.LogicalTypeRoot; +import org.apache.flink.table.types.logical.utils.LogicalTypeChecks; +import org.apache.flink.table.types.utils.DataTypeUtils; +import org.apache.flink.types.ColumnList; +import org.apache.flink.util.TimeUtils; + +import java.time.Duration; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +/** Argument validation and output type helpers shared by the deduplication PTFs. */ +@Internal +public final class DeduplicateTypeStrategyUtils { + + /** Which record of a key is kept. */ + @Internal + public enum Keep { + FIRST("first"), + LAST("last"); + + private final String value; + + Keep(final String value) { + this.value = value; + } + + /** Returns the mode for an argument value, or empty if the value names no mode. */ + public static Optional<Keep> fromValue(final String value) { + return Arrays.stream(values()).filter(keep -> keep.value.equals(value)).findFirst(); + } + } + + /** Returns the {@code keep} argument, or {@link Keep#FIRST} when it is omitted. */ + public static Keep keep(final CallContext callContext, final int argPos) { + return callContext + .getArgumentValue(argPos, String.class) + .map( + value -> + Keep.fromValue(value) + .orElseThrow( + () -> + new IllegalStateException( + "Validated keep argument expected."))) + .orElse(Keep.FIRST); + } + + /** + * Returns the positions of the {@code sequence_by} columns, in the listed order, within the + * output row without the PARTITION BY columns. + */ + public static int[] sequenceByOutputIndices( + final CallContext callContext, final TableSemantics tableSemantics, final int argPos) { + final List<String> fieldNames = DataType.getFieldNames(tableSemantics.dataType()); + final List<Integer> outputIndices = + Arrays.stream(ChangelogTypeStrategyUtils.computeOutputIndices(tableSemantics)) + .boxed() + .collect(Collectors.toList()); + return sequenceBy(callContext, argPos).stream() + .mapToInt(column -> outputIndices.indexOf(fieldNames.indexOf(column))) + .toArray(); + } + + /** Returns the output columns after the PARTITION BY columns, without time attributes. */ + public static List<Field> outputFields(final TableSemantics tableSemantics) { + final List<Field> inputFields = DataType.getFields(tableSemantics.dataType()); + return Arrays.stream(ChangelogTypeStrategyUtils.computeOutputIndices(tableSemantics)) + .mapToObj(inputFields::get) + .map( + field -> + DataTypes.FIELD( + field.getName(), + DataTypeUtils.removeTimeAttribute(field.getDataType()))) + .collect(Collectors.toList()); + } + + public static Optional<String> validatePartitionByNoTimeAttribute( + final TableSemantics tableSemantics, final String functionName) { + final List<Field> fields = DataType.getFields(tableSemantics.dataType()); + return Arrays.stream(tableSemantics.partitionByColumns()) + .mapToObj(fields::get) + .filter( + field -> + LogicalTypeChecks.isTimeAttribute( + field.getDataType().getLogicalType())) + .findFirst() + .map( + field -> + String.format( + "%s does not support a time attribute as a " + + "PARTITION BY column, but '%s' is one. Partition " + + "by a regular column, or cast the column in a " + + "subquery first, for example CAST(%s AS %s) AS %s.", + functionName, + field.getName(), + field.getName(), + DataTypeUtils.removeTimeAttribute(field.getDataType()) + .getLogicalType() + .asSummaryString(), + field.getName())); + } + + public static Optional<String> validateKeep( + final CallContext callContext, final int argPos, final String functionName) { + if (callContext.isArgumentNull(argPos)) { + return Optional.empty(); + } + final String received; + if (!callContext.isArgumentLiteral(argPos)) { + received = "a non-literal expression"; + } else { + final String value = callContext.getArgumentValue(argPos, String.class).orElse(null); + if (value == null || Keep.fromValue(value).isPresent()) { + return Optional.empty(); + } + received = String.format("keep => '%s'", value); + } + return Optional.of( + String.format( + "%s requires keep => 'first' or keep => 'last', but received %s. " + + "Use keep => 'first' to keep the first record per key, or " + + "keep => 'last' to keep the last one.", + functionName, received)); + } + + public static Optional<String> validateSequenceBy( + final CallContext callContext, + final TableSemantics tableSemantics, + final int argPos, + final String functionName) { + final List<String> fieldNames = DataType.getFieldNames(tableSemantics.dataType()); + final List<DataType> fieldTypes = DataType.getFieldDataTypes(tableSemantics.dataType()); + final Set<String> seen = new HashSet<>(); + for (final String column : sequenceBy(callContext, argPos)) { + final int index = fieldNames.indexOf(column); + if (index == -1) { + return Optional.of( + String.format( + "The sequence_by column '%s' does not exist in the input of " + + "%s. Available columns are: %s.", + column, functionName, String.join(", ", fieldNames))); + } + if (!seen.add(column)) { + return Optional.of( + String.format( + "The sequence_by column '%s' is listed more than once. List each " + + "ordering column once.", + column)); + } + if (Arrays.stream(tableSemantics.partitionByColumns()).anyMatch(c -> c == index)) { + return Optional.of( + String.format( + "The sequence_by column '%s' is a PARTITION BY column, which has " + + "the same value for every record of a key. Use a " + + "column that is not part of PARTITION BY, such as a " + + "version or sequence number.", + column)); + } + final LogicalType type = fieldTypes.get(index).getLogicalType(); + if (!isOrderable(type)) { + return Optional.of( + String.format( + "The sequence_by column '%s' has type '%s', which cannot order " + + "records. Use a numeric, character string, binary " + + "string, boolean, or date-time column.", + column, type.asSummaryString())); + } + } + return Optional.empty(); + } + + public static Optional<String> validateStateTtl( Review Comment: There's no shared helper for this yet: `state_ttl` is declared by each function itself, and other functions take one too (e.g. LATERAL SNAPSHOT). Could this become a shared helper for all PTFs instead of a deduplicate-specific one? ########## flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateKeptRowFunction.java: ########## @@ -0,0 +1,196 @@ +/* + * 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.flink.table.runtime.functions.ptf; + +import org.apache.flink.annotation.Internal; +import org.apache.flink.table.api.DataTypes; +import org.apache.flink.table.api.dataview.ValueView; +import org.apache.flink.table.data.GenericRowData; +import org.apache.flink.table.data.RowData; +import org.apache.flink.table.data.StringData; +import org.apache.flink.table.data.binary.BinaryRowData; +import org.apache.flink.table.data.utils.JoinedRowData; +import org.apache.flink.table.functions.FunctionContext; +import org.apache.flink.table.functions.SpecializedFunction.SpecializedContext; +import org.apache.flink.table.runtime.functions.ptf.DeduplicateUtils.SequenceComparator; +import org.apache.flink.table.runtime.typeutils.RowDataSerializer; +import org.apache.flink.table.types.DataType; +import org.apache.flink.table.types.inference.CallContext; +import org.apache.flink.table.types.inference.StateTypeStrategy; +import org.apache.flink.table.types.inference.strategies.DeduplicateTypeStrategy; +import org.apache.flink.table.types.inference.strategies.DeduplicateTypeStrategyUtils; +import org.apache.flink.table.types.inference.strategies.DeduplicateTypeStrategyUtils.Keep; +import org.apache.flink.table.types.logical.LogicalType; +import org.apache.flink.types.ColumnList; +import org.apache.flink.types.RowKind; + +import javax.annotation.Nullable; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +/** + * {@link Deduplicate} with {@code keep => 'last'}, or {@code keep => 'first'} with {@code + * sequence_by}: a later record can replace the kept one, so the kept record is held in the {@code + * kept} state. + */ +@Internal +public class DeduplicateKeptRowFunction extends DeduplicateFunctionBase { + + private static final long serialVersionUID = 1L; + + private final Keep keep; + + private final LogicalType[] payloadTypes; + + private final boolean isUpdateBeforeEmitted; + + private final @Nullable SequenceComparator sequenceComparator; + + private transient RowData.FieldGetter[] payloadGetters; + + private transient RowDataSerializer candidateSerializer; + + private transient RowDataSerializer currentSerializer; + + private transient GenericRowData reusedCandidate; + + private transient JoinedRowData output; + + private transient RowData emptyRow; + + DeduplicateKeptRowFunction(final SpecializedContext context) { + super(context, internalState(Map.entry("kept", keptState(context)))); + final CallContext callContext = context.getCallContext(); + this.keep = DeduplicateTypeStrategy.keep(callContext); + this.payloadTypes = + DeduplicateTypeStrategyUtils.outputFields(DeduplicateUtils.tableSemantics(context)) + .stream() + .map(field -> field.getDataType().getLogicalType()) + .toArray(LogicalType[]::new); + this.isUpdateBeforeEmitted = + callContext + .getOutputChangelogMode() + .map(mode -> mode.contains(RowKind.UPDATE_BEFORE)) + .orElse(false); + this.sequenceComparator = sequenceComparator(context, outputIndices); + } + + @Override + public void open(final FunctionContext context) throws Exception { + super.open(context); + payloadGetters = new RowData.FieldGetter[outputIndices.length]; + for (int i = 0; i < outputIndices.length; i++) { + payloadGetters[i] = RowData.createFieldGetter(payloadTypes[i], outputIndices[i]); + } + if (sequenceComparator != null) { + sequenceComparator.open(context); + } + // toBinaryRow reuses its result row, so each side of a comparison needs its own + // serializer + candidateSerializer = new RowDataSerializer(payloadTypes); + currentSerializer = new RowDataSerializer(payloadTypes); + reusedCandidate = new GenericRowData(outputIndices.length); + output = new JoinedRowData(); + emptyRow = GenericRowData.of(); + } + + @Override + public void close() throws Exception { + if (sequenceComparator != null) { + sequenceComparator.close(); + } + super.close(); + } + + public void eval( Review Comment: This is a lot of work per record: copying the fields into a `GenericRowData` (boxing), serializing it, running a second serializer on the kept row (a no-op, since the row from state is already binary), copying again before writing to state, and emitting through a `JoinedRowData` with an empty row. Could we project once, serialize once, and compare directly with the row from state? That would also make the function much easier to read. ########## flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/runtime/harness/DeduplicateHarnessTest.java: ########## @@ -0,0 +1,227 @@ +/* + * 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.flink.table.planner.runtime.harness; + +import org.apache.flink.api.dag.Transformation; +import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; +import org.apache.flink.streaming.api.operators.StreamOperatorFactory; +import org.apache.flink.streaming.api.transformations.KeyedMultipleInputTransformation; +import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; +import org.apache.flink.streaming.util.KeyedMultiInputStreamOperatorTestHarness; +import org.apache.flink.table.api.bridge.java.StreamTableEnvironment; +import org.apache.flink.table.data.GenericRowData; +import org.apache.flink.table.data.RowData; +import org.apache.flink.table.data.StringData; +import org.apache.flink.table.runtime.keyselector.RowDataKeySelector; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.function.Function; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Harness tests for the processing-time state retention of the built-in DEDUPLICATE PTF, which need + * control over the time that state TTL observes. + */ +class DeduplicateHarnessTest { Review Comment: Do we need this test? The framework already tests the TTL plumbing (`PROCESS_STATE_TTL`), and TTL expiry is state backend behavior. The only deduplicate-specific part is `reset_ttl_on_duplicate`, which is still open in the FLIP. If we keep the parameter, one parameterized test should be enough. -- 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]
