gustavodemorais commented on code in PR #30182:
URL: https://github.com/apache/flink/pull/30182#discussion_r4739034497
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/Deduplicate.java:
##########
@@ -46,6 +60,14 @@ public Deduplicate() {
@Override
public UserDefinedFunction specialize(final SpecializedContext context) {
Review Comment:
Could we read all the inputs of the decision at the top and keep one flat
decision, like the table in the Javadoc? For example:
```java
if (isInsertOnly) {
return isKeepFirst && !hasSequenceBy
? new DeduplicateEmitOnceFunction(context)
: new DeduplicateCurrentRowFunction(context);
}
if (hasOneRowPerKey) {
return needsStoredRow
? new DeduplicateKeyedRowFunction(context)
: new DeduplicatePassThroughFunction(context);
}
return new DeduplicateLiveRowsFunction(context);
```
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/definitions/DeduplicateDefinition.java:
##########
@@ -155,6 +157,16 @@ private static ChangelogMode inferChangelogMode(final
ChangelogContext changelog
if (requiredMode != null &&
requiredMode.contains(RowKind.UPDATE_BEFORE)) {
builder.addContainedKind(RowKind.UPDATE_BEFORE);
}
+ if (inputMode != null
+ && (inputMode.contains(RowKind.DELETE)
Review Comment:
The planner fixes the PTF's change kinds in its first pass, before it
decides whether updates carry -U, so this check never sees UPDATE_BEFORE there.
A DELETE returned in a later pass is ignored. Example (keep last):
```
CREATE VIEW page_counts AS SELECT user_id, page, COUNT(*) AS cnt FROM clicks
GROUP BY user_id, page;
SELECT * FROM DEDUPLICATE(input => TABLE page_counts PARTITION BY user_id,
keep => 'last');
```
Two clicks on (u1, A) give +I, -U, +U. DeduplicateLiveRowsFunction turns the
-U into a -D, which the output doesn't declare, and the job fails with "Invalid
row kind received: DELETE".
We have to understand this better to decide how we want to fix this
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateLiveRowsFunction.java:
##########
@@ -0,0 +1,257 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.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 rows} state counts each live row and
stamps it with its
+ * arrival, the {@code current} state holds the kept row, and the {@code
arrival} state numbers the
+ * rows of a key. When the kept row is retracted, the next one is found among
the live rows.
+ */
+@Internal
+public class DeduplicateLiveRowsFunction extends DeduplicateRowFunctionBase {
+
+ private static final long serialVersionUID = 1L;
+
+ private static final String ROWS_STATE = "rows";
+
+ private static final String CURRENT_STATE = "current";
+
+ private static final String ARRIVAL_STATE = "arrival";
+
+ private static final int COUNT = 0;
+
+ private static final int ARRIVAL = 1;
+
+ private final Keep keepMode;
+
+ private final @Nullable SequenceComparator sequenceComparator;
+
+ DeduplicateLiveRowsFunction(final SpecializedContext context) {
+ super(context, liveRowsState(context));
+ this.keepMode = DeduplicateDefinition.keep(context.getCallContext());
+ this.sequenceComparator = DeduplicateUtils.sequenceComparator(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> rows,
+ final ValueView<RowData> currentState,
+ final ValueView<Long> arrivalState,
+ final RowData input,
+ @Nullable final StringData keep,
+ @Nullable final ColumnList sequenceBy,
+ @Nullable final Long stateTtl)
+ throws Exception {
+ final BinaryRowData row = toStateRow(input);
+ final RowData current = currentState.getValue();
+ final RowKind kind = input.getRowKind();
+ if (kind == RowKind.INSERT || kind == RowKind.UPDATE_AFTER) {
+ add(rows, currentState, arrivalState, row, current);
+ } else {
+ retract(rows, currentState, arrivalState, row, current);
+ }
+ }
+
+ private void add(
+ final MapView<RowData, RowData> rows,
+ final ValueView<RowData> currentState,
+ final ValueView<Long> arrivalState,
+ final BinaryRowData row,
+ @Nullable final RowData current)
+ throws Exception {
+ final long arrival = nextArrival(rows, arrivalState);
+ arrivalState.setValue(arrival);
+
+ final RowData entry = rows.get(row);
+ final long count = entry == null ? 1L : entry.getLong(COUNT) + 1;
+ final long rowArrival =
+ entry == null || keepMode == Keep.LAST ? arrival :
entry.getLong(ARRIVAL);
+ rows.put(row, GenericRowData.of(count, rowArrival));
+
+ final RowData currentEntry = current == null ? null :
rows.get(current);
+ if (currentEntry == null) {
+ // No kept row, or its entry expired: choose among the remembered
rows.
+ selectCurrent(rows, currentState, arrivalState, current);
+ return;
+ }
+ if (!row.equals(current) && wins(row, rowArrival, current,
currentEntry.getLong(ARRIVAL))) {
+ currentState.setValue(row);
+ if (isUpdateBeforeEmitted) {
+ emit(RowKind.UPDATE_BEFORE, current);
+ }
+ emit(RowKind.UPDATE_AFTER, row);
+ } else if (isTtlEnabled) {
+ currentState.setValue(current);
+ }
+ }
+
+ private void retract(
+ final MapView<RowData, RowData> rows,
+ final ValueView<RowData> currentState,
+ final ValueView<Long> arrivalState,
+ final BinaryRowData row,
+ @Nullable final RowData current)
+ throws Exception {
+ final boolean isCurrent = current != null && row.equals(current);
+ final RowData entry = rows.get(row);
+ if (entry == null) {
+ // The entry of the kept row can expire before the kept row itself.
+ if (isCurrent) {
+ selectCurrent(rows, currentState, arrivalState, current);
+ }
+ return;
+ }
+ final long count = entry.getLong(COUNT);
+ if (count > 1) {
+ rows.put(row, GenericRowData.of(count - 1,
entry.getLong(ARRIVAL)));
+ if (isTtlEnabled && current != null) {
+ currentState.setValue(current);
+ }
+ return;
+ }
+ rows.remove(row);
Review Comment:
With TTL, this path and the one for an unknown row don't refresh `current`,
so the kept row can expire while its key still gets records: TTL 1 hour, keep
first, `+I x@10:00`, `+I y@10:30`, `-D y@11:20`, `+I z@11:40` emits `+I z`
without retracting x. Could we refresh `current` on every record of the key
when TTL is enabled? i think that's what we do in other operators right
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateRowFunctionBase.java:
##########
@@ -0,0 +1,106 @@
+/*
+ * 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.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.binary.BinaryRowData;
+import org.apache.flink.table.data.utils.JoinedRowData;
+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.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.RowKind;
+
+import java.util.LinkedHashMap;
+
+import static
org.apache.flink.table.functions.definitions.DeduplicateDefinition.ARG_INPUT;
+
+/** Base class of the {@link Deduplicate} implementations that can retract a
row they emitted. */
+@Internal
+abstract class DeduplicateRowFunctionBase extends DeduplicateFunctionBase {
Review Comment:
Can we simplify the two base classes to one? `DeduplicateFunctionBase` now
has a single direct subclass (`DeduplicateEmitOnceFunction`), which could emit
through `emit()` as well. Merging both into `DeduplicateFunctionBase` keeps the
shared parts in one place and reduces the hoping around
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateCurrentRowFunction.java:
##########
@@ -54,56 +41,20 @@
* {@code kept} state.
*/
@Internal
-public class DeduplicateCurrentRowFunction extends DeduplicateFunctionBase {
+public class DeduplicateCurrentRowFunction extends DeduplicateRowFunctionBase {
private static final long serialVersionUID = 1L;
private static final String CURRENT_STATE = "kept";
private final Keep keepMode;
- private final LogicalType[] inputTypes;
-
- private final boolean isUpdateBeforeEmitted;
-
private final @Nullable SequenceComparator sequenceComparator;
- private transient RowDataSerializer inputSerializer;
-
- private transient ProjectedRowData projectedCandidate;
-
- private transient ProjectedRowData projectedCurrent;
-
- private transient JoinedRowData retraction;
-
- private transient RowData emptyRow;
-
DeduplicateCurrentRowFunction(final SpecializedContext context) {
- super(
- context,
- valueState(
- context,
- CURRENT_STATE,
- DataTypes.ROW(
- DataType.getFields(
-
CallContextUtils.getTableSemanticsOrThrow(
-
context.getCallContext(), ARG_INPUT)
- .dataType())),
- ARG_STATE_TTL));
+ super(context, valueState(context, CURRENT_STATE,
inputRowType(context), ARG_STATE_TTL));
Review Comment:
The new functions call their state `current`, this one is `kept`, and the
docs say "kept row". Since state names end up in savepoints, let's pick one
name before the release.
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/runtime/harness/DeduplicateHarnessTest.java:
##########
@@ -67,6 +72,81 @@ void testDuplicateResetsTtl(final String keep) throws
Exception {
}
}
+ @Test
+ void testLiveRowsForgetKeptRowWithItsEntry() throws Exception {
+ try (KeyedMultiInputStreamOperatorTestHarness<RowData, ?> harness =
+ createHarness(
+ "SELECT * FROM DEDUPLICATE("
+ + "input => TABLE visits PARTITION BY user_id,
"
+ + "keep => 'first', "
+ + "state_ttl => INTERVAL '1' HOUR)")) {
+ final List<String> output = new ArrayList<>();
+ output.addAll(process(harness, "10:00", VISIT,
visit(RowKind.INSERT, "a1")));
+ output.addAll(process(harness, "10:40", VISIT,
visit(RowKind.INSERT, "a2")));
+ // a1 expired at 11:00: the kept row is chosen among the
remembered rows
+ output.addAll(process(harness, "11:10", VISIT,
visit(RowKind.INSERT, "a3")));
+ // a2 expired at 11:40, but a delete of the kept row still
retracts it
+ output.addAll(process(harness, "11:50", VISIT,
visit(RowKind.DELETE, "a2")));
+
+ assertThat(output)
+ .containsExactly(
+ "+I[u1, a1]@10:00",
+ "-U[u1, a1]@11:10",
+ "+U[u1, a2]@11:10",
+ "-U[u1, a2]@11:50",
+ "+U[u1, a3]@11:50");
+ }
+ }
+
+ @Test
+ void testLiveRowsContinueArrivalAfterCounterExpires() throws Exception {
Review Comment:
This test and `testLiveRowsRetractionKeepsKeptRowAlive` check how the three
states expire relative to each other, which is quite internal. Is
`testLiveRowsForgetKeptRowWithItsEntry` enough, maybe extended with the case
from the TTL comment?
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateKeyedRowFunction.java:
##########
@@ -0,0 +1,77 @@
+/*
+ * 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.dataview.ValueView;
+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.SpecializedFunction.SpecializedContext;
+import org.apache.flink.types.ColumnList;
+import org.apache.flink.types.RowKind;
+
+import javax.annotation.Nullable;
+
+import static
org.apache.flink.table.functions.definitions.DeduplicateDefinition.ARG_STATE_TTL;
+
+/**
+ * {@link Deduplicate} on updating input whose PARTITION BY columns are an
upsert key, when the
+ * output needs a -U or a full -D that the input does not carry. A key has at
most one live row,
+ * which is held in the {@code current} state to produce them. The input
carries no -U.
+ */
+@Internal
+public class DeduplicateKeyedRowFunction extends DeduplicateRowFunctionBase {
+
+ private static final long serialVersionUID = 1L;
+
+ private static final String CURRENT_STATE = "current";
+
+ DeduplicateKeyedRowFunction(final SpecializedContext context) {
+ super(context, valueState(context, CURRENT_STATE,
inputRowType(context), ARG_STATE_TTL));
+ }
+
+ public void eval(
+ final Context ctx,
+ final ValueView<RowData> currentState,
+ final RowData input,
+ @Nullable final StringData keep,
+ @Nullable final ColumnList sequenceBy,
+ @Nullable final Long stateTtl)
+ throws Exception {
+ final RowData current = currentState.getValue();
+ if (input.getRowKind() == RowKind.DELETE) {
+ if (current != null) {
+ currentState.clear();
+ emit(RowKind.DELETE, current);
+ }
+ return;
+ }
+ final BinaryRowData row = toStateRow(input);
+ currentState.setValue(row);
Review Comment:
This writes state before the equality check, so an identical upsert writes
state even without TTL. Could we write only when the row changes, or when TTL
is enabled, like `DeduplicateCurrentRowFunction`?
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateCurrentRowFunction.java:
##########
@@ -128,21 +74,21 @@ public void eval(
@Nullable final Long stateTtl)
throws Exception {
- final BinaryRowData current = (BinaryRowData) currentState.getValue();
+ final RowData current = currentState.getValue();
if (current == null) {
- final BinaryRowData candidate = inputSerializer.toBinaryRow(input);
- currentState.setValue(candidate.copy());
- emitCandidate(RowKind.INSERT, candidate);
+ final BinaryRowData candidate = toStateRow(input);
+ currentState.setValue(candidate);
+ emit(RowKind.INSERT, candidate);
return;
}
if (replacesCurrent(input, current)) {
Review Comment:
`toStateRow()` copies before the equality check, so with `keep => 'last'`
every exact duplicate now allocates a copy that was skipped before. Could we
compare first and copy only when the row changes?
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateKeyedRowFunction.java:
##########
@@ -0,0 +1,77 @@
+/*
+ * 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.dataview.ValueView;
+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.SpecializedFunction.SpecializedContext;
+import org.apache.flink.types.ColumnList;
+import org.apache.flink.types.RowKind;
+
+import javax.annotation.Nullable;
+
+import static
org.apache.flink.table.functions.definitions.DeduplicateDefinition.ARG_STATE_TTL;
+
+/**
+ * {@link Deduplicate} on updating input whose PARTITION BY columns are an
upsert key, when the
+ * output needs a -U or a full -D that the input does not carry. A key has at
most one live row,
+ * which is held in the {@code current} state to produce them. The input
carries no -U.
+ */
+@Internal
+public class DeduplicateKeyedRowFunction extends DeduplicateRowFunctionBase {
Review Comment:
`KeyedRow` and `CurrentRow` both keep one row per key, so the names don't
tell them apart. This one does what ChangelogNormalize does (it keeps the last
row to produce -U and full -D). We need better namings for all the 5 variants
so its intuitive to read when going through them
--
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]