diff --git a/fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/source/reader/FlinkSourceReader.java b/fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/source/reader/FlinkSourceReader.java index 65ef6e75ee5..b16d1b0a62e 100644 --- a/fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/source/reader/FlinkSourceReader.java +++ b/fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/source/reader/FlinkSourceReader.java @@ -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; @@ -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; @@ -61,6 +66,16 @@ public class FlinkSourceReader 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 LAKE_SNAPSHOT_SPLIT_ORDER = + Comparator.comparing( + (LakeSnapshotSplit split) -> split.getTableBucket().getPartitionId(), + Comparator.nullsFirst(Comparator.naturalOrder())) + .thenComparingInt(LakeSnapshotSplit::getSplitIndex); + /** the tableBuckets ignore to send FinishedKvSnapshotConsumeEvent as it already sending. */ private final Set finishedKvSnapshotConsumeBuckets; @@ -95,6 +110,14 @@ public FlinkSourceReader( this.finishedKvSnapshotConsumeBuckets = new HashSet<>(); } + @Override + public void addSplits(List 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 map) { // do nothing @@ -141,6 +164,31 @@ public List snapshotState(long checkpointId) { return sourceSplitBases; } + /** + * Returns the splits with the lake snapshot splits in planning order. Other splits keep their + * positions. + */ + @VisibleForTesting + static List sortLakeSnapshotSplits(List splits) { + List 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 sortedLakeSnapshotSplits = lakeSnapshotSplits.iterator(); + List 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) { diff --git a/fluss-flink/fluss-flink-common/src/test/java/org/apache/fluss/flink/lake/LakeSplitGeneratorTest.java b/fluss-flink/fluss-flink-common/src/test/java/org/apache/fluss/flink/lake/LakeSplitGeneratorTest.java index b68dbdd411c..f5e9f96ef8b 100644 --- a/fluss-flink/fluss-flink-common/src/test/java/org/apache/fluss/flink/lake/LakeSplitGeneratorTest.java +++ b/fluss-flink/fluss-flink-common/src/test/java/org/apache/fluss/flink/lake/LakeSplitGeneratorTest.java @@ -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; @@ -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; @@ -151,6 +153,73 @@ private static Map zeroOffsets(Collection 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 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 lakeOffsets = new HashMap<>(); + lakeOffsets.put(new TableBucket(1L, 0), 30L); + lakeOffsets.put(new TableBucket(1L, 1), 20L); + TestAdminAdapter admin = + new TestAdminAdapter() { + @Override + public CompletableFuture 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 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 expected = + plannedSplits.stream() + .filter(split -> split.bucket() == currentBucket) + .collect(Collectors.toList()); + List 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) diff --git a/fluss-flink/fluss-flink-common/src/test/java/org/apache/fluss/flink/source/reader/FlinkSourceReaderTest.java b/fluss-flink/fluss-flink-common/src/test/java/org/apache/fluss/flink/source/reader/FlinkSourceReaderTest.java index 9894ca5ba93..8ba7d935db1 100644 --- a/fluss-flink/fluss-flink-common/src/test/java/org/apache/fluss/flink/source/reader/FlinkSourceReaderTest.java +++ b/fluss-flink/fluss-flink-common/src/test/java/org/apache/fluss/flink/source/reader/FlinkSourceReaderTest.java @@ -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; @@ -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 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 assignedSplits = new ArrayList<>(plannedSplits); + Collections.reverse(assignedSplits); + TestingReaderOutput output = new TestingReaderOutput<>(); + List checkpoint; + try (FlinkSourceReader 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 restoredOutput = new TestingReaderOutput<>(); + try (FlinkSourceReader 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 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 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 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"); @@ -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 idsOfBucket(List 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 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 context) { + OrderedTestingLakeSplit split = (OrderedTestingLakeSplit) context.lakeSplit(); + List 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 records; diff --git a/fluss-lake/fluss-lake-iceberg-common/src/main/java/org/apache/fluss/lake/iceberg/source/IcebergSplitPlanner.java b/fluss-lake/fluss-lake-iceberg-common/src/main/java/org/apache/fluss/lake/iceberg/source/IcebergSplitPlanner.java index 34c02175691..f47bf8cd2aa 100644 --- a/fluss-lake/fluss-lake-iceberg-common/src/main/java/org/apache/fluss/lake/iceberg/source/IcebergSplitPlanner.java +++ b/fluss-lake/fluss-lake-iceberg-common/src/main/java/org/apache/fluss/lake/iceberg/source/IcebergSplitPlanner.java @@ -35,24 +35,48 @@ import org.apache.iceberg.expressions.ExpressionVisitors; import org.apache.iceberg.expressions.UnboundPredicate; import org.apache.iceberg.io.CloseableIterable; +import org.apache.iceberg.types.Conversions; +import org.apache.iceberg.types.Types; import javax.annotation.Nullable; import java.io.IOException; +import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.apache.fluss.lake.iceberg.utils.IcebergConversions.toIceberg; +import static org.apache.fluss.metadata.TableDescriptor.OFFSET_COLUMN_NAME; /** Iceberg split planner. */ public class IcebergSplitPlanner implements Planner { + /** + * Orders splits by the data sequence number of their file, which follows the commit order of + * the tiering rounds. Files without a data sequence number are ordered first. + * + *

Files of one commit share a sequence number, and Iceberg may list them in any order: a + * commit's files can span several manifests, which {@code planFiles()} reads in parallel. A + * tiering round writes each bucket with a single rolling writer, whose file names differ only + * in a zero-padded counter that grows as it rolls files, so the file name puts those files + * back in write order. The name, not the full location, is compared, since a location provider + * may prefix it with a hash. + */ + private static final Comparator SEQUENCE_NUMBER_ORDER = + Comparator.comparing( + split -> split.fileScanTask().file().dataSequenceNumber(), + Comparator.nullsFirst(Comparator.naturalOrder())) + .thenComparing(split -> fileName(split.fileScanTask().file().location())); + private final Configuration icebergConfig; private final TablePath tablePath; private final long snapshotId; @@ -73,12 +97,21 @@ public List plan() throws IOException { Table table = catalog.loadTable(toIceberg(tablePath)); Function> partitionExtract = createPartitionExtractor(table); Function bucketExtractor = createBucketExtractor(table); + // Tables tiered before FIP-27 carry the __offset column, which orders a bucket's rows + // exactly, also after compaction. + Types.NestedField offsetField = table.schema().findField(OFFSET_COLUMN_NAME); TableScan tableScan = table.newScan().useSnapshot(snapshotId); + Set statsColumns = new HashSet<>(); + if (filter != null) { + statsColumns.addAll(referencedColumns(filter)); + } + if (offsetField != null) { + statsColumns.add(OFFSET_COLUMN_NAME); + } + if (!statsColumns.isEmpty()) { + tableScan = tableScan.includeColumnStats(statsColumns); + } if (filter != null) { - Set filterColumns = referencedColumns(filter); - if (!filterColumns.isEmpty()) { - tableScan = tableScan.includeColumnStats(filterColumns); - } tableScan = tableScan.filter(filter); } try (CloseableIterable tasks = tableScan.planFiles()) { @@ -90,9 +123,48 @@ public List plan() throws IOException { bucketExtractor.apply(task), partitionExtract.apply(task)))); } + // Iceberg plans files in no particular order: manifests are kept in a hash set and, + // with more than one manifest, planned concurrently on a worker pool. The Flink source + // reads a bucket's lake splits one after another, so put them back in write order. + sortInWriteOrder(splits, offsetField == null ? null : offsetField.fieldId()); return splits; } + /** + * Sorts splits so that the files of each bucket are in write order. + * + *

If the table has an {@code __offset} column and every file records its lower bound, the + * files are ordered by it. The offsets of a bucket's files do not overlap, also after + * compaction, which rewrites runs of files sorted by {@code __offset}, so this order is exact. + * Otherwise, the files are ordered by {@link #SEQUENCE_NUMBER_ORDER}. + */ + @VisibleForTesting + static void sortInWriteOrder(List splits, @Nullable Integer offsetFieldId) { + if (offsetFieldId != null + && splits.stream() + .allMatch(split -> offsetLowerBound(split, offsetFieldId) != null)) { + splits.sort( + Comparator.comparing( + split -> offsetLowerBound(split, offsetFieldId)) + .thenComparing(SEQUENCE_NUMBER_ORDER)); + } else { + splits.sort(SEQUENCE_NUMBER_ORDER); + } + } + + @Nullable + private static Long offsetLowerBound(IcebergSplit split, int offsetFieldId) { + Map lowerBounds = split.fileScanTask().file().lowerBounds(); + ByteBuffer lowerBound = lowerBounds == null ? null : lowerBounds.get(offsetFieldId); + return lowerBound == null + ? null + : Conversions.fromByteBuffer(Types.LongType.get(), lowerBound); + } + + private static String fileName(String location) { + return location.substring(location.lastIndexOf('/') + 1); + } + @VisibleForTesting Set referencedColumns(Expression expression) { return ExpressionVisitors.visit( diff --git a/fluss-lake/fluss-lake-iceberg-common/src/main/java/org/apache/fluss/lake/iceberg/tiering/IcebergLakeCommitter.java b/fluss-lake/fluss-lake-iceberg-common/src/main/java/org/apache/fluss/lake/iceberg/tiering/IcebergLakeCommitter.java index 4b32c2d29a8..6ba2703cb5c 100644 --- a/fluss-lake/fluss-lake-iceberg-common/src/main/java/org/apache/fluss/lake/iceberg/tiering/IcebergLakeCommitter.java +++ b/fluss-lake/fluss-lake-iceberg-common/src/main/java/org/apache/fluss/lake/iceberg/tiering/IcebergLakeCommitter.java @@ -167,7 +167,17 @@ private Long commitRewrite( throw new IllegalArgumentException( "Rewrite data file results must have same snapshot id."); } - rewriteFiles.validateFromSnapshot(rewriteDataFileResults.get(0).snapshotId()); + long startingSnapshotId = rewriteDataFileResults.get(0).snapshotId(); + rewriteFiles.validateFromSnapshot(startingSnapshotId); + // The rewrite is committed after this round's data, so by default its files would get + // a newer data sequence number than the data and be read after it. Keep the sequence + // number of the snapshot the rewrite was planned from, as Spark's rewrite does, so + // compacted rows stay ordered before rows tiered later. Equality deletes committed + // since then still apply to the rewritten files. + Snapshot startingSnapshot = icebergTable.snapshot(startingSnapshotId); + if (startingSnapshot != null) { + rewriteFiles.dataSequenceNumber(startingSnapshot.sequenceNumber()); + } for (RewriteDataFileResult rewriteDataFileResult : rewriteDataFileResults) { rewriteDataFileResult.addedDataFiles().forEach(rewriteFiles::addFile); rewriteDataFileResult.deletedDataFiles().forEach(rewriteFiles::deleteFile); diff --git a/fluss-lake/fluss-lake-iceberg-common/src/test/java/org/apache/fluss/lake/iceberg/flink/FlinkUnionReadOrderITCase.java b/fluss-lake/fluss-lake-iceberg-common/src/test/java/org/apache/fluss/lake/iceberg/flink/FlinkUnionReadOrderITCase.java new file mode 100644 index 00000000000..b2a0288bc9b --- /dev/null +++ b/fluss-lake/fluss-lake-iceberg-common/src/test/java/org/apache/fluss/lake/iceberg/flink/FlinkUnionReadOrderITCase.java @@ -0,0 +1,470 @@ +/* + * 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.lake.iceberg.flink; + +import org.apache.fluss.client.initializer.OffsetsInitializer; +import org.apache.fluss.config.ConfigOptions; +import org.apache.fluss.flink.source.FlussSource; +import org.apache.fluss.flink.source.FlussSourceBuilder; +import org.apache.fluss.flink.source.deserializer.RowDataDeserializationSchema; +import org.apache.fluss.metadata.Schema; +import org.apache.fluss.metadata.TableBucket; +import org.apache.fluss.metadata.TableDescriptor; +import org.apache.fluss.metadata.TablePath; +import org.apache.fluss.row.InternalRow; +import org.apache.fluss.server.log.LogTablet; +import org.apache.fluss.types.DataTypes; + +import org.apache.flink.api.common.RuntimeExecutionMode; +import org.apache.flink.api.common.eventtime.WatermarkStrategy; +import org.apache.flink.api.common.functions.RichMapFunction; +import org.apache.flink.api.common.typeinfo.TypeInformation; +import org.apache.flink.api.connector.source.Boundedness; +import org.apache.flink.api.connector.source.ReaderOutput; +import org.apache.flink.api.connector.source.Source; +import org.apache.flink.api.connector.source.SourceEvent; +import org.apache.flink.api.connector.source.SourceReader; +import org.apache.flink.api.connector.source.SourceReaderContext; +import org.apache.flink.api.connector.source.SourceSplit; +import org.apache.flink.api.connector.source.SplitEnumerator; +import org.apache.flink.api.connector.source.SplitEnumeratorContext; +import org.apache.flink.api.java.typeutils.ResultTypeQueryable; +import org.apache.flink.configuration.Configuration; +import org.apache.flink.configuration.RestartStrategyOptions; +import org.apache.flink.core.execution.JobClient; +import org.apache.flink.core.io.InputStatus; +import org.apache.flink.core.io.SimpleVersionedSerializer; +import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; +import org.apache.flink.streaming.api.functions.sink.v2.DiscardingSink; +import org.apache.flink.table.data.RowData; +import org.apache.flink.util.CloseableIterator; +import org.apache.iceberg.FileScanTask; +import org.apache.iceberg.io.CloseableIterable; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.apache.fluss.lake.iceberg.utils.IcebergConversions.toIceberg; +import static org.apache.fluss.testutils.DataTestUtils.row; +import static org.apache.fluss.testutils.common.CommonTestUtils.waitUntil; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * End-to-end tests that a union read of a log table returns each bucket's rows in write order, when + * the bucket's lake data spans several Iceberg commits. + */ +class FlinkUnionReadOrderITCase extends FlinkUnionReadTestBase { + + private static final int BUCKET_NUM = 3; + private static final List KEYS = Arrays.asList("k0", "k1", "k2", "k3"); + private static final int LAKE_ROUNDS = 5; + private static final int ROWS_PER_ROUND = 10; + private static final int LAKE_ROWS_PER_KEY = LAKE_ROUNDS * ROWS_PER_ROUND; + private static final int TOTAL_ROWS_PER_KEY = LAKE_ROWS_PER_KEY + ROWS_PER_ROUND; + + /** Rows seen by {@link RecordRows}, shared across task attempts. */ + private static final Queue EMITTED_ROWS = new ConcurrentLinkedQueue<>(); + + /** Set when {@link FailOnceAfterCheckpointReader} has failed the job once. */ + private static final AtomicBoolean FAILED_ONCE = new AtomicBoolean(); + + @BeforeAll + protected static void beforeAll() { + FlinkUnionReadTestBase.beforeAll(); + } + + @BeforeEach + void resetSharedState() { + EMITTED_ROWS.clear(); + FAILED_ONCE.set(false); + } + + @Test + void testBatchUnionReadKeepsWriteOrderWithinBucket() throws Exception { + TablePath tablePath = TablePath.of(DEFAULT_DB, "union_read_order_batch"); + prepareTableWithSeveralLakeCommits(tablePath); + + StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); + env.setRuntimeMode(RuntimeExecutionMode.BATCH); + // One reader owns every bucket and reads their lake splits one after another. + env.setParallelism(1); + FlussSource source = sourceBuilder(tablePath).setBatch().build(); + Map> seqsByKey = new HashMap<>(); + try (CloseableIterator rows = + env.fromSource(source, WatermarkStrategy.noWatermarks(), "union read") + .executeAndCollect()) { + while (rows.hasNext()) { + RowData row = rows.next(); + seqsByKey + .computeIfAbsent(row.getString(0).toString(), k -> new ArrayList<>()) + .add(row.getInt(1)); + } + } + + List expectedSeqs = seqRange(0, TOTAL_ROWS_PER_KEY); + for (String key : KEYS) { + assertThat(seqsByKey.get(key)).as("rows of key %s", key).isEqualTo(expectedSeqs); + } + } + + @Test + void testStreamingUnionReadKeepsWriteOrderAcrossRestoreDuringLakePhase() throws Exception { + TablePath tablePath = TablePath.of(DEFAULT_DB, "union_read_order_restore"); + prepareTableWithSeveralLakeCommits(tablePath); + + Configuration conf = new Configuration(); + conf.set(RestartStrategyOptions.RESTART_STRATEGY, "fixed-delay"); + conf.set(RestartStrategyOptions.RESTART_STRATEGY_FIXED_DELAY_ATTEMPTS, 1); + conf.set(RestartStrategyOptions.RESTART_STRATEGY_FIXED_DELAY_DELAY, Duration.ofMillis(100)); + StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf); + env.setRuntimeMode(RuntimeExecutionMode.STREAMING); + env.enableCheckpointing(100); + // One reader owns every bucket. The reader pauses after a few rows and fails the job once + // a checkpoint taken during the pause completes, so the restore starts from a checkpoint + // that holds most of the lake splits. + env.setParallelism(1); + env.fromSource( + new FailOnceAfterCheckpointSource<>(sourceBuilder(tablePath).build()), + WatermarkStrategy.noWatermarks(), + "union read") + .map(new RecordRows()) + .sinkTo(new DiscardingSink<>()); + JobClient jobClient = env.executeAsync(); + try { + waitUntil( + () -> + KEYS.stream() + .allMatch( + key -> seqsOf(1, key).contains(TOTAL_ROWS_PER_KEY - 1)), + Duration.ofMinutes(2), + "the restored job did not read every row"); + } finally { + jobClient.cancel().get(); + } + + boolean restoredDuringLakePhase = false; + for (String key : KEYS) { + List beforeFailure = seqsOf(0, key); + List afterRestore = seqsOf(1, key); + // Before the failure, rows come out in write order from the start. + assertThat(beforeFailure) + .as("rows of key %s before the failure", key) + .isEqualTo(seqRange(0, beforeFailure.size())); + // After the restore, rows continue from the checkpointed position in write order, + // without a gap to what was read before the failure. + assertThat(afterRestore).as("rows of key %s after the restore", key).isNotEmpty(); + int resumedFrom = afterRestore.get(0); + assertThat(resumedFrom) + .as( + "first row of key %s after the restore must follow the %s rows read" + + " before the failure", + key, beforeFailure.size()) + .isLessThanOrEqualTo(beforeFailure.size()); + assertThat(afterRestore) + .as("rows of key %s after the restore", key) + .isEqualTo(seqRange(resumedFrom, TOTAL_ROWS_PER_KEY)); + restoredDuringLakePhase |= resumedFrom > 0 && resumedFrom < LAKE_ROWS_PER_KEY; + } + // At least one key must resume part way through its lake rows, which means the reader + // restored its own pending lake splits from the checkpoint. + assertThat(restoredDuringLakePhase) + .as("the job must restore from a checkpoint taken during the lake phase") + .isTrue(); + } + + /** + * Creates a log table and writes {@link #LAKE_ROUNDS} rounds of rows, waiting for each round to + * be tiered so that every round is a separate Iceberg commit. A last round is written after + * tiering stops, so it lives only in the Fluss log. Each key's rows carry a rising sequence + * number starting at 0. + */ + private void prepareTableWithSeveralLakeCommits(TablePath tablePath) throws Exception { + TableDescriptor descriptor = + TableDescriptor.builder() + .schema( + Schema.newBuilder() + .column("k", DataTypes.STRING()) + .column("seq", DataTypes.INT()) + .build()) + .distributedBy(BUCKET_NUM, "k") + .property(ConfigOptions.TABLE_DATALAKE_ENABLED.key(), "true") + .property(ConfigOptions.TABLE_DATALAKE_FRESHNESS, Duration.ofMillis(500)) + .build(); + long tableId = createTable(tablePath, descriptor); + + JobClient tieringJob = buildTieringJob(execEnv); + try { + for (int round = 0; round < LAKE_ROUNDS; round++) { + writeRound(tablePath, round); + waitUntilTieredToHighWatermark(tableId); + } + } finally { + tieringJob.cancel().get(); + } + writeRound(tablePath, LAKE_ROUNDS); + + // Every bucket that holds data must have one data file per tiering round, and the keys + // must cover more than one bucket. + Map dataFilesByBucket = new HashMap<>(); + try (CloseableIterable tasks = + icebergCatalog.loadTable(toIceberg(tablePath)).newScan().planFiles()) { + for (FileScanTask task : tasks) { + dataFilesByBucket.merge( + task.file().partition().get(0, Integer.class), 1, Integer::sum); + } + } + assertThat(dataFilesByBucket).hasSizeGreaterThan(1); + assertThat(dataFilesByBucket.values()).allMatch(count -> count >= LAKE_ROUNDS); + } + + private void writeRound(TablePath tablePath, int round) throws Exception { + List rows = new ArrayList<>(); + for (int i = 0; i < ROWS_PER_ROUND; i++) { + for (String key : KEYS) { + rows.add(row(key, round * ROWS_PER_ROUND + i)); + } + } + writeRows(tablePath, rows, true); + } + + private void waitUntilTieredToHighWatermark(long tableId) { + for (int bucket = 0; bucket < BUCKET_NUM; bucket++) { + TableBucket tableBucket = new TableBucket(tableId, bucket); + waitUntil( + () -> { + LogTablet logTablet = getLeaderReplica(tableBucket).getLogTablet(); + return logTablet.getLakeLogEndOffset() >= logTablet.getHighWatermark(); + }, + Duration.ofMinutes(2), + "bucket " + tableBucket + " was not tiered"); + } + } + + private FlussSourceBuilder sourceBuilder(TablePath tablePath) { + return FlussSource.builder() + .setBootstrapServers( + String.join(",", clientConf.get(ConfigOptions.BOOTSTRAP_SERVERS))) + .setDatabase(tablePath.getDatabaseName()) + .setTable(tablePath.getTableName()) + .setStartingOffsets(OffsetsInitializer.full()) + .setDeserializationSchema(new RowDataDeserializationSchema()); + } + + private static List seqsOf(int attempt, String key) { + return EMITTED_ROWS.stream() + .filter(row -> row.attempt == attempt && row.key.equals(key)) + .map(row -> row.seq) + .collect(Collectors.toList()); + } + + private static List seqRange(int fromInclusive, int toExclusive) { + return IntStream.range(fromInclusive, toExclusive).boxed().collect(Collectors.toList()); + } + + /** A row passed on by {@link RecordRows}, with the task attempt that saw it. */ + private static final class EmittedRow { + private final int attempt; + private final String key; + private final int seq; + + private EmittedRow(int attempt, String key, int seq) { + this.attempt = attempt; + this.key = key; + this.seq = seq; + } + } + + /** Records every row together with the task attempt that saw it. */ + private static final class RecordRows extends RichMapFunction { + + @Override + public RowData map(RowData row) { + int attempt = getRuntimeContext().getTaskInfo().getAttemptNumber(); + EMITTED_ROWS.add(new EmittedRow(attempt, row.getString(0).toString(), row.getInt(1))); + return row; + } + } + + /** Wraps a source so that its reader is a {@link FailOnceAfterCheckpointReader}. */ + private static final class FailOnceAfterCheckpointSource< + T, SplitT extends SourceSplit, EnumChkT> + implements Source, ResultTypeQueryable { + + private static final long serialVersionUID = 1L; + + private final Source delegate; + private final TypeInformation producedType; + + private & ResultTypeQueryable> + FailOnceAfterCheckpointSource(S delegate) { + this.delegate = delegate; + this.producedType = delegate.getProducedType(); + } + + @Override + public Boundedness getBoundedness() { + return delegate.getBoundedness(); + } + + @Override + public SourceReader createReader(SourceReaderContext readerContext) + throws Exception { + return new FailOnceAfterCheckpointReader<>(delegate.createReader(readerContext)); + } + + @Override + public SplitEnumerator createEnumerator( + SplitEnumeratorContext enumContext) throws Exception { + return delegate.createEnumerator(enumContext); + } + + @Override + public SplitEnumerator restoreEnumerator( + SplitEnumeratorContext enumContext, EnumChkT checkpoint) throws Exception { + return delegate.restoreEnumerator(enumContext, checkpoint); + } + + @Override + public SimpleVersionedSerializer getSplitSerializer() { + return delegate.getSplitSerializer(); + } + + @Override + public SimpleVersionedSerializer getEnumeratorCheckpointSerializer() { + return delegate.getEnumeratorCheckpointSerializer(); + } + + @Override + public TypeInformation getProducedType() { + return producedType; + } + } + + /** + * Pauses the first task attempt after {@link #PAUSE_AFTER_ROWS} rows and fails it once a + * checkpoint taken during the pause completes. While paused the reader reports no data, so the + * task stays idle and checkpoints run normally. That checkpoint holds the reader's pending lake + * splits, which the restored attempt gets back. After the failure the reader passes everything + * through. + */ + private static final class FailOnceAfterCheckpointReader + implements SourceReader { + + private static final int PAUSE_AFTER_ROWS = 5; + + private final SourceReader delegate; + private final CompletableFuture checkpointCompletedWhilePaused = + new CompletableFuture<>(); + private boolean paused; + private long checkpointTakenWhilePaused = -1L; + + private FailOnceAfterCheckpointReader(SourceReader delegate) { + this.delegate = delegate; + } + + @Override + public void start() { + delegate.start(); + } + + @Override + public InputStatus pollNext(ReaderOutput output) throws Exception { + if (!FAILED_ONCE.get()) { + if (checkpointCompletedWhilePaused.isDone()) { + FAILED_ONCE.set(true); + throw new RuntimeException("Expected test failure to trigger a restore."); + } + // The reader emits at most one row per call, so the pause starts exactly here. + if (EMITTED_ROWS.size() >= PAUSE_AFTER_ROWS) { + paused = true; + return InputStatus.NOTHING_AVAILABLE; + } + } + return delegate.pollNext(output); + } + + @Override + public CompletableFuture isAvailable() { + return paused && !FAILED_ONCE.get() + ? checkpointCompletedWhilePaused + : delegate.isAvailable(); + } + + @Override + public List snapshotState(long checkpointId) { + if (paused && checkpointTakenWhilePaused < 0) { + checkpointTakenWhilePaused = checkpointId; + } + return delegate.snapshotState(checkpointId); + } + + @Override + public void notifyCheckpointComplete(long checkpointId) throws Exception { + delegate.notifyCheckpointComplete(checkpointId); + if (checkpointTakenWhilePaused >= 0 && checkpointId >= checkpointTakenWhilePaused) { + checkpointCompletedWhilePaused.complete(null); + } + } + + @Override + public void notifyCheckpointAborted(long checkpointId) throws Exception { + delegate.notifyCheckpointAborted(checkpointId); + } + + @Override + public void addSplits(List splits) { + delegate.addSplits(splits); + } + + @Override + public void notifyNoMoreSplits() { + delegate.notifyNoMoreSplits(); + } + + @Override + public void handleSourceEvents(SourceEvent event) { + delegate.handleSourceEvents(event); + } + + @Override + public void pauseOrResumeSplits( + Collection splitsToPause, Collection splitsToResume) { + delegate.pauseOrResumeSplits(splitsToPause, splitsToResume); + } + + @Override + public void close() throws Exception { + delegate.close(); + } + } +} diff --git a/fluss-lake/fluss-lake-iceberg-common/src/test/java/org/apache/fluss/lake/iceberg/source/IcebergSplitPlannerTest.java b/fluss-lake/fluss-lake-iceberg-common/src/test/java/org/apache/fluss/lake/iceberg/source/IcebergSplitPlannerTest.java index a083b63f288..f70379ece3f 100644 --- a/fluss-lake/fluss-lake-iceberg-common/src/test/java/org/apache/fluss/lake/iceberg/source/IcebergSplitPlannerTest.java +++ b/fluss-lake/fluss-lake-iceberg-common/src/test/java/org/apache/fluss/lake/iceberg/source/IcebergSplitPlannerTest.java @@ -19,6 +19,7 @@ package org.apache.fluss.lake.iceberg.source; import org.apache.fluss.config.Configuration; +import org.apache.fluss.lake.iceberg.tiering.writer.TaskWriterFactory; import org.apache.fluss.lake.source.LakeSource; import org.apache.fluss.metadata.TablePath; import org.apache.fluss.predicate.PredicateBuilder; @@ -26,22 +27,34 @@ import org.apache.fluss.types.RowType; import org.apache.fluss.types.StringType; +import org.apache.iceberg.AppendFiles; +import org.apache.iceberg.DataFile; import org.apache.iceberg.PartitionSpec; import org.apache.iceberg.Schema; import org.apache.iceberg.Snapshot; import org.apache.iceberg.Table; +import org.apache.iceberg.TableProperties; import org.apache.iceberg.data.GenericRecord; +import org.apache.iceberg.data.Record; import org.apache.iceberg.expressions.Expression; import org.apache.iceberg.expressions.Expressions; +import org.apache.iceberg.io.TaskWriter; import org.apache.iceberg.types.Types; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import javax.annotation.Nullable; + import java.time.OffsetDateTime; import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; import java.util.List; +import java.util.Map; +import java.util.Random; import java.util.Set; import static org.apache.fluss.metadata.TableDescriptor.BUCKET_COLUMN_NAME; @@ -154,6 +167,121 @@ void testBucketUnawareLogTablePlan(boolean isPartitioned) throws Exception { } } + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void testLogTablePlanKeepsWriteOrderWithinBucket(boolean isPartitioned) throws Exception { + TablePath tablePath = + TablePath.of( + DEFAULT_DB, + "log_write_order_" + (isPartitioned ? "partitioned_" : "") + DEFAULT_TABLE); + Schema schema = + new Schema( + optional(1, "c1", Types.IntegerType.get()), + optional(2, "c2", Types.StringType.get())); + PartitionSpec partitionSpec = + isPartitioned + ? PartitionSpec.builderFor(schema).identity("c2").bucket("c1", 2).build() + : PartitionSpec.builderFor(schema).bucket("c1", 2).build(); + createTable(tablePath, schema, partitionSpec); + Table table = getTable(tablePath); + List partitions = + isPartitioned ? Arrays.asList("p1", "p2") : Collections.singletonList(null); + + // Each tiering round is one Iceberg commit. Interleave commits across partitions and + // buckets, so the snapshot has one manifest per commit and every bucket has several files. + Map bucketByFile = new HashMap<>(); + Map> expectedFilesByBucket = new HashMap<>(); + for (int round = 0; round < 5; round++) { + for (String partition : partitions) { + for (int bucket = 0; bucket < 2; bucket++) { + DataFile dataFile = writeDataFile(table, schema, partition, bucket, round); + table.newAppend().appendFile(dataFile).commit(); + recordFile(bucketByFile, expectedFilesByBucket, partition, bucket, dataFile); + } + } + } + // One commit holding several files of the same bucket, which share a sequence number. As + // in a tiering round, they are rolled by a single writer. + AppendFiles append = table.newAppend(); + for (DataFile dataFile : writeRollingDataFiles(table, schema, partitions.get(0), 0, 3)) { + append.appendFile(dataFile); + recordFile(bucketByFile, expectedFilesByBucket, partitions.get(0), 0, dataFile); + } + append.commit(); + table.refresh(); + long snapshotId = table.currentSnapshot().snapshotId(); + + // Iceberg's planning order varies between runs, so plan several times. + LakeSource lakeSource = lakeStorage.createLakeSource(tablePath); + for (int run = 0; run < 20; run++) { + Map> plannedFilesByBucket = new HashMap<>(); + for (IcebergSplit split : lakeSource.createPlanner(() -> snapshotId).plan()) { + String file = split.fileScanTask().file().location(); + assertThat(bucketKey(split.partition(), split.bucket())) + .isEqualTo(bucketByFile.get(file)); + plannedFilesByBucket + .computeIfAbsent(bucketByFile.get(file), k -> new ArrayList<>()) + .add(file); + } + assertThat(plannedFilesByBucket).isEqualTo(expectedFilesByBucket); + } + } + + @Test + void testSortKeepsRolledFilesOfOneCommitInWriteOrder() throws Exception { + TablePath tablePath = TablePath.of(DEFAULT_DB, "log_rolled_files_" + DEFAULT_TABLE); + Schema schema = + new Schema( + optional(1, "c1", Types.IntegerType.get()), + optional(2, "c2", Types.StringType.get())); + createTable(tablePath, schema, PartitionSpec.builderFor(schema).bucket("c1", 2).build()); + Table table = getTable(tablePath); + List dataFiles = writeRollingDataFiles(table, schema, null, 0, 4); + AppendFiles append = table.newAppend(); + dataFiles.forEach(append::appendFile); + append.commit(); + table.refresh(); + + // The files share a sequence number. Iceberg may list them in any order when the commit + // spans several manifests, which a shuffle stands in for. + assertSortRestoresWriteOrder(tablePath, table, null, locationsOf(dataFiles)); + } + + @Test + void testSortOrdersLegacyTableByOffset() throws Exception { + TablePath tablePath = TablePath.of(DEFAULT_DB, "log_legacy_offset_" + DEFAULT_TABLE); + Schema schema = + new Schema( + optional(1, "c1", Types.IntegerType.get()), + required(2, OFFSET_COLUMN_NAME, Types.LongType.get())); + createTable(tablePath, schema, PartitionSpec.builderFor(schema).bucket("c1", 2).build()); + Table table = getTable(tablePath); + // Files written by separate writers, as compaction does for separate file groups, so + // neither their sequence number nor their file name tells their order apart. + List dataFiles = new ArrayList<>(); + AppendFiles append = table.newAppend(); + for (int i = 0; i < 4; i++) { + try (TaskWriter taskWriter = + TaskWriterFactory.createTaskWriter(table, null, 0)) { + for (long offset = i * 10L; offset < i * 10L + 3; offset++) { + taskWriter.write(createIcebergRecord(schema, 1, offset)); + } + DataFile[] files = taskWriter.dataFiles(); + assertThat(files).hasSize(1); + dataFiles.add(files[0]); + append.appendFile(files[0]); + } + } + append.commit(); + table.refresh(); + + assertSortRestoresWriteOrder( + tablePath, + table, + table.schema().findField(OFFSET_COLUMN_NAME).fieldId(), + locationsOf(dataFiles)); + } + @Test void testOnlyIncludesFilterColumnStats() throws Exception { TablePath tablePath = TablePath.of(DEFAULT_DB, "test_filter_column_stats"); @@ -206,6 +334,85 @@ void testReferencedColumns() { assertThat(referencedColumns(boundExpression)).containsOnly("c2"); } + private DataFile writeDataFile( + Table table, Schema schema, @Nullable String partition, int bucket, int value) + throws Exception { + try (TaskWriter taskWriter = + TaskWriterFactory.createTaskWriter(table, partition, bucket)) { + taskWriter.write(createIcebergRecord(schema, value, partition)); + DataFile[] dataFiles = taskWriter.dataFiles(); + assertThat(dataFiles).hasSize(1); + return dataFiles[0]; + } + } + + /** Writes {@code numFiles} files of one bucket with a single writer that rolls them. */ + private List writeRollingDataFiles( + Table table, Schema schema, @Nullable String partition, int bucket, int numFiles) + throws Exception { + // The writer checks whether to roll every 1000 rows, so every 1000 rows go to a new file. + table.updateProperties().set(TableProperties.WRITE_TARGET_FILE_SIZE_BYTES, "1").commit(); + try (TaskWriter taskWriter = + TaskWriterFactory.createTaskWriter(table, partition, bucket)) { + for (int i = 0; i < numFiles * 1000; i++) { + taskWriter.write(createIcebergRecord(schema, i, partition)); + } + DataFile[] dataFiles = taskWriter.dataFiles(); + assertThat(dataFiles).hasSize(numFiles); + return Arrays.asList(dataFiles); + } finally { + table.updateProperties().remove(TableProperties.WRITE_TARGET_FILE_SIZE_BYTES).commit(); + } + } + + private void assertSortRestoresWriteOrder( + TablePath tablePath, + Table table, + @Nullable Integer offsetFieldId, + List expectedLocations) + throws Exception { + long snapshotId = table.currentSnapshot().snapshotId(); + List splits = + lakeStorage.createLakeSource(tablePath).createPlanner(() -> snapshotId).plan(); + Random random = new Random(42); + for (int run = 0; run < 20; run++) { + List shuffled = new ArrayList<>(splits); + Collections.shuffle(shuffled, random); + IcebergSplitPlanner.sortInWriteOrder(shuffled, offsetFieldId); + assertThat(shuffled) + .extracting(split -> split.fileScanTask().file().location()) + .containsExactlyElementsOf(expectedLocations); + } + } + + private static List locationsOf(List dataFiles) { + List locations = new ArrayList<>(); + dataFiles.forEach(dataFile -> locations.add(dataFile.location())); + return locations; + } + + private static void recordFile( + Map bucketByFile, + Map> expectedFilesByBucket, + @Nullable String partition, + int bucket, + DataFile dataFile) { + String bucketKey = + bucketKey( + partition == null + ? Collections.emptyList() + : Collections.singletonList(partition), + bucket); + bucketByFile.put(dataFile.location(), bucketKey); + expectedFilesByBucket + .computeIfAbsent(bucketKey, k -> new ArrayList<>()) + .add(dataFile.location()); + } + + private static String bucketKey(List partition, int bucket) { + return partition + "/" + bucket; + } + private Set referencedColumns(Expression expression) { return new IcebergSplitPlanner( new Configuration(), diff --git a/fluss-lake/fluss-lake-iceberg-common/src/test/java/org/apache/fluss/lake/iceberg/tiering/IcebergLakeCommitterTest.java b/fluss-lake/fluss-lake-iceberg-common/src/test/java/org/apache/fluss/lake/iceberg/tiering/IcebergLakeCommitterTest.java index 50b0a0c69b9..b4588fde6a1 100644 --- a/fluss-lake/fluss-lake-iceberg-common/src/test/java/org/apache/fluss/lake/iceberg/tiering/IcebergLakeCommitterTest.java +++ b/fluss-lake/fluss-lake-iceberg-common/src/test/java/org/apache/fluss/lake/iceberg/tiering/IcebergLakeCommitterTest.java @@ -62,7 +62,10 @@ import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.Collections; +import java.util.HashMap; import java.util.HashSet; +import java.util.List; +import java.util.Map; import java.util.Set; import static org.apache.fluss.lake.iceberg.utils.IcebergConversions.toIceberg; @@ -133,6 +136,41 @@ void testRewriteDeletesAddedFilesWhenCommitFailed() throws Exception { assertFallsBackToDataCommit(table, result, snapshotBefore); } + @Test + void testRewriteKeepsSequenceNumberOfStartingSnapshot() throws Exception { + Table table = createTableWithSmallFiles(); + RewriteDataFileResult rewrite = planRewrite(table); + long startingSequenceNumber = table.snapshot(rewrite.snapshotId()).sequenceNumber(); + DataFile tieredData = writeDataFile(table, 100L); + + // The round commits its tiered data first and the rewrite after it. + LakeCommitResult result = + commit(icebergCatalog, Collections.singletonList(tieredData), rewrite); + + table.refresh(); + assertThat(table.snapshot(result.getCommittedSnapshotId()).operation()) + .isEqualTo(DataOperations.REPLACE); + Map sequenceNumbers = new HashMap<>(); + try (CloseableIterable tasks = table.newScan().planFiles()) { + tasks.forEach( + task -> + sequenceNumbers.put( + task.file().location(), task.file().dataSequenceNumber())); + } + Set rewritten = locationsOf(rewrite.addedDataFiles()); + assertThat(sequenceNumbers.keySet()) + .containsExactlyInAnyOrderElementsOf( + union(rewritten, Collections.singleton(tieredData.location()))); + // Compacted rows keep the sequence number they were planned from, so they are still read + // before the rows tiered in the same round. + rewritten.forEach( + location -> + assertThat(sequenceNumbers.get(location)) + .isEqualTo(startingSequenceNumber)); + assertThat(sequenceNumbers.get(tieredData.location())) + .isGreaterThan(startingSequenceNumber); + } + @Test void testRewriteDeletesAddedFilesWhenConflictingWithConcurrentDelete() throws Exception { Table table = createTableWithSmallFiles(); @@ -182,6 +220,13 @@ void testRewriteDeletesAddedFilesWhenFailingBeforeCommit() throws Exception { /** Commits a tiering round that carries no new data but the given rewrites. */ private LakeCommitResult commitRewrites(Catalog catalog, RewriteDataFileResult... rewrites) throws Exception { + return commit(catalog, Collections.emptyList(), rewrites); + } + + /** Commits a tiering round that carries the given data files and rewrites. */ + private LakeCommitResult commit( + Catalog catalog, List dataFiles, RewriteDataFileResult... rewrites) + throws Exception { IcebergCatalogProvider provider = new IcebergCatalogProvider(configuration) { @Override @@ -190,6 +235,7 @@ public Catalog get() { } }; IcebergCommittable.Builder committable = IcebergCommittable.builder(); + dataFiles.forEach(committable::addDataFile); for (RewriteDataFileResult rewrite : rewrites) { committable.addRewriteDataFileResult(rewrite); } @@ -289,6 +335,12 @@ private static Set currentDataFiles(Table table) throws IOException { return locations; } + private static Set union(Set first, Set second) { + Set union = new HashSet<>(first); + union.addAll(second); + return union; + } + private static boolean exists(Table table, String location) { return table.io().newInputFile(location).exists(); } diff --git a/website/docs/streaming-lakehouse/union-read.md b/website/docs/streaming-lakehouse/union-read.md index 18617486375..c4d8f09b2c2 100644 --- a/website/docs/streaming-lakehouse/union-read.md +++ b/website/docs/streaming-lakehouse/union-read.md @@ -78,6 +78,17 @@ For **primary key tables**, Union Read automatically deduplicates records with t For **log tables** (append-only), Union Read concatenates data from both sources without deduplication. +## Read Order + +For **log tables** with a bucket key, Flink Union Read returns each bucket's lake data before its Fluss log data, and the hand-off between them has no gap and no overlap. Rows from different buckets are not ordered relative to each other. Whether rows inside the lake data stay in write order depends on the lake format: + +- **Paimon**: the lake data of a bucket is read in write order. +- **Iceberg**: tables created before Fluss 1.0, which carry the `__offset` system column, are read in write order, also after compaction. For other tables, a bucket's data files are read in commit order, which is write order until the table is compacted. Compaction rewrites files without keeping row order, so rows rewritten by a compaction run can come out of order, among themselves and relative to files of the bucket that the run did not rewrite. Compacted data is still read before data tiered after the compaction was planned. + +Tables without a bucket key have no per-bucket order in the lake for either format. Rescaling a job while it is still reading lake data also loses the order. + +For event-time processing, note that a source reader often reads several buckets and partitions one after another. If an idle timeout is set, the watermark can advance past buckets that have not been read yet. + ## Data Freshness The `table.datalake.freshness` option controls how often data is tiered to the lake: