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 @@ -17,9 +17,11 @@

package org.apache.fluss.flink.source.reader;

import org.apache.fluss.annotation.VisibleForTesting;
import org.apache.fluss.config.Configuration;
import org.apache.fluss.flink.adapter.SingleThreadMultiplexSourceReaderBaseAdapter;
import org.apache.fluss.flink.lake.LakeSplitStateInitializer;
import org.apache.fluss.flink.lake.split.LakeSnapshotSplit;
import org.apache.fluss.flink.source.emitter.FlinkRecordEmitter;
import org.apache.fluss.flink.source.event.FinishedKvSnapshotConsumeEvent;
import org.apache.fluss.flink.source.event.PartitionBucketsUnsubscribedEvent;
Expand Down Expand Up @@ -48,7 +50,10 @@

import javax.annotation.Nullable;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
Expand All @@ -61,6 +66,16 @@ public class FlinkSourceReader<OUT>

private static final Logger LOG = LoggerFactory.getLogger(FlinkSourceReader.class);

/**
* Orders lake snapshot splits in the order they were planned. The split index is assigned per
* partition in planning order, which is write order within a bucket.
*/
private static final Comparator<LakeSnapshotSplit> LAKE_SNAPSHOT_SPLIT_ORDER =
Comparator.comparing(
(LakeSnapshotSplit split) -> split.getTableBucket().getPartitionId(),
Comparator.nullsFirst(Comparator.<Long>naturalOrder()))
.thenComparingInt(LakeSnapshotSplit::getSplitIndex);

/** the tableBuckets ignore to send FinishedKvSnapshotConsumeEvent as it already sending. */
private final Set<TableBucket> finishedKvSnapshotConsumeBuckets;

Expand Down Expand Up @@ -95,6 +110,14 @@ public FlinkSourceReader(
this.finishedKvSnapshotConsumeBuckets = new HashSet<>();
}

@Override
public void addSplits(List<SourceSplitBase> splits) {
// Restored splits come from the reader's checkpointed state, which Flink keeps in no
// particular order. A bucket's lake snapshot splits are read one after another, so put
// them back in planning order before handing them to the split reader.
super.addSplits(sortLakeSnapshotSplits(splits));
}

@Override
protected void onSplitFinished(Map<String, SourceSplitState> map) {
// do nothing
Expand Down Expand Up @@ -141,6 +164,31 @@ public List<SourceSplitBase> snapshotState(long checkpointId) {
return sourceSplitBases;
}

/**
* Returns the splits with the lake snapshot splits in planning order. Other splits keep their
* positions.
*/
@VisibleForTesting
static List<SourceSplitBase> sortLakeSnapshotSplits(List<SourceSplitBase> splits) {
List<LakeSnapshotSplit> lakeSnapshotSplits = new ArrayList<>();
for (SourceSplitBase split : splits) {
if (split instanceof LakeSnapshotSplit) {
lakeSnapshotSplits.add((LakeSnapshotSplit) split);
}
}
if (lakeSnapshotSplits.size() < 2) {
return splits;
}
lakeSnapshotSplits.sort(LAKE_SNAPSHOT_SPLIT_ORDER);
Iterator<LakeSnapshotSplit> sortedLakeSnapshotSplits = lakeSnapshotSplits.iterator();
List<SourceSplitBase> result = new ArrayList<>(splits.size());
for (SourceSplitBase split : splits) {
result.add(
split instanceof LakeSnapshotSplit ? sortedLakeSnapshotSplits.next() : split);
}
return result;
}

@Override
public void handleSourceEvents(SourceEvent sourceEvent) {
if (sourceEvent instanceof PartitionsRemovedEvent) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
Expand All @@ -51,6 +52,7 @@
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.apache.fluss.client.table.scanner.log.LogScanner.EARLIEST_OFFSET;
Expand Down Expand Up @@ -151,6 +153,73 @@ private static Map<Integer, Long> zeroOffsets(Collection<Integer> buckets) {
}
}

@Test
void testLogTableLakeSplitIndexFollowsPlanningOrderWithinBucket() throws Exception {
TablePath path = TablePath.of("db", "log_table");
TableDescriptor descriptor =
TableDescriptor.builder()
.schema(Schema.newBuilder().column("id", DataTypes.INT()).build())
.distributedBy(2, "id")
.build();
TableInfo info = TableInfo.of(path, 1L, 1, descriptor, null, 1L, 1L);

// The planner returns the lake splits of both buckets interleaved, in write order.
List<LakeSplit> plannedSplits =
Arrays.asList(
new TestingLakeSplit(0, Collections.emptyList()),
new TestingLakeSplit(1, Collections.emptyList()),
new TestingLakeSplit(0, Collections.emptyList()),
new TestingLakeSplit(0, Collections.emptyList()),
new TestingLakeSplit(1, Collections.emptyList()));
Map<TableBucket, Long> lakeOffsets = new HashMap<>();
lakeOffsets.put(new TableBucket(1L, 0), 30L);
lakeOffsets.put(new TableBucket(1L, 1), 20L);
TestAdminAdapter admin =
new TestAdminAdapter() {
@Override
public CompletableFuture<LakeSnapshot> getReadableLakeSnapshot(
TablePath ignored) {
return CompletableFuture.completedFuture(new LakeSnapshot(1L, lakeOffsets));
}
};
LakeSplitGenerator generator =
new LakeSplitGenerator(
info,
admin,
TestingLakeSource.fromSplits(plannedSplits),
new ZeroOffsetsRetriever(),
OffsetsInitializer.latest(),
2,
Collections::emptySet);

List<SourceSplitBase> splits = generator.generateHybridLakeFlussSplits();

// The reader restores a bucket's lake splits by split index, so the index must follow
// the planning order within each bucket.
for (int bucket = 0; bucket < 2; bucket++) {
int currentBucket = bucket;
List<LakeSplit> expected =
plannedSplits.stream()
.filter(split -> split.bucket() == currentBucket)
.collect(Collectors.toList());
List<LakeSnapshotSplit> lakeSnapshotSplits = new ArrayList<>();
for (SourceSplitBase split : splits) {
if (split instanceof LakeSnapshotSplit
&& split.getTableBucket().getBucket() == currentBucket) {
lakeSnapshotSplits.add((LakeSnapshotSplit) split);
}
}
lakeSnapshotSplits.sort(
(left, right) -> Integer.compare(left.getSplitIndex(), right.getSplitIndex()));
assertThat(lakeSnapshotSplits)
.extracting(LakeSnapshotSplit::getLakeSplit)
.containsExactlyElementsOf(expected);
}
// Split ids must stay unique within the table.
assertThat(splits.stream().map(SourceSplitBase::splitId).distinct().count())
.isEqualTo(splits.size());
}

@Test
void testPrimaryKeyOutOfRangeLakeBucketFailsLoud() throws Exception {
// lake split lands in bucket 5, which is outside [0, 2)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@
import org.apache.flink.table.data.RowData;
import org.junit.jupiter.api.Test;

import javax.annotation.Nullable;

import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
Expand Down Expand Up @@ -515,6 +517,128 @@ clientConf, tablePath, rowType, new TestingReaderContext(), lakeSource)) {
.containsExactly(2, 3);
}

