gustavodemorais commented on code in PR #30182: URL: https://github.com/apache/flink/pull/30182#discussion_r4756698497
########## flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateLiveRowsFunction.java: ########## @@ -0,0 +1,255 @@ +/* + * 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 currentRow} 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 DeduplicateFunctionBase { + + private static final long serialVersionUID = 1L; + + private static final String ROWS_STATE = "rows"; + + private static final String CURRENT_ROW_STATE = "currentRow"; + + 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 (isTtlEnabled && current != null) { + currentState.setValue(current); + } + 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); Review Comment: Per +I/+U we read and write `currentRow` (TTL refresh, then again when the row is replaced), read and write `arrival`, and read and write `rows` twice (the new row and the kept row's arrival). If `currentRow` also stored the kept row's arrival and the counter, `rows.get(current)` and the `arrival` state go away, and the TTL refresh merges with the replace write. That's about 3-4 state accesses instead of 7, which matters most on RocksDB. ########## flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateLiveRowsFunction.java: ########## @@ -0,0 +1,255 @@ +/* + * 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 currentRow} 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 DeduplicateFunctionBase { + + private static final long serialVersionUID = 1L; + + private static final String ROWS_STATE = "rows"; + + private static final String CURRENT_ROW_STATE = "currentRow"; + + 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); Review Comment: This copies every record, also retractions, which only look up and remove. Only `rows.put` needs a copy, so could we use `toBinaryRow` here (with row kind INSERT, like `isSameAsStateRow`) and copy right before the put? ########## flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/Deduplicate.java: ########## @@ -46,18 +60,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 DeduplicateEmitOnceFunction(context) + : new DeduplicateCurrentRowFunction(context); } + if (hasOneRowPerKey) { + return needsUpdateBefore || needsFullDeletes + ? new DeduplicateKeyedRowFunction(context) + : new DeduplicatePassThroughFunction(context); + } + return new DeduplicateLiveRowsFunction(context); Review Comment: Reads nicely 🙂 ########## flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateLiveRowsFunction.java: ########## @@ -0,0 +1,255 @@ +/* + * 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 currentRow} 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 DeduplicateFunctionBase { + + private static final long serialVersionUID = 1L; + + private static final String ROWS_STATE = "rows"; + + private static final String CURRENT_ROW_STATE = "currentRow"; + + 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 (isTtlEnabled && current != null) { + currentState.setValue(current); + } + 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); + } + } + + 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))); + return; + } + rows.remove(row); + if (isCurrent) { + selectCurrent(rows, currentState, arrivalState, current); + } + } + + /** + * Makes the best remembered row the kept row, in place of {@code previous}, which is no longer + * among the remembered rows. + */ + private void selectCurrent( + final MapView<RowData, RowData> rows, + final ValueView<RowData> currentState, + final ValueView<Long> arrivalState, + @Nullable final RowData previous) + throws Exception { + RowData next = null; + long nextArrival = 0L; + for (final Map.Entry<RowData, RowData> candidate : rows.entries()) { + final long candidateArrival = candidate.getValue().getLong(ARRIVAL); + if (next == null || wins(candidate.getKey(), candidateArrival, next, nextArrival)) { + next = candidate.getKey(); + nextArrival = candidateArrival; + } + } + if (next == null) { + currentState.clear(); + arrivalState.clear(); + if (previous != null) { + emit(RowKind.DELETE, previous); + } + return; + } + final BinaryRowData nextRow = ((BinaryRowData) next).copy(); + currentState.setValue(nextRow); + if (previous == null) { + emit(RowKind.INSERT, nextRow); + return; + } + if (isUpdateBeforeEmitted) { + emit(RowKind.UPDATE_BEFORE, previous); + } + emit(RowKind.UPDATE_AFTER, nextRow); + } + + /** + * Returns the arrival of the next record of the key. Without a counter, for a new key or after + * the counter expired, numbering continues after the remembered rows. + */ + private static long nextArrival( Review Comment: Without a counter this iterates `rows`, which happens for the first record of every key (an iterator seek on RocksDB). Since `currentRow` is refreshed on every record, no entry of `rows` outlives it, so when `currentRow` is null we could start at 0 without looking. ########## flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateFunctionBase.java: ########## @@ -55,5 +77,65 @@ abstract class DeduplicateFunctionBase extends BuiltInProcessTableFunction<RowDa CallContextUtils.getStateTtl(callContext, ARG_STATE_TTL) .orElseGet(() -> context.getConfiguration().get(IDLE_STATE_RETENTION)); this.isTtlEnabled = !effectiveTtl.isZero(); + this.isUpdateBeforeEmitted = + callContext + .getOutputChangelogMode() + .map(mode -> mode.contains(RowKind.UPDATE_BEFORE)) + .orElse(false); + this.inputTypes = + DataType.getFieldDataTypes(inputRowType(context)).stream() + .map(DataType::getLogicalType) + .toArray(LogicalType[]::new); + } + + @Override + public void open(final FunctionContext context) throws Exception { + super.open(context); + inputSerializer = new RowDataSerializer(inputTypes); + projectedRow = ProjectedRowData.from(outputIndices); + outputRow = new JoinedRowData(); + emptyRow = GenericRowData.of(); + } + + /** Returns the type of a full input row, as kept in state. */ + static DataType inputRowType(final SpecializedContext context) { + return DataTypes.ROW( + DataType.getFields( + CallContextUtils.getTableSemanticsOrThrow( + context.getCallContext(), ARG_INPUT) + .dataType())); + } + + /** Returns a copy of the input row with row kind INSERT, so that equal rows compare equal. */ + protected BinaryRowData toStateRow(final RowData input) { + return copyAsStateRow(toBinaryRow(input)); + } + + /** Returns the input as a binary row without copying it, valid until the next call. */ + protected BinaryRowData toBinaryRow(final RowData input) { + return inputSerializer.toBinaryRow(input); + } + + protected static BinaryRowData copyAsStateRow(final BinaryRowData row) { + final BinaryRowData copy = row.copy(); Review Comment: The copy is only needed for the heap state backend, which keeps a reference to the row. RocksDB serializes the row on write, so there it's copied twice. Once PTFs can see the state backend (like `InputSortBuffer` does), we could skip it, so maybe a short note here: ```suggestion // The heap state backend keeps a reference to the row, RocksDB does not need this copy. // A potential future optimization would be to skip this if we pass down the used state backend final BinaryRowData copy = row.copy(); ``` ########## flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateFunctionBase.java: ########## @@ -55,5 +77,65 @@ abstract class DeduplicateFunctionBase extends BuiltInProcessTableFunction<RowDa CallContextUtils.getStateTtl(callContext, ARG_STATE_TTL) .orElseGet(() -> context.getConfiguration().get(IDLE_STATE_RETENTION)); this.isTtlEnabled = !effectiveTtl.isZero(); + this.isUpdateBeforeEmitted = + callContext + .getOutputChangelogMode() + .map(mode -> mode.contains(RowKind.UPDATE_BEFORE)) + .orElse(false); + this.inputTypes = + DataType.getFieldDataTypes(inputRowType(context)).stream() + .map(DataType::getLogicalType) + .toArray(LogicalType[]::new); + } + + @Override + public void open(final FunctionContext context) throws Exception { + super.open(context); + inputSerializer = new RowDataSerializer(inputTypes); + projectedRow = ProjectedRowData.from(outputIndices); + outputRow = new JoinedRowData(); + emptyRow = GenericRowData.of(); + } + + /** Returns the type of a full input row, as kept in state. */ + static DataType inputRowType(final SpecializedContext context) { + return DataTypes.ROW( + DataType.getFields( + CallContextUtils.getTableSemanticsOrThrow( + context.getCallContext(), ARG_INPUT) + .dataType())); + } + + /** Returns a copy of the input row with row kind INSERT, so that equal rows compare equal. */ + protected BinaryRowData toStateRow(final RowData input) { + return copyAsStateRow(toBinaryRow(input)); + } + + /** Returns the input as a binary row without copying it, valid until the next call. */ + protected BinaryRowData toBinaryRow(final RowData input) { + return inputSerializer.toBinaryRow(input); + } + + protected static BinaryRowData copyAsStateRow(final BinaryRowData row) { + final BinaryRowData copy = row.copy(); + copy.setRowKind(RowKind.INSERT); + return copy; + } + + /** Returns whether the row equals the state row, ignoring its row kind. */ + protected static boolean isSameAsStateRow(final BinaryRowData row, final RowData stateRow) { + final RowKind kind = row.getRowKind(); + row.setRowKind(RowKind.INSERT); + final boolean isSame = row.equals(stateRow); + row.setRowKind(kind); + return isSame; + } + + /** Emits the output columns of an input row with the given row kind, leaving the row as is. */ + protected void emit(final RowKind kind, final RowData inputRow) { Review Comment: This now wraps every output in a `JoinedRowData` with an empty row, also for `DeduplicateEmitOnceFunction` and the `+I`/`+U` of `DeduplicateCurrentRowFunction`, which emitted a plain `ProjectedRowData` before. The wrapper is only needed when we emit a row owned by state with a different row kind (-U/-D of the kept row). Could we keep it for that case only? -- 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]
