Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,14 @@ public class FlinkConnectorOptions {
+ "as a small value would cause frequent requests and increase server load. In the future, "
+ "once list partitions is optimized, the default value of this parameter can be reduced.");

public static final ConfigOption<Boolean> SCAN_FILTER_UNCHANGED_ROW_ENABLED =
ConfigOptions.key("scan.filter-unchanged-row.enabled")
.booleanType()
.defaultValue(false)
.withDescription(
"Skip complete update pairs with equal projected values when scanning a subset of "
+ "a primary-key table's columns. Skipped updates do not advance watermarks.");

public static final ConfigOption<Integer> SCAN_SPLIT_ASSIGNMENT_BATCH_SIZE =
ConfigOptions.key("scan.split.assignment.batch-size")
.intType()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,7 @@ public Set<ConfigOption<?>> optionalOptions() {
FlinkConnectorOptions.SCAN_BOUNDED_MODE,
FlinkConnectorOptions.SCAN_BOUNDED_TIMESTAMP,
FlinkConnectorOptions.SCAN_PARTITION_DISCOVERY_INTERVAL,
FlinkConnectorOptions.SCAN_FILTER_UNCHANGED_ROW_ENABLED,
FlinkConnectorOptions.SCAN_SPLIT_ASSIGNMENT_BATCH_SIZE,
FlinkConnectorOptions.SCAN_KV_SNAPSHOT_LEASE_ID,
FlinkConnectorOptions.SCAN_KV_SNAPSHOT_LEASE_DURATION,
Expand Down Expand Up @@ -296,10 +297,12 @@ private static Configuration toFlussClientConfig(
ConfigOptions.BOOTSTRAP_SERVERS.key(),
tableOptions.get(FlinkConnectorOptions.BOOTSTRAP_SERVERS.key()));

// forward all client configs
tableOptions.forEach(
(key, value) -> {
if (key.startsWith(CLIENT_PREFIX)) {
if (key.startsWith(CLIENT_PREFIX)
|| key.equals(
FlinkConnectorOptions.SCAN_FILTER_UNCHANGED_ROW_ENABLED
.key())) {
flussConfig.setString(key, value);
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@ public void emitRecord(
// update the log offset
lakeSnapshotAndFlussLogSplitState.setNextLogOffset(scanRecord.logOffset() + 1);
}
sourceOutputFunc.accept(recordAndPos.record(), sourceOutput);
if (!recordAndPos.skipEmission()) {
sourceOutputFunc.accept(recordAndPos.record(), sourceOutput);
}
} else {
throw new UnsupportedOperationException(
"Unknown split state type: " + splitState.getClass());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,7 @@ public SourceReader<OUT, SourceSplitBase> createReader(SourceReaderContext conte
elementsQueue,
readerConf,
tablePath,
hasPrimaryKey,
scanRowType,
context,
projectedFields,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,18 +88,16 @@ public void emitRecord(
// update the records number to skip
hybridSnapshotLogSplitState.setRecordsToSkip(recordAndPosition.readRecordsCount());
}
processAndEmitRecord(scanRecord, sourceOutput);
if (!recordAndPosition.skipEmission()) {
processAndEmitRecord(scanRecord, sourceOutput);
}
} else if (splitState.isLogSplitState()) {
// Attempt to process and emit the record.
// For $binlog, this returns true only when a complete row (or the final part of
// a split) is emitted.
boolean emitted = processAndEmitRecord(recordAndPosition.record(), sourceOutput);

if (emitted) {
// Only advance the offset in state if the record was successfully emitted.
// This ensures that if a crash occurs mid-update (between BEFORE and AFTER),
// the source will re-read the same log offset upon recovery,
// allowing the BinlogDeserializationSchema to correctly reconstruct the state.
boolean consumed =
recordAndPosition.skipEmission()
|| processAndEmitRecord(recordAndPosition.record(), sourceOutput);

if (consumed) {
// Buffered $binlog UPDATE_BEFORE records must be replayed after recovery.
splitState
.asLogSplitState()
.setNextOffset(recordAndPosition.record().logOffset() + 1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ public FlinkSourceReader(
FutureCompletingBlockingQueue<RecordsWithSplitIds<RecordAndPos>> elementsQueue,
Configuration flussConfig,
TablePath tablePath,
boolean hasPrimaryKey,
RowType sourceOutputType,
SourceReaderContext context,
@Nullable int[] projectedFields,
Expand All @@ -83,6 +84,7 @@ public FlinkSourceReader(
new FlinkSourceSplitReader(
flussConfig,
tablePath,
hasPrimaryKey,
sourceOutputType,
projectedFields,
logRecordBatchFilter,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@
import org.apache.fluss.metrics.Gauge;
import org.apache.fluss.metrics.MetricNames;
import org.apache.fluss.predicate.Predicate;
import org.apache.fluss.record.ChangeType;
import org.apache.fluss.row.InternalRow;
import org.apache.fluss.types.RowType;
import org.apache.fluss.utils.CloseableIterator;
import org.apache.fluss.utils.ExceptionUtils;
Expand All @@ -68,11 +70,14 @@
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
import java.util.function.BiPredicate;

import static org.apache.fluss.flink.FlinkConnectorOptions.SCAN_FILTER_UNCHANGED_ROW_ENABLED;
import static org.apache.fluss.utils.Preconditions.checkArgument;
import static org.apache.fluss.utils.Preconditions.checkNotNull;

Expand All @@ -95,6 +100,7 @@ public class FlinkSourceSplitReader implements SplitReader<RecordAndPos, SourceS
private final Map<TableBucket, String> subscribedBuckets;

@Nullable private final int[] projectedFields;
@Nullable private final BiPredicate<InternalRow, InternalRow> projectedRowEquals;

private final FlinkSourceReaderMetrics flinkSourceReaderMetrics;
private final Gauge<Long> recordsLagMetric;
Expand Down Expand Up @@ -124,6 +130,7 @@ public class FlinkSourceSplitReader implements SplitReader<RecordAndPos, SourceS
public FlinkSourceSplitReader(
Configuration flussConf,
TablePath tablePath,
boolean hasPrimaryKey,
RowType sourceOutputType,
@Nullable int[] projectedFields,
@Nullable Predicate logRecordBatchFilter,
Expand All @@ -140,6 +147,18 @@ public FlinkSourceSplitReader(
this.boundedSplits = new ArrayDeque<>();
this.subscribedBuckets = new HashMap<>();
this.projectedFields = projectedFields;
// Use the scan's primary key flag: virtual tables must retain every change event even
// when their backing table has a primary key.
this.projectedRowEquals =
hasPrimaryKey
&& org.apache.flink.configuration.Configuration.fromMap(
flussConf.toMap())
.get(SCAN_FILTER_UNCHANGED_ROW_ENABLED)
&& projectedFields != null
&& projectedFields.length
< table.getTableInfo().getRowType().getFieldCount()
? ProjectedRowEquality.create(sourceOutputType)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we also exclude $changelog scans from this optimization? ChangelogFlinkTableSource passes its dataProjection to the same split reader, and toFlussClientConfig() now forwards this option for that source as well, so projected virtual-table reads can satisfy this condition.

I reproduced this with a primary-key table (id, name, age): insert (1, 'Alice', 10), then update only age to 20, and run:

SELECT _change_type, _log_offset, id, name
FROM t$changelog
/*+ OPTIONS(
  'scan.startup.mode' = 'earliest',
  'scan.bounded.mode' = 'latest-offset',
  'scan.filter-unchanged-row.enabled' = 'true') */;

With the option disabled, the query returns the insert plus both update events. With it enabled, only the insert remains. The physical projected values are equal, but _change_type and _log_offset distinguish the two update events; they are filtered before that metadata is materialized. Since $changelog represents each event as a separate INSERT row, this drops change-history records, contrary to the documented exclusion of virtual tables.

Would it make sense to restrict filtering to ordinary primary-key table scans and add a regression test combining projected data and metadata columns?

: null;

this.flinkSourceReaderMetrics = flinkSourceReaderMetrics;
sanityCheck(table.getTableInfo().getRowType(), projectedFields);
Expand Down Expand Up @@ -512,7 +531,8 @@ private FlinkRecordsWithSplitIds forLogRecords(ScanRecords scanRecords) {
finishedSplits.add(splitId);
}
}
splitRecords.put(splitId, toRecordAndPos(bucketScanRecords.iterator()));
splitRecords.put(
splitId, toRecordAndPos(bucketScanRecords, stoppingOffset, projectedRowEquals));
}
Iterator<TableBucket> buckets = tableScanBuckets.iterator();
Iterator<String> splitIterator =
Expand Down Expand Up @@ -566,24 +586,39 @@ private void removeFinishedSplits(Set<String> finishedSplitIds) {
}
}

private CloseableIterator<RecordAndPos> toRecordAndPos(
Iterator<ScanRecord> recordAndPosIterator) {
@VisibleForTesting
static CloseableIterator<RecordAndPos> toRecordAndPos(
List<ScanRecord> records,
long stoppingOffset,
@Nullable BiPredicate<InternalRow, InternalRow> projectedRowEquals) {
ListIterator<ScanRecord> iterator = records.listIterator();
return new CloseableIterator<RecordAndPos>() {

@Override
public boolean hasNext() {
return recordAndPosIterator.hasNext();
return iterator.hasNext();
}

@Override
public RecordAndPos next() {
return new RecordAndPos(recordAndPosIterator.next());
ScanRecord record = iterator.next();
if (projectedRowEquals != null
&& record.getChangeType() == ChangeType.UPDATE_BEFORE
&& iterator.hasNext()) {
ScanRecord next = records.get(iterator.nextIndex());
if (next.getChangeType() == ChangeType.UPDATE_AFTER
&& next.logOffset() == record.logOffset() + 1
&& next.logOffset() < stoppingOffset
&& projectedRowEquals.test(record.getRow(), next.getRow())) {
// One marker makes filtering the pair and checkpointing its offset atomic.
return RecordAndPos.filteredUpdate(iterator.next());
}
}
return new RecordAndPos(record);
}

@Override
public void close() {
// do nothing
}
public void close() {}
};
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
/*
* 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.fluss.flink.source.reader;

import org.apache.fluss.row.InternalArray;
import org.apache.fluss.row.InternalMap;
import org.apache.fluss.row.InternalRow;
import org.apache.fluss.types.ArrayType;
import org.apache.fluss.types.BinaryType;
import org.apache.fluss.types.BytesType;
import org.apache.fluss.types.DataType;
import org.apache.fluss.types.DataTypeDefaultVisitor;
import org.apache.fluss.types.MapType;
import org.apache.fluss.types.RowType;
import org.apache.fluss.utils.ByteArrayWrapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiPredicate;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;

import static org.apache.fluss.utils.CollectionUtils.newHashMapWithExpectedSize;

/** Builds equality checks for projected log rows materialized by the Fluss scanner. */
final class ProjectedRowEquality extends DataTypeDefaultVisitor<UnaryOperator<Object>> {
private static final ProjectedRowEquality INSTANCE = new ProjectedRowEquality();
private static final UnaryOperator<Object> IDENTITY = UnaryOperator.identity();
private static final UnaryOperator<Object> BINARY =
value -> new ByteArrayWrapper((byte[]) value);

private ProjectedRowEquality() {}

static BiPredicate<InternalRow, InternalRow> create(RowType type) {
List<UnaryOperator<Object>> fields = INSTANCE.fieldKeys(type);
if (fields.stream().allMatch(ProjectedRowEquality::supportsDeepEquals)) {
return Objects::equals;
}
InternalRow.FieldGetter[] getters = InternalRow.createFieldGetters(type);
for (int i = 0; i < getters.length; i++) {
UnaryOperator<Object> key = fields.get(i);
if (!supportsDeepEquals(key)) {
InternalRow.FieldGetter getter = getters[i];
getters[i] = row -> comparisonKey(key, getter.getFieldOrNull(row));
}
}
return (left, right) -> {
for (InternalRow.FieldGetter getter : getters) {
if (!Objects.deepEquals(
getter.getFieldOrNull(left), getter.getFieldOrNull(right))) {
return false;
}
}
return true;
};
}

// GenericRow, GenericArray and GenericMap values already compare byte[] by content.
// Java map keys also need a content-based hash code.
private static boolean supportsDeepEquals(UnaryOperator<Object> key) {
return key == IDENTITY || key == BINARY;
}

@Override
protected UnaryOperator<Object> defaultMethod(DataType type) {
return IDENTITY;
}

@Override
public UnaryOperator<Object> visit(BinaryType type) {
return BINARY;
}

@Override
public UnaryOperator<Object> visit(BytesType type) {
return BINARY;
}

@Override
public UnaryOperator<Object> visit(MapType type) {
UnaryOperator<Object> key = type.getKeyType().accept(this);
UnaryOperator<Object> value = type.getValueType().accept(this);
if (key == IDENTITY && supportsDeepEquals(value)) {
return IDENTITY;
}
InternalArray.ElementGetter keyGetter =
InternalArray.createElementGetter(type.getKeyType());
InternalArray.ElementGetter valueGetter =
InternalArray.createElementGetter(type.getValueType());
return object -> {
InternalMap map = (InternalMap) object;
Map<Object, Object> entries = newHashMapWithExpectedSize(map.size());
InternalArray keys = map.keyArray();
InternalArray values = map.valueArray();
for (int i = 0; i < map.size(); i++) {
entries.put(
key.apply(keyGetter.getElementOrNull(keys, i)),
comparisonKey(value, valueGetter.getElementOrNull(values, i)));
}
return entries;
};
}

@Override
public UnaryOperator<Object> visit(ArrayType type) {
UnaryOperator<Object> element = type.getElementType().accept(this);
if (supportsDeepEquals(element)) {
return IDENTITY;
}
InternalArray.ElementGetter getter =
InternalArray.createElementGetter(type.getElementType());
return object -> {
InternalArray array = (InternalArray) object;
List<Object> elements = new ArrayList<>(array.size());
for (int i = 0; i < array.size(); i++) {
elements.add(comparisonKey(element, getter.getElementOrNull(array, i)));
}
return elements;
};
}

@Override
public UnaryOperator<Object> visit(RowType type) {
List<UnaryOperator<Object>> fields = fieldKeys(type);
if (fields.stream().allMatch(ProjectedRowEquality::supportsDeepEquals)) {
return IDENTITY;
}
InternalRow.FieldGetter[] getters = InternalRow.createFieldGetters(type);
return object -> {
InternalRow row = (InternalRow) object;
List<Object> values = new ArrayList<>(fields.size());
for (int i = 0; i < getters.length; i++) {
values.add(comparisonKey(fields.get(i), getters[i].getFieldOrNull(row)));
}
return values;
};
}

private List<UnaryOperator<Object>> fieldKeys(RowType type) {
return type.getFieldTypes().stream()
.map(field -> field.accept(this))
.collect(Collectors.toList());
}

private static Object comparisonKey(UnaryOperator<Object> key, Object value) {
return value == null ? null : key.apply(value);
}
}
Loading
Loading