gustavodemorais commented on code in PR #29967:
URL: https://github.com/apache/flink/pull/29967#discussion_r4694299233


##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/definitions/DeduplicateDefinition.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * 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.functions.definitions;
+
+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.connector.ChangelogMode;
+import org.apache.flink.table.functions.BuiltInFunctionDefinition;
+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.StaticArgument;
+import org.apache.flink.table.types.inference.StaticArgumentTrait;
+import org.apache.flink.table.types.inference.TypeStrategy;
+import 
org.apache.flink.table.types.inference.strategies.ChangelogTypeStrategyUtils;
+import 
org.apache.flink.table.types.inference.strategies.ValidationOnlyInputTypeStrategy;
+import org.apache.flink.table.types.inference.utils.CallContextUtils;
+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.types.ColumnList;
+import org.apache.flink.types.Row;
+import org.apache.flink.types.RowKind;
+
+import java.util.Arrays;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.table.functions.FunctionKind.PROCESS_TABLE;
+
+/**
+ * Definition of the {@code DEDUPLICATE} built-in 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.
+ */
+@Internal
+public final class DeduplicateDefinition {
+
+    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;
+
+    private static final String NAME = "DEDUPLICATE";
+
+    /** Which record of a key is kept. */
+    @Internal
+    public enum Keep {
+        FIRST,
+        LAST
+    }
+
+    static final InputTypeStrategy INPUT_TYPE_STRATEGY =

Review Comment:
   Since other functions will follow this pattern, could we order the file top 
to bottom: `INSTANCE` first (what the function is), then argument positions and 
enums, then the accessors used by the runtime, then the strategies in builder 
order (input, output, changelog), then private helpers? For `INSTANCE` to come 
first, the strategies need to be method references (e.g. 
`.outputTypeStrategy(DeduplicateDefinition::inferOutputType)`) instead of 
static fields declared above it, otherwise they are still null during class 
initialization.



##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/definitions/DeduplicateDefinition.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * 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.functions.definitions;
+
+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.connector.ChangelogMode;
+import org.apache.flink.table.functions.BuiltInFunctionDefinition;
+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.StaticArgument;
+import org.apache.flink.table.types.inference.StaticArgumentTrait;
+import org.apache.flink.table.types.inference.TypeStrategy;
+import 
org.apache.flink.table.types.inference.strategies.ChangelogTypeStrategyUtils;
+import 
org.apache.flink.table.types.inference.strategies.ValidationOnlyInputTypeStrategy;
+import org.apache.flink.table.types.inference.utils.CallContextUtils;
+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.types.ColumnList;
+import org.apache.flink.types.Row;
+import org.apache.flink.types.RowKind;
+
+import java.util.Arrays;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.table.functions.FunctionKind.PROCESS_TABLE;
+
+/**
+ * Definition of the {@code DEDUPLICATE} built-in 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.
+ */
+@Internal
+public final class DeduplicateDefinition {
+
+    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;
+
+    private static final String NAME = "DEDUPLICATE";
+
+    /** Which record of a key is kept. */
+    @Internal
+    public enum Keep {
+        FIRST,
+        LAST
+    }
+
+    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());
+                }
+            };
+
+    static final TypeStrategy OUTPUT_TYPE_STRATEGY =
+            callContext ->
+                    
Optional.of(DataTypes.ROW(outputFields(tableSemantics(callContext))).notNull());
+
+    static final ChangelogModeStrategy CHANGELOG_MODE_STRATEGY =
+            DeduplicateDefinition::inferChangelogMode;
+
+    public static final BuiltInFunctionDefinition INSTANCE =
+            BuiltInFunctionDefinition.newBuilder()
+                    .name(NAME)
+                    .kind(PROCESS_TABLE)
+                    .staticArguments(
+                            StaticArgument.table(
+                                    "input",
+                                    Row.class,
+                                    false,
+                                    EnumSet.of(
+                                            StaticArgumentTrait.TABLE,
+                                            
StaticArgumentTrait.SET_SEMANTIC_TABLE,
+                                            StaticArgumentTrait.NO_ORDER_BY)),
+                            StaticArgument.scalar("keep", DataTypes.STRING(), 
true),
+                            StaticArgument.scalar("sequence_by", 
DataTypes.DESCRIPTOR(), true),
+                            StaticArgument.scalar(
+                                    "state_ttl", 
DataTypes.INTERVAL(DataTypes.SECOND()), true))
+                    .changelogModeStrategy(CHANGELOG_MODE_STRATEGY)
+                    .inputTypeStrategy(INPUT_TYPE_STRATEGY)
+                    .outputTypeStrategy(OUTPUT_TYPE_STRATEGY)
+                    
.runtimeClass("org.apache.flink.table.runtime.functions.ptf.Deduplicate")
+                    .build();
+
+    /** Returns the {@code keep} argument, or {@link Keep#FIRST} when it is 
omitted. */
+    public static Keep keep(final CallContext callContext) {
+        return CallContextUtils.getEnumArgument(callContext, ARG_KEEP, 
Keep.class)
+                .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 = tableSemantics(callContext);
+        final List<String> fieldNames = 
DataType.getFieldNames(tableSemantics.dataType());
+        final List<Integer> outputIndices =
+                
Arrays.stream(ChangelogTypeStrategyUtils.computeOutputIndices(tableSemantics))
+                        .boxed()
+                        .collect(Collectors.toList());
+        return sequenceBy(callContext).stream()
+                .mapToInt(column -> 
outputIndices.indexOf(fieldNames.indexOf(column)))
+                .toArray();
+    }
+
+    private static Optional<String> validate(final CallContext callContext) {
+        final TableSemantics tableSemantics = tableSemantics(callContext);
+        return CallContextUtils.validateEnumArgument(
+                        callContext, ARG_KEEP, "keep", NAME, Keep.class)
+                .or(() -> validateSequenceBy(callContext, tableSemantics))
+                .or(() -> CallContextUtils.validateStateTtl(callContext, 
ARG_STATE_TTL));
+    }
+
+    private static ChangelogMode inferChangelogMode(final ChangelogContext 
changelogContext) {
+        final ChangelogMode requiredMode = 
changelogContext.getRequiredChangelogMode();
+        final ChangelogMode.Builder builder =
+                ChangelogMode.newBuilder()
+                        .addContainedKind(RowKind.INSERT)
+                        .addContainedKind(RowKind.UPDATE_AFTER);
+        if (requiredMode != null && 
requiredMode.contains(RowKind.UPDATE_BEFORE)) {
+            builder.addContainedKind(RowKind.UPDATE_BEFORE);
+        }
+        return builder.build();
+    }
+
+    private static TableSemantics tableSemantics(final CallContext 
callContext) {
+        return CallContextUtils.getTableSemanticsOrThrow(callContext, 
ARG_INPUT);
+    }
+
+    /** Returns the output columns after the PARTITION BY columns. */
+    private static List<Field> outputFields(final TableSemantics 
tableSemantics) {
+        final List<Field> inputFields = 
DataType.getFields(tableSemantics.dataType());
+        return 
Arrays.stream(ChangelogTypeStrategyUtils.computeOutputIndices(tableSemantics))
+                .mapToObj(inputFields::get)
+                .collect(Collectors.toList());
+    }
+
+    private static Optional<String> validateSequenceBy(
+            final CallContext callContext, final TableSemantics 
tableSemantics) {
+        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)) {
+            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, NAME, String.join(", ", fieldNames)));
+            }
+            if (!seen.add(column)) {

Review Comment:
   Do we need this one? Listing a column twice is harmless (the second 
comparison always ties), so we could drop the check.



##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/stream/sql/DeduplicateTableFunctionTest.java:
##########
@@ -0,0 +1,142 @@
+/*
+ * 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.plan.stream.sql;
+
+import org.apache.flink.table.api.ExplainDetail;
+import org.apache.flink.table.api.Table;
+import org.apache.flink.table.api.TableConfig;
+import org.apache.flink.table.planner.utils.PlanKind;
+import org.apache.flink.table.planner.utils.TableTestBase;
+import org.apache.flink.table.planner.utils.TableTestUtil;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.time.Duration;
+
+import scala.Enumeration;
+
+import static org.apache.flink.core.testutils.FlinkAssertions.anyCauseMatches;
+import static org.apache.flink.table.api.Expressions.$;
+import static org.apache.flink.table.api.Expressions.descriptor;
+import static org.apache.flink.table.api.Expressions.lit;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Plan tests for the changelog mode and upsert key of the DEDUPLICATE 
built-in PTF. */
+class DeduplicateTableFunctionTest extends TableTestBase {
+
+    private TableTestUtil util;
+
+    @BeforeEach
+    void setup() {
+        util = streamTestUtil(TableConfig.getDefault());
+        util.tableEnv()
+                .executeSql(
+                        "CREATE TABLE user_events (user_id STRING, event 
STRING, "
+                                + "ts TIMESTAMP_LTZ(3), WATERMARK FOR ts AS 
ts) "
+                                + "WITH ('connector' = 'values')");
+        util.tableEnv()
+                .executeSql(
+                        "CREATE TABLE customer_changes (customer_id STRING, 
city STRING, "
+                                + "lsn BIGINT) WITH ('connector' = 'values')");
+    }
+
+    @Test
+    void testUpsertKeyIsPartitionKey() {
+        verifyPlan(
+                "SELECT * FROM DEDUPLICATE("
+                        + "input => TABLE user_events PARTITION BY user_id, 
keep => 'last')");
+    }
+
+    @Test
+    void testOrderByIsRejected() {

Review Comment:
   `NO_ORDER_BY` is a generic trait, but this is its only test. Could we move 
this case to the framework tests (e.g. `ProcessTableFunctionTest`)?



##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/definitions/DeduplicateDefinition.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * 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.functions.definitions;
+
+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.connector.ChangelogMode;
+import org.apache.flink.table.functions.BuiltInFunctionDefinition;
+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.StaticArgument;
+import org.apache.flink.table.types.inference.StaticArgumentTrait;
+import org.apache.flink.table.types.inference.TypeStrategy;
+import 
org.apache.flink.table.types.inference.strategies.ChangelogTypeStrategyUtils;
+import 
org.apache.flink.table.types.inference.strategies.ValidationOnlyInputTypeStrategy;
+import org.apache.flink.table.types.inference.utils.CallContextUtils;
+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.types.ColumnList;
+import org.apache.flink.types.Row;
+import org.apache.flink.types.RowKind;
+
+import java.util.Arrays;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.table.functions.FunctionKind.PROCESS_TABLE;
+
+/**
+ * Definition of the {@code DEDUPLICATE} built-in 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.
+ */
+@Internal
+public final class DeduplicateDefinition {
+
+    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;
+
+    private static final String NAME = "DEDUPLICATE";
+
+    /** Which record of a key is kept. */
+    @Internal
+    public enum Keep {
+        FIRST,
+        LAST
+    }
+
+    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());
+                }
+            };
+
+    static final TypeStrategy OUTPUT_TYPE_STRATEGY =
+            callContext ->
+                    
Optional.of(DataTypes.ROW(outputFields(tableSemantics(callContext))).notNull());
+
+    static final ChangelogModeStrategy CHANGELOG_MODE_STRATEGY =
+            DeduplicateDefinition::inferChangelogMode;
+
+    public static final BuiltInFunctionDefinition INSTANCE =
+            BuiltInFunctionDefinition.newBuilder()
+                    .name(NAME)
+                    .kind(PROCESS_TABLE)
+                    .staticArguments(
+                            StaticArgument.table(
+                                    "input",
+                                    Row.class,
+                                    false,
+                                    EnumSet.of(
+                                            StaticArgumentTrait.TABLE,
+                                            
StaticArgumentTrait.SET_SEMANTIC_TABLE,
+                                            StaticArgumentTrait.NO_ORDER_BY)),
+                            StaticArgument.scalar("keep", DataTypes.STRING(), 
true),
+                            StaticArgument.scalar("sequence_by", 
DataTypes.DESCRIPTOR(), true),
+                            StaticArgument.scalar(
+                                    "state_ttl", 
DataTypes.INTERVAL(DataTypes.SECOND()), true))
+                    .changelogModeStrategy(CHANGELOG_MODE_STRATEGY)
+                    .inputTypeStrategy(INPUT_TYPE_STRATEGY)
+                    .outputTypeStrategy(OUTPUT_TYPE_STRATEGY)
+                    
.runtimeClass("org.apache.flink.table.runtime.functions.ptf.Deduplicate")
+                    .build();
+
+    /** Returns the {@code keep} argument, or {@link Keep#FIRST} when it is 
omitted. */
+    public static Keep keep(final CallContext callContext) {
+        return CallContextUtils.getEnumArgument(callContext, ARG_KEEP, 
Keep.class)
+                .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 = tableSemantics(callContext);
+        final List<String> fieldNames = 
DataType.getFieldNames(tableSemantics.dataType());
+        final List<Integer> outputIndices =
+                
Arrays.stream(ChangelogTypeStrategyUtils.computeOutputIndices(tableSemantics))
+                        .boxed()
+                        .collect(Collectors.toList());
+        return sequenceBy(callContext).stream()
+                .mapToInt(column -> 
outputIndices.indexOf(fieldNames.indexOf(column)))
+                .toArray();
+    }
+
+    private static Optional<String> validate(final CallContext callContext) {
+        final TableSemantics tableSemantics = tableSemantics(callContext);
+        return CallContextUtils.validateEnumArgument(
+                        callContext, ARG_KEEP, "keep", NAME, Keep.class)
+                .or(() -> validateSequenceBy(callContext, tableSemantics))
+                .or(() -> CallContextUtils.validateStateTtl(callContext, 
ARG_STATE_TTL));
+    }
+
+    private static ChangelogMode inferChangelogMode(final ChangelogContext 
changelogContext) {
+        final ChangelogMode requiredMode = 
changelogContext.getRequiredChangelogMode();
+        final ChangelogMode.Builder builder =
+                ChangelogMode.newBuilder()
+                        .addContainedKind(RowKind.INSERT)
+                        .addContainedKind(RowKind.UPDATE_AFTER);
+        if (requiredMode != null && 
requiredMode.contains(RowKind.UPDATE_BEFORE)) {
+            builder.addContainedKind(RowKind.UPDATE_BEFORE);
+        }
+        return builder.build();
+    }
+
+    private static TableSemantics tableSemantics(final CallContext 
callContext) {
+        return CallContextUtils.getTableSemanticsOrThrow(callContext, 
ARG_INPUT);
+    }
+
+    /** Returns the output columns after the PARTITION BY columns. */
+    private static List<Field> outputFields(final TableSemantics 
tableSemantics) {
+        final List<Field> inputFields = 
DataType.getFields(tableSemantics.dataType());
+        return 
Arrays.stream(ChangelogTypeStrategyUtils.computeOutputIndices(tableSemantics))
+                .mapToObj(inputFields::get)
+                .collect(Collectors.toList());
+    }
+
+    private static Optional<String> validateSequenceBy(
+            final CallContext callContext, final TableSemantics 
tableSemantics) {
+        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)) {
+            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, NAME, 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 "
+                                        + "non-PARTITION BY column.",
+                                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, string, 
boolean, or date-time "
+                                        + "column.",
+                                column, type.asSummaryString()));
+            }
+        }
+        return Optional.empty();
+    }
+
+    private static List<String> sequenceBy(final CallContext callContext) {
+        return callContext
+                .getArgumentValue(ARG_SEQUENCE_BY, ColumnList.class)
+                .map(ColumnList::getNames)
+                .orElse(List.of());
+    }
+
+    private static boolean isOrderable(final LogicalType type) {

Review Comment:
   The list doesn't match the generated comparator anymore (it now supports 
structured types, and e.g. intervals or UUID are orderable too), and the error 
message leaves out binary. Could we use `LogicalTypeChecks.areComparable(type, 
type, StructuredComparison.FULL)`, the same check SQL comparisons use, so there 
is one source of truth?



