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


##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/DeduplicateRestoreTest.java:
##########
@@ -34,6 +34,9 @@ public DeduplicateRestoreTest() {
     public List<TableTestProgram> programs() {
         return List.of(
                 DeduplicateRestoreTestPrograms.FIRST_ARRIVAL_RESTORE,
-                DeduplicateRestoreTestPrograms.SEQUENCE_BY_RESTORE);
+                DeduplicateRestoreTestPrograms.SEQUENCE_BY_RESTORE,
+                DeduplicateRestoreTestPrograms.RETRACT_INPUT_RESTORE,
+                
DeduplicateRestoreTestPrograms.RETRACT_INPUT_UPSERT_KEY_RESTORE,

Review Comment:
   The upsert key layout with `sequence_by` (key -> row, no arrival position) 
has no restore program yet. Could we add one next to this, e.g. `page_hits` 
with `sequence_by => DESCRIPTOR(hits)`: u1 has A (1) and B (5) before the 
restore, then `-D(u1, B, 99)` falls back to A and `+I(u1, C, 3)` replaces it?
   
   ```suggestion
                   
DeduplicateRestoreTestPrograms.RETRACT_INPUT_UPSERT_KEY_RESTORE,
                   
DeduplicateRestoreTestPrograms.RETRACT_INPUT_UPSERT_KEY_SEQUENCE_BY_RESTORE,
   ```



##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateRetractFunction.java:
##########
@@ -0,0 +1,416 @@
+/*
+ * 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.data.utils.ProjectedRowData;
+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.runtime.typeutils.RowDataSerializer;
+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.table.types.logical.LogicalType;
+import org.apache.flink.types.ColumnList;
+import org.apache.flink.types.RowKind;
+
+import javax.annotation.Nullable;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+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. If an upsert key of the input contains the 
PARTITION BY columns, each
+ * upsert key has at most one live row, so {@code liveRows} maps that key to 
the row instead of
+ * counting copies of whole rows, and retractions are matched by that key.
+ */
+@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;
+
+    private final @Nullable int[] upsertKey;
+
+    private final @Nullable LogicalType[] upsertKeyTypes;
+
+    private transient ProjectedRowData keyProjection;
+
+    private transient RowDataSerializer keySerializer;
+
+    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));
+        this.upsertKey = 
DeduplicateUtils.upsertKeyContainingPartitionBy(context);
+        this.upsertKeyTypes =
+                upsertKey == null
+                        ? null
+                        : 
DataType.getFieldDataTypes(keyType(inputRowType(context), upsertKey))
+                                .stream()
+                                .map(DataType::getLogicalType)
+                                .toArray(LogicalType[]::new);
+    }
+
+    @Override
+    public void open(final FunctionContext context) throws Exception {
+        super.open(context);
+        if (sequenceComparator != null) {
+            sequenceComparator.open(context);
+        }
+        if (upsertKey != null) {
+            keyProjection = ProjectedRowData.from(upsertKey);
+            keySerializer = new RowDataSerializer(upsertKeyTypes);
+        }
+    }
+
+    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 BinaryRowData key = liveRowKey(row);
+        final RowData liveRowEntry = liveRows.get(key);
+        final long count =
+                liveRowEntry == null || upsertKey != null ? 1L : 
liveRowEntry.getLong(COUNT) + 1;
+        final BinaryRowData stateRow = copyForState(row);
+        putLiveRow(liveRows, key, stateRow, count, 0L);
+
+        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 BinaryRowData key = liveRowKey(row);
+        final RowData liveRowEntry = liveRows.get(key);
+        final boolean isNewLiveRow = liveRowEntry == null || upsertKey != null;
+        final long count = isNewLiveRow ? 1L : liveRowEntry.getLong(COUNT) + 1;
+        final long rowArrivalPosition =
+                isNewLiveRow || keepMode == Keep.LAST
+                        ? arrivalPosition
+                        : liveRowEntry.getLong(ARRIVAL_POSITION);
+        final BinaryRowData stateRow = copyForState(row);
+        putLiveRow(liveRows, key, stateRow, 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 BinaryRowData key = liveRowKey(row);
+        final RowData liveRowEntry = liveRows.get(key);
+        final RowData currentRow =
+                currentEntry == null ? null : currentEntry.getRow(ROW, 
inputArity);
+        final boolean isCurrent =

Review Comment:
   Every method now handles both layouts (`upsertKey == null`, 
`hasSequenceBy`), which ends in nested ternaries like `isCurrent` here or 
`count` at :247 that are hard to follow. Could we move the `liveRows` state 
behind a state view with one implementation per layout (whole row -> count, 
upsert key -> row), like `JoinRecordStateViews` does for the join state? The 
function then only calls `add`, `retract` and reads the rows, e.g.:
   
   ```java
   final RowData currentRow = currentEntry == null ? null : 
currentEntry.getRow(ROW, inputArity);
   if (liveRowsStateView.retract(liveRows, row, currentRow)) {
       selectCurrent(liveRows, current, currentEntry);
   } else if (isTtlEnabled && currentEntry != null) {
       current.setValue(currentEntry);
   }
   ```
   
   I've shared a version with you that passes all DEDUPLICATE tests and also 
removes the reads from my other comment.



##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateRetractFunction.java:
##########
@@ -0,0 +1,416 @@
+/*
+ * 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.data.utils.ProjectedRowData;
+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.runtime.typeutils.RowDataSerializer;
+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.table.types.logical.LogicalType;
+import org.apache.flink.types.ColumnList;
+import org.apache.flink.types.RowKind;
+
+import javax.annotation.Nullable;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+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. If an upsert key of the input contains the 
PARTITION BY columns, each
+ * upsert key has at most one live row, so {@code liveRows} maps that key to 
the row instead of
+ * counting copies of whole rows, and retractions are matched by that key.
+ */
+@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;
+
+    private final @Nullable int[] upsertKey;
+
+    private final @Nullable LogicalType[] upsertKeyTypes;
+
+    private transient ProjectedRowData keyProjection;
+
+    private transient RowDataSerializer keySerializer;
+
+    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));
+        this.upsertKey = 
DeduplicateUtils.upsertKeyContainingPartitionBy(context);
+        this.upsertKeyTypes =
+                upsertKey == null
+                        ? null
+                        : 
DataType.getFieldDataTypes(keyType(inputRowType(context), upsertKey))
+                                .stream()
+                                .map(DataType::getLogicalType)
+                                .toArray(LogicalType[]::new);
+    }
+
+    @Override
+    public void open(final FunctionContext context) throws Exception {
+        super.open(context);
+        if (sequenceComparator != null) {
+            sequenceComparator.open(context);
+        }
+        if (upsertKey != null) {
+            keyProjection = ProjectedRowData.from(upsertKey);
+            keySerializer = new RowDataSerializer(upsertKeyTypes);
+        }
+    }
+
+    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 BinaryRowData key = liveRowKey(row);
+        final RowData liveRowEntry = liveRows.get(key);
+        final long count =
+                liveRowEntry == null || upsertKey != null ? 1L : 
liveRowEntry.getLong(COUNT) + 1;
+        final BinaryRowData stateRow = copyForState(row);
+        putLiveRow(liveRows, key, stateRow, count, 0L);
+
+        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 BinaryRowData key = liveRowKey(row);
+        final RowData liveRowEntry = liveRows.get(key);

