From 2296566f146f30ab7d8a4f34e07a319a3fda0aa5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=BF=9F=E5=B2=B8?= Date: Mon, 5 Oct 2026 15:45:21 +0800 Subject: [PATCH] [core] Add single-pass split planning --- .../apache/paimon/manifest/ManifestFile.java | 25 +- .../operation/AbstractFileStoreScan.java | 233 ++++++++++++++++++ .../paimon/operation/FileStoreScan.java | 32 +++ .../table/source/AbstractBatchTableScan.java | 31 +++ .../table/source/AbstractDataTableScan.java | 24 ++ .../table/source/AppendBatchTableScan.java | 5 + .../paimon/table/source/InnerTableScan.java | 6 + .../snapshot/ReadPlanStartingScanner.java | 10 + .../table/source/snapshot/SnapshotReader.java | 81 ++++++ .../source/snapshot/SnapshotReaderImpl.java | 64 +++++ .../table/AppendOnlySimpleTableTest.java | 67 +++++ .../source/snapshot/SnapshotReaderTest.java | 210 ++++++++++++++++ 12 files changed, 781 insertions(+), 7 deletions(-) diff --git a/paimon-core/src/main/java/org/apache/paimon/manifest/ManifestFile.java b/paimon-core/src/main/java/org/apache/paimon/manifest/ManifestFile.java index 608c7dc57610..f6f3dc3d6d3e 100644 --- a/paimon-core/src/main/java/org/apache/paimon/manifest/ManifestFile.java +++ b/paimon-core/src/main/java/org/apache/paimon/manifest/ManifestFile.java @@ -212,21 +212,32 @@ public List read( } /** - * Scans projected manifest entries without materializing {@link PojoManifestEntry}s. - * - *

Every returned {@link ProjectedManifestEntry} has independent backing data and can be - * retained after the iterator advances or closes. The caller must close the iterator. - * - *

This method intentionally bypasses the manifest cache because cached entries are - * materialized with the complete manifest schema. + * Scans projected manifest entries without materializing {@link PojoManifestEntry}s. Returned + * entries have independent backing data. The caller must close the iterator. */ public CloseableIterator scan(String fileName, Projection projection) { + return scan(fileName, projection, null, null, null); + } + + /** + * Scans projected entries with manifest pruning while keeping only the current reader block in + * memory. + */ + public CloseableIterator scan( + String fileName, + Projection projection, + @Nullable PartitionPredicate partitionFilter, + @Nullable BucketFilter bucketFilter, + @Nullable ManifestSidecar.Selection selected) { try { CloseableIterator rows = createManifestIterator( fileIO, pathFactory.toPath(fileName), projection.projectedType(), + partitionFilter, + bucketFilter, + selected, null, null); return new CloseableIterator() { diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/AbstractFileStoreScan.java b/paimon-core/src/main/java/org/apache/paimon/operation/AbstractFileStoreScan.java index d5aaa35766d5..982735a5a3dd 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/AbstractFileStoreScan.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/AbstractFileStoreScan.java @@ -31,6 +31,7 @@ import org.apache.paimon.manifest.ManifestFileMeta; import org.apache.paimon.manifest.ManifestSidecar; import org.apache.paimon.manifest.PartitionEntry; +import org.apache.paimon.manifest.ProjectedManifestEntry; import org.apache.paimon.manifest.SimpleFileEntry; import org.apache.paimon.operation.metrics.ScanMetrics; import org.apache.paimon.operation.metrics.ScanStats; @@ -41,6 +42,7 @@ import org.apache.paimon.table.source.ScanMode; import org.apache.paimon.types.RowType; import org.apache.paimon.utils.BiFilter; +import org.apache.paimon.utils.CloseableIterator; import org.apache.paimon.utils.Filter; import org.apache.paimon.utils.ListUtils; import org.apache.paimon.utils.Pair; @@ -60,6 +62,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -435,6 +438,236 @@ public Iterator readFileIterator(List manifestF return readManifestEntries(manifestFileMetas, true); } + @Override + public boolean supportsStreamingPlan() { + return limit == null && !postFilterManifestEntriesEnabled(); + } + + @Override + public StreamingPlan streamingPlan() { + long started = System.nanoTime(); + if (!supportsStreamingPlan()) { + throw new UnsupportedOperationException( + "This scan requires post-processing the complete manifest entry list"); + } + ManifestsReader.Result manifestsResult = readManifests(); + if (manifestsResult.filteredManifests.stream() + .anyMatch(manifest -> manifest.numDeletedFiles() > 0)) { + throw new StreamingPlanFallbackException( + "Streaming file planning requires add-only manifest entries"); + } + Snapshot snapshot = manifestsResult.snapshot; + long allDataFiles = + manifestsResult.allManifests.stream() + .mapToLong(f -> f.numAddedFiles() - f.numDeletedFiles()) + .sum(); + CloseableIterator files = + streamAddedManifestEntries(manifestsResult.filteredManifests); + CloseableIterator measuredFiles = + reportStreamingScanOnCompletion( + files, + System.nanoTime() - started, + snapshot, + manifestsResult.filteredManifests.size(), + allDataFiles); + return new StreamingPlan() { + @Nullable + @Override + public Long watermark() { + return snapshot == null ? null : snapshot.watermark(); + } + + @Nullable + @Override + public Snapshot snapshot() { + return snapshot; + } + + @Override + public CloseableIterator files() { + return measuredFiles; + } + }; + } + + private CloseableIterator reportStreamingScanOnCompletion( + CloseableIterator files, + long preparationNanos, + @Nullable Snapshot snapshot, + int scannedManifests, + long allDataFiles) { + return new CloseableIterator() { + private long resultFiles; + private long scanNanos = preparationNanos; + private boolean reported; + + @Override + public boolean hasNext() { + long started = System.nanoTime(); + boolean hasNext; + try { + hasNext = files.hasNext(); + } finally { + scanNanos = Math.addExact(scanNanos, System.nanoTime() - started); + } + if (!hasNext) { + report(); + } + return hasNext; + } + + @Override + public ManifestEntry next() { + long started = System.nanoTime(); + ManifestEntry entry; + try { + entry = files.next(); + } finally { + scanNanos = Math.addExact(scanNanos, System.nanoTime() - started); + } + resultFiles = Math.addExact(resultFiles, 1); + return entry; + } + + private void report() { + if (reported) { + return; + } + reported = true; + long scanDuration = scanNanos / 1_000_000; + LOG.info( + "Streaming file store scan plan completed in {} ms. Files size : {}", + scanDuration, + resultFiles); + if (scanMetrics != null) { + scanMetrics.reportScan( + new ScanStats( + scanDuration, + snapshot == null ? 0 : snapshot.id(), + scannedManifests, + allDataFiles - resultFiles, + resultFiles)); + } + } + + @Override + public void close() throws Exception { + files.close(); + } + }; + } + + private CloseableIterator streamAddedManifestEntries( + List manifests) { + List addedManifests = + manifests.stream() + .filter(manifest -> manifest.numAddedFiles() > 0) + .collect(Collectors.toList()); + Iterator manifestIterator = addedManifests.iterator(); + Filter rowFilter = createEntryRowFilter(); + BucketFilter bucketFilter = createBucketFilter(); + PartitionPredicate partitionFilter = manifestsReader.partitionFilter(); + ManifestEntrySerializer serializer = new ManifestEntrySerializer(); + + return new CloseableIterator() { + private CloseableIterator entries = CloseableIterator.empty(); + private ManifestEntry next; + private boolean closed; + + @Override + public boolean hasNext() { + if (next == null && !closed) { + advance(); + } + return next != null; + } + + @Override + public ManifestEntry next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + ManifestEntry result = next; + next = null; + return result; + } + + private void advance() { + try { + while (next == null) { + while (entries.hasNext()) { + ProjectedManifestEntry projected = entries.next(); + try { + if (rowFilter.test(projected.fullRow()) + && (manifestEntryFilter == null + || manifestEntryFilter.test(projected)) + && filterByStats(projected)) { + ManifestEntry materialized = + serializer.fromRow(projected.fullRow()); + next = + dropStats + ? materialized.copyWithoutStats() + : materialized; + return; + } + } finally { + projected.clear(); + } + } + + closeEntries(); + if (!manifestIterator.hasNext()) { + closed = true; + return; + } + + ManifestFileMeta manifest = manifestIterator.next(); + ManifestFile manifestFile = manifestFileFactory.create(); + ManifestSidecar.Selection selected = + manifestFile.selectBlocks( + manifest, rowRangeIndex, partitionFilter, bucketFilter); + if (selected != null && selected.blocks().isEmpty()) { + continue; + } + entries = + manifestFile.scan( + manifest.fileName(), + ProjectedManifestEntry.fullProjection(), + partitionFilter, + bucketFilter, + selected); + } + } catch (RuntimeException | Error error) { + try { + close(); + } catch (Exception closeError) { + error.addSuppressed(closeError); + } + throw error; + } + } + + private void closeEntries() { + try { + entries.close(); + entries = CloseableIterator.empty(); + } catch (Exception error) { + throw new RuntimeException("Failed to close streaming manifest reader", error); + } + } + + @Override + public void close() throws Exception { + if (!closed) { + closed = true; + next = null; + entries.close(); + entries = CloseableIterator.empty(); + } + } + }; + } + public Iterator readManifestEntries( List manifests, boolean useSequential) { return scanMode == ScanMode.ALL diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreScan.java b/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreScan.java index 8f543ca7d39a..3f23954b42c7 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreScan.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreScan.java @@ -32,6 +32,7 @@ import org.apache.paimon.table.source.ScanMode; import org.apache.paimon.types.RowType; import org.apache.paimon.utils.BiFilter; +import org.apache.paimon.utils.CloseableIterator; import org.apache.paimon.utils.Filter; import org.apache.paimon.utils.Range; import org.apache.paimon.utils.RowRangeIndex; @@ -125,6 +126,25 @@ public interface FileStoreScan { Iterator readFileIterator(List manifestFileMetas); + /** Whether this scan can expose its effective files without first materializing them. */ + default boolean supportsStreamingPlan() { + return false; + } + + /** Produce snapshot metadata and an iterator over the effective files of the plan. */ + default StreamingPlan streamingPlan() { + throw new UnsupportedOperationException( + "Streaming file planning is not supported by " + getClass().getName()); + } + + /** Signals that a scan discovered a shape which requires the eager planning implementation. */ + final class StreamingPlanFallbackException extends UnsupportedOperationException { + + public StreamingPlanFallbackException(String message) { + super(message); + } + } + default List listPartitions() { return readPartitionEntries().stream() .map(PartitionEntry::partition) @@ -164,4 +184,16 @@ static Map>> groupByPartFiles( return groupBy; } } + + /** Snapshot metadata plus a single-pass iterator over effective manifest entries. */ + interface StreamingPlan { + + @Nullable + Long watermark(); + + @Nullable + Snapshot snapshot(); + + CloseableIterator files(); + } } diff --git a/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractBatchTableScan.java b/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractBatchTableScan.java index 0a19f5326ce9..43b700b89b22 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractBatchTableScan.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractBatchTableScan.java @@ -27,6 +27,7 @@ import org.apache.paimon.schema.SchemaManager; import org.apache.paimon.schema.TableSchema; import org.apache.paimon.table.BucketMode; +import org.apache.paimon.table.source.snapshot.ReadPlanStartingScanner; import org.apache.paimon.table.source.snapshot.SnapshotReader; import org.apache.paimon.table.source.snapshot.StartingScanner; import org.apache.paimon.table.source.snapshot.StartingScanner.ScannedResult; @@ -141,6 +142,36 @@ protected final TableScan.Plan planWithoutAuth() { return postProcessPlan(DataFilePlan.fromResult(result)); } + @Override + protected SnapshotReader.SplitPlan openSplitPlanWithoutAuth() { + if (!incrementalSplitPlanningEnabled() + || !snapshotReader.supportsFineGrainedSplitPlanning() + || pushDownLimit != null + || topN != null) { + return super.openSplitPlanWithoutAuth(); + } + if (startingScanner == null) { + startingScanner = createStartingScanner(false); + } + if (!(startingScanner instanceof ReadPlanStartingScanner)) { + return super.openSplitPlanWithoutAuth(); + } + if (!hasNext) { + throw new EndOfScanException(); + } + hasNext = false; + SnapshotReader.SplitPlan plan = + ((ReadPlanStartingScanner) startingScanner).openSplitPlan(snapshotReader); + if (plan.snapshotId() != null) { + maybeCreateReadProtectionTag(plan.snapshotId()); + } + return plan; + } + + protected boolean incrementalSplitPlanningEnabled() { + return false; + } + @Nullable protected Plan preProcessPlan() { return null; diff --git a/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataTableScan.java b/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataTableScan.java index 9cea4edfe477..440b7c7e1c47 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataTableScan.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataTableScan.java @@ -160,6 +160,30 @@ public final TableScan.Plan plan() { return plan; } + @Override + public final SnapshotReader.SplitPlan openSplitPlan() { + TableQueryAuthResult queryAuthResult = applyAuthRules(); + applyAuthReadType(queryAuthResult); + if (queryAuthResult != null) { + Plan original = planWithoutAuth(); + Long watermark = + original instanceof SnapshotReader.Plan + ? ((SnapshotReader.Plan) original).watermark() + : null; + Long snapshotId = + original instanceof SnapshotReader.Plan + ? ((SnapshotReader.Plan) original).snapshotId() + : null; + Plan converted = queryAuthResult.convertPlan(original); + return SnapshotReader.SplitPlan.fromTablePlan(converted, watermark, snapshotId); + } + return openSplitPlanWithoutAuth(); + } + + protected SnapshotReader.SplitPlan openSplitPlanWithoutAuth() { + return SnapshotReader.SplitPlan.fromTablePlan(planWithoutAuth()); + } + protected abstract TableScan.Plan planWithoutAuth(); private void applyAuthFilter(@Nullable Predicate authPredicate) { diff --git a/paimon-core/src/main/java/org/apache/paimon/table/source/AppendBatchTableScan.java b/paimon-core/src/main/java/org/apache/paimon/table/source/AppendBatchTableScan.java index 6570bb66980a..44dadfd76f5e 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/source/AppendBatchTableScan.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/source/AppendBatchTableScan.java @@ -34,4 +34,9 @@ public AppendBatchTableScan( TableQueryAuth queryAuth) { super(schema, schemaManager, options, snapshotReader, queryAuth); } + + @Override + protected boolean incrementalSplitPlanningEnabled() { + return true; + } } diff --git a/paimon-core/src/main/java/org/apache/paimon/table/source/InnerTableScan.java b/paimon-core/src/main/java/org/apache/paimon/table/source/InnerTableScan.java index 6c4b18ec9b76..db74cb68247e 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/source/InnerTableScan.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/source/InnerTableScan.java @@ -24,6 +24,7 @@ import org.apache.paimon.partition.PartitionPredicate; import org.apache.paimon.predicate.Predicate; import org.apache.paimon.predicate.TopN; +import org.apache.paimon.table.source.snapshot.SnapshotReader; import org.apache.paimon.types.RowType; import org.apache.paimon.utils.Filter; import org.apache.paimon.utils.Range; @@ -37,6 +38,11 @@ /** Inner {@link TableScan} contains filter push down. */ public interface InnerTableScan extends TableScan { + /** Open a single-pass plan, falling back to the materialized plan by default. */ + default SnapshotReader.SplitPlan openSplitPlan() { + return SnapshotReader.SplitPlan.fromTablePlan(plan()); + } + InnerTableScan withFilter(Predicate predicate); default InnerTableScan withReadType(@Nullable RowType readType) { diff --git a/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/ReadPlanStartingScanner.java b/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/ReadPlanStartingScanner.java index 56b7680eb74c..1df59840ee38 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/ReadPlanStartingScanner.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/ReadPlanStartingScanner.java @@ -45,6 +45,16 @@ public Result scan(SnapshotReader snapshotReader) { return StartingScanner.fromPlan(configured.read()); } + /** Configure the fixed starting snapshot and open its single-pass plan. */ + public SnapshotReader.SplitPlan openSplitPlan(SnapshotReader snapshotReader) { + SnapshotReader configured = configure(snapshotReader); + if (configured == null) { + return new SnapshotReader.SplitPlan( + null, null, false, org.apache.paimon.utils.CloseableIterator.empty()); + } + return configured.openSplitPlan(); + } + @Override public List scanPartitions(SnapshotReader snapshotReader) { SnapshotReader configured = configure(snapshotReader); diff --git a/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReader.java b/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReader.java index 68611f009116..0e3d72859f9d 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReader.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReader.java @@ -38,6 +38,7 @@ import org.apache.paimon.types.RowType; import org.apache.paimon.utils.BiFilter; import org.apache.paimon.utils.ChangelogManager; +import org.apache.paimon.utils.CloseableIterator; import org.apache.paimon.utils.FileStorePathFactory; import org.apache.paimon.utils.Filter; import org.apache.paimon.utils.Range; @@ -140,6 +141,23 @@ public interface SnapshotReader { /** Get splits plan from snapshot. */ Plan read(); + /** Whether this reader can expose fine-grained splits without materializing a complete plan. */ + default boolean supportsFineGrainedSplitPlanning() { + return false; + } + + /** + * Opens a single-pass split plan. + * + *

The default implementation adapts the fully materialized {@link Plan}. Implementations may + * instead return fine-grained splits, which preserve the files and rows of the logical plan but + * deliberately leave connector-specific task grouping to the caller. Callers must close the + * returned iterator and discard all previously consumed splits if iteration fails. + */ + default SplitPlan openSplitPlan() { + return SplitPlan.fromPlan(read()); + } + /** Get splits plan from file changes. */ Plan readChanges(); @@ -179,4 +197,67 @@ default List dataSplits() { return (List) splits(); } } + + /** Metadata and a closeable, single-use iterator for a split plan. */ + final class SplitPlan { + @Nullable private final Long watermark; + @Nullable private final Long snapshotId; + private final boolean fineGrained; + private final CloseableIterator splits; + + public SplitPlan( + @Nullable Long watermark, + @Nullable Long snapshotId, + boolean fineGrained, + CloseableIterator splits) { + this.watermark = watermark; + this.snapshotId = snapshotId; + this.fineGrained = fineGrained; + this.splits = splits; + } + + public static SplitPlan fromPlan(Plan plan) { + return new SplitPlan( + plan.watermark(), + plan.snapshotId(), + false, + CloseableIterator.adapterForIterator(plan.splits().iterator())); + } + + public static SplitPlan fromTablePlan(TableScan.Plan plan) { + if (plan instanceof Plan) { + return fromPlan((Plan) plan); + } + return fromTablePlan(plan, null, null); + } + + public static SplitPlan fromTablePlan( + TableScan.Plan plan, @Nullable Long watermark, @Nullable Long snapshotId) { + return new SplitPlan( + watermark, + snapshotId, + false, + CloseableIterator.adapterForIterator(plan.splits().iterator())); + } + + @Nullable + public Long watermark() { + return watermark; + } + + @Nullable + public Long snapshotId() { + return snapshotId; + } + + /** Whether the iterator intentionally leaves task grouping to the caller. */ + public boolean fineGrained() { + return fineGrained; + } + + /** Returns the single-use iterator. The caller must close it. */ + public CloseableIterator splits() { + return splits; + } + } } diff --git a/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReaderImpl.java b/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReaderImpl.java index 29f1ef029756..0e81b30c99b2 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReaderImpl.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/SnapshotReaderImpl.java @@ -43,6 +43,7 @@ import org.apache.paimon.predicate.Predicate; import org.apache.paimon.predicate.PredicateBuilder; import org.apache.paimon.schema.TableSchema; +import org.apache.paimon.table.source.AppendOnlySplitGenerator; import org.apache.paimon.table.source.DataSplit; import org.apache.paimon.table.source.DeletionFile; import org.apache.paimon.table.source.IncrementalSplit; @@ -53,6 +54,7 @@ import org.apache.paimon.types.RowType; import org.apache.paimon.utils.BiFilter; import org.apache.paimon.utils.ChangelogManager; +import org.apache.paimon.utils.CloseableIterator; import org.apache.paimon.utils.DVMetaCache; import org.apache.paimon.utils.FileStorePathFactory; import org.apache.paimon.utils.Filter; @@ -409,6 +411,68 @@ public Plan read() { plan.watermark(), snapshot == null ? null : snapshot.id(), snapshot, (List) splits); } + @Override + public boolean supportsFineGrainedSplitPlanning() { + return scanMode == ScanMode.ALL + && splitGenerator instanceof AppendOnlySplitGenerator + && !deletionVectors + && !options.scanPlanSortPartition() + && scan.supportsStreamingPlan(); + } + + @Override + public SplitPlan openSplitPlan() { + if (!supportsFineGrainedSplitPlanning()) { + return SnapshotReader.super.openSplitPlan(); + } + + FileStoreScan.StreamingPlan plan; + try { + plan = scan.streamingPlan(); + } catch (FileStoreScan.StreamingPlanFallbackException ignored) { + return SnapshotReader.super.openSplitPlan(); + } + @Nullable Snapshot snapshot = plan.snapshot(); + long snapshotId = snapshot == null ? FIRST_SNAPSHOT_ID - 1 : snapshot.id(); + CloseableIterator files = plan.files(); + CloseableIterator splits = + new CloseableIterator() { + @Override + public boolean hasNext() { + return files.hasNext(); + } + + @Override + public Split next() { + ManifestEntry entry = files.next(); + if (entry.kind() != FileKind.ADD) { + throw new IllegalStateException( + "Incremental full-snapshot planning produced a non-ADD entry"); + } + DataFileMeta file = entry.file(); + return DataSplit.builder() + .withSnapshot(snapshotId) + .withPartition(entry.partition()) + .withBucket(entry.bucket()) + .withTotalBuckets(entry.totalBuckets()) + .withDataFiles(Collections.singletonList(file)) + .rawConvertible(true) + .withBucketPath( + pathFactory + .bucketPath(entry.partition(), entry.bucket()) + .toString()) + .build(); + } + + @Override + public void close() throws Exception { + files.close(); + } + }; + return new SplitPlan( + plan.watermark(), snapshot == null ? null : snapshot.id(), true, splits); + } + private List generateSplits( @Nullable Snapshot snapshot, boolean isStreaming, diff --git a/paimon-core/src/test/java/org/apache/paimon/table/AppendOnlySimpleTableTest.java b/paimon-core/src/test/java/org/apache/paimon/table/AppendOnlySimpleTableTest.java index e6352b8d91fb..586a00e01201 100644 --- a/paimon-core/src/test/java/org/apache/paimon/table/AppendOnlySimpleTableTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/table/AppendOnlySimpleTableTest.java @@ -68,12 +68,14 @@ import org.apache.paimon.table.sink.StreamTableWrite; import org.apache.paimon.table.sink.TableWriteImpl; import org.apache.paimon.table.source.DataSplit; +import org.apache.paimon.table.source.InnerTableScan; import org.apache.paimon.table.source.ReadBuilder; import org.apache.paimon.table.source.ScanMode; import org.apache.paimon.table.source.Split; import org.apache.paimon.table.source.StreamTableScan; import org.apache.paimon.table.source.TableRead; import org.apache.paimon.table.source.TableScan; +import org.apache.paimon.tag.BatchReadTagCreator; import org.apache.paimon.types.DataField; import org.apache.paimon.types.DataTypes; import org.apache.paimon.types.RowType; @@ -499,6 +501,71 @@ public void testBatchReadWrite() throws Exception { "2|21|201|binary|varbinary|mapKey:mapVal|multiset")); } + @Test + public void testIncrementalSplitPlanningHasEquivalentFiles() throws Exception { + writeData(); + FileStoreTable table = createFileStoreTable(); + + List expected = table.newReadBuilder().newScan().plan().splits(); + List actual = new ArrayList<>(); + org.apache.paimon.table.source.snapshot.SnapshotReader.SplitPlan plan = + ((InnerTableScan) table.newReadBuilder().newScan()).openSplitPlan(); + try (CloseableIterator splits = plan.splits()) { + splits.forEachRemaining(actual::add); + } + + List expectedFiles = + expected.stream() + .map(DataSplit.class::cast) + .flatMap(split -> split.dataFiles().stream()) + .map(DataFileMeta::fileName) + .sorted() + .collect(Collectors.toList()); + List actualFiles = + actual.stream() + .map(DataSplit.class::cast) + .flatMap(split -> split.dataFiles().stream()) + .map(DataFileMeta::fileName) + .sorted() + .collect(Collectors.toList()); + + assertThat(actualFiles).isEqualTo(expectedFiles); + assertThat(plan.fineGrained()).isTrue(); + assertThat(actual) + .allSatisfy( + split -> { + DataSplit dataSplit = (DataSplit) split; + assertThat(dataSplit.dataFiles()).hasSize(1); + assertThat(dataSplit.rawConvertible()).isTrue(); + }); + assertThat(actual.stream().mapToLong(Split::rowCount).sum()) + .isEqualTo(expected.stream().mapToLong(Split::rowCount).sum()); + } + + @Test + public void testFineGrainedPlanCreatesReadProtectionBeforeIteration() throws Exception { + writeData(); + FileStoreTable table = + createFileStoreTable() + .copy( + Collections.singletonMap( + CoreOptions.SCAN_PLAN_AUTO_TAG_FOR_READ_TIME_RETAINED.key(), + "1 h")); + InnerTableScan scan = (InnerTableScan) table.newReadBuilder().newScan(); + + org.apache.paimon.table.source.snapshot.SnapshotReader.SplitPlan plan = + scan.openSplitPlan(); + String tagName = scan.readProtectionTagName(); + + assertThat(plan.fineGrained()).isTrue(); + assertThat(tagName).startsWith(BatchReadTagCreator.BATCH_READ_TAG_PREFIX); + assertThat(table.tagManager().tagExists(tagName)).isTrue(); + try (CloseableIterator splits = plan.splits()) { + assertThat(splits.hasNext()).isTrue(); + } + table.deleteTag(tagName); + } + @Test public void testReadWriteWithDataDirectory() throws Exception { Consumer optionsSetter = options -> options.set(DATA_FILE_PATH_DIRECTORY, "data"); diff --git a/paimon-core/src/test/java/org/apache/paimon/table/source/snapshot/SnapshotReaderTest.java b/paimon-core/src/test/java/org/apache/paimon/table/source/snapshot/SnapshotReaderTest.java index e0bfd5fd918e..28162fa87fd0 100644 --- a/paimon-core/src/test/java/org/apache/paimon/table/source/snapshot/SnapshotReaderTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/table/source/snapshot/SnapshotReaderTest.java @@ -27,6 +27,14 @@ import org.apache.paimon.fs.FileIOFinder; import org.apache.paimon.fs.Path; import org.apache.paimon.io.DataFileMeta; +import org.apache.paimon.manifest.ManifestFileMeta; +import org.apache.paimon.metrics.Gauge; +import org.apache.paimon.metrics.Histogram; +import org.apache.paimon.metrics.MetricGroup; +import org.apache.paimon.metrics.MetricRegistry; +import org.apache.paimon.metrics.TestMetricRegistry; +import org.apache.paimon.operation.FileStoreScan; +import org.apache.paimon.operation.metrics.ScanMetrics; import org.apache.paimon.options.Options; import org.apache.paimon.schema.FileSystemSchemaManager; import org.apache.paimon.schema.Schema; @@ -36,30 +44,38 @@ import org.apache.paimon.table.CatalogEnvironment; import org.apache.paimon.table.FileStoreTable; import org.apache.paimon.table.FileStoreTableFactory; +import org.apache.paimon.table.sink.BatchTableCommit; +import org.apache.paimon.table.sink.BatchTableWrite; +import org.apache.paimon.table.sink.BatchWriteBuilder; import org.apache.paimon.table.sink.StreamTableCommit; import org.apache.paimon.table.sink.StreamTableWrite; import org.apache.paimon.table.source.DataSplit; import org.apache.paimon.table.source.IndexFile; import org.apache.paimon.table.source.RawFile; +import org.apache.paimon.table.source.Split; import org.apache.paimon.types.DataType; import org.apache.paimon.types.DataTypes; import org.apache.paimon.types.RowType; +import org.apache.paimon.utils.CloseableIterator; import org.apache.paimon.utils.TraceableFileIO; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +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.UUID; +import java.util.stream.Collectors; import static org.apache.paimon.CoreOptions.BUCKET_KEY; import static org.apache.paimon.io.DataFilePathFactory.INDEX_PATH_SUFFIX; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Tests for {@link SnapshotReader}. */ public class SnapshotReaderTest { @@ -261,6 +277,200 @@ public void testGetAppendOnlyRawFiles() throws Exception { commit.close(); } + @Test + public void testIncrementalSplitPlanningFallsBackBeforeDeletedManifests() throws Exception { + RowType rowType = + RowType.of( + new DataType[] {DataTypes.INT(), DataTypes.BIGINT()}, + new String[] {"k", "v"}); + FileStoreTable table = + createFileStoreTable(rowType, Collections.emptyList(), Collections.emptyList()); + + String commitUser = UUID.randomUUID().toString(); + try (StreamTableWrite write = table.newWrite(commitUser); + StreamTableCommit commit = table.newCommit(commitUser)) { + write.write(GenericRow.of(1, 10L)); + commit.commit(1, write.prepareCommit(false, 1)); + write.write(GenericRow.of(2, 20L)); + commit.commit(2, write.prepareCommit(false, 2)); + } + + BatchWriteBuilder overwrite = table.newBatchWriteBuilder().withOverwrite(); + try (BatchTableWrite write = overwrite.newWrite(); + BatchTableCommit commit = overwrite.newCommit()) { + write.write(GenericRow.of(3, 30L)); + write.write(GenericRow.of(4, 40L)); + commit.commit(write.prepareCommit()); + } + + List manifests = + table.store() + .manifestListFactory() + .create() + .readDataManifests( + table.latestSnapshot() + .orElseThrow( + () -> + new IllegalStateException( + "Expected a latest snapshot"))); + assertThat(manifests).anyMatch(manifest -> manifest.numDeletedFiles() > 0); + assertThatThrownBy(() -> table.store().newScan().streamingPlan()) + .isInstanceOf(FileStoreScan.StreamingPlanFallbackException.class); + + SnapshotReader reader = table.newSnapshotReader(); + assertThat(reader.supportsFineGrainedSplitPlanning()).isTrue(); + SnapshotReader.SplitPlan plan = reader.openSplitPlan(); + List emitted = readSplits(plan); + List eager = table.newSnapshotReader().read().splits(); + + assertThat(fileNames(emitted)).containsExactlyElementsOf(fileNames(eager)); + assertThat(plan.fineGrained()).isFalse(); + assertThat(plan.snapshotId()).isEqualTo(table.latestSnapshot().get().id()); + assertThat(emitted.stream().mapToLong(Split::rowCount).sum()) + .isEqualTo(eager.stream().mapToLong(Split::rowCount).sum()); + } + + @Test + public void testIncrementalSplitPlanningStreamsAddOnlyManifests() throws Exception { + RowType rowType = + RowType.of( + new DataType[] {DataTypes.INT(), DataTypes.BIGINT()}, + new String[] {"k", "v"}); + FileStoreTable table = + createFileStoreTable(rowType, Collections.emptyList(), Collections.emptyList()); + + String commitUser = UUID.randomUUID().toString(); + try (StreamTableWrite write = table.newWrite(commitUser); + StreamTableCommit commit = table.newCommit(commitUser)) { + for (int identifier = 0; identifier < 4; identifier++) { + write.write(GenericRow.of(identifier, identifier * 10L)); + commit.commit(identifier + 1L, write.prepareCommit(false, identifier + 1L)); + } + } + + SnapshotReader reader = table.newSnapshotReader(); + assertThat(reader.supportsFineGrainedSplitPlanning()).isTrue(); + SnapshotReader.SplitPlan plan = reader.openSplitPlan(); + List streamed = readSplits(plan); + List eager = table.newSnapshotReader().read().splits(); + + assertThat(fileNames(streamed)).containsExactlyElementsOf(fileNames(eager)); + assertThat(plan.fineGrained()).isTrue(); + assertThat(plan.snapshotId()).isEqualTo(table.latestSnapshot().get().id()); + assertThat(streamed) + .allSatisfy( + split -> { + DataSplit dataSplit = (DataSplit) split; + assertThat(dataSplit.dataFiles()).hasSize(1); + assertThat(dataSplit.rawConvertible()).isTrue(); + }); + assertThat(streamed.stream().mapToLong(Split::rowCount).sum()) + .isEqualTo(eager.stream().mapToLong(Split::rowCount).sum()); + } + + @Test + public void testIncrementalSplitPlanningReportsCompletedScanMetrics() throws Exception { + RowType rowType = + RowType.of( + new DataType[] {DataTypes.INT(), DataTypes.BIGINT()}, + new String[] {"k", "v"}); + FileStoreTable table = + createFileStoreTable(rowType, Collections.emptyList(), Collections.emptyList()); + + String commitUser = UUID.randomUUID().toString(); + try (StreamTableWrite write = table.newWrite(commitUser); + StreamTableCommit commit = table.newCommit(commitUser)) { + for (int identifier = 0; identifier < 4; identifier++) { + write.write(GenericRow.of(identifier, identifier * 10L)); + commit.commit(identifier + 1L, write.prepareCommit(false, identifier + 1L)); + } + } + + CapturingMetricRegistry registry = new CapturingMetricRegistry(); + SnapshotReader reader = table.newSnapshotReader().withMetricRegistry(registry); + SnapshotReader.SplitPlan plan = reader.openSplitPlan(); + List streamed = new ArrayList<>(); + try (CloseableIterator iterator = plan.splits()) { + assertThat(iterator.hasNext()).isTrue(); + streamed.add(iterator.next()); + // Time spent by the caller between iterator operations is not scan planning time. + Thread.sleep(1500); + iterator.forEachRemaining(streamed::add); + } + + Map metrics = registry.group.getMetrics(); + Gauge snapshotId = (Gauge) metrics.get(ScanMetrics.LAST_SCANNED_SNAPSHOT_ID); + Gauge scannedManifests = + (Gauge) metrics.get(ScanMetrics.LAST_SCANNED_MANIFESTS); + Gauge resultedFiles = + (Gauge) metrics.get(ScanMetrics.LAST_SCAN_RESULTED_TABLE_FILES); + Histogram duration = (Histogram) metrics.get(ScanMetrics.SCAN_DURATION); + + assertThat(snapshotId.getValue()).isEqualTo(table.latestSnapshot().get().id()); + assertThat(scannedManifests.getValue()).isPositive(); + assertThat(resultedFiles.getValue()).isEqualTo(fileNames(streamed).size()); + assertThat(duration.getCount()).isOne(); + assertThat(duration.getStatistics().getMax()).isLessThan(1000); + } + + @Test + public void testFineGrainedPlanningFallsBackForLimit() throws Exception { + RowType rowType = + RowType.of( + new DataType[] {DataTypes.INT(), DataTypes.BIGINT()}, + new String[] {"k", "v"}); + FileStoreTable table = + createFileStoreTable(rowType, Collections.emptyList(), Collections.emptyList()); + + String commitUser = UUID.randomUUID().toString(); + try (StreamTableWrite write = table.newWrite(commitUser); + StreamTableCommit commit = table.newCommit(commitUser)) { + for (int identifier = 0; identifier < 4; identifier++) { + write.write(GenericRow.of(identifier, identifier * 10L)); + commit.commit(identifier + 1L, write.prepareCommit(false, identifier + 1L)); + } + } + + SnapshotReader reader = table.newSnapshotReader().withLimit(1); + assertThat(reader.supportsFineGrainedSplitPlanning()).isFalse(); + SnapshotReader.SplitPlan plan = reader.openSplitPlan(); + List actual = readSplits(plan); + List expected = table.newSnapshotReader().withLimit(1).read().splits(); + + assertThat(plan.fineGrained()).isFalse(); + assertThat(fileNames(actual)).containsExactlyElementsOf(fileNames(expected)); + assertThat(actual.stream().mapToLong(Split::rowCount).sum()) + .isEqualTo(expected.stream().mapToLong(Split::rowCount).sum()); + } + + private static List readSplits(SnapshotReader.SplitPlan plan) throws Exception { + List splits = new ArrayList<>(); + try (CloseableIterator iterator = plan.splits()) { + iterator.forEachRemaining(splits::add); + } + return splits; + } + + private static List fileNames(List splits) { + return splits.stream() + .map(DataSplit.class::cast) + .flatMap(split -> split.dataFiles().stream()) + .map(DataFileMeta::fileName) + .sorted() + .collect(Collectors.toList()); + } + + private static class CapturingMetricRegistry implements MetricRegistry { + + private MetricGroup group; + + @Override + public MetricGroup createMetricGroup(String groupName, Map variables) { + group = new TestMetricRegistry().createMetricGroup(groupName, variables); + return group; + } + } + @Test public void testGetAppendOnlyIndexFiles() throws Exception { RowType rowType =