##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/stream/sql/DeduplicateTableFunctionTest.java:
##########
@@ -0,0 +1,142 @@
+/*
+ * 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.plan.stream.sql;
+
+import org.apache.flink.table.api.ExplainDetail;
+import org.apache.flink.table.api.Table;
+import org.apache.flink.table.api.TableConfig;
+import org.apache.flink.table.planner.utils.PlanKind;
+import org.apache.flink.table.planner.utils.TableTestBase;
+import org.apache.flink.table.planner.utils.TableTestUtil;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.time.Duration;
+
+import scala.Enumeration;
+
+import static org.apache.flink.core.testutils.FlinkAssertions.anyCauseMatches;
+import static org.apache.flink.table.api.Expressions.$;
+import static org.apache.flink.table.api.Expressions.descriptor;
+import static org.apache.flink.table.api.Expressions.lit;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Plan tests for the changelog mode and upsert key of the DEDUPLICATE 
built-in PTF. */
+class DeduplicateTableFunctionTest extends TableTestBase {
+
+    private TableTestUtil util;
+
+    @BeforeEach
+    void setup() {
+        util = streamTestUtil(TableConfig.getDefault());
+        util.tableEnv()
+                .executeSql(
+                        "CREATE TABLE user_events (user_id STRING, event 
STRING, "
+                                + "ts TIMESTAMP_LTZ(3), WATERMARK FOR ts AS 
ts) "
+                                + "WITH ('connector' = 'values')");
+        util.tableEnv()
+                .executeSql(
+                        "CREATE TABLE customer_changes (customer_id STRING, 
city STRING, "
+                                + "lsn BIGINT) WITH ('connector' = 'values')");
+    }
+
+    @Test
+    void testUpsertKeyIsPartitionKey() {
+        verifyPlan(
+                "SELECT * FROM DEDUPLICATE("
+                        + "input => TABLE user_events PARTITION BY user_id, 
keep => 'last')");
+    }
+
+    @Test
+    void testOrderByIsRejected() {
+        assertThatThrownBy(
+                        () ->
+                                util.tableEnv()
+                                        .explainSql(
+                                                "SELECT * FROM 
DEDUPLICATE(input => TABLE "
+                                                        + "user_events 
PARTITION BY user_id "
+                                                        + "ORDER BY ts, keep 
=> 'last')"))
+                .satisfies(
+                        anyCauseMatches(
+                                "Table argument 'input' does not support an 
ORDER BY clause. "
+                                        + "Remove it, and use an argument of 
the function to "
+                                        + "order records if the function 
offers one."));
+    }
+
+    @Test
+    void testRetractingConsumer() {
+        verifyPlan(
+                "SELECT event, COUNT(*) AS users FROM DEDUPLICATE("
+                        + "input => TABLE user_events PARTITION BY user_id, 
keep => 'last') "
+                        + "GROUP BY event");
+    }
+
+    @Test
+    void testOutputHasNoTimeAttribute() {

Review Comment:
   This, `testPartitionByTimeAttribute` and 
`testOnTimeIsRejectedForUpdatingOutput` test framework behavior that 
`ProcessTableFunctionTest` covers now. Can we drop them here?



##########
docs/content/docs/sql/reference/queries/deduplication.md:
##########
@@ -69,4 +69,142 @@ FROM (
 WHERE row_num = 1
 ```
 
+## DEDUPLICATE
+
+{{< label Streaming >}}
+
+The `DEDUPLICATE` process table function (PTF) keeps the first or the last row 
per key of an append-only table, as long as the state of the key is retained. 
Rows are ordered by arrival or by `sequence_by` columns.
+
+### Syntax
+
+```sql
+SELECT * FROM DEDUPLICATE(
+  input => TABLE source_table PARTITION BY key_col[, ...],
+  [keep => 'first' | 'last',]
+  [sequence_by => DESCRIPTOR(col[, ...]),]
+  [state_ttl => INTERVAL '1' HOUR,]
+  [uid => 'my-id']
+)
+```
+
+### Parameters
+
+| Parameter | Required | Description |
+|:----------|:---------|:------------|
+| `input` | Yes | The append-only input table. `PARTITION BY` is required and 
its columns are the key of the output.|
+| `keep` | No | `'first'` (default) keeps the earliest arrival or the lowest 
`sequence_by` value, `'last'` keeps the latest arrival or the highest. Must be 
a literal. Arrival order is not deterministic across reruns, use `sequence_by` 
for a repeatable result. |
+| `sequence_by` | No | One or more columns that order the records of a key 
instead of their arrival, ascending, with strings and binaries compared 
lexicographically. The first column decides, later columns break ties, and 
`NULL` orders below every other value. On a tie, the later arrival wins for 
`'last'` and the earlier one for `'first'`. Columns must be numeric, string, 
binary, boolean or date-time, and not part of `PARTITION BY`. |
+| `state_ttl` | No | How long the state of an idle key is retained, as an 
`INTERVAL` literal. Every record of a key, including a dropped duplicate, 
restarts the TTL. Defaults to `table.exec.state.ttl`, and `INTERVAL '0' SECOND` 
disables expiry. After the state of a key expires, its next record is emitted 
as `+I` again. |
+| `uid` | No | A unique identifier for the PTF invocation. Defaults to 
`DEDUPLICATE`. Can be omitted if the PTF is invoked only once per job. See 
[Query Evolution with UIDs]({{< ref "docs/dev/table/functions/ptfs" 
>}}#query-evolution-with-uids). |
+
+
+### Output
+
+The output columns are the `PARTITION BY` columns, in the order listed, 
followed by the remaining input columns. Time attributes are emitted as regular 
timestamps.
+
+The result has one row per key. When a later row replaces the kept one, the 
row of that key is updated, so the result must be written to a table that 
accepts updates, for example one with a primary key on the `PARTITION BY` 
columns. Currently this holds for every `keep` mode, including `keep => 
'first'` without `sequence_by`, which never replaces a row.
+
+{{< hint info >}}
+The first record of a key is emitted as `+I`. A record that replaces the kept 
one is emitted as `+U`, preceded by `-U` if the consumer needs retractions. A 
record that equals the kept one, or does not replace it, emits nothing. See 
[Updates and Changelogs]({{< ref "docs/dev/table/functions/ptfs" 
>}}#updates-and-changelogs).
+{{< /hint >}}
+
+### Examples
+
+#### Keep the first or the last record
+
+Rows of `user_events` arrive in this order:
+
+| `user_events`   |
+|:----------------|
+| `(u1, login)`   |
+| `(u2, login)`   |
+| `(u1, click)`   |
+
+`keep` defaults to `'first'`, which keeps the first row of each user:
+
+```sql
+SELECT * FROM DEDUPLICATE(
+  input => TABLE user_events PARTITION BY user_id)
+```
+
+| Result          |
+|:----------------|
+| `(u1, login)`   |
+| `(u2, login)`   |
+
+With `keep => 'last'`, a later row replaces the kept one:
+
+```sql
+SELECT * FROM DEDUPLICATE(
+  input => TABLE user_events PARTITION BY user_id,
+  keep => 'last')
+```
+
+| Result          |
+|:----------------|
+| `(u1, click)`   |
+| `(u2, login)`   |
+
+#### Order by a column
+
+`sequence_by` ranks the rows of a key by a column instead of by arrival, so a 
late, older row does not replace a newer one:

Review Comment:
   "late, older row" is a bit ambiguous. Maybe:
   ```suggestion
   `sequence_by` orders the rows of a key by a column instead of by arrival, so 
a row that arrives late with a smaller value does not replace the kept one:
   ```
   (same in the zh copy)



##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateUtils.java:
##########
@@ -0,0 +1,99 @@
+/*
+ * 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.data.RowData;
+import org.apache.flink.table.data.utils.ProjectedRowData;
+import org.apache.flink.table.functions.FunctionContext;
+import org.apache.flink.table.functions.SpecializedFunction.ComparatorOrder;
+import 
org.apache.flink.table.functions.SpecializedFunction.GeneratedComparator;
+import org.apache.flink.table.functions.SpecializedFunction.SpecializedContext;
+import org.apache.flink.table.functions.TableSemantics;
+import org.apache.flink.table.functions.definitions.DeduplicateDefinition.Keep;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.inference.utils.CallContextUtils;
+
+import java.io.Serializable;
+
+import static 
org.apache.flink.table.functions.definitions.DeduplicateDefinition.ARG_INPUT;
+
+/** Record ordering of the built-in deduplication PTFs. */
+@Internal
+public final class DeduplicateUtils {
+
+    public static TableSemantics tableSemantics(final SpecializedContext 
context) {

Review Comment:
   Could this use 
`CallContextUtils.getTableSemanticsOrThrow(context.getCallContext(), 
ARG_INPUT)` directly?



##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/SpecializedFunction.java:
##########
@@ -113,6 +114,55 @@ ExpressionEvaluator createEvaluator(
          */
         ExpressionEvaluator createEvaluator(
                 BuiltInFunctionDefinition function, DataType outputDataType, 
DataType... args);
+
+        /**
+         * Creates a serializable comparator for values of the given data 
type, in the given order.
+         *
+         * <p>The comparator uses the same ordering as {@code ORDER BY}. A 
{@code ROW} or structured
+         * type is compared field by field, every field in the given order, 
and the compared values
+         * are {@link RowData}. Any other type is compared as a single value. 
Types that cannot be
+         * ordered are rejected during planning.
+         *
+         * <p>Initialize the comparator in {@link 
UserDefinedFunction#open(FunctionContext)} by
+         * calling {@link GeneratedComparator#open(FunctionContext)}.
+         *
+         * @param dataType type of the compared values, which are expected in 
the internal data
+         *     structure of the type, see {@link DataType#toInternal()}
+         * @param order direction of the comparison and position of NULL
+         */
+        GeneratedComparator createComparator(DataType dataType, 
ComparatorOrder order);
+    }
+
+    /** Order of a {@link GeneratedComparator}: its direction and where NULL 
sorts. */
+    @PublicEvolving
+    enum ComparatorOrder {

Review Comment:
   `TableSemantics.SortDirection` is already a public enum with exactly these 
four values. Could we reuse it instead of adding `ComparatorOrder`?



##########
flink-table/flink-table-common/src/test/java/org/apache/flink/table/functions/definitions/DeduplicateDefinitionTest.java:
##########
@@ -0,0 +1,200 @@
+/*
+ * 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.functions.definitions;
+
+import org.apache.flink.table.api.DataTypes;
+import org.apache.flink.table.connector.ChangelogMode;
+import org.apache.flink.table.functions.ChangelogFunction.ChangelogContext;
+import org.apache.flink.table.functions.TableSemantics;
+import org.apache.flink.table.types.AtomicDataType;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.inference.InputTypeStrategiesTestBase;
+import org.apache.flink.table.types.inference.utils.CallContextMock;
+import org.apache.flink.table.types.inference.utils.TableSemanticsMock;
+import org.apache.flink.table.types.logical.LocalZonedTimestampType;
+import org.apache.flink.table.types.logical.TimestampKind;
+import org.apache.flink.types.ColumnList;
+import org.apache.flink.types.RowKind;
+
+import org.junit.jupiter.api.Test;
+
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Stream;
+
+import static 
org.apache.flink.table.functions.definitions.DeduplicateDefinition.ARG_INPUT;
+import static 
org.apache.flink.table.functions.definitions.DeduplicateDefinition.ARG_KEEP;
+import static 
org.apache.flink.table.functions.definitions.DeduplicateDefinition.ARG_SEQUENCE_BY;
+import static 
org.apache.flink.table.functions.definitions.DeduplicateDefinition.ARG_STATE_TTL;
+import static 
org.apache.flink.table.functions.definitions.DeduplicateDefinition.CHANGELOG_MODE_STRATEGY;
+import static 
org.apache.flink.table.functions.definitions.DeduplicateDefinition.INPUT_TYPE_STRATEGY;
+import static 
org.apache.flink.table.functions.definitions.DeduplicateDefinition.OUTPUT_TYPE_STRATEGY;
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Tests for {@link DeduplicateDefinition}. */
+class DeduplicateDefinitionTest extends InputTypeStrategiesTestBase {
+
+    private static final DataType ROWTIME =
+            new AtomicDataType(new LocalZonedTimestampType(true, 
TimestampKind.ROWTIME, 3));
+
+    private static final DataType INPUT_TYPE =
+            DataTypes.ROW(
+                    DataTypes.FIELD("user_id", DataTypes.STRING()),
+                    DataTypes.FIELD("event", DataTypes.STRING()),
+                    DataTypes.FIELD("ts", ROWTIME),
+                    DataTypes.FIELD("lsn", DataTypes.BIGINT()),
+                    DataTypes.FIELD("tags", 
DataTypes.ARRAY(DataTypes.STRING())));
+
+    private static final DataType[] ARGUMENT_TYPES = {
+        INPUT_TYPE,
+        DataTypes.STRING(),
+        DataTypes.DESCRIPTOR(),
+        DataTypes.INTERVAL(DataTypes.SECOND())
+    };
+
+    private static final TableSemanticsMock PARTITIONED_BY_USER =
+            new TableSemanticsMock(
+                    INPUT_TYPE, new int[] {0}, new int[0], -1, 
ChangelogMode.insertOnly());
+
+    @Override
+    protected Stream<TestSpec> testData() {
+        return Stream.of(
+                withDefaults("All optional arguments omitted", 
PARTITIONED_BY_USER)
+                        .expectArgumentTypes(ARGUMENT_TYPES),
+                withDefaults("All arguments set", PARTITIONED_BY_USER)
+                        .calledWithLiteralAt(ARG_KEEP, "last")
+                        .calledWithLiteralAt(ARG_SEQUENCE_BY, 
ColumnList.of("lsn", "ts"))
+                        .calledWithLiteralAt(ARG_STATE_TTL, 
Duration.ofHours(1))
+                        .expectArgumentTypes(ARGUMENT_TYPES),
+                withDefaults("Invalid keep", PARTITIONED_BY_USER)
+                        .calledWithLiteralAt(ARG_KEEP, "FIRST")
+                        .expectErrorMessage(
+                                "DEDUPLICATE requires keep => 'first' or keep 
=> 'last', but "
+                                        + "received keep => 'FIRST'."),
+                sequenceBy("Unknown sequence_by column", "nope")
+                        .expectErrorMessage(
+                                "The sequence_by column 'nope' does not exist 
in the input of "
+                                        + "DEDUPLICATE. Available columns are: 
user_id, event, "
+                                        + "ts, lsn, tags."),
+                sequenceBy("Repeated sequence_by column", "lsn", "lsn")
+                        .expectErrorMessage(
+                                "The sequence_by column 'lsn' is listed more 
than once. List "
+                                        + "each ordering column once."),
+                sequenceBy("PARTITION BY column in sequence_by", "user_id")
+                        .expectErrorMessage(
+                                "The sequence_by column 'user_id' is a 
PARTITION BY column, "
+                                        + "which has the same value for every 
record of a key."),
+                sequenceBy("Non-orderable sequence_by column", "tags")
+                        .expectErrorMessage(
+                                "The sequence_by column 'tags' has type 
'ARRAY<STRING>', which "
+                                        + "cannot order records. Use a 
numeric, string, boolean, "
+                                        + "or date-time column."),
+                withDefaults("Negative state_ttl", PARTITIONED_BY_USER)
+                        .calledWithLiteralAt(ARG_STATE_TTL, 
Duration.ofSeconds(-1))
+                        .expectErrorMessage(
+                                "The 'state_ttl' argument must not be 
negative, but was '-1 s'. "
+                                        + "Use INTERVAL '0' SECOND to retain 
state indefinitely."));
+    }
+
+    @Test
+    void testOutputExcludesPartitionKeys() {

Review Comment:
   These three unit tests (output fields, `sequence_by` indices, changelog 
mode) are covered by the plan and semantic tests. I'd keep only the validation 
specs in this class.



-- 
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]

Reply via email to