Review Comment:
   With an upsert key, this read's result is never used (same in 
`addBySequence`), and `retract()` reads the live row only to compare it with 
the current row. So every record pays a state lookup for nothing. In 
`retract()`, comparing keys is enough: remove the key, and the current row is 
retracted if it has the same key.



##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateRetractFunction.java:
##########
@@ -0,0 +1,416 @@
+/*
+ * 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.data.utils.ProjectedRowData;
+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.runtime.typeutils.RowDataSerializer;
+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.table.types.logical.LogicalType;
+import org.apache.flink.types.ColumnList;
+import org.apache.flink.types.RowKind;
+
+import javax.annotation.Nullable;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+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. If an upsert key of the input contains the 
PARTITION BY columns, each
+ * upsert key has at most one live row, so {@code liveRows} maps that key to 
the row instead of
+ * counting copies of whole rows, and retractions are matched by that key.
+ */
+@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;
+
+    private final @Nullable int[] upsertKey;
+
+    private final @Nullable LogicalType[] upsertKeyTypes;
+
+    private transient ProjectedRowData keyProjection;
+
+    private transient RowDataSerializer keySerializer;
+
+    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));
+        this.upsertKey = 
DeduplicateUtils.upsertKeyContainingPartitionBy(context);
+        this.upsertKeyTypes =
+                upsertKey == null
+                        ? null
+                        : 
DataType.getFieldDataTypes(keyType(inputRowType(context), upsertKey))
+                                .stream()
+                                .map(DataType::getLogicalType)
+                                .toArray(LogicalType[]::new);
+    }
+
+    @Override
+    public void open(final FunctionContext context) throws Exception {
+        super.open(context);
+        if (sequenceComparator != null) {
+            sequenceComparator.open(context);
+        }
+        if (upsertKey != null) {
+            keyProjection = ProjectedRowData.from(upsertKey);
+            keySerializer = new RowDataSerializer(upsertKeyTypes);
+        }
+    }
+
+    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 BinaryRowData key = liveRowKey(row);
+        final RowData liveRowEntry = liveRows.get(key);
+        final long count =
+                liveRowEntry == null || upsertKey != null ? 1L : 
liveRowEntry.getLong(COUNT) + 1;
+        final BinaryRowData stateRow = copyForState(row);
+        putLiveRow(liveRows, key, stateRow, count, 0L);
+
+        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 BinaryRowData key = liveRowKey(row);
+        final RowData liveRowEntry = liveRows.get(key);
+        final boolean isNewLiveRow = liveRowEntry == null || upsertKey != null;
+        final long count = isNewLiveRow ? 1L : liveRowEntry.getLong(COUNT) + 1;
+        final long rowArrivalPosition =
+                isNewLiveRow || keepMode == Keep.LAST
+                        ? arrivalPosition
+                        : liveRowEntry.getLong(ARRIVAL_POSITION);
+        final BinaryRowData stateRow = copyForState(row);
+        putLiveRow(liveRows, key, stateRow, 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 BinaryRowData key = liveRowKey(row);
+        final RowData liveRowEntry = liveRows.get(key);
+        final RowData currentRow =
+                currentEntry == null ? null : currentEntry.getRow(ROW, 
inputArity);
+        final boolean isCurrent =
+                currentRow != null
+                        && (upsertKey == null
+                                ? row.equals(currentRow)
+                                : liveRowEntry != null
+                                        ? liveRowEntry.getRow(ROW, 
inputArity).equals(currentRow)
+                                        // The live row expired: copy the key 
before the buffer is
+                                        // reused for the key of the current 
row.
+                                        : key.copy()
+                                                .equals(
+                                                        
keySerializer.toBinaryRow(
+                                                                
keyProjection.replaceRow(
+                                                                        
currentRow))));
+        final long count =
+                liveRowEntry == null ? 0L : upsertKey != null ? 1L : 
liveRowEntry.getLong(COUNT);
+        if (count > 1) {
+            putLiveRow(
+                    liveRows,
+                    key,
+                    copyForState(row),
+                    count - 1,
+                    hasSequenceBy ? 0L : 
liveRowEntry.getLong(ARRIVAL_POSITION));
+        } else if (count == 1) {
+            liveRows.remove(key);
+        }
+        // The live row of the current row can expire before the current row 
itself.
+        if (isCurrent && count <= 1) {
+            selectCurrent(liveRows, current, currentEntry);
+        } else if (isTtlEnabled && currentEntry != null) {
+            current.setValue(currentEntry);
+        }
+    }
+
+    /**
+     * Makes the best live row the current row, in place of the retracted one. 
With {@code
+     * sequence_by}, any of the tied best rows is taken.
+     */
+    private void selectCurrent(
+            final MapView<RowData, RowData> liveRows,
+            final ValueView<RowData> current,
+            final RowData currentEntry)
+            throws Exception {
+        RowData next = null;
+        long nextArrivalPosition = 0L;
+        for (final Map.Entry<RowData, RowData> candidate : liveRows.entries()) 
{
+            final RowData candidateRow =
+                    upsertKey == null
+                            ? candidate.getKey()
+                            : candidate.getValue().getRow(ROW, inputArity);
+            final long candidateArrivalPosition =
+                    hasSequenceBy ? 0L : 
candidate.getValue().getLong(ARRIVAL_POSITION);
+            if (next == null
+                    || wins(candidateRow, candidateArrivalPosition, next, 
nextArrivalPosition)) {
+                next = candidateRow;
+                nextArrivalPosition = candidateArrivalPosition;
+            }
+        }
+        final RowData previous = currentEntry.getRow(ROW, inputArity);
+        if (next == null) {
+            current.clear();
+            emitStateRow(RowKind.DELETE, previous);
+            return;
+        }
+        final BinaryRowData nextRow = copyForState(toBinaryRow(next));
+        current.setValue(
+                hasSequenceBy
+                        ? GenericRowData.of(nextRow)
+                        : GenericRowData.of(
+                                nextRow,
+                                nextArrivalPosition,
+                                currentEntry.getLong(LAST_ARRIVAL_POSITION)));
+        if (isUpdateBeforeEmitted) {
+            emitStateRow(RowKind.UPDATE_BEFORE, previous);
+        }
+        emitStateRow(RowKind.UPDATE_AFTER, nextRow);
+    }
+
+    /**
+     * Returns the map key of a row in {@code liveRows}: the row itself, or 
its upsert key. An
+     * upsert key is valid until the next call.
+     */
+    private BinaryRowData liveRowKey(final BinaryRowData row) {
+        if (upsertKey == null) {
+            return row;
+        }
+        return keySerializer.toBinaryRow(keyProjection.replaceRow(row));
+    }
+
+    /** Puts a live row, leaving out what the state layout does not hold. */
+    private void putLiveRow(
+            final MapView<RowData, RowData> liveRows,
+            final BinaryRowData key,
+            final BinaryRowData stateRow,
+            final long count,
+            final long arrivalPosition)
+            throws Exception {
+        if (upsertKey == null) {
+            liveRows.put(
+                    stateRow,
+                    hasSequenceBy
+                            ? GenericRowData.of(count)
+                            : GenericRowData.of(count, arrivalPosition));
+        } else {
+            liveRows.put(
+                    copyForState(key),
+                    hasSequenceBy
+                            ? GenericRowData.of(stateRow)
+                            : GenericRowData.of(stateRow, arrivalPosition));
+        }
+    }
+
+    /**
+     * Returns whether row {@code a} is kept over row {@code b}, by their 
{@code sequence_by} values
+     * or else by their arrival positions.
+     */
+    private boolean wins(
+            final RowData a,
+            final long arrivalPositionA,
+            final RowData b,
+            final long arrivalPositionB) {
+        final int order =
+                hasSequenceBy
+                        ? sequenceComparator.compare(a, b)
+                        : Long.compare(arrivalPositionA, arrivalPositionB);
+        return keepMode == Keep.LAST ? order > 0 : order < 0;
+    }
+
+    private static DataType keyType(final DataType rowType, final int[] 
upsertKey) {
+        final List<DataTypes.Field> fields = DataType.getFields(rowType);
+        return DataTypes.ROW(
+                
Arrays.stream(upsertKey).mapToObj(fields::get).toArray(DataTypes.Field[]::new));
+    }
+
+    private static LinkedHashMap<String, StateTypeStrategy> retractState(

Review Comment:
   I really like This one was very easy to read! gj



##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateRetractFunction.java:
##########
@@ -0,0 +1,416 @@
+/*
+ * 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.data.utils.ProjectedRowData;
+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.runtime.typeutils.RowDataSerializer;
+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.table.types.logical.LogicalType;
+import org.apache.flink.types.ColumnList;
+import org.apache.flink.types.RowKind;
+
+import javax.annotation.Nullable;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+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. If an upsert key of the input contains the 
PARTITION BY columns, each
+ * upsert key has at most one live row, so {@code liveRows} maps that key to 
the row instead of
+ * counting copies of whole rows, and retractions are matched by that key.
+ */
+@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;
+
+    private final @Nullable int[] upsertKey;
+
+    private final @Nullable LogicalType[] upsertKeyTypes;
+
+    private transient ProjectedRowData keyProjection;
+
+    private transient RowDataSerializer keySerializer;
+
+    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));
+        this.upsertKey = 
DeduplicateUtils.upsertKeyContainingPartitionBy(context);
+        this.upsertKeyTypes =
+                upsertKey == null
+                        ? null
+                        : 
DataType.getFieldDataTypes(keyType(inputRowType(context), upsertKey))
+                                .stream()
+                                .map(DataType::getLogicalType)
+                                .toArray(LogicalType[]::new);
+    }
+
+    @Override
+    public void open(final FunctionContext context) throws Exception {
+        super.open(context);
+        if (sequenceComparator != null) {
+            sequenceComparator.open(context);
+        }
+        if (upsertKey != null) {
+            keyProjection = ProjectedRowData.from(upsertKey);
+            keySerializer = new RowDataSerializer(upsertKeyTypes);
+        }
+    }
+
+    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 BinaryRowData key = liveRowKey(row);
+        final RowData liveRowEntry = liveRows.get(key);
+        final long count =
+                liveRowEntry == null || upsertKey != null ? 1L : 
liveRowEntry.getLong(COUNT) + 1;
+        final BinaryRowData stateRow = copyForState(row);
+        putLiveRow(liveRows, key, stateRow, count, 0L);
+
+        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)

Review Comment:
   Could we check `replaces(...)` first and compare the rows only then, as 
`DeduplicateAppendReplaceFunction` does? Same for `isCurrent` in `addByArrival` 
(only needed when the new row wins) and in `retract()` (only needed when the 
last copy is retracted). Then most records skip the full-row compare.



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