@Test
void testLakeSnapshotSplitsKeepPlanningOrderAcrossRestore() throws Exception {
TablePath tablePath = TablePath.of(DEFAULT_DB, "test_lake_snapshot_split_order");
TableDescriptor tableDescriptor =
TableDescriptor.builder().schema(DEFAULT_LOG_TABLE_SCHEMA).distributedBy(2).build();
long tableId = createTable(tablePath, tableDescriptor);
RowType rowType = tableDescriptor.getSchema().getRowType();

// Two buckets on one reader, three lake splits each, in planning (write) order. Each
// split holds two records whose id encodes the split index.
List<SourceSplitBase> plannedSplits = new ArrayList<>();
for (int splitIndex = 0; splitIndex < 6; splitIndex++) {
int bucket = splitIndex % 2;
plannedSplits.add(
new LakeSnapshotSplit(
new TableBucket(tableId, bucket),
null,
new OrderedTestingLakeSplit(
bucket, splitIndex * 10 + 1, splitIndex * 10 + 2),
splitIndex));
}

// Splits can arrive in any order, so add them reversed.
List<SourceSplitBase> assignedSplits = new ArrayList<>(plannedSplits);
Collections.reverse(assignedSplits);
TestingReaderOutput<RowData> output = new TestingReaderOutput<>();
List<SourceSplitBase> checkpoint;
try (FlinkSourceReader<RowData> reader =
createReader(
clientConf,
tablePath,
rowType,
new TestingReaderContext(),
new OrderedTestingLakeSource())) {
reader.addSplits(assignedSplits);
retry(
Duration.ofMinutes(1),
() -> {
reader.pollNext(output);
assertThat(output.getEmittedRecords()).hasSize(3);
});
checkpoint = new ArrayList<>(reader.snapshotState(1L));
}

// Restore while lake splits are still pending. Flink restores reader state in no
// particular order, so reverse it.
Collections.reverse(checkpoint);
TestingReaderOutput<RowData> restoredOutput = new TestingReaderOutput<>();
try (FlinkSourceReader<RowData> restoredReader =
createReader(
clientConf,
tablePath,
rowType,
new TestingReaderContext(),
new OrderedTestingLakeSource())) {
restoredReader.addSplits(checkpoint);
retry(
Duration.ofMinutes(1),
() -> {
restoredReader.pollNext(restoredOutput);
assertThat(restoredOutput.getEmittedRecords()).hasSize(9);
});
}

List<RowData> emitted = new ArrayList<>(output.getEmittedRecords());
emitted.addAll(restoredOutput.getEmittedRecords());
assertThat(idsOfBucket(emitted, 0)).containsExactly(1, 2, 21, 22, 41, 42);
assertThat(idsOfBucket(emitted, 1)).containsExactly(11, 12, 31, 32, 51, 52);
}

@Test
void testSortLakeSnapshotSplitsKeepsOtherSplitsInPlace() {
TableBucket bucket0 = new TableBucket(1L, 0);
TableBucket bucket1 = new TableBucket(1L, 1);
LakeSnapshotSplit first =
new LakeSnapshotSplit(bucket0, null, new TestingLakeSplit(0, null), 0);
LakeSnapshotSplit second =
new LakeSnapshotSplit(bucket0, null, new TestingLakeSplit(0, null), 1);
LogSplit logSplit = new LogSplit(bucket1, null, 0L);

assertThat(FlinkSourceReader.sortLakeSnapshotSplits(Arrays.asList(second, logSplit, first)))
.containsExactly(first, logSplit, second);
}

@Test
void testSortLakeSnapshotSplitsOrdersByPartitionThenSplitIndex() {
// Split indexes restart in every partition, so the partition is compared first.
LakeSnapshotSplit p2Index0 = lakeSnapshotSplit(2L, 0, 0);
LakeSnapshotSplit p1Index1 = lakeSnapshotSplit(1L, 1, 1);
LakeSnapshotSplit p1Index0 = lakeSnapshotSplit(1L, 0, 0);
LakeSnapshotSplit p1Index2 = lakeSnapshotSplit(1L, 0, 2);
LakeSnapshotSplit p2Index1 = lakeSnapshotSplit(2L, 1, 1);

assertThat(
FlinkSourceReader.sortLakeSnapshotSplits(
Arrays.asList(p2Index1, p1Index2, p2Index0, p1Index1, p1Index0)))
.containsExactly(p1Index0, p1Index1, p1Index2, p2Index0, p2Index1);
}

@Test
void testSortLakeSnapshotSplitsLeavesOtherSplitTypesUntouched() {
TableBucket bucket0 = new TableBucket(1L, 0);
TableBucket bucket1 = new TableBucket(1L, 1);
List<SourceSplitBase> noLakeSnapshotSplits =
Arrays.asList(
new LogSplit(bucket1, null, 0L),
new LakeSnapshotAndFlussLogSplit(
bucket0,
null,
Collections.singletonList(
new TestingLakeSplit(0, Collections.emptyList())),
0L,
10L));
assertThat(FlinkSourceReader.sortLakeSnapshotSplits(noLakeSnapshotSplits))
.isSameAs(noLakeSnapshotSplits);

List<SourceSplitBase> oneLakeSnapshotSplit =
Arrays.asList(new LogSplit(bucket1, null, 0L), lakeSnapshotSplit(null, 0, 0));
assertThat(FlinkSourceReader.sortLakeSnapshotSplits(oneLakeSnapshotSplit))
.isSameAs(oneLakeSnapshotSplit);
}

@Test
void testHandlePartitionsRemovedEvent() throws Exception {
TablePath tablePath = TablePath.of(DEFAULT_DB, "test_partitioned_table");
Expand Down Expand Up @@ -804,6 +928,49 @@ private int getNumAliveFetchers() {
}
}

private static LakeSnapshotSplit lakeSnapshotSplit(
@Nullable Long partitionId, int bucket, int splitIndex) {
return new LakeSnapshotSplit(
new TableBucket(1L, partitionId, bucket),
partitionId == null ? null : "p" + partitionId,
new TestingLakeSplit(bucket, Collections.emptyList()),
splitIndex);
}

private static List<Integer> idsOfBucket(List<RowData> rows, int bucket) {
return rows.stream()
.filter(row -> row.getString(1).toString().equals("b" + bucket))
.map(row -> row.getInt(0))
.collect(Collectors.toList());
}

/** A lake split that carries the ids of the records it holds. */
private static final class OrderedTestingLakeSplit extends TestingLakeSplit {

private final List<Integer> ids;

private OrderedTestingLakeSplit(int bucket, Integer... ids) {
super(bucket, null);
this.ids = Arrays.asList(ids);
}
}

/** A lake source that reads the records an {@link OrderedTestingLakeSplit} holds. */
private static final class OrderedTestingLakeSource extends TestingLakeSource {

@Override
public RecordReader createRecordReader(ReaderContext<LakeSplit> context) {
OrderedTestingLakeSplit split = (OrderedTestingLakeSplit) context.lakeSplit();
List<LogRecord> records = new ArrayList<>();
for (int id : split.ids) {
records.add(
new GenericRecord(
-1L, -1L, ChangeType.APPEND_ONLY, row(id, "b" + split.bucket())));
}
return () -> CloseableIterator.wrap(records.iterator());
}
}

private static final class TrackingLakeSource extends TestingLakeSource {

private final List<LogRecord> records;
Expand Down
Loading