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


##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateRetractFunction.java:
##########
@@ -0,0 +1,310 @@
+/*
+ * 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.MapView;
+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.functions.FunctionContext;
+import org.apache.flink.table.functions.SpecializedFunction.SpecializedContext;
+import org.apache.flink.table.functions.definitions.DeduplicateDefinition;
+import org.apache.flink.table.functions.definitions.DeduplicateDefinition.Keep;
+import 
org.apache.flink.table.runtime.functions.ptf.DeduplicateUtils.SequenceComparator;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.inference.StateTypeStrategy;
+import org.apache.flink.table.types.inference.utils.CallContextUtils;
+import org.apache.flink.types.ColumnList;
+import org.apache.flink.types.RowKind;
+
+import javax.annotation.Nullable;
+
+import java.time.Duration;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Optional;
+
+import static 
org.apache.flink.table.functions.definitions.DeduplicateDefinition.ARG_STATE_TTL;
+
+/**
+ * {@link Deduplicate} on updating input whose PARTITION BY columns contain no 
upsert key: a key can
+ * have several live rows. The {@code liveRows} state counts each live row and 
stamps it with its
+ * arrival position. The {@code current} state holds the current row, its 
arrival position, and the
+ * arrival position of the key's last record. When the current row is 
retracted, the next one is
+ * found among the live rows. With {@code sequence_by}, its values order the 
rows, so neither state
+ * holds arrival positions.
+ */
+@Internal
+public class DeduplicateRetractFunction extends DeduplicateFunctionBase {
+
+    private static final long serialVersionUID = 1L;
+
+    private static final String LIVE_ROWS_STATE = "liveRows";
+
+    private static final String CURRENT_STATE = "current";
+
+    private static final int COUNT = 0;
+
+    private static final int ROW = 0;
+
+    private static final int ARRIVAL_POSITION = 1;
+
+    private static final int LAST_ARRIVAL_POSITION = 2;
+
+    private final Keep keepMode;
+
+    private final @Nullable SequenceComparator sequenceComparator;
+
+    private final boolean hasSequenceBy;
+
+    private final int inputArity;
+
+    DeduplicateRetractFunction(final SpecializedContext context) {
+        super(context, retractState(context));
+        this.keepMode = DeduplicateDefinition.keep(context.getCallContext());
+        this.sequenceComparator = DeduplicateUtils.sequenceComparator(context);
+        this.hasSequenceBy = sequenceComparator != null;
+        this.inputArity = DataType.getFieldCount(inputRowType(context));
+    }
+
+    @Override
+    public void open(final FunctionContext context) throws Exception {
+        super.open(context);
+        if (sequenceComparator != null) {
+            sequenceComparator.open(context);
+        }
+    }
+
+    public void eval(
+            final Context ctx,
+            final MapView<RowData, RowData> liveRows,
+            final ValueView<RowData> current,
+            final RowData input,
+            @Nullable final StringData keep,
+            @Nullable final ColumnList sequenceBy,
+            @Nullable final Long stateTtl)
+            throws Exception {
+        final RowKind kind = input.getRowKind();
+        final BinaryRowData row = toBinaryRow(input);
+        row.setRowKind(RowKind.INSERT);
+        final RowData currentEntry = current.getValue();
+        if (kind != RowKind.INSERT && kind != RowKind.UPDATE_AFTER) {
+            retract(liveRows, current, row, currentEntry);
+        } else if (hasSequenceBy) {
+            addBySequence(liveRows, current, row, currentEntry);
+        } else {
+            addByArrival(liveRows, current, row, currentEntry);
+        }
+    }
+
+    /** The incoming row is the newest, so a tie of the sequence values is 
decided by keep. */
+    private void addBySequence(
+            final MapView<RowData, RowData> liveRows,
+            final ValueView<RowData> current,
+            final BinaryRowData row,
+            @Nullable final RowData currentEntry)
+            throws Exception {
+        final RowData liveRowEntry = liveRows.get(row);
+        final long count = liveRowEntry == null ? 1L : 
liveRowEntry.getLong(COUNT) + 1;
+        final BinaryRowData stateRow = copyForState(row);
+        liveRows.put(stateRow, GenericRowData.of(count));
+
+        if (currentEntry == null) {
+            // No live row outlives the current row, so this is the only live 
row.
+            current.setValue(GenericRowData.of(stateRow));
+            emitStateRow(RowKind.INSERT, stateRow);
+            return;
+        }
+        final RowData currentRow = currentEntry.getRow(ROW, inputArity);
+        if (!row.equals(currentRow)
+                && DeduplicateUtils.replaces(
+                        keepMode, sequenceComparator.compare(row, 
currentRow))) {
+            current.setValue(GenericRowData.of(stateRow));
+            if (isUpdateBeforeEmitted) {
+                emitStateRow(RowKind.UPDATE_BEFORE, currentRow);
+            }
+            emitStateRow(RowKind.UPDATE_AFTER, stateRow);
+        } else if (isTtlEnabled) {
+            current.setValue(currentEntry);
+        }
+    }
+
+    private void addByArrival(
+            final MapView<RowData, RowData> liveRows,
+            final ValueView<RowData> current,
+            final BinaryRowData row,
+            @Nullable final RowData currentEntry)
+            throws Exception {
+        final long arrivalPosition =
+                currentEntry == null ? 0L : 
currentEntry.getLong(LAST_ARRIVAL_POSITION) + 1;
+        final RowData liveRowEntry = liveRows.get(row);
+        final long count = liveRowEntry == null ? 1L : 
liveRowEntry.getLong(COUNT) + 1;
+        final long rowArrivalPosition =
+                liveRowEntry == null || keepMode == Keep.LAST
+                        ? arrivalPosition
+                        : liveRowEntry.getLong(ARRIVAL_POSITION);
+        final BinaryRowData stateRow = copyForState(row);
+        liveRows.put(stateRow, GenericRowData.of(count, rowArrivalPosition));
+
+        if (currentEntry == null) {
+            // No live row outlives the current row, so this is the only live 
row.
+            current.setValue(GenericRowData.of(stateRow, rowArrivalPosition, 
arrivalPosition));
+            emitStateRow(RowKind.INSERT, stateRow);
+            return;
+        }
+        final RowData currentRow = currentEntry.getRow(ROW, inputArity);
+        final long currentArrivalPosition = 
currentEntry.getLong(ARRIVAL_POSITION);
+        final boolean isCurrent = row.equals(currentRow);
+        if (!isCurrent && wins(row, rowArrivalPosition, currentRow, 
currentArrivalPosition)) {
+            current.setValue(GenericRowData.of(stateRow, rowArrivalPosition, 
arrivalPosition));
+            if (isUpdateBeforeEmitted) {
+                emitStateRow(RowKind.UPDATE_BEFORE, currentRow);
+            }
+            emitStateRow(RowKind.UPDATE_AFTER, stateRow);
+        } else {
+            current.setValue(
+                    GenericRowData.of(
+                            currentRow,
+                            isCurrent ? rowArrivalPosition : 
currentArrivalPosition,
+                            arrivalPosition));
+        }
+    }
+
+    private void retract(
+            final MapView<RowData, RowData> liveRows,
+            final ValueView<RowData> current,
+            final BinaryRowData row,
+            @Nullable final RowData currentEntry)
+            throws Exception {
+        final boolean isCurrent =
+                currentEntry != null && row.equals(currentEntry.getRow(ROW, 
inputArity));
+        final RowData liveRowEntry = liveRows.get(row);

Review Comment:
   One limitation to track: retractions are matched by the full input row, and 
the table argument keeps every column, also the ones the query never reads. If 
a column differs between a row and its retraction (`PROCTIME()`, `NOW()`, or 
CDC metadata like a Kafka `offset`), the -U/-D misses and the deleted row 
stays. I've opened 
[FLINK-41811](https://issues.apache.org/jira/browse/FLINK-41811) to track this 
and you don't have to worry about it for now.



##########
docs/content.zh/docs/sql/reference/queries/deduplication.md:
##########
@@ -92,10 +92,10 @@ SELECT * FROM DEDUPLICATE(
 
 | Parameter | Required | Description |
 |:----------|:---------|:------------|
-| `input` | Yes | The append-only input table. `PARTITION BY` is required and 
its columns are the key of the output.|
+| `input` | Yes | The input table. `PARTITION BY` is required and its columns 
are the key of the output. See [Updating input](#updating-input).|
 | `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 of a type that 
`ORDER BY` supports, and not part of `PARTITION BY`. |

Review Comment:
   Users coming from `ROW_NUMBER() ... ORDER BY rowtime` expect watermark 
semantics, so maybe a short note in "Order by a column" (same in the English 
copy):
   
   ```
   `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 (a 
time attribute is ordered by its value only, without waiting for the watermark 
or dropping late rows):
   ```



##########
docs/content.zh/docs/sql/reference/queries/deduplication.md:
##########
@@ -92,10 +92,10 @@ SELECT * FROM DEDUPLICATE(
 
 | Parameter | Required | Description |
 |:----------|:---------|:------------|
-| `input` | Yes | The append-only input table. `PARTITION BY` is required and 
its columns are the key of the output.|
+| `input` | Yes | The input table. `PARTITION BY` is required and its columns 
are the key of the output. See [Updating input](#updating-input).|
 | `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 of a type that 
`ORDER BY` supports, 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. |
+| `state_ttl` | No | How long the state of an idle key is retained, as an 
`INTERVAL` literal. Defaults to `table.exec.state.ttl`, and `INTERVAL '0' 
SECOND` disables expiry. A key that expired is emitted again with its next 
record. |
 | `on_time` | No | A time attribute to forward as a `rowtime` column. Only 
with `keep => 'first'` and no `sequence_by`. See [Keep time 
attributes](#keep-time-attributes). |

Review Comment:
   On updating input the result is updating, so `on_time` is rejected there. 
Could we scope this row, and the sentence in "Keep time attributes", to 
append-only input (same in the English copy)?
   
   ```suggestion
   | `on_time` | No | A time attribute to forward as a `rowtime` column. Only 
on append-only input with `keep => 'first'` and no `sequence_by`. See [Keep 
time attributes](#keep-time-attributes). |
   ```



##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateRetractFunction.java:
##########
@@ -0,0 +1,310 @@
+/*
+ * 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.MapView;
+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.functions.FunctionContext;
+import org.apache.flink.table.functions.SpecializedFunction.SpecializedContext;
+import org.apache.flink.table.functions.definitions.DeduplicateDefinition;
+import org.apache.flink.table.functions.definitions.DeduplicateDefinition.Keep;
+import 
org.apache.flink.table.runtime.functions.ptf.DeduplicateUtils.SequenceComparator;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.inference.StateTypeStrategy;
+import org.apache.flink.table.types.inference.utils.CallContextUtils;
+import org.apache.flink.types.ColumnList;
+import org.apache.flink.types.RowKind;
+
+import javax.annotation.Nullable;
+
+import java.time.Duration;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Optional;
+
+import static 
org.apache.flink.table.functions.definitions.DeduplicateDefinition.ARG_STATE_TTL;
+
+/**
+ * {@link Deduplicate} on updating input whose PARTITION BY columns contain no 
upsert key: a key can
+ * have several live rows. The {@code liveRows} state counts each live row and 
stamps it with its
+ * arrival position. The {@code current} state holds the current row, its 
arrival position, and the
+ * arrival position of the key's last record. When the current row is 
retracted, the next one is
+ * found among the live rows. With {@code sequence_by}, its values order the 
rows, so neither state
+ * holds arrival positions.
+ */
+@Internal
+public class DeduplicateRetractFunction extends DeduplicateFunctionBase {
+
+    private static final long serialVersionUID = 1L;
+
+    private static final String LIVE_ROWS_STATE = "liveRows";
+
+    private static final String CURRENT_STATE = "current";
+
+    private static final int COUNT = 0;
+
+    private static final int ROW = 0;
+
+    private static final int ARRIVAL_POSITION = 1;
+
+    private static final int LAST_ARRIVAL_POSITION = 2;
+
+    private final Keep keepMode;
+
+    private final @Nullable SequenceComparator sequenceComparator;
+
+    private final boolean hasSequenceBy;
+
+    private final int inputArity;
+
+    DeduplicateRetractFunction(final SpecializedContext context) {
+        super(context, retractState(context));
+        this.keepMode = DeduplicateDefinition.keep(context.getCallContext());
+        this.sequenceComparator = DeduplicateUtils.sequenceComparator(context);
+        this.hasSequenceBy = sequenceComparator != null;
+        this.inputArity = DataType.getFieldCount(inputRowType(context));
+    }
+
+    @Override
+    public void open(final FunctionContext context) throws Exception {
+        super.open(context);
+        if (sequenceComparator != null) {
+            sequenceComparator.open(context);
+        }
+    }
+
+    public void eval(
+            final Context ctx,
+            final MapView<RowData, RowData> liveRows,
+            final ValueView<RowData> current,
+            final RowData input,
+            @Nullable final StringData keep,
+            @Nullable final ColumnList sequenceBy,
+            @Nullable final Long stateTtl)
+            throws Exception {
+        final RowKind kind = input.getRowKind();
+        final BinaryRowData row = toBinaryRow(input);
+        row.setRowKind(RowKind.INSERT);
+        final RowData currentEntry = current.getValue();
+        if (kind != RowKind.INSERT && kind != RowKind.UPDATE_AFTER) {
+            retract(liveRows, current, row, currentEntry);
+        } else if (hasSequenceBy) {
+            addBySequence(liveRows, current, row, currentEntry);
+        } else {
+            addByArrival(liveRows, current, row, currentEntry);
+        }
+    }
+
+    /** The incoming row is the newest, so a tie of the sequence values is 
decided by keep. */
+    private void addBySequence(
+            final MapView<RowData, RowData> liveRows,
+            final ValueView<RowData> current,
+            final BinaryRowData row,
+            @Nullable final RowData currentEntry)
+            throws Exception {
+        final RowData liveRowEntry = liveRows.get(row);
+        final long count = liveRowEntry == null ? 1L : 
liveRowEntry.getLong(COUNT) + 1;
+        final BinaryRowData stateRow = copyForState(row);
+        liveRows.put(stateRow, GenericRowData.of(count));
+
+        if (currentEntry == null) {
+            // No live row outlives the current row, so this is the only live 
row.
+            current.setValue(GenericRowData.of(stateRow));
+            emitStateRow(RowKind.INSERT, stateRow);
+            return;
+        }
+        final RowData currentRow = currentEntry.getRow(ROW, inputArity);
+        if (!row.equals(currentRow)
+                && DeduplicateUtils.replaces(
+                        keepMode, sequenceComparator.compare(row, 
currentRow))) {
+            current.setValue(GenericRowData.of(stateRow));
+            if (isUpdateBeforeEmitted) {
+                emitStateRow(RowKind.UPDATE_BEFORE, currentRow);

Review Comment:
   No test reaches this -U yet: every `LIVE_ROWS` sink has a primary key. Could 
`latest_opened_accounts` drop its primary key? Then a2 replacing a1 also checks 
this `-U a1`.



##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/Deduplicate.java:
##########
@@ -46,18 +63,43 @@ public Deduplicate() {
     @Override
     public UserDefinedFunction specialize(final SpecializedContext context) {
         final CallContext callContext = context.getCallContext();
+        final TableSemantics tableSemantics =
+                CallContextUtils.getTableSemanticsOrThrow(callContext, 
ARG_INPUT);
+        final ChangelogMode inputMode =
+                
tableSemantics.changelogMode().orElseThrow(IllegalStateException::new);
+        final ChangelogMode outputMode =
+                
callContext.getOutputChangelogMode().orElseThrow(IllegalStateException::new);
+
+        final boolean isInsertOnly = inputMode.containsOnly(RowKind.INSERT);
         final boolean isKeepFirst = DeduplicateDefinition.keep(callContext) == 
Keep.FIRST;
+        final boolean hasSequenceBy =
+                
DeduplicateDefinition.sequenceByOutputIndices(callContext).length > 0;
+        final boolean hasOneRowPerKey = isPartitionByUpsertKey(tableSemantics);
+        final boolean needsUpdateBefore =
+                outputMode.contains(RowKind.UPDATE_BEFORE)
+                        && !inputMode.contains(RowKind.UPDATE_BEFORE);
+        final boolean needsFullDeletes = inputMode.keyOnlyDeletes() && 
!outputMode.keyOnlyDeletes();
 
-        if (isKeepFirst) {
-            final boolean hasSequenceBy =
-                    
DeduplicateDefinition.sequenceByOutputIndices(callContext).length > 0;
-            if (!hasSequenceBy) {
-                return new DeduplicateEmitOnceFunction(context);
-            } else {
-                return new DeduplicateCurrentRowFunction(context);
-            }
-        } else {
-            return new DeduplicateCurrentRowFunction(context);
+        if (isInsertOnly) {
+            return isKeepFirst && !hasSequenceBy
+                    ? new DeduplicateAppendEmitOnceFunction(context)
+                    : new DeduplicateAppendReplaceFunction(context);
         }
+        if (hasOneRowPerKey) {
+            return needsUpdateBefore || needsFullDeletes
+                    ? new DeduplicateUpsertNormalizeFunction(context)
+                    : new DeduplicateUpsertForwardFunction(context);
+        }
+        return new DeduplicateRetractFunction(context);
+    }
+
+    /** Returns whether the PARTITION BY columns contain an upsert key of the 
input. */
+    private static boolean isPartitionByUpsertKey(final TableSemantics 
tableSemantics) {

Review Comment:
   When the input's upsert key contains the `PARTITION BY` columns, 
`upsertKeyColumns()` already has it, but `DeduplicateRetractFunction` still 
uses the whole row as the state key. For example, `GROUP BY user_id, page` 
followed by `PARTITION BY user_id` has the key `(user_id, page)`, so `liveRows` 
could hold `(u1, A) -> row` instead of `row -> count`. Could we use that key 
instead? It's smaller than the row and, since a key has at most one live row, 
`liveRows` wouldn't need the count. Compiled plans already store the key, so 
it's easiest to do before the release.



##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/DeduplicateTestPrograms.java:
##########
@@ -248,6 +251,254 @@ public class DeduplicateTestPrograms {
                                     + "keep => 'last')")
                     .build();
 
+    public static final TableTestProgram UPDATING_INPUT =
+            TableTestProgram.of(
+                            "deduplicate-updating-input",
+                            "with one live row per key, every change is 
forwarded whatever "
+                                    + "keep and sequence_by say, a key-only -D 
is emitted with the "
+                                    + "full row, a -D without state emits 
nothing, +U without "
+                                    + "state is a first record, and a consumer 
without a key "
+                                    + "gets -U")
+                    .setupTableSource(
+                            SourceTestStep.newBuilder("customers_cdc")
+                                    .addSchema(
+                                            "customer_id STRING PRIMARY KEY 
NOT ENFORCED",
+                                            "city STRING",
+                                            "lsn BIGINT")
+                                    .addMode(ChangelogMode.upsert())
+                                    .producedValues(
+                                            Row.ofKind(RowKind.INSERT, "c1", 
"Berlin", 100L),
+                                            Row.ofKind(RowKind.UPDATE_AFTER, 
"c1", "Munich", 120L),
+                                            Row.ofKind(RowKind.UPDATE_AFTER, 
"c1", "Hamburg", 110L),
+                                            Row.ofKind(RowKind.DELETE, "c1", 
null, null),
+                                            Row.ofKind(RowKind.DELETE, "c1", 
null, null),
+                                            Row.ofKind(RowKind.UPDATE_AFTER, 
"c1", "Bremen", 115L))
+                                    .build())
+                    .setupTableSink(
+                            SinkTestStep.newBuilder("sink")
+                                    .addSchema(
+                                            "customer_id STRING PRIMARY KEY 
NOT ENFORCED",
+                                            "city STRING",
+                                            "lsn BIGINT")
+                                    .consumedValues(
+                                            "+I[c1, Berlin, 100]",
+                                            "+U[c1, Munich, 120]",
+                                            "+U[c1, Hamburg, 110]",
+                                            "-D[c1, Hamburg, 110]",
+                                            "+I[c1, Bremen, 115]")
+                                    .build())
+                    .setupTableSink(
+                            SinkTestStep.newBuilder("sink_first")
+                                    .addSchema("customer_id STRING", "city 
STRING", "lsn BIGINT")
+                                    .consumedValues(
+                                            "+I[c1, Berlin, 100]",
+                                            "-U[c1, Berlin, 100]",
+                                            "+U[c1, Munich, 120]",
+                                            "-U[c1, Munich, 120]",
+                                            "+U[c1, Hamburg, 110]",
+                                            "-D[c1, Hamburg, 110]",
+                                            "+I[c1, Bremen, 115]")
+                                    .build())
+                    .runSql(
+                            "INSERT INTO sink SELECT * FROM DEDUPLICATE("
+                                    + "input => TABLE customers_cdc PARTITION 
BY customer_id, "
+                                    + "keep => 'last', "
+                                    + "sequence_by => DESCRIPTOR(lsn))")
+                    .runSql(
+                            "INSERT INTO sink_first SELECT * FROM DEDUPLICATE("
+                                    + "input => TABLE customers_cdc PARTITION 
BY customer_id, "
+                                    + "keep => 'first')")
+                    .build();
+
+    public static final TableTestProgram RETRACT_INPUT =
+            TableTestProgram.of(
+                            "deduplicate-retract-input",
+                            "on retract input partitioned by its upsert key, 
the planner drops "
+                                    + "the -U before the PTF, so every change 
is forwarded as is")
+                    .setupTableSource(
+                            SourceTestStep.newBuilder("customers_cdc")
+                                    .addSchema(
+                                            "customer_id STRING PRIMARY KEY 
NOT ENFORCED",
+                                            "city STRING")
+                                    .addMode(ChangelogMode.all())
+                                    .producedValues(
+                                            Row.ofKind(RowKind.INSERT, "c1", 
"Berlin"),
+                                            Row.ofKind(RowKind.UPDATE_BEFORE, 
"c1", "Berlin"),
+                                            Row.ofKind(RowKind.UPDATE_AFTER, 
"c1", "Munich"),
+                                            Row.ofKind(RowKind.DELETE, "c1", 
"Munich"))
+                                    .build())
+                    .setupTableSink(
+                            SinkTestStep.newBuilder("sink")
+                                    .addSchema(
+                                            "customer_id STRING PRIMARY KEY 
NOT ENFORCED",
+                                            "city STRING")
+                                    .consumedValues(
+                                            "+I[c1, Berlin]", "+U[c1, 
Munich]", "-D[c1, Munich]")
+                                    .build())
+                    .runSql(
+                            "INSERT INTO sink SELECT * FROM DEDUPLICATE("
+                                    + "input => TABLE customers_cdc PARTITION 
BY customer_id, "
+                                    + "keep => 'last')")
+                    .build();
+
+    public static final TableTestProgram LIVE_ROWS =
+            TableTestProgram.of(
+                            "deduplicate-live-rows",
+                            "with several live rows per key, a retraction of 
the kept row falls "
+                                    + "back to the next live row, and of the 
last row emits -D; "
+                                    + "with 'first', a row keeps the arrival 
of its earliest copy; "
+                                    + "a -U of an aggregate input is retracted 
as -D; with "
+                                    + "sequence_by, the fallback goes to the 
best remaining row")
+                    .setupTableSource(
+                            SourceTestStep.newBuilder("accounts")
+                                    .addSchema(
+                                            "customer_id STRING",
+                                            "account_id STRING PRIMARY KEY NOT 
ENFORCED",
+                                            "balance INT")
+                                    .addMode(ChangelogMode.all())
+                                    .producedValues(
+                                            Row.ofKind(RowKind.INSERT, "c1", 
"a1", 10),
+                                            Row.ofKind(RowKind.INSERT, "c1", 
"a2", 20),
+                                            Row.ofKind(RowKind.INSERT, "c2", 
"a3", 30),
+                                            Row.ofKind(RowKind.DELETE, "c1", 
"a2", 20),
+                                            Row.ofKind(RowKind.UPDATE_BEFORE, 
"c1", "a1", 10),
+                                            Row.ofKind(RowKind.UPDATE_AFTER, 
"c1", "a1", 15),
+                                            Row.ofKind(RowKind.DELETE, "c2", 
"a3", 30))
+                                    .build())
+                    .setupTableSource(
+                            SourceTestStep.newBuilder("visits")
+                                    .addSchema("user_id STRING", "page STRING")
+                                    .addMode(ChangelogMode.all())
+                                    .producedValues(
+                                            Row.ofKind(RowKind.INSERT, "u1", 
"B"),
+                                            Row.ofKind(RowKind.INSERT, "u1", 
"A"),
+                                            Row.ofKind(RowKind.INSERT, "u1", 
"C"),
+                                            Row.ofKind(RowKind.INSERT, "u1", 
"A"),
+                                            Row.ofKind(RowKind.DELETE, "u1", 
"B"))

Review Comment:
   No test retracts one copy of a duplicated row or a row `DEDUPLICATE` has 
never seen, so dropping the `count > 1` branch or the null check in `retract()` 
passes every test. Could we add a few rows to the existing sources?
   - `visits`: a final `-D(u1, A)`. A copy of A is still live, so 
`first_visits` stays `+I[u1, B]`, `+U[u1, A]`.
   - `accounts`: a leading `-D(c3, a9, 90)`, which emits nothing.



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