diff --git a/docs/docs/multimodal-table/data-evolution.mdx b/docs/docs/multimodal-table/data-evolution.mdx index e9ba024f5ab5..c0eb8ed4037b 100644 --- a/docs/docs/multimodal-table/data-evolution.mdx +++ b/docs/docs/multimodal-table/data-evolution.mdx @@ -501,6 +501,106 @@ Persisted row-ID references must be coordinated with this maintenance. See [Data Evolution Maintenance](./data-evolution-maintenance) for commands, large-file splitting, limitations, and the row-ID lifetime table. +## Spark File Metadata Memory + +Tables with many files can require substantial heap for the metadata returned +by scans and write tasks, and processed during commit. Select a metadata mode +manually for Spark Data Evolution operations: + +```sql +ALTER TABLE target_table SET TBLPROPERTIES ( + 'data-evolution.metadata-memory-optimization.mode' = 'lightweight' +); +``` + +The mode defaults to `off` and takes effect only for Data Evolution tables: + +| Mode | Behavior | +| --- | --- | +| `off` | Uses the ordinary metadata path. | +| `lightweight` | Reduces unnecessary metadata copies, decoded objects and their lifetime. | +| `streaming` | Also plans complete row-ID dependency groups incrementally and replays file metadata from Driver-local disk. | + +For scans that request discarded statistics, `lightweight` mode releases value +statistics before collecting file metadata when no pushed data predicate needs +them. Filtered scans retain statistics until row-ID groups have been evaluated. +In `streaming` mode, statistics remain in the external sort and dependency-group +filtering input. Unneeded statistics are discarded before selected file metadata +is encoded into replay files. +Explicitly retained statistics, including supported statistics-based Top-N +planning, follow the original retention policy. +Scans also share repeated column-name strings from the current schema while +keeping each file's column list independent. Historical names absent from the +current schema retain their original representation. + +For writes, it keeps commit messages encoded until needed, avoids some eager +copies of expanded file metadata, and completes MERGE preparation and requests +cache cleanup before entering commit. + +In `streaming` mode, metadata is filtered in complete Data Evolution dependency +groups before splits are produced. Completed file lists are encoded into two +local replay files per store. MERGE preparation keeps numeric row-ID summaries +and re-encodes pruned lists, preserving file order and aligned deletion vectors. +Partial-write Tasks consume contiguous row-ID ranges as Spark requests results. +Each completed range produces its original commit-message payload directly, +without retaining all decoded messages or writing a Task-local message replay file. +The original Snapshot, authorization, filtering and read-protection rules still +apply. This path supports batch ALL planning with one physical snapshot reader. +Spark fallback/chain, audit-log and incremental reads, including `latest-delta`, +keep their existing planner and its metadata memory boundaries. Internal batch +scan modes also keep the existing planner. + +For LIMIT reads without data predicates, RowID filters or deletion vectors, +replay keeps only the required complete dependency groups. Candidate metadata +is still scanned and externally sorted before selecting that prefix; the +largest-group and sorting memory boundaries still apply. + +Streaming scan planning requires at least three sort-buffer pages. Smaller +buffers remain valid and use ordinary scan planning with its original metadata +memory boundary. + +Streaming commit conflict checking requires at least six sort-buffer pages for +its two sorters. Smaller buffers remain valid and use ordinary conflict checking, +which retains its original metadata memory boundary instead of increasing the +configured buffer budget. + +Tasks receive the normal serialized metadata, so Executors do not need access +to the Driver's replay-file paths. MERGE closes its preparation stores after +its internal jobs finish. Ordinary query plans keep replay files available +while their splits remain reachable; backup cleanup has no timing guarantee. +Partial-write resources are closed when their output is consumed or the Task +completes, including failed Tasks. Input processing can overlap Spark's growing +Task-result buffer; that buffer and the complete encoded results collected by +the Driver remain memory boundaries. + +`data-evolution.metadata-memory-optimization.max-disk-size` limits encoded +data and offset-index bytes per replay store, defaulting to `1 gb`. It does not +include external-sort spill, filesystem allocation overhead or other stores. +Multiple planning stores can coexist. Repeated decoding, sorting and disk I/O add +work; compare complete SQL time and resource use on a representative workload. + +These modes do not make the entire Spark execution constant-memory. Complete +dependency groups, final task arrays, row-ID summaries, deletion/conflict state, +all returned message bytes and the largest individual message still require +heap. Multi-partition commit grouping +may materialize file metadata. Commit extensions that need stable, mutable +messages retain the materialized compatibility path. + +Streaming conflict checks retain compact row-ID summaries and use external +sorting for file identity reconciliation. These summaries still grow with the +number of files. Potential conflicts are replayed through the original checker +to preserve diagnostics, retaining its original memory limit. Compatibility +paths, including commits with deletion vectors or callbacks, also retain the +original conflict checker. + +To use streaming mode, set the mode to `streaming`. To disable metadata optimization: + +```sql +ALTER TABLE target_table SET TBLPROPERTIES ( + 'data-evolution.metadata-memory-optimization.mode' = 'off' +); +``` + ## File Sizing and Metadata Compatibility diff --git a/docs/generated/core_configuration.html b/docs/generated/core_configuration.html index 4bbc4e082cc2..a6449b897445 100644 --- a/docs/generated/core_configuration.html +++ b/docs/generated/core_configuration.html @@ -410,12 +410,6 @@ MemorySize When incremental size is bigger than this threshold, force a full compaction. - -
continuous-compaction.initial-scan-mode
- earliest -

Enum

- Initial snapshot mode for dedicated streaming compaction. When set to 'earliest' (the default), compaction starts from the earliest available snapshot if no COMPACT snapshot exists; when a COMPACT snapshot exists, compaction always resumes from the snapshot after it. When set to 'latest', the latest snapshot is read in ALL mode as the initial baseline and subsequent scans start from the next snapshot. The 'latest' mode skips historical snapshot changes and should only be used when historical changelog replay is not required.

Possible values: -
compaction.max-size-amplification-percent
200 @@ -506,6 +500,12 @@

Enum

Specify the consumer consistency mode for table.

Possible values: + +
continuous-compaction.initial-scan-mode
+ earliest +

Enum

+ Initial snapshot mode for dedicated streaming compaction. When set to 'earliest' (the default), compaction starts from the earliest available snapshot if no COMPACT snapshot exists; when a COMPACT snapshot exists, compaction always resumes from the snapshot after it. When set to 'latest', the latest snapshot is read in ALL mode as the initial baseline and subsequent scans start from the next snapshot. The 'latest' mode skips historical snapshot changes and should only be used when historical changelog replay is not required.

Possible values: +
continuous.discovery-interval
10 s @@ -590,6 +590,18 @@ Boolean Whether to push filters down into a row-id range whose columns are merged from several data files. The rows which may match are computed from the file statistics and page indexes of the files holding the latest values of the filtered columns, then every file of the range reads only these rows. Only Parquet files are supported. + +
data-evolution.metadata-memory-optimization.max-disk-size
+ 1 gb + MemorySize + Maximum encoded data and offset-index bytes per metadata replay store in streaming mode. Excludes external-sort spill files, filesystem allocation overhead and other concurrent plans. + + +
data-evolution.metadata-memory-optimization.mode
+ off +

Enum

+ Metadata memory mode for Spark data evolution operations: off, lightweight or streaming. Enable manually for tables with many files. Repeated decoding, sorting and disk I/O may increase execution time.

Possible values: +
data-evolution.nested-field.enabled
false diff --git a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java index 06d94253fcd3..21aba3a6284f 100644 --- a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java +++ b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java @@ -2684,6 +2684,26 @@ public String toString() { .defaultValue(false) .withDescription("Whether enable data evolution for row tracking table."); + public static final ConfigOption + DATA_EVOLUTION_METADATA_MEMORY_OPTIMIZATION_MODE = + key("data-evolution.metadata-memory-optimization.mode") + .enumType(DataEvolutionMetadataMemoryMode.class) + .defaultValue(DataEvolutionMetadataMemoryMode.OFF) + .withDescription( + "Metadata memory mode for Spark data evolution operations: off, " + + "lightweight or streaming. Enable manually for tables " + + "with many files. Repeated decoding, sorting and disk I/O " + + "may increase execution time."); + + public static final ConfigOption DATA_EVOLUTION_METADATA_MEMORY_MAX_DISK_SIZE = + key("data-evolution.metadata-memory-optimization.max-disk-size") + .memoryType() + .defaultValue(MemorySize.ofMebiBytes(1024)) + .withDescription( + "Maximum encoded data and offset-index bytes per metadata replay store " + + "in streaming mode. Excludes external-sort spill files, " + + "filesystem allocation overhead and other concurrent plans."); + public static final ConfigOption DATA_EVOLUTION_WRITE_COLS_OPTIMIZATION_ENABLED = key("data-evolution.write-cols-optimization.enabled") .booleanType() @@ -4800,6 +4820,31 @@ public boolean dataEvolutionEnabled() { return options.get(DATA_EVOLUTION_ENABLED); } + public boolean dataEvolutionMetadataMemoryOptimizationEnabled() { + return dataEvolutionMetadataMemoryMode() != DataEvolutionMetadataMemoryMode.OFF; + } + + public DataEvolutionMetadataMemoryMode dataEvolutionMetadataMemoryMode() { + if (!dataEvolutionEnabled()) { + return DataEvolutionMetadataMemoryMode.OFF; + } + return options.get(DATA_EVOLUTION_METADATA_MEMORY_OPTIMIZATION_MODE); + } + + public boolean dataEvolutionMetadataStreamingEnabled() { + return dataEvolutionMetadataMemoryMode() == DataEvolutionMetadataMemoryMode.STREAMING; + } + + public long dataEvolutionMetadataMaxDiskSize() { + long bytes = options.get(DATA_EVOLUTION_METADATA_MEMORY_MAX_DISK_SIZE).getBytes(); + checkArgument( + bytes >= Long.BYTES, + "%s must be at least %s bytes.", + DATA_EVOLUTION_METADATA_MEMORY_MAX_DISK_SIZE.key(), + Long.BYTES); + return bytes; + } + public boolean dataEvolutionWriteColsOptimizationEnabled() { return options.get(DATA_EVOLUTION_WRITE_COLS_OPTIMIZATION_ENABLED); } @@ -5631,6 +5676,31 @@ public InlineElement getDescription() { } } + /** Manually selected metadata retention strategy for Spark data evolution operations. */ + public enum DataEvolutionMetadataMemoryMode implements DescribedEnum { + OFF("off", "Use the ordinary metadata path."), + LIGHTWEIGHT("lightweight", "Reduce metadata copies and retained decoded objects."), + STREAMING("streaming", "Incrementally produce and replay file metadata."); + + private final String value; + private final String description; + + DataEvolutionMetadataMemoryMode(String value, String description) { + this.value = value; + this.description = description; + } + + @Override + public String toString() { + return value; + } + + @Override + public InlineElement getDescription() { + return text(description); + } + } + /** Inner stream scan mode for some internal requirements. */ public enum StreamScanMode implements DescribedEnum { NONE("none", "No requirement."), diff --git a/paimon-core/src/main/java/org/apache/paimon/io/DataFileMeta.java b/paimon-core/src/main/java/org/apache/paimon/io/DataFileMeta.java index 48aaf0780931..bd4e8adf73a7 100644 --- a/paimon-core/src/main/java/org/apache/paimon/io/DataFileMeta.java +++ b/paimon-core/src/main/java/org/apache/paimon/io/DataFileMeta.java @@ -389,6 +389,32 @@ default Range nonNullRowIdRange() { DataFileMeta assignFileSource(FileSource fileSource); + /** Returns a standard metadata value copy with only the physical column names replaced. */ + default DataFileMeta withWriteCols(@Nullable List writeCols) { + return create( + fileName(), + fileSize(), + rowCount(), + minKey(), + maxKey(), + keyStats(), + valueStats(), + minSequenceNumber(), + maxSequenceNumber(), + schemaId(), + level(), + extraFiles(), + creationTime(), + deleteRowCount().orElse(null), + embeddedIndex(), + fileSource().orElse(null), + valueStatsCols(), + externalPath().orElse(null), + firstRowId(), + writeCols, + writeColsSequences()); + } + DataFileMeta withWriteColsSequences(long[] writeColsSequences); DataFileMeta assignFirstRowId(long firstRowId); diff --git a/paimon-core/src/main/java/org/apache/paimon/io/PojoDataFileMeta.java b/paimon-core/src/main/java/org/apache/paimon/io/PojoDataFileMeta.java index 4632b8332d06..a9ea2f8f5a64 100644 --- a/paimon-core/src/main/java/org/apache/paimon/io/PojoDataFileMeta.java +++ b/paimon-core/src/main/java/org/apache/paimon/io/PojoDataFileMeta.java @@ -355,6 +355,32 @@ public PojoDataFileMeta assignSequenceNumber(long minSequenceNumber, long maxSeq writeColsSequences); } + @Override + public PojoDataFileMeta withWriteCols(@Nullable List writeCols) { + return new PojoDataFileMeta( + fileName, + fileSize, + rowCount, + minKey, + maxKey, + keyStats, + valueStats, + minSequenceNumber, + maxSequenceNumber, + schemaId, + level, + extraFiles, + creationTime, + deleteRowCount, + embeddedIndex, + fileSource, + valueStatsCols, + externalPath, + firstRowId, + writeCols, + writeColsSequences); + } + @Override public PojoDataFileMeta withWriteColsSequences(long[] writeColsSequences) { return new PojoDataFileMeta( diff --git a/paimon-core/src/main/java/org/apache/paimon/io/ProjectedDataFileMeta.java b/paimon-core/src/main/java/org/apache/paimon/io/ProjectedDataFileMeta.java index 00451ed1be77..0b4fed9b2f32 100644 --- a/paimon-core/src/main/java/org/apache/paimon/io/ProjectedDataFileMeta.java +++ b/paimon-core/src/main/java/org/apache/paimon/io/ProjectedDataFileMeta.java @@ -312,6 +312,11 @@ public DataFileMeta assignFileSource(FileSource fileSource) { throw unsupportedOperation("assignFileSource(FileSource)"); } + @Override + public DataFileMeta withWriteCols(@Nullable List writeCols) { + throw unsupportedOperation("withWriteCols(List)"); + } + @Override public DataFileMeta withWriteColsSequences(long[] writeColsSequences) { throw unsupportedOperation("withWriteColsSequences(long[])"); 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..b6afc0bffc3b 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 @@ -46,6 +46,7 @@ import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; @@ -221,15 +222,46 @@ public List read( * materialized with the complete manifest schema. */ public CloseableIterator scan(String fileName, Projection projection) { + return scan(fileName, projection, null, null, null); + } + + /** Streams selected blocks while retaining the ordinary partition and bucket pushdown. */ + public CloseableIterator scan( + ManifestFileMeta manifest, + Projection projection, + @Nullable PartitionPredicate partitionFilter, + @Nullable BucketFilter bucketFilter, + @Nullable ManifestSidecar.Selection selected) { + return scan(manifest.fileName(), projection, partitionFilter, bucketFilter, selected); + } + + private CloseableIterator scan( + String fileName, + Projection projection, + @Nullable PartitionPredicate partitionFilter, + @Nullable BucketFilter bucketFilter, + @Nullable ManifestSidecar.Selection selected) { + if (selected != null && selected.blocks().isEmpty()) { + return CloseableIterator.adapterForIterator(Collections.emptyIterator()); + } + CacheMetrics metrics = cacheMetrics; + ManifestSidecar.CacheStatus cacheStatus = + selected != null && cache != null && metrics != null + ? new ManifestSidecar.CacheStatus() + : null; try { CloseableIterator rows = createManifestIterator( fileIO, pathFactory.toPath(fileName), projection.projectedType(), - null, - null); + partitionFilter, + bucketFilter, + selected, + cache == null ? null : cache.segmentsCache(), + cacheStatus); return new CloseableIterator() { + private boolean closed; @Override public boolean hasNext() { @@ -243,7 +275,20 @@ public ProjectedManifestEntry next() { @Override public void close() throws Exception { - rows.close(); + if (!closed) { + closed = true; + try { + rows.close(); + } finally { + if (cacheStatus != null) { + if (cacheStatus.hit()) { + metrics.increaseHitObject(); + } else { + metrics.increaseMissedObject(); + } + } + } + } } }; } catch (IOException e) { 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..0e061b62a7ed 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 @@ -23,14 +23,17 @@ import org.apache.paimon.data.InternalRow; import org.apache.paimon.manifest.BucketEntry; import org.apache.paimon.manifest.BucketFilter; +import org.apache.paimon.manifest.CompactFileIdentifierSet; import org.apache.paimon.manifest.FileEntry; import org.apache.paimon.manifest.FileEntry.Identifier; +import org.apache.paimon.manifest.FileKind; import org.apache.paimon.manifest.ManifestEntry; import org.apache.paimon.manifest.ManifestEntrySerializer; import org.apache.paimon.manifest.ManifestFile; 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,12 +44,14 @@ 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; import org.apache.paimon.utils.Range; import org.apache.paimon.utils.RowRangeIndex; import org.apache.paimon.utils.SnapshotManager; +import org.apache.paimon.utils.ThrowingConsumer; import org.apache.paimon.utils.TriFilter; import org.slf4j.Logger; @@ -313,24 +318,7 @@ public Plan plan() { List result = files; - long scanDuration = (System.nanoTime() - started) / 1_000_000; - LOG.info( - "File store scan plan completed in {} ms. Files size : {}", - scanDuration, - result.size()); - if (scanMetrics != null) { - long allDataFiles = - manifestsResult.allManifests.stream() - .mapToLong(f -> f.numAddedFiles() - f.numDeletedFiles()) - .sum(); - scanMetrics.reportScan( - new ScanStats( - scanDuration, - snapshot == null ? 0 : snapshot.id(), - manifests.size(), - allDataFiles - result.size(), - result.size())); - } + reportScan(manifestsResult, started, result.size()); return new Plan() { @Nullable @@ -352,6 +340,28 @@ public List files() { }; } + protected final void reportScan( + ManifestsReader.Result manifestsResult, long started, long resultedFiles) { + long scanDuration = (System.nanoTime() - started) / 1_000_000; + LOG.info( + "File store scan plan completed in {} ms. Files size : {}", + scanDuration, + resultedFiles); + if (scanMetrics != null) { + long allDataFiles = + manifestsResult.allManifests.stream() + .mapToLong(f -> f.numAddedFiles() - f.numDeletedFiles()) + .sum(); + scanMetrics.reportScan( + new ScanStats( + scanDuration, + manifestsResult.snapshot == null ? 0 : manifestsResult.snapshot.id(), + manifestsResult.filteredManifests.size(), + allDataFiles - resultedFiles, + resultedFiles)); + } + } + @Override public List readSimpleEntries() { List manifests = readManifests().filteredManifests; @@ -366,6 +376,47 @@ public List readSimpleEntries() { return result; } + @Override + public void forEachSimpleEntry(ThrowingConsumer consumer) + throws Exception { + // Resolve manifests once so DELETE collection and ADD production use the same snapshot. + List manifests = readManifests().filteredManifests; + if (scanMode != ScanMode.ALL) { + for (ManifestFileMeta manifest : manifests) { + forEachManifestEntry( + manifest, + null, + null, + entry -> consumer.accept(SimpleFileEntry.from(entry))); + } + return; + } + + // Only DELETE identities survive this pass. They still grow with the number of deleted + // files, but neither a per-manifest result list nor the complete ADD metadata is retained. + CompactFileIdentifierSet deleted = new CompactFileIdentifierSet(); + try { + for (ManifestFileMeta manifest : manifests) { + if (manifest.numDeletedFiles() > 0) { + forEachManifestEntry(manifest, FileKind.DELETE, null, deleted::add); + } + } + for (ManifestFileMeta manifest : manifests) { + if (manifest.numAddedFiles() > 0) { + forEachManifestEntry( + manifest, + FileKind.ADD, + entry -> !deleted.contains((ProjectedManifestEntry) entry), + // SimpleFileEntry carries no statistics or write-column names, so the + // ordinary drop-stats/name-sharing conversions have nothing to retain. + entry -> consumer.accept(SimpleFileEntry.from(entry))); + } + } + } finally { + deleted.release(); + } + } + @Override public List readPartitionEntries() { List manifests = readManifests().filteredManifests; @@ -489,7 +540,7 @@ private Iterator readAndNoMergeFileEntries( } } - private ManifestsReader.Result readManifests() { + protected final ManifestsReader.Result readManifests() { return manifestsReader.read(specifiedSnapshot, scanMode); } @@ -536,8 +587,7 @@ private List readManifest( return Collections.emptyList(); } Filter entryRowFilter = createEntryRowFilter(); - Function finalConverter = - dropStats ? e -> converter.apply(dropStats(e)) : converter; + Function finalConverter = createManifestEntryConverter(converter); List entries = manifestFile @@ -560,6 +610,62 @@ && filterByStats(entry), return entries; } + protected Function createManifestEntryConverter( + Function converter) { + return dropStats ? e -> converter.apply(dropStats(e)) : converter; + } + + /** Applies the ordinary scan filters before consuming each independent binary entry. */ + protected final void forEachManifestEntry( + ManifestFileMeta manifest, + @Nullable FileKind kind, + @Nullable Filter beforeEntryFilter, + ThrowingConsumer consumer) + throws Exception { + ManifestFile file = + manifestFileFactory + .create() + .withCacheMetrics( + scanMetrics == null ? null : scanMetrics.getCacheMetrics()); + BucketFilter buckets = createBucketFilter(); + PartitionPredicate partitions = manifestsReader.partitionFilter(); + ManifestSidecar.Selection selected = + file.selectBlocks(manifest, rowRangeIndex, partitions, buckets); + Filter rowFilter = createEntryRowFilter(); + ManifestEntrySerializer filterSerializer = + manifestEntryFilter == null ? null : new ManifestEntrySerializer(); + try (CloseableIterator entries = + file.scan( + manifest, + ProjectedManifestEntry.fullProjection(), + partitions, + buckets, + selected)) { + while (entries.hasNext()) { + ProjectedManifestEntry entry = entries.next(); + if (!rowFilter.test(entry.fullRow()) + || (kind != null && entry.kind() != kind) + || (beforeEntryFilter != null && !beforeEntryFilter.test(entry))) { + continue; + } + // Custom filters retain the ordinary entry API, including copy operations. + ManifestEntry filteredEntry = + filterSerializer == null + ? entry + : filterSerializer.fromRow(entry.fullRow()); + if ((manifestEntryFilter == null || manifestEntryFilter.test(filteredEntry)) + && filterByStats(filteredEntry)) { + consumer.accept( + filterSerializer == null + ? entry + : ProjectedManifestEntry.fullProjection() + .createEntry() + .replace(filterSerializer.toRow(filteredEntry))); + } + } + } + } + protected ManifestEntry dropStats(ManifestEntry entry) { return entry.copyWithoutStats(); } diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/DataEvolutionFileStoreScan.java b/paimon-core/src/main/java/org/apache/paimon/operation/DataEvolutionFileStoreScan.java index 8bc55a0e3dbb..b936206faa30 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/DataEvolutionFileStoreScan.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/DataEvolutionFileStoreScan.java @@ -18,14 +18,21 @@ package org.apache.paimon.operation; +import org.apache.paimon.CoreOptions; +import org.apache.paimon.Snapshot; import org.apache.paimon.annotation.VisibleForTesting; import org.apache.paimon.data.BinaryArray; import org.apache.paimon.data.InternalArray; import org.apache.paimon.data.InternalRow; +import org.apache.paimon.disk.IOManager; import org.apache.paimon.io.DataFileMeta; +import org.apache.paimon.manifest.CompactFileIdentifierSet; +import org.apache.paimon.manifest.FileEntry.ReusableIdentifier; +import org.apache.paimon.manifest.FileKind; import org.apache.paimon.manifest.ManifestEntry; import org.apache.paimon.manifest.ManifestFile; import org.apache.paimon.manifest.ManifestFileMeta; +import org.apache.paimon.manifest.ProjectedManifestEntry; import org.apache.paimon.predicate.Predicate; import org.apache.paimon.predicate.PredicateVisitor; import org.apache.paimon.reader.DataEvolutionArray; @@ -34,6 +41,7 @@ import org.apache.paimon.schema.TableSchema; import org.apache.paimon.stats.SimpleStats; import org.apache.paimon.table.SpecialFields; +import org.apache.paimon.table.source.ScanMode; import org.apache.paimon.types.DataField; import org.apache.paimon.types.DataType; import org.apache.paimon.types.RowType; @@ -41,6 +49,7 @@ import org.apache.paimon.utils.Range; import org.apache.paimon.utils.RangeHelper; import org.apache.paimon.utils.SnapshotManager; +import org.apache.paimon.utils.ThrowingConsumer; import javax.annotation.Nullable; @@ -48,9 +57,11 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; +import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -72,6 +83,8 @@ public class DataEvolutionFileStoreScan extends AppendOnlyFileStoreScan { private boolean dropStats = false; @Nullable private RowType readType; private final boolean deletionVectorsEnabled; + private final boolean metadataMemoryOptimizationEnabled; + private final Map sharedWriteColumnNames; // Cache file's physical field id set per (schemaId, writeCols) to avoid recomputing during // per-file column pruning in postFilterManifestEntries. @@ -101,21 +114,31 @@ public DataEvolutionFileStoreScan( deletionVectorsEnabled, true); this.deletionVectorsEnabled = deletionVectorsEnabled; + this.metadataMemoryOptimizationEnabled = + new CoreOptions(schema.options()).dataEvolutionMetadataMemoryOptimizationEnabled(); + if (metadataMemoryOptimizationEnabled) { + // Reuse schema-owned names; this lookup cannot grow with the number of files. + Map names = new HashMap<>(); + for (String name : schema.fieldNames()) { + names.put(name, name); + } + this.sharedWriteColumnNames = Collections.unmodifiableMap(names); + } else { + this.sharedWriteColumnNames = Collections.emptyMap(); + } } @Override public FileStoreScan dropStats() { - // overwrite to keep stats here - // TODO refactor this hacky this.dropStats = true; + updateBaseDropStats(); return this; } @Override public FileStoreScan keepStats() { - // overwrite to keep stats here - // TODO refactor this hacky this.dropStats = false; + updateBaseDropStats(); return this; } @@ -124,9 +147,66 @@ public DataEvolutionFileStoreScan withFilter(Predicate predicate) { // overwrite to keep all filter here // TODO refactor this hacky this.inputFilter = predicate; + updateBaseDropStats(); return this; } + private void updateBaseDropStats() { + // Predicates need statistics until the complete row-id group has been filtered. + if (metadataMemoryOptimizationEnabled && dropStats && inputFilter == null) { + super.dropStats(); + } else { + super.keepStats(); + } + } + + @Override + protected Function createManifestEntryConverter( + Function converter) { + return super.createManifestEntryConverter( + metadataMemoryOptimizationEnabled + ? entry -> converter.apply(shareWriteColumnNames(entry)) + : converter); + } + + private ManifestEntry shareWriteColumnNames(ManifestEntry entry) { + List columns = entry.file().writeCols(); + if (columns == null || columns.isEmpty()) { + return entry; + } + List shared = null; + for (int i = 0; i < columns.size(); i++) { + String name = columns.get(i); + String canonical = sharedWriteColumnNames.getOrDefault(name, name); + if (canonical != name) { + if (shared == null) { + // File-owned lists remain independent; only immutable names are shared. + shared = new ArrayList<>(columns); + } + shared.set(i, canonical); + } + } + return shared == null + ? entry + : ManifestEntry.create( + entry.kind(), + entry.partition(), + entry.bucket(), + entry.totalBuckets(), + entry.file().withWriteCols(shared)); + } + + @Override + protected ManifestEntry dropStats(ManifestEntry entry) { + DataFileMeta file = entry.file(); + if (metadataMemoryOptimizationEnabled + && file.valueStats() == SimpleStats.EMPTY_STATS + && Collections.emptyList().equals(file.valueStatsCols())) { + return entry; + } + return super.dropStats(entry); + } + @Override public FileStoreScan withReadType(RowType readType) { // a type without user columns prunes nothing; assign unconditionally, this method @@ -183,6 +263,90 @@ public Iterator readManifestEntries( return filtered.iterator(); } + /** + * Streams complete, filtered RowID groups from one pinned batch snapshot. + * + *

The consumer should encode each group before requesting the next. Sort buffers are + * bounded, but DELETE identities and the largest connected group still grow with their input. + * The caller owns the supplied IO manager; this method only closes its own sorting channels. + */ + @Nullable + public Snapshot forEachFileGroup( + IOManager ioManager, ThrowingConsumer, Exception> consumer) + throws Exception { + if (scanMode != ScanMode.ALL) { + throw new UnsupportedOperationException( + "Incremental DE group planning only supports batch ALL scans."); + } + long started = System.nanoTime(); + ManifestsReader.Result manifests = readManifests(); + long[] resultedFiles = {0}; + Long rowLimit = + limit != null + && limit > 0 + && inputFilter == null + && rowRangeIndex == null + && !deletionVectorsEnabled + ? limit + : null; + long[] remainingRows = {rowLimit == null ? 0 : rowLimit}; + CompactFileIdentifierSet deleted = new CompactFileIdentifierSet(); + ReusableIdentifier identifier = new ReusableIdentifier(); + Function converter = + createManifestEntryConverter(Function.identity()); + try (DataEvolutionManifestEntryProducer producer = + new DataEvolutionManifestEntryProducer( + ManifestEntryExternalSort.ExternalSortConfig.from( + new CoreOptions(schema.options()), ioManager))) { + for (ManifestFileMeta manifest : manifests.filteredManifests) { + if (manifest.numDeletedFiles() > 0) { + forEachManifestEntry(manifest, FileKind.DELETE, null, deleted::add); + } + } + for (ManifestFileMeta manifest : manifests.filteredManifests) { + if (manifest.numAddedFiles() > 0) { + forEachManifestEntry( + manifest, + FileKind.ADD, + entry -> + !deleted.contains( + identifier.replaceWithPartition( + (ProjectedManifestEntry) entry)), + producer::write); + } + } + producer.forEachGroup( + group -> { + List converted = new ArrayList<>(group.size()); + for (ManifestEntry entry : group) { + converted.add(converter.apply(entry)); + } + List filtered = postFilterManifestEntries(converted); + if (!filtered.isEmpty()) { + int count = filtered.size(); + consumer.accept(filtered); + resultedFiles[0] += count; + if (rowLimit != null) { + // Providers can cover the same rows; summing them would stop early. + long rows = + filtered.stream() + .mapToLong(entry -> entry.file().rowCount()) + .max() + .orElse(0L); + remainingRows[0] -= Math.min(remainingRows[0], rows); + } + } + }, + () -> rowLimit == null || remainingRows[0] > 0); + } finally { + deleted.release(); + identifier.release(); + } + // This scan timing includes synchronous consumer work; it is not whole-SQL elapsed time. + reportScan(manifests, started, resultedFiles[0]); + return manifests.snapshot; + } + @Override protected boolean postFilterManifestEntriesEnabled() { return true; diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/DataEvolutionManifestEntryProducer.java b/paimon-core/src/main/java/org/apache/paimon/operation/DataEvolutionManifestEntryProducer.java new file mode 100644 index 000000000000..6b4b11c035d7 --- /dev/null +++ b/paimon-core/src/main/java/org/apache/paimon/operation/DataEvolutionManifestEntryProducer.java @@ -0,0 +1,141 @@ +/* + * 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.paimon.operation; + +import org.apache.paimon.data.BinaryRow; +import org.apache.paimon.data.GenericRow; +import org.apache.paimon.manifest.ManifestEntry; +import org.apache.paimon.manifest.ManifestEntrySerializer; +import org.apache.paimon.manifest.ProjectedManifestEntry; +import org.apache.paimon.types.DataTypes; +import org.apache.paimon.types.RowType; +import org.apache.paimon.utils.MutableObjectIterator; +import org.apache.paimon.utils.ThrowingConsumer; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.function.BooleanSupplier; + +/** + * Sorts valid binary entries with bounded buffers and decodes one complete RowID group at a time. + */ +final class DataEvolutionManifestEntryProducer implements AutoCloseable { + + private static final RowType SORT_TYPE = + DataTypes.ROW( + DataTypes.BIGINT(), + DataTypes.BIGINT(), + DataTypes.BIGINT(), + ManifestEntry.MANIFEST_ROW_TYPE); + + private final ManifestEntryExternalSort.BinaryRowSorter sorter; + private final GenericRow row = new GenericRow(4); + private long ordinal; + + DataEvolutionManifestEntryProducer(ManifestEntryExternalSort.ExternalSortConfig config) { + sorter = + new ManifestEntryExternalSort.BinaryRowSorter( + SORT_TYPE, new int[] {0, 1, 2}, config); + } + + void write(ProjectedManifestEntry entry) throws Exception { + Long first = entry.file().firstRowId(); + long count = entry.file().rowCount(); + if (first == null || count <= 0 || first > Long.MAX_VALUE - (count - 1)) { + throw new UnsupportedOperationException( + "Incremental DE planning requires valid non-null row id ranges."); + } + row.setField(0, first); + row.setField(1, first + count - 1); + row.setField(2, ordinal); + row.setField(3, entry.fullRow()); + try { + sorter.write(row); + ordinal = Math.incrementExact(ordinal); + } finally { + row.setField(3, null); + } + } + + void forEachGroup(ThrowingConsumer, Exception> consumer) throws Exception { + forEachGroup(consumer, () -> true); + } + + /** Stops only between complete dependency groups, without decoding a partial successor. */ + void forEachGroup( + ThrowingConsumer, Exception> consumer, + BooleanSupplier continueReading) + throws Exception { + MutableObjectIterator iterator = sorter.sortedIterator(); + BinaryRow reuse = new BinaryRow(SORT_TYPE.getFieldCount()); + ManifestEntrySerializer serializer = new ManifestEntrySerializer(); + List group = new ArrayList<>(); + long end = Long.MIN_VALUE; + BinaryRow next; + while ((next = iterator.next(reuse)) != null) { + long first = next.getLong(0); + if (!group.isEmpty() && first > end) { + emit(group, consumer); + if (!continueReading.getAsBoolean()) { + return; + } + group.clear(); + } + end = group.isEmpty() ? next.getLong(1) : Math.max(end, next.getLong(1)); + // fromRow creates independent metadata before the sort iterator reuses its row. + group.add( + new OrderedEntry( + next.getLong(2), + serializer.fromRow( + next.getRow( + 3, ManifestEntry.MANIFEST_ROW_TYPE.getFieldCount())))); + } + if (!group.isEmpty()) { + emit(group, consumer); + } + } + + private static void emit( + List group, ThrowingConsumer, Exception> consumer) + throws Exception { + // Preserve RangeHelper's original input order, including equal-version providers. + group.sort(Comparator.comparingLong(entry -> entry.ordinal)); + List entries = new ArrayList<>(group.size()); + for (OrderedEntry entry : group) { + entries.add(entry.entry); + } + consumer.accept(entries); + } + + @Override + public void close() throws Exception { + sorter.close(); + } + + private static final class OrderedEntry { + private final long ordinal; + private final ManifestEntry entry; + + private OrderedEntry(long ordinal, ManifestEntry entry) { + this.ordinal = ordinal; + this.entry = entry; + } + } +} diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/FileEntryMergeBuffer.java b/paimon-core/src/main/java/org/apache/paimon/operation/FileEntryMergeBuffer.java new file mode 100644 index 000000000000..44969e4c8ee5 --- /dev/null +++ b/paimon-core/src/main/java/org/apache/paimon/operation/FileEntryMergeBuffer.java @@ -0,0 +1,442 @@ +/* + * 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.paimon.operation; + +import org.apache.paimon.CoreOptions; +import org.apache.paimon.data.BinaryRow; +import org.apache.paimon.data.GenericRow; +import org.apache.paimon.data.serializer.InternalRowSerializer; +import org.apache.paimon.disk.IOManager; +import org.apache.paimon.manifest.FileEntry; +import org.apache.paimon.manifest.FileKind; +import org.apache.paimon.manifest.SimpleFileEntry; +import org.apache.paimon.manifest.SimpleFileEntryWithDV; +import org.apache.paimon.operation.ManifestEntryExternalSort.BinaryRowSorter; +import org.apache.paimon.operation.ManifestEntryExternalSort.ExternalSortConfig; +import org.apache.paimon.types.DataTypes; +import org.apache.paimon.types.RowType; +import org.apache.paimon.utils.IOUtils; +import org.apache.paimon.utils.MutableObjectIterator; +import org.apache.paimon.utils.ThrowingConsumer; + +import javax.annotation.Nullable; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.apache.paimon.utils.Preconditions.checkArgument; +import static org.apache.paimon.utils.Preconditions.checkState; +import static org.apache.paimon.utils.SerializationUtils.deserializeBinaryRow; +import static org.apache.paimon.utils.SerializationUtils.serializeBinaryRow; + +/** + * Spillable equivalent of validating delta entries and then merging base and delta entries with + * {@link FileEntry#mergeEntries(Iterable)}. Survivors retain the original insertion order. + * + *

The two sorters share one configured sort-buffer budget. Reduction retains only the current + * identity's state and the first invalid histories, rather than a map of all file identities. The + * encoded-size limit covers input and survivor rows; it is a logical metadata budget, not a bound + * on physical spill I/O (merging runs may temporarily coexist). A single entry still has to fit in + * the sort buffer. The caller owns this buffer until consumption finishes, including on failure. + */ +public final class FileEntryMergeBuffer implements AutoCloseable { + + private static final int MIN_SORT_BUFFER_PAGES = 6; + + private static final RowType ROW_TYPE = + DataTypes.ROW( + DataTypes.BYTES(), // complete identity, including DV subtype + DataTypes.INT(), // base before delta + DataTypes.BIGINT(), // original ordinal within source + DataTypes.TINYINT(), // kind + DataTypes.INT(), // total buckets (not part of identity) + DataTypes.BYTES(), // min key + DataTypes.BYTES(), // max key + DataTypes.BIGINT(), // row count + DataTypes.BIGINT()); // nullable first row id + + private final IOManager ioManager; + private final boolean ownedIOManager; + private final BinaryRowSorter identities; + private final BinaryRowSorter survivors; + private final InternalRowSerializer serializer = new InternalRowSerializer(ROW_TYPE); + private final long maxEncodedSize; + private final long[] ordinals = new long[2]; + private long encodedSize; + private boolean finished; + private boolean closed; + @Nullable private Failure deltaFailure; + @Nullable private Failure combinedFailure; + + public FileEntryMergeBuffer(CoreOptions options, @Nullable IOManager ioManager) + throws Exception { + maxEncodedSize = options.dataEvolutionMetadataMaxDiskSize(); + ExternalSortConfig configured = ExternalSortConfig.from(options, ioManager); + long pages = configured.bufferSize / configured.pageSize; + checkArgument( + pages >= MIN_SORT_BUFFER_PAGES, + "Metadata merge requires at least six sort-buffer pages."); + this.ownedIOManager = ioManager == null; + this.ioManager = + ownedIOManager ? IOManager.create(System.getProperty("java.io.tmpdir")) : ioManager; + BinaryRowSorter first = null; + try { + first = + new BinaryRowSorter( + ROW_TYPE, new int[] {0, 1, 2}, config(configured, pages / 2)); + survivors = + new BinaryRowSorter( + ROW_TYPE, new int[] {1, 2}, config(configured, pages - pages / 2)); + identities = first; + } catch (Throwable failure) { + try { + IOUtils.closeAll(first, ownedIOManager ? this.ioManager : null); + } catch (Throwable cleanup) { + failure.addSuppressed(cleanup); + } + throw failure; + } + } + + /** Whether one configured budget can supply both sorters with at least three full pages. */ + public static boolean supportsBufferSize(CoreOptions options) { + return options.sortSpillBufferSize() / options.pageSize() >= MIN_SORT_BUFFER_PAGES; + } + + private ExternalSortConfig config(ExternalSortConfig configured, long pages) { + return new ExternalSortConfig( + pages * configured.pageSize, + configured.pageSize, + configured.maxNumFileHandles, + configured.compression, + configured.maxDiskSize, + ioManager); + } + + public void writeBase(SimpleFileEntry entry) throws IOException { + write(entry, 0); + } + + public void writeDelta(SimpleFileEntry entry) throws IOException { + write(entry, 1); + } + + private void write(SimpleFileEntry entry, int source) throws IOException { + checkWritable(); + // Copy into the sorter immediately. No complete decoded entry is retained by this buffer. + BinaryRow row = + serializer.toBinaryRow( + GenericRow.of( + identity(entry), + source, + ordinals[source], + entry.kind().toByteValue(), + entry.totalBuckets(), + entry.minKey() == null ? null : serializeBinaryRow(entry.minKey()), + entry.maxKey() == null ? null : serializeBinaryRow(entry.maxKey()), + entry.rowCount(), + entry.firstRowId())); + writeEncoded(identities, row); + ordinals[source] = Math.incrementExact(ordinals[source]); + } + + private void writeEncoded(BinaryRowSorter sorter, BinaryRow row) throws IOException { + long bytes = row.getSizeInBytes(); + if (bytes > maxEncodedSize - encodedSize) { + throw new IOException("Metadata merge encoded limit exceeded: " + maxEncodedSize); + } + sorter.write(row); + encodedSize += bytes; + } + + /** Validates both histories before invoking the consumer, exactly once. */ + public void forEachMerged(ThrowingConsumer consumer) + throws Exception { + forEachMerged(false, consumer); + } + + /** + * Optionally keeps the first base record per identity, as the ordinary DE supplemental-file + * scan does. Delta records are never deduplicated. The caller must select this only when that + * scan branch would deduplicate its base input, even if the supplemental scan returns no rows. + */ + public void forEachMerged( + boolean deduplicateBase, ThrowingConsumer consumer) + throws Exception { + forEachMerged(deduplicateBase, null, consumer); + } + + /** + * Observes the first base record and last delta DELETE for each base identity before they can + * cancel. This is intended for current-ADD base scans. Observations arrive in identity order; + * the original base ordinal is supplied to preserve conflict selection order. + * + *

The observer may only prepare discardable local state: identity validation can still fail + * after an observation. Semantic errors from these observations must be decided only after the + * merge's own validation succeeds. Observer failures propagate to the caller, who must close + * this buffer. Ordinary consumers still run only after identity validation. + */ + public void forEachMerged( + boolean deduplicateBase, + @Nullable BaseEntryConsumer baseConsumer, + ThrowingConsumer consumer) + throws Exception { + checkWritable(); + finished = true; + MutableObjectIterator iterator = identities.sortedIterator(); + BinaryRow reuse = new BinaryRow(ROW_TYPE.getFieldCount()); + byte[] currentIdentity = null; + State delta = new State(); + State combined = new State(); + BinaryRow base = null; + BinaryRow lastDelete = null; + BinaryRow row; + while ((row = iterator.next(reuse)) != null) { + byte[] identity = row.getBinary(0); + if (!Arrays.equals(identity, currentIdentity)) { + observeBase(baseConsumer, base, lastDelete); + emitSurvivor(combined); + delta = new State(); + combined = new State(); + base = null; + lastDelete = null; + currentIdentity = identity; + } + if (baseConsumer != null) { + if (row.getInt(1) == 0 && base == null) { + base = row.copy(); + } else if (row.getInt(1) == 1 + && FileKind.fromByteValue(row.getByte(3)) == FileKind.DELETE) { + lastDelete = row.copy(); + } + } + if (row.getInt(1) == 1) { + deltaFailure = transition(delta, row, deltaFailure); + } + if (!deduplicateBase || row.getInt(1) == 1 || combined.row == null) { + combinedFailure = transition(combined, row, combinedFailure); + } + } + observeBase(baseConsumer, base, lastDelete); + emitSurvivor(combined); + // Delta-only validation precedes combined validation in the original conflict checker. + if (deltaFailure != null) { + throw deltaFailure.exception(); + } + if (combinedFailure != null) { + throw combinedFailure.exception(); + } + iterator = survivors.sortedIterator(); + while ((row = iterator.next(reuse)) != null) { + consumer.accept(decode(row)); + } + } + + private static void observeBase( + @Nullable BaseEntryConsumer consumer, + @Nullable BinaryRow base, + @Nullable BinaryRow lastDelete) + throws Exception { + if (consumer != null && base != null) { + consumer.accept( + decode(base), base.getLong(2), lastDelete == null ? null : decode(lastDelete)); + } + } + + /** Receives independent decoded metadata for one current base identity. */ + @FunctionalInterface + public interface BaseEntryConsumer { + void accept( + SimpleFileEntry base, long originalOrdinal, @Nullable SimpleFileEntry lastDelete) + throws Exception; + } + + @Nullable + private Failure transition(State state, BinaryRow row, @Nullable Failure firstFailure) { + if (state.invalid) { + return firstFailure; + } + if (FileKind.fromByteValue(row.getByte(3)) == FileKind.ADD && state.row != null) { + state.invalid = true; + if (firstFailure == null || earlier(row, firstFailure.addition)) { + return new Failure(state.row, row.copy()); + } + } else { + state.row = state.row == null ? row.copy() : null; + } + return firstFailure; + } + + private static boolean earlier(BinaryRow left, BinaryRow right) { + return left.getInt(1) < right.getInt(1) + || (left.getInt(1) == right.getInt(1) && left.getLong(2) < right.getLong(2)); + } + + private void emitSurvivor(State state) throws IOException { + if (!state.invalid && state.row != null) { + writeEncoded(survivors, state.row); + } + } + + private void checkWritable() { + checkState(!closed && !finished, "Metadata merge buffer is already finished or closed."); + } + + @Override + public void close() throws Exception { + if (!closed) { + closed = true; + deltaFailure = null; + combinedFailure = null; + IOUtils.closeAll(identities, survivors, ownedIOManager ? ioManager : null); + } + } + + private static byte[] identity(SimpleFileEntry entry) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(bytes); + writeBytes(out, serializeBinaryRow(entry.partition())); + out.writeInt(entry.bucket()); + out.writeInt(entry.level()); + writeString(out, entry.fileName()); + out.writeInt(entry.extraFiles().size()); + for (String extra : entry.extraFiles()) { + writeString(out, extra); + } + writeBytes(out, entry.embeddedIndex()); + writeString(out, entry.externalPath()); + boolean dv = entry instanceof SimpleFileEntryWithDV; + out.writeBoolean(dv); + if (dv) { + writeString(out, ((SimpleFileEntryWithDV) entry).dvFileName()); + } + return bytes.toByteArray(); + } + + private static SimpleFileEntry decode(BinaryRow row) throws IOException { + DataInputStream in = new DataInputStream(new ByteArrayInputStream(row.getBinary(0))); + BinaryRow partition = deserializeBinaryRow(readBytes(in)); + int bucket = in.readInt(); + int level = in.readInt(); + String name = readString(in); + int extraCount = in.readInt(); + List extra = new ArrayList<>(extraCount); + for (int i = 0; i < extraCount; i++) { + extra.add(readString(in)); + } + byte[] embedded = readBytes(in); + String external = readString(in); + boolean dv = in.readBoolean(); + String dvName = dv ? readString(in) : null; + SimpleFileEntry entry = + new SimpleFileEntry( + FileKind.fromByteValue(row.getByte(3)), + partition, + bucket, + row.getInt(4), + level, + name, + extra, + embedded, + row.isNullAt(5) ? null : deserializeBinaryRow(row.getBinary(5)), + row.isNullAt(6) ? null : deserializeBinaryRow(row.getBinary(6)), + external, + row.getLong(7), + row.isNullAt(8) ? null : row.getLong(8)); + return dv ? new SimpleFileEntryWithDV(entry, dvName) : entry; + } + + private static void writeString(DataOutputStream out, @Nullable String value) + throws IOException { + // String.equals compares UTF-16 code units, including unpaired surrogates. Charset + // encoders can replace those units and incorrectly collapse distinct file identities. + out.writeInt(value == null ? -1 : value.length()); + if (value != null) { + for (int i = 0; i < value.length(); i++) { + out.writeChar(value.charAt(i)); + } + } + } + + @Nullable + private static String readString(DataInputStream in) throws IOException { + int length = in.readInt(); + if (length == -1) { + return null; + } + if (length < 0 || length > in.available() / Character.BYTES) { + throw new IOException("Invalid metadata merge string length: " + length); + } + char[] chars = new char[length]; + for (int i = 0; i < length; i++) { + chars[i] = in.readChar(); + } + return new String(chars); + } + + private static void writeBytes(DataOutputStream out, @Nullable byte[] bytes) + throws IOException { + out.writeInt(bytes == null ? -1 : bytes.length); + if (bytes != null) { + out.write(bytes); + } + } + + @Nullable + private static byte[] readBytes(DataInputStream in) throws IOException { + int length = in.readInt(); + if (length == -1) { + return null; + } + if (length < 0 || length > in.available()) { + throw new IOException("Invalid metadata merge identity length: " + length); + } + byte[] bytes = new byte[length]; + in.readFully(bytes); + return bytes; + } + + private static final class State { + @Nullable private BinaryRow row; + private boolean invalid; + } + + private static final class Failure { + private final BinaryRow previous; + private final BinaryRow addition; + + private Failure(BinaryRow previous, BinaryRow addition) { + this.previous = previous; + this.addition = addition; + } + + private IllegalStateException exception() throws IOException { + return new IllegalStateException( + String.format( + "Trying to add file %s which is already in the the map: %s", + decode(addition).identifier(), decode(previous))); + } + } +} diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreCommitImpl.java b/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreCommitImpl.java index 3d996fea9283..438bcf175c26 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreCommitImpl.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreCommitImpl.java @@ -53,6 +53,7 @@ import org.apache.paimon.operation.commit.CommitScanner; import org.apache.paimon.operation.commit.ConflictDetection; import org.apache.paimon.operation.commit.DataEvolutionChangesProvider; +import org.apache.paimon.operation.commit.DataEvolutionConflictDetection; import org.apache.paimon.operation.commit.DataEvolutionRowRangeConflictException; import org.apache.paimon.operation.commit.DiscardingCompactChangesProvider; import org.apache.paimon.operation.commit.ManifestEntryChanges; @@ -79,6 +80,7 @@ import org.apache.paimon.table.sink.CommitCallback; import org.apache.paimon.table.sink.CommitMessage; import org.apache.paimon.table.sink.CommitMessageImpl; +import org.apache.paimon.table.sink.CommitMessageList; import org.apache.paimon.table.sink.CommitPreCallback; import org.apache.paimon.types.RowType; import org.apache.paimon.utils.DataFilePathFactories; @@ -101,7 +103,6 @@ import javax.annotation.Nullable; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; @@ -129,6 +130,7 @@ import static org.apache.paimon.manifest.ManifestEntry.recordCountDelete; import static org.apache.paimon.operation.commit.ManifestEntryChanges.changedPartitions; import static org.apache.paimon.operation.commit.RowTrackingCommitUtils.assignRowTracking; +import static org.apache.paimon.operation.commit.RowTrackingCommitUtils.groupByPartition; import static org.apache.paimon.partition.PartitionPredicate.createBinaryPartitions; import static org.apache.paimon.partition.PartitionPredicate.createPartitionPredicate; import static org.apache.paimon.types.VectorType.isVectorStoreFile; @@ -324,6 +326,12 @@ public FileStoreCommit withOperation(Snapshot.Operation operation) { @Override public List filterCommitted(List committables) { + if (!commitCallbacks.isEmpty()) { + committables = + committables.stream() + .map(this::materializeForCallbacks) + .collect(Collectors.toList()); + } // nothing to filter, fast exit if (committables.isEmpty()) { return committables; @@ -366,6 +374,7 @@ public List filterCommitted(List commi @Override public int commit(ManifestCommittable committable, boolean checkAppendFiles) { + committable = materializeForCallbacks(committable); LOG.info( "Ready to commit to table {}, number of commit messages: {}", tableName, @@ -385,8 +394,6 @@ public int commit(ManifestCommittable committable, boolean checkAppendFiles) { List committedCompactFiles = changes.compactTableFiles; Set> materializedBuckets = materializedBuckets(commitMessages); try { - List appendSimpleEntries = - SimpleFileEntry.from(changes.appendTableFiles); if (!ignoreEmptyCommit || !changes.appendTableFiles.isEmpty() || !changes.appendChangelog.isEmpty() @@ -398,7 +405,7 @@ public int commit(ManifestCommittable committable, boolean checkAppendFiles) { boolean allowRollback = false; if (conflictDetection.shouldBeOverwriteCommit( - appendSimpleEntries, changes.appendIndexFiles)) { + SimpleFileEntry.from(changes.appendTableFiles), changes.appendIndexFiles)) { commitKind = CommitKind.OVERWRITE; checkAppendFiles = true; allowRollback = true; @@ -898,12 +905,33 @@ public FileIO fileIO() { } private ManifestEntryChanges collectChanges(List commitMessages) { - ManifestEntryChanges changes = new ManifestEntryChanges(options.bucket()); - commitMessages.forEach(changes::collect); + ManifestEntryChanges changes; + if (options.dataEvolutionMetadataMemoryOptimizationEnabled() + && commitMessages instanceof CommitMessageList + && commitPreCallbacks.isEmpty() + && commitCallbacks.isEmpty()) { + changes = ManifestEntryChanges.lazyChanges(options.bucket(), commitMessages); + } else { + // Extensions may retain or mutate entries. Preserve their stable, mutable lists. + changes = new ManifestEntryChanges(options.bucket()); + commitMessages.forEach(changes::collect); + } LOG.info("Finished collecting changes, including: {}", changes); return changes; } + private ManifestCommittable materializeForCallbacks(ManifestCommittable committable) { + if ((!commitPreCallbacks.isEmpty() || !commitCallbacks.isEmpty()) + && committable.fileCommittables() instanceof CommitMessageList) { + return new ManifestCommittable( + committable.identifier(), + committable.watermark(), + ((CommitMessageList) committable.fileCommittables()).materialize(), + committable.properties()); + } + return committable; + } + private Map, Long> prepareConflictChecks( List commitMessages) { rangeSortConflict = null; @@ -1426,48 +1454,54 @@ private CommitResult tryCommitOnceWithoutLock( retryResult instanceof CommitFailRetryResult ? (CommitFailRetryResult) retryResult : null; - baseDataFiles = - conflictDetection.scanBaseDataFiles( - latestSnapshot, - changedPartitions, - deltaFiles, - indexFiles, - commitKind, - commitFailRetry, - hasOverwriteSinceLastAttempt); - if (discardDuplicate) { - Set baseIdentifiers = - baseDataFiles.stream() - .map(FileEntry::identifier) - .collect(Collectors.toSet()); - deltaFiles = - deltaFiles.stream() - .filter(entry -> !baseIdentifiers.contains(entry.identifier())) - .collect(Collectors.toList()); - } - RowIdConflictChecker rowIdConflictChecker = - conflictDetection.createRowIdConflictChecker( - schemaManager, deltaFiles, commitKind); - Optional exception = - conflictDetection.checkConflicts( - latestSnapshot, - baseDataFiles, - SimpleFileEntry.from(deltaFiles), - indexFiles, - rowIdConflictChecker, - commitKind); - while (exception.isPresent() - && exception.get() instanceof DataEvolutionRowRangeConflictException - && changesProvider instanceof DiscardingCompactChangesProvider - && ((DiscardingCompactChangesProvider) changesProvider) - .discard( - ((DataEvolutionRowRangeConflictException) exception.get()) - .conflictingFiles())) { - LOG.warn( - "Discarding conflicting compaction tasks for table {}: {}", - tableName, - exception.get().getMessage()); - deltaFiles = changesProvider.provide(latestSnapshot).tableFiles; + Optional exception; + boolean streamConflicts = + options.dataEvolutionMetadataStreamingEnabled() + && conflictDetection instanceof DataEvolutionConflictDetection + && ((DataEvolutionConflictDetection) conflictDetection) + .supportsStreamingConflicts() + && !discardDuplicate + && commitPreCallbacks.isEmpty() + && commitCallbacks.isEmpty() + && !(changesProvider instanceof DiscardingCompactChangesProvider); + if (streamConflicts) { + RowIdConflictChecker rowIdConflictChecker = + conflictDetection.createRowIdConflictChecker( + schemaManager, deltaFiles, commitKind); + exception = + ((DataEvolutionConflictDetection) conflictDetection) + .checkConflictsStreaming( + options, + ioManager, + latestSnapshot, + changedPartitions, + deltaFiles, + indexFiles, + rowIdConflictChecker, + commitKind); + } else { + baseDataFiles = + conflictDetection.scanBaseDataFiles( + latestSnapshot, + changedPartitions, + deltaFiles, + indexFiles, + commitKind, + commitFailRetry, + hasOverwriteSinceLastAttempt); + if (discardDuplicate) { + Set baseIdentifiers = + baseDataFiles.stream() + .map(FileEntry::identifier) + .collect(Collectors.toSet()); + deltaFiles = + deltaFiles.stream() + .filter(entry -> !baseIdentifiers.contains(entry.identifier())) + .collect(Collectors.toList()); + } + RowIdConflictChecker rowIdConflictChecker = + conflictDetection.createRowIdConflictChecker( + schemaManager, deltaFiles, commitKind); exception = conflictDetection.checkConflicts( latestSnapshot, @@ -1476,6 +1510,27 @@ private CommitResult tryCommitOnceWithoutLock( indexFiles, rowIdConflictChecker, commitKind); + while (exception.isPresent() + && exception.get() instanceof DataEvolutionRowRangeConflictException + && changesProvider instanceof DiscardingCompactChangesProvider + && ((DiscardingCompactChangesProvider) changesProvider) + .discard( + ((DataEvolutionRowRangeConflictException) exception.get()) + .conflictingFiles())) { + LOG.warn( + "Discarding conflicting compaction tasks for table {}: {}", + tableName, + exception.get().getMessage()); + deltaFiles = changesProvider.provide(latestSnapshot).tableFiles; + exception = + conflictDetection.checkConflicts( + latestSnapshot, + baseDataFiles, + SimpleFileEntry.from(deltaFiles), + indexFiles, + rowIdConflictChecker, + commitKind); + } } if (exception.isPresent()) { if (allowRollback @@ -1556,13 +1611,7 @@ private CommitResult tryCommitOnceWithoutLock( if (options.rowTrackingEnabled()) { if (options.rowTrackingPartitionGroupOnCommit()) { - Map> deltaFilesByPart = - deltaFiles.stream() - .collect(Collectors.groupingBy(ManifestEntry::partition)); - deltaFiles = - deltaFilesByPart.values().stream() - .flatMap(Collection::stream) - .collect(Collectors.toList()); + deltaFiles = groupByPartition(deltaFiles); } RowTrackingAssigned assigned = assignRowTracking(newSnapshotId, firstRowIdStart, deltaFiles); @@ -1575,7 +1624,21 @@ private CommitResult tryCommitOnceWithoutLock( } // the added records subtract the deleted records from - long deltaRecordCount = recordCountAdd(deltaFiles) - recordCountDelete(deltaFiles); + long deltaRecordCount; + if (options.dataEvolutionMetadataMemoryOptimizationEnabled()) { + long addedRecords = 0L; + long deletedRecords = 0L; + for (ManifestEntry entry : deltaFiles) { + if (entry.kind() == FileKind.ADD) { + addedRecords += entry.file().rowCount(); + } else if (entry.kind() == FileKind.DELETE) { + deletedRecords += entry.file().rowCount(); + } + } + deltaRecordCount = addedRecords - deletedRecords; + } else { + deltaRecordCount = recordCountAdd(deltaFiles) - recordCountDelete(deltaFiles); + } long totalRecordCount = previousTotalRecordCount + deltaRecordCount; // write new delta files into manifest files 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..4b7dc7a745c4 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 @@ -35,6 +35,7 @@ import org.apache.paimon.utils.Filter; import org.apache.paimon.utils.Range; import org.apache.paimon.utils.RowRangeIndex; +import org.apache.paimon.utils.ThrowingConsumer; import org.apache.paimon.utils.TriFilter; import javax.annotation.Nullable; @@ -117,6 +118,17 @@ public interface FileStoreScan { */ List readSimpleEntries(); + /** + * Consumes independent simple entries without collecting the complete result. ALL scans remove + * globally deleted identities, retaining duplicate ADDs for conflict detection. Other scan + * modes retain the manifest entry kinds and order. Implementations must not emulate streaming + * by first calling {@link #readSimpleEntries()}. + */ + default void forEachSimpleEntry(ThrowingConsumer consumer) + throws Exception { + throw new UnsupportedOperationException("Streaming simple entry scan is not supported."); + } + List readPartitionEntries(); List readBucketEntries(); diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/ManifestEntryExternalSort.java b/paimon-core/src/main/java/org/apache/paimon/operation/ManifestEntryExternalSort.java index 00e8e38bcc99..680711b99276 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/ManifestEntryExternalSort.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/ManifestEntryExternalSort.java @@ -22,6 +22,7 @@ import org.apache.paimon.compression.CompressOptions; import org.apache.paimon.data.BinaryRow; import org.apache.paimon.data.GenericRow; +import org.apache.paimon.data.InternalRow; import org.apache.paimon.data.serializer.InternalRowSerializer; import org.apache.paimon.disk.IOManager; import org.apache.paimon.manifest.CollectedDeletes; @@ -34,6 +35,7 @@ import org.apache.paimon.manifest.ProjectedManifestEntry; import org.apache.paimon.options.MemorySize; import org.apache.paimon.sort.BinaryExternalSortBuffer; +import org.apache.paimon.types.RowType; import org.apache.paimon.utils.CloseableIterator; import org.apache.paimon.utils.ExceptionUtils; import org.apache.paimon.utils.MutableObjectIterator; @@ -41,6 +43,7 @@ import javax.annotation.Nullable; +import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -196,17 +199,13 @@ static ExternalSortConfig from(CoreOptions options, @Nullable IOManager ioManage } } - /** Spillable sorter that stores sort keys plus complete binary manifest rows. */ - private static class EntrySorter implements AutoCloseable { - private final ManifestFileSorter.ManifestSortKey sortKey; - private final GenericRow externalSortRow; + /** Shared binary sorting kernel; callers retain their own row and output semantics. */ + static final class BinaryRowSorter implements AutoCloseable { private final IOManager ioManager; private final boolean ownedIOManager; private final BinaryExternalSortBuffer sortBuffer; - private EntrySorter(ManifestFileSorter.ManifestSortKey sortKey, ExternalSortConfig config) { - this.sortKey = sortKey; - this.externalSortRow = new GenericRow(sortKey.externalSortRowType().getFieldCount()); + BinaryRowSorter(RowType rowType, int[] keyFields, ExternalSortConfig config) { this.ioManager = config.ioManager == null ? IOManager.create(System.getProperty("java.io.tmpdir")) @@ -215,8 +214,8 @@ private EntrySorter(ManifestFileSorter.ManifestSortKey sortKey, ExternalSortConf this.sortBuffer = BinaryExternalSortBuffer.create( ioManager, - sortKey.externalSortRowType(), - sortKey.externalSortKeyFields(), + rowType, + keyFields, config.bufferSize, config.pageSize, config.maxNumFileHandles, @@ -224,6 +223,44 @@ private EntrySorter(ManifestFileSorter.ManifestSortKey sortKey, ExternalSortConf config.maxDiskSize); } + void write(InternalRow row) throws IOException { + sortBuffer.write(row); + } + + boolean isEmpty() { + return sortBuffer.isEmpty(); + } + + MutableObjectIterator sortedIterator() throws IOException { + return sortBuffer.sortedIterator(); + } + + @Override + public void close() throws Exception { + try { + sortBuffer.clear(); + } finally { + if (ownedIOManager) { + ioManager.close(); + } + } + } + } + + /** Spillable sorter that stores sort keys plus complete binary manifest rows. */ + private static class EntrySorter implements AutoCloseable { + private final ManifestFileSorter.ManifestSortKey sortKey; + private final GenericRow externalSortRow; + private final BinaryRowSorter sortBuffer; + + private EntrySorter(ManifestFileSorter.ManifestSortKey sortKey, ExternalSortConfig config) { + this.sortKey = sortKey; + this.externalSortRow = new GenericRow(sortKey.externalSortRowType().getFieldCount()); + this.sortBuffer = + new BinaryRowSorter( + sortKey.externalSortRowType(), sortKey.externalSortKeyFields(), config); + } + private void write(ProjectedManifestEntry entry) throws Exception { sortKey.replaceExternalSortRow(externalSortRow, entry, entry.fullRow()); sortBuffer.write(externalSortRow); @@ -344,10 +381,7 @@ private Pair, List> writeMinorToManifes @Override public void close() throws Exception { - sortBuffer.clear(); - if (ownedIOManager) { - ioManager.close(); - } + sortBuffer.close(); } } } diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/commit/CommitScanner.java b/paimon-core/src/main/java/org/apache/paimon/operation/commit/CommitScanner.java index 5338761c8704..adacb1c68e6f 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/commit/CommitScanner.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/commit/CommitScanner.java @@ -33,6 +33,7 @@ import org.apache.paimon.utils.Pair; import org.apache.paimon.utils.Range; import org.apache.paimon.utils.SnapshotManager; +import org.apache.paimon.utils.ThrowingConsumer; import javax.annotation.Nullable; @@ -256,6 +257,43 @@ public List readAllEntriesFromDataFiles( } } + /** Streams the same scoped base entries without retaining the complete scan result. */ + public void forEachEntryFromChangedRowRanges( + Snapshot snapshot, + List changedPartitions, + List changedRowRanges, + ThrowingConsumer consumer) + throws Exception { + freshBaseScan(snapshot, changedPartitions) + .withRowRanges(changedRowRanges) + .forEachSimpleEntry(consumer); + } + + /** Streams every matching physical identity, including duplicate ADDs. */ + public void forEachEntryFromDataFiles( + Snapshot snapshot, + List changedPartitions, + Set dataFiles, + ThrowingConsumer consumer) + throws Exception { + if (!dataFiles.isEmpty()) { + freshBaseScan(snapshot, changedPartitions) + .withDataFileNameFilter(dataFiles::contains) + .forEachSimpleEntry(consumer); + } + } + + private FileStoreScan freshBaseScan(Snapshot snapshot, List changedPartitions) { + FileStoreScan freshScan = scanSupplier.get(); + if (dropStats) { + freshScan.dropStats(); + } + return freshScan + .withSnapshot(snapshot) + .withKind(ScanMode.ALL) + .withPartitionFilter(changedPartitions); + } + public Map readTotalBuckets( Snapshot snapshot, List changedPartitions) { try { diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/commit/ConflictDetection.java b/paimon-core/src/main/java/org/apache/paimon/operation/commit/ConflictDetection.java index 3685d96311da..daf267701783 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/commit/ConflictDetection.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/commit/ConflictDetection.java @@ -36,6 +36,7 @@ import org.apache.paimon.schema.SchemaManager; import org.apache.paimon.table.BucketMode; import org.apache.paimon.types.RowType; +import org.apache.paimon.utils.ExceptionUtils; import org.apache.paimon.utils.FileStorePathFactory; import org.apache.paimon.utils.Pair; import org.apache.paimon.utils.SnapshotManager; @@ -229,6 +230,7 @@ public final Optional checkConflicts( deltaEntries = buildDeltaEntriesWithDV(baseEntries, deltaEntries, deltaIndexEntries); } catch (Throwable e) { + ExceptionUtils.rethrowIfFatalErrorOrOOM(e); return Optional.of( conflictException(commitUser, baseEntries, deltaEntries).apply(e)); } @@ -252,6 +254,7 @@ public final Optional checkConflicts( // relies on map for deduplication, this may result in the loss of this file FileEntry.mergeEntries(deltaEntries); } catch (Throwable e) { + ExceptionUtils.rethrowIfFatalErrorOrOOM(e); throw conflictException.apply(e); } @@ -260,6 +263,7 @@ public final Optional checkConflicts( // merge manifest entries and also check if the files we want to delete are still there mergedEntries = FileEntry.mergeEntries(allEntries); } catch (Throwable e) { + ExceptionUtils.rethrowIfFatalErrorOrOOM(e); return Optional.of(conflictException.apply(e)); } @@ -469,6 +473,7 @@ private Optional checkDeleteInEntries( tableName); } } catch (Throwable e) { + ExceptionUtils.rethrowIfFatalErrorOrOOM(e); Optional exception = checkConflictForPartitionExpire(mergedEntries); if (exception.isPresent()) { return exception; diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/commit/DataEvolutionConflictDetection.java b/paimon-core/src/main/java/org/apache/paimon/operation/commit/DataEvolutionConflictDetection.java index 89ad887882e0..48e6e5467187 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/commit/DataEvolutionConflictDetection.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/commit/DataEvolutionConflictDetection.java @@ -18,9 +18,11 @@ package org.apache.paimon.operation.commit; +import org.apache.paimon.CoreOptions; import org.apache.paimon.Snapshot; import org.apache.paimon.Snapshot.CommitKind; import org.apache.paimon.data.BinaryRow; +import org.apache.paimon.disk.IOManager; import org.apache.paimon.errors.ErrorMessages; import org.apache.paimon.globalindex.CentroidIndexMeta; import org.apache.paimon.index.DataEvolutionIndexSourceMeta; @@ -33,6 +35,7 @@ import org.apache.paimon.manifest.IndexManifestEntry; import org.apache.paimon.manifest.ManifestEntry; import org.apache.paimon.manifest.SimpleFileEntry; +import org.apache.paimon.operation.FileEntryMergeBuffer; import org.apache.paimon.operation.commit.RetryCommitResult.CommitFailRetryResult; import org.apache.paimon.schema.SchemaManager; import org.apache.paimon.schema.TableSchema; @@ -44,6 +47,9 @@ import org.apache.paimon.utils.RangeHelper; import org.apache.paimon.utils.RowRangeIndex; import org.apache.paimon.utils.SnapshotManager; +import org.apache.paimon.utils.ThrowingConsumer; + +import org.apache.paimon.shade.guava30.com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -79,6 +85,7 @@ public class DataEvolutionConflictDetection extends ConflictDetection { private final SnapshotManager snapshotManager; private final IndexFileHandler indexFileHandler; private final boolean nestedFieldEnabled; + private final boolean streamingConflictsSupported; private @Nullable Long rowIdCheckFromSnapshot; private @Nullable RowIdConflictCheckStrategy rowIdConflictCheckStrategy; @@ -108,6 +115,7 @@ public DataEvolutionConflictDetection( this.snapshotManager = snapshotManager; this.indexFileHandler = indexFileHandler; this.nestedFieldEnabled = nestedFieldEnabled; + this.streamingConflictsSupported = !deletionVectorsEnabled; } @Override @@ -310,6 +318,150 @@ private List scanChangedRowRanges( .values()); } + /** + * Produces the ordinary DE base scan's input without retaining its complete metadata. Returns + * whether the caller must keep the first base record per identity, matching the supplemental + * scan branch's left-first deduplication. Range and referenced-name state still grow with the + * changes; the consumer must not retain the entire decoded base. + */ + public boolean forEachBaseDataFile( + Snapshot latestSnapshot, + List changedPartitions, + List deltaFiles, + List indexFiles, + ThrowingConsumer consumer) + throws Exception { + List changedRowRanges = changedRowRanges(deltaFiles, indexFiles); + Set referencedDataFiles = referencedDataFiles(deltaFiles, indexFiles); + if (changedRowRanges.isEmpty()) { + if (!referencedDataFiles.isEmpty()) { + commitScanner() + .forEachEntryFromDataFiles( + latestSnapshot, changedPartitions, referencedDataFiles, consumer); + } + return false; + } + + commitScanner() + .forEachEntryFromChangedRowRanges( + latestSnapshot, + changedPartitions, + changedRowRanges, + entry -> { + referencedDataFiles.remove(entry.fileName()); + consumer.accept(entry); + }); + if (referencedDataFiles.isEmpty()) { + return false; + } + commitScanner() + .forEachEntryFromDataFiles( + latestSnapshot, changedPartitions, referencedDataFiles, consumer); + // Selecting this branch triggers deduplication even when the second scan emits no rows. + return true; + } + + public boolean supportsStreamingConflicts() { + return streamingConflictsSupported; + } + + /** + * Checks the no-DV successful path without complete base/delta/merged metadata collections. + * Possible conflicts fall back to the original checker after closing spill resources, + * preserving its diagnostics, error priority and throw/return contract. That diagnostic path + * retains the original memory boundary. Buffers too small for both sorters also use that + * boundary instead of increasing the configured sort-buffer budget. Callback and DV callers + * keep the ordinary path. + */ + public Optional checkConflictsStreaming( + CoreOptions options, + @Nullable IOManager ioManager, + Snapshot latestSnapshot, + List changedPartitions, + List deltaFiles, + List indexFiles, + @Nullable RowIdConflictChecker rowIdConflictChecker, + CommitKind commitKind) { + boolean ordinary = + !supportsStreamingConflicts() || !FileEntryMergeBuffer.supportsBufferSize(options); + if (!ordinary) { + boolean globalIndexes = + indexFiles.stream() + .anyMatch( + entry -> + entry.kind() == FileKind.ADD + && entry.indexFile().globalIndexMeta() != null); + DataEvolutionStreamingChecks checks = + new DataEvolutionStreamingChecks( + commitKind, + rowIdCheckFromSnapshot != null || commitKind == CommitKind.COMPACT, + globalIndexes); + try (FileEntryMergeBuffer buffer = new FileEntryMergeBuffer(options, ioManager)) { + boolean deduplicate = + forEachBaseDataFile( + latestSnapshot, + changedPartitions, + deltaFiles, + indexFiles, + entry -> { + checks.addRawBase(entry); + buffer.writeBase(entry); + }); + for (ManifestEntry entry : deltaFiles) { + buffer.writeDelta(SimpleFileEntry.from(entry)); + } + try { + buffer.forEachMerged(deduplicate, checks::addBase, checks::addMerged); + } catch (IllegalStateException invalidIdentity) { + // The original checker selects bucket errors before identity errors and + // distinguishes delta exceptions from combined conflict return values. + ordinary = true; + } + ordinary = + ordinary + || checks.mayConflict( + deduplicate, + deltaFiles, + indexFiles, + latestSnapshot.nextRowId()); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException("Failed streaming data evolution conflict check.", e); + } finally { + checks.clear(); + } + } + if (ordinary) { + List base = + scanBaseDataFiles( + latestSnapshot, + changedPartitions, + deltaFiles, + indexFiles, + commitKind, + null, + false); + return checkConflicts( + latestSnapshot, + base, + SimpleFileEntry.from(deltaFiles), + indexFiles, + rowIdConflictChecker, + commitKind); + } + Optional exception = + checkCentroidSourceChanges(latestSnapshot, indexFiles); + if (exception.isPresent()) { + return exception; + } + return checkForRowIdFromSnapshot( + latestSnapshot, + Lists.transform(deltaFiles, SimpleFileEntry::from), + indexFiles, + rowIdConflictChecker); + } + private Set referencedDataFiles( List deltaFiles, List indexFiles) { // Include ADD files to detect replay even if their row IDs have changed or are unassigned. @@ -553,7 +705,7 @@ public RowIdConflictChecker createChecker( boolean nestedFieldEnabled) { return RowIdColumnConflictChecker.fromDataFiles( schemaManager, - deltaFiles.stream().map(ManifestEntry::file).collect(Collectors.toList()), + Lists.transform(deltaFiles, ManifestEntry::file), nestedFieldEnabled); } @@ -870,7 +1022,7 @@ private static RowRangeIndex rowRangeIndex( mergeAdjacent); } - private static boolean dedicatedStorageFile(String fileName) { + static boolean dedicatedStorageFile(String fileName) { return isBlobFile(fileName) || isVectorStoreFile(fileName); } } diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/commit/DataEvolutionStreamingChecks.java b/paimon-core/src/main/java/org/apache/paimon/operation/commit/DataEvolutionStreamingChecks.java new file mode 100644 index 000000000000..778f32cfa6b6 --- /dev/null +++ b/paimon-core/src/main/java/org/apache/paimon/operation/commit/DataEvolutionStreamingChecks.java @@ -0,0 +1,345 @@ +/* + * 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.paimon.operation.commit; + +import org.apache.paimon.Snapshot.CommitKind; +import org.apache.paimon.data.BinaryRow; +import org.apache.paimon.index.GlobalIndexMeta; +import org.apache.paimon.manifest.FileEntry; +import org.apache.paimon.manifest.IndexManifestEntry; +import org.apache.paimon.manifest.ManifestEntry; +import org.apache.paimon.manifest.SimpleFileEntry; +import org.apache.paimon.sort.IndexedSortable; +import org.apache.paimon.sort.QuickSort; +import org.apache.paimon.utils.Pair; +import org.apache.paimon.utils.Range; + +import javax.annotation.Nullable; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import static org.apache.paimon.manifest.FileKind.ADD; +import static org.apache.paimon.manifest.FileKind.DELETE; +import static org.apache.paimon.operation.commit.DataEvolutionConflictDetection.dedicatedStorageFile; + +/** + * Successful-path DE checks retaining intervals rather than full file metadata. A possible conflict + * is diagnosed by the ordinary checker after the caller closes its sorting resources. Interval + * capacity and scope directories still grow with the input; this is not constant-memory storage. + */ +final class DataEvolutionStreamingChecks { + + private final boolean compact; + private final boolean checkRanges; + private final boolean checkBuckets; + private final boolean checkIndexes; + private final Intervals existing = new Intervals(); + private final Intervals normal = new Intervals(); + private final Intervals dedicated = new Intervals(); + private final Map, Intervals> existingByBucket = new HashMap<>(); + private final Map, Intervals> indexBase = new HashMap<>(); + private final Map rawBuckets = new HashMap<>(); + private final Map uniqueBuckets = new HashMap<>(); + private boolean rawBucketMismatch; + private boolean uniqueBucketMismatch; + private boolean invalid; + + DataEvolutionStreamingChecks(CommitKind kind, boolean checkRanges, boolean checkIndexes) { + this.compact = kind == CommitKind.COMPACT; + this.checkRanges = checkRanges; + this.checkBuckets = kind != CommitKind.OVERWRITE; + this.checkIndexes = checkIndexes; + } + + void addRawBase(SimpleFileEntry entry) { + if (checkBuckets) { + rawBucketMismatch |= bucketMismatch(rawBuckets, entry); + } + } + + void addBase(SimpleFileEntry entry, long ordinal, @Nullable SimpleFileEntry lastDelete) { + if (checkBuckets) { + uniqueBucketMismatch |= bucketMismatch(uniqueBuckets, entry); + } + if (entry.kind() == ADD && lastDelete != null) { + invalid |= + !Objects.equals(entry.firstRowId(), lastDelete.firstRowId()) + || entry.rowCount() != lastDelete.rowCount(); + } + if (entry.firstRowId() == null) { + return; + } + long end = entry.firstRowId() + entry.rowCount() - 1; + if (end < entry.firstRowId()) { + invalid = true; + return; + } + Range range = new Range(entry.firstRowId(), end); + if (!dedicatedStorageFile(entry.fileName())) { + if (compact) { + existingByBucket + .computeIfAbsent(scope(entry), ignored -> new Intervals()) + .add(range); + } else { + existing.add(range); + } + } + if (checkIndexes && entry.kind() == ADD) { + // Global indexes include dedicated base files, unlike ordinary existence checks. + indexBase.computeIfAbsent(scope(entry), ignored -> new Intervals()).add(range); + } + } + + void addMerged(SimpleFileEntry entry) { + if (entry.kind() == DELETE) { + invalid = true; + } else if (checkRanges && entry.firstRowId() != null) { + long end = entry.firstRowId() + entry.rowCount() - 1; + if (end < entry.firstRowId()) { + invalid = true; + } else { + (dedicatedStorageFile(entry.fileName()) ? dedicated : normal) + .add(new Range(entry.firstRowId(), end)); + } + } + } + + boolean mayConflict( + boolean deduplicateBase, + List delta, + List indexes, + @Nullable Long nextRowId) { + if (invalid + || (checkBuckets && (deduplicateBase ? uniqueBucketMismatch : rawBucketMismatch))) { + return true; + } + Map buckets = deduplicateBase ? uniqueBuckets : rawBuckets; + existing.prepare(false); + existingByBucket.values().forEach(ranges -> ranges.prepare(true)); + for (ManifestEntry entry : delta) { + if (checkBuckets && bucketMismatch(buckets, entry)) { + return true; + } + if (entry.kind() != ADD || entry.firstRowId() == null) { + continue; + } + Range range; + if (compact) { + Intervals ranges = existingByBucket.get(scope(entry)); + if (ranges == null || !ranges.contains(entry.file().nonNullRowIdRange(), false)) { + return true; + } + } else if (nextRowId != null && entry.firstRowId() < nextRowId) { + range = entry.file().nonNullRowIdRange(); + if (!existing.contains(range, !dedicatedStorageFile(entry.fileName()))) { + return true; + } + } + } + if (checkRanges) { + if (normal.hasDifferentOverlaps()) { + return true; + } + normal.prepare(false); + for (int i = 0; i < dedicated.size; i++) { + if (!normal.contains(new Range(dedicated.from(i), dedicated.to(i)), false)) { + return true; + } + } + } + if (checkIndexes) { + indexBase.values().forEach(ranges -> ranges.prepare(true)); + for (IndexManifestEntry entry : indexes) { + GlobalIndexMeta meta = entry.indexFile().globalIndexMeta(); + if (entry.kind() == ADD && meta != null) { + Intervals ranges = indexBase.get(Pair.of(entry.partition(), entry.bucket())); + if (ranges == null || !ranges.contains(meta.rowRange(), false)) { + return true; + } + } + } + } + return false; + } + + private static Pair scope(FileEntry entry) { + return Pair.of(entry.partition(), entry.bucket()); + } + + private static boolean bucketMismatch(Map counts, FileEntry entry) { + if (entry.totalBuckets() <= 0) { + return false; + } + Integer previous = counts.putIfAbsent(entry.partition(), entry.totalBuckets()); + return previous != null && previous != entry.totalBuckets(); + } + + void clear() { + existing.values = new long[0]; + normal.values = new long[0]; + dedicated.values = new long[0]; + existingByBucket.clear(); + indexBase.clear(); + rawBuckets.clear(); + uniqueBuckets.clear(); + } + + /** Pairs sorted with Paimon's existing sorter, then compacted in place. */ + private static final class Intervals implements IndexedSortable { + private long[] values = new long[32]; + private int size; + private boolean sorted; + + private void add(Range range) { + if (size == (Integer.MAX_VALUE - 8) / 2) { + throw new IllegalStateException("Too many DE conflict intervals."); + } + int required = (size + 1) * 2; + if (required > values.length) { + values = + Arrays.copyOf( + values, + (int) Math.min(Integer.MAX_VALUE - 8L, (long) values.length * 2)); + } + values[size * 2] = range.from; + values[size * 2 + 1] = range.to; + size++; + sorted = false; + } + + private long from(int i) { + return values[i * 2]; + } + + private long to(int i) { + return values[i * 2 + 1]; + } + + private void sort() { + if (!sorted && size > 1) { + new QuickSort().sort(this); + } + sorted = true; + } + + private boolean hasDifferentOverlaps() { + sort(); + if (size == 0) { + return false; + } + long start = from(0); + long end = to(0); + for (int i = 1; i < size; i++) { + if (from(i) <= end) { + if (from(i) != start || to(i) != end) { + return true; + } + } else { + start = from(i); + end = to(i); + } + } + return false; + } + + private void prepare(boolean adjacent) { + sort(); + int result = 0; + for (int i = 0; i < size; i++) { + long start = from(i); + long end = to(i); + if (result > 0 + && (start <= to(result - 1) + || (adjacent + && to(result - 1) != Long.MAX_VALUE + && start == to(result - 1) + 1))) { + values[(result - 1) * 2 + 1] = Math.max(to(result - 1), end); + } else { + values[result * 2] = start; + values[result * 2 + 1] = end; + result++; + } + } + size = result; + } + + private boolean contains(Range range, boolean exact) { + int low = 0; + int high = size; + while (low < high) { + int middle = (low + high) >>> 1; + if (to(middle) < range.from) { + low = middle + 1; + } else { + high = middle; + } + } + return low < size + && (exact + ? from(low) == range.from && to(low) == range.to + : from(low) <= range.from && to(low) >= range.to); + } + + @Override + public int compare(int i, int j) { + int first = Long.compare(from(i), from(j)); + return first == 0 ? Long.compare(to(i), to(j)) : first; + } + + @Override + public void swap(int i, int j) { + long first = from(i); + long last = to(i); + values[i * 2] = from(j); + values[i * 2 + 1] = to(j); + values[j * 2] = first; + values[j * 2 + 1] = last; + } + + // One logical segment with one-element address strides; no segmented byte storage. + @Override + public int compare(int si, int oi, int sj, int oj) { + return compare(oi, oj); + } + + @Override + public void swap(int si, int oi, int sj, int oj) { + swap(oi, oj); + } + + @Override + public int size() { + return size; + } + + @Override + public int recordSize() { + return 1; + } + + @Override + public int recordsPerSegment() { + return Integer.MAX_VALUE; + } + } +} diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/commit/ManifestEntryChanges.java b/paimon-core/src/main/java/org/apache/paimon/operation/commit/ManifestEntryChanges.java index faa65bba4750..2e4e599def5d 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/commit/ManifestEntryChanges.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/commit/ManifestEntryChanges.java @@ -19,6 +19,7 @@ package org.apache.paimon.operation.commit; import org.apache.paimon.data.BinaryRow; +import org.apache.paimon.index.IndexFileMeta; import org.apache.paimon.io.DataFileMeta; import org.apache.paimon.manifest.FileEntry; import org.apache.paimon.manifest.FileKind; @@ -27,10 +28,14 @@ import org.apache.paimon.table.sink.CommitMessage; import org.apache.paimon.table.sink.CommitMessageImpl; +import org.apache.paimon.shade.guava30.com.google.common.collect.Iterators; + import java.util.ArrayList; import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Set; +import java.util.function.Function; import static org.apache.paimon.deletionvectors.DeletionVectorsIndexFile.DELETION_VECTORS_INDEX; @@ -56,6 +61,134 @@ public ManifestEntryChanges(int defaultNumBucket) { this.compactIndexFiles = new ArrayList<>(); } + /** Expands one decoded message at a time; the input must be stable and replayable. */ + public static ManifestEntryChanges lazyChanges( + int defaultNumBucket, List messages) { + int[] sizes = new int[6]; + for (CommitMessage message : messages) { + CommitMessageImpl m = (CommitMessageImpl) message; + sizes[0] = + Math.addExact( + sizes[0], + Math.addExact( + m.newFilesIncrement().newFiles().size(), + m.newFilesIncrement().deletedFiles().size())); + sizes[1] = Math.addExact(sizes[1], m.newFilesIncrement().changelogFiles().size()); + sizes[2] = + Math.addExact( + sizes[2], + Math.addExact( + m.newFilesIncrement().deletedIndexFiles().size(), + m.newFilesIncrement().newIndexFiles().size())); + sizes[3] = + Math.addExact( + sizes[3], + Math.addExact( + m.compactIncrement().compactBefore().size(), + m.compactIncrement().compactAfter().size())); + sizes[4] = Math.addExact(sizes[4], m.compactIncrement().changelogFiles().size()); + sizes[5] = + Math.addExact( + sizes[5], + Math.addExact( + m.compactIncrement().deletedIndexFiles().size(), + m.compactIncrement().newIndexFiles().size())); + } + ManifestEntryChanges changes = new ManifestEntryChanges(defaultNumBucket); + changes.appendTableFiles = + flatten( + messages, + sizes[0], + m -> + Iterators.concat( + changes.files( + m, FileKind.ADD, m.newFilesIncrement().newFiles()), + changes.files( + m, + FileKind.DELETE, + m.newFilesIncrement().deletedFiles()))); + changes.appendChangelog = + flatten( + messages, + sizes[1], + m -> + changes.files( + m, FileKind.ADD, m.newFilesIncrement().changelogFiles())); + changes.appendIndexFiles = + flatten( + messages, + sizes[2], + m -> + Iterators.concat( + indexes( + m, + FileKind.DELETE, + m.newFilesIncrement().deletedIndexFiles()), + indexes( + m, + FileKind.ADD, + m.newFilesIncrement().newIndexFiles()))); + changes.compactTableFiles = + flatten( + messages, + sizes[3], + m -> + Iterators.concat( + changes.files( + m, + FileKind.DELETE, + m.compactIncrement().compactBefore()), + changes.files( + m, + FileKind.ADD, + m.compactIncrement().compactAfter()))); + changes.compactChangelog = + flatten( + messages, + sizes[4], + m -> changes.files(m, FileKind.ADD, m.compactIncrement().changelogFiles())); + changes.compactIndexFiles = + flatten( + messages, + sizes[5], + m -> + Iterators.concat( + indexes( + m, + FileKind.DELETE, + m.compactIncrement().deletedIndexFiles()), + indexes( + m, + FileKind.ADD, + m.compactIncrement().newIndexFiles()))); + return changes; + } + + private Iterator files( + CommitMessageImpl message, FileKind kind, List files) { + return Iterators.transform(files.iterator(), file -> makeEntry(kind, message, file)); + } + + private static Iterator indexes( + CommitMessageImpl message, FileKind kind, List files) { + return Iterators.transform( + files.iterator(), + file -> new IndexManifestEntry(kind, message.partition(), message.bucket(), file)); + } + + private static List flatten( + List messages, + int size, + Function> entries) { + return new ReplayableList<>( + size, + () -> + Iterators.concat( + Iterators.transform( + messages.iterator(), + message -> entries.apply((CommitMessageImpl) message)))); + } + public void collect(CommitMessage message) { CommitMessageImpl commitMessage = (CommitMessageImpl) message; commitMessage diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/commit/ReplayableList.java b/paimon-core/src/main/java/org/apache/paimon/operation/commit/ReplayableList.java new file mode 100644 index 000000000000..90e948ea8cb1 --- /dev/null +++ b/paimon-core/src/main/java/org/apache/paimon/operation/commit/ReplayableList.java @@ -0,0 +1,117 @@ +/* + * 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.paimon.operation.commit; + +import java.util.AbstractSequentialList; +import java.util.Iterator; +import java.util.ListIterator; +import java.util.NoSuchElementException; +import java.util.function.Supplier; + +/** + * Read-only, repeatable traversal of commit entries without caching them. Forward traversal is + * linear; random access and backwards traversal replay the input. The supplier must return the same + * ordered values on every traversal and must not require closing external resources. + */ +class ReplayableList extends AbstractSequentialList { + + private final int size; + private final Supplier> iterators; + + ReplayableList(int size, Supplier> iterators) { + this.size = size; + this.iterators = iterators; + } + + @Override + public int size() { + return size; + } + + @Override + public ListIterator listIterator(int index) { + if (index < 0 || index > size) { + throw new IndexOutOfBoundsException("Entry index: " + index + ", size: " + size); + } + return new ListIterator() { + private int position = index; + private Iterator forward; + + @Override + public boolean hasNext() { + return position < size; + } + + @Override + public T next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + if (forward == null) { + forward = iterators.get(); + for (int i = 0; i < position; i++) { + forward.next(); + } + } + T result = forward.next(); + position++; + return result; + } + + @Override + public boolean hasPrevious() { + return position > 0; + } + + @Override + public T previous() { + if (!hasPrevious()) { + throw new NoSuchElementException(); + } + forward = null; + return ReplayableList.this.get(--position); + } + + @Override + public int nextIndex() { + return position; + } + + @Override + public int previousIndex() { + return position - 1; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + + @Override + public void set(T value) { + throw new UnsupportedOperationException(); + } + + @Override + public void add(T value) { + throw new UnsupportedOperationException(); + } + }; + } +} diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/commit/RowIdColumnConflictChecker.java b/paimon-core/src/main/java/org/apache/paimon/operation/commit/RowIdColumnConflictChecker.java index b81bbfd68128..6b414e7bb618 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/commit/RowIdColumnConflictChecker.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/commit/RowIdColumnConflictChecker.java @@ -24,7 +24,6 @@ import org.apache.paimon.types.DataField; import org.apache.paimon.types.RowType; import org.apache.paimon.utils.Range; -import org.apache.paimon.utils.RangeHelper; import java.util.ArrayList; import java.util.Collections; @@ -71,34 +70,48 @@ public static RowIdColumnConflictChecker fromDataFiles( } private List buildWriteRanges(List deltaFiles) { - List rowIdFiles = - deltaFiles.stream() - .filter(file -> file.firstRowId() != null) - .collect(Collectors.toList()); - - if (rowIdFiles.isEmpty()) { - return Collections.emptyList(); + // Only row ranges and resolved field ids survive this pass, not file statistics. + Map, Set> fieldSets = new HashMap<>(); + List ranges = new ArrayList<>(); + for (DataFileMeta file : deltaFiles) { + if (file.firstRowId() == null) { + continue; + } + Set fields = new HashSet<>(); + addWriteFieldIds(fields, file); + Set sharedFields = fieldSets.get(fields); + if (sharedFields == null) { + sharedFields = Collections.unmodifiableSet(fields); + fieldSets.put(sharedFields, sharedFields); + } + ranges.add(new WriteRange(file.nonNullRowIdRange(), sharedFields)); } - - // 1. merge overlapping ranges and calculate [Range, Set] tuples. - RangeHelper rangeHelper = new RangeHelper<>(DataFileMeta::nonNullRowIdRange); - List writeRanges = new ArrayList<>(); - for (List group : rangeHelper.mergeOverlappingRanges(rowIdFiles)) { - Range range = mergeRange(group); - Set fieldIds = new HashSet<>(); - for (DataFileMeta file : group) { - addWriteFieldIds(fieldIds, file); + ranges.sort( + Comparator.comparingLong((WriteRange r) -> r.range.from) + .thenComparingLong(r -> r.range.to)); + // Match RangeHelper's transitive overlap rule; adjacent ranges stay separate. + int size = 0; + for (WriteRange current : ranges) { + if (size > 0 && current.range.from <= ranges.get(size - 1).range.to) { + WriteRange previous = ranges.get(size - 1); + Set fields = previous.fieldIds; + if (!fields.containsAll(current.fieldIds)) { + fields = new HashSet<>(fields); + fields.addAll(current.fieldIds); + } + ranges.set( + size - 1, + new WriteRange( + new Range( + previous.range.from, + Math.max(previous.range.to, current.range.to)), + fields)); + } else { + ranges.set(size++, current); } - - writeRanges.add(new WriteRange(range, fieldIds)); } - - // 2. sort by range for binary search - writeRanges.sort( - Comparator.comparingLong((WriteRange writeRange) -> writeRange.range.from) - .thenComparingLong(writeRange -> writeRange.range.to)); - - return writeRanges; + ranges.subList(size, ranges.size()).clear(); + return ranges; } private void addWriteFieldIds(Set fieldIds, DataFileMeta file) { @@ -113,17 +126,6 @@ private void addWriteFieldIds(Set fieldIds, DataFileMeta file) { } } - private static Range mergeRange(List files) { - long from = Long.MAX_VALUE; - long to = Long.MIN_VALUE; - for (DataFileMeta file : files) { - Range range = file.nonNullRowIdRange(); - from = Math.min(from, range.from); - to = Math.max(to, range.to); - } - return new Range(from, to); - } - @Override public boolean isEmpty() { return writeRanges.isEmpty(); diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/commit/RowTrackingCommitUtils.java b/paimon-core/src/main/java/org/apache/paimon/operation/commit/RowTrackingCommitUtils.java index dc67cbfa80bd..f458c76a6d4e 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/commit/RowTrackingCommitUtils.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/commit/RowTrackingCommitUtils.java @@ -23,11 +23,15 @@ import org.apache.paimon.manifest.ManifestEntry; import org.apache.paimon.table.SpecialFields; +import org.apache.paimon.shade.guava30.com.google.common.collect.Iterators; + import java.util.ArrayList; +import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.stream.Collectors; import static org.apache.paimon.format.blob.BlobFileFormat.isBlobFile; import static org.apache.paimon.types.VectorType.isVectorStoreFile; @@ -38,17 +42,45 @@ public class RowTrackingCommitUtils { public static RowTrackingAssigned assignRowTracking( long newSnapshotId, long firstRowIdStart, List deltaFiles) { - // assigned snapshot id to delta files - List snapshotAssigned = new ArrayList<>(); - assignSnapshotId(newSnapshotId, deltaFiles, snapshotAssigned); - // assign row id for new files - List rowIdAssigned = new ArrayList<>(); - long nextRowIdStart = - assignRowTrackingMeta( - Math.max(firstRowIdStart, rowIdEnd(deltaFiles)), - snapshotAssigned, - rowIdAssigned); - return new RowTrackingAssigned(nextRowIdStart, rowIdAssigned); + long start = Math.max(firstRowIdStart, rowIdEnd(deltaFiles)); + RowTrackingAssigner assigner = new RowTrackingAssigner(start); + boolean replay = deltaFiles instanceof ReplayableList; + List assigned = replay ? null : new ArrayList<>(deltaFiles.size()); + // Validate and compute the final row-id frontier before publishing any manifests. + for (ManifestEntry entry : deltaFiles) { + ManifestEntry result = assigner.assign(assignSnapshotId(newSnapshotId, entry)); + if (!replay) { + assigned.add(result); + } + } + if (replay) { + assigned = + new ReplayableList<>( + deltaFiles.size(), + () -> { + RowTrackingAssigner replayAssigner = new RowTrackingAssigner(start); + return Iterators.transform( + deltaFiles.iterator(), + entry -> + replayAssigner.assign( + assignSnapshotId(newSnapshotId, entry))); + }); + } + return new RowTrackingAssigned(assigner.start, assigned); + } + + /** Preserves the existing partition grouping, without copying a single-partition replay. */ + public static List groupByPartition(List files) { + if (files instanceof ReplayableList + && files.stream().map(ManifestEntry::partition).distinct().limit(2).count() <= 1) { + return files; + } + return files.stream() + .collect(Collectors.groupingBy(ManifestEntry::partition)) + .values() + .stream() + .flatMap(Collection::stream) + .collect(Collectors.toList()); } /** @@ -68,41 +100,30 @@ private static long rowIdEnd(List deltaFiles) { return end; } - private static void assignSnapshotId( - long snapshotId, List deltaFiles, List snapshotAssigned) { - for (ManifestEntry entry : deltaFiles) { - long minSeqNumber = entry.file().minSequenceNumber(); - long maxSeqNumber = entry.file().maxSequenceNumber(); - if (minSeqNumber == 0L) { - // Case 1: New file (e.g., from INSERT) - // All records in this file get the current snapshot ID as sequence number - snapshotAssigned.add(entry.assignSequenceNumber(snapshotId, snapshotId)); - } else if (maxSeqNumber == 0L) { - // Case 2: File with some modified records - // - min: Preserve original sequence number (from unmodified records) - // - max: Assign current snapshot ID - snapshotAssigned.add(entry.assignSequenceNumber(minSeqNumber, snapshotId)); - } else { - // Case 3: Pure compact file (no modified records) - // Preserve original min/max sequence numbers from source files - snapshotAssigned.add(entry); - } + private static ManifestEntry assignSnapshotId(long snapshotId, ManifestEntry entry) { + long min = entry.file().minSequenceNumber(); + long max = entry.file().maxSequenceNumber(); + if (min == 0L) { + return entry.assignSequenceNumber(snapshotId, snapshotId); + } else if (max == 0L) { + return entry.assignSequenceNumber(min, snapshotId); } + return entry; } - private static long assignRowTrackingMeta( - long firstRowIdStart, - List deltaFiles, - List rowIdAssigned) { - if (deltaFiles.isEmpty()) { - return firstRowIdStart; + private static class RowTrackingAssigner { + private long start; + private long blobStartDefault; + private final Map blobStarts = new HashMap<>(); + private long vectorStoreStart; + + private RowTrackingAssigner(long start) { + this.start = start; + this.blobStartDefault = start; + this.vectorStoreStart = start; } - // assign row id for new files - long start = firstRowIdStart; - long blobStartDefault = firstRowIdStart; - Map blobStarts = new HashMap<>(); - long vectorStoreStart = firstRowIdStart; - for (ManifestEntry entry : deltaFiles) { + + private ManifestEntry assign(ManifestEntry entry) { Optional fileSource = entry.file().fileSource(); checkArgument( fileSource.isPresent(), @@ -123,8 +144,8 @@ private static long assignRowTrackingMeta( "This is a bug, blobStart %d should be less than start %d when assigning a blob entry file.", blobStart, start)); } - rowIdAssigned.add(entry.assignFirstRowId(blobStart)); blobStarts.put(blobFieldName, blobStart + rowCount); + return entry.assignFirstRowId(blobStart); } else if (isVectorStoreFile(entry.file().fileName())) { if (vectorStoreStart >= start) { throw new IllegalStateException( @@ -132,22 +153,21 @@ private static long assignRowTrackingMeta( "This is a bug, vectorStoreStart %d should be less than start %d when assigning a vector-store entry file.", vectorStoreStart, start)); } - rowIdAssigned.add(entry.assignFirstRowId(vectorStoreStart)); + long first = vectorStoreStart; vectorStoreStart += rowCount; + return entry.assignFirstRowId(first); } else { - rowIdAssigned.add(entry.assignFirstRowId(start)); + long first = start; blobStartDefault = start; blobStarts.clear(); // Skip the rows of normal files written without vector-store files. vectorStoreStart = Math.max(vectorStoreStart, start); start += rowCount; + return entry.assignFirstRowId(first); } - } else { - // for compact file, do not assign first row id. - rowIdAssigned.add(entry); } + return entry; } - return start; } /** Assigned results. */ diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/metrics/CommitStats.java b/paimon-core/src/main/java/org/apache/paimon/operation/metrics/CommitStats.java index ed53b611c2c5..449eeb4f700b 100644 --- a/paimon-core/src/main/java/org/apache/paimon/operation/metrics/CommitStats.java +++ b/paimon-core/src/main/java/org/apache/paimon/operation/metrics/CommitStats.java @@ -20,7 +20,6 @@ import org.apache.paimon.annotation.VisibleForTesting; import org.apache.paimon.data.BinaryRow; -import org.apache.paimon.io.DataFileMeta; import org.apache.paimon.manifest.FileKind; import org.apache.paimon.manifest.ManifestEntry; @@ -64,51 +63,25 @@ public CommitStats( int generatedSnapshots, int attempts, long lastCommittedSnapshotId) { - List addedTableFiles = - appendTableFiles.stream() - .filter(f -> FileKind.ADD.equals(f.kind())) - .collect(Collectors.toList()); - List deletedTableFiles = - appendTableFiles.stream() - .filter(f -> FileKind.DELETE.equals(f.kind())) - .collect(Collectors.toList()); - - List compactAfterFiles = - compactTableFiles.stream() - .filter(f -> FileKind.ADD.equals(f.kind())) - .collect(Collectors.toList()); - addedTableFiles.addAll(compactAfterFiles); - - List compactionInputFiles = - compactTableFiles.stream() - .filter(f -> FileKind.DELETE.equals(f.kind())) - .collect(Collectors.toList()); - deletedTableFiles.addAll(compactionInputFiles); - - this.compactionInputFileSize = - compactionInputFiles.stream() - .map(ManifestEntry::file) - .map(DataFileMeta::fileSize) - .reduce(Long::sum) - .orElse(0L); - this.compactionOutputFileSize = - compactAfterFiles.stream() - .map(ManifestEntry::file) - .map(DataFileMeta::fileSize) - .reduce(Long::sum) - .orElse(0L); - this.tableFilesAppended = appendTableFiles.size(); - this.tableFilesAdded = addedTableFiles.size(); - this.tableFilesDeleted = deletedTableFiles.size(); - this.tableFilesCompacted = compactTableFiles.size(); - this.changelogFilesAppended = appendChangelogFiles.size(); - this.changelogFilesCompacted = compactChangelogFiles.size(); - this.numPartitionsWritten = numChangedPartitions(appendTableFiles, compactTableFiles); - this.numBucketsWritten = numChangedBuckets(appendTableFiles, compactTableFiles); - this.changelogRecordsCompacted = getRowCounts(compactChangelogFiles); - this.deltaRecordsCompacted = getRowCounts(compactTableFiles); - this.changelogRecordsAppended = getRowCounts(appendChangelogFiles); - this.deltaRecordsAppended = getRowCounts(appendTableFiles); + Map> buckets = new LinkedHashMap<>(); + ChangeStats append = summarize(appendTableFiles, buckets); + ChangeStats compact = summarize(compactTableFiles, buckets); + ChangeStats appendLog = summarize(appendChangelogFiles, null); + ChangeStats compactLog = summarize(compactChangelogFiles, null); + this.compactionInputFileSize = compact.deletedBytes; + this.compactionOutputFileSize = compact.addedBytes; + this.tableFilesAppended = append.files; + this.tableFilesAdded = append.added + compact.added; + this.tableFilesDeleted = append.deleted + compact.deleted; + this.tableFilesCompacted = compact.files; + this.changelogFilesAppended = appendLog.files; + this.changelogFilesCompacted = compactLog.files; + this.numPartitionsWritten = buckets.size(); + this.numBucketsWritten = buckets.values().stream().mapToLong(Set::size).sum(); + this.changelogRecordsCompacted = compactLog.rows; + this.deltaRecordsCompacted = compact.rows; + this.changelogRecordsAppended = appendLog.rows; + this.deltaRecordsAppended = append.rows; this.duration = commitDuration; this.generatedSnapshots = generatedSnapshots; this.attempts = attempts; @@ -153,8 +126,34 @@ protected static Map> changedPartBuckets( return changedPartBuckets; } - private long getRowCounts(List files) { - return files.stream().mapToLong(file -> file.file().rowCount()).sum(); + private static ChangeStats summarize( + List files, Map> buckets) { + ChangeStats stats = new ChangeStats(); + for (ManifestEntry entry : files) { + stats.files++; + stats.rows += entry.file().rowCount(); + if (entry.kind() == FileKind.ADD) { + stats.added++; + stats.addedBytes += entry.file().fileSize(); + } else if (entry.kind() == FileKind.DELETE) { + stats.deleted++; + stats.deletedBytes += entry.file().fileSize(); + } + if (buckets != null) { + buckets.computeIfAbsent(entry.partition(), k -> new LinkedHashSet<>()) + .add(entry.bucket()); + } + } + return stats; + } + + private static class ChangeStats { + private long files; + private long rows; + private long added; + private long deleted; + private long addedBytes; + private long deletedBytes; } @VisibleForTesting diff --git a/paimon-core/src/main/java/org/apache/paimon/table/sink/CommitMessageList.java b/paimon-core/src/main/java/org/apache/paimon/table/sink/CommitMessageList.java new file mode 100644 index 000000000000..8dc478e6b898 --- /dev/null +++ b/paimon-core/src/main/java/org/apache/paimon/table/sink/CommitMessageList.java @@ -0,0 +1,138 @@ +/* + * 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.paimon.table.sink; + +import org.apache.paimon.shade.guava30.com.google.common.collect.Iterators; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.AbstractList; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.RandomAccess; +import java.util.function.IntFunction; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; + +/** + * Internal, read-only view of task results. Unless explicitly materialized for extensions, decoded + * messages are not cached: each traversal can release the preceding message. All serialized bytes + * and the largest single message still need to fit in memory. Callers must not modify the backing + * messages or byte arrays during commit. + */ +public final class CommitMessageList extends AbstractList implements RandomAccess { + + private final int size; + private final IntFunction getter; + private final Supplier> iterators; + private List materialized; + + private CommitMessageList( + int size, + IntFunction getter, + Supplier> iterators) { + this.size = size; + this.getter = getter; + this.iterators = iterators; + } + + public static CommitMessageList fromBytes(List messages) { + List bytes = new ArrayList<>(messages); + return new CommitMessageList( + bytes.size(), + index -> deserialize(new CommitMessageSerializer(), bytes.get(index)), + () -> { + CommitMessageSerializer serializer = new CommitMessageSerializer(); + return Iterators.transform(bytes.iterator(), b -> deserialize(serializer, b)); + }); + } + + public static CommitMessageList concat(List> messages) { + List> children = new ArrayList<>(messages); + int[] ends = new int[children.size()]; + int size = 0; + for (int i = 0; i < children.size(); i++) { + size = Math.addExact(size, children.get(i).size()); + ends[i] = size; + } + return new CommitMessageList( + size, + index -> { + int low = 0; + int high = ends.length; + while (low < high) { + int mid = (low + high) >>> 1; + if (ends[mid] <= index) { + low = mid + 1; + } else { + high = mid; + } + } + return children.get(low).get(index - (low == 0 ? 0 : ends[low - 1])); + }, + () -> Iterators.concat(Iterators.transform(children.iterator(), List::iterator))); + } + + public static CommitMessageList map( + List messages, UnaryOperator mapper) { + return new CommitMessageList( + messages.size(), + index -> mapper.apply(messages.get(index)), + () -> Iterators.transform(messages.iterator(), mapper::apply)); + } + + @Override + public int size() { + return materialized == null ? size : materialized.size(); + } + + @Override + public CommitMessage get(int index) { + if (materialized != null) { + return materialized.get(index); + } + if (index < 0 || index >= size) { + throw new IndexOutOfBoundsException("Message index: " + index + ", size: " + size); + } + return getter.apply(index); + } + + @Override + public Iterator iterator() { + return Iterators.unmodifiableIterator( + materialized == null ? iterators.get() : materialized.iterator()); + } + + /** Restores stable, mutable objects for extensions that retain or modify commit messages. */ + public List materialize() { + if (materialized == null) { + materialized = new ArrayList<>(this); + } + return materialized; + } + + private static CommitMessage deserialize(CommitMessageSerializer serializer, byte[] bytes) { + try { + return serializer.deserialize(serializer.getVersion(), bytes); + } catch (IOException e) { + throw new UncheckedIOException("Failed to deserialize commit message", e); + } + } +} diff --git a/paimon-core/src/main/java/org/apache/paimon/table/sink/TableCommitImpl.java b/paimon-core/src/main/java/org/apache/paimon/table/sink/TableCommitImpl.java index accf6e184b24..9a87a4f47656 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/sink/TableCommitImpl.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/sink/TableCommitImpl.java @@ -275,6 +275,9 @@ public int filterAndCommit(Map> commitIdentifiersAndMe private ManifestCommittable createManifestCommittable( long identifier, List commitMessages) { + if (commitMessages instanceof CommitMessageList) { + return new ManifestCommittable(identifier, null, commitMessages); + } ManifestCommittable committable = new ManifestCommittable(identifier); for (CommitMessage commitMessage : commitMessages) { committable.addFileCommittable(commitMessage); diff --git a/paimon-core/src/main/java/org/apache/paimon/table/source/DataEvolutionSplitGenerator.java b/paimon-core/src/main/java/org/apache/paimon/table/source/DataEvolutionSplitGenerator.java index c6ac2f0934f4..b4663092a4a5 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/source/DataEvolutionSplitGenerator.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/source/DataEvolutionSplitGenerator.java @@ -22,7 +22,9 @@ import org.apache.paimon.io.DataFileMeta; import org.apache.paimon.utils.BinPacking; import org.apache.paimon.utils.RangeHelper; +import org.apache.paimon.utils.ThrowingConsumer; +import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.Function; @@ -51,19 +53,7 @@ public boolean alwaysRawConvertible() { public List splitForBatch(List input) { RangeHelper rangeHelper = new RangeHelper<>(DataFileMeta::nonNullRowIdRange); List> ranges = rangeHelper.mergeOverlappingRanges(input); - Function, Long> weightFunc = - file -> - Math.max( - file.stream() - .mapToLong( - meta -> - BlobFileFormat.isBlobFile(meta.fileName()) - ? countBlobSize - ? meta.fileSize() - : openFileCost - : meta.fileSize()) - .sum(), - openFileCost); + Function, Long> weightFunc = this::rangeWeight; return BinPacking.packForOrdered(ranges, weightFunc, targetSplitSize).stream() .map( f -> { @@ -83,4 +73,94 @@ public List splitForBatch(List input) { public List splitForStreaming(List files) { return splitForBatch(files); } + + /** Packs complete, ordered RowID groups without keeping all groups until planning finishes. */ + public BatchPacker newBatchPacker( + int maxPendingFiles, ThrowingConsumer consumer) { + return new BatchPacker<>(maxPendingFiles, consumer); + } + + private long rangeWeight(List files) { + return Math.max( + files.stream() + .mapToLong( + meta -> + BlobFileFormat.isBlobFile(meta.fileName()) + ? countBlobSize ? meta.fileSize() : openFileCost + : meta.fileSize()) + .sum(), + openFileCost); + } + + /** The file cap applies between groups; a larger connected group is never cut apart. */ + public final class BatchPacker { + private final int maxPendingFiles; + private final ThrowingConsumer consumer; + private List files = new ArrayList<>(); + private long weight; + private boolean rawConvertible = true; + private boolean finished; + private boolean failed; + + private BatchPacker(int maxPendingFiles, ThrowingConsumer consumer) { + if (maxPendingFiles <= 0) { + throw new IllegalArgumentException("Pending file limit must be positive."); + } + this.maxPendingFiles = maxPendingFiles; + this.consumer = consumer; + } + + public void addRangeGroup(List group) throws E { + checkFailure(); + if (finished) { + throw new IllegalStateException("Split packing has finished."); + } + if (group.isEmpty()) { + throw new IllegalArgumentException("A RowID group must not be empty."); + } + long groupWeight = rangeWeight(group); + if (!files.isEmpty() + && (weight + groupWeight > targetSplitSize + || (long) files.size() + group.size() > maxPendingFiles)) { + flush(); + } + files.addAll(group); + weight += groupWeight; + rawConvertible &= group.size() == 1; + } + + public void finish() throws E { + checkFailure(); + if (!finished) { + finished = true; + flush(); + } + } + + private void flush() throws E { + if (files.isEmpty()) { + return; + } + SplitGroup completed = + rawConvertible + ? SplitGroup.rawConvertibleGroup(files) + : SplitGroup.nonRawConvertibleGroup(files); + files = new ArrayList<>(); + weight = 0; + rawConvertible = true; + boolean success = false; + try { + consumer.accept(completed); + success = true; + } finally { + failed = !success; + } + } + + private void checkFailure() { + if (failed) { + throw new IllegalStateException("Split packing failed; discard this plan."); + } + } + } } diff --git a/paimon-core/src/main/java/org/apache/paimon/table/source/DataFileMetaStore.java b/paimon-core/src/main/java/org/apache/paimon/table/source/DataFileMetaStore.java new file mode 100644 index 000000000000..b9e143f5541e --- /dev/null +++ b/paimon-core/src/main/java/org/apache/paimon/table/source/DataFileMetaStore.java @@ -0,0 +1,495 @@ +/* + * 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.paimon.table.source; + +import org.apache.paimon.io.DataFileMeta; +import org.apache.paimon.io.DataFileMetaSerializer; +import org.apache.paimon.io.DataInputDeserializer; +import org.apache.paimon.io.DataInputViewStreamWrapper; +import org.apache.paimon.io.DataOutputSerializer; + +import org.apache.paimon.shade.guava30.com.google.common.base.FinalizablePhantomReference; +import org.apache.paimon.shade.guava30.com.google.common.base.FinalizableReferenceQueue; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.Closeable; +import java.io.DataOutputStream; +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InterruptedIOException; +import java.io.RandomAccessFile; +import java.io.UncheckedIOException; +import java.nio.ByteBuffer; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.AbstractList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Driver-local, explicitly owned storage for replaying split metadata without retaining POJOs. + * + *

Append is single-threaded. After sealing, immutable slices support independent concurrent + * readers. The owner must outlive every traversal and Task serialization; closing invalidates all + * slices. Serialized splits contain the metadata itself, never these local file paths. + */ +public final class DataFileMetaStore implements Closeable { + + private static final Logger LOG = LoggerFactory.getLogger(DataFileMetaStore.class); + + private static final int BUFFER_SIZE = 64 * 1024; + + private final long maxDiskBytes; + private Path dataPath; + private Path indexPath; + private BufferedOutputStream dataOutput; + private DataOutputStream indexOutput; + private RandomAccessFile dataInput; + private RandomAccessFile indexInput; + private DataFileMetaSerializer writer = new DataFileMetaSerializer(); + private DataOutputSerializer encoded = new DataOutputSerializer(1024); + private int count; + private long dataBytes; + private volatile boolean sealed; + private volatile boolean closed; + private volatile CleanupReference cleanupReference; + + public DataFileMetaStore(Path directory, long maxDiskBytes) throws IOException { + if (maxDiskBytes < Long.BYTES) { + throw new IllegalArgumentException("Metadata store limit must include an end offset."); + } + this.maxDiskBytes = maxDiskBytes; + try { + dataPath = Files.createTempFile(directory, "paimon-metadata-", ".data"); + indexPath = Files.createTempFile(directory, "paimon-metadata-", ".index"); + dataOutput = new BufferedOutputStream(Files.newOutputStream(dataPath), BUFFER_SIZE); + indexOutput = + new DataOutputStream( + new BufferedOutputStream( + Files.newOutputStream(indexPath), BUFFER_SIZE)); + } catch (IOException | RuntimeException | Error failure) { + abort(failure); + throw failure; + } + } + + public void append(DataFileMeta file) throws IOException { + ensureOpen(); + if (sealed) { + throw new IllegalStateException("Metadata store is sealed."); + } + try { + if (count == Integer.MAX_VALUE) { + throw new IOException("Metadata store exceeds the maximum List size."); + } + encoded.clear(); + writer.serialize(file, encoded); + long nextDataBytes = Math.addExact(dataBytes, encoded.length()); + // Include this record's offset and the final end offset, even before sealing. + long nextIndexBytes = ((long) count + 2) * Long.BYTES; + if (nextIndexBytes > maxDiskBytes || nextDataBytes > maxDiskBytes - nextIndexBytes) { + throw new IOException("Metadata store disk limit exceeded: " + maxDiskBytes); + } + dataOutput.write(encoded.getSharedBuffer(), 0, encoded.length()); + indexOutput.writeLong(dataBytes); + dataBytes = nextDataBytes; + count++; + } catch (IOException | RuntimeException | Error failure) { + abort(failure); + throw failure; + } + } + + public void seal() throws IOException { + ensureOpen(); + if (sealed) { + return; + } + try { + indexOutput.writeLong(dataBytes); + dataOutput.close(); + indexOutput.close(); + dataInput = new RandomAccessFile(dataPath.toFile(), "r"); + indexInput = new RandomAccessFile(indexPath.toFile(), "r"); + dataOutput = null; + indexOutput = null; + writer = null; + encoded = null; + sealed = true; + } catch (IOException | RuntimeException | Error failure) { + abort(failure); + throw failure; + } + } + + public List slice(int fromInclusive, int toExclusive) { + ensureReadable(); + checkRange(fromInclusive, toExclusive, count); + return new Slice(this, fromInclusive, toExclusive - fromInclusive); + } + + /** Encoded data and index bytes, including the reserved final offset, not filesystem blocks. */ + public long serializedBytes() { + return dataBytes + ((long) count + 1) * Long.BYTES; + } + + void requireFresh() { + ensureOpen(); + if (sealed || count != 0) { + throw new IllegalStateException("Metadata output store must be fresh and writable."); + } + } + + /** + * Enables backup cleanup for a sealed plan whose lifetime follows its reachable slices. + * Explicit owners should still close promptly. Collection and backup cleanup have no timing + * guarantee; this is not a substitute for a disk budget or planning-failure cleanup. + */ + public synchronized DataFileMetaStore withAutomaticCleanup() { + ensureReadable(); + if (cleanupReference == null) { + cleanupReference = + new CleanupReference(this, dataInput, indexInput, dataPath, indexPath); + } + return this; + } + + private void ensureOpen() { + if (closed) { + throw new IllegalStateException("Metadata store is closed."); + } + } + + private void ensureReadable() { + ensureOpen(); + if (!sealed) { + throw new IllegalStateException("Metadata store must be sealed before reading."); + } + } + + private long offset(int record) throws IOException { + ByteBuffer offset = ByteBuffer.allocate(Long.BYTES); + readFully(indexInput, offset.array(), (long) record * Long.BYTES); + return offset.getLong(0); + } + + private void checkOffsets(long from, long to) throws IOException { + if (from < 0 || to <= from || to > dataBytes) { + throw new IOException("Invalid metadata store offsets: " + from + ", " + to); + } + } + + private DataFileMeta get(int record) { + ensureReadable(); + try { + long from = offset(record); + long to = offset(record + 1); + checkOffsets(from, to); + if (to - from > Integer.MAX_VALUE) { + throw new IOException("Metadata record exceeds the maximum array size."); + } + byte[] bytes = new byte[(int) (to - from)]; + readFully(dataInput, bytes, from); + return new DataFileMetaSerializer().deserialize(new DataInputDeserializer(bytes)); + } catch (IOException failure) { + throw new UncheckedIOException(failure); + } finally { + keepAlive(); + } + } + + private Iterator iterator(int fromRecord, int size) { + ensureReadable(); + if (size == 0) { + return Collections.emptyList().iterator(); + } + try { + long from = offset(fromRecord); + long to = offset(fromRecord + size); + checkOffsets(from, to); + DataInputViewStreamWrapper input = + new DataInputViewStreamWrapper( + new BufferedInputStream(rangeInput(from, to), BUFFER_SIZE)); + return new Iterator() { + private final DataFileMetaSerializer reader = new DataFileMetaSerializer(); + private int remaining = size; + + @Override + public boolean hasNext() { + ensureReadable(); + return remaining > 0; + } + + @Override + public DataFileMeta next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + try { + checkInterrupted(); + DataFileMeta value = reader.deserialize(input); + checkInterrupted(); + remaining--; + return value; + } catch (IOException failure) { + throw new UncheckedIOException(failure); + } finally { + keepAlive(); + } + } + }; + } catch (IOException failure) { + throw new UncheckedIOException(failure); + } + } + + private InputStream rangeInput(long from, long to) { + // Iterators retain only their logical position and buffer, never an extra file handle. + return new InputStream() { + private long position = from; + + @Override + public int read() throws IOException { + byte[] one = new byte[1]; + return read(one, 0, 1) < 0 ? -1 : one[0] & 0xff; + } + + @Override + public int read(byte[] bytes, int offset, int length) throws IOException { + ensureReadable(); + if (offset < 0 || length < 0 || offset > bytes.length - length) { + throw new IndexOutOfBoundsException(); + } + if (length == 0) { + return 0; + } + if (position == to) { + return -1; + } + int requested = (int) Math.min(length, to - position); + int read = readAt(dataInput, bytes, offset, requested, position); + if (read <= 0) { + throw new EOFException("Incomplete metadata store data."); + } + position += read; + return read; + } + }; + } + + private void readFully(RandomAccessFile input, byte[] bytes, long position) throws IOException { + int offset = 0; + while (offset < bytes.length) { + int read = readAt(input, bytes, offset, bytes.length - offset, position + offset); + if (read <= 0) { + throw new EOFException("Incomplete metadata store record or index."); + } + offset += read; + } + } + + private synchronized int readAt( + RandomAccessFile input, byte[] bytes, int offset, int length, long position) + throws IOException { + ensureReadable(); + checkInterrupted(); + // RAF reads cannot close shared handles on interruption. Serialize seeks with reads and + // owner close; bound each read so cancellation is checked between chunks. + input.seek(position); + int read = input.read(bytes, offset, Math.min(length, BUFFER_SIZE)); + checkInterrupted(); + return read; + } + + private static void checkInterrupted() throws InterruptedIOException { + if (Thread.currentThread().isInterrupted()) { + throw new InterruptedIOException("Metadata replay interrupted."); + } + } + + private void abort(Throwable failure) { + try { + close(); + } catch (IOException cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + } + + private void keepAlive() { + if (cleanupReference != null) { + // JDK 8 has no reachabilityFence. Keep the owner alive until its last file I/O. + synchronized (this) { + // Acquiring the owner's monitor is the reachability barrier. + } + } + } + + @Override + public synchronized void close() throws IOException { + closed = true; + writer = null; + encoded = null; + if (cleanupReference != null) { + cleanupReference.close(); + return; + } + closeResources( + new Closeable[] {dataOutput, indexOutput, dataInput, indexInput}, + new Path[] {dataPath, indexPath}); + } + + private static void closeResources(Closeable[] resources, Path[] paths) throws IOException { + IOException failure = null; + for (Closeable resource : resources) { + try { + if (resource != null) { + resource.close(); + } + } catch (IOException cleanupFailure) { + if (failure == null) { + failure = cleanupFailure; + } else { + failure.addSuppressed(cleanupFailure); + } + } + } + for (Path path : paths) { + try { + if (path != null) { + Files.deleteIfExists(path); + } + } catch (IOException cleanupFailure) { + if (failure == null) { + failure = cleanupFailure; + } else { + failure.addSuppressed(cleanupFailure); + } + } + } + if (failure != null) { + throw failure; + } + } + + private static final class CleanupHolder { + private static final Set REFERENCES = ConcurrentHashMap.newKeySet(); + private static final FinalizableReferenceQueue QUEUE = new FinalizableReferenceQueue(); + } + + /** Only independent resources may be retained here, never a store, slice or reader. */ + private static final class CleanupReference + extends FinalizablePhantomReference implements Closeable { + private final Closeable[] resources; + private final Path[] paths; + private boolean cleaned; + + private CleanupReference( + DataFileMetaStore owner, + RandomAccessFile data, + RandomAccessFile index, + Path dataPath, + Path indexPath) { + super(owner, CleanupHolder.QUEUE); + resources = new Closeable[] {data, index}; + paths = new Path[] {dataPath, indexPath}; + CleanupHolder.REFERENCES.add(this); + } + + @Override + public synchronized void close() throws IOException { + if (!cleaned) { + closeResources(resources, paths); + cleaned = true; + CleanupHolder.REFERENCES.remove(this); + clear(); + } + } + + @Override + public void finalizeReferent() { + try { + close(); + } catch (IOException failure) { + LOG.warn("Could not clean up unreachable metadata replay files.", failure); + } finally { + CleanupHolder.REFERENCES.remove(this); + clear(); + } + } + } + + static List retainOrCopy(List files) { + if (files instanceof Slice) { + ((Slice) files).store.ensureReadable(); + return files; + } + return new java.util.ArrayList<>(files); + } + + private static void checkRange(int from, int to, int size) { + if (from < 0 || to < from || to > size) { + throw new IndexOutOfBoundsException("Range " + from + ":" + to + ", size " + size); + } + } + + private static final class Slice extends AbstractList { + private final DataFileMetaStore store; + private final int start; + private final int size; + + private Slice(DataFileMetaStore store, int start, int size) { + this.store = store; + this.start = start; + this.size = size; + } + + @Override + public int size() { + return size; + } + + @Override + public DataFileMeta get(int index) { + if (index < 0 || index >= size) { + throw new IndexOutOfBoundsException("Index " + index + ", size " + size); + } + return store.get(start + index); + } + + @Override + public Iterator iterator() { + return store.iterator(start, size); + } + + @Override + public List subList(int fromIndex, int toIndex) { + checkRange(fromIndex, toIndex, size); + return store.slice(start + fromIndex, start + toIndex); + } + } +} diff --git a/paimon-core/src/main/java/org/apache/paimon/table/source/DataSplit.java b/paimon-core/src/main/java/org/apache/paimon/table/source/DataSplit.java index 87b244db57f6..09467b1734e0 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/source/DataSplit.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/source/DataSplit.java @@ -336,6 +336,70 @@ public Optional filterDataFile(Predicate filter) { return Optional.of(split); } + /** + * Filters files into one fresh caller-owned replay store without retaining decoded metadata. + * The caller must keep the store open through every use of the returned splits. A failed filter + * discards its partial output; an already-used store is rejected without closing it. + */ + public static List filterDataFiles( + List splits, Predicate filter, DataFileMetaStore store) + throws IOException { + store.requireFresh(); + try { + List selected = new ArrayList<>(); + int nextFile = 0; + for (DataSplit source : splits) { + int start = nextFile; + List deletions = + source.dataDeletionFiles == null ? null : new ArrayList<>(); + int index = 0; + for (DataFileMeta file : source.dataFiles) { + if (filter.test(file)) { + store.append(file); + nextFile++; + if (deletions != null) { + deletions.add(source.dataDeletionFiles.get(index)); + } + } + index++; + } + if (nextFile > start) { + DataSplit split = new DataSplit(); + split.assign(source); + split.dataFiles = null; + split.dataDeletionFiles = deletions; + selected.add(new FilteredSplit(split, start, nextFile)); + } + } + store.seal(); + List result = new ArrayList<>(selected.size()); + for (FilteredSplit selectedSplit : selected) { + selectedSplit.split.dataFiles = store.slice(selectedSplit.start, selectedSplit.end); + result.add(selectedSplit.split); + } + return result; + } catch (IOException | RuntimeException | Error failure) { + try { + store.close(); + } catch (IOException cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + throw failure; + } + } + + private static final class FilteredSplit { + private final DataSplit split; + private final int start; + private final int end; + + private FilteredSplit(DataSplit split, int start, int end) { + this.split = split; + this.start = start; + this.end = end; + } + } + @Override public boolean equals(Object o) { if (this == o) { @@ -568,7 +632,7 @@ public Builder withTotalBuckets(Integer totalBuckets) { } public Builder withDataFiles(List dataFiles) { - this.split.dataFiles = new ArrayList<>(dataFiles); + this.split.dataFiles = DataFileMetaStore.retainOrCopy(dataFiles); return this; } diff --git a/paimon-core/src/main/java/org/apache/paimon/table/source/ReadBuilder.java b/paimon-core/src/main/java/org/apache/paimon/table/source/ReadBuilder.java index a83dd59de90e..9abd07728703 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/source/ReadBuilder.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/source/ReadBuilder.java @@ -24,6 +24,7 @@ import org.apache.paimon.predicate.Predicate; import org.apache.paimon.predicate.PredicateBuilder; import org.apache.paimon.predicate.TopN; +import org.apache.paimon.table.FileStoreTable; import org.apache.paimon.types.RowType; import org.apache.paimon.utils.Filter; import org.apache.paimon.utils.Range; @@ -186,6 +187,14 @@ default ReadBuilder withLimit(long limit) { /** Create a {@link TableScan} to perform batch planning. */ TableScan newScan(); + /** + * Creates a Driver-side batch scan with a custom snapshot reader. The factory is used only + * during this call and must not become part of this serializable builder. + */ + default TableScan newScan(FileStoreTable.SnapshotReaderFactory snapshotReaderFactory) { + throw new UnsupportedOperationException("Custom snapshot readers are not supported."); + } + /** Create a {@link TableScan} to perform streaming planning. */ StreamTableScan newStreamScan(); diff --git a/paimon-core/src/main/java/org/apache/paimon/table/source/ReadBuilderImpl.java b/paimon-core/src/main/java/org/apache/paimon/table/source/ReadBuilderImpl.java index 51c76d71839b..f2849ef674f5 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/source/ReadBuilderImpl.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/source/ReadBuilderImpl.java @@ -29,6 +29,7 @@ import org.apache.paimon.reader.ReadBatchSizer; import org.apache.paimon.reader.RecordReader; import org.apache.paimon.reader.RecordReader.RecordIterator; +import org.apache.paimon.table.FileStoreTable; import org.apache.paimon.table.InnerTable; import org.apache.paimon.types.RowType; import org.apache.paimon.utils.Filter; @@ -199,8 +200,21 @@ public ReadBuilder dropStats() { @Override public TableScan newScan() { + return configureBatchScan(table.newScan()); + } + + @Override + public TableScan newScan(FileStoreTable.SnapshotReaderFactory snapshotReaderFactory) { + if (!(table instanceof FileStoreTable)) { + throw new UnsupportedOperationException( + "Custom snapshot readers require a file store table."); + } + return configureBatchScan(((FileStoreTable) table).newScan(snapshotReaderFactory)); + } + + private TableScan configureBatchScan(InnerTableScan scan) { Long limit = effectiveLimit(); - InnerTableScan tableScan = configureScan(table.newScan()); + InnerTableScan tableScan = configureScan(scan); if (limit != null) { tableScan.withLimit(limit); } 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..b7d9dd9955a3 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 @@ -21,6 +21,7 @@ import org.apache.paimon.Snapshot; import org.apache.paimon.consumer.ConsumerManager; import org.apache.paimon.data.BinaryRow; +import org.apache.paimon.disk.IOManager; import org.apache.paimon.index.IndexFileHandler; import org.apache.paimon.manifest.BucketEntry; import org.apache.paimon.manifest.ManifestEntry; @@ -30,6 +31,7 @@ import org.apache.paimon.operation.ManifestsReader; import org.apache.paimon.partition.PartitionPredicate; import org.apache.paimon.predicate.Predicate; +import org.apache.paimon.table.source.DataFileMetaStore; import org.apache.paimon.table.source.DataSplit; import org.apache.paimon.table.source.ScanMode; import org.apache.paimon.table.source.Split; @@ -140,6 +142,23 @@ public interface SnapshotReader { /** Get splits plan from snapshot. */ Plan read(); + /** + * Configures one batch {@link #read()} to use fresh caller-owned resources, preserving the + * surrounding table scan lifecycle. Register the store with its owner before planning: auth can + * fail before this reader is called. The owner must outlive all uses of the returned plan. + */ + default SnapshotReader withIncrementalPlanning(DataFileMetaStore store, IOManager ioManager) { + throw new UnsupportedOperationException("This snapshot reader cannot plan incrementally."); + } + + /** + * Plans a DE batch read into a fresh caller-owned metadata store. The caller must retain the + * sealed store through every use and serialization of the resulting splits, then close it. + */ + default Plan readIncrementally(DataFileMetaStore store, IOManager ioManager) throws Exception { + throw new UnsupportedOperationException("This snapshot reader cannot plan incrementally."); + } + /** Get splits plan from file changes. */ Plan readChanges(); 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 934e8d39e525..c34c93f8007a 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 @@ -25,6 +25,7 @@ import org.apache.paimon.consumer.ConsumerManager; import org.apache.paimon.data.BinaryRow; import org.apache.paimon.deletionvectors.DeletionVectorsIndexFile; +import org.apache.paimon.disk.IOManager; import org.apache.paimon.fs.Path; import org.apache.paimon.index.DeletionVectorMeta; import org.apache.paimon.index.IndexFileHandler; @@ -36,6 +37,7 @@ import org.apache.paimon.manifest.ManifestFileMeta; import org.apache.paimon.manifest.PartitionEntry; import org.apache.paimon.metrics.MetricRegistry; +import org.apache.paimon.operation.DataEvolutionFileStoreScan; import org.apache.paimon.operation.FileStoreScan; import org.apache.paimon.operation.ManifestsReader; import org.apache.paimon.operation.metrics.CacheMetrics; @@ -46,6 +48,8 @@ import org.apache.paimon.predicate.PredicateBuilder; import org.apache.paimon.schema.TableSchema; import org.apache.paimon.table.BucketMode; +import org.apache.paimon.table.source.DataEvolutionSplitGenerator; +import org.apache.paimon.table.source.DataFileMetaStore; import org.apache.paimon.table.source.DataSplit; import org.apache.paimon.table.source.DeletionFile; import org.apache.paimon.table.source.IncrementalSplit; @@ -62,11 +66,13 @@ import org.apache.paimon.utils.LazyField; import org.apache.paimon.utils.Pair; import org.apache.paimon.utils.Range; +import org.apache.paimon.utils.RangeHelper; import org.apache.paimon.utils.RowRangeIndex; import org.apache.paimon.utils.SnapshotManager; import javax.annotation.Nullable; +import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -90,6 +96,8 @@ /** Implementation of {@link SnapshotReader}. */ public class SnapshotReaderImpl implements SnapshotReader { + private static final int INCREMENTAL_PENDING_FILE_LIMIT = 1024; + private final FileStoreScan scan; private final TableSchema tableSchema; private final CoreOptions options; @@ -108,6 +116,9 @@ public class SnapshotReaderImpl implements SnapshotReader { private boolean hasNonPartitionFilter; private RecordComparator lazyPartitionComparator; private CacheMetrics dvMetaCacheMetrics; + @Nullable private DataFileMetaStore incrementalStore; + @Nullable private IOManager incrementalIoManager; + private boolean incrementalRead; public SnapshotReaderImpl( FileStoreScan scan, @@ -395,6 +406,23 @@ public SnapshotReader withShard(int indexOfThisSubtask, int numberOfParallelSubt /** Get splits from {@link FileKind#ADD} files. */ @Override public Plan read() { + if (incrementalStore != null) { + if (incrementalRead) { + throw new IllegalStateException("Incremental metadata planning is single use."); + } + incrementalRead = true; + try { + return readIncrementally(incrementalStore, incrementalIoManager); + } catch (RuntimeException failure) { + throw failure; + } catch (Exception failure) { + throw new RuntimeException(failure); + } + } + return readPlan(); + } + + private Plan readPlan() { FileStoreScan.Plan plan = scan.plan(); @Nullable Snapshot snapshot = plan.snapshot(); @@ -413,6 +441,199 @@ public Plan read() { plan.watermark(), snapshot == null ? null : snapshot.id(), snapshot, (List) splits); } + @Override + public SnapshotReader withIncrementalPlanning(DataFileMetaStore store, IOManager ioManager) { + if (incrementalStore != null) { + throw new IllegalStateException("Incremental metadata resources are already bound."); + } + Objects.requireNonNull(store, "Metadata store"); + Objects.requireNonNull(ioManager, "IO manager"); + incrementalStore = store; + incrementalIoManager = ioManager; + return this; + } + + @Override + public Plan readIncrementally(DataFileMetaStore store, IOManager ioManager) throws Exception { + try { + if (!(scan instanceof DataEvolutionFileStoreScan) + || !(splitGenerator instanceof DataEvolutionSplitGenerator) + || scanMode != ScanMode.ALL) { + throw new UnsupportedOperationException( + "Incremental metadata planning requires a DE batch ALL scan."); + } + // The external sorter needs three pages; smaller valid budgets keep ordinary planning. + if (options.sortSpillBufferSize() / options.pageSize() < 3) { + Plan plan = readPlan(); + store.seal(); + return plan; + } + IncrementalSplitPlanner planner = new IncrementalSplitPlanner(store); + Snapshot snapshot = + ((DataEvolutionFileStoreScan) scan) + .forEachFileGroup(ioManager, planner::accept); + planner.finish(); + store.seal(); + if (options.scanPlanSortPartition()) { + planner.splits.sort( + (left, right) -> + partitionComparator() + .compare(left.bucket.partition, right.bucket.partition)); + } + Set> buckets = new HashSet<>(); + for (SpilledSplit split : planner.splits) { + buckets.add(Pair.of(split.bucket.partition, split.bucket.bucket)); + } + Map, Map> deletions = + deletionVectors ? scanDvIndex(snapshot, buckets) : Collections.emptyMap(); + List splits = new ArrayList<>(); + for (SpilledSplit split : planner.splits) { + List files = store.slice(split.start, split.start + split.count); + IncrementalBucket bucket = split.bucket; + DataSplit.Builder builder = + DataSplit.builder() + .withSnapshot( + snapshot == null ? FIRST_SNAPSHOT_ID - 1 : snapshot.id()) + .withPartition(bucket.partition) + .withBucket(bucket.bucket) + .withTotalBuckets(bucket.totalBuckets) + .withBucketPath(bucket.path) + .withDataFiles(files) + .rawConvertible(split.rawConvertible); + if (deletionVectors) { + builder.withDataDeletionFiles( + getDeletionFiles( + files, + deletions.getOrDefault( + Pair.of(bucket.partition, bucket.bucket), + Collections.emptyMap()))); + } + splits.add(builder.build()); + } + return new PlanImpl( + snapshot == null ? null : snapshot.watermark(), + snapshot == null ? null : snapshot.id(), + snapshot, + splits); + } catch (Exception | Error failure) { + try { + store.close(); + } catch (IOException cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + throw failure; + } + } + + private final class IncrementalSplitPlanner { + private final DataFileMetaStore store; + private final List splits = new ArrayList<>(); + private final Map, IncrementalBucket> pending = + new LinkedHashMap<>(16, 0.75f, true); + private long pendingFiles; + private int nextFile; + + private IncrementalSplitPlanner(DataFileMetaStore store) { + this.store = store; + } + + private void accept(List group) throws IOException { + // Partition only after the complete global group has been filtered. Providers from + // one partition may be interleaved with another partition in the group's source order. + Map>> partitions = groupByPartFiles(group); + for (Map.Entry>> partition : + partitions.entrySet()) { + for (Map.Entry> bucket : + partition.getValue().entrySet()) { + Pair key = Pair.of(partition.getKey(), bucket.getKey()); + IncrementalBucket target = pending.get(key); + if (target == null) { + target = + new IncrementalBucket( + partition.getKey(), + bucket.getKey(), + bucket.getValue().get(0).totalBuckets(), + pathFactory + .bucketPath(partition.getKey(), bucket.getKey()) + .toString()); + IncrementalBucket spillBucket = target; + target.packer = + ((DataEvolutionSplitGenerator) splitGenerator) + .newBatchPacker( + INCREMENTAL_PENDING_FILE_LIMIT, + split -> spill(spillBucket, split)); + pending.put(key, target); + } + List files = + bucket.getValue().stream() + .map(ManifestEntry::file) + .collect(Collectors.toList()); + RangeHelper ranges = + new RangeHelper<>(DataFileMeta::nonNullRowIdRange); + for (List range : ranges.mergeOverlappingRanges(files)) { + pendingFiles += range.size(); + target.packer.addRangeGroup(range); + } + // Bound all partitions together, but only evict complete RowID groups. + while (pendingFiles > INCREMENTAL_PENDING_FILE_LIMIT) { + Iterator oldest = pending.values().iterator(); + IncrementalBucket evicted = oldest.next(); + oldest.remove(); + evicted.packer.finish(); + } + } + } + } + + private void spill(IncrementalBucket bucket, SplitGenerator.SplitGroup group) + throws IOException { + pendingFiles -= group.files.size(); + int start = nextFile; + for (DataFileMeta file : group.files) { + store.append(file); + nextFile++; + } + splits.add(new SpilledSplit(bucket, start, nextFile - start, group.rawConvertible)); + } + + private void finish() throws IOException { + for (IncrementalBucket bucket : pending.values()) { + bucket.packer.finish(); + } + pending.clear(); + } + } + + private static final class IncrementalBucket { + private final BinaryRow partition; + private final int bucket; + private final int totalBuckets; + private final String path; + private DataEvolutionSplitGenerator.BatchPacker packer; + + private IncrementalBucket(BinaryRow partition, int bucket, int totalBuckets, String path) { + this.partition = partition; + this.bucket = bucket; + this.totalBuckets = totalBuckets; + this.path = path; + } + } + + private static final class SpilledSplit { + private final IncrementalBucket bucket; + private final int start; + private final int count; + private final boolean rawConvertible; + + private SpilledSplit( + IncrementalBucket bucket, int start, int count, boolean rawConvertible) { + this.bucket = bucket; + this.start = start; + this.count = count; + this.rawConvertible = rawConvertible; + } + } + private List generateSplits( @Nullable Snapshot snapshot, boolean isStreaming, @@ -510,8 +731,28 @@ public Iterator readFileIterator() { return scan.readFileIterator(); } + private void requireMaterializedChanges() { + if (incrementalStore == null) { + return; + } + UnsupportedOperationException failure = + new UnsupportedOperationException( + "Incremental metadata planning requires a DE batch ALL scan."); + // Reject a new operation without invalidating a previously returned plan. + if (!incrementalRead) { + incrementalRead = true; + try { + incrementalStore.close(); + } catch (IOException cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + } + throw failure; + } + @Override public Plan readChanges() { + requireMaterializedChanges(); withMode(ScanMode.DELTA); FileStoreScan.Plan plan = scan.plan(); @@ -640,6 +881,7 @@ private Plan toIncrementalPlan( @Override public Plan readIncrementalDiff(Snapshot before) { + requireMaterializedChanges(); withMode(ScanMode.ALL); FileStoreScan.Plan plan = scan.plan(); Map>> afterFiles = diff --git a/paimon-core/src/test/java/org/apache/paimon/DataEvolutionMetadataMemoryOptionsTest.java b/paimon-core/src/test/java/org/apache/paimon/DataEvolutionMetadataMemoryOptionsTest.java new file mode 100644 index 000000000000..ce1b1f041ea2 --- /dev/null +++ b/paimon-core/src/test/java/org/apache/paimon/DataEvolutionMetadataMemoryOptionsTest.java @@ -0,0 +1,116 @@ +/* + * 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.paimon; + +import org.apache.paimon.CoreOptions.DataEvolutionMetadataMemoryMode; +import org.apache.paimon.options.Options; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** Explicit modes for manually enabled metadata memory optimization. */ +class DataEvolutionMetadataMemoryOptionsTest { + + private static final String MODE = "data-evolution.metadata-memory-optimization.mode"; + + @Test + void testDefaultRemainsOff() { + CoreOptions core = new CoreOptions(deOptions()); + assertThat(core.dataEvolutionMetadataMemoryMode()) + .isEqualTo(DataEvolutionMetadataMemoryMode.OFF); + assertThat(core.dataEvolutionMetadataMemoryOptimizationEnabled()).isFalse(); + assertThat(core.dataEvolutionMetadataStreamingEnabled()).isFalse(); + } + + @Test + void testExplicitModes() { + for (DataEvolutionMetadataMemoryMode mode : DataEvolutionMetadataMemoryMode.values()) { + Options options = deOptions(); + options.setString(MODE, mode.toString()); + CoreOptions core = new CoreOptions(options); + assertThat(core.dataEvolutionMetadataMemoryMode()).isEqualTo(mode); + assertThat(core.dataEvolutionMetadataMemoryOptimizationEnabled()) + .isEqualTo(mode != DataEvolutionMetadataMemoryMode.OFF); + assertThat(core.dataEvolutionMetadataStreamingEnabled()) + .isEqualTo(mode == DataEvolutionMetadataMemoryMode.STREAMING); + } + } + + @Test + void testModeParsingUsesExistingCaseInsensitiveEnumRules() { + Options options = deOptions(); + options.setString(MODE, "StReAmInG"); + CoreOptions core = new CoreOptions(options); + assertThat(core.dataEvolutionMetadataMemoryMode()) + .isEqualTo(DataEvolutionMetadataMemoryMode.STREAMING); + assertThat(core.dataEvolutionMetadataStreamingEnabled()).isTrue(); + } + + @Test + void testInvalidModeDoesNotSilentlyFallBack() { + Options options = deOptions(); + options.setString(MODE, "automatic"); + assertThatThrownBy(() -> new CoreOptions(options).dataEvolutionMetadataMemoryMode()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(MODE) + .hasMessageContaining("automatic") + .cause() + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("off") + .hasMessageContaining("lightweight") + .hasMessageContaining("streaming"); + } + + @Test + void testNonDataEvolutionTablesDoNotEnableEitherPath() { + for (DataEvolutionMetadataMemoryMode mode : DataEvolutionMetadataMemoryMode.values()) { + Options options = new Options(); + options.setString(MODE, mode.toString()); + CoreOptions core = new CoreOptions(options); + assertThat(core.dataEvolutionMetadataMemoryMode()) + .isEqualTo(DataEvolutionMetadataMemoryMode.OFF); + assertThat(core.dataEvolutionMetadataMemoryOptimizationEnabled()).isFalse(); + assertThat(core.dataEvolutionMetadataStreamingEnabled()).isFalse(); + } + } + + @Test + void testReplayDiskBudgetHasAValidatedExplicitLimit() { + Options options = deOptions(); + CoreOptions core = new CoreOptions(options); + assertThat(core.dataEvolutionMetadataMaxDiskSize()).isEqualTo(1024L * 1024 * 1024); + String key = "data-evolution.metadata-memory-optimization.max-disk-size"; + options.setString(key, "8 b"); + assertThat(core.dataEvolutionMetadataMaxDiskSize()).isEqualTo(8L); + for (String invalid : new String[] {"0 b", "7 b"}) { + options.setString(key, invalid); + assertThatThrownBy(core::dataEvolutionMetadataMaxDiskSize) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(key); + } + } + + private static Options deOptions() { + Options options = new Options(); + options.set(CoreOptions.DATA_EVOLUTION_ENABLED, true); + return options; + } +} diff --git a/paimon-core/src/test/java/org/apache/paimon/io/DataFileMetaSerializerTest.java b/paimon-core/src/test/java/org/apache/paimon/io/DataFileMetaSerializerTest.java index d7f1c1bbf7ec..1a99f77a8eb6 100644 --- a/paimon-core/src/test/java/org/apache/paimon/io/DataFileMetaSerializerTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/io/DataFileMetaSerializerTest.java @@ -18,14 +18,18 @@ package org.apache.paimon.io; +import org.apache.paimon.manifest.FileSource; import org.apache.paimon.utils.ObjectSerializerTestBase; import org.junit.jupiter.api.Test; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; /** Tests for {@link DataFileMetaSerializer}. */ public class DataFileMetaSerializerTest extends ObjectSerializerTestBase { @@ -57,6 +61,79 @@ void testCopyOperationsPreserveWriteColsSequences() { assertWriteColsSequences(file.copy(Collections.emptyList())); assertWriteColsSequences(file.newExternalPath("external/renamed.parquet")); assertWriteColsSequences(file.copy(new byte[] {1})); + assertWriteColsSequences(file.withWriteCols(Arrays.asList("first", "second"))); + } + + @Test + void testWriteColumnCopyPreservesMetadataAndSerialization() { + DataFileMeta original = metadataWithAllFields(); + List sharedNames = new ArrayList<>(Arrays.asList("f0", "nested.f1", "f0", "F0")); + DataFileMeta copy = original.withWriteCols(sharedNames); + assertThat(copy).isEqualTo(original); + assertThat(copy.hashCode()).isEqualTo(original.hashCode()); + assertThat(copy.writeCols()).isNotSameAs(original.writeCols()); + assertThat(copy.writeCols().get(0)).isSameAs(sharedNames.get(0)); + assertThat(copy.writeColsSequences()).containsExactly(3L, 42L, 43L, 50L); + assertThat(serializer().fromRow(serializer().toRow(copy))).isEqualTo(original); + assertThat(copy.withWriteCols(null).writeCols()).isNull(); + assertThat(copy.withWriteCols(Collections.emptyList()).writeCols()).isEmpty(); + copy.writeCols().set(0, "changed"); + assertThat(original.writeCols()).containsExactly("f0", "nested.f1", "f0", "F0"); + } + + @Test + void testDefaultWriteColumnCopyMatchesPojo() { + DataFileMeta original = metadataWithAllFields(); + DataFileMeta external = + mock( + DataFileMeta.class, + invocation -> { + if (invocation.getMethod().getName().equals("withWriteCols")) { + return invocation.callRealMethod(); + } + return invocation + .getMethod() + .invoke(original, invocation.getArguments()); + }); + for (List names : + Arrays.>asList( + null, + Collections.emptyList(), + Arrays.asList("f0", "nested.f1", "f0", "F0"))) { + DataFileMeta copy = external.withWriteCols(names); + assertThat(copy).isEqualTo(original.withWriteCols(names)); + assertThat(serializer().fromRow(serializer().toRow(copy))).isEqualTo(copy); + } + } + + private DataFileMeta metadataWithAllFields() { + DataFileMeta template = object(); + return DataFileMeta.create( + "columns.parquet", + 123L, + 5L, + template.minKey(), + template.maxKey(), + template.keyStats(), + template.valueStats(), + 11L, + 99L, + 7L, + 2, + Arrays.asList("extra-1", "extra-2"), + template.creationTime(), + 1L, + new byte[] {1, 2}, + FileSource.COMPACT, + Collections.singletonList("stats-column"), + "external/columns.parquet", + 100L, + Arrays.asList( + new String("f0"), + new String("nested.f1"), + new String("f0"), + new String("F0")), + new long[] {3L, 42L, 43L, 50L}); } @Test diff --git a/paimon-core/src/test/java/org/apache/paimon/io/ProjectedDataFileMetaTest.java b/paimon-core/src/test/java/org/apache/paimon/io/ProjectedDataFileMetaTest.java index f1d6b35bbd96..fff8f9500cc2 100644 --- a/paimon-core/src/test/java/org/apache/paimon/io/ProjectedDataFileMetaTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/io/ProjectedDataFileMetaTest.java @@ -106,6 +106,9 @@ void testImplementsProjectedDataFileMeta() { assertUnsupported( () -> actual.withWriteColsSequences(new long[] {2L}), "withWriteColsSequences(long[])"); + assertUnsupported( + () -> actual.withWriteCols(Collections.singletonList("other")), + "withWriteCols(List)"); assertUnsupported(() -> actual.assignFirstRowId(20L), "assignFirstRowId(long)"); assertUnsupported(() -> actual.newFirstRowId(20L), "newFirstRowId(Long)"); assertUnsupported(() -> actual.copy(Collections.emptyList()), "copy(List)"); diff --git a/paimon-core/src/test/java/org/apache/paimon/manifest/ManifestFileTest.java b/paimon-core/src/test/java/org/apache/paimon/manifest/ManifestFileTest.java index e48a352da1d1..b4e1b354a8e7 100644 --- a/paimon-core/src/test/java/org/apache/paimon/manifest/ManifestFileTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/manifest/ManifestFileTest.java @@ -19,6 +19,7 @@ package org.apache.paimon.manifest; import org.apache.paimon.CoreOptions; +import org.apache.paimon.CoreOptions.DataEvolutionMetadataMemoryMode; import org.apache.paimon.data.BinaryRow; import org.apache.paimon.data.GenericRow; import org.apache.paimon.data.InternalRow; @@ -35,13 +36,17 @@ import org.apache.paimon.io.DataFileMeta; import org.apache.paimon.io.DataFileMetaWriteColsLegacySerializer; import org.apache.paimon.operation.AppendOnlyFileStoreScan; +import org.apache.paimon.operation.DataEvolutionFileStoreScan; import org.apache.paimon.operation.ManifestsReader; import org.apache.paimon.operation.metrics.CacheMetrics; import org.apache.paimon.options.MemorySize; import org.apache.paimon.options.Options; import org.apache.paimon.partition.PartitionPredicate; +import org.apache.paimon.predicate.PredicateBuilder; import org.apache.paimon.schema.FileSystemSchemaManager; +import org.apache.paimon.schema.Schema; import org.apache.paimon.schema.TableSchema; +import org.apache.paimon.stats.SimpleStats; import org.apache.paimon.stats.StatsTestUtils; import org.apache.paimon.types.DataField; import org.apache.paimon.types.DataType; @@ -2159,6 +2164,118 @@ public int read(byte[] buffer, int offset, int length) throws IOException { } } + @ParameterizedTest + @MethodSource("dataEvolutionMetadataModes") + void testDataEvolutionDropsUnneededStatsBeforeManifestResults( + Boolean enabled, String cacheMode) { + Options options = dataEvolutionMetadataOptions(enabled); + RecordingFileIO io = new RecordingFileIO(); + ManifestFile.Factory factory = dataEvolutionMetadataFactory(options, cacheMode, io); + ManifestFile manifests = factory.create(); + ManifestEntry entry = gen.next(); + assertThat(entry.file().valueStats()).isNotEqualTo(SimpleStats.EMPTY_STATS); + ManifestFileMeta meta = manifests.write(Collections.singletonList(entry)).get(0); + assertThat(manifests.read(meta.fileName(), meta.fileSize())).containsExactly(entry); + + DataEvolutionFileStoreScan scan = dataEvolutionMetadataScan(factory, options); + scan.dropStats(); + io.reset(); + assertThat(scan.readManifest(meta)) + .containsExactly(Boolean.TRUE.equals(enabled) ? entry.copyWithoutStats() : entry); + if ("cached".equals(cacheMode)) { + assertThat(io.opened).isEmpty(); + } else { + assertThat(io.opened).isNotEmpty(); + } + // A low-retention consumer must not remove statistics from the shared cache. + assertThat(manifests.read(meta.fileName(), meta.fileSize())).containsExactly(entry); + } + + @ParameterizedTest + @MethodSource("dataEvolutionMetadataCacheModes") + void testDataEvolutionRestoresStatsForFiltersAndKeepStats(String cacheMode) { + Options options = dataEvolutionMetadataOptions(true); + RecordingFileIO io = new RecordingFileIO(); + ManifestFile.Factory factory = dataEvolutionMetadataFactory(options, cacheMode, io); + ManifestFile manifests = factory.create(); + ManifestEntry entry = gen.next(); + assertThat(entry.file().valueStats()).isNotEqualTo(SimpleStats.EMPTY_STATS); + ManifestFileMeta meta = manifests.write(Collections.singletonList(entry)).get(0); + DataEvolutionFileStoreScan scan = dataEvolutionMetadataScan(factory, options); + assertThat(scan.readManifest(meta)).containsExactly(entry); + + scan.dropStats(); + assertThat(scan.readManifest(meta)).containsExactly(entry.copyWithoutStats()); + scan.withFilter(new PredicateBuilder(DataTypes.ROW(DataTypes.INT())).equal(0, 7)); + assertThat(scan.readManifest(meta)).containsExactly(entry); + scan.withFilter(null); + assertThat(scan.readManifest(meta)).containsExactly(entry.copyWithoutStats()); + scan.keepStats(); + assertThat(scan.readManifest(meta)).containsExactly(entry); + scan.dropStats(); + assertThat(scan.readManifest(meta)).containsExactly(entry.copyWithoutStats()); + scan.withFilter(new PredicateBuilder(DataTypes.ROW(DataTypes.INT())).equal(0, 7)); + scan.keepStats(); + scan.dropStats(); + assertThat(scan.readManifest(meta)).containsExactly(entry); + scan.withFilter(null); + assertThat(scan.readManifest(meta)).containsExactly(entry.copyWithoutStats()); + scan.keepStats(); + assertThat(scan.readManifest(meta)).containsExactly(entry); + assertThat(manifests.read(meta.fileName(), meta.fileSize())).containsExactly(entry); + } + + private static Stream dataEvolutionMetadataCacheModes() { + return Stream.of("none", "cached", "oversized"); + } + + private static Stream dataEvolutionMetadataModes() { + return Stream.of((Boolean) null, Boolean.FALSE, Boolean.TRUE) + .flatMap( + enabled -> + dataEvolutionMetadataCacheModes() + .map(mode -> Arguments.of(enabled, mode))); + } + + private static Options dataEvolutionMetadataOptions(Boolean enabled) { + Options options = new Options(); + options.set(CoreOptions.DATA_EVOLUTION_ENABLED, true); + options.set(CoreOptions.ROW_TRACKING_ENABLED, true); + if (enabled != null) { + options.set( + CoreOptions.DATA_EVOLUTION_METADATA_MEMORY_OPTIMIZATION_MODE, + enabled + ? DataEvolutionMetadataMemoryMode.LIGHTWEIGHT + : DataEvolutionMetadataMemoryMode.OFF); + } + return options; + } + + private ManifestFile.Factory dataEvolutionMetadataFactory( + Options options, String cacheMode, RecordingFileIO io) { + SegmentsCache cache = + "none".equals(cacheMode) + ? null + : new SegmentsCache<>( + 1024, + MemorySize.ofMebiBytes(16), + "cached".equals(cacheMode) ? Long.MAX_VALUE : 1L); + return createManifestFileFactory(tempDir.toString(), Long.MAX_VALUE, options, io, cache); + } + + private static DataEvolutionFileStoreScan dataEvolutionMetadataScan( + ManifestFile.Factory factory, Options options) { + TableSchema schema = + TableSchema.create( + 0L, + Schema.newBuilder() + .column("v", DataTypes.INT()) + .options(options.toMap()) + .build()); + return new DataEvolutionFileStoreScan( + mock(ManifestsReader.class), null, null, null, schema, factory, 2, false); + } + private ManifestFile createManifestFile(String pathStr) { return createManifestFile(pathStr, ThreadLocalRandom.current().nextInt(8192) + 1024); } diff --git a/paimon-core/src/test/java/org/apache/paimon/operation/DataEvolutionIncrementalScanTest.java b/paimon-core/src/test/java/org/apache/paimon/operation/DataEvolutionIncrementalScanTest.java new file mode 100644 index 000000000000..a2cbccedd34f --- /dev/null +++ b/paimon-core/src/test/java/org/apache/paimon/operation/DataEvolutionIncrementalScanTest.java @@ -0,0 +1,1319 @@ +/* + * 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.paimon.operation; + +import org.apache.paimon.CoreOptions; +import org.apache.paimon.CoreOptions.DataEvolutionMetadataMemoryMode; +import org.apache.paimon.Snapshot; +import org.apache.paimon.catalog.TableQueryAuthResult; +import org.apache.paimon.data.BinaryArray; +import org.apache.paimon.data.BinaryArrayWriter; +import org.apache.paimon.data.BinaryRow; +import org.apache.paimon.data.BinaryRowWriter; +import org.apache.paimon.data.Timestamp; +import org.apache.paimon.disk.BufferFileWriter; +import org.apache.paimon.disk.FileIOChannel; +import org.apache.paimon.disk.IOManagerImpl; +import org.apache.paimon.format.FileFormat; +import org.apache.paimon.fs.local.LocalFileIO; +import org.apache.paimon.io.DataFileMeta; +import org.apache.paimon.manifest.FileKind; +import org.apache.paimon.manifest.FileSource; +import org.apache.paimon.manifest.ManifestEntry; +import org.apache.paimon.manifest.ManifestFile; +import org.apache.paimon.manifest.ManifestFileMeta; +import org.apache.paimon.manifest.SimpleFileEntry; +import org.apache.paimon.metrics.Gauge; +import org.apache.paimon.metrics.MetricGroup; +import org.apache.paimon.metrics.TestMetricRegistry; +import org.apache.paimon.operation.metrics.ScanMetrics; +import org.apache.paimon.options.MemorySize; +import org.apache.paimon.options.Options; +import org.apache.paimon.partition.PartitionPredicate; +import org.apache.paimon.predicate.Predicate; +import org.apache.paimon.predicate.PredicateBuilder; +import org.apache.paimon.schema.FileSystemSchemaManager; +import org.apache.paimon.schema.Schema; +import org.apache.paimon.schema.TableSchema; +import org.apache.paimon.stats.SimpleStats; +import org.apache.paimon.table.BucketMode; +import org.apache.paimon.table.FileStoreTable; +import org.apache.paimon.table.FileStoreTableFactory; +import org.apache.paimon.table.source.AppendBatchTableScan; +import org.apache.paimon.table.source.DataEvolutionSplitGenerator; +import org.apache.paimon.table.source.DataFileMetaStore; +import org.apache.paimon.table.source.DataSplit; +import org.apache.paimon.table.source.InnerTableScan; +import org.apache.paimon.table.source.QueryAuthSplit; +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.SplitSerializer; +import org.apache.paimon.table.source.snapshot.SnapshotReader; +import org.apache.paimon.table.source.snapshot.SnapshotReaderImpl; +import org.apache.paimon.types.DataTypes; +import org.apache.paimon.types.RowType; +import org.apache.paimon.utils.FileStorePathFactory; +import org.apache.paimon.utils.InstantiationUtil; +import org.apache.paimon.utils.JsonSerdeUtil; +import org.apache.paimon.utils.Range; +import org.apache.paimon.utils.SnapshotManager; +import org.apache.paimon.utils.TagManager; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** Real-manifest semantic checks for incremental DE group production, not SQL capacity tests. */ +class DataEvolutionIncrementalScanTest { + + @TempDir Path directory; + + @Test + void testStreamingCommitEntriesCancelDeletesAndKeepDuplicateAdds() throws Exception { + Fixture fixture = new Fixture(); + ManifestEntry removed = entry("same.parquet", 0L, 2, 1, "a", 1, 1, 1, 0, 0); + ManifestEntry otherPartition = entry("same.parquet", 10L, 2, 1, "a", 1, 1, 2, 0, 0); + ManifestEntry duplicate = entry("duplicate.parquet", 20L, 2, 1, "b", 2, 1, 1, 0, 0); + fixture.write(removed, otherPartition, duplicate); + fixture.write( + ManifestEntry.create( + FileKind.DELETE, + removed.partition(), + removed.bucket(), + removed.totalBuckets(), + removed.file()), + duplicate); + List expected = fixture.scan().readSimpleEntries(); + List actual = new ArrayList<>(); + + fixture.scan().forEachSimpleEntry(actual::add); + + assertThat(actual).containsExactlyInAnyOrderElementsOf(expected); + assertThat(actual) + .containsExactly( + SimpleFileEntry.from(otherPartition), + SimpleFileEntry.from(duplicate), + SimpleFileEntry.from(duplicate)); + assertThat(actual.get(0).identifier()).isEqualTo(otherPartition.identifier()); + } + + @Test + void testStreamingCommitEntriesPreserveDeltaKindsAndOrder() throws Exception { + Fixture fixture = new Fixture(); + ManifestEntry first = entry("first.parquet", 0L, 2, 1, "a", 1, 1, 1, 0, 0); + ManifestEntry deleted = + ManifestEntry.create( + FileKind.DELETE, + first.partition(), + first.bucket(), + first.totalBuckets(), + first.file()); + ManifestEntry last = entry("last.parquet", 10L, 2, 2, "b", 2, 1, 1, 0, 0); + fixture.write(first, deleted, last); + DataEvolutionFileStoreScan scan = fixture.scan(); + scan.withKind(ScanMode.DELTA); + List expected = scan.readSimpleEntries(); + List actual = new ArrayList<>(); + + scan.forEachSimpleEntry(actual::add); + + assertThat(actual).containsExactlyElementsOf(expected); + assertThat(actual) + .extracting(SimpleFileEntry::kind) + .containsExactly(FileKind.ADD, FileKind.DELETE, FileKind.ADD); + } + + @Test + void testStreamingCommitEntriesKeepFiltersAndIndependentMetadata() throws Exception { + Fixture fixture = new Fixture(); + fixture.write( + entry("keep.parquet", 10L, 2, 1, "a", 1, 1, 2, 1, 2), + entry("wrong-q.parquet", 12L, 2, 1, "a", 1, 1, 3, 1, 2), + entry("wrong-bucket.parquet", 14L, 2, 1, "a", 1, 1, 2, 0, 2), + entry("wrong-level.parquet", 16L, 2, 1, "a", 1, 1, 2, 1, 0), + entry("wrong-name.parquet", 18L, 2, 1, "a", 1, 1, 2, 1, 2), + entry("keep-later.parquet", 20L, 3, 2, "b", 2, 1, 2, 1, 2), + entry("keep-reject.parquet", 23L, 2, 1, "a", 1, 1, 2, 1, 2), + entry("keep-outside.parquet", 90L, 2, 1, "a", 1, 1, 2, 1, 2)); + DataEvolutionFileStoreScan scan = fixture.scan(); + scan.withPartitionFilter(Collections.singletonList(row(1, 2))); + scan.withBucket(1); + scan.withLevel(2); + scan.withDataFileNameFilter(name -> name.startsWith("keep")); + scan.withRowRanges(Collections.singletonList(new Range(10, 25))); + scan.withManifestEntryFilter( + value -> !value.copyWithoutStats().file().fileName().contains("reject")); + scan.dropStats(); + List expected = scan.readSimpleEntries(); + List actual = new ArrayList<>(); + + scan.forEachSimpleEntry(actual::add); + + assertThat(actual).containsExactlyElementsOf(expected); + assertThat(actual) + .extracting(SimpleFileEntry::fileName) + .containsExactly("keep.parquet", "keep-later.parquet"); + for (int i = 0; i < expected.size(); i++) { + assertThat(actual.get(i).identifier()).isEqualTo(expected.get(i).identifier()); + } + assertThat(actual.get(0).firstRowId()).isEqualTo(10L); + assertThat(actual.get(1).firstRowId()).isEqualTo(20L); + assertThat(actual.get(0).rowCount()).isEqualTo(2L); + assertThat(actual.get(1).rowCount()).isEqualTo(3L); + } + + @Test + void testStreamingCommitEntriesConsumeBeforeFilteringTheWholeManifest() throws Exception { + Fixture fixture = new Fixture(); + fixture.write( + entry("first.parquet", 0L, 2, 1, "a", 1, 1, 1, 0, 0), + entry("late.parquet", 10L, 2, 2, "b", 2, 1, 1, 0, 0)); + DataEvolutionFileStoreScan scan = fixture.scan(); + AtomicInteger filtered = new AtomicInteger(); + scan.withManifestEntryFilter( + value -> { + filtered.incrementAndGet(); + if (value.fileName().equals("late.parquet")) { + throw new AssertionError("Consumer should stop before this entry"); + } + return true; + }); + IOException failure = new IOException("consumer stopped"); + + assertThatThrownBy( + () -> + scan.forEachSimpleEntry( + value -> { + assertThat(value.fileName()).isEqualTo("first.parquet"); + throw failure; + })) + .isSameAs(failure); + assertThat(filtered.get()).isEqualTo(1); + } + + @Test + void testStreamingCommitEntriesCanScanAgainAfterConsumerFailure() throws Exception { + Fixture fixture = new Fixture(); + fixture.write( + entry("first.parquet", 0L, 2, 1, "a", 1, 1, 1, 0, 0), + entry("last.parquet", 10L, 2, 2, "b", 2, 1, 1, 0, 0)); + DataEvolutionFileStoreScan scan = fixture.scan(); + IOException failure = new IOException("consumer stopped"); + assertThatThrownBy( + () -> + scan.forEachSimpleEntry( + value -> { + throw failure; + })) + .isSameAs(failure); + List actual = new ArrayList<>(); + + scan.forEachSimpleEntry(actual::add); + + assertThat(actual).containsExactlyElementsOf(scan.readSimpleEntries()); + } + + @Test + void testConnectedRangesAcrossManifestsKeepOriginalGroupOrder() throws Exception { + Fixture fixture = new Fixture(); + ManifestEntry nested = entry("nested.parquet", 8L, 3, 2, "a", 2, 1, 1, 0, 0); + ManifestEntry extending = entry("extending.parquet", 10L, 3, 3, "b", 3, 1, 1, 0, 0); + ManifestEntry adjacent = entry("adjacent.parquet", 13L, 2, 4, "a", 4, 1, 1, 0, 0); + ManifestEntry anchor = entry("anchor.parquet", 0L, 10, 1, "a", 1, 1, 1, 0, 0); + fixture.write(nested, extending, adjacent); + fixture.write(anchor); + try (ObservedIOManager io = fixture.io()) { + assertThat(groups(fixture.scan(), io)) + .containsExactly( + Arrays.asList("nested.parquet", "extending.parquet", "anchor.parquet"), + Collections.singletonList("adjacent.parquet")); + assertThat(io.closed).isFalse(); + } + assertThat(fixture.reads.get()).isEqualTo(1); + } + + @Test + void testDeleteUsesFullFileIdentityAndDoesNotDeleteAnotherColumnFile() throws Exception { + Fixture fixture = new Fixture(); + ManifestEntry removed = entry("same.parquet", 0L, 2, 1, "a", 1, 1, 1, 0, 0); + ManifestEntry otherColumn = entry("other.parquet", 0L, 2, 2, "b", 2, 1, 1, 0, 0); + ManifestEntry otherPartition = entry("same.parquet", 100L, 2, 3, "a", 3, 1, 2, 0, 0); + fixture.write(removed, otherColumn, otherPartition); + fixture.write( + ManifestEntry.create( + FileKind.DELETE, + removed.partition(), + removed.bucket(), + removed.totalBuckets(), + removed.file())); + try (ObservedIOManager io = fixture.io()) { + assertThat(groups(fixture.scan(), io)) + .containsExactly( + Collections.singletonList("other.parquet"), + Collections.singletonList("same.parquet")); + } + } + + @Test + void testAllPartitionFieldsAndExistingEntryFiltersAreApplied() throws Exception { + Fixture fixture = new Fixture(); + fixture.write( + entry("keep.parquet", 10L, 2, 1, "a", 1, 1, 2, 1, 2), + entry("wrong-q.parquet", 12L, 2, 1, "a", 1, 1, 3, 1, 2), + entry("wrong-bucket.parquet", 14L, 2, 1, "a", 1, 1, 2, 0, 2), + entry("wrong-level.parquet", 16L, 2, 1, "a", 1, 1, 2, 1, 0), + entry("wrong-name.parquet", 18L, 2, 1, "a", 1, 1, 2, 1, 2), + entry("keep-outside.parquet", 90L, 2, 1, "a", 1, 1, 2, 1, 2)); + DataEvolutionFileStoreScan scan = fixture.scan(); + scan.withPartitionFilter( + PartitionPredicate.fromMultiple( + fixture.partitionType, Collections.singletonList(row(1, 2)))); + scan.withBucket(1); + scan.withLevel(2); + scan.withDataFileNameFilter(name -> name.startsWith("keep")); + scan.withRowRanges(Collections.singletonList(new Range(10, 20))); + scan.withManifestEntryFilter(entry -> !entry.file().fileName().contains("outside")); + try (ObservedIOManager io = fixture.io()) { + assertThat(groups(scan, io)).containsExactly(Collections.singletonList("keep.parquet")); + } + } + + @Test + void testCustomEntryFilterKeepsOrdinaryManifestEntryCapabilities() throws Exception { + Fixture fixture = new Fixture(); + fixture.write( + entry("two.parquet", 0L, 2, 1, "a", 1, 1, 1, 0, 0), + entry("three.parquet", 10L, 3, 2, "a", 2, 1, 1, 0, 0)); + DataEvolutionFileStoreScan original = fixture.scan(); + original.withManifestEntryFilter(entry -> entry.copyWithoutStats().file().rowCount() == 2); + List expected = + original.plan().files().stream() + .map(entry -> entry.file().fileName()) + .collect(Collectors.toList()); + DataEvolutionFileStoreScan incremental = fixture.scan(); + incremental.withManifestEntryFilter( + entry -> entry.copyWithoutStats().file().rowCount() == 2); + try (ObservedIOManager io = fixture.io()) { + assertThat(groups(incremental, io)).containsExactly(expected); + } + assertThat(expected).containsExactly("two.parquet"); + } + + @Test + void testNullCountViewsRemainStableAcrossSpilledRows() throws Exception { + Fixture fixture = new Fixture(); + List entries = new ArrayList<>(); + entries.add(entry("a-null.parquet", 0L, 4, 1, "a", null, 1, 1, 0, 0)); + for (int i = 1499; i >= 0; i--) { + entries.add(entry("filler-" + i + ".parquet", 100L + i * 2L, 2, i, "a", i, 1, 1, 0, 0)); + } + entries.add(entry("b-not-null.parquet", 0L, 4, 2, "b", 7, 1, 1, 0, 0)); + fixture.write(entries.toArray(new ManifestEntry[0])); + DataEvolutionFileStoreScan scan = fixture.scan(); + scan.withFilter(new PredicateBuilder(fixture.schema.logicalRowType()).isNull(3)); + List result = new ArrayList<>(); + try (ObservedIOManager io = fixture.io()) { + scan.forEachFileGroup(io, result::addAll); + assertThat(io.spills.get()).isPositive(); + } + assertThat(result) + .extracting(entry -> entry.file().fileName()) + .containsExactly("a-null.parquet", "b-not-null.parquet"); + assertThat(result.get(0).file().valueStats().nullCounts().getLong(0)).isEqualTo(4); + assertThat(result.get(1).file().valueStats().nullCounts().getLong(0)).isZero(); + } + + @Test + void testStatisticsUseCompleteLatestColumnGroupBeforeDroppingStats() throws Exception { + Fixture fixture = new Fixture(); + fixture.write(entry("old-a.parquet", 0L, 4, 1, "a", 1, 1, 1, 0, 0)); + fixture.write( + entry("new-a.parquet", 0L, 4, 2, "a", 9, 1, 1, 0, 0), + entry("b.parquet", 0L, 4, 3, "b", 7, 1, 1, 0, 0)); + DataEvolutionFileStoreScan matching = fixture.scan(); + matching.withFilter(new PredicateBuilder(fixture.schema.logicalRowType()).equal(3, 9)); + matching.withReadType( + new RowType(Collections.singletonList(fixture.schema.fields().get(4)))); + matching.dropStats(); + List result = new ArrayList<>(); + try (ObservedIOManager io = fixture.io()) { + matching.forEachFileGroup(io, result::addAll); + } + assertThat(result) + .extracting(entry -> entry.file().fileName()) + .containsExactly("old-a.parquet", "new-a.parquet", "b.parquet"); + assertThat(result) + .allSatisfy( + entry -> + assertThat(entry.file().valueStats()) + .isSameAs(SimpleStats.EMPTY_STATS)); + DataEvolutionFileStoreScan staleValue = fixture.scan(); + staleValue.withFilter(new PredicateBuilder(fixture.schema.logicalRowType()).equal(3, 1)); + try (ObservedIOManager io = fixture.io()) { + assertThat(groups(staleValue, io)).isEmpty(); + } + assertThat( + fixture.factory + .create() + .read(fixture.manifests.get(0).fileName()) + .get(0) + .file() + .valueStats() + .minValues() + .getInt(0)) + .isEqualTo(1); + } + + @Test + void testDedicatedSubrangeKeepsFullRangeAnchor() throws Exception { + Fixture fixture = new Fixture(); + fixture.write(entry("b.blob", 0L, 3, 2, "b", 7, 1, 1, 0, 0)); + fixture.write(entry("anchor.parquet", 0L, 10, 1, "a", 1, 1, 1, 0, 0)); + DataEvolutionFileStoreScan scan = fixture.scan(); + scan.withReadType(new RowType(Collections.singletonList(fixture.schema.fields().get(4)))); + try (ObservedIOManager io = fixture.io()) { + assertThat(groups(scan, io)).containsExactly(Arrays.asList("b.blob", "anchor.parquet")); + } + } + + @Test + void testGlobalRangeFilteringMatchesExistingPlannerForOverlappingPartitions() throws Exception { + Fixture fixture = new Fixture(); + // Preserve the existing global post-filter contract even for historical RowID overlaps; + // this fixture does not assert that normal SQL creates such cross-partition overlaps. + fixture.write(entry("older-part.parquet", 0L, 4, 1, "a", 1, 1, 1, 0, 0)); + fixture.write(entry("newer-part.parquet", 0L, 4, 2, "a", 9, 1, 2, 0, 0)); + DataEvolutionFileStoreScan original = fixture.scan(); + original.withFilter(new PredicateBuilder(fixture.schema.logicalRowType()).equal(3, 1)); + List expected = + original.plan().files().stream() + .map(entry -> entry.file().fileName()) + .collect(Collectors.toList()); + DataEvolutionFileStoreScan incremental = fixture.scan(); + incremental.withFilter(new PredicateBuilder(fixture.schema.logicalRowType()).equal(3, 1)); + List actual = new ArrayList<>(); + try (ObservedIOManager io = fixture.io()) { + incremental.forEachFileGroup(io, actual::addAll); + } + assertThat(actual) + .extracting(entry -> entry.file().fileName()) + .containsExactlyElementsOf(expected); + assertThat(expected).isEmpty(); + } + + @Test + void testExternalSortActuallySpillsAndReleasesItsFiles() throws Exception { + Fixture fixture = new Fixture(); + List entries = new ArrayList<>(); + for (int i = 1499; i >= 0; i--) { + entries.add(entry("file-" + i + ".parquet", i * 2L, 2, i, "a", i, 1, 1, 0, 0)); + } + fixture.write(entries.toArray(new ManifestEntry[0])); + AtomicInteger next = new AtomicInteger(); + Set names = new HashSet<>(); + try (ObservedIOManager io = fixture.io()) { + Snapshot snapshot = + fixture.scan() + .forEachFileGroup( + io, + group -> { + assertThat(group).hasSize(1); + assertThat(group.get(0).file().firstRowId()) + .isEqualTo(next.getAndIncrement() * 2L); + assertThat(names.add(group.get(0).file().fileName())) + .isTrue(); + }); + assertThat(snapshot).isSameAs(fixture.snapshot); + assertThat(io.spills.get()).isPositive(); + assertThat(io.closed).isFalse(); + assertThat(next.get()).isEqualTo(1500); + assertThat(names).hasSize(1500); + fixture.assertNoSpillFiles(); + } + assertThat(fixture.reads.get()).isEqualTo(1); + } + + @Test + void testConsumerFailureReleasesSortButDoesNotCloseBorrowedIoManager() throws Exception { + Fixture fixture = new Fixture(); + List entries = new ArrayList<>(); + for (int i = 0; i < 1000; i++) { + entries.add(entry("file-" + i + ".parquet", i * 2L, 2, i, "a", i, 1, 1, 0, 0)); + } + fixture.write(entries.toArray(new ManifestEntry[0])); + IOException failure = new IOException("consumer stopped"); + try (ObservedIOManager io = fixture.io()) { + assertThatThrownBy( + () -> + fixture.scan() + .forEachFileGroup( + io, + group -> { + throw failure; + })) + .isSameAs(failure); + assertThat(io.spills.get()).isPositive(); + assertThat(io.closed).isFalse(); + fixture.assertNoSpillFiles(); + } + } + + @Test + void testUnsupportedInputsFailBeforeAnyGroupIsPublished() throws Exception { + Fixture fixture = new Fixture(); + fixture.write(entry("valid.parquet", 0L, 2, 1, "a", 1, 1, 1, 0, 0)); + fixture.write(entry("missing-row-id.parquet", null, 2, 2, "a", 1, 1, 1, 0, 0)); + AtomicInteger callbacks = new AtomicInteger(); + try (ObservedIOManager io = fixture.io()) { + assertThatThrownBy( + () -> + fixture.scan() + .forEachFileGroup( + io, group -> callbacks.incrementAndGet())) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("row"); + assertThat(callbacks.get()).isZero(); + DataEvolutionFileStoreScan delta = fixture.scan(); + delta.withKind(ScanMode.DELTA); + assertThatThrownBy( + () -> delta.forEachFileGroup(io, group -> callbacks.incrementAndGet())) + .isInstanceOf(UnsupportedOperationException.class); + assertThat(callbacks.get()).isZero(); + fixture.assertNoSpillFiles(); + } + } + + @Test + void testIncrementalSnapshotPlanMatchesBatchAndKeepsMetadataInStore() throws Exception { + Fixture fixture = new Fixture(); + fixture.write( + entry("base.parquet", 0L, 2, 1, "a", 1, 1, 1, 0, 0), + entry("update.parquet", 0L, 2, 2, "b", 2, 1, 1, 0, 0)); + for (int i = 1; i < 12; i++) { + fixture.write(entry("base-" + i + ".parquet", 2L * i, 2, i, "a", i, 1, 1, 0, 0)); + } + SnapshotReaderImpl original = fixture.reader(fixture.scan()); + original.dropStats(); + List expected = original.read().dataSplits(); + assertThat(expected).hasSize(3); + Path metadata = Files.createDirectory(directory.resolve("plan-metadata")); + List transported = new ArrayList<>(); + try (ObservedIOManager io = fixture.io(); + DataFileMetaStore store = new DataFileMetaStore(metadata, 1024 * 1024)) { + SnapshotReaderImpl incremental = fixture.reader(fixture.scan()); + incremental.dropStats(); + SnapshotReader.Plan plan = incremental.readIncrementally(store, io); + assertThat(plan.snapshot()).isSameAs(fixture.snapshot); + assertThat(plan.dataSplits()).containsExactlyElementsOf(expected); + long physical = 0; + long merged = 0; + for (DataSplit split : plan.dataSplits()) { + physical += split.rowCount(); + merged += split.mergedRowCount().getAsLong(); + transported.add(SplitSerializer.serialize(split)); + } + assertThat(physical).isEqualTo(26); + assertThat(merged).isEqualTo(24); + store.close(); + assertThatThrownBy(() -> plan.dataSplits().get(0).dataFiles().get(0)) + .isInstanceOf(IllegalStateException.class); + assertThat(io.closed).isFalse(); + } + for (int i = 0; i < expected.size(); i++) { + assertThat(SplitSerializer.deserialize(transported.get(i))).isEqualTo(expected.get(i)); + } + try (Stream files = Files.list(metadata)) { + assertThat(files.count()).isZero(); + } + } + + @ParameterizedTest + @ValueSource(longs = {1, 3}) + void testSmallLimitStreamsCompleteGroupsAcrossOverlappingManifests(long limit) + throws Exception { + Fixture fixture = new Fixture(); + List bases = new ArrayList<>(); + List updates = new ArrayList<>(); + for (int i = 0; i < 64; i++) { + bases.add(entry("base-" + i + ".parquet", 2L * i, 2, 1, "a", i, 1, 1, 0, 0)); + updates.add(entry("update-" + i + ".parquet", 2L * i, 2, 2, "b", i, 1, 1, 0, 0)); + } + fixture.write(bases.toArray(new ManifestEntry[0])); + fixture.write(updates.toArray(new ManifestEntry[0])); + assertThat(fixture.manifests).hasSize(2); + assertThat(fixture.manifests).extracting(ManifestFileMeta::minRowId).containsOnly(0L); + assertThat(fixture.manifests).extracting(ManifestFileMeta::maxRowId).containsOnly(127L); + CapturingRegistry metrics = new CapturingRegistry(); + DataEvolutionFileStoreScan scan = fixture.scan(true); + scan.withMetrics(new ScanMetrics(metrics, "fixture")); + Path metadata = Files.createDirectory(directory.resolve("limit-prefix-metadata")); + try (ObservedIOManager io = fixture.io(); + DataFileMetaStore store = + new DataFileMetaStore(metadata, limit == 1 ? 1024 : 2048)) { + SnapshotReader reader = fixture.reader(scan).withLimit(limit); + SnapshotReader.Plan plan = reader.readIncrementally(store, io); + int expectedGroups = (int) ((limit + 1) / 2); + List expectedFiles = new ArrayList<>(); + for (int i = 0; i < expectedGroups; i++) { + expectedFiles.add("base-" + i + ".parquet"); + expectedFiles.add("update-" + i + ".parquet"); + } + assertThat(plan.snapshot()).isSameAs(fixture.snapshot); + assertThat(plan.dataSplits()).hasSize(1); + DataSplit split = plan.dataSplits().get(0); + assertThat(split.dataFiles()) + .extracting(DataFileMeta::fileName) + .containsExactlyElementsOf(expectedFiles); + assertThat(split.rawConvertible()).isFalse(); + assertThat(split.mergedRowCount().getAsLong()).isEqualTo(expectedGroups * 2L); + assertThat(fixture.streamedGroups.get()).isEqualTo(expectedGroups); + assertThat(store.serializedBytes()).isLessThanOrEqualTo(limit == 1 ? 1024 : 2048); + assertThat(metrics.value(ScanMetrics.LAST_SCAN_RESULTED_TABLE_FILES)) + .isEqualTo(expectedGroups * 2L); + assertThat(metrics.value(ScanMetrics.LAST_SCAN_SKIPPED_TABLE_FILES)) + .isEqualTo(128L - expectedGroups * 2); + } + fixture.assertNoSpillFiles(); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void testStreamingLimitDoesNotPruneBeforeDataFilter(boolean configureScan) throws Exception { + Fixture fixture = new Fixture(); + fixture.write( + entry("first-a.parquet", 0L, 2, 1, "a", 100, 1, 1, 0, 0), + entry("last-a.parquet", 2L, 2, 1, "a", 101, 1, 1, 0, 0)); + fixture.write( + entry("first-b.parquet", 0L, 2, 2, "b", 200, 1, 1, 0, 0), + entry("last-b.parquet", 2L, 2, 2, "b", 201, 1, 1, 0, 0)); + Path metadata = Files.createDirectory(directory.resolve("filtered-limit-metadata")); + try (ObservedIOManager io = fixture.io(); + DataFileMetaStore store = new DataFileMetaStore(metadata, 1024 * 1024)) { + DataEvolutionFileStoreScan scan = fixture.scan(true); + Predicate filter = + new PredicateBuilder(fixture.schema.logicalRowType()).greaterOrEqual(3, 100); + SnapshotReader reader = fixture.reader(scan); + if (configureScan) { + scan.withFilter(filter); + } else { + reader.withFilter(filter); + } + reader.withLimit(1); + SnapshotReader.Plan plan = reader.readIncrementally(store, io); + assertThat( + plan.dataSplits().stream() + .flatMap(split -> split.dataFiles().stream()) + .map(DataFileMeta::fileName) + .collect(Collectors.toList())) + .containsExactly( + "first-a.parquet", + "first-b.parquet", + "last-a.parquet", + "last-b.parquet"); + } + fixture.assertNoSpillFiles(); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void testStreamingLimitDoesNotCountRowsOutsideRanges(boolean configureScan) throws Exception { + Fixture fixture = new Fixture(); + fixture.write( + entry("first.parquet", 0L, 2, 1, "a", 1, 1, 1, 0, 0), + entry("last.parquet", 2L, 2, 1, "a", 2, 1, 1, 0, 0)); + Path metadata = Files.createDirectory(directory.resolve("row-range-limit-metadata")); + try (ObservedIOManager io = fixture.io(); + DataFileMetaStore store = new DataFileMetaStore(metadata, 1024 * 1024)) { + DataEvolutionFileStoreScan scan = fixture.scan(true); + List ranges = Arrays.asList(new Range(0, 0), new Range(2, 2)); + SnapshotReader reader = fixture.reader(scan); + if (configureScan) { + scan.withRowRanges(ranges); + } else { + reader.withRowRanges(ranges); + } + reader.withLimit(2); + SnapshotReader.Plan plan = reader.readIncrementally(store, io); + assertThat( + plan.dataSplits().stream() + .flatMap(split -> split.dataFiles().stream()) + .map(DataFileMeta::fileName) + .collect(Collectors.toList())) + .containsExactly("first.parquet", "last.parquet"); + } + fixture.assertNoSpillFiles(); + } + + @Test + void testSnapshotPackingDoesNotCutProvidersWhenPartitionsInterleave() throws Exception { + Fixture fixture = new Fixture(); + fixture.write( + entry("p1-a.parquet", 0L, 4, 1, "a", 1, 1, 1, 0, 0), + entry("p2-x.parquet", 0L, 4, 1, "a", 2, 1, 2, 0, 0), + entry("p1-b.parquet", 0L, 4, 2, "b", 3, 1, 1, 0, 0)); + Path metadata = Files.createDirectory(directory.resolve("plan-metadata")); + try (ObservedIOManager io = fixture.io(); + DataFileMetaStore store = new DataFileMetaStore(metadata, 1024 * 1024)) { + SnapshotReader.Plan plan = fixture.reader(fixture.scan()).readIncrementally(store, io); + List first = + plan.dataSplits().stream() + .filter(split -> split.partition().equals(row(1, 1))) + .collect(Collectors.toList()); + assertThat(first).hasSize(1); + assertThat(first.get(0).dataFiles()) + .extracting(DataFileMeta::fileName) + .containsExactly("p1-a.parquet", "p1-b.parquet"); + assertThat(first.get(0).rawConvertible()).isFalse(); + assertThat(plan.dataSplits()).hasSize(2); + } + } + + @Test + void testPartitionPackerEvictionKeepsEveryCompleteProviderGroup() throws Exception { + Fixture fixture = new Fixture(); + List entries = new ArrayList<>(); + for (int i = 0; i < 1030; i++) { + entries.add(entry("base-" + i + ".parquet", i * 2L, 2, 1, "a", i, 1, i, 0, 0)); + } + entries.add(entry("late-a.parquet", 3000L, 2, 1, "a", 1, 1, 0, 0, 0)); + entries.add(entry("late-b.parquet", 3000L, 2, 2, "b", 2, 1, 0, 0, 0)); + fixture.write(entries.toArray(new ManifestEntry[0])); + Path metadata = Files.createDirectory(directory.resolve("eviction-metadata")); + try (ObservedIOManager io = fixture.io(); + DataFileMetaStore store = new DataFileMetaStore(metadata, 1024 * 1024)) { + SnapshotReader.Plan plan = fixture.reader(fixture.scan()).readIncrementally(store, io); + assertThat( + plan.dataSplits().stream() + .flatMap(split -> split.dataFiles().stream()) + .map(DataFileMeta::fileName) + .collect(Collectors.toList())) + .containsExactlyInAnyOrderElementsOf( + entries.stream() + .map(entry -> entry.file().fileName()) + .collect(Collectors.toList())); + List updated = + plan.dataSplits().stream() + .filter( + split -> + split.dataFiles().stream() + .anyMatch( + file -> + file.fileName() + .equals( + "late-a.parquet"))) + .collect(Collectors.toList()); + assertThat(updated).hasSize(1); + assertThat(updated.get(0).dataFiles()) + .extracting(DataFileMeta::fileName) + .contains("late-a.parquet", "late-b.parquet"); + assertThat(updated.get(0).rawConvertible()).isFalse(); + } + fixture.assertNoSpillFiles(); + } + + @Test + void testSnapshotStoreFailureDoesNotReturnAPartialPlanOrCloseBorrowedIo() throws Exception { + Fixture fixture = new Fixture(); + List entries = new ArrayList<>(); + for (int i = 0; i < 1000; i++) { + entries.add(entry("base-" + i + ".parquet", i * 2L, 2, i, "a", i, 1, 1, 0, 0)); + } + fixture.write(entries.toArray(new ManifestEntry[0])); + Path metadata = Files.createDirectory(directory.resolve("plan-metadata")); + try (ObservedIOManager io = fixture.io(); + DataFileMetaStore store = new DataFileMetaStore(metadata, 8)) { + assertThatThrownBy(() -> fixture.reader(fixture.scan()).readIncrementally(store, io)) + .isInstanceOf(IOException.class) + .hasMessageContaining("limit"); + assertThat(io.closed).isFalse(); + fixture.assertNoSpillFiles(); + try (Stream files = Files.list(metadata)) { + assertThat(files.count()).isZero(); + } + } + Path unsupportedMetadata = Files.createDirectory(directory.resolve("unsupported-metadata")); + try (ObservedIOManager io = fixture.io(); + DataFileMetaStore store = new DataFileMetaStore(unsupportedMetadata, 1024 * 1024)) { + SnapshotReaderImpl unsupported = fixture.reader(fixture.scan()); + unsupported.withMode(ScanMode.DELTA); + assertThatThrownBy(() -> unsupported.readIncrementally(store, io)) + .isInstanceOf(UnsupportedOperationException.class); + assertThat(io.closed).isFalse(); + try (Stream files = Files.list(unsupportedMetadata)) { + assertThat(files.count()).isZero(); + } + } + } + + @Test + void testIncrementalScanReportsTheSameCountsUsedByExistingGuards() throws Exception { + Fixture fixture = new Fixture(); + fixture.write( + entry("keep.parquet", 0L, 2, 1, "a", 1, 1, 1, 0, 0), + entry("skip.parquet", 10L, 2, 2, "a", 2, 1, 1, 0, 0)); + CapturingRegistry originalMetrics = new CapturingRegistry(); + DataEvolutionFileStoreScan original = fixture.scan(); + original.withMetrics(new ScanMetrics(originalMetrics, "fixture")); + original.withDataFileNameFilter(name -> name.startsWith("keep")); + original.plan(); + CapturingRegistry incrementalMetrics = new CapturingRegistry(); + DataEvolutionFileStoreScan incremental = fixture.scan(); + incremental.withMetrics(new ScanMetrics(incrementalMetrics, "fixture")); + incremental.withDataFileNameFilter(name -> name.startsWith("keep")); + try (ObservedIOManager io = fixture.io()) { + List> accepted = new ArrayList<>(); + incremental.forEachFileGroup( + io, + group -> { + accepted.add( + group.stream() + .map(entry -> entry.file().fileName()) + .collect(Collectors.toList())); + group.clear(); + }); + assertThat(accepted).containsExactly(Collections.singletonList("keep.parquet")); + } + for (String metric : + Arrays.asList( + ScanMetrics.LAST_SCANNED_SNAPSHOT_ID, + ScanMetrics.LAST_SCANNED_MANIFESTS, + ScanMetrics.LAST_SCAN_SKIPPED_TABLE_FILES, + ScanMetrics.LAST_SCAN_RESULTED_TABLE_FILES)) { + assertThat(incrementalMetrics.value(metric)) + .as(metric) + .isEqualTo(originalMetrics.value(metric)); + } + assertThat(incrementalMetrics.value(ScanMetrics.LAST_SCANNED_SNAPSHOT_ID)).isEqualTo(17L); + assertThat(incrementalMetrics.value(ScanMetrics.LAST_SCAN_SKIPPED_TABLE_FILES)) + .isEqualTo(1L); + assertThat(incrementalMetrics.value(ScanMetrics.LAST_SCAN_RESULTED_TABLE_FILES)) + .isEqualTo(1L); + } + + @Test + void testConfiguredReadReplaysMetadataAndRejectsReuseWithoutInvalidatingThePlan() + throws Exception { + Fixture fixture = new Fixture(); + fixture.write(entry("base.parquet", 0L, 2, 1, "a", 1, 1, 1, 0, 0)); + Path metadata = Files.createDirectory(directory.resolve("configured-metadata")); + try (ObservedIOManager io = fixture.io(); + DataFileMetaStore store = new DataFileMetaStore(metadata, 1024 * 1024)) { + SnapshotReader reader = + fixture.reader(fixture.scan()).withIncrementalPlanning(store, io); + SnapshotReader.Plan plan = reader.read(); + assertThat(plan.dataSplits()).hasSize(1); + assertThatThrownBy(reader::read).isInstanceOf(IllegalStateException.class); + assertThat(plan.dataSplits().get(0).dataFiles()) + .extracting(DataFileMeta::fileName) + .containsExactly("base.parquet"); + store.close(); + assertThatThrownBy(() -> plan.dataSplits().get(0).dataFiles().get(0)) + .isInstanceOf(IllegalStateException.class); + assertThat(io.closed).isFalse(); + } + } + + @Test + void testConfiguredReadDoesNotFallBackToMaterializedChanges() throws Exception { + Fixture fixture = new Fixture(); + fixture.write(entry("base.parquet", 0L, 2, 1, "a", 1, 1, 1, 0, 0)); + for (int operation = 0; operation < 3; operation++) { + Path metadata = Files.createDirectory(directory.resolve("unsupported-" + operation)); + try (ObservedIOManager io = fixture.io(); + DataFileMetaStore store = new DataFileMetaStore(metadata, 1024 * 1024)) { + SnapshotReader reader = + fixture.reader(fixture.scan()).withIncrementalPlanning(store, io); + if (operation == 0) { + reader.withMode(ScanMode.DELTA); + assertThatThrownBy(reader::read) + .isInstanceOf(UnsupportedOperationException.class); + } else if (operation == 1) { + assertThatThrownBy(reader::readChanges) + .isInstanceOf(UnsupportedOperationException.class); + } else { + assertThatThrownBy(() -> reader.readIncrementalDiff(fixture.snapshot)) + .isInstanceOf(UnsupportedOperationException.class); + } + assertThat(io.closed).isFalse(); + try (Stream files = Files.list(metadata)) { + assertThat(files.count()).isZero(); + } + } + } + assertThat(fixture.reads.get()).isZero(); + } + + @Test + void testReadBuilderFactoryKeepsFiltersLimitTagAndExecutorBuilderIndependent() + throws Exception { + Fixture fixture = new Fixture(); + for (int i = 0; i < 8; i++) { + fixture.write( + entry( + "base-" + i + ".parquet", + 2L * i, + 2, + i, + "a", + i + 1, + i == 7 ? 2 : 1, + 1, + 0, + 0)); + } + org.apache.paimon.fs.Path tablePath = fixture.paths.root(); + SnapshotReaderImpl reader = fixture.reader(fixture.scan()); + SnapshotManager snapshots = reader.snapshotManager(); + assertThat( + LocalFileIO.INSTANCE.tryToWriteAtomic( + snapshots.snapshotPath(17), fixture.snapshot.toJson())) + .isTrue(); + Options dynamic = new Options(fixture.schema.options()); + dynamic.set(CoreOptions.SCAN_PLAN_AUTO_TAG_FOR_READ_TIME_RETAINED, Duration.ofMinutes(10)); + dynamic.set(CoreOptions.QUERY_AUTH_ENABLED, false); + FileStoreTable table = + FileStoreTableFactory.create(LocalFileIO.INSTANCE, tablePath).copy(dynamic.toMap()); + ReadBuilder builder = + table.newReadBuilder() + .withPartitionFilter(Collections.singletonMap("p", "1")) + .withLimit(1) + .dropStats(); + Path metadata = Files.createDirectory(directory.resolve("builder-metadata")); + String tag; + try (ObservedIOManager io = fixture.io(); + DataFileMetaStore store = new DataFileMetaStore(metadata, 1024 * 1024)) { + AtomicInteger factories = new AtomicInteger(); + InnerTableScan scan = + (InnerTableScan) + builder.newScan( + actual -> { + factories.incrementAndGet(); + assertThat( + actual.coreOptions() + .scanPlanAutoTagTimeRetained()) + .isEqualTo(Duration.ofMinutes(10)); + return reader.withIncrementalPlanning(store, io); + }); + List splits = scan.plan().splits(); + assertThat(factories.get()).isEqualTo(1); + assertThat(splits).hasSize(1); + DataSplit split = (DataSplit) splits.get(0); + assertThat(split.partition()).isEqualTo(row(1, 1)); + assertThat(split.dataFiles()) + .extracting(DataFileMeta::fileName) + .doesNotContain("base-7.parquet"); + tag = scan.readProtectionTagName(); + assertThat(tag).startsWith("batch-read-17-"); + assertThat(new TagManager(LocalFileIO.INSTANCE, tablePath, null).tagExists(tag)) + .isTrue(); + byte[] executorBuilder = InstantiationUtil.serializeObject(builder); + store.close(); + ReadBuilder restored = + InstantiationUtil.deserializeObject( + executorBuilder, getClass().getClassLoader()); + assertThat(restored.newRead()).isNotNull(); + assertThatThrownBy(() -> split.dataFiles().get(0)) + .isInstanceOf(IllegalStateException.class); + assertThat(io.closed).isFalse(); + } + LocalFileIO.INSTANCE.delete( + new TagManager(LocalFileIO.INSTANCE, tablePath, null).tagPath(tag), false); + } + + @Test + void testIncrementalBatchPlanKeepsAuthWrapperAndDoesNotApplyUnsafeLimit() throws Exception { + Fixture fixture = new Fixture(); + for (int i = 0; i < 7; i++) { + fixture.write(entry("base-" + i + ".parquet", i * 2L, 2, i, "a", i + 1, 1, 1, 0, 0)); + } + SnapshotReaderImpl reader = fixture.reader(fixture.scan()); + assertThat( + LocalFileIO.INSTANCE.tryToWriteAtomic( + reader.snapshotManager().snapshotPath(17), + fixture.snapshot.toJson())) + .isTrue(); + Options options = new Options(fixture.schema.options()); + options.set(CoreOptions.QUERY_AUTH_ENABLED, true); + TableQueryAuthResult auth = + new TableQueryAuthResult( + Collections.singletonList( + JsonSerdeUtil.toFlatJson( + new PredicateBuilder(fixture.schema.logicalRowType()) + .greaterThan(3, 0))), + null); + Path metadata = Files.createDirectory(directory.resolve("auth-metadata")); + try (ObservedIOManager io = fixture.io(); + DataFileMetaStore store = new DataFileMetaStore(metadata, 1024 * 1024)) { + reader.withIncrementalPlanning(store, io); + AtomicInteger authorizations = new AtomicInteger(); + AppendBatchTableScan scan = + new AppendBatchTableScan( + fixture.schema, + new FileSystemSchemaManager(LocalFileIO.INSTANCE, fixture.paths.root()), + new CoreOptions(options), + reader, + select -> { + authorizations.incrementAndGet(); + return auth; + }); + scan.withLimit(1); + List splits = scan.plan().splits(); + assertThat(authorizations.get()).isEqualTo(1); + assertThat(splits).hasSize(2); + int selected = 0; + for (Split split : splits) { + assertThat(split).isInstanceOf(QueryAuthSplit.class); + QueryAuthSplit wrapped = (QueryAuthSplit) split; + assertThat(wrapped.authResult()).isSameAs(auth); + assertThat(wrapped.mergedRowCount()).isEmpty(); + selected += ((DataSplit) wrapped.split()).dataFiles().size(); + } + assertThat(selected).isEqualTo(7); + } + } + + @Test + void testConfiguredReadPreservesCheckedStorageFailureAndCleansOwnedFiles() throws Exception { + Fixture fixture = new Fixture(); + fixture.write(entry("base.parquet", 0L, 2, 1, "a", 1, 1, 1, 0, 0)); + Path metadata = Files.createDirectory(directory.resolve("configured-limit")); + try (ObservedIOManager io = fixture.io(); + DataFileMetaStore store = new DataFileMetaStore(metadata, 8)) { + SnapshotReader reader = + fixture.reader(fixture.scan()).withIncrementalPlanning(store, io); + assertThatThrownBy(reader::read) + .isInstanceOf(RuntimeException.class) + .hasCauseInstanceOf(IOException.class); + assertThat(io.closed).isFalse(); + try (Stream files = Files.list(metadata)) { + assertThat(files.count()).isZero(); + } + fixture.assertNoSpillFiles(); + } + } + + private static List> groups(DataEvolutionFileStoreScan scan, ObservedIOManager io) + throws Exception { + List> result = new ArrayList<>(); + scan.forEachFileGroup( + io, + group -> + result.add( + group.stream() + .map(entry -> entry.file().fileName()) + .collect(Collectors.toList()))); + return result; + } + + private final class Fixture { + private final TableSchema schema; + private final RowType partitionType; + private final ManifestFile.Factory factory; + private final FileStorePathFactory paths; + private final List manifests = new ArrayList<>(); + private final AtomicInteger reads = new AtomicInteger(); + private final AtomicInteger streamedGroups = new AtomicInteger(); + private final Snapshot snapshot = + new Snapshot( + 17, + 0, + "base-list", + null, + "delta-list", + null, + null, + null, + null, + "test", + null, + 1, + Snapshot.CommitKind.APPEND, + 12345, + 0, + 0, + null, + null, + null, + null, + null, + null); + private final Path spill = directory.resolve("spill"); + + private Fixture() throws Exception { + Options options = new Options(); + options.set(CoreOptions.DATA_EVOLUTION_ENABLED, true); + options.set(CoreOptions.ROW_TRACKING_ENABLED, true); + options.set(CoreOptions.BUCKET, -1); + options.set( + CoreOptions.DATA_EVOLUTION_METADATA_MEMORY_OPTIMIZATION_MODE, + DataEvolutionMetadataMemoryMode.LIGHTWEIGHT); + options.set(CoreOptions.SORT_SPILL_BUFFER_SIZE, MemorySize.ofKibiBytes(128)); + options.set(CoreOptions.PAGE_SIZE, MemorySize.ofKibiBytes(32)); + options.set(CoreOptions.LOCAL_SORT_MAX_NUM_FILE_HANDLES, 4); + options.set(CoreOptions.MANIFEST_SIDECAR_ENABLED, true); + schema = + TableSchema.create( + 0, + Schema.newBuilder() + .column("p", DataTypes.INT()) + .column("q", DataTypes.INT()) + .column("id", DataTypes.INT()) + .column("a", DataTypes.INT()) + .column("b", DataTypes.INT()) + .partitionKeys("p", "q") + .options(options.toMap()) + .build()); + partitionType = schema.logicalPartitionType(); + org.apache.paimon.fs.Path table = + new org.apache.paimon.fs.Path(directory.resolve("table").toString()); + LocalFileIO fileIO = new LocalFileIO(); + FileSystemSchemaManager schemas = new FileSystemSchemaManager(fileIO, table); + assertThat(schemas.commit(schema)).isTrue(); + paths = + new FileStorePathFactory( + table, + partitionType, + "default", + "parquet", + "data-", + "changelog-", + false, + false, + "zstd", + null, + null, + CoreOptions.ExternalPathStrategy.NONE, + null, + false, + null); + factory = + new ManifestFile.Factory( + fileIO, + schemas, + partitionType, + FileFormat.fromIdentifier("avro", new Options()), + "zstd", + paths, + Long.MAX_VALUE, + null, + null, + new CoreOptions(options)); + Files.createDirectories(spill); + } + + private void write(ManifestEntry... entries) { + manifests.addAll(factory.create().write(Arrays.asList(entries))); + } + + private DataEvolutionFileStoreScan scan() { + return scan(false); + } + + private DataEvolutionFileStoreScan scan(boolean forbidMaterializedPlan) { + ManifestsReader reader = + new ManifestsReader(partitionType, "default", null, null) { + @Override + public Result read(Snapshot requested, ScanMode mode) { + reads.incrementAndGet(); + return new Result(snapshot, manifests, manifests); + } + }; + BucketSelectConverter bucketSelectConverter = + new BucketSelectConverter( + BucketMode.BUCKET_UNAWARE, + new CoreOptions(schema.options()), + schema.logicalRowType(), + partitionType, + schema.logicalBucketKeyType()); + return new DataEvolutionFileStoreScan( + reader, bucketSelectConverter, null, null, schema, factory, 2, false) { + @Override + protected List postFilterManifestEntries( + List entries) { + if (forbidMaterializedPlan) { + streamedGroups.incrementAndGet(); + } + return super.postFilterManifestEntries(entries); + } + + @Override + public FileStoreScan.Plan plan() { + if (forbidMaterializedPlan) { + throw new AssertionError( + "Streaming LIMIT must not materialize scan.plan()"); + } + return super.plan(); + } + }; + } + + private ObservedIOManager io() { + return new ObservedIOManager(spill.toString()); + } + + private SnapshotReaderImpl reader(DataEvolutionFileStoreScan scan) { + return new SnapshotReaderImpl( + scan, + schema, + new CoreOptions(schema.options()), + new SnapshotManager( + LocalFileIO.INSTANCE, + new org.apache.paimon.fs.Path(directory.resolve("table").toString()), + null, + null, + null), + null, + new DataEvolutionSplitGenerator(4096, 1024, false), + (target, predicate) -> + ((DataEvolutionFileStoreScan) target).withFilter(predicate), + paths, + "incremental-fixture", + null, + null); + } + + private void assertNoSpillFiles() throws IOException { + try (Stream files = Files.walk(spill)) { + assertThat(files.filter(Files::isRegularFile).count()).isZero(); + } + } + } + + private static final class ObservedIOManager extends IOManagerImpl { + private final AtomicInteger spills = new AtomicInteger(); + private boolean closed; + + private ObservedIOManager(String directory) { + super(directory); + } + + @Override + public BufferFileWriter createBufferFileWriter(FileIOChannel.ID channel) + throws IOException { + spills.incrementAndGet(); + return super.createBufferFileWriter(channel); + } + + @Override + public void close() throws Exception { + closed = true; + super.close(); + } + } + + private static final class CapturingRegistry extends TestMetricRegistry { + private MetricGroup group; + + @Override + public MetricGroup createMetricGroup(String name, Map variables) { + group = super.createMetricGroup(name, variables); + return group; + } + + private Object value(String name) { + return ((Gauge) group.getMetrics().get(name)).getValue(); + } + } + + private static ManifestEntry entry( + String name, + Long first, + long count, + long sequence, + String column, + Integer value, + int p, + int q, + int bucket, + int level) { + BinaryArray nulls = new BinaryArray(); + BinaryArrayWriter writer = new BinaryArrayWriter(nulls, 1, Long.BYTES); + writer.writeLong(0, value == null ? count : 0); + writer.complete(); + return ManifestEntry.create( + FileKind.ADD, + row(p, q), + bucket, + 2, + DataFileMeta.create( + name, + 100, + count, + DataFileMeta.EMPTY_MIN_KEY, + DataFileMeta.EMPTY_MAX_KEY, + SimpleStats.EMPTY_STATS, + new SimpleStats(valueRow(value), valueRow(value), nulls), + sequence, + sequence, + 0, + level, + Collections.emptyList(), + Timestamp.fromEpochMillis(12345), + 0L, + null, + FileSource.APPEND, + Collections.singletonList(column), + null, + first, + Collections.singletonList(column), + null)); + } + + private static BinaryRow row(int... values) { + BinaryRow row = new BinaryRow(values.length); + BinaryRowWriter writer = new BinaryRowWriter(row); + for (int i = 0; i < values.length; i++) { + writer.writeInt(i, values[i]); + } + writer.complete(); + return row; + } + + private static BinaryRow valueRow(Integer value) { + BinaryRow row = new BinaryRow(1); + BinaryRowWriter writer = new BinaryRowWriter(row); + if (value == null) { + writer.setNullAt(0); + } else { + writer.writeInt(0, value); + } + writer.complete(); + return row; + } +} diff --git a/paimon-core/src/test/java/org/apache/paimon/operation/FileEntryMergeBufferSmallBufferTest.java b/paimon-core/src/test/java/org/apache/paimon/operation/FileEntryMergeBufferSmallBufferTest.java new file mode 100644 index 000000000000..da1623c3d10c --- /dev/null +++ b/paimon-core/src/test/java/org/apache/paimon/operation/FileEntryMergeBufferSmallBufferTest.java @@ -0,0 +1,53 @@ +/* + * 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.paimon.operation; + +import org.apache.paimon.CoreOptions; +import org.apache.paimon.disk.IOManager; +import org.apache.paimon.options.MemorySize; +import org.apache.paimon.options.Options; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +/** Tests the full-page boundary without changing either sorter's minimum allocation. */ +class FileEntryMergeBufferSmallBufferTest { + + @ParameterizedTest + @CsvSource({"0, false", "256, false", "383, false", "384, true", "448, true"}) + void testFullPageCapacity(int bufferKibiBytes, boolean supported) { + Options options = new Options(); + options.set(CoreOptions.PAGE_SIZE, MemorySize.ofKibiBytes(64)); + options.set(CoreOptions.SORT_SPILL_BUFFER_SIZE, MemorySize.ofKibiBytes(bufferKibiBytes)); + CoreOptions coreOptions = new CoreOptions(options); + assertThat(FileEntryMergeBuffer.supportsBufferSize(coreOptions)).isEqualTo(supported); + if (!supported) { + IOManager io = mock(IOManager.class); + assertThatThrownBy(() -> new FileEntryMergeBuffer(coreOptions, io)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("at least six sort-buffer pages"); + verifyNoInteractions(io); + } + } +} diff --git a/paimon-core/src/test/java/org/apache/paimon/operation/FileEntryMergeBufferTest.java b/paimon-core/src/test/java/org/apache/paimon/operation/FileEntryMergeBufferTest.java new file mode 100644 index 000000000000..faecb35c0dbc --- /dev/null +++ b/paimon-core/src/test/java/org/apache/paimon/operation/FileEntryMergeBufferTest.java @@ -0,0 +1,532 @@ +/* + * 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.paimon.operation; + +import org.apache.paimon.CoreOptions; +import org.apache.paimon.data.BinaryRow; +import org.apache.paimon.disk.IOManager; +import org.apache.paimon.manifest.FileEntry; +import org.apache.paimon.manifest.FileKind; +import org.apache.paimon.manifest.SimpleFileEntry; +import org.apache.paimon.manifest.SimpleFileEntryWithDV; +import org.apache.paimon.options.MemorySize; +import org.apache.paimon.options.Options; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.apache.paimon.data.BinaryRow.EMPTY_ROW; +import static org.apache.paimon.manifest.FileKind.ADD; +import static org.apache.paimon.manifest.FileKind.DELETE; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class FileEntryMergeBufferTest { + + @TempDir Path temporary; + + @Test + void testPreservesInsertionOrderAfterIdentitySorting() throws Exception { + List base = Arrays.asList(entry("z", ADD), entry("a", ADD)); + List delta = Arrays.asList(entry("a", DELETE), entry("m", ADD)); + + assertThat(merge(base, delta)).containsExactly(entry("z", ADD), entry("m", ADD)); + + SimpleFileEntry reinserted = + new SimpleFileEntry( + ADD, + EMPTY_ROW, + 0, + 1, + 0, + "f", + Collections.emptyList(), + null, + EMPTY_ROW, + EMPTY_ROW, + null, + 3L, + 100L); + assertThat( + merge( + Collections.singletonList(entry("z", ADD)), + Arrays.asList( + entry("f", ADD), + entry("g", ADD), + entry("f", DELETE), + reinserted))) + .containsExactly(entry("z", ADD), entry("g", ADD), reinserted); + } + + @Test + void testPreservesOrderedAddDeleteStateMachine() throws Exception { + List> histories = + Arrays.asList( + Collections.singletonList(entry("f", ADD)), + Collections.singletonList(entry("f", DELETE)), + Arrays.asList(entry("f", ADD), entry("f", DELETE)), + Arrays.asList(entry("f", DELETE), entry("f", DELETE)), + Arrays.asList(entry("f", ADD), entry("f", DELETE), entry("f", ADD)), + Arrays.asList(entry("f", ADD), entry("f", ADD)), + Arrays.asList(entry("f", DELETE), entry("f", ADD))); + for (boolean existing : new boolean[] {false, true}) { + List base = + existing ? Collections.singletonList(entry("f", ADD)) : Collections.emptyList(); + for (List delta : histories) { + List expected; + try { + FileEntry.mergeEntries(delta); + List combined = new ArrayList<>(base); + combined.addAll(delta); + expected = new ArrayList<>(FileEntry.mergeEntries(combined)); + } catch (IllegalStateException invalidHistory) { + assertThatThrownBy(() -> merge(base, delta)) + .isInstanceOf(IllegalStateException.class); + continue; + } + assertThat(merge(base, delta)).containsExactlyElementsOf(expected); + } + } + } + + @Test + void testPreservesCompleteIdentityAndDvSubtype() throws Exception { + SimpleFileEntry plain = entry("same", ADD); + List distinct = + Arrays.asList( + plain, + entry("same", ADD, EMPTY_ROW, 1, Collections.emptyList(), null, null), + entry( + "same", + ADD, + BinaryRow.singleColumn(7), + 0, + Collections.emptyList(), + null, + null), + new SimpleFileEntry( + ADD, + EMPTY_ROW, + 0, + 1, + 1, + "same", + Collections.emptyList(), + null, + EMPTY_ROW, + EMPTY_ROW, + null, + 2L, + 10L), + entry( + "same", + ADD, + EMPTY_ROW, + 0, + Collections.singletonList("extra"), + null, + null), + entry( + "same", + ADD, + EMPTY_ROW, + 0, + Arrays.asList("first", "second"), + null, + null), + entry( + "same", + ADD, + EMPTY_ROW, + 0, + Arrays.asList("second", "first"), + null, + null), + entry( + "same", + ADD, + EMPTY_ROW, + 0, + Collections.emptyList(), + new byte[0], + null), + entry( + "same", + ADD, + EMPTY_ROW, + 0, + Collections.emptyList(), + new byte[] {1}, + null), + entry("same", ADD, EMPTY_ROW, 0, Collections.emptyList(), null, ""), + entry("same", ADD, EMPTY_ROW, 0, Collections.emptyList(), null, "external"), + new SimpleFileEntryWithDV(plain, null), + new SimpleFileEntryWithDV(plain, "dv"), + entry("unicode-文件", ADD)); + List actual = merge(distinct, Collections.emptyList()); + + assertThat(actual).containsExactlyElementsOf(distinct); + for (int i = 0; i < distinct.size(); i++) { + assertThat(actual.get(i).identifier()).isEqualTo(distinct.get(i).identifier()); + } + assertThat(actual.stream().map(FileEntry::identifier).distinct().count()) + .isEqualTo(distinct.size()); + } + + @Test + void testPhysicalIdentityExcludesRowIdCountAndKeyRange() { + SimpleFileEntry changedMetadata = + new SimpleFileEntry( + ADD, + EMPTY_ROW, + 0, + 1, + 0, + "same", + Collections.emptyList(), + null, + BinaryRow.singleColumn(99), + BinaryRow.singleColumn(101), + null, + 3L, + 100L); + + assertThatThrownBy( + () -> + merge( + Collections.singletonList(entry("same", ADD)), + Collections.singletonList(changedMetadata))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void testStringIdentityIsLossless() throws Exception { + SimpleFileEntry original = + entry("same", ADD, EMPTY_ROW, 0, Collections.emptyList(), null, "x\uD800"); + SimpleFileEntry different = + entry("same", DELETE, EMPTY_ROW, 0, Collections.emptyList(), null, "x?"); + List expected = + new ArrayList<>(FileEntry.mergeEntries(Arrays.asList(original, different))); + + assertThat(original.identifier()).isNotEqualTo(different.identifier()); + List actual = + merge(Collections.singletonList(original), Collections.singletonList(different)); + assertThat(actual).containsExactlyElementsOf(expected); + assertThat(actual.get(0).identifier()).isEqualTo(original.identifier()); + assertThat(actual.get(1).identifier()).isEqualTo(different.identifier()); + } + + @Test + void testDeduplicatedBaseKeepsFirstPayloadAndOriginalOrder() throws Exception { + SimpleFileEntry first = entry("f", ADD); + SimpleFileEntry later = + new SimpleFileEntry( + ADD, + EMPTY_ROW, + 0, + 1, + 0, + "f", + Collections.emptyList(), + null, + EMPTY_ROW, + EMPTY_ROW, + null, + 3L, + 100L); + List base = Arrays.asList(entry("z", ADD), first, entry("g", ADD), later); + List delta = Collections.singletonList(entry("h", ADD)); + + assertThatThrownBy(() -> merge(base, delta)).isInstanceOf(IllegalStateException.class); + assertThat(merge(base, delta, true)) + .containsExactly(entry("z", ADD), first, entry("g", ADD), entry("h", ADD)); + } + + @Test + void testDeduplicatedBaseDoesNotDeduplicateDelta() { + List base = Arrays.asList(entry("f", ADD), entry("f", ADD)); + List delta = Arrays.asList(entry("g", ADD), entry("g", ADD)); + + assertThatThrownBy(() -> merge(base, delta, true)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("fileName=g"); + } + + @Test + void testObservesBaseAndLastDeleteBeforeTheyCancel() throws Exception { + SimpleFileEntry current = + new SimpleFileEntry( + ADD, + EMPTY_ROW, + 0, + 1, + 0, + "f", + Collections.emptyList(), + null, + EMPTY_ROW, + EMPTY_ROW, + null, + 3L, + 100L); + SimpleFileEntry stale = entry("f", DELETE); + List observed = new ArrayList<>(); + List merged = new ArrayList<>(); + try (IOManager io = IOManager.create(temporary.toString()); + FileEntryMergeBuffer buffer = new FileEntryMergeBuffer(options(), io)) { + buffer.writeBase(current); + buffer.writeDelta(current.toDelete()); + buffer.writeDelta(current.toDelete()); + buffer.writeDelta(stale); + buffer.forEachMerged( + false, + (base, ordinal, lastDelete) -> { + assertThat(ordinal).isZero(); + observed.add(base); + observed.add(lastDelete); + }, + merged::add); + } + + assertThat(merged).isEmpty(); + assertThat(observed).containsExactly(current, stale); + } + + @Test + void testBaseObservationKeepsFirstPayloadOrdinalAndIndependentRecords() throws Exception { + SimpleFileEntry first = entry("f", ADD); + SimpleFileEntry later = + new SimpleFileEntry( + ADD, + EMPTY_ROW, + 0, + 1, + 0, + "f", + Collections.emptyList(), + null, + EMPTY_ROW, + EMPTY_ROW, + null, + 3L, + 100L); + List observed = new ArrayList<>(); + List ordinals = new ArrayList<>(); + try (IOManager io = IOManager.create(temporary.toString()); + FileEntryMergeBuffer buffer = new FileEntryMergeBuffer(options(), io)) { + buffer.writeBase(entry("z", ADD)); + buffer.writeBase(first); + buffer.writeBase(later); + buffer.writeDelta(entry("delta-only", ADD)); + buffer.forEachMerged( + true, + (base, ordinal, lastDelete) -> { + observed.add(base); + ordinals.add(base.fileName() + ":" + ordinal); + assertThat(lastDelete).isNull(); + }, + ignored -> {}); + } + + assertThat(observed).containsExactlyInAnyOrder(entry("z", ADD), first); + assertThat(ordinals).containsExactlyInAnyOrder("z:0", "f:1"); + } + + @Test + void testBaseObserverFailureClosesSpillFiles() throws Exception { + IOException failure = new IOException("base observer failed"); + try (IOManager io = IOManager.create(temporary.toString())) { + try (FileEntryMergeBuffer buffer = new FileEntryMergeBuffer(options(), io)) { + for (int i = 0; i < 3000; i++) { + buffer.writeBase(entry("file-" + i, ADD)); + } + assertThat(regularFiles()).isNotEmpty(); + assertThatThrownBy( + () -> + buffer.forEachMerged( + false, + (base, ordinal, lastDelete) -> { + throw failure; + }, + ignored -> {})) + .isSameAs(failure); + } + assertThat(regularFiles()).isEmpty(); + } + } + + @Test + void testSpillsAndEmitsOriginalOrder() throws Exception { + try (IOManager io = IOManager.create(temporary.toString())) { + try (FileEntryMergeBuffer buffer = new FileEntryMergeBuffer(options(), io)) { + for (int i = 20000; i > 0; i--) { + buffer.writeBase(entry(String.format("file-%05d", i), ADD)); + } + assertThat(regularFiles()).isNotEmpty(); + int[] expected = {20000}; + buffer.forEachMerged( + value -> { + assertThat(value.fileName()) + .isEqualTo(String.format("file-%05d", expected[0]--)); + assertThat(value.kind()).isEqualTo(ADD); + }); + assertThat(expected[0]).isZero(); + } + assertThat(regularFiles()).isEmpty(); + } + } + + @Test + void testConsumerFailureCleansOwnedFilesAndKeepsBorrowedManager() throws Exception { + try (IOManager io = IOManager.create(temporary.toString())) { + List ownedByIo; + IOException failure = new IOException("range consumer failed"); + try (FileEntryMergeBuffer buffer = new FileEntryMergeBuffer(options(), io)) { + for (int i = 0; i < 3000; i++) { + buffer.writeBase(entry("file-" + i, ADD)); + } + assertThat(regularFiles()).isNotEmpty(); + try (Stream paths = Files.list(temporary)) { + ownedByIo = paths.filter(Files::isDirectory).collect(Collectors.toList()); + } + assertThatThrownBy( + () -> + buffer.forEachMerged( + value -> { + throw failure; + })) + .isSameAs(failure); + } + assertThat(regularFiles()).isEmpty(); + assertThat(ownedByIo).isNotEmpty().allMatch(Files::isDirectory); + } + } + + @Test + void testEncodedMetadataBudgetFailureCleansFiles() throws Exception { + Options limited = options().toConfiguration(); + limited.set(CoreOptions.DATA_EVOLUTION_METADATA_MEMORY_MAX_DISK_SIZE, new MemorySize(8)); + try (IOManager io = IOManager.create(temporary.toString())) { + try (FileEntryMergeBuffer buffer = + new FileEntryMergeBuffer(new CoreOptions(limited), io)) { + assertThatThrownBy(() -> buffer.writeBase(entry("exceeds-budget", ADD))) + .isInstanceOf(IOException.class) + .hasMessageContaining("Metadata merge encoded limit"); + } + assertThat(regularFiles()).isEmpty(); + } + } + + @Test + void testRejectsConsumptionAndWritesAfterFinishOrClose() throws Exception { + try (IOManager io = IOManager.create(temporary.toString())) { + FileEntryMergeBuffer buffer = new FileEntryMergeBuffer(options(), io); + try { + buffer.forEachMerged( + value -> { + throw new AssertionError("empty input"); + }); + assertThatThrownBy(() -> buffer.writeDelta(entry("late", ADD))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> buffer.forEachMerged(value -> {})) + .isInstanceOf(IllegalStateException.class); + } finally { + buffer.close(); + } + buffer.close(); + assertThatThrownBy(() -> buffer.writeBase(entry("closed", ADD))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> buffer.forEachMerged(value -> {})) + .isInstanceOf(IllegalStateException.class); + } + } + + private List merge(List base, List delta) + throws Exception { + return merge(base, delta, false); + } + + private List merge( + List base, List delta, boolean deduplicateBase) + throws Exception { + List result = new ArrayList<>(); + try (IOManager io = IOManager.create(temporary.toString()); + FileEntryMergeBuffer buffer = new FileEntryMergeBuffer(options(), io)) { + for (SimpleFileEntry entry : base) { + buffer.writeBase(entry); + } + for (SimpleFileEntry entry : delta) { + buffer.writeDelta(entry); + } + buffer.forEachMerged(deduplicateBase, result::add); + } + return result; + } + + private CoreOptions options() { + Options options = new Options(); + options.set(CoreOptions.SORT_SPILL_BUFFER_SIZE, MemorySize.parse("256 kb")); + options.set(CoreOptions.PAGE_SIZE, MemorySize.parse("4 kb")); + return new CoreOptions(options); + } + + private List regularFiles() throws IOException { + try (Stream paths = Files.walk(temporary)) { + return paths.filter(Files::isRegularFile).collect(Collectors.toList()); + } + } + + private SimpleFileEntry entry(String name, FileKind kind) { + return entry(name, kind, EMPTY_ROW, 0, Collections.emptyList(), null, null); + } + + private SimpleFileEntry entry( + String name, + FileKind kind, + BinaryRow partition, + int bucket, + List extra, + byte[] index, + String externalPath) { + return new SimpleFileEntry( + kind, + partition, + bucket, + 1, + 0, + name, + extra, + index, + EMPTY_ROW, + EMPTY_ROW, + externalPath, + 2L, + 10L); + } +} diff --git a/paimon-core/src/test/java/org/apache/paimon/operation/FileStoreCommitTest.java b/paimon-core/src/test/java/org/apache/paimon/operation/FileStoreCommitTest.java index 2d5ab91edd8f..826fd716a6a1 100644 --- a/paimon-core/src/test/java/org/apache/paimon/operation/FileStoreCommitTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/operation/FileStoreCommitTest.java @@ -67,6 +67,8 @@ import org.apache.paimon.table.sink.CommitCallback; import org.apache.paimon.table.sink.CommitMessage; import org.apache.paimon.table.sink.CommitMessageImpl; +import org.apache.paimon.table.sink.CommitMessageList; +import org.apache.paimon.table.sink.CommitMessageSerializer; import org.apache.paimon.table.sink.CommitPreCallback; import org.apache.paimon.table.sink.TableCommitImpl; import org.apache.paimon.table.source.IncrementalSplit; @@ -2399,6 +2401,63 @@ public void close() {} assertThat(store.snapshotManager().latestSnapshot()).isNull(); } + @Test + public void testByteBackedMessagesPreserveCallbackMutationAndRetention() throws Exception { + TestFileStore store = createStore(false); + ManifestCommittable eager = prepareLockRetryCommittable(store); + CommitMessageList messages = + CommitMessageList.fromBytes( + CommitMessageSerializer.serializeAll(eager.fileCommittables())); + ManifestCommittable prepared = + new ManifestCommittable( + eager.identifier(), eager.watermark(), messages, eager.properties()); + AtomicReference retained = new AtomicReference<>(); + AtomicReference retried = new AtomicReference<>(); + CommitCallback callback = mock(CommitCallback.class); + doAnswer( + invocation -> { + CommitCallback.Context context = invocation.getArgument(0); + retained.set(context); + ManifestEntry entry = context.deltaFiles.get(0); + assertThat(context.deltaFiles.get(0)).isSameAs(entry); + context.deltaFiles.set(0, entry); + context.deltaFiles.add(context.deltaFiles.remove(0)); + return null; + }) + .when(callback) + .call(any()); + doAnswer( + invocation -> { + ManifestCommittable committable = invocation.getArgument(0); + CommitMessage message = committable.fileCommittables().get(0); + if (retried.get() == null) { + retried.set(message); + } else { + assertThat(message).isSameAs(retried.get()); + } + committable.fileCommittables().set(0, message); + return null; + }) + .when(callback) + .retry(any()); + try (FileStoreCommitImpl commit = + newCommitWithSnapshotCommit( + store, + "writer", + new RenamingSnapshotCommit(store.snapshotManager(), Lock.empty()), + store.options(), + false, + Collections.singletonList(callback))) { + commit.commit(prepared, false); + commit.filterCommitted(Collections.singletonList(prepared)); + commit.filterCommitted(Collections.singletonList(prepared)); + } + assertThat(retained.get().deltaFiles).hasSize(1); + assertThat(messages.get(0)).isSameAs(retried.get()); + assertThat(store.readKvsFromSnapshot(1)).hasSize(1); + verify(callback, times(2)).retry(any()); + } + @Test public void testReleaseFailureKeepsSuccessfulPublicationAndCallbacks() throws Exception { TestFileStore store = createStore(false); diff --git a/paimon-core/src/test/java/org/apache/paimon/operation/commit/ConflictDetectionTest.java b/paimon-core/src/test/java/org/apache/paimon/operation/commit/ConflictDetectionTest.java index d5e9e5bca16a..8dd62da2a8c5 100644 --- a/paimon-core/src/test/java/org/apache/paimon/operation/commit/ConflictDetectionTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/operation/commit/ConflictDetectionTest.java @@ -71,6 +71,7 @@ import java.util.List; import java.util.Optional; import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; import static org.apache.paimon.data.BinaryRow.EMPTY_ROW; import static org.apache.paimon.deletionvectors.DeletionVectorsIndexFile.DELETION_VECTORS_INDEX; @@ -79,6 +80,7 @@ import static org.apache.paimon.operation.commit.ConflictDetection.buildBaseEntriesWithDV; import static org.apache.paimon.operation.commit.ConflictDetection.buildDeltaEntriesWithDV; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -88,6 +90,54 @@ class ConflictDetectionTest { + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void testMergeOutOfMemoryIsNotFormattedAsConflict(boolean failInBase) { + OutOfMemoryError failure = new OutOfMemoryError("metadata allocation failed"); + AtomicInteger formatted = new AtomicInteger(); + SimpleFileEntry entry = + new SimpleFileEntry( + ADD, + EMPTY_ROW, + 0, + 1, + 0, + "allocation-failure", + Collections.emptyList(), + null, + EMPTY_ROW, + EMPTY_ROW, + null, + 0L, + null) { + @Override + public FileEntry.Identifier identifier() { + throw failure; + } + + @Override + public String toStringWithPartition(String partition) { + formatted.incrementAndGet(); + return super.toStringWithPartition(partition); + } + }; + List failing = Collections.singletonList(entry); + List empty = Collections.emptyList(); + ConflictDetection detection = createConflictDetection(null, false, false); + + assertThatThrownBy( + () -> + detection.checkConflicts( + snapshot(1), + failInBase ? failing : empty, + failInBase ? empty : failing, + Collections.emptyList(), + null, + Snapshot.CommitKind.APPEND)) + .isSameAs(failure); + assertThat(formatted.get()).isZero(); + } + @Test void testFileEntryWithDVToStringPreservesOriginalOutput() { // Guard the inherited toString() path after moving DV formatting to toStringWithPartition. diff --git a/paimon-core/src/test/java/org/apache/paimon/operation/commit/ManifestEntryChangesTest.java b/paimon-core/src/test/java/org/apache/paimon/operation/commit/ManifestEntryChangesTest.java new file mode 100644 index 000000000000..ed5702055d7e --- /dev/null +++ b/paimon-core/src/test/java/org/apache/paimon/operation/commit/ManifestEntryChangesTest.java @@ -0,0 +1,70 @@ +/* + * 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.paimon.operation.commit; + +import org.apache.paimon.table.sink.CommitMessage; +import org.apache.paimon.table.sink.CommitMessageImpl; +import org.apache.paimon.table.sink.CommitMessageList; +import org.apache.paimon.table.sink.CommitMessageSerializer; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +import static org.apache.paimon.manifest.ManifestCommittableSerializerTest.randomCompactIncrement; +import static org.apache.paimon.manifest.ManifestCommittableSerializerTest.randomNewFilesIncrement; +import static org.apache.paimon.mergetree.compact.MergeTreeCompactManagerTest.row; +import static org.assertj.core.api.Assertions.assertThat; + +/** Tests replaying all kinds of file changes without retaining decoded messages. */ +class ManifestEntryChangesTest { + + @Test + void testReplayMatchesEagerOrderAndBucketFallback() throws IOException { + List originals = Arrays.asList(message(null), message(8)); + List messages = + CommitMessageList.fromBytes(CommitMessageSerializer.serializeAll(originals)); + ManifestEntryChanges expected = new ManifestEntryChanges(4); + originals.forEach(expected::collect); + ManifestEntryChanges actual = ManifestEntryChanges.lazyChanges(4, messages); + for (int pass = 0; pass < 2; pass++) { + assertThat(actual.appendTableFiles) + .containsExactlyElementsOf(expected.appendTableFiles); + assertThat(actual.appendChangelog).containsExactlyElementsOf(expected.appendChangelog); + assertThat(actual.appendIndexFiles) + .containsExactlyElementsOf(expected.appendIndexFiles); + assertThat(actual.compactTableFiles) + .containsExactlyElementsOf(expected.compactTableFiles); + assertThat(actual.compactChangelog) + .containsExactlyElementsOf(expected.compactChangelog); + assertThat(actual.compactIndexFiles) + .containsExactlyElementsOf(expected.compactIndexFiles); + } + assertThat(actual.appendTableFiles.get(0)).isNotSameAs(actual.appendTableFiles.get(0)); + assertThat(actual.appendTableFiles.subList(1, 3)) + .containsExactlyElementsOf(expected.appendTableFiles.subList(1, 3)); + } + + private CommitMessage message(Integer totalBuckets) { + return new CommitMessageImpl( + row(1), 2, totalBuckets, randomNewFilesIncrement(), randomCompactIncrement()); + } +} diff --git a/paimon-core/src/test/java/org/apache/paimon/operation/commit/RowTrackingCommitUtilsTest.java b/paimon-core/src/test/java/org/apache/paimon/operation/commit/RowTrackingCommitUtilsTest.java new file mode 100644 index 000000000000..2356bad16b65 --- /dev/null +++ b/paimon-core/src/test/java/org/apache/paimon/operation/commit/RowTrackingCommitUtilsTest.java @@ -0,0 +1,147 @@ +/* + * 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.paimon.operation.commit; + +import org.apache.paimon.data.BinaryRow; +import org.apache.paimon.io.DataFileMeta; +import org.apache.paimon.manifest.FileKind; +import org.apache.paimon.manifest.FileSource; +import org.apache.paimon.manifest.ManifestEntry; +import org.apache.paimon.stats.SimpleStats; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.ListIterator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class RowTrackingCommitUtilsTest { + @Test + void testReplaysSequenceAndRowIdsWithoutCachingAssignedEntries() { + List input = + Arrays.asList( + entry("copied.parquet", 2, 10L, 2, 3), + entry("new.parquet", 3, null, 0, 0), + entry("update.parquet", 2, 0L, 2, 0)); + RowTrackingCommitUtils.RowTrackingAssigned expected = + RowTrackingCommitUtils.assignRowTracking(8, 5, input); + RowTrackingCommitUtils.RowTrackingAssigned actual = + RowTrackingCommitUtils.assignRowTracking( + 8, 5, new ReplayableList<>(input.size(), input::iterator)); + assertThat(actual.nextRowIdStart).isEqualTo(15); + assertThat(actual.assignedEntries).containsExactlyElementsOf(expected.assignedEntries); + assertThat(actual.assignedEntries).containsExactlyElementsOf(expected.assignedEntries); + assertThat(actual.assignedEntries.get(1)).isNotSameAs(actual.assignedEntries.get(1)); + assertThat(actual.assignedEntries.get(0).file().firstRowId()).isEqualTo(10); + assertThat(actual.assignedEntries.get(1).file().firstRowId()).isEqualTo(12); + assertThat(actual.assignedEntries.get(2).file().firstRowId()).isEqualTo(0); + assertThat(actual.assignedEntries.get(2).file().minSequenceNumber()).isEqualTo(2); + assertThat(actual.assignedEntries.get(2).file().maxSequenceNumber()).isEqualTo(8); + } + + @Test + void testDedicatedFilesKeepTheirParentRowIdRangesOnEveryReplay() { + List input = + Arrays.asList( + entry("first.parquet", 4, null, 0, 0), + entry("a-1.blob", 2, null, 0, 0, Collections.singletonList("a")), + entry("a-2.blob", 2, null, 0, 0, Collections.singletonList("a")), + entry("b.blob", 4, null, 0, 0, Collections.singletonList("b")), + entry("first.vector.bin", 4, null, 0, 0), + entry("second.parquet", 3, null, 0, 0), + entry("a-3.blob", 3, null, 0, 0, Collections.singletonList("a")), + entry("second.vector.bin", 3, null, 0, 0)); + RowTrackingCommitUtils.RowTrackingAssigned actual = + RowTrackingCommitUtils.assignRowTracking( + 7, 100, new ReplayableList<>(input.size(), input::iterator)); + assertThat(actual.nextRowIdStart).isEqualTo(107); + for (int pass = 0; pass < 2; pass++) { + assertThat(actual.assignedEntries) + .extracting(e -> e.file().firstRowId()) + .containsExactly(100L, 100L, 102L, 100L, 100L, 104L, 104L, 104L); + assertThat(actual.assignedEntries) + .extracting(e -> e.file().maxSequenceNumber()) + .containsOnly(7L); + } + } + + @Test + void testRejectsDedicatedFileBeforeParentDuringPreparation() { + List input = + Collections.singletonList( + entry("early.blob", 2, null, 0, 0, Collections.singletonList("a"))); + assertThatThrownBy( + () -> + RowTrackingCommitUtils.assignRowTracking( + 7, + 100, + new ReplayableList<>(input.size(), input::iterator))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("blobStart"); + } + + @Test + void testReplayListIteratorAndSubListContract() { + List list = new ReplayableList<>(3, () -> Arrays.asList(10, 20, 30).iterator()); + ListIterator iterator = list.listIterator(1); + assertThat(iterator.previous()).isEqualTo(10); + assertThat(iterator.next()).isEqualTo(10); + assertThat(iterator.next()).isEqualTo(20); + assertThat(iterator.previous()).isEqualTo(20); + assertThat(iterator.next()).isEqualTo(20); + assertThat(iterator.next()).isEqualTo(30); + assertThat(iterator.hasNext()).isFalse(); + assertThat(list.subList(1, 3)).containsExactly(20, 30); + assertThat(list.toArray()).containsExactly(10, 20, 30); + assertThatThrownBy(() -> list.get(-1)).isInstanceOf(IndexOutOfBoundsException.class); + assertThatThrownBy(() -> list.get(3)).isInstanceOf(IndexOutOfBoundsException.class); + } + + private ManifestEntry entry(String name, long rows, Long rowId, long min, long max) { + return entry(name, rows, rowId, min, max, null); + } + + private ManifestEntry entry( + String name, long rows, Long rowId, long min, long max, List cols) { + return ManifestEntry.create( + FileKind.ADD, + BinaryRow.EMPTY_ROW, + 0, + -1, + DataFileMeta.forAppend( + name, + 10, + rows, + SimpleStats.EMPTY_STATS, + min, + max, + 0, + Collections.emptyList(), + null, + FileSource.APPEND, + null, + null, + rowId, + cols)); + } +} diff --git a/paimon-core/src/test/java/org/apache/paimon/operation/commit/StreamingDataEvolutionBaseScanTest.java b/paimon-core/src/test/java/org/apache/paimon/operation/commit/StreamingDataEvolutionBaseScanTest.java new file mode 100644 index 000000000000..555daaa95fdf --- /dev/null +++ b/paimon-core/src/test/java/org/apache/paimon/operation/commit/StreamingDataEvolutionBaseScanTest.java @@ -0,0 +1,264 @@ +/* + * 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.paimon.operation.commit; + +import org.apache.paimon.CoreOptions; +import org.apache.paimon.Snapshot; +import org.apache.paimon.data.BinaryRow; +import org.apache.paimon.disk.IOManager; +import org.apache.paimon.io.DataFileMeta; +import org.apache.paimon.manifest.ManifestEntry; +import org.apache.paimon.manifest.SimpleFileEntry; +import org.apache.paimon.operation.FileEntryMergeBuffer; +import org.apache.paimon.table.BucketMode; +import org.apache.paimon.types.RowType; +import org.apache.paimon.utils.Range; +import org.apache.paimon.utils.ThrowingConsumer; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.apache.paimon.data.BinaryRow.EMPTY_ROW; +import static org.apache.paimon.manifest.FileKind.ADD; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anySet; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +/** + * Checks equivalence of the DE base scan and its streaming producer, including conditional dedup. + */ +class StreamingDataEvolutionBaseScanTest { + + @TempDir Path temporary; + + private final Snapshot snapshot = mock(Snapshot.class); + private final List partitions = Collections.singletonList(EMPTY_ROW); + private final Range range = new Range(10, 19); + + @Test + void testSupplementalBranchDeduplicatesEvenWhenItsScanIsEmpty() throws Exception { + SimpleFileEntry first = base("base", 10L, 10L); + Fixture fixture = + new Fixture(Arrays.asList(first, base("base", 100L, 2L)), Collections.emptyList()); + List delta = Collections.singletonList(delta("new", 10L)); + + assertThat(fixture.streamAndMerge(delta, true)).containsExactly(first); + assertThat(fixture.original(delta)).containsExactly(first); + verify(fixture.scanner) + .forEachEntryFromChangedRowRanges( + eq(snapshot), eq(partitions), eq(Collections.singletonList(range)), any()); + verify(fixture.scanner) + .forEachEntryFromDataFiles( + eq(snapshot), eq(partitions), eq(Collections.singleton("new")), any()); + } + + @Test + void testFirstScanSatisfyingAllReferencesKeepsDuplicateConflict() throws Exception { + SimpleFileEntry first = base("base", 10L, 10L); + Fixture fixture = new Fixture(Arrays.asList(first, first), Collections.emptyList()); + List delta = Collections.singletonList(delta("base", 10L)); + + assertThat(fixture.original(delta)).containsExactly(first, first); + assertThatThrownBy(() -> fixture.streamAndMerge(delta, false)) + .isInstanceOf(IllegalStateException.class); + verify(fixture.scanner, never()) + .forEachEntryFromDataFiles(any(), anyList(), anySet(), any()); + } + + @Test + void testSupplementalEntriesKeepFirstPayloadAndScanOrder() throws Exception { + SimpleFileEntry first = base("z", 10L, 10L); + SimpleFileEntry supplemental = base("a", null, 2L); + Fixture fixture = + new Fixture( + Arrays.asList(first, base("z", 100L, 2L)), + Arrays.asList(supplemental, base("a", null, 3L))); + List delta = Collections.singletonList(delta("a", 10L)); + + assertThat(fixture.streamAndMerge(delta, true)).containsExactly(first, supplemental); + assertThat(fixture.original(delta)).containsExactly(first, supplemental); + } + + @Test + void testNameOnlyBranchDoesNotDeduplicate() throws Exception { + SimpleFileEntry first = base("legacy", null, 2L); + Fixture fixture = new Fixture(Collections.emptyList(), Arrays.asList(first, first)); + List delta = Collections.singletonList(delta("legacy", null)); + + assertThat(fixture.original(delta)).containsExactly(first, first); + assertThatThrownBy(() -> fixture.streamAndMerge(delta, false)) + .isInstanceOf(IllegalStateException.class); + verify(fixture.scanner, never()) + .forEachEntryFromChangedRowRanges(any(), anyList(), anyList(), any()); + } + + @Test + void testEmptyChangesDoNotScan() throws Exception { + Fixture fixture = new Fixture(Collections.emptyList(), Collections.emptyList()); + + assertThat(fixture.streamAndMerge(Collections.emptyList(), false)).isEmpty(); + verifyNoInteractions(fixture.scanner); + } + + @Test + void testConsumerFailureStopsBeforeSupplementalScan() throws Exception { + Fixture fixture = + new Fixture( + Collections.singletonList(base("base", 10L, 10L)), Collections.emptyList()); + IOException failure = new IOException("base consumer failed"); + + assertThatThrownBy( + () -> + fixture.detection.forEachBaseDataFile( + snapshot, + partitions, + Collections.singletonList(delta("new", 10L)), + Collections.emptyList(), + entry -> { + throw failure; + })) + .isSameAs(failure); + verify(fixture.scanner, never()) + .forEachEntryFromDataFiles(any(), anyList(), anySet(), any()); + } + + private final class Fixture { + private final CommitScanner scanner = mock(CommitScanner.class); + private final DataEvolutionConflictDetection detection = + new DataEvolutionConflictDetection( + "test", + "writer", + RowType.of(), + null, + BucketMode.BUCKET_UNAWARE, + false, + false, + null, + null, + scanner); + + private Fixture(List byRange, List byName) + throws Exception { + when(scanner.readAllEntriesFromChangedRowRanges( + eq(snapshot), eq(partitions), anyList())) + .thenReturn(byRange); + when(scanner.readAllEntriesFromDataFiles(eq(snapshot), eq(partitions), anySet())) + .thenReturn(byName); + doAnswer( + invocation -> { + ThrowingConsumer consumer = + invocation.getArgument(3); + for (SimpleFileEntry entry : byRange) { + consumer.accept(entry); + } + return null; + }) + .when(scanner) + .forEachEntryFromChangedRowRanges( + eq(snapshot), eq(partitions), anyList(), any()); + doAnswer( + invocation -> { + ThrowingConsumer consumer = + invocation.getArgument(3); + for (SimpleFileEntry entry : byName) { + consumer.accept(entry); + } + return null; + }) + .when(scanner) + .forEachEntryFromDataFiles(eq(snapshot), eq(partitions), anySet(), any()); + } + + private List original(List delta) { + return detection.scanBaseDataFiles( + snapshot, + partitions, + delta, + Collections.emptyList(), + Snapshot.CommitKind.APPEND, + null, + false); + } + + private List streamAndMerge( + List delta, boolean expectedDeduplication) throws Exception { + List result = new ArrayList<>(); + try (IOManager io = IOManager.create(temporary.toString()); + FileEntryMergeBuffer buffer = + new FileEntryMergeBuffer(new CoreOptions(Collections.emptyMap()), io)) { + boolean deduplicate = + detection.forEachBaseDataFile( + snapshot, + partitions, + delta, + Collections.emptyList(), + buffer::writeBase); + assertThat(deduplicate).isEqualTo(expectedDeduplication); + buffer.forEachMerged(deduplicate, result::add); + } + return result; + } + } + + private ManifestEntry delta(String name, Long first) { + ManifestEntry entry = mock(ManifestEntry.class); + DataFileMeta file = mock(DataFileMeta.class); + when(entry.kind()).thenReturn(ADD); + when(entry.file()).thenReturn(file); + when(file.fileName()).thenReturn(name); + when(file.firstRowId()).thenReturn(first); + if (first != null) { + when(file.nonNullRowIdRange()).thenReturn(range); + } + return entry; + } + + private static SimpleFileEntry base(String name, Long first, long count) { + return new SimpleFileEntry( + ADD, + EMPTY_ROW, + 0, + 1, + 0, + name, + Collections.emptyList(), + null, + EMPTY_ROW, + EMPTY_ROW, + null, + count, + first); + } +} diff --git a/paimon-core/src/test/java/org/apache/paimon/operation/commit/StreamingDataEvolutionConflictTest.java b/paimon-core/src/test/java/org/apache/paimon/operation/commit/StreamingDataEvolutionConflictTest.java new file mode 100644 index 000000000000..e213b715e644 --- /dev/null +++ b/paimon-core/src/test/java/org/apache/paimon/operation/commit/StreamingDataEvolutionConflictTest.java @@ -0,0 +1,588 @@ +/* + * 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.paimon.operation.commit; + +import org.apache.paimon.CoreOptions; +import org.apache.paimon.Snapshot; +import org.apache.paimon.Snapshot.CommitKind; +import org.apache.paimon.disk.BufferFileWriter; +import org.apache.paimon.disk.FileIOChannel; +import org.apache.paimon.disk.IOManager; +import org.apache.paimon.disk.IOManagerImpl; +import org.apache.paimon.globalindex.CentroidIndexMeta; +import org.apache.paimon.globalindex.ResultEntry; +import org.apache.paimon.index.DataEvolutionIndexSourceMeta; +import org.apache.paimon.index.GlobalIndexMeta; +import org.apache.paimon.index.IndexFileMeta; +import org.apache.paimon.io.DataFileMeta; +import org.apache.paimon.manifest.FileKind; +import org.apache.paimon.manifest.FileSource; +import org.apache.paimon.manifest.IndexManifestEntry; +import org.apache.paimon.manifest.ManifestEntry; +import org.apache.paimon.manifest.SimpleFileEntry; +import org.apache.paimon.options.MemorySize; +import org.apache.paimon.options.Options; +import org.apache.paimon.schema.Schema; +import org.apache.paimon.schema.TableSchema; +import org.apache.paimon.stats.SimpleStats; +import org.apache.paimon.table.BucketMode; +import org.apache.paimon.types.DataTypes; +import org.apache.paimon.types.RowType; +import org.apache.paimon.utils.FileStorePathFactory; +import org.apache.paimon.utils.Range; +import org.apache.paimon.utils.SnapshotManager; +import org.apache.paimon.utils.ThrowingConsumer; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import static org.apache.paimon.data.BinaryRow.EMPTY_ROW; +import static org.apache.paimon.manifest.FileKind.ADD; +import static org.apache.paimon.manifest.FileKind.DELETE; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anySet; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Whole conflict-check comparisons; successful streaming checks must not collect legacy bases. */ +class StreamingDataEvolutionConflictTest { + + @TempDir Path temporary; + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void testCentroidSourceChangesMatchOrdinaryCheck(boolean indexedColumn) throws Exception { + Fixture fixture = new Fixture(list(file("base", ADD, 0L, 10, 0, -1)), 10, false); + TableSchema schema = + TableSchema.create( + 0, + Schema.newBuilder() + .column("a", DataTypes.INT()) + .column("b", DataTypes.INT()) + .build()); + when(fixture.scanner.schema(0)).thenReturn(schema); + DataFileMeta update = + file("updated", ADD, 0L, 10, 0, -1) + .file() + .withWriteCols(Collections.singletonList(indexedColumn ? "a" : "b")); + when(fixture.scanner.readIncrementalEntries( + fixture.snapshot, Collections.singletonList(EMPTY_ROW))) + .thenReturn( + Collections.singletonList( + ManifestEntry.create(ADD, EMPTY_ROW, 0, -1, update))); + byte[] meta = + CentroidIndexMeta.router(new ResultEntry("model", 0, null), "model", 2).meta(); + IndexFileMeta indexFile = + new IndexFileMeta( + "ivf-pq", + "router", + 100, + 0, + null, + null, + new GlobalIndexMeta( + 0, + 9, + 0, + null, + meta, + new DataEvolutionIndexSourceMeta(1).serialize())); + List changes = + Collections.singletonList(new IndexManifestEntry(ADD, EMPTY_ROW, 0, indexFile)); + Optional ordinary = + fixture.detection.checkConflicts( + fixture.snapshot, + fixture.base, + Collections.emptyList(), + changes, + null, + CommitKind.APPEND); + assertThat(ordinary.isPresent()).isEqualTo(indexedColumn); + try (IOManager io = IOManager.create(temporary.toString())) { + Optional streaming = + fixture.detection.checkConflictsStreaming( + options(), + io, + fixture.snapshot, + Collections.singletonList(EMPTY_ROW), + Collections.emptyList(), + changes, + null, + CommitKind.APPEND); + assertThat(streaming.isPresent()).isEqualTo(indexedColumn); + if (indexedColumn) { + assertThat(streaming.get()).hasMessage(ordinary.get().getMessage()); + assertThat(streaming.get()).hasMessageContaining("source rows changed"); + } + fixture.assertNoLegacyBaseCollection(); + } + } + + @ParameterizedTest(name = "{0}") + @MethodSource("cases") + void testMatchesOriginal( + String name, + List base, + List delta, + CommitKind kind, + long nextRowId, + boolean checkRanges, + boolean valid) + throws Exception { + Fixture fixture = new Fixture(base, nextRowId, checkRanges); + Outcome expected = fixture.original(delta, kind); + assertThat(expected.error == null).as(name).isEqualTo(valid); + try (IOManager io = IOManager.create(temporary.toString())) { + Outcome actual = + outcome( + () -> + fixture.detection.checkConflictsStreaming( + options(), + io, + fixture.snapshot, + Collections.singletonList(EMPTY_ROW), + delta, + Collections.emptyList(), + null, + kind)); + assertThat(actual.thrown).as(name).isEqualTo(expected.thrown); + assertThat(actual.error == null).as(name).isEqualTo(valid); + if (!valid) { + assertThat(actual.error.getClass()).as(name).isEqualTo(expected.error.getClass()); + assertThat(actual.error.getMessage()) + .as(name) + .isEqualTo(expected.error.getMessage()); + } else { + fixture.assertNoLegacyBaseCollection(); + } + } + try (Stream files = Files.walk(temporary)) { + assertThat(files.filter(Files::isRegularFile).count()).isZero(); + } + } + + @Test + void testSuccessfulUpdateActuallySpillsWithoutLegacyCollection() throws Exception { + List base = new ArrayList<>(); + List delta = new ArrayList<>(); + for (int i = 0; i < 10000; i++) { + base.add(file("base-" + i, ADD, i * 2L, 2, 0, -1)); + delta.add(file("update-" + i, ADD, i * 2L, 2, 0, -1)); + } + Fixture fixture = new Fixture(base, 20000, true); + try (ObservedIO io = new ObservedIO(temporary.toString())) { + assertThat( + fixture.detection.checkConflictsStreaming( + options(), + io, + fixture.snapshot, + Collections.singletonList(EMPTY_ROW), + delta, + Collections.emptyList(), + null, + CommitKind.APPEND)) + .isEmpty(); + assertThat(io.spills.get()).isPositive(); + fixture.assertNoLegacyBaseCollection(); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void testGlobalIndexUsesBaseDedicatedFilesAndBucketScope(boolean wrongBucket) throws Exception { + Fixture fixture = new Fixture(list(file("base.blob", ADD, 0L, 10, 0, -1)), 10, false); + GlobalIndexMeta global = mock(GlobalIndexMeta.class); + when(global.rowRange()).thenReturn(new Range(0, 9)); + IndexFileMeta indexFile = mock(IndexFileMeta.class); + when(indexFile.globalIndexMeta()).thenReturn(global); + when(indexFile.fileName()).thenReturn("index"); + IndexManifestEntry index = mock(IndexManifestEntry.class); + when(index.kind()).thenReturn(ADD); + when(index.partition()).thenReturn(EMPTY_ROW); + when(index.bucket()).thenReturn(wrongBucket ? 1 : 0); + when(index.indexFile()).thenReturn(indexFile); + List changes = Collections.singletonList(index); + Outcome expected = + outcome( + () -> + fixture.detection.checkConflicts( + fixture.snapshot, + fixture.base, + Collections.emptyList(), + changes, + null, + CommitKind.APPEND)); + try (IOManager io = IOManager.create(temporary.toString())) { + Outcome actual = + outcome( + () -> + fixture.detection.checkConflictsStreaming( + options(), + io, + fixture.snapshot, + Collections.singletonList(EMPTY_ROW), + Collections.emptyList(), + changes, + null, + CommitKind.APPEND)); + assertThat(actual.thrown).isEqualTo(expected.thrown); + assertThat(actual.error == null).isEqualTo(!wrongBucket); + if (wrongBucket) { + assertThat(actual.error.getClass()).isEqualTo(expected.error.getClass()); + assertThat(actual.error.getMessage()).isEqualTo(expected.error.getMessage()); + } else { + fixture.assertNoLegacyBaseCollection(); + } + } + } + + @Test + void testHistoricalFieldConflictStillRunsAfterStreamingChecks() throws Exception { + Fixture fixture = new Fixture(list(file("f", ADD, 0L, 10, 0, -1)), 10, true); + List delta = list(file("g", ADD, 0L, 10, 0, -1)); + when(fixture.scanner.readIncrementalEntries(any(), anyList())) + .thenReturn(list(file("concurrent", ADD, 0L, 10, 0, -1))); + RowIdConflictChecker checker = mock(RowIdConflictChecker.class); + when(checker.isEmpty()).thenReturn(false); + when(checker.conflictsWith(any())).thenReturn(true); + Outcome expected = + outcome( + () -> + fixture.detection.checkConflicts( + fixture.snapshot, + fixture.base, + SimpleFileEntry.from(delta), + Collections.emptyList(), + checker, + CommitKind.APPEND)); + assertThat(expected.error).isNotNull(); + try (IOManager io = IOManager.create(temporary.toString())) { + Outcome actual = + outcome( + () -> + fixture.detection.checkConflictsStreaming( + options(), + io, + fixture.snapshot, + Collections.singletonList(EMPTY_ROW), + delta, + Collections.emptyList(), + checker, + CommitKind.APPEND)); + assertThat(actual.thrown).isEqualTo(expected.thrown); + assertThat(actual.error).isNotNull(); + assertThat(actual.error.getClass()).isEqualTo(expected.error.getClass()); + assertThat(actual.error.getMessage()).isEqualTo(expected.error.getMessage()); + fixture.assertNoLegacyBaseCollection(); + } + } + + private static Stream cases() { + ManifestEntry f = file("f", ADD, 0L, 10, 0, -1); + ManifestEntry z = file("z", ADD, 10L, 10, 0, -1); + ManifestEntry deleteF = file("f", DELETE, 0L, 10, 0, -1); + ManifestEntry deleteZ = file("z", DELETE, 10L, 10, 0, -1); + ManifestEntry g = file("g", ADD, 0L, 10, 0, -1); + return Stream.of( + example("partial update", list(f), list(g), CommitKind.APPEND, 10, true, true), + example( + "new IDs", + list(f), + list(file("g", ADD, 10L, 10, 0, -1)), + CommitKind.APPEND, + 10, + true, + true), + example( + "ordinary subrange", + list(f), + list(file("g", ADD, 2L, 4, 0, -1)), + CommitKind.APPEND, + 10, + true, + false), + example( + "stale DELETE", + list(file("f", ADD, 100L, 10, 0, -1)), + list(deleteF), + CommitKind.APPEND, + 110, + true, + false), + example( + "different overlapping ranges", + list(f), + list(file("g", ADD, 0L, 20, 0, -1)), + CommitKind.APPEND, + 0, + true, + false), + example( + "dedicated containment", + list(f), + list(file("g.blob", ADD, 2L, 4, 0, -1)), + CommitKind.APPEND, + 10, + true, + true), + example( + "dedicated spans adjacent ranges", + list(f, z), + list(file("g.blob", ADD, 0L, 20, 0, -1)), + CommitKind.APPEND, + 0, + true, + false), + example( + "compact adjacent coverage", + list(f, z), + list(deleteF, deleteZ, file("g", ADD, 0L, 20, 0, -1)), + CommitKind.COMPACT, + 20, + true, + true), + example( + "compact bucket scope", + list(f), + list(deleteF, file("g", ADD, 0L, 10, 1, -1)), + CommitKind.COMPACT, + 10, + true, + false), + example( + "union exact", + list(f, file("z", ADD, 5L, 10, 0, -1)), + list(file("g", ADD, 0L, 15, 0, -1)), + CommitKind.APPEND, + 15, + false, + true), + example( + "union subrange rejected", + list(f, file("z", ADD, 5L, 10, 0, -1)), + list(g), + CommitKind.APPEND, + 15, + false, + false), + example( + "delta duplicate throws", + list(f), + list(g, g), + CommitKind.APPEND, + 10, + true, + false), + example( + "bucket conflict precedes delta duplicate", + list(file("f", ADD, 0L, 10, 0, 1)), + list(file("g", ADD, 0L, 10, 0, 2), file("g", ADD, 0L, 10, 0, 2)), + CommitKind.APPEND, + 10, + true, + false), + example( + "unassigned new IDs", + Collections.emptyList(), + list(file("g", ADD, null, 10, 0, -1)), + CommitKind.APPEND, + 0, + true, + true), + example( + "64 bit row IDs", + list(file("f", ADD, 1L << 40, 10, 0, -1)), + list(file("g", ADD, 1L << 40, 10, 0, -1)), + CommitKind.APPEND, + (1L << 40) + 10, + true, + true)); + } + + private static Arguments example( + String name, + List base, + List delta, + CommitKind kind, + long next, + boolean ranges, + boolean valid) { + return Arguments.of(name, base, delta, kind, next, ranges, valid); + } + + private static List list(ManifestEntry... entries) { + return Arrays.asList(entries); + } + + private static ManifestEntry file( + String name, FileKind kind, Long first, long count, int bucket, int totalBuckets) { + return ManifestEntry.create( + kind, + EMPTY_ROW, + bucket, + totalBuckets, + DataFileMeta.forAppend( + name, + 100, + count, + SimpleStats.EMPTY_STATS, + 0, + 0, + 0, + Collections.emptyList(), + null, + FileSource.APPEND, + Collections.singletonList("a"), + null, + first, + Collections.singletonList("a"))); + } + + private static CoreOptions options() { + Options options = new Options(); + options.set(CoreOptions.SORT_SPILL_BUFFER_SIZE, MemorySize.ofKibiBytes(256)); + options.set(CoreOptions.PAGE_SIZE, MemorySize.ofKibiBytes(4)); + return new CoreOptions(options); + } + + private static final class Fixture { + private final CommitScanner scanner = mock(CommitScanner.class); + private final Snapshot snapshot = mock(Snapshot.class); + private final DataEvolutionConflictDetection detection; + private final List base; + + private Fixture(List entries, long next, boolean ranges) throws Exception { + base = SimpleFileEntry.from(entries); + when(snapshot.nextRowId()).thenReturn(next); + when(snapshot.commitUser()).thenReturn("base-writer"); + when(snapshot.id()).thenReturn(2L); + when(snapshot.commitKind()).thenReturn(CommitKind.APPEND); + SnapshotManager snapshots = mock(SnapshotManager.class); + Snapshot start = mock(Snapshot.class); + when(start.nextRowId()).thenReturn(next); + when(snapshots.snapshot(1L)).thenReturn(start); + when(snapshots.snapshot(2L)).thenReturn(snapshot); + FileStorePathFactory paths = mock(FileStorePathFactory.class); + when(paths.getPartitionString(any())).thenReturn(""); + detection = + new DataEvolutionConflictDetection( + "table", + "writer", + RowType.of(), + paths, + BucketMode.BUCKET_UNAWARE, + false, + false, + null, + snapshots, + scanner); + if (ranges) { + detection.setRowIdCheckFromSnapshot(1L); + } + when(scanner.readAllEntriesFromChangedRowRanges(any(), anyList(), anyList())) + .thenReturn(base); + when(scanner.readAllEntriesFromDataFiles(any(), anyList(), anySet())) + .thenReturn(Collections.emptyList()); + doAnswer( + invocation -> { + ThrowingConsumer consumer = + invocation.getArgument(3); + for (SimpleFileEntry entry : base) { + consumer.accept(entry); + } + return null; + }) + .when(scanner) + .forEachEntryFromChangedRowRanges(any(), anyList(), anyList(), any()); + } + + private Outcome original(List delta, CommitKind kind) { + return outcome( + () -> + detection.checkConflicts( + snapshot, + base, + SimpleFileEntry.from(delta), + Collections.emptyList(), + null, + kind)); + } + + private void assertNoLegacyBaseCollection() { + verify(scanner, never()) + .readAllEntriesFromChangedRowRanges(any(), anyList(), anyList()); + verify(scanner, never()).readAllEntriesFromDataFiles(any(), anyList(), anySet()); + verify(scanner, never()).readAllEntriesFromChangedPartitions(any(), anyList()); + } + } + + private static Outcome outcome(Supplier> supplier) { + try { + return new Outcome(supplier.get().orElse(null), false); + } catch (RuntimeException failure) { + return new Outcome(failure, true); + } + } + + private static final class Outcome { + private final RuntimeException error; + private final boolean thrown; + + private Outcome(RuntimeException error, boolean thrown) { + this.error = error; + this.thrown = thrown; + } + } + + private static final class ObservedIO extends IOManagerImpl { + private final AtomicInteger spills = new AtomicInteger(); + + private ObservedIO(String directory) { + super(directory); + } + + @Override + public BufferFileWriter createBufferFileWriter(FileIOChannel.ID channel) + throws IOException { + spills.incrementAndGet(); + return super.createBufferFileWriter(channel); + } + } +} diff --git a/paimon-core/src/test/java/org/apache/paimon/operation/metrics/CommitStatsTest.java b/paimon-core/src/test/java/org/apache/paimon/operation/metrics/CommitStatsTest.java index e705dfd41012..a789236594fa 100644 --- a/paimon-core/src/test/java/org/apache/paimon/operation/metrics/CommitStatsTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/operation/metrics/CommitStatsTest.java @@ -24,8 +24,10 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import java.util.AbstractList; import java.util.ArrayList; import java.util.Collections; +import java.util.Iterator; import java.util.List; import static org.apache.paimon.io.DataFileTestUtils.row; @@ -34,6 +36,48 @@ /** Tests for {@link org.apache.paimon.operation.metrics.CommitStats}. */ public class CommitStatsTest { + @Test + public void testConsumesEachChangeListOnce() { + CountingList append = new CountingList(appendDataFiles); + CountingList appendLog = new CountingList(appendChangelogFiles); + CountingList compact = new CountingList(compactDataFiles); + CountingList compactLog = new CountingList(compactChangelogFiles); + CommitStats actual = new CommitStats(append, appendLog, compact, compactLog, 10, 2, 3, 4); + assertThat(actual.getTableFilesAdded()).isEqualTo(4); + assertThat(actual.getTableFilesDeleted()).isEqualTo(1); + assertThat(actual.getNumPartitionsWritten()).isEqualTo(3); + assertThat(actual.getNumBucketsWritten()).isEqualTo(3); + assertThat(append.traversals).isEqualTo(1); + assertThat(appendLog.traversals).isEqualTo(1); + assertThat(compact.traversals).isEqualTo(1); + assertThat(compactLog.traversals).isEqualTo(1); + } + + private static class CountingList extends AbstractList { + private final List entries; + private int traversals; + + private CountingList(List entries) { + this.entries = entries; + } + + @Override + public int size() { + return entries.size(); + } + + @Override + public ManifestEntry get(int index) { + return entries.get(index); + } + + @Override + public Iterator iterator() { + traversals++; + return entries.iterator(); + } + } + private static List files = new ArrayList<>(); private static List appendDataFiles = new ArrayList<>(); private static List appendChangelogFiles = new ArrayList<>(); diff --git a/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalPlanningTest.java b/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalPlanningTest.java new file mode 100644 index 000000000000..0f7b33a98f2a --- /dev/null +++ b/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionIncrementalPlanningTest.java @@ -0,0 +1,214 @@ +/* + * 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.paimon.table; + +import org.apache.paimon.catalog.FileSystemCatalog; +import org.apache.paimon.catalog.Identifier; +import org.apache.paimon.data.GenericRow; +import org.apache.paimon.data.InternalRow; +import org.apache.paimon.disk.IOManagerImpl; +import org.apache.paimon.fs.Path; +import org.apache.paimon.fs.local.LocalFileIO; +import org.apache.paimon.predicate.PredicateBuilder; +import org.apache.paimon.schema.Schema; +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.source.DataFileMetaStore; +import org.apache.paimon.table.source.DataSplit; +import org.apache.paimon.table.source.ReadBuilder; +import org.apache.paimon.table.source.TableScan; +import org.apache.paimon.types.DataTypes; +import org.apache.paimon.utils.CloseableIterator; +import org.apache.paimon.utils.Range; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** End-to-end regressions for bounded incremental metadata planning. */ +class DataEvolutionIncrementalPlanningTest { + + @TempDir java.nio.file.Path directory; + + @ParameterizedTest + @ValueSource(ints = {2, 3}) + void testSmallScanBufferPreservesRows(int pages) throws Exception { + FileStoreTable table = + createTable(false) + .copy( + Collections.singletonMap( + "sort-spill-buffer-size", pages * 64 + " kb")); + write(table, GenericRow.of(1, 0), GenericRow.of(2, 0)); + ReadBuilder read = table.newReadBuilder(); + assertThat(readIds(read, read.newScan().plan())).containsExactly(1, 2); + try (IOManagerImpl io = new IOManagerImpl(directory.toString()); + DataFileMetaStore store = newStore(1024 * 1024)) { + TableScan.Plan plan = plan(read, store, io); + assertThat(readIds(read, plan)).containsExactly(1, 2); + // The unused fallback store is sealed and stays within its original empty budget. + if (pages == 2) { + assertThat(store.serializedBytes()).isEqualTo(Long.BYTES); + assertThat(store.slice(0, 0)).isEmpty(); + } else { + assertThat(store.serializedBytes()).isGreaterThan(Long.BYTES); + } + } + } + + @Test + void testSmallLimitFitsReplayBudget() throws Exception { + FileStoreTable table = createTable(false); + for (int id = 0; id < 29; id++) { + write(table, GenericRow.of(id, 0)); + } + ReadBuilder read = table.newReadBuilder().withLimit(1); + TableScan.Plan classic = read.newScan().plan(); + assertThat(classic.splits()).hasSize(1); + assertThat(readIds(read, classic)).containsExactly(0); + try (IOManagerImpl io = new IOManagerImpl(directory.toString()); + DataFileMetaStore store = newStore(1024)) { + TableScan.Plan plan = plan(read, store, io); + assertThat(plan.splits()).hasSize(1); + assertThat(readIds(read, plan)).containsExactly(0); + assertThat(store.serializedBytes()).isLessThanOrEqualTo(1024); + } + } + + @Test + void testLimitDoesNotCountRowsRemovedByDataFilter() throws Exception { + FileStoreTable table = createTable(false); + write(table, GenericRow.of(0, 0), GenericRow.of(100, 0)); + write(table, GenericRow.of(101, 0)); + ReadBuilder read = + table.newReadBuilder() + .withFilter(new PredicateBuilder(table.rowType()).greaterOrEqual(0, 100)) + .withLimit(2); + try (IOManagerImpl io = new IOManagerImpl(directory.toString()); + DataFileMetaStore store = newStore(1024 * 1024)) { + assertThat(readIds(read, plan(read, store, io))).containsExactlyInAnyOrder(100, 101); + } + } + + @Test + void testLimitDoesNotCountRowsOutsideRowRanges() throws Exception { + FileStoreTable table = createTable(false); + write(table, GenericRow.of(0, 0), GenericRow.of(1, 0)); + write(table, GenericRow.of(2, 0), GenericRow.of(3, 0)); + ReadBuilder read = + table.newReadBuilder() + .withRowRanges(Arrays.asList(new Range(0, 0), new Range(2, 2))) + .withLimit(2); + try (IOManagerImpl io = new IOManagerImpl(directory.toString()); + DataFileMetaStore store = newStore(1024 * 1024)) { + assertThat(readIds(read, plan(read, store, io))).containsExactlyInAnyOrder(0, 2); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void testInterleavedPartitionsKeepSplitCoalescing(boolean deletionVectors) throws Exception { + FileStoreTable table = createTable(deletionVectors); + write(table, GenericRow.of(0, 0), GenericRow.of(1, 1)); + for (int id = 2; id < 26; id++) { + write(table, GenericRow.of(id, id % 2)); + } + ReadBuilder read = table.newReadBuilder(); + TableScan.Plan classic = read.newScan().plan(); + List expected = readIds(read, classic); + assertThat(expected).hasSize(26).doesNotHaveDuplicates(); + try (IOManagerImpl io = new IOManagerImpl(directory.toString()); + DataFileMetaStore store = newStore(1024 * 1024)) { + TableScan.Plan plan = plan(read, store, io); + assertThat(plan.splits()).hasSize(classic.splits().size()); + assertThat(readIds(read, plan)).containsExactlyInAnyOrderElementsOf(expected); + for (org.apache.paimon.table.source.Split split : plan.splits()) { + DataSplit data = (DataSplit) split; + assertThat(data.dataFiles()).hasSize(13); + assertThat(data.rawConvertible()).isTrue(); + } + } + } + + private FileStoreTable createTable(boolean deletionVectors) throws Exception { + try (FileSystemCatalog catalog = + new FileSystemCatalog( + LocalFileIO.create(), new Path(directory.resolve("warehouse").toUri()))) { + catalog.createDatabase("test_db", false); + Identifier identifier = Identifier.create("test_db", "incremental_plan"); + catalog.createTable( + identifier, + Schema.newBuilder() + .column("id", DataTypes.INT()) + .column("pt", DataTypes.INT()) + .partitionKeys("pt") + .option("bucket", "-1") + .option("file.format", "parquet") + .option("write-only", "true") + .option("data-evolution.enabled", "true") + .option("row-tracking.enabled", "true") + .option("sort-spill-buffer-size", "1 mb") + .option("page-size", "64 kb") + .option("deletion-vectors.enabled", String.valueOf(deletionVectors)) + .build(), + false); + return (FileStoreTable) catalog.getTable(identifier); + } + } + + private void write(FileStoreTable table, InternalRow... rows) throws Exception { + BatchWriteBuilder builder = table.newBatchWriteBuilder(); + try (BatchTableWrite write = builder.newWrite(); + BatchTableCommit commit = builder.newCommit()) { + for (InternalRow row : rows) { + write.write(row); + } + commit.commit(write.prepareCommit()); + } + } + + private DataFileMetaStore newStore(long budget) throws Exception { + return new DataFileMetaStore(Files.createTempDirectory(directory, "metadata-"), budget); + } + + private TableScan.Plan plan(ReadBuilder read, DataFileMetaStore store, IOManagerImpl io) { + return read.newScan(table -> table.newSnapshotReader().withIncrementalPlanning(store, io)) + .plan(); + } + + private List readIds(ReadBuilder read, TableScan.Plan plan) throws Exception { + List ids = new ArrayList<>(); + try (CloseableIterator rows = + read.newRead().executeFilter().createReader(plan).toCloseableIterator()) { + while (rows.hasNext()) { + ids.add(rows.next().getInt(0)); + } + } + return ids; + } +} diff --git a/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionSmallBufferTest.java b/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionSmallBufferTest.java new file mode 100644 index 000000000000..be3818121e59 --- /dev/null +++ b/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionSmallBufferTest.java @@ -0,0 +1,167 @@ +/* + * 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.paimon.table; + +import org.apache.paimon.CoreOptions; +import org.apache.paimon.catalog.Catalog; +import org.apache.paimon.catalog.CatalogContext; +import org.apache.paimon.catalog.CatalogFactory; +import org.apache.paimon.catalog.Identifier; +import org.apache.paimon.data.BinaryString; +import org.apache.paimon.data.GenericRow; +import org.apache.paimon.data.InternalRow; +import org.apache.paimon.fs.Path; +import org.apache.paimon.reader.RecordReaderIterator; +import org.apache.paimon.schema.Schema; +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.CommitMessage; +import org.apache.paimon.table.sink.CommitMessageImpl; +import org.apache.paimon.types.DataTypes; + +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +import static org.apache.paimon.errors.ErrorMessages.DATA_EVOLUTION_ROW_ID_CONFLICT_MESSAGE; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** Small sort buffers must retain ordinary Data Evolution commit semantics. */ +class DataEvolutionSmallBufferTest { + + @TempDir java.nio.file.Path temporary; + + @ParameterizedTest + @CsvSource({ + "off, 4", + "lightweight, 4", + "streaming, 4", + "off, 6", + "lightweight, 6", + "streaming, 6" + }) + void testPartialUpdateAndStaleConflict(String mode, int pages) throws Exception { + FileStoreTable table; + try (Catalog catalog = + CatalogFactory.createCatalog(CatalogContext.create(new Path(temporary.toUri())))) { + catalog.createDatabase("default", true); + Identifier identifier = Identifier.create("default", "small_buffer"); + catalog.createTable( + identifier, + Schema.newBuilder() + .column("f0", DataTypes.INT()) + .column("f1", DataTypes.STRING()) + .column("f2", DataTypes.STRING()) + .option(CoreOptions.BUCKET.key(), "-1") + .option(CoreOptions.ROW_TRACKING_ENABLED.key(), "true") + .option(CoreOptions.DATA_EVOLUTION_ENABLED.key(), "true") + .option( + CoreOptions.DATA_EVOLUTION_METADATA_MEMORY_OPTIMIZATION_MODE + .key(), + mode) + .option(CoreOptions.PAGE_SIZE.key(), "64 kb") + .option(CoreOptions.SORT_SPILL_BUFFER_SIZE.key(), pages * 64 + " kb") + .build(), + false); + table = (FileStoreTable) catalog.getTable(identifier); + } + BatchWriteBuilder initial = table.newBatchWriteBuilder(); + try (BatchTableWrite write = initial.newWrite(); + BatchTableCommit commit = initial.newCommit()) { + write.write( + GenericRow.of( + 1, + BinaryString.fromString("untouched"), + BinaryString.fromString("base"))); + commit.commit(write.prepareCommit()); + } + long readSnapshot = table.snapshotManager().latestSnapshot().id(); + assertThat(readSnapshot).isEqualTo(1L); + long firstRowId = table.snapshotManager().latestSnapshot().nextRowId() - 1; + String originalFile = table.store().newScan().readSimpleEntries().get(0).fileName(); + + BatchWriteBuilder staleBuilder = table.newBatchWriteBuilder(); + List stale = + prepareUpdate(staleBuilder, table, firstRowId, readSnapshot, "stale"); + BatchWriteBuilder builder = table.newBatchWriteBuilder(); + List update = + prepareUpdate(builder, table, firstRowId, readSnapshot, "updated"); + try (BatchTableCommit commit = builder.newCommit()) { + commit.commit(update); + } + assertThat(table.snapshotManager().latestSnapshot().id()).isEqualTo(2L); + assertThat( + table.store().newScan().readSimpleEntries().stream() + .map(entry -> entry.fileName()) + .collect(Collectors.toList())) + .contains(originalFile); + + assertThatThrownBy( + () -> { + try (BatchTableCommit commit = staleBuilder.newCommit()) { + commit.commit(stale); + } + }) + .hasMessageContaining(DATA_EVOLUTION_ROW_ID_CONFLICT_MESSAGE); + assertThat(table.snapshotManager().latestSnapshot().id()).isEqualTo(2L); + try (RecordReaderIterator reader = + new RecordReaderIterator<>( + table.newRead().createReader(table.newScan().plan().splits()))) { + assertThat(reader.hasNext()).isTrue(); + InternalRow row = reader.next(); + assertThat(row.getInt(0)).isEqualTo(1); + assertThat(row.getString(1).toString()).isEqualTo("untouched"); + assertThat(row.getString(2).toString()).isEqualTo("updated"); + assertThat(reader.hasNext()).isFalse(); + } + } + + private List prepareUpdate( + BatchWriteBuilder builder, + FileStoreTable table, + long firstRowId, + long readSnapshot, + String value) + throws Exception { + try (BatchTableWrite write = + builder.newWrite() + .withWriteType(table.rowType().project(Collections.singletonList("f2")))) { + write.write(GenericRow.of(BinaryString.fromString(value))); + List messages = write.prepareCommit(); + for (CommitMessage message : messages) { + ((CommitMessageImpl) message) + .newFilesIncrement() + .newFiles() + .replaceAll(file -> file.assignFirstRowId(firstRowId)); + } + return messages.stream() + .map( + message -> + ((CommitMessageImpl) message) + .withCheckFromSnapshot(readSnapshot)) + .collect(Collectors.toList()); + } + } +} diff --git a/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionTableTest.java b/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionTableTest.java index 1a5347278b78..af8f77a4c7b4 100644 --- a/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionTableTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/table/DataEvolutionTableTest.java @@ -19,9 +19,11 @@ package org.apache.paimon.table; import org.apache.paimon.CoreOptions; +import org.apache.paimon.Snapshot; import org.apache.paimon.append.dataevolution.DataEvolutionCompactCoordinator; import org.apache.paimon.append.dataevolution.DataEvolutionCompactTask; import org.apache.paimon.catalog.TableRollback; +import org.apache.paimon.data.BinaryRow; import org.apache.paimon.data.BinaryString; import org.apache.paimon.data.BlobData; import org.apache.paimon.data.GenericRow; @@ -36,6 +38,10 @@ import org.apache.paimon.manifest.FileSource; import org.apache.paimon.manifest.ManifestEntry; import org.apache.paimon.manifest.ManifestFileMeta; +import org.apache.paimon.manifest.SimpleFileEntry; +import org.apache.paimon.operation.DataEvolutionFileStoreScan; +import org.apache.paimon.operation.FileStoreScan; +import org.apache.paimon.operation.commit.CommitScanner; import org.apache.paimon.partition.PartitionPredicate; import org.apache.paimon.predicate.Predicate; import org.apache.paimon.predicate.PredicateBuilder; @@ -51,6 +57,7 @@ import org.apache.paimon.table.source.DataSplit; import org.apache.paimon.table.source.EndOfScanException; 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.TableScan; @@ -63,11 +70,13 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -83,6 +92,123 @@ /** Test for table with data evolution. */ public class DataEvolutionTableTest extends DataEvolutionTestBase { + @Test + public void testStreamingCommitConflictPathEnforcesEncodedBudget() throws Exception { + createTableDefault(); + FileStoreTable table = getTableDefault(); + long firstRowId = writeFullRows(table, 1); + long before = table.snapshotManager().latestSnapshot().id(); + Map options = new HashMap<>(); + options.put( + CoreOptions.DATA_EVOLUTION_METADATA_MEMORY_OPTIMIZATION_MODE.key(), "streaming"); + options.put(CoreOptions.DATA_EVOLUTION_METADATA_MEMORY_MAX_DISK_SIZE.key(), "8 b"); + FileStoreTable streaming = table.copy(options); + BatchWriteBuilder builder = streaming.newBatchWriteBuilder(); + try (BatchTableWrite write = + builder.newWrite() + .withWriteType( + table.rowType().project(Collections.singletonList("f2"))); + BatchTableCommit commit = builder.newCommit()) { + write.write(GenericRow.of(BinaryString.fromString("updated"))); + List messages = write.prepareCommit(); + setFirstRowId(messages, firstRowId); + CommitMessageImpl update = + ((CommitMessageImpl) messages.get(0)).withCheckFromSnapshot(before); + assertThatThrownBy(() -> commit.commit(Collections.singletonList(update))) + .hasStackTraceContaining("Metadata merge encoded limit"); + } + assertThat(table.snapshotManager().latestSnapshot().id()).isEqualTo(before); + } + + @Test + public void testStreamingCommitEntriesPinSnapshotAndReadDelta() throws Exception { + createTableDefault(); + FileStoreTable table = getTableDefault(); + List firstNames = + writeOneFullRowAndCollectNewFiles(table).stream() + .map(DataFileMeta::fileName) + .collect(Collectors.toList()); + Snapshot firstSnapshot = table.snapshotManager().latestSnapshot(); + List secondNames = new ArrayList<>(); + List scannedNames = new ArrayList<>(); + FileStoreScan initiallyLatest = table.store().newScan(); + + initiallyLatest.forEachSimpleEntry( + entry -> { + scannedNames.add(entry.fileName()); + if (secondNames.isEmpty()) { + secondNames.addAll( + writeOneFullRowAndCollectNewFiles(table).stream() + .map(DataFileMeta::fileName) + .collect(Collectors.toList())); + } + }); + + Snapshot secondSnapshot = table.snapshotManager().latestSnapshot(); + assertThat(secondSnapshot.id()).isEqualTo(firstSnapshot.id() + 1); + assertThat(scannedNames).isEqualTo(firstNames); + List pinned = new ArrayList<>(); + table.store().newScan().withSnapshot(firstSnapshot).forEachSimpleEntry(pinned::add); + assertThat(pinned.stream().map(SimpleFileEntry::fileName).collect(Collectors.toList())) + .isEqualTo(firstNames); + + List delta = new ArrayList<>(); + table.store() + .newScan() + .withSnapshot(secondSnapshot) + .withKind(ScanMode.DELTA) + .forEachSimpleEntry(delta::add); + assertThat(delta.stream().map(SimpleFileEntry::fileName).collect(Collectors.toList())) + .isEqualTo(secondNames); + assertThat(delta) + .isEqualTo( + table.store() + .newScan() + .withSnapshot(secondSnapshot) + .withKind(ScanMode.DELTA) + .readSimpleEntries()); + assertThat(table.store().newScan().readSimpleEntries().size()) + .isEqualTo(firstNames.size() + secondNames.size()); + + CommitScanner commitScanner = + new CommitScanner( + table.store()::newScan, + ((AbstractFileStoreTable) table).schemaManager(), + table.snapshotManager(), + null, + new CoreOptions(table.schema().options())); + List partitions = Collections.singletonList(BinaryRow.EMPTY_ROW); + List firstRange = Collections.singletonList(pinned.get(0).nonNullRowIdRange()); + List scoped = new ArrayList<>(); + commitScanner.forEachEntryFromChangedRowRanges( + secondSnapshot, partitions, firstRange, scoped::add); + assertThat(scoped.stream().map(SimpleFileEntry::fileName).collect(Collectors.toList())) + .isEqualTo(firstNames); + + IOException failure = new IOException("scoped metadata consumer stopped"); + assertThatThrownBy( + () -> + commitScanner.forEachEntryFromDataFiles( + secondSnapshot, + partitions, + new HashSet<>(secondNames), + entry -> { + throw failure; + })) + .isSameAs(failure); + scoped.clear(); + commitScanner.forEachEntryFromDataFiles( + secondSnapshot, partitions, new HashSet<>(secondNames), scoped::add); + assertThat(scoped.stream().map(SimpleFileEntry::fileName).collect(Collectors.toList())) + .isEqualTo(secondNames); + + scoped.clear(); + commitScanner.forEachEntryFromChangedRowRanges( + secondSnapshot, partitions, firstRange, scoped::add); + assertThat(scoped.stream().map(SimpleFileEntry::fileName).collect(Collectors.toList())) + .isEqualTo(firstNames); + } + @Test public void testRowSidecarDisabledByDefault() throws Exception { createTableDefault(); @@ -2752,17 +2878,174 @@ public void testSystemFieldOnlyProjectionIsNotPruned() throws Exception { assertThat(plannedFileCount(table, RowType.of(SpecialFields.ROW_ID), null)).isEqualTo(2); } - @Test - public void testDropStatsWithoutFilterOrReadType() throws Exception { + @ParameterizedTest + @ValueSource(booleans = {false, true}) + public void testSharedWriteColumnNamesKeepFileListsIndependent(boolean enabled) + throws Exception { write(5); + FileStoreTable original = getTableDefault(); + BatchWriteBuilder builder = original.newBatchWriteBuilder(); + RowType partial = schemaDefault().rowType().project(Collections.singletonList("f2")); + try (BatchTableWrite writer = builder.newWrite().withWriteType(partial)) { + writer.write(GenericRow.of(BinaryString.fromString("updated"))); + List messages = writer.prepareCommit(); + setFirstRowId(messages, 1L); + builder.newCommit().commit(messages); + } + FileStoreTable table = + original.copy( + Collections.singletonMap( + CoreOptions.DATA_EVOLUTION_METADATA_MEMORY_OPTIMIZATION_MODE.key(), + enabled ? "lightweight" : "off")); + for (int mode = 0; mode < 3; mode++) { + DataEvolutionFileStoreScan scan = (DataEvolutionFileStoreScan) table.store().newScan(); + if (mode == 1) { + scan.dropStats(); + } else { + scan.keepStats(); + } + if (mode == 2) { + scan.withFilter(new PredicateBuilder(schemaDefault().rowType()).equal(0, 2)); + } + List files = + scan.plan().files().stream() + .map(ManifestEntry::file) + .filter(f -> Collections.singletonList("f2").equals(f.writeCols())) + .collect(Collectors.toList()); + assertThat(files.size()).isEqualTo(2); + assertThat(files.get(0).writeCols()).isNotSameAs(files.get(1).writeCols()); + if (enabled) { + assertThat(files.get(0).writeCols().get(0)) + .isSameAs(files.get(1).writeCols().get(0)); + } else { + assertThat(files.get(0).writeCols().get(0)) + .isNotSameAs(files.get(1).writeCols().get(0)); + } + for (DataFileMeta file : files) { + if (mode == 1) { + assertThat(file.valueStats()).isEqualTo(EMPTY_STATS); + } else { + assertThat(file.valueStats()).isNotEqualTo(EMPTY_STATS); + } + } + files.get(0).writeCols().set(0, "mutated"); + assertThat(files.get(1).writeCols()).isEqualTo(Collections.singletonList("f2")); + List reread = table.store().newScan().plan().files(); + assertThat( + reread.stream() + .filter( + e -> + Collections.singletonList("f2") + .equals(e.file().writeCols())) + .count()) + .isEqualTo(2L); + } + } - List entries = - getTableDefault().store().newScan().dropStats().plan().files(); + @Test + public void testSharedColumnNamesPreserveHistoricalNamesAfterRename() throws Exception { + write(5); + catalog.alterTable(identifier(), SchemaChange.renameColumn("f2", "f3"), false); + FileStoreTable table = + getTableDefault() + .copy( + Collections.singletonMap( + CoreOptions.DATA_EVOLUTION_METADATA_MEMORY_OPTIMIZATION_MODE + .key(), + "lightweight")); + List entries = table.store().newScan().keepStats().plan().files(); + assertThat( + entries.stream() + .anyMatch( + e -> + Collections.singletonList("f2") + .equals(e.file().writeCols()))) + .isTrue(); + List rows = new ArrayList<>(); + ReadBuilder read = table.newReadBuilder(); + try (RecordReader reader = + read.newRead().createReader(read.newScan().plan())) { + reader.forEachRemaining( + row -> + rows.add( + row.getInt(0) + + "|" + + row.getString(1) + + "|" + + row.getString(2))); + } + Collections.sort(rows); + assertThat(rows) + .isEqualTo(Arrays.asList("0|a0|b0", "1|a1|b1", "2|a2|b2", "3|a3|b3", "4|a4|b4")); + } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + public void testDropStatsWithoutFilterOrReadType(boolean enabled) throws Exception { + write(5); + FileStoreTable table = + getTableDefault() + .copy( + Collections.singletonMap( + CoreOptions.DATA_EVOLUTION_METADATA_MEMORY_OPTIMIZATION_MODE + .key(), + enabled ? "lightweight" : "off")); + assertThat(table.coreOptions().dataEvolutionMetadataMemoryOptimizationEnabled()) + .isEqualTo(enabled); + DataEvolutionFileStoreScan scan = (DataEvolutionFileStoreScan) table.store().newScan(); + List manifests = + table.store() + .manifestListFactory() + .create() + .readDataManifests(table.latestSnapshot().get()); + assertThat(manifests.isEmpty()).isFalse(); + scan.dropStats(); + for (ManifestFileMeta manifest : manifests) { + List retained = + table.store() + .manifestFileFactory() + .create() + .read(manifest.fileName(), manifest.fileSize()); + assertThat(retained.isEmpty()).isFalse(); + for (ManifestEntry entry : retained) { + assertThat(entry.file().valueStats()).isNotEqualTo(EMPTY_STATS); + } + assertThat(scan.readManifest(manifest)) + .isEqualTo( + retained.stream() + .map(e -> enabled ? e.copyWithoutStats() : e) + .collect(Collectors.toList())); + scan.withFilter(new PredicateBuilder(schemaDefault().rowType()).equal(0, 99)); + scan.keepStats(); + scan.withFilter(null); + assertThat(scan.readManifest(manifest)).isEqualTo(retained); + scan.dropStats(); + } + + List entries = scan.plan().files(); assertThat(entries.isEmpty()).isFalse(); for (ManifestEntry entry : entries) { assertThat(entry.file().valueStats()).isEqualTo(EMPTY_STATS); } + PredicateBuilder predicates = new PredicateBuilder(schemaDefault().rowType()); + scan.withFilter(predicates.equal(0, 99)); + assertThat(scan.plan().files().isEmpty()).isTrue(); + scan.withFilter(predicates.equal(0, 2)); + assertThat(scan.plan().files().size()).isEqualTo(2); + ReadBuilder filtered = table.newReadBuilder().withFilter(predicates.equal(0, 2)); + List rows = new ArrayList<>(); + try (RecordReader reader = + filtered.newRead().executeFilter().createReader(filtered.newScan().plan())) { + reader.forEachRemaining( + row -> + rows.add( + row.getInt(0) + + "|" + + row.getString(1) + + "|" + + row.getString(2))); + } + assertThat(rows).isEqualTo(Collections.singletonList("2|a2|b2")); } private List writeOneFullRowAndCollectNewFiles(FileStoreTable table) diff --git a/paimon-core/src/test/java/org/apache/paimon/table/sink/CommitMessageListTest.java b/paimon-core/src/test/java/org/apache/paimon/table/sink/CommitMessageListTest.java new file mode 100644 index 000000000000..2adc6ee18aa8 --- /dev/null +++ b/paimon-core/src/test/java/org/apache/paimon/table/sink/CommitMessageListTest.java @@ -0,0 +1,113 @@ +/* + * 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.paimon.table.sink; + +import org.apache.paimon.data.BinaryRow; +import org.apache.paimon.io.CompactIncrement; +import org.apache.paimon.io.DataIncrement; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** Tests for byte-backed, repeatable commit messages. */ +class CommitMessageListTest { + + @Test + void testIteratorCannotInvalidateByteOrChildDirectory() throws IOException { + CommitMessageSerializer serializer = new CommitMessageSerializer(); + CommitMessageList bytes = + CommitMessageList.fromBytes( + Arrays.asList( + serializer.serialize(message(1)), + serializer.serialize(message(2)))); + List concatenated = + CommitMessageList.concat(Arrays.asList(Collections.emptyList(), bytes)); + for (List list : + Arrays.asList(bytes, concatenated, CommitMessageList.map(concatenated, m -> m))) { + Iterator iterator = list.iterator(); + assertThat(iterator.next()).isEqualTo(message(1)); + assertThatThrownBy(iterator::remove).isInstanceOf(UnsupportedOperationException.class); + assertThat(list).containsExactly(message(1), message(2)); + assertThat(list.size()).isEqualTo(2); + } + List stable = bytes.materialize(); + stable.set(0, message(3)); + Iterator iterator = bytes.iterator(); + assertThat(iterator.next()).isSameAs(stable.get(0)); + assertThatThrownBy(iterator::remove).isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void testDecodeOnlyAccessedMessage() throws IOException { + CommitMessageSerializer serializer = new CommitMessageSerializer(); + List messages = + CommitMessageList.fromBytes( + Arrays.asList(serializer.serialize(message(1)), new byte[0])); + assertThat(messages.size()).isEqualTo(2); + assertThat(messages.get(0)).isEqualTo(message(1)); + assertThat(messages.get(0)).isNotSameAs(messages.get(0)); + assertThatThrownBy(() -> messages.get(1)).isInstanceOf(UncheckedIOException.class); + assertThatThrownBy(() -> messages.get(-1)).isInstanceOf(IndexOutOfBoundsException.class); + assertThatThrownBy(() -> messages.get(2)).isInstanceOf(IndexOutOfBoundsException.class); + } + + @Test + void testConcatAndMapRemainLazyAndReplayable() throws IOException { + CommitMessageSerializer serializer = new CommitMessageSerializer(); + List first = + CommitMessageList.fromBytes( + Collections.singletonList(serializer.serialize(message(1)))); + List second = + CommitMessageList.fromBytes( + Collections.singletonList(serializer.serialize(message(2)))); + List joined = + CommitMessageList.concat(Arrays.asList(Collections.emptyList(), first, second)); + List checked = + CommitMessageList.map( + joined, m -> ((CommitMessageImpl) m).withCheckFromSnapshot(42)); + assertThat(checked) + .containsExactly( + message(1).withCheckFromSnapshot(42), message(2).withCheckFromSnapshot(42)); + assertThat(checked) + .containsExactly( + message(1).withCheckFromSnapshot(42), message(2).withCheckFromSnapshot(42)); + assertThat(checked.get(0)).isNotSameAs(checked.get(0)); + assertThatThrownBy(() -> checked.add(message(3))) + .isInstanceOf(UnsupportedOperationException.class); + assertThat(joined.get(1)).isEqualTo(message(2)); + } + + private static CommitMessageImpl message(int bucket) { + return new CommitMessageImpl( + BinaryRow.EMPTY_ROW, + bucket, + null, + DataIncrement.emptyIncrement(), + CompactIncrement.emptyIncrement()); + } +} diff --git a/paimon-core/src/test/java/org/apache/paimon/table/source/DataEvolutionSplitGeneratorTest.java b/paimon-core/src/test/java/org/apache/paimon/table/source/DataEvolutionSplitGeneratorTest.java index f94727f7df7a..5379c1d051a6 100644 --- a/paimon-core/src/test/java/org/apache/paimon/table/source/DataEvolutionSplitGeneratorTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/table/source/DataEvolutionSplitGeneratorTest.java @@ -23,11 +23,15 @@ import org.junit.jupiter.api.Test; +import java.io.IOException; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import static org.apache.paimon.data.BinaryRow.EMPTY_ROW; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Tests for {@link DataEvolutionSplitGenerator}. */ public class DataEvolutionSplitGeneratorTest { @@ -51,6 +55,123 @@ public void testCountBlobSize() { assertThat(splits.size()).isEqualTo(1); } + @Test + void testIncrementalPackingMatchesBatchWeightsAndRawConversion() { + List first = + Arrays.asList( + newFile("base-0.parquet", 0, 10, 100), + newFile("update-0.parquet", 0, 10, 20)); + List second = + Arrays.asList( + newFile("base-10.parquet", 10, 10, 80), newBlobFile("blob-10", 10, 3, 500)); + List third = + Collections.singletonList(newFile("base-20.parquet", 20, 10, 40)); + List input = new ArrayList<>(); + input.addAll(first); + input.addAll(second); + input.addAll(third); + for (boolean countBlobSize : Arrays.asList(false, true)) { + DataEvolutionSplitGenerator generator = + new DataEvolutionSplitGenerator(200, 50, countBlobSize); + List expected = generator.splitForBatch(input); + List actual = new ArrayList<>(); + DataEvolutionSplitGenerator.BatchPacker packer = + generator.newBatchPacker(1024, actual::add); + packer.addRangeGroup(first); + packer.addRangeGroup(second); + packer.addRangeGroup(third); + packer.finish(); + assertThat(actual).hasSize(expected.size()); + for (int i = 0; i < actual.size(); i++) { + assertThat(actual.get(i).files).containsExactlyElementsOf(expected.get(i).files); + assertThat(actual.get(i).rawConvertible).isEqualTo(expected.get(i).rawConvertible); + } + } + } + + @Test + void testFileCapDoesNotCutAConnectedDependencyGroup() { + DataEvolutionSplitGenerator generator = new DataEvolutionSplitGenerator(1000, 0, false); + List emitted = new ArrayList<>(); + DataEvolutionSplitGenerator.BatchPacker packer = + generator.newBatchPacker(2, emitted::add); + List connected = + Arrays.asList( + newFile("a.parquet", 0, 10, 0), + newFile("b.parquet", 0, 10, 0), + newFile("c.parquet", 0, 10, 0)); + DataFileMeta independent = newFile("next.parquet", 10, 10, 0); + packer.addRangeGroup(connected); + packer.addRangeGroup(Collections.singletonList(independent)); + packer.finish(); + assertThat(emitted).hasSize(2); + assertThat(emitted.get(0).files).containsExactlyElementsOf(connected); + assertThat(emitted.get(0).rawConvertible).isFalse(); + assertThat(emitted.get(1).files).containsExactly(independent); + assertThat(emitted.get(1).rawConvertible).isTrue(); + } + + @Test + void testEmissionIsImmediateAndCompletedGroupsStayStable() { + DataEvolutionSplitGenerator generator = new DataEvolutionSplitGenerator(2, 1, false); + List emitted = new ArrayList<>(); + DataEvolutionSplitGenerator.BatchPacker packer = + generator.newBatchPacker(2, emitted::add); + DataFileMeta first = newFile("first.parquet", 0, 1, 1); + DataFileMeta second = newFile("second.parquet", 1, 1, 1); + DataFileMeta third = newFile("third.parquet", 2, 1, 1); + packer.addRangeGroup(Collections.singletonList(first)); + packer.addRangeGroup(Collections.singletonList(second)); + assertThat(emitted).isEmpty(); + packer.addRangeGroup(Collections.singletonList(third)); + assertThat(emitted).hasSize(1); + assertThat(emitted.get(0).files).containsExactly(first, second); + packer.finish(); + assertThat(emitted).hasSize(2); + assertThat(emitted.get(0).files).containsExactly(first, second); + assertThat(emitted.get(1).files).containsExactly(third); + assertThatThrownBy(() -> packer.addRangeGroup(Collections.singletonList(third))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void testEmptyPackingAndInvalidLimit() { + DataEvolutionSplitGenerator generator = new DataEvolutionSplitGenerator(1000, 0, false); + List emitted = new ArrayList<>(); + assertThatThrownBy(() -> generator.newBatchPacker(0, emitted::add)) + .isInstanceOf(IllegalArgumentException.class); + DataEvolutionSplitGenerator.BatchPacker packer = + generator.newBatchPacker(2, emitted::add); + packer.finish(); + assertThat(emitted).isEmpty(); + } + + @Test + void testCheckedConsumerFailureCannotBeResumedAsASuccessfulPlan() throws Exception { + DataEvolutionSplitGenerator generator = new DataEvolutionSplitGenerator(1, 1, false); + DataFileMeta first = newFile("first.parquet", 0, 1, 1); + DataFileMeta second = newFile("second.parquet", 1, 1, 1); + for (boolean failOnFinish : Arrays.asList(false, true)) { + IOException failure = new IOException("metadata store write failed"); + DataEvolutionSplitGenerator.BatchPacker packer = + generator.newBatchPacker( + 2, + group -> { + throw failure; + }); + packer.addRangeGroup(Collections.singletonList(first)); + if (failOnFinish) { + assertThatThrownBy(packer::finish).isSameAs(failure); + } else { + assertThatThrownBy(() -> packer.addRangeGroup(Collections.singletonList(second))) + .isSameAs(failure); + } + assertThatThrownBy(packer::finish).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> packer.addRangeGroup(Collections.singletonList(second))) + .isInstanceOf(IllegalStateException.class); + } + } + private static DataFileMeta newFile( String name, long firstRowId, long rowCount, long fileSize) { return DataFileMeta.create( diff --git a/paimon-core/src/test/java/org/apache/paimon/table/source/DataFileMetaStoreTest.java b/paimon-core/src/test/java/org/apache/paimon/table/source/DataFileMetaStoreTest.java new file mode 100644 index 000000000000..bb0c7a26af48 --- /dev/null +++ b/paimon-core/src/test/java/org/apache/paimon/table/source/DataFileMetaStoreTest.java @@ -0,0 +1,545 @@ +/* + * 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.paimon.table.source; + +import org.apache.paimon.data.BinaryRow; +import org.apache.paimon.data.Timestamp; +import org.apache.paimon.io.DataFileMeta; +import org.apache.paimon.io.DataFileMetaSerializer; +import org.apache.paimon.io.DataOutputSerializer; +import org.apache.paimon.manifest.FileSource; +import org.apache.paimon.stats.SimpleStats; +import org.apache.paimon.utils.InstantiationUtil; + +import org.apache.paimon.shade.guava30.com.google.common.base.FinalizablePhantomReference; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.io.RandomAccessFile; +import java.io.UncheckedIOException; +import java.lang.reflect.Field; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** Tests for the Driver-owned replay store, independently of streaming SQL integration. */ +class DataFileMetaStoreTest { + + @TempDir Path directory; + + @Test + void testBulkFilteringReplaysIndependentFilesAndPreservesSplitFieldsAndDeletionAlignment() + throws Exception { + try (DataFileMetaStore input = new DataFileMetaStore(directory, 1024 * 1024); + DataFileMetaStore output = new DataFileMetaStore(directory, 1024 * 1024)) { + for (int i = 0; i < 5; i++) { + input.append(file(i)); + } + input.seal(); + DeletionFile first = new DeletionFile("first.dv", 2, 12, 1L); + DeletionFile third = new DeletionFile("third.dv", 20, 30, null); + DataSplit withDeletes = + DataSplit.builder() + .withSnapshot(42) + .withPartition(BinaryRow.EMPTY_ROW) + .withBucket(3) + .withBucketPath("/unused/p/bucket-3") + .withTotalBuckets(7) + .withDataFiles(input.slice(0, 3)) + .withDataDeletionFiles(Arrays.asList(first, null, third)) + .isStreaming(true) + .rawConvertible(true) + .build(); + DataSplit withoutDeletes = split(input.slice(3, 5)); + java.util.function.Predicate keep = + value -> + !value.fileName().equals("file-1") + && !value.fileName().equals("file-3"); + List expected = + Arrays.asList( + withDeletes.filterDataFile(keep).get(), + withoutDeletes.filterDataFile(keep).get()); + List actual = + DataSplit.filterDataFiles( + Arrays.asList(withDeletes, withoutDeletes), keep, output); + input.close(); + assertThat(actual).containsExactlyElementsOf(expected); + assertThat(actual.get(0).deletionFiles().get()).containsExactly(first, third); + assertThat(actual.get(1).deletionFiles()).isEmpty(); + assertThat(actual.get(0).isStreaming()).isTrue(); + assertThat(actual.get(0).totalBuckets()).isEqualTo(7); + assertThat(actual.get(0).dataFiles().getClass().getName()) + .contains("DataFileMetaStore$Slice"); + assertThat(actual.get(1).dataFiles()).containsExactly(file(4)); + output.close(); + assertThatThrownBy(() -> actual.get(0).dataFiles().get(0)) + .isInstanceOf(IllegalStateException.class); + } + assertNoOwnedFiles(); + } + + @Test + void testBulkFilteringEmptyResultSealsAnEmptyReplayStore() throws Exception { + try (DataFileMetaStore output = new DataFileMetaStore(directory, 8)) { + assertThat( + DataSplit.filterDataFiles( + Collections.singletonList( + split(Arrays.asList(file(0), file(1)))), + value -> false, + output)) + .isEmpty(); + assertThat(output.slice(0, 0)).isEmpty(); + assertThat(output.serializedBytes()).isEqualTo(8); + } + assertNoOwnedFiles(); + } + + @Test + void testBulkFilteringPredicateFailureDiscardsPartialOutputAndKeepsInputUsable() + throws Exception { + DataSplit source = split(Arrays.asList(file(0), file(1), file(2))); + RuntimeException stopped = new RuntimeException("stop filtering"); + try (DataFileMetaStore output = new DataFileMetaStore(directory, 1024 * 1024)) { + assertThatThrownBy( + () -> + DataSplit.filterDataFiles( + Collections.singletonList(source), + value -> { + if (value.fileName().equals("file-1")) { + throw stopped; + } + return true; + }, + output)) + .isSameAs(stopped); + assertNoOwnedFiles(); + assertThat(source.dataFiles()).containsExactly(file(0), file(1), file(2)); + } + } + + @Test + void testBulkFilteringDiskFailureDoesNotExposeAPartialSplit() throws Exception { + DataSplit source = split(Arrays.asList(file(0), file(1))); + try (DataFileMetaStore output = new DataFileMetaStore(directory, 8)) { + assertThatThrownBy( + () -> + DataSplit.filterDataFiles( + Collections.singletonList(source), + value -> true, + output)) + .isInstanceOf(IOException.class) + .hasMessageContaining("limit"); + assertNoOwnedFiles(); + assertThat(source.dataFiles()).containsExactly(file(0), file(1)); + } + } + + @Test + void testBulkFilteringRejectsUsedOutputWithoutClosingItsExistingContents() throws Exception { + for (boolean sealed : new boolean[] {false, true}) { + try (DataFileMetaStore output = new DataFileMetaStore(directory, 1024 * 1024)) { + output.append(file(9)); + if (sealed) { + output.seal(); + } + assertThatThrownBy( + () -> + DataSplit.filterDataFiles( + Collections.singletonList( + split(Collections.singletonList(file(0)))), + value -> true, + output)) + .isInstanceOf(IllegalStateException.class); + output.seal(); + assertThat(output.slice(0, 1)).containsExactly(file(9)); + } + } + assertNoOwnedFiles(); + } + + @Test + void testAutomaticCleanupRequiresASealedStoreAndPreservesExplicitOwnership() throws Exception { + try (DataFileMetaStore store = new DataFileMetaStore(directory, 1024 * 1024)) { + assertThatThrownBy(store::withAutomaticCleanup) + .isInstanceOf(IllegalStateException.class); + store.append(file(0)); + store.seal(); + assertThat(store.withAutomaticCleanup()).isSameAs(store); + List slice = store.slice(0, 1); + assertThat(store.withAutomaticCleanup()).isSameAs(store); + assertThat(slice).containsExactly(file(0)); + RandomAccessFile data = input(store, "dataInput"); + RandomAccessFile index = input(store, "indexInput"); + store.close(); + assertThat(data.getFD().valid()).isFalse(); + assertThat(index.getFD().valid()).isFalse(); + assertThatThrownBy(() -> slice.get(0)).isInstanceOf(IllegalStateException.class); + // A queued notification after explicit close must remain harmless. + cleanupNotification(store).finalizeReferent(); + } + assertNoOwnedFiles(); + } + + @Test + void testAutomaticCleanupNotificationClosesHandlesAndDeletesFilesWithoutForcedGc() + throws Exception { + try (DataFileMetaStore store = new DataFileMetaStore(directory, 1024 * 1024)) { + store.append(file(0)); + store.seal(); + store.withAutomaticCleanup(); + RandomAccessFile data = input(store, "dataInput"); + RandomAccessFile index = input(store, "indexInput"); + // Deterministically exercise the queue callback, without asserting GC timing. + cleanupNotification(store).finalizeReferent(); + cleanupNotification(store).finalizeReferent(); + assertThat(data.getFD().valid()).isFalse(); + assertThat(index.getFD().valid()).isFalse(); + assertNoOwnedFiles(); + } + } + + private static RandomAccessFile input(DataFileMetaStore store, String name) throws Exception { + Field field = DataFileMetaStore.class.getDeclaredField(name); + field.setAccessible(true); + return (RandomAccessFile) field.get(store); + } + + private static FinalizablePhantomReference cleanupNotification(DataFileMetaStore store) + throws Exception { + Field field = DataFileMetaStore.class.getDeclaredField("cleanupReference"); + field.setAccessible(true); + return (FinalizablePhantomReference) field.get(store); + } + + @Test + void testSealedSlicesReplayIndependentlyAndAreImmutable() throws Exception { + try (DataFileMetaStore store = new DataFileMetaStore(directory, 1024 * 1024)) { + for (int i = 0; i < 10; i++) { + store.append(file(i)); + } + assertThatThrownBy(() -> store.slice(0, 10)).isInstanceOf(IllegalStateException.class); + store.seal(); + List slice = store.slice(2, 7); + assertThat(slice).containsExactly(file(2), file(3), file(4), file(5), file(6)); + assertThat(slice.subList(1, 3)).containsExactly(file(3), file(4)); + Iterator first = slice.iterator(); + Iterator second = slice.iterator(); + assertThat(first.next()).isEqualTo(file(2)); + assertThat(first.next()).isEqualTo(file(3)); + assertThat(second.next()).isEqualTo(file(2)); + assertThat(slice.get(4)).isEqualTo(file(6)); + assertThat(first.next()).isEqualTo(file(4)); + assertThatThrownBy(() -> slice.add(file(11))) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> slice.set(0, file(11))) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> store.append(file(11))) + .isInstanceOf(IllegalStateException.class); + } + assertNoOwnedFiles(); + } + + @Test + void testBoundsAndEmptyStore() throws Exception { + try (DataFileMetaStore store = new DataFileMetaStore(directory, 8)) { + store.seal(); + assertThat(store.slice(0, 0)).isEmpty(); + assertThat(store.serializedBytes()).isEqualTo(8); + assertThatThrownBy(() -> store.slice(-1, 0)) + .isInstanceOf(IndexOutOfBoundsException.class); + assertThatThrownBy(() -> store.slice(0, 1)) + .isInstanceOf(IndexOutOfBoundsException.class); + assertThatThrownBy(() -> store.slice(1, 0)) + .isInstanceOf(IndexOutOfBoundsException.class); + } + assertNoOwnedFiles(); + } + + @Test + void testSplitRetainsOnlyOwnedSliceButCopiesOrdinaryLists() throws Exception { + List ordinary = new ArrayList<>(Arrays.asList(file(0), file(1))); + DataSplit copied = split(ordinary); + ordinary.clear(); + assertThat(copied.dataFiles()).containsExactly(file(0), file(1)); + try (DataFileMetaStore store = new DataFileMetaStore(directory, 1024 * 1024)) { + store.append(file(0)); + store.append(file(1)); + store.seal(); + List owned = store.slice(0, 2); + assertThat(split(owned).dataFiles()).isSameAs(owned); + } + assertNoOwnedFiles(); + } + + @Test + void testBothSplitTransportsOutliveDriverStore() throws Exception { + byte[] javaBytes; + byte[] binaryBytes; + try (DataFileMetaStore store = new DataFileMetaStore(directory, 1024 * 1024)) { + store.append(file(0)); + store.append(file(1)); + store.seal(); + DataSplit original = split(store.slice(0, 2)); + javaBytes = InstantiationUtil.serializeObject(original); + binaryBytes = SplitSerializer.serialize(original); + } + assertNoOwnedFiles(); + DataSplit fromJava = + InstantiationUtil.deserializeObject(javaBytes, getClass().getClassLoader()); + DataSplit fromBinary = (DataSplit) SplitSerializer.deserialize(binaryBytes); + assertThat(fromJava).isEqualTo(split(Arrays.asList(file(0), file(1)))); + assertThat(fromBinary).isEqualTo(fromJava); + assertThat(fromJava.dataFiles()).isInstanceOf(ArrayList.class); + assertThat(fromBinary.dataFiles()).isInstanceOf(ArrayList.class); + } + + @Test + void testFileCountDoesNotGrowWithRecordCount() throws Exception { + try (DataFileMetaStore store = new DataFileMetaStore(directory, 32 * 1024 * 1024)) { + for (int i = 0; i < 20000; i++) { + store.append(file(i)); + } + store.seal(); + try (Stream files = Files.list(directory)) { + List paths = files.collect(Collectors.toList()); + assertThat(paths).hasSize(2); + long bytes = 0; + for (Path path : paths) { + bytes += Files.size(path); + } + assertThat(store.serializedBytes()).isEqualTo(bytes); + } + Iterator iterator = store.slice(0, 20000).iterator(); + int count = 0; + while (iterator.hasNext()) { + assertThat(iterator.next()).isEqualTo(file(count++)); + } + assertThat(count).isEqualTo(20000); + assertThat(store.slice(19999, 20000).get(0)).isEqualTo(file(19999)); + } + assertNoOwnedFiles(); + } + + @Test + void testDiskLimitFailureClosesStoreAndLeavesNoPartialFiles() throws Exception { + try (DataFileMetaStore store = new DataFileMetaStore(directory, 8)) { + assertThatThrownBy(() -> store.append(file(0))) + .isInstanceOf(IOException.class) + .hasMessageContaining("limit"); + assertNoOwnedFiles(); + assertThatThrownBy(store::seal).isInstanceOf(IllegalStateException.class); + } + assertNoOwnedFiles(); + } + + @Test + void testDiskLimitIncludesIndexAndEndOffset() throws Exception { + DataOutputSerializer serialized = new DataOutputSerializer(128); + new DataFileMetaSerializer().serialize(file(0), serialized); + try (DataFileMetaStore store = new DataFileMetaStore(directory, serialized.length() + 8L)) { + assertThatThrownBy(() -> store.append(file(0))) + .isInstanceOf(IOException.class) + .hasMessageContaining("limit"); + assertNoOwnedFiles(); + } + } + + @Test + void testReadFailureIsNotReportedAsAnEmptySlice() throws Exception { + try (DataFileMetaStore store = new DataFileMetaStore(directory, 1024 * 1024)) { + store.append(file(0)); + store.append(file(1)); + store.seal(); + Path data; + try (Stream files = Files.list(directory)) { + data = files.filter(path -> path.toString().endsWith(".data")).findFirst().get(); + } + try (FileChannel channel = FileChannel.open(data, StandardOpenOption.WRITE)) { + channel.truncate(0); + } + List slice = store.slice(0, 2); + assertThatThrownBy(() -> slice.get(0)).isInstanceOf(UncheckedIOException.class); + assertThatThrownBy(() -> slice.iterator().next()) + .isInstanceOf(UncheckedIOException.class); + } + assertNoOwnedFiles(); + } + + @Test + void testInterruptedDataReplayDoesNotPoisonIndependentSlices() throws Exception { + try (DataFileMetaStore store = new DataFileMetaStore(directory, 1024 * 1024)) { + store.append(file(0)); + store.append(file(1)); + store.seal(); + List interruptedSlice = store.slice(0, 2); + List independentSlice = store.slice(0, 2); + // Resolve index offsets before interruption, but leave both data buffers empty. + Iterator interrupted = interruptedSlice.iterator(); + Iterator independent = independentSlice.iterator(); + + assertInterruptedReadFails(interrupted::next); + + assertThat(independent.next()).isEqualTo(file(0)); + assertThat(independent.next()).isEqualTo(file(1)); + assertThat(independent.hasNext()).isFalse(); + assertThat(independentSlice).containsExactly(file(0), file(1)); + assertThat(independentSlice.get(0)).isEqualTo(file(0)); + assertThat(independentSlice.get(1)).isEqualTo(file(1)); + + Iterator buffered = interruptedSlice.iterator(); + assertThat(buffered.next()).isEqualTo(file(0)); + assertInterruptedReadFails(buffered::next); + assertThat(independentSlice).containsExactly(file(0), file(1)); + } + assertNoOwnedFiles(); + } + + @Test + void testInterruptedIndexReadDoesNotPoisonIndependentSlices() throws Exception { + try (DataFileMetaStore store = new DataFileMetaStore(directory, 1024 * 1024)) { + store.append(file(0)); + store.append(file(1)); + store.seal(); + List interruptedSlice = store.slice(0, 2); + List independentSlice = store.slice(0, 2); + + assertInterruptedReadFails(() -> interruptedSlice.get(0)); + + assertThat(independentSlice.get(0)).isEqualTo(file(0)); + assertThat(independentSlice.get(1)).isEqualTo(file(1)); + assertThat(independentSlice).containsExactly(file(0), file(1)); + } + assertNoOwnedFiles(); + } + + private static void assertInterruptedReadFails(Runnable read) throws Exception { + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + executor.submit( + () -> { + Thread.currentThread().interrupt(); + assertThatThrownBy(read::run) + .isInstanceOf(UncheckedIOException.class); + assertThat(Thread.currentThread().isInterrupted()).isTrue(); + }) + .get(10, TimeUnit.SECONDS); + } finally { + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + } + + @Test + void testConcurrentReplayAndCloseInvalidation() throws Exception { + DataFileMetaStore store = new DataFileMetaStore(directory, 1024 * 1024); + ExecutorService executor = Executors.newFixedThreadPool(4); + try { + for (int i = 0; i < 100; i++) { + store.append(file(i)); + } + store.seal(); + List slice = store.slice(10, 90); + List> reads = new ArrayList<>(); + for (int task = 0; task < 4; task++) { + reads.add( + () -> { + int count = 0; + for (DataFileMeta value : slice) { + assertThat(value).isEqualTo(file(10 + count++)); + assertThat(slice.get(79)).isEqualTo(file(89)); + } + return count; + }); + } + for (Future result : executor.invokeAll(reads)) { + assertThat(result.get()).isEqualTo(80); + } + Iterator iterator = slice.iterator(); + assertThat(iterator.next()).isEqualTo(file(10)); + assertThat(iterator.hasNext()).isTrue(); + store.close(); + assertThatThrownBy(() -> slice.get(0)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(iterator::next).isInstanceOf(IllegalStateException.class); + } finally { + executor.shutdownNow(); + store.close(); + } + assertNoOwnedFiles(); + } + + private void assertNoOwnedFiles() throws IOException { + try (Stream files = Files.list(directory)) { + assertThat(files.count()).isZero(); + } + } + + private static DataFileMeta file(int index) { + return DataFileMeta.create( + "file-" + index, + 100L + index, + 2, + DataFileMeta.EMPTY_MIN_KEY, + DataFileMeta.EMPTY_MAX_KEY, + SimpleStats.EMPTY_STATS, + SimpleStats.EMPTY_STATS, + index, + index + 1L, + 0, + 0, + Collections.singletonList("extra-" + index), + Timestamp.fromEpochMillis(12345), + 0L, + new byte[] {1, 2, 3}, + FileSource.APPEND, + Arrays.asList("id", "value"), + "s3://not-opened/" + index, + 2L * index, + Arrays.asList("id", "value"), + new long[] {index, index + 1L}); + } + + private static DataSplit split(List files) { + return DataSplit.builder() + .withSnapshot(17) + .withPartition(BinaryRow.EMPTY_ROW) + .withBucket(0) + .withBucketPath("/unused-on-executor/bucket-0") + .withDataFiles(files) + .rawConvertible(false) + .build(); + } +} diff --git a/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala b/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala index 9b425c661ce6..8910ee848cb9 100644 --- a/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala +++ b/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala @@ -29,12 +29,13 @@ import org.apache.paimon.io.{CompactIncrement, DataFileMeta, DataIncrement} import org.apache.paimon.manifest.IndexManifestEntry import org.apache.paimon.options.Options import org.apache.paimon.predicate.{Predicate, PredicateBuilder} -import org.apache.paimon.spark.SparkTable +import org.apache.paimon.spark.{SparkTable, SparkUtils} import org.apache.paimon.spark.catalyst.analysis.PaimonRelation import org.apache.paimon.spark.catalyst.analysis.PaimonUpdateTable.toColumn import org.apache.paimon.spark.catalyst.analysis.expressions.ExpressionHelper import org.apache.paimon.spark.leafnode.PaimonLeafRunnableCommand import org.apache.paimon.spark.util.ScanPlanHelper.createNewScanPlan +import org.apache.paimon.spark.write.CommitMessageSeq import org.apache.paimon.table.FileStoreTable import org.apache.paimon.table.sink.{CommitMessage, CommitMessageImpl} import org.apache.paimon.table.source.DataSplit @@ -314,58 +315,113 @@ case class MergeIntoPaimonDataEvolutionTable( } private def invokeMergeInto(sparkSession: SparkSession): Unit = { + val optimized = table.coreOptions().dataEvolutionMetadataMemoryOptimizationEnabled() + val (updates, otherMessages, readSnapshotId) = prepareMergeInto(sparkSession, optimized) + if (optimized) commitPrepared(sparkSession, updates, otherMessages, readSnapshotId) + } + + private def commitPrepared( + sparkSession: SparkSession, + updates: Seq[CommitMessage], + otherMessages: Seq[CommitMessage], + readSnapshotId: Long): Unit = { + DataEvolutionRowIdConflictCommitter.commit( + sparkSession, + table, + targetRelation, + writer, + updates, + otherMessages, + readSnapshotId, + Snapshot.Operation.MERGE) + } + + // All preparation jobs have completed when this returns. Keep their plans and cached outputs + // out of the commit frame, while retaining the messages needed for conflict retries. + private def prepareMergeInto( + sparkSession: SparkSession, + optimized: Boolean): (Seq[CommitMessage], Seq[CommitMessage], Long) = { + if (!table.coreOptions().dataEvolutionMetadataStreamingEnabled()) { + return prepareMergeJobs(sparkSession, optimized, None) + } + val maxDiskBytes = table.coreOptions().dataEvolutionMetadataMaxDiskSize() + val metadata = new DataEvolutionMergeMetadata(SparkUtils.createIOManager(), maxDiskBytes) + try { + val prepared = prepareMergeJobs(sparkSession, optimized, Some(metadata)) + metadata.close() + prepared + } catch { + case failure: Throwable => + try metadata.close() + catch { + case cleanupFailure: Throwable => + if (cleanupFailure ne failure) failure.addSuppressed(cleanupFailure) + } + throw failure + } + } + + private def prepareMergeJobs( + sparkSession: SparkSession, + optimized: Boolean, + metadataOwner: Option[DataEvolutionMergeMetadata]) + : (Seq[CommitMessage], Seq[CommitMessage], Long) = { val readSnapshot = TimeTravelUtil.tryTravelOrLatest(table) val snapshotReader = table.newSnapshotReader() if (readSnapshot != null) { snapshotReader.withSnapshot(readSnapshot) } pushDownMergeFilters(snapshotReader) - val plan = snapshotReader.read() + if (optimized) { + // Preparation only needs file identity and row-id ranges after pruning. + snapshotReader.dropStats() + } + val plan = metadataOwner match { + case Some(owner) => owner.read(snapshotReader) + case None => snapshotReader.read() + } val tableSplits: Seq[DataSplit] = plan .splits() .asScala .map(_.asInstanceOf[DataSplit]) .toSeq - val normalDataFiles: Seq[DataFileMeta] = tableSplits - .flatMap(_.dataFiles().asScala) - .filter { - file => - file.firstRowId() != null && - !isBlobFile(file.fileName()) && - !isVectorStoreFile(file.fileName()) - } - val firstRowIds: immutable.IndexedSeq[Long] = normalDataFiles - .map(file => file.firstRowId().asInstanceOf[Long]) - .distinct - .sorted - .toIndexedSeq - // Exclusive end of the row-id range starting at each entry of `firstRowIds`. Files sharing a - // first row id are column groups of one range and end at the same row id. - val rowIdRangeEnds: immutable.IndexedSeq[Long] = { - val ends = normalDataFiles - .groupBy(_.firstRowId().longValue()) - .map { case (first, files) => first -> files.map(file => first + file.rowCount()).max } - firstRowIds.map(ends) - } - - val firstRowIdToBlobFirstRowIds: Map[Long, List[Long]] = { - val map = new mutable.HashMap[Long, List[Long]]() - val files = tableSplits - .flatMap(_.dataFiles().asScala) - .filter(file => isBlobFile(file.fileName())) - .sortBy(f => f.firstRowId()) - - for (file <- files) { - val firstRowId = file.firstRowId().asInstanceOf[Long] - val firstIdInNormalFile = floorBinarySearch(firstRowIds, firstRowId) - map.update( - firstIdInNormalFile, - map.getOrElseUpdate(firstIdInNormalFile, List.empty[Long]) :+ firstRowId - ) + val (firstRowIds, rowIdRangeEnds, firstRowIdToBlobFirstRowIds) = + if (metadataOwner.isDefined) { + val summary = DataEvolutionMergeMetadata.summarize(tableSplits) + (summary.firstRowIds, summary.rowIdRangeEnds, summary.firstRowIdToBlobFirstRowIds) + } else { + val normalDataFiles: Seq[DataFileMeta] = tableSplits + .flatMap(_.dataFiles().asScala) + .filter { + file => + file.firstRowId() != null && + !isBlobFile(file.fileName()) && + !isVectorStoreFile(file.fileName()) + } + val starts: immutable.IndexedSeq[Long] = normalDataFiles + .map(file => file.firstRowId().asInstanceOf[Long]) + .distinct + .sorted + .toIndexedSeq + val rangeEnds = normalDataFiles + .groupBy(_.firstRowId().longValue()) + .map { case (first, files) => first -> files.map(file => first + file.rowCount()).max } + val ends: immutable.IndexedSeq[Long] = starts.map(rangeEnds) + val mapping = new mutable.HashMap[Long, List[Long]]() + val files = tableSplits + .flatMap(_.dataFiles().asScala) + .filter(file => isBlobFile(file.fileName())) + .sortBy(f => f.firstRowId()) + for (file <- files) { + val firstRowId = file.firstRowId().asInstanceOf[Long] + val firstIdInNormalFile = floorBinarySearch(starts, firstRowId) + mapping.update( + firstIdInNormalFile, + mapping.getOrElseUpdate(firstIdInNormalFile, List.empty[Long]) :+ firstRowId) + } + (starts, ends, mapping.toMap) } - map.toMap - } val persistSourceDss: Option[Dataset[Row]] = if ( @@ -389,7 +445,8 @@ case class MergeIntoPaimonDataEvolutionTable( firstRowIds, rowIdRangeEnds, firstRowIdToBlobFirstRowIds, - persistSourceDss) + persistSourceDss, + metadataOwner) lazy val touchedFileTargetRelation = createNewScanPlan(matchedOrInsertDataSplits, targetRelation) @@ -415,7 +472,11 @@ case class MergeIntoPaimonDataEvolutionTable( } val notMatchedBySourceDvs = if (notMatchedBySourceActions.nonEmpty) { - notMatchedBySourceDeletionVectors(sparkSession, readSnapshot, persistSourceDss) + notMatchedBySourceDeletionVectors( + sparkSession, + readSnapshot, + persistSourceDss, + metadataOwner) } else None // Merge deletion vectors generated from NMBS and matched conditions @@ -434,16 +495,17 @@ case class MergeIntoPaimonDataEvolutionTable( sharedMatches) else Nil - DataEvolutionRowIdConflictCommitter.commit( - sparkSession, - table, - targetRelation, - writer, - matchedResult.commitMessages, - deleteCommit ++ insertCommit, - if (readSnapshot == null) -1L else readSnapshot.id(), - Snapshot.Operation.MERGE - ) + val updates = matchedResult.commitMessages + val otherMessages = + if (optimized) CommitMessageSeq.concat(Seq(deleteCommit, insertCommit)) + else deleteCommit ++ insertCommit + val readSnapshotId = if (readSnapshot == null) -1L else readSnapshot.id() + if (optimized) { + (updates, otherMessages, readSnapshotId) + } else { + commitPrepared(sparkSession, updates, otherMessages, readSnapshotId) + (Nil, Nil, -1L) + } } finally { try { targetActionCleanup() @@ -612,7 +674,8 @@ case class MergeIntoPaimonDataEvolutionTable( firstRowIds: immutable.IndexedSeq[Long], rowIdRangeEnds: immutable.IndexedSeq[Long], firstRowIdToBlobFirstRowIds: Map[Long, List[Long]], - persistSourceDss: Option[Dataset[Row]]): Seq[DataSplit] = { + persistSourceDss: Option[Dataset[Row]], + metadataOwner: Option[DataEvolutionMergeMetadata]): Seq[DataSplit] = { // Self-Merge shortcut: // Snapshot-level merge filters have already removed unrelated splits. MergeRows preserves // rows in the remaining splits which do not satisfy any matched action condition. @@ -653,6 +716,13 @@ case class MergeIntoPaimonDataEvolutionTable( ).toSet } + if (metadataOwner.isDefined) { + if (firstRowIdsTouched.isEmpty) return Nil + return metadataOwner.get.prune( + tableSplits, + file => file.firstRowId() != null && firstRowIdsTouched.contains(file.firstRowId())) + } + tableSplits .map( split => @@ -1117,7 +1187,8 @@ case class MergeIntoPaimonDataEvolutionTable( private def notMatchedBySourceDeletionVectors( sparkSession: SparkSession, readSnapshot: Snapshot, - persistSourceDss: Option[Dataset[Row]]): Option[Dataset[SparkDeletionVector]] = { + persistSourceDss: Option[Dataset[Row]], + metadataOwner: Option[DataEvolutionMergeMetadata]): Option[Dataset[SparkDeletionVector]] = { // Do not reuse tableSplits here because they may have been pruned by the MERGE ON // partition filter. NOT MATCHED BY SOURCE must scan target rows independently. val snapshotReader = table.newSnapshotReader() @@ -1127,8 +1198,11 @@ case class MergeIntoPaimonDataEvolutionTable( if (table.coreOptions().manifestDeleteFileDropStats()) { snapshotReader.dropStats() } - val dataSplits = - snapshotReader.read().splits().asScala.collect { case split: DataSplit => split }.toSeq + val plan = metadataOwner match { + case Some(owner) => owner.read(snapshotReader) + case None => snapshotReader.read() + } + val dataSplits = plan.splits().asScala.collect { case split: DataSplit => split }.toSeq if (dataSplits.isEmpty) { return None } @@ -1306,7 +1380,7 @@ case class MergeIntoPaimonDataEvolutionTable( return updateCommit } - val affectedParts: Set[BinaryRow] = updateCommit.map(_.partition()).toSet + val affectedParts: Set[BinaryRow] = updateCommit.iterator.map(_.partition()).toSet val rowType = table.rowType() // find all global index files of affected partitions and updated columns @@ -1359,7 +1433,11 @@ case class MergeIntoPaimonDataEvolutionTable( DataIncrement.deleteIndexIncrement(entries.map(_.indexFile()).asJava), CompactIncrement.emptyIncrement()) } - updateCommit ++ deleteCommitMessages + if (table.coreOptions().dataEvolutionMetadataMemoryOptimizationEnabled()) { + CommitMessageSeq.concat(Seq(updateCommit, deleteCommitMessages.toSeq)) + } else { + updateCommit ++ deleteCommitMessages + } } } } diff --git a/paimon-spark/paimon-spark-4.3/pom.xml b/paimon-spark/paimon-spark-4.3/pom.xml index 201e3d3e31f6..0a75f0ff0fcb 100644 --- a/paimon-spark/paimon-spark-4.3/pom.xml +++ b/paimon-spark/paimon-spark-4.3/pom.xml @@ -108,6 +108,19 @@ under the License. spark-hive_${scala.binary.version} ${spark.version} + + org.apache.paimon + paimon-spark-ut_${scala.binary.version} + ${project.version} + tests + test + + + * + * + + + org.apache.spark spark-sql_${scala.binary.version} diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonBaseScan.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonBaseScan.scala index 9e1430a03130..c5da2229949f 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonBaseScan.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonBaseScan.scala @@ -27,8 +27,8 @@ import org.apache.paimon.spark.metric.SparkMetricRegistry import org.apache.paimon.spark.read.{BaseScan, BatchReadTagCleanupListener, PaimonStatistics, PaimonSupportsRuntimeFiltering, SparkHybridSearchBuilderImpl, SparkVectorSearchBuilderImpl} import org.apache.paimon.spark.sources.PaimonMicroBatchStream import org.apache.paimon.spark.util.OptionUtils -import org.apache.paimon.table.{DataTable, FileStoreTable, InnerTable} -import org.apache.paimon.table.source.{InnerTableScan, Split} +import org.apache.paimon.table.{DataTable, FallbackReadFileStoreTable, FileStoreTable, InnerTable} +import org.apache.paimon.table.source.{DataFileMetaStore, InnerTableScan, Split} import org.apache.spark.sql.SparkSession import org.apache.spark.sql.catalyst.SQLConfHelper @@ -38,6 +38,8 @@ import org.apache.spark.sql.connector.read.{Batch, Statistics} import org.apache.spark.sql.connector.read.streaming.MicroBatchStream import org.apache.spark.sql.execution.SQLExecution +import java.nio.file.Paths + import scala.collection.JavaConverters._ abstract class PaimonBaseScan(table: InnerTable) @@ -50,8 +52,27 @@ abstract class PaimonBaseScan(table: InnerTable) @transient private lazy val postponeMergeOnRead = new PostponeMergeOnRead(this) protected def getInputSplits: Array[Split] = { - val scan = readBuilder - .newScan() + if (coreOptions.dataEvolutionMetadataStreamingEnabled() && supportsMetadataReplay) { + return getIncrementalInputSplits + } + planInputSplits(readBuilder.newScan().asInstanceOf[InnerTableScan]) + } + + private def supportsMetadataReplay: Boolean = { + // A replay store belongs to one ALL-snapshot reader, not composite or incremental scans. + if (!table.isInstanceOf[FileStoreTable] || table.isInstanceOf[FallbackReadFileStoreTable]) { + return false + } + coreOptions.startupMode() match { + case CoreOptions.StartupMode.INCREMENTAL | CoreOptions.StartupMode.LATEST_DELTA => false + case _ => + coreOptions.toConfiguration.get(CoreOptions.BATCH_SCAN_MODE) == + CoreOptions.BatchScanMode.NONE + } + } + + private def planInputSplits(inputScan: InnerTableScan): Array[Split] = { + val scan = inputScan .withGlobalIndexResult(evalGlobalIndexSearch()) .asInstanceOf[InnerTableScan] .withMetricRegistry(paimonMetricsRegistry) @@ -61,6 +82,50 @@ abstract class PaimonBaseScan(table: InnerTable) plan.splits().asScala.toArray } + private def getIncrementalInputSplits: Array[Split] = { + val io = SparkUtils.createIOManager() + var store: DataFileMetaStore = null + try { + store = new DataFileMetaStore( + Paths.get(io.pickTempDir()), + coreOptions.dataEvolutionMetadataMaxDiskSize()) + val scan = + readBuilder.newScan(actual => actual.newSnapshotReader().withIncrementalPlanning(store, io)) + val splits = planInputSplits(scan.asInstanceOf[InnerTableScan]) + if (splits.isEmpty) { + // Empty-table planning may finish before the snapshot reader seals its store. + store.close() + io.close() + return splits + } + // Sort spill is finished; replay files remain owned by the returned split slices. + io.close() + store.withAutomaticCleanup() + logInfo( + s"Incremental metadata planning produced ${splits.length} splits with " + + s"${store.serializedBytes()} encoded replay bytes.") + splits + } catch { + case failure: Throwable => + if (store != null) { + closeAfterFailure(store, failure) + } + closeAfterFailure(io, failure) + throw failure + } + } + + private def closeAfterFailure(resource: AutoCloseable, failure: Throwable): Unit = { + try { + resource.close() + } catch { + case cleanupFailure: Throwable => + if (cleanupFailure ne failure) { + failure.addSuppressed(cleanupFailure) + } + } + } + final private[spark] def registerReadProtectionTagCleanup(tagName: String): Unit = { Option(tagName).foreach { name => diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DataEvolutionMergeMetadata.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DataEvolutionMergeMetadata.scala new file mode 100644 index 000000000000..be449486bc7b --- /dev/null +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DataEvolutionMergeMetadata.scala @@ -0,0 +1,151 @@ +/* + * 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.paimon.spark.commands + +import org.apache.paimon.disk.IOManager +import org.apache.paimon.format.blob.BlobFileFormat.isBlobFile +import org.apache.paimon.io.DataFileMeta +import org.apache.paimon.table.source.{DataFileMetaStore, DataSplit} +import org.apache.paimon.table.source.snapshot.SnapshotReader +import org.apache.paimon.types.VectorType.isVectorStoreFile +import org.apache.paimon.utils.LongArrayList + +import java.nio.file.Paths +import java.util.{Arrays, TreeMap} + +import scala.collection.{immutable, mutable} +import scala.collection.JavaConverters._ +import scala.collection.mutable.ArrayBuffer + +/** Owns replay files until all internal MERGE preparation jobs have finished. */ +final private[spark] class DataEvolutionMergeMetadata(val ioManager: IOManager, maxDiskBytes: Long) + extends AutoCloseable { + + private val stores = new ArrayBuffer[DataFileMetaStore] + private var closed = false + private var fullyClosed = false + + def newStore(): DataFileMetaStore = { + checkOpen() + val store = new DataFileMetaStore(Paths.get(ioManager.pickTempDir()), maxDiskBytes) + try { + stores += store + store + } catch { + case failure: Throwable => + try store.close() + catch { + case cleanupFailure: Throwable => + if (cleanupFailure ne failure) failure.addSuppressed(cleanupFailure) + } + throw failure + } + } + + def read(reader: SnapshotReader): SnapshotReader.Plan = + reader.readIncrementally(newStore(), ioManager) + + def prune(splits: Seq[DataSplit], keep: DataFileMeta => Boolean): Seq[DataSplit] = + DataSplit.filterDataFiles(splits.asJava, file => keep(file), newStore()).asScala.toVector + + override def close(): Unit = { + if (fullyClosed) return + closed = true + var failure: Throwable = null + val resources = stores.reverseIterator.map(store => store: AutoCloseable) ++ Iterator(ioManager) + resources.foreach { + resource => + try resource.close() + catch { + case error: Throwable => + if (failure == null) failure = error + else if (error ne failure) failure.addSuppressed(error) + } + } + if (failure != null) throw failure + fullyClosed = true + stores.clear() + } + + private def checkOpen(): Unit = { + if (closed) throw new IllegalStateException("MERGE metadata owner is closed.") + } +} + +private[spark] object DataEvolutionMergeMetadata { + + case class RangeSummary( + firstRowIds: immutable.IndexedSeq[Long], + rowIdRangeEnds: immutable.IndexedSeq[Long], + firstRowIdToBlobFirstRowIds: Map[Long, List[Long]]) + + def summarize(splits: Seq[DataSplit]): RangeSummary = { + val ranges = new TreeMap[java.lang.Long, java.lang.Long]() + val blobs = new LongArrayList(16) + splits.iterator.flatMap(_.dataFiles().asScala.iterator).foreach { + file => + val first = file.firstRowId() + if (isBlobFile(file.fileName())) { + blobs.add(first.longValue()) + } else if (first != null && !isVectorStoreFile(file.fileName())) { + val end = first.longValue() + file.rowCount() + val previous = ranges.get(first) + if (previous == null || end > previous.longValue()) ranges.put(first, end) + } + } + val starts = new Array[Long](ranges.size()) + val ends = new Array[Long](ranges.size()) + val entries = ranges.entrySet().iterator() + var index = 0 + while (entries.hasNext) { + val entry = entries.next() + starts(index) = entry.getKey.longValue() + ends(index) = entry.getValue.longValue() + index += 1 + } + val blobIds = blobs.toArray + Arrays.sort(blobIds) + val mapping = new mutable.HashMap[Long, mutable.ListBuffer[Long]] + blobIds.foreach { + first => + if (starts.isEmpty) { + throw new IllegalArgumentException("The input sorted sequence is empty.") + } + val found = Arrays.binarySearch(starts, first) + val floor = if (found >= 0) found else -found - 2 + if (floor < 0) { + throw new IllegalArgumentException( + s"Value $first is less than the first element in the sorted sequence.") + } + mapping.getOrElseUpdate(starts(floor), mutable.ListBuffer.empty[Long]) += first + } + RangeSummary( + new LongIndexedSeq(starts), + new LongIndexedSeq(ends), + mapping.iterator.map { case (first, values) => first -> values.toList }.toMap) + } + + @SerialVersionUID(1L) + final private class LongIndexedSeq(values: Array[Long]) + extends immutable.IndexedSeq[Long] + with Serializable { + override def length: Int = values.length + override def apply(index: Int): Long = values(index) + } +} diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DataEvolutionPaimonWriter.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DataEvolutionPaimonWriter.scala index f11d661432c6..46f660a3634d 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DataEvolutionPaimonWriter.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DataEvolutionPaimonWriter.scala @@ -20,7 +20,7 @@ package org.apache.paimon.spark.commands import org.apache.paimon.CoreOptions import org.apache.paimon.format.blob.BlobFileFormat.isBlobFile -import org.apache.paimon.spark.write.{DataEvolutionTableDataWrite, WriteHelper, WriteTaskResult} +import org.apache.paimon.spark.write.{CommitMessageSeq, DataEvolutionTableDataWrite, WriteHelper, WriteTaskResult} import org.apache.paimon.table.FileStoreTable import org.apache.paimon.table.sink._ import org.apache.paimon.table.source.DataSplit @@ -29,6 +29,7 @@ import org.apache.paimon.types.RowType import org.apache.paimon.types.VectorType.isVectorStoreFile import org.apache.paimon.utils.SerializationUtils +import org.apache.spark.TaskContext import org.apache.spark.sql._ import org.apache.spark.sql.catalyst.analysis.SimpleAnalyzer.resolver @@ -127,24 +128,66 @@ case class DataEvolutionPaimonWriter(paimonTable: FileStoreTable, dataSplits: Se sparkSession.sparkContext.broadcast(firstRowIdToPartitionMap) val writeBuilder = table.newBatchWriteBuilder() - val written = - data.mapPartitions { - iter => - { - val write = DataEvolutionTableDataWrite( - writeBuilder, - writeType, - firstRowIdToPartitionMapBroadcast.value, - uriReaderFactory, - rawBlobPlaceholderMarkerIndexes) - try { - iter.foreach(row => write.write(row)) - Iterator.apply(write.commit) - } finally { - write.close() + if (table.coreOptions().dataEvolutionMetadataMemoryOptimizationEnabled()) { + val streaming = table.coreOptions().dataEvolutionMetadataStreamingEnabled() + val written = + data.mapPartitions { + iter => + { + val write = DataEvolutionTableDataWrite( + writeBuilder, + writeType, + firstRowIdToPartitionMapBroadcast.value, + uriReaderFactory, + rawBlobPlaceholderMarkerIndexes) + if (streaming) { + try { + val context = TaskContext.get + if (context != null) { + context.addTaskCompletionListener[Unit](_ => write.close()) + } + write.writeAndCommitRows(iter) + } catch { + case failure: Throwable => + try write.close() + catch { + case cleanupFailure: Throwable => + if (cleanupFailure ne failure) failure.addSuppressed(cleanupFailure) + } + throw failure + } + } else { + try { + iter.foreach(row => write.write(row)) + // Avoid one UnsafeRow buffer holding all messages returned by this task. + write.commit.serializedMessageBytes.iterator + } finally { + write.close() + } + } } - } - } - WriteTaskResult.merge(written.collect()) + } + new CommitMessageSeq(CommitMessageList.fromBytes(written.collect().toSeq.asJava)) + } else { + val written = + data.mapPartitions { + iter => + { + val write = DataEvolutionTableDataWrite( + writeBuilder, + writeType, + firstRowIdToPartitionMapBroadcast.value, + uriReaderFactory, + rawBlobPlaceholderMarkerIndexes) + try { + iter.foreach(row => write.write(row)) + Iterator.apply(write.commit) + } finally { + write.close() + } + } + } + WriteTaskResult.merge(written.collect()) + } } } diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DataEvolutionRowIdConflictRewriter.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DataEvolutionRowIdConflictRewriter.scala index 4cb9b80079aa..c0716747f2d7 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DataEvolutionRowIdConflictRewriter.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DataEvolutionRowIdConflictRewriter.scala @@ -25,8 +25,9 @@ import org.apache.paimon.io.{DataFileMeta, DataIncrement} import org.apache.paimon.operation.commit.RowIdExistenceConflictException import org.apache.paimon.schema.TableSchema import org.apache.paimon.spark.util.ScanPlanHelper +import org.apache.paimon.spark.write.CommitMessageSeq import org.apache.paimon.table.{FileStoreTable, SpecialFields} -import org.apache.paimon.table.sink.{CommitMessage, CommitMessageImpl} +import org.apache.paimon.table.sink.{CommitMessage, CommitMessageImpl, CommitMessageList, CommitMessageSerializer} import org.apache.paimon.table.source.DataSplit import org.apache.paimon.types.VectorType.isVectorStoreFile import org.apache.paimon.utils.{DataEvolutionUtils, ExceptionUtils, Range, RetryWaiter} @@ -63,6 +64,10 @@ private[spark] class DataEvolutionRowIdConflictRewriter( return None } + if (table.coreOptions().dataEvolutionMetadataMemoryOptimizationEnabled()) { + return rewriteIncrementally(sparkSession, latestSnapshot, commitMessages) + } + val messageImpls = commitMessages.collect { case message: CommitMessageImpl => message } if (messageImpls.size != commitMessages.size) { return None @@ -125,6 +130,76 @@ private[spark] class DataEvolutionRowIdConflictRewriter( Some(RewriteResult(remainingMessages ++ rewrittenMessages, candidates.size)) } + private def rewriteIncrementally( + sparkSession: SparkSession, + latestSnapshot: Snapshot, + commitMessages: Seq[CommitMessage]): Option[RewriteResult] = { + val nextRowId = Option(latestSnapshot.nextRowId()).map(_.longValue()).getOrElse(return None) + var unsupported = false + var dedicated = false + // Inspect one decoded message at a time; a harmless snapshot advance must not retain them all. + commitMessages.iterator.foreach { + case message: CommitMessageImpl => + message.newFilesIncrement().newFiles().asScala.foreach { + file => + if ( + isDedicatedFile(file) && file.firstRowId() != null && file.firstRowId() < nextRowId + ) { + dedicated = true + } + } + case _ => unsupported = true + } + if (unsupported || dedicated) return None + + def stagedFiles: Iterator[StagedFile] = commitMessages.iterator.flatMap { + message => + val impl = message.asInstanceOf[CommitMessageImpl] + impl.newFilesIncrement().newFiles().asScala.iterator.map(file => StagedFile(impl, file)) + } + if (!stagedFiles.exists(staged => isRewriteCandidate(staged.file, nextRowId))) return None + + val currentSplits = table + .newSnapshotReader() + .withSnapshot(latestSnapshot) + .read() + .splits() + .asScala + .collect { case split: DataSplit => split } + .toSeq + def currentFiles: Iterator[CurrentFile] = currentSplits.iterator.flatMap { + split => + split + .dataFiles() + .asScala + .iterator + .filter(isNormalRowIdFile) + .map(file => CurrentFile(split, file)) + } + val exactRanges = currentFiles.map(current => rangeKey(current.split, current.file)).toSet + val candidates = stagedFiles + .filter( + staged => + isRewriteCandidate(staged.file, nextRowId) && + !exactRanges.contains(rangeKey(staged.message, staged.file))) + .toVector + if (candidates.isEmpty || !rangesAreStillCovered(currentFiles.toVector, candidates)) return None + + val rewritten = candidates.groupBy(staged => partialFileWriteCols(staged.file).get).toSeq.map { + case (columnNames, files) => rewriteFiles(sparkSession, columnNames, files, currentSplits) + } + val candidateKeys = + candidates.iterator.map(staged => fileKey(staged.message, staged.file)).toSet + // Re-encode survivors once so successive retries do not retain every previous source directory. + val serializer = new CommitMessageSerializer() + val remainingBytes = commitMessages.iterator + .flatMap(message => withoutCandidates(message.asInstanceOf[CommitMessageImpl], candidateKeys)) + .map(serializer.serialize) + .toArray + val remaining = new CommitMessageSeq(CommitMessageList.fromBytes(remainingBytes.toSeq.asJava)) + Some(RewriteResult(CommitMessageSeq.concat(Seq(remaining) ++ rewritten), candidates.size)) + } + private def rewriteFiles( sparkSession: SparkSession, columnNames: Seq[String], @@ -268,6 +343,7 @@ private[spark] class DataEvolutionRowIdConflictRewriter( ) if (remaining.isEmpty) None else Some(remaining) } + } private[spark] object DataEvolutionRowIdConflictRewriter { @@ -370,12 +446,20 @@ private[spark] object DataEvolutionRowIdConflictCommitter { while (true) { try { - val messages = currentUpdateMessages ++ otherMessages - writer.commit( - if (readSnapshotId < 0) messages - else - messages.map(_.asInstanceOf[CommitMessageImpl].withCheckFromSnapshot(readSnapshotId)), - operation) + val messages = + if (options.dataEvolutionMetadataMemoryOptimizationEnabled()) { + val combined = CommitMessageSeq.concat(Seq(currentUpdateMessages, otherMessages)) + if (readSnapshotId < 0) combined + else + CommitMessageSeq.map(combined)( + _.asInstanceOf[CommitMessageImpl].withCheckFromSnapshot(readSnapshotId)) + } else { + val combined = currentUpdateMessages ++ otherMessages + if (readSnapshotId < 0) combined + else + combined.map(_.asInstanceOf[CommitMessageImpl].withCheckFromSnapshot(readSnapshotId)) + } + writer.commit(messages, operation) return } catch { case conflict: RuntimeException if isRowIdExistenceConflict(conflict) => diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala index 9b425c661ce6..8910ee848cb9 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala @@ -29,12 +29,13 @@ import org.apache.paimon.io.{CompactIncrement, DataFileMeta, DataIncrement} import org.apache.paimon.manifest.IndexManifestEntry import org.apache.paimon.options.Options import org.apache.paimon.predicate.{Predicate, PredicateBuilder} -import org.apache.paimon.spark.SparkTable +import org.apache.paimon.spark.{SparkTable, SparkUtils} import org.apache.paimon.spark.catalyst.analysis.PaimonRelation import org.apache.paimon.spark.catalyst.analysis.PaimonUpdateTable.toColumn import org.apache.paimon.spark.catalyst.analysis.expressions.ExpressionHelper import org.apache.paimon.spark.leafnode.PaimonLeafRunnableCommand import org.apache.paimon.spark.util.ScanPlanHelper.createNewScanPlan +import org.apache.paimon.spark.write.CommitMessageSeq import org.apache.paimon.table.FileStoreTable import org.apache.paimon.table.sink.{CommitMessage, CommitMessageImpl} import org.apache.paimon.table.source.DataSplit @@ -314,58 +315,113 @@ case class MergeIntoPaimonDataEvolutionTable( } private def invokeMergeInto(sparkSession: SparkSession): Unit = { + val optimized = table.coreOptions().dataEvolutionMetadataMemoryOptimizationEnabled() + val (updates, otherMessages, readSnapshotId) = prepareMergeInto(sparkSession, optimized) + if (optimized) commitPrepared(sparkSession, updates, otherMessages, readSnapshotId) + } + + private def commitPrepared( + sparkSession: SparkSession, + updates: Seq[CommitMessage], + otherMessages: Seq[CommitMessage], + readSnapshotId: Long): Unit = { + DataEvolutionRowIdConflictCommitter.commit( + sparkSession, + table, + targetRelation, + writer, + updates, + otherMessages, + readSnapshotId, + Snapshot.Operation.MERGE) + } + + // All preparation jobs have completed when this returns. Keep their plans and cached outputs + // out of the commit frame, while retaining the messages needed for conflict retries. + private def prepareMergeInto( + sparkSession: SparkSession, + optimized: Boolean): (Seq[CommitMessage], Seq[CommitMessage], Long) = { + if (!table.coreOptions().dataEvolutionMetadataStreamingEnabled()) { + return prepareMergeJobs(sparkSession, optimized, None) + } + val maxDiskBytes = table.coreOptions().dataEvolutionMetadataMaxDiskSize() + val metadata = new DataEvolutionMergeMetadata(SparkUtils.createIOManager(), maxDiskBytes) + try { + val prepared = prepareMergeJobs(sparkSession, optimized, Some(metadata)) + metadata.close() + prepared + } catch { + case failure: Throwable => + try metadata.close() + catch { + case cleanupFailure: Throwable => + if (cleanupFailure ne failure) failure.addSuppressed(cleanupFailure) + } + throw failure + } + } + + private def prepareMergeJobs( + sparkSession: SparkSession, + optimized: Boolean, + metadataOwner: Option[DataEvolutionMergeMetadata]) + : (Seq[CommitMessage], Seq[CommitMessage], Long) = { val readSnapshot = TimeTravelUtil.tryTravelOrLatest(table) val snapshotReader = table.newSnapshotReader() if (readSnapshot != null) { snapshotReader.withSnapshot(readSnapshot) } pushDownMergeFilters(snapshotReader) - val plan = snapshotReader.read() + if (optimized) { + // Preparation only needs file identity and row-id ranges after pruning. + snapshotReader.dropStats() + } + val plan = metadataOwner match { + case Some(owner) => owner.read(snapshotReader) + case None => snapshotReader.read() + } val tableSplits: Seq[DataSplit] = plan .splits() .asScala .map(_.asInstanceOf[DataSplit]) .toSeq - val normalDataFiles: Seq[DataFileMeta] = tableSplits - .flatMap(_.dataFiles().asScala) - .filter { - file => - file.firstRowId() != null && - !isBlobFile(file.fileName()) && - !isVectorStoreFile(file.fileName()) - } - val firstRowIds: immutable.IndexedSeq[Long] = normalDataFiles - .map(file => file.firstRowId().asInstanceOf[Long]) - .distinct - .sorted - .toIndexedSeq - // Exclusive end of the row-id range starting at each entry of `firstRowIds`. Files sharing a - // first row id are column groups of one range and end at the same row id. - val rowIdRangeEnds: immutable.IndexedSeq[Long] = { - val ends = normalDataFiles - .groupBy(_.firstRowId().longValue()) - .map { case (first, files) => first -> files.map(file => first + file.rowCount()).max } - firstRowIds.map(ends) - } - - val firstRowIdToBlobFirstRowIds: Map[Long, List[Long]] = { - val map = new mutable.HashMap[Long, List[Long]]() - val files = tableSplits - .flatMap(_.dataFiles().asScala) - .filter(file => isBlobFile(file.fileName())) - .sortBy(f => f.firstRowId()) - - for (file <- files) { - val firstRowId = file.firstRowId().asInstanceOf[Long] - val firstIdInNormalFile = floorBinarySearch(firstRowIds, firstRowId) - map.update( - firstIdInNormalFile, - map.getOrElseUpdate(firstIdInNormalFile, List.empty[Long]) :+ firstRowId - ) + val (firstRowIds, rowIdRangeEnds, firstRowIdToBlobFirstRowIds) = + if (metadataOwner.isDefined) { + val summary = DataEvolutionMergeMetadata.summarize(tableSplits) + (summary.firstRowIds, summary.rowIdRangeEnds, summary.firstRowIdToBlobFirstRowIds) + } else { + val normalDataFiles: Seq[DataFileMeta] = tableSplits + .flatMap(_.dataFiles().asScala) + .filter { + file => + file.firstRowId() != null && + !isBlobFile(file.fileName()) && + !isVectorStoreFile(file.fileName()) + } + val starts: immutable.IndexedSeq[Long] = normalDataFiles + .map(file => file.firstRowId().asInstanceOf[Long]) + .distinct + .sorted + .toIndexedSeq + val rangeEnds = normalDataFiles + .groupBy(_.firstRowId().longValue()) + .map { case (first, files) => first -> files.map(file => first + file.rowCount()).max } + val ends: immutable.IndexedSeq[Long] = starts.map(rangeEnds) + val mapping = new mutable.HashMap[Long, List[Long]]() + val files = tableSplits + .flatMap(_.dataFiles().asScala) + .filter(file => isBlobFile(file.fileName())) + .sortBy(f => f.firstRowId()) + for (file <- files) { + val firstRowId = file.firstRowId().asInstanceOf[Long] + val firstIdInNormalFile = floorBinarySearch(starts, firstRowId) + mapping.update( + firstIdInNormalFile, + mapping.getOrElseUpdate(firstIdInNormalFile, List.empty[Long]) :+ firstRowId) + } + (starts, ends, mapping.toMap) } - map.toMap - } val persistSourceDss: Option[Dataset[Row]] = if ( @@ -389,7 +445,8 @@ case class MergeIntoPaimonDataEvolutionTable( firstRowIds, rowIdRangeEnds, firstRowIdToBlobFirstRowIds, - persistSourceDss) + persistSourceDss, + metadataOwner) lazy val touchedFileTargetRelation = createNewScanPlan(matchedOrInsertDataSplits, targetRelation) @@ -415,7 +472,11 @@ case class MergeIntoPaimonDataEvolutionTable( } val notMatchedBySourceDvs = if (notMatchedBySourceActions.nonEmpty) { - notMatchedBySourceDeletionVectors(sparkSession, readSnapshot, persistSourceDss) + notMatchedBySourceDeletionVectors( + sparkSession, + readSnapshot, + persistSourceDss, + metadataOwner) } else None // Merge deletion vectors generated from NMBS and matched conditions @@ -434,16 +495,17 @@ case class MergeIntoPaimonDataEvolutionTable( sharedMatches) else Nil - DataEvolutionRowIdConflictCommitter.commit( - sparkSession, - table, - targetRelation, - writer, - matchedResult.commitMessages, - deleteCommit ++ insertCommit, - if (readSnapshot == null) -1L else readSnapshot.id(), - Snapshot.Operation.MERGE - ) + val updates = matchedResult.commitMessages + val otherMessages = + if (optimized) CommitMessageSeq.concat(Seq(deleteCommit, insertCommit)) + else deleteCommit ++ insertCommit + val readSnapshotId = if (readSnapshot == null) -1L else readSnapshot.id() + if (optimized) { + (updates, otherMessages, readSnapshotId) + } else { + commitPrepared(sparkSession, updates, otherMessages, readSnapshotId) + (Nil, Nil, -1L) + } } finally { try { targetActionCleanup() @@ -612,7 +674,8 @@ case class MergeIntoPaimonDataEvolutionTable( firstRowIds: immutable.IndexedSeq[Long], rowIdRangeEnds: immutable.IndexedSeq[Long], firstRowIdToBlobFirstRowIds: Map[Long, List[Long]], - persistSourceDss: Option[Dataset[Row]]): Seq[DataSplit] = { + persistSourceDss: Option[Dataset[Row]], + metadataOwner: Option[DataEvolutionMergeMetadata]): Seq[DataSplit] = { // Self-Merge shortcut: // Snapshot-level merge filters have already removed unrelated splits. MergeRows preserves // rows in the remaining splits which do not satisfy any matched action condition. @@ -653,6 +716,13 @@ case class MergeIntoPaimonDataEvolutionTable( ).toSet } + if (metadataOwner.isDefined) { + if (firstRowIdsTouched.isEmpty) return Nil + return metadataOwner.get.prune( + tableSplits, + file => file.firstRowId() != null && firstRowIdsTouched.contains(file.firstRowId())) + } + tableSplits .map( split => @@ -1117,7 +1187,8 @@ case class MergeIntoPaimonDataEvolutionTable( private def notMatchedBySourceDeletionVectors( sparkSession: SparkSession, readSnapshot: Snapshot, - persistSourceDss: Option[Dataset[Row]]): Option[Dataset[SparkDeletionVector]] = { + persistSourceDss: Option[Dataset[Row]], + metadataOwner: Option[DataEvolutionMergeMetadata]): Option[Dataset[SparkDeletionVector]] = { // Do not reuse tableSplits here because they may have been pruned by the MERGE ON // partition filter. NOT MATCHED BY SOURCE must scan target rows independently. val snapshotReader = table.newSnapshotReader() @@ -1127,8 +1198,11 @@ case class MergeIntoPaimonDataEvolutionTable( if (table.coreOptions().manifestDeleteFileDropStats()) { snapshotReader.dropStats() } - val dataSplits = - snapshotReader.read().splits().asScala.collect { case split: DataSplit => split }.toSeq + val plan = metadataOwner match { + case Some(owner) => owner.read(snapshotReader) + case None => snapshotReader.read() + } + val dataSplits = plan.splits().asScala.collect { case split: DataSplit => split }.toSeq if (dataSplits.isEmpty) { return None } @@ -1306,7 +1380,7 @@ case class MergeIntoPaimonDataEvolutionTable( return updateCommit } - val affectedParts: Set[BinaryRow] = updateCommit.map(_.partition()).toSet + val affectedParts: Set[BinaryRow] = updateCommit.iterator.map(_.partition()).toSet val rowType = table.rowType() // find all global index files of affected partitions and updated columns @@ -1359,7 +1433,11 @@ case class MergeIntoPaimonDataEvolutionTable( DataIncrement.deleteIndexIncrement(entries.map(_.indexFile()).asJava), CompactIncrement.emptyIncrement()) } - updateCommit ++ deleteCommitMessages + if (table.coreOptions().dataEvolutionMetadataMemoryOptimizationEnabled()) { + CommitMessageSeq.concat(Seq(updateCommit, deleteCommitMessages.toSeq)) + } else { + updateCommit ++ deleteCommitMessages + } } } } diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/PaimonSparkWriter.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/PaimonSparkWriter.scala index 605284ec2e18..7c2d84c2e888 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/PaimonSparkWriter.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/PaimonSparkWriter.scala @@ -37,7 +37,7 @@ import org.apache.paimon.spark.schema.SparkSystemColumns.{BUCKET_COL, ROW_KIND_C import org.apache.paimon.spark.sort.TableSorter import org.apache.paimon.spark.util.OptionUtils.paimonExtensionEnabled import org.apache.paimon.spark.util.SparkRowUtils -import org.apache.paimon.spark.write.{PaimonDataWrite, WriteHelper, WriteTaskResult} +import org.apache.paimon.spark.write.{CommitMessageSeq, PaimonDataWrite, WriteHelper, WriteTaskResult} import org.apache.paimon.table.{FileStoreTable, SpecialFields} import org.apache.paimon.table.BucketMode._ import org.apache.paimon.table.sink._ @@ -482,7 +482,13 @@ case class PaimonSparkWriter( tableCommit.withOperation(operation) } try { - tableCommit.commit(commitMessages.toList.asJava) + val messages = + if (table.coreOptions().dataEvolutionMetadataMemoryOptimizationEnabled()) { + CommitMessageSeq.asJava(commitMessages) + } else { + commitMessages.toList.asJava + } + tableCommit.commit(messages) } catch { case e: Throwable => throw new RuntimeException(e); } finally { diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/write/CommitMessageSeq.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/write/CommitMessageSeq.scala new file mode 100644 index 000000000000..13676326de79 --- /dev/null +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/write/CommitMessageSeq.scala @@ -0,0 +1,45 @@ +/* + * 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.paimon.spark.write + +import org.apache.paimon.table.sink.{CommitMessage, CommitMessageList} + +import scala.collection.JavaConverters._ + +/** Keeps the byte-backed list intact across Scala's collection and Java commit interfaces. */ +private[spark] class CommitMessageSeq(val messages: java.util.List[CommitMessage]) + extends IndexedSeq[CommitMessage] { + override def length: Int = messages.size() + override def apply(index: Int): CommitMessage = messages.get(index) + override def iterator: Iterator[CommitMessage] = messages.iterator().asScala +} + +private[spark] object CommitMessageSeq { + def asJava(messages: Seq[CommitMessage]): java.util.List[CommitMessage] = messages match { + case lazyMessages: CommitMessageSeq => lazyMessages.messages + case _ => messages.asJava + } + + def concat(children: Seq[Seq[CommitMessage]]): Seq[CommitMessage] = + new CommitMessageSeq(CommitMessageList.concat(children.map(asJava).asJava)) + + def map(messages: Seq[CommitMessage])( + mapper: CommitMessage => CommitMessage): Seq[CommitMessage] = + new CommitMessageSeq(CommitMessageList.map(asJava(messages), m => mapper(m))) +} diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/write/DataEvolutionTableDataWrite.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/write/DataEvolutionTableDataWrite.scala index bd0043e6c601..2f3f53eb54c5 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/write/DataEvolutionTableDataWrite.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/write/DataEvolutionTableDataWrite.scala @@ -27,7 +27,7 @@ import org.apache.paimon.io.{CompactIncrement, DataIncrement} import org.apache.paimon.operation.AbstractFileStoreWrite import org.apache.paimon.spark.SparkUtils import org.apache.paimon.spark.util.SparkRowUtils -import org.apache.paimon.table.sink.{BatchWriteBuilder, CommitMessage, CommitMessageImpl, TableWriteImpl} +import org.apache.paimon.table.sink.{BatchWriteBuilder, CommitMessage, CommitMessageImpl, CommitMessageSerializer, TableWriteImpl} import org.apache.paimon.types.{DataTypeRoot, RowType} import org.apache.paimon.types.VectorType.isVectorStoreFile import org.apache.paimon.utils.RecordWriter @@ -56,6 +56,12 @@ case class DataEvolutionTableDataWrite( private val rowIdIndex = writeType.getFieldCount private val firstRowIdIndex = rowIdIndex + 1 private val commitMessages = ListBuffer[CommitMessageImpl]() + private var streamingWrite = false + private var pendingMessage: CommitMessageImpl = _ + private var bytesWritten = 0L + private var recordsWritten = 0L + private var streamingInputClosed = false + private var streamingResourcesClosed = false private val toPaimonRow = { SparkRowUtils.toPaimonRow(writeType, -1, uriReaderFactory) @@ -105,6 +111,7 @@ case class DataEvolutionTableDataWrite( } def write(row: Row): Unit = { + if (streamingInputClosed) throw new IllegalStateException("Partial writer is closed.") val firstRowId = row.getLong(firstRowIdIndex) val rowId = row.getLong(rowIdIndex) @@ -161,7 +168,18 @@ case class DataEvolutionTableDataWrite( private def finishCurrentWriter(): Unit = { if (currentWriter != null) { - commitMessages ++= currentWriter.finish() + val message = currentWriter.finish() + if (streamingWrite) { + if (pendingMessage != null) { + throw new IllegalStateException("The previous file message has not been consumed.") + } + pendingMessage = message + message.newFilesIncrement().newFiles().asScala.foreach { + file => + bytesWritten += file.fileSize() + recordsWritten += file.rowCount() + } + } else commitMessages += message } currentWriter = null } @@ -172,12 +190,92 @@ case class DataEvolutionTableDataWrite( } override def commitImpl(): Seq[CommitMessage] = { + if (streamingWrite) { + throw new IllegalStateException( + "Streaming partial writes must consume their result iterator.") + } finishCurrentWriter() commitMessages.toSeq } + /** Consumes contiguous row-ID ranges only as Spark requests each file's commit message. */ + private[spark] def writeAndCommitRows(rows: Iterator[Row]): Iterator[Array[Byte]] = { + if (streamingWrite || currentWriter != null || commitMessages.nonEmpty) { + throw new IllegalStateException("Streaming partial writes must start before writing rows.") + } + streamingWrite = true + val serializer = new CommitMessageSerializer() + new Iterator[Array[Byte]] { + private var inputFinished = false + + override def hasNext: Boolean = { + if (streamingInputClosed) return false + try { + while (pendingMessage == null && !inputFinished) { + if (rows.hasNext) { + // Write the boundary row before advancing a possibly reusable input Row. + write(rows.next()) + } else { + inputFinished = true + preCommit() + finishCurrentWriter() + reportOutputMetrics(bytesWritten, recordsWritten) + } + } + if (pendingMessage == null) DataEvolutionTableDataWrite.this.close() + pendingMessage != null + } catch { + case failure: Throwable => + closeAfterFailure(failure) + throw failure + } + } + + override def next(): Array[Byte] = { + if (!hasNext) throw new NoSuchElementException() + val message = pendingMessage + pendingMessage = null + try serializer.serialize(message) + catch { + case failure: Throwable => + closeAfterFailure(failure) + throw failure + } + } + } + } + + private def closeAfterFailure(failure: Throwable): Unit = { + try close() + catch { + case cleanupFailure: Throwable => + if (cleanupFailure ne failure) failure.addSuppressed(cleanupFailure) + } + } + override def close(): Unit = { - ioManager.close() + if (!streamingWrite) { + ioManager.close() + return + } + streamingInputClosed = true + pendingMessage = null + if (streamingResourcesClosed) return + var failure: Throwable = null + def attempt(action: => Unit): Unit = { + try action + catch { + case error: Throwable => + if (failure == null) failure = error + else if (error ne failure) failure.addSuppressed(error) + } + } + // Cleanup must never finish a writer or produce new commit messages. + if (currentWriter != null) attempt(currentWriter.closeRecordWriter()) + attempt(ioManager.close()) + if (failure != null) throw failure + currentWriter = null + streamingResourcesClosed = true } private case class PerFileWriter( @@ -189,6 +287,14 @@ case class DataEvolutionTableDataWrite( private var numWritten = 0L private var fillerRows = 0L private var fillerRow: InternalRow = _ + private var writerClosed = false + + def closeRecordWriter(): Unit = { + if (!writerClosed) { + recordWriter.close() + writerClosed = true + } + } def matchFirstRowId(firstRowId: Long): Boolean = { this.firstRowId == firstRowId @@ -210,7 +316,7 @@ case class DataEvolutionTableDataWrite( recordWriter.write(row) } - def finish(): Seq[CommitMessageImpl] = { + def finish(): CommitMessageImpl = { try { fillGapUntil(firstRowId + numRecords) @@ -226,19 +332,14 @@ case class DataEvolutionTableDataWrite( val result = recordWriter.prepareCommit(false) val dataFiles = result.newFilesIncrement().newFiles() val dataFileMetas = assignFirstRowIds(dataFiles.asScala.toSeq) - Seq( - new CommitMessageImpl( - partition, - 0, - null, - new DataIncrement( - dataFileMetas.asJava, - Collections.emptyList(), - Collections.emptyList()), - CompactIncrement.emptyIncrement() - )) + new CommitMessageImpl( + partition, + 0, + null, + new DataIncrement(dataFileMetas.asJava, Collections.emptyList(), Collections.emptyList()), + CompactIncrement.emptyIncrement()) } finally { - recordWriter.close() + closeRecordWriter() } } diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/write/DataWrite.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/write/DataWrite.scala index 603ec7ecff1c..460c96e5a77e 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/write/DataWrite.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/write/DataWrite.scala @@ -70,6 +70,10 @@ trait DataWrite[T] extends AutoCloseable { // todo: support format table. case _ => } + reportOutputMetrics(bytesWritten, recordsWritten) + } + + protected def reportOutputMetrics(bytesWritten: Long, recordsWritten: Long): Unit = { val taskContext = TaskContext.get if (taskContext != null) { PaimonUtils.updateOutputMetrics( diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeMetadataTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeMetadataTest.scala new file mode 100644 index 000000000000..e9edfe286b4f --- /dev/null +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeMetadataTest.scala @@ -0,0 +1,236 @@ +/* + * 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.paimon.spark.commands + +import org.apache.paimon.data.{BinaryRow, Timestamp} +import org.apache.paimon.disk.IOManagerImpl +import org.apache.paimon.io.DataFileMeta +import org.apache.paimon.manifest.FileSource +import org.apache.paimon.stats.SimpleStats +import org.apache.paimon.table.source.{DataSplit, SplitSerializer} +import org.apache.paimon.utils.InstantiationUtil + +import org.scalatest.funsuite.AnyFunSuite + +import java.io.IOException +import java.lang.reflect.{InvocationHandler, Method, Proxy} +import java.nio.file.{Files, Path} +import java.util.{AbstractList, Collections, Iterator => JIterator, List => JList} + +import scala.collection.JavaConverters._ + +class DataEvolutionMergeMetadataTest extends AnyFunSuite { + + test("range summaries preserve equal starts, gaps and sorted duplicate blob IDs") { + val files = Seq( + file("late.parquet", 20L, 2), + file("base.parquet", 0L, 10), + file("partial.parquet", 0L, 12), + file("null.parquet", null, 2), + file("ignored.vector.bin", 100L, 50), + file("a.blob", 7L, 1), + file("b.blob", 3L, 1), + file("c.blob", 7L, 1), + file("d.blob", 23L, 1) + ) + val summary = DataEvolutionMergeMetadata.summarize(Seq(split(files.asJava))) + assert(summary.firstRowIds == Vector(0L, 20L)) + assert(summary.rowIdRangeEnds == Vector(12L, 22L)) + assert(summary.firstRowIdToBlobFirstRowIds == Map(0L -> List(3L, 7L, 7L), 20L -> List(23L))) + val restored = InstantiationUtil.deserializeObject[scala.collection.immutable.IndexedSeq[Long]]( + InstantiationUtil.serializeObject(summary.firstRowIds), + getClass.getClassLoader) + assert(restored == summary.firstRowIds) + } + + test("summary consumes each normal file before requesting the next metadata object") { + var consumed = true + val files = new AbstractList[DataFileMeta] { + override def size(): Int = 4 + override def get(index: Int): DataFileMeta = throw new UnsupportedOperationException() + override def iterator(): JIterator[DataFileMeta] = new JIterator[DataFileMeta] { + private var index = 0 + override def hasNext: Boolean = index < size() + override def next(): DataFileMeta = { + assert(consumed, "Fetched another metadata object before consuming the current one") + consumed = false + val value = file(s"$index.parquet", index * 2L, 2) + index += 1 + Proxy + .newProxyInstance( + getClass.getClassLoader, + Array(classOf[DataFileMeta]), + new InvocationHandler { + override def invoke(proxy: Any, method: Method, args: Array[AnyRef]): AnyRef = { + if (method.getName == "rowCount") consumed = true + method.invoke(value, Option(args).getOrElse(Array.empty[AnyRef]): _*) + } + } + ) + .asInstanceOf[DataFileMeta] + } + } + } + val source = new DataSplit { override def dataFiles(): JList[DataFileMeta] = files } + val summary = DataEvolutionMergeMetadata.summarize(Seq(source)) + assert(consumed) + assert(summary.firstRowIds == Vector(0L, 2L, 4L, 6L)) + assert(summary.rowIdRangeEnds == Vector(2L, 4L, 6L, 8L)) + } + + test("range summaries serialize primitive arrays without a boxed per-range object graph") { + val count = 20000 + val files = (0 until count).map(i => file(s"$i.parquet", i * 2L, 2)) + val summary = DataEvolutionMergeMetadata.summarize(Seq(split(files.asJava))) + assert(summary.firstRowIds.size == count && summary.rowIdRangeEnds.size == count) + val bytes = InstantiationUtil.serializeObject((summary.firstRowIds, summary.rowIdRangeEnds)) + assert(bytes.length < count * 17, s"Unexpected serialized range summary: ${bytes.length}") + } + + test("preparation owner retains original and pruned stores until all consumers finish") { + withOwner(1024 * 1024) { + (owner, io, directory) => + val input = owner.newStore() + (0 until 4).foreach(i => input.append(file(s"$i.parquet", i * 2L, 2))) + input.seal() + val source = split(input.slice(0, 4)) + val selected = owner.prune(Seq(source), value => value.firstRowId().longValue() >= 4L) + assert(selected.size == 1) + assert( + selected.head.dataFiles().asScala.map(_.fileName()).toVector == + Vector("2.parquet", "3.parquet")) + assert(selected.head.dataFiles().getClass.getName.contains("DataFileMetaStore$Slice")) + assert(!io.closed) + val transported = SplitSerializer.serialize(selected.head) + owner.close() + assert(io.closed) + intercept[IllegalStateException](source.dataFiles().get(0)) + intercept[IllegalStateException](selected.head.dataFiles().get(0)) + assert( + SplitSerializer + .deserialize(transported) + .asInstanceOf[DataSplit] + .dataFiles() + .asScala + .map(_.fileName()) + .toVector == Vector("2.parquet", "3.parquet")) + assertEmpty(directory) + } + } + + test("preparation owner cleans a disk failure and rejects new stores after closing") { + withOwner(8) { + (owner, io, directory) => + val output = owner.newStore() + intercept[IOException](output.append(file("large.parquet", 0L, 2))) + owner.close() + assert(io.closed) + intercept[IllegalStateException](owner.newStore()) + assertEmpty(directory) + } + } + + test("failed IO cleanup still closes stores and can be retried") { + val directory = Files.createTempDirectory("paimon-merge-owner-error-") + val stopped = new IOException("IO close failed") + val io = new ObservedIO(directory) { + private var failed = false + override def close(): Unit = { + super.close() + if (!failed) { + failed = true + throw stopped + } + } + } + val owner = new DataEvolutionMergeMetadata(io, 1024 * 1024) + try { + owner.newStore().append(file("owned.parquet", 0L, 2)) + assert(intercept[IOException](owner.close()) eq stopped) + assert(io.closeCalls == 1) + assertEmpty(directory) + owner.close() + assert(io.closeCalls == 2) + intercept[IllegalStateException](owner.newStore()) + } finally { + owner.close() + Files.delete(directory) + } + } + + private def withOwner(limit: Long)( + action: (DataEvolutionMergeMetadata, ObservedIO, Path) => Unit): Unit = { + val directory = Files.createTempDirectory("paimon-merge-owner-") + val io = new ObservedIO(directory) + val owner = new DataEvolutionMergeMetadata(io, limit) + try action(owner, io, directory) + finally { + owner.close() + assertEmpty(directory) + Files.delete(directory) + } + } + + private def assertEmpty(directory: Path): Unit = { + val files = Files.list(directory) + try assert(files.count() == 0L) + finally files.close() + } + + private class ObservedIO(directory: Path) extends IOManagerImpl(directory.toString) { + var closed = false + var closeCalls = 0 + override def close(): Unit = { closeCalls += 1; closed = true; super.close() } + } + + private def file(name: String, first: java.lang.Long, count: Long): DataFileMeta = + DataFileMeta.create( + name, + 100L, + count, + DataFileMeta.EMPTY_MIN_KEY, + DataFileMeta.EMPTY_MAX_KEY, + SimpleStats.EMPTY_STATS, + SimpleStats.EMPTY_STATS, + 1L, + 1L, + 0L, + 0, + Collections.emptyList[String](), + Timestamp.fromEpochMillis(12345), + 0L, + null, + FileSource.APPEND, + null, + null, + first, + null, + null + ) + + private def split(files: JList[DataFileMeta]): DataSplit = DataSplit + .builder() + .withSnapshot(17) + .withPartition(BinaryRow.EMPTY_ROW) + .withBucket(0) + .withBucketPath("/unused/bucket-0") + .withDataFiles(files) + .rawConvertible(false) + .build() +} diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMetadataMemoryOptionTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMetadataMemoryOptionTest.scala new file mode 100644 index 000000000000..c5e4dcaed075 --- /dev/null +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMetadataMemoryOptionTest.scala @@ -0,0 +1,122 @@ +/* + * 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.paimon.spark.commands + +import org.apache.paimon.Snapshot.Operation +import org.apache.paimon.spark.PaimonSparkTestBase +import org.apache.paimon.table.sink.CommitMessageImpl +import org.apache.paimon.table.source.DataSplit + +import org.apache.spark.sql.Row +import org.apache.spark.sql.execution.QueryExecution +import org.apache.spark.sql.paimon.Utils +import org.apache.spark.sql.types.{ArrayType, BinaryType, DataType} +import org.apache.spark.sql.util.QueryExecutionListener + +import java.util.concurrent.ConcurrentLinkedQueue + +import scala.collection.JavaConverters._ + +class DataEvolutionMetadataMemoryOptionTest extends PaimonSparkTestBase { + + Seq(None, Some("off"), Some("lightweight"), Some("streaming")).foreach { + mode => + val label = mode.getOrElse("default") + test(s"metadata memory option $label preserves partial writes and result encoding") { + withTable("t") { + val option = mode + .map(value => s", 'data-evolution.metadata-memory-optimization.mode'='$value'") + .getOrElse("") + sql(s""" + |CREATE TABLE t (id INT, b INT) TBLPROPERTIES ( + | 'bucket'='-1', 'row-tracking.enabled'='true', + | 'data-evolution.enabled'='true', 'write-only'='true'$option) + |""".stripMargin) + sql( + "INSERT INTO t SELECT /*+ COALESCE(1) */ * FROM VALUES (1, 10), " + + "(2, CAST(NULL AS INT)) AS v(id, b)") + sql("INSERT INTO t SELECT /*+ COALESCE(1) */ * FROM VALUES (3, 30), (4, 40) AS v(id, b)") + val table = loadTable("t") + val snapshot = table.latestSnapshot().get().id() + val splits = table + .newSnapshotReader() + .read() + .splits() + .asScala + .collect { case split: DataSplit => split } + .toSeq + val data = sql( + "SELECT b + 1 AS b, _ROW_ID, " + + "CAST(2 * FLOOR(_ROW_ID / 2) AS BIGINT) AS _FIRST_ROW_ID FROM t") + .coalesce(1) + .sortWithinPartitions("_FIRST_ROW_ID", "_ROW_ID") + val empty = + spark.createDataFrame(spark.sparkContext.parallelize(Seq.empty[Row], 2), data.schema) + val encodings = new ConcurrentLinkedQueue[DataType]() + val listener = new QueryExecutionListener { + override def onSuccess(name: String, qe: QueryExecution, nanos: Long): Unit = { + if (qe.executedPlan.toString.contains("DataEvolutionPaimonWriter")) { + assert(qe.analyzed.output.size == 1) + encodings.add(qe.analyzed.output.head.dataType) + } + } + override def onFailure(name: String, qe: QueryExecution, error: Exception): Unit = {} + } + spark.listenerManager.register(listener) + try { + val writer = DataEvolutionPaimonWriter(table, splits) + assert(writer.writePartialFields(empty, Seq("b")).isEmpty) + val messages = writer.writePartialFields(data, Seq("b")) + Utils.waitUntilEventEmpty(spark) + val actual = encodings.asScala.toSeq + assert(actual.size == 2, s"Expected both real writer calls, observed: $actual") + if (mode.exists(_ != "off")) { + assert(actual.forall(_ == BinaryType), actual) + } else { + assert( + actual.forall { + case ArrayType(BinaryType, _) => true + case _ => false + }, + actual) + } + assert(messages.size == 2) + val ranges = messages.flatMap { + message => + message + .asInstanceOf[CommitMessageImpl] + .newFilesIncrement() + .newFiles() + .asScala + .map(file => (file.nonNullFirstRowId(), file.rowCount())) + } + assert(ranges == Seq((0L, 2L), (2L, 2L))) + assert(table.latestSnapshot().get().id() == snapshot) + PaimonSparkWriter(table).commit(messages, Operation.UPDATE) + assert(table.latestSnapshot().get().id() == snapshot + 1) + checkAnswer( + sql("SELECT id, b, _ROW_ID FROM t"), + Seq(Row(1, 11, 0L), Row(2, null, 1L), Row(3, 31, 2L), Row(4, 41, 3L))) + } finally { + spark.listenerManager.unregister(listener) + } + } + } + } +} diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMetadataScanCompatibilityTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMetadataScanCompatibilityTest.scala new file mode 100644 index 000000000000..5ad08b9e6924 --- /dev/null +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMetadataScanCompatibilityTest.scala @@ -0,0 +1,99 @@ +/* + * 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.paimon.spark.commands + +import org.apache.paimon.spark.PaimonSparkTestBase + +import org.apache.spark.sql.Row + +class DataEvolutionMetadataScanCompatibilityTest extends PaimonSparkTestBase { + + private val modeOption = "data-evolution.metadata-memory-optimization.mode" + private val options = + "'bucket'='-1','row-tracking.enabled'='true'," + + "'data-evolution.enabled'='true','write-only'='true'" + + Seq(2, 3).foreach { + pages => + test(s"streaming metadata mode preserves SELECT with $pages sort-buffer pages") { + withTable("t") { + sql(s"""CREATE TABLE t (id INT, value INT) TBLPROPERTIES ( + |$options,'page-size'='64 kb','sort-spill-buffer-size'='${pages * 64} kb') + |""".stripMargin) + sql("INSERT INTO t VALUES (1,10),(2,20)") + checkAnswer(sql("SELECT * FROM t"), Seq(Row(1, 10), Row(2, 20))) + sql(s"ALTER TABLE t SET TBLPROPERTIES ('$modeOption'='streaming')") + checkAnswer(sql("SELECT * FROM t"), Seq(Row(1, 10), Row(2, 20))) + checkAnswer(sql("SELECT * FROM t WHERE id=2 LIMIT 1"), Seq(Row(2, 20))) + } + } + } + + test("streaming metadata mode preserves fallback rows and current partition precedence") { + withTable("t") { + sql(s"""CREATE TABLE t (id INT, value INT, p INT) PARTITIONED BY (p) + |TBLPROPERTIES ($options)""".stripMargin) + sql("INSERT INTO t VALUES (1,10,1)") + sql("CALL sys.create_branch('test.t','backup')") + sql("INSERT INTO `t$branch_backup` VALUES (2,20,2)") + sql("ALTER TABLE t SET TBLPROPERTIES ('scan.fallback-branch'='backup')") + val original = sql("SELECT *,_ROW_ID FROM t").collect().toSeq + checkAnswer(sql("SELECT id,value,p FROM t"), Seq(Row(1, 10, 1), Row(2, 20, 2))) + sql(s"ALTER TABLE t SET TBLPROPERTIES ('$modeOption'='streaming')") + checkAnswer(sql("SELECT *,_ROW_ID FROM t"), original) + checkAnswer(sql("SELECT id,value,p FROM t WHERE p=2"), Seq(Row(2, 20, 2))) + checkAnswer(sql("SELECT *,_ROW_ID FROM t"), original) + } + } + + test("streaming metadata mode preserves nonempty audit-log reads") { + withTable("t") { + sql(s"CREATE TABLE t (id INT, value INT) TBLPROPERTIES ($options)") + sql("INSERT INTO t VALUES (1,10)") + val original = sql("SELECT * FROM `t$audit_log`").collect().toSeq + assert(original.nonEmpty) + sql(s"ALTER TABLE t SET TBLPROPERTIES ('$modeOption'='streaming')") + checkAnswer(sql("SELECT * FROM `t$audit_log`"), original) + } + } + + Seq("delta", "auto", "latest-delta").foreach { + scanMode => + test(s"streaming metadata mode preserves nonempty $scanMode reads") { + withTable("t") { + sql(s"CREATE TABLE t (id INT, value INT) TBLPROPERTIES ($options)") + sql("INSERT INTO t VALUES (1,10)") + sql("INSERT INTO t VALUES (2,20)") + def read(mode: String) = { + val reader = spark.read.option(modeOption, mode) + if (scanMode == "latest-delta") reader.option("scan.mode", "latest-delta") + else { + reader.option("incremental-between", "1,2") + reader.option("incremental-between-scan-mode", scanMode) + } + reader.table("t") + } + checkAnswer(read("off"), Seq(Row(2, 20))) + checkAnswer(read("streaming"), Seq(Row(2, 20))) + checkAnswer(sql("SELECT * FROM t"), Seq(Row(1, 10), Row(2, 20))) + assert(loadTable("t").snapshotManager().latestSnapshot().id() == 2L) + } + } + } +} diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMetadataStreamingScanTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMetadataStreamingScanTest.scala new file mode 100644 index 000000000000..7d7b14b9d233 --- /dev/null +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMetadataStreamingScanTest.scala @@ -0,0 +1,130 @@ +/* + * 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.paimon.spark.commands + +import org.apache.paimon.spark.{PaimonScan, PaimonSparkTestBase} +import org.apache.paimon.table.source.DataSplit + +import org.apache.spark.sql.Row +import org.apache.spark.sql.execution.datasources.v2.DataSourceV2ScanRelation + +class DataEvolutionMetadataStreamingScanTest extends PaimonSparkTestBase { + + Seq("off", "lightweight", "streaming").foreach { + mode => + test(s"metadata mode $mode preserves partial columns and repeatable SELECT and LIMIT") { + withTable("t") { + sql(s""" + |CREATE TABLE t (id INT, a INT, b INT) TBLPROPERTIES ( + | 'bucket'='-1', 'row-tracking.enabled'='true', + | 'data-evolution.enabled'='true', 'write-only'='true', + | 'data-evolution.metadata-memory-optimization.mode'='$mode') + |""".stripMargin) + sql( + "INSERT INTO t SELECT /*+ COALESCE(1) */ * FROM VALUES " + + "(1, 10, 100), (2, 20, CAST(NULL AS INT)), (3, 30, 300) AS v(id, a, b)") + sql("INSERT INTO t VALUES (4, 40, 400)") + sql( + "MERGE INTO t USING (SELECT 1 AS id, 111 AS b) s ON t.id = s.id " + + "WHEN MATCHED THEN UPDATE SET b = s.b") + val query = spark.sql("SELECT id, a, b, _ROW_ID FROM t") + val scan = query.queryExecution.optimizedPlan.collectFirst { + case relation: DataSourceV2ScanRelation => relation.scan.asInstanceOf[PaimonScan] + }.get + val splits = scan.inputSplits.collect { case split: DataSplit => split } + assert(splits.nonEmpty) + assert(splits.forall { + split => + split.dataFiles().getClass.getName.contains("DataFileMetaStore$Slice") == + (mode == "streaming") + }) + val expected = + Seq(Row(1, 10, 111, 0L), Row(2, 20, null, 1L), Row(3, 30, 300, 2L), Row(4, 40, 400, 3L)) + checkAnswer(query, expected) + checkAnswer(query, expected) + query.cache() + try { + checkAnswer(query, expected) + checkAnswer(query, expected) + } finally { + query.unpersist(blocking = true) + } + checkAnswer(query, expected) + checkAnswer(sql("SELECT id FROM t WHERE b IS NULL"), Seq(Row(2))) + checkAnswer( + sql("SELECT id, b FROM t ORDER BY id LIMIT 2"), + Seq(Row(1, 111), Row(2, null))) + val limited = sql("SELECT id, a, b, _ROW_ID FROM t LIMIT 2").collect().toSeq + assert(limited.size == 2 && limited.distinct.size == 2) + assert(limited.forall(expected.contains)) + } + } + } + + test("streaming scan handles an empty table without requiring a sealed snapshot store") { + withTable("t") { + sql(""" + |CREATE TABLE t (id INT, b INT) TBLPROPERTIES ( + | 'bucket'='-1', 'row-tracking.enabled'='true', + | 'data-evolution.enabled'='true', 'write-only'='true', + | 'data-evolution.metadata-memory-optimization.mode'='streaming') + |""".stripMargin) + checkAnswer(sql("SELECT * FROM t"), Seq.empty[Row]) + checkAnswer(sql("SELECT * FROM t LIMIT 2"), Seq.empty[Row]) + } + } + + test("streaming scan preserves partition filtering and the full scan guard") { + withTable("t") { + sql(""" + |CREATE TABLE t (id INT, b INT, p INT) PARTITIONED BY (p) TBLPROPERTIES ( + | 'bucket'='-1', 'row-tracking.enabled'='true', + | 'data-evolution.enabled'='true', 'write-only'='true', + | 'data-evolution.metadata-memory-optimization.mode'='streaming') + |""".stripMargin) + sql("INSERT INTO t VALUES (1, 10, 1), (2, 20, 2)") + withSparkSQLConf("spark.paimon.read.allow.fullScan" -> "false") { + assert( + intercept[Exception](sql("SELECT * FROM t").collect()).getMessage + .contains("Full scan is not supported.")) + checkAnswer(sql("SELECT * FROM t WHERE p = 2"), Seq(Row(2, 20, 2))) + } + } + } + + test("streaming scan propagates its replay disk limit instead of materializing") { + withTable("t") { + sql(""" + |CREATE TABLE t (id INT, b INT) TBLPROPERTIES ( + | 'bucket'='-1', 'row-tracking.enabled'='true', + | 'data-evolution.enabled'='true', 'write-only'='true', + | 'data-evolution.metadata-memory-optimization.mode'='streaming', + | 'data-evolution.metadata-memory-optimization.max-disk-size'='8 b') + |""".stripMargin) + sql("INSERT INTO t VALUES (1, 10)") + val failure = intercept[Exception](sql("SELECT id FROM t").collect()) + val causes = Iterator.iterate[Throwable](failure)(_.getCause).takeWhile(_ != null) + assert( + causes.exists( + error => + Option(error.getMessage) + .exists(_.contains("Metadata store disk limit exceeded")))) + } + } +} diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionPaimonWriterTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionPaimonWriterTest.scala new file mode 100644 index 000000000000..ba556363d354 --- /dev/null +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionPaimonWriterTest.scala @@ -0,0 +1,99 @@ +/* + * 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.paimon.spark.commands + +import org.apache.paimon.Snapshot.Operation +import org.apache.paimon.spark.PaimonSparkTestBase +import org.apache.paimon.table.sink.CommitMessageImpl +import org.apache.paimon.table.source.DataSplit + +import org.apache.spark.sql.Row + +import scala.collection.JavaConverters._ + +class DataEvolutionPaimonWriterTest extends PaimonSparkTestBase { + + test("partial writes preserve all range messages and row IDs across empty output") { + withTable("t") { + sql(""" + |CREATE TABLE t (id INT, b INT) TBLPROPERTIES ( + | 'bucket' = '-1', + | 'row-tracking.enabled' = 'true', + | 'data-evolution.enabled' = 'true', + | 'write-only' = 'true') + |""".stripMargin) + sql( + "INSERT INTO t SELECT /*+ COALESCE(1) */ * " + + "FROM VALUES (1, 10), (2, CAST(NULL AS INT)) AS v(id, b)") + sql( + "INSERT INTO t SELECT /*+ COALESCE(1) */ * " + + "FROM VALUES (3, 30), (4, 40) AS v(id, b)") + + checkAnswer( + sql("SELECT id, b, _ROW_ID FROM t"), + Seq(Row(1, 10, 0L), Row(2, null, 1L), Row(3, 30, 2L), Row(4, 40, 3L))) + val table = loadTable("t") + val snapshotId = table.latestSnapshot().get().id() + val splits = table + .newSnapshotReader() + .read() + .splits() + .asScala + .collect { case split: DataSplit => split } + .toSeq + assert( + splits + .flatMap(_.dataFiles().asScala) + .map(f => (f.nonNullFirstRowId(), f.rowCount())) + .sorted == + Seq((0L, 2L), (2L, 2L))) + + val data = sql(""" + |SELECT b + 1 AS b, _ROW_ID, + | CAST(2 * FLOOR(_ROW_ID / 2) AS BIGINT) AS _FIRST_ROW_ID + |FROM t + |""".stripMargin) + .coalesce(1) + .sortWithinPartitions("_FIRST_ROW_ID", "_ROW_ID") + val writer = DataEvolutionPaimonWriter(table, splits) + val emptyData = + spark.createDataFrame(spark.sparkContext.parallelize(Seq.empty[Row], 2), data.schema) + assert(writer.writePartialFields(emptyData, Seq("b")).isEmpty) + val messages = writer.writePartialFields(data, Seq("b")) + assert(messages.size == 2) + val ranges = messages.flatMap { + message => + message + .asInstanceOf[CommitMessageImpl] + .newFilesIncrement() + .newFiles() + .asScala + .map(f => (f.nonNullFirstRowId(), f.rowCount())) + } + assert(ranges == Seq((0L, 2L), (2L, 2L))) + assert(table.latestSnapshot().get().id() == snapshotId) + + PaimonSparkWriter(table).commit(messages, Operation.UPDATE) + assert(table.latestSnapshot().get().id() == snapshotId + 1) + checkAnswer( + sql("SELECT id, b, _ROW_ID FROM t"), + Seq(Row(1, 11, 0L), Row(2, null, 1L), Row(3, 31, 2L), Row(4, 41, 3L))) + } + } +} diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionRebaseMemoryTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionRebaseMemoryTest.scala new file mode 100644 index 000000000000..84025ae61e3d --- /dev/null +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionRebaseMemoryTest.scala @@ -0,0 +1,96 @@ +/* + * 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.paimon.spark.commands + +import org.apache.paimon.io.{CompactIncrement, DataIncrement} +import org.apache.paimon.spark.PaimonSparkTestBase +import org.apache.paimon.table.sink.{CommitMessage, CommitMessageImpl} +import org.apache.paimon.table.source.DataSplit + +import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation + +import java.util.Collections +import java.util.concurrent.atomic.AtomicBoolean + +import scala.collection.JavaConverters._ + +class DataEvolutionRebaseMemoryTest extends PaimonSparkTestBase { + + Seq("off", "lightweight").foreach { + mode => + test(s"no-op rebase consumes messages incrementally when metadata memory mode is $mode") { + withTable("t") { + sql(s""" + |CREATE TABLE t (id INT, value INT) TBLPROPERTIES ( + | 'bucket'='-1', 'row-tracking.enabled'='true', + | 'data-evolution.enabled'='true', 'write-only'='true', + | 'data-evolution.metadata-memory-optimization.mode'='$mode') + |""".stripMargin) + sql("INSERT INTO t VALUES (1, 10)") + sql("INSERT INTO t VALUES (2, 20)") + val table = loadTable("t") + val snapshot = table.latestSnapshot().get() + val relation = sql("SELECT * FROM t").queryExecution.analyzed.collectFirst { + case r: DataSourceV2Relation => r + }.get + val splits = table.newSnapshotReader().read().splits().asScala.collect { + case split: DataSplit => split + } + val files = splits.flatMap(split => split.dataFiles().asScala.map(file => (split, file))) + assert(files.size == 2) + val firstConsumed = new AtomicBoolean(false) + val messages = files.zipWithIndex.map { + case ((split, file), index) => + new CommitMessageImpl( + split.partition(), + split.bucket(), + split.totalBuckets(), + new DataIncrement( + Collections.singletonList(file), + Collections.emptyList(), + Collections.emptyList()), + CompactIncrement.emptyIncrement() + ) { + override def newFilesIncrement(): DataIncrement = { + if (index == 0) firstConsumed.set(true) + super.newFilesIncrement() + } + } + } + // A byte-backed producer can release the previous decoded message only after consumption. + // This deterministic demand check catches collect-before-processing without GC heuristics. + val source = new scala.collection.immutable.IndexedSeq[CommitMessage] { + override def length: Int = messages.size + override def apply(index: Int): CommitMessage = { + if (mode != "off" && index > 0) { + assert(firstConsumed.get(), "Decoded the next message before consuming the first") + } + messages(index) + } + } + val result = new DataEvolutionRowIdConflictRewriter(table, relation) + .rewrite(spark, snapshot, source) + assert(result.isEmpty) + assert(firstConsumed.get()) + assert(table.latestSnapshot().get().id() == snapshot.id()) + checkAnswer(sql("SELECT id, value FROM t"), sql("SELECT * FROM VALUES (1, 10), (2, 20)")) + } + } + } +} diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionStreamingMergeTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionStreamingMergeTest.scala new file mode 100644 index 000000000000..890862f1c6c6 --- /dev/null +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionStreamingMergeTest.scala @@ -0,0 +1,200 @@ +/* + * 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.paimon.spark.commands + +import org.apache.paimon.spark.PaimonSparkTestBase +import org.apache.paimon.spark.read.PaimonSplitScan +import org.apache.paimon.table.source.DataSplit + +import org.apache.spark.sql.Row +import org.apache.spark.sql.execution.QueryExecution +import org.apache.spark.sql.execution.datasources.v2.DataSourceV2ScanRelation +import org.apache.spark.sql.paimon.Utils +import org.apache.spark.sql.util.QueryExecutionListener + +import java.util.concurrent.ConcurrentLinkedQueue + +import scala.collection.JavaConverters._ + +class DataEvolutionStreamingMergeTest extends PaimonSparkTestBase { + + Seq("off", "lightweight", "streaming").foreach { + mode => + test(s"MERGE preparation $mode preserves versioned columns, partition pruning and RowIDs") { + withTable("t", "s") { + sql(s""" + |CREATE TABLE t (id INT, p INT, b INT, c INT) PARTITIONED BY (p) + |TBLPROPERTIES ('bucket'='-1', 'row-tracking.enabled'='true', + | 'data-evolution.enabled'='true', 'write-only'='true', + | 'data-evolution.metadata-memory-optimization.mode'='$mode') + |""".stripMargin) + sql("INSERT INTO t VALUES (1, 1, 10, 100)") + sql("INSERT INTO t VALUES (2, 1, 20, 200)") + sql("INSERT INTO t VALUES (3, 2, 30, 300)") + val original = sql("SELECT id, _ROW_ID FROM t ORDER BY id").collect().toSeq + sql( + "MERGE INTO t USING (SELECT 1 AS id, 11 AS b UNION ALL SELECT 3, 31) u " + + "ON t.id = u.id WHEN MATCHED THEN UPDATE SET b = u.b") + sql("CREATE TABLE s (id INT, p INT, b INT, c INT)") + sql( + "INSERT INTO s VALUES (1, 1, 111, 1111), (2, 1, 222, 2222), " + + "(3, 2, 333, 3333), (4, 1, 444, 4444)") + val before = loadTable("t").latestSnapshot().get().id() + val storedSplits = new ConcurrentLinkedQueue[Boolean]() + val listener = new QueryExecutionListener { + override def onSuccess(name: String, qe: QueryExecution, nanos: Long): Unit = { + qe.optimizedPlan.foreach { + case relation: DataSourceV2ScanRelation => + relation.scan match { + case known: PaimonSplitScan => + known.inputSplits.collect { case split: DataSplit => split }.foreach { + split => + storedSplits.add( + split + .dataFiles() + .getClass + .getName + .contains("DataFileMetaStore$Slice")) + } + case _ => + } + case _ => + } + } + override def onFailure(name: String, qe: QueryExecution, error: Exception): Unit = {} + } + spark.listenerManager.register(listener) + try { + sql(""" + |MERGE INTO t USING s + |ON t.id = s.id AND t.p = s.p AND t.p = 1 AND t.b >= 11 + |WHEN MATCHED THEN UPDATE SET b = s.b + |WHEN NOT MATCHED THEN INSERT (id, p, b, c) VALUES (s.id, s.p, s.b, s.c) + |""".stripMargin) + Utils.waitUntilEventEmpty(spark) + assert(!storedSplits.isEmpty, "Expected an actual KnownSplits consumer during MERGE") + assert(storedSplits.asScala.forall(_ == (mode == "streaming"))) + } finally { + spark.listenerManager.unregister(listener) + } + assert(loadTable("t").latestSnapshot().get().id() == before + 1) + checkAnswer( + sql("SELECT id, p, b, c FROM t"), + Seq( + Row(1, 1, 111, 100), + Row(2, 1, 222, 200), + Row(3, 2, 31, 300), + Row(3, 2, 333, 3333), + Row(4, 1, 444, 4444))) + checkAnswer(sql("SELECT id, _ROW_ID FROM t WHERE c < 1000"), original) + val inserted = sql("SELECT _ROW_ID FROM t WHERE c >= 1000").collect().map(_.getLong(0)) + assert(inserted.toSet == Set(3L, 4L) && inserted.length == 2) + checkAnswer( + sql("SELECT * FROM s"), + Seq( + Row(1, 1, 111, 1111), + Row(2, 1, 222, 2222), + Row(3, 2, 333, 3333), + Row(4, 1, 444, 4444))) + } + } + } + + test("streaming MERGE keeps NMBS independent of ON partition pruning across repeated deletes") { + withTable("t") { + withTempView("s") { + sql(""" + |CREATE TABLE t (id INT, p INT, b INT, c INT) PARTITIONED BY (p) + |TBLPROPERTIES ('bucket'='-1', 'row-tracking.enabled'='true', + | 'data-evolution.enabled'='true', 'write-only'='true', + | 'deletion-vectors.enabled'='true', + | 'data-evolution.metadata-memory-optimization.mode'='streaming') + |""".stripMargin) + sql( + "INSERT INTO t VALUES (1, 1, 10, 100), (2, 1, 20, 200), " + + "(3, 2, 30, 300), (4, 2, 40, 400)") + val original = sql("SELECT id, _ROW_ID FROM t WHERE id IN (1, 4)").collect().toSeq + sql( + "CREATE OR REPLACE TEMP VIEW s AS SELECT * FROM VALUES " + + "(1, 1, 111), (5, 1, 555) AS s(id, p, b)") + val firstSnapshot = loadTable("t").latestSnapshot().get().id() + sql(""" + |MERGE INTO t USING s ON t.id = s.id AND t.p = s.p AND t.p = 1 + |WHEN MATCHED THEN UPDATE SET b = s.b + |WHEN NOT MATCHED THEN INSERT (id, p, b, c) VALUES (s.id, s.p, s.b, s.b + 1000) + |WHEN NOT MATCHED BY SOURCE AND t.id IN (2, 3) THEN DELETE + |""".stripMargin) + assert(loadTable("t").latestSnapshot().get().id() == firstSnapshot + 1) + checkAnswer( + sql("SELECT id, p, b, c FROM t"), + Seq(Row(1, 1, 111, 100), Row(4, 2, 40, 400), Row(5, 1, 555, 1555))) + checkAnswer(sql("SELECT id, _ROW_ID FROM t WHERE id IN (1, 4)"), original) + sql( + "CREATE OR REPLACE TEMP VIEW s AS SELECT * FROM VALUES " + + "(1, 1, 112), (2, 1, 222), (6, 1, 666) AS s(id, p, b)") + val secondSnapshot = loadTable("t").latestSnapshot().get().id() + sql(""" + |MERGE INTO t USING s ON t.id = s.id AND t.p = s.p AND t.p = 1 + |WHEN MATCHED THEN UPDATE SET b = s.b + |WHEN NOT MATCHED THEN INSERT (id, p, b, c) VALUES (s.id, s.p, s.b, s.b + 1000) + |WHEN NOT MATCHED BY SOURCE AND t.id IN (4, 5) THEN DELETE + |""".stripMargin) + assert(loadTable("t").latestSnapshot().get().id() == secondSnapshot + 1) + checkAnswer( + sql("SELECT id, p, b, c FROM t"), + Seq(Row(1, 1, 112, 100), Row(2, 1, 222, 1222), Row(6, 1, 666, 1666))) + checkAnswer( + sql("SELECT id, _ROW_ID FROM t WHERE id = 1"), + original.filter(_.getInt(0) == 1)) + val fresh = sql("SELECT _ROW_ID FROM t WHERE id IN (2, 6)").collect().map(_.getLong(0)) + assert(fresh.length == 2 && fresh.distinct.length == 2 && fresh.forall(_ >= 5L)) + } + } + } + + test("streaming MERGE enforces its initial planning disk budget before publication") { + withTable("t") { + sql(""" + |CREATE TABLE t (id INT, b INT, c INT) TBLPROPERTIES ( + | 'bucket'='-1', 'row-tracking.enabled'='true', + | 'data-evolution.enabled'='true', 'write-only'='true', + | 'data-evolution.merge-into.file-pruning'='false', + | 'data-evolution.metadata-memory-optimization.mode'='streaming', + | 'data-evolution.metadata-memory-optimization.max-disk-size'='8 b') + |""".stripMargin) + sql("INSERT INTO t VALUES (1, 10, 100)") + val before = loadTable("t").latestSnapshot().get().id() + val failure = intercept[Exception] { + sql( + "MERGE INTO t USING (SELECT 1 AS id, 111 AS b) s ON t.id = s.id " + + "WHEN MATCHED THEN UPDATE SET b = s.b") + } + assert( + Iterator + .iterate[Throwable](failure)(_.getCause) + .takeWhile(_ != null) + .exists( + error => Option(error.getMessage).exists(_.contains("Metadata store disk limit")))) + assert(loadTable("t").latestSnapshot().get().id() == before) + sql( + "ALTER TABLE t SET TBLPROPERTIES ('data-evolution.metadata-memory-optimization.mode'='off')") + checkAnswer(sql("SELECT id, b, c, _ROW_ID FROM t"), Seq(Row(1, 10, 100, 0L))) + } + } +} diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionTaskCommitDemandTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionTaskCommitDemandTest.scala new file mode 100644 index 000000000000..5eced40a5a9e --- /dev/null +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionTaskCommitDemandTest.scala @@ -0,0 +1,186 @@ +/* + * 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.paimon.spark.commands + +import org.apache.paimon.Snapshot.Operation +import org.apache.paimon.spark.PaimonSparkTestBase +import org.apache.paimon.spark.write.DataEvolutionTableDataWrite +import org.apache.paimon.table.{BlobDescriptorReaderFactory, FileStoreTable} +import org.apache.paimon.table.sink.{CommitMessageImpl, CommitMessageSerializer} +import org.apache.paimon.table.source.DataSplit +import org.apache.paimon.utils.SerializationUtils + +import org.apache.spark.sql.Row +import org.apache.spark.sql.catalyst.expressions.GenericRow + +import java.io.IOException +import java.util.Collections + +import scala.collection.JavaConverters._ +import scala.collection.mutable + +class DataEvolutionTaskCommitDemandTest extends PaimonSparkTestBase { + + private def withWriter( + body: (FileStoreTable, DataEvolutionTableDataWrite, Array[Row]) => Unit): Unit = { + withTable("t") { + sql(""" + |CREATE TABLE t (id INT, b INT) TBLPROPERTIES ( + | 'bucket'='-1', 'row-tracking.enabled'='true', + | 'data-evolution.enabled'='true', 'write-only'='true') + |""".stripMargin) + sql( + "INSERT INTO t SELECT /*+ COALESCE(1) */ * FROM VALUES (1, 10), (2, CAST(NULL AS INT)) AS v(id, b)") + sql("INSERT INTO t SELECT /*+ COALESCE(1) */ * FROM VALUES (3, 30), (4, 40) AS v(id, b)") + val table = loadTable("t") + val ranges = mutable.HashMap.empty[Long, (Array[Byte], Long)] + table.newSnapshotReader().read().splits().asScala.foreach { + case split: DataSplit => + split.dataFiles().asScala.foreach { + file => + ranges.put( + file.firstRowId(), + (SerializationUtils.serializeBinaryRow(split.partition()), file.rowCount())) + } + } + assert(ranges.size == 2) + val rows = sql(""" + |SELECT b + 1 AS b, _ROW_ID, + | CAST(2 * FLOOR(_ROW_ID / 2) AS BIGINT) AS _FIRST_ROW_ID + |FROM t ORDER BY _ROW_ID + |""".stripMargin).collect() + val writer = DataEvolutionTableDataWrite( + table.newBatchWriteBuilder(), + table.rowType().project(Collections.singletonList("b")), + ranges, + BlobDescriptorReaderFactory.create(table), + Map.empty) + try body(table, writer, rows) + finally writer.close() + } + } + + private def decode(bytes: Array[Byte]): CommitMessageImpl = { + val serializer = new CommitMessageSerializer() + serializer.deserialize(serializer.getVersion, bytes).asInstanceOf[CommitMessageImpl] + } + + test("produces each file message on demand without draining or retaining reusable input rows") { + withWriter { + (table, writer, rows) => + var consumed = 0 + val values = new Array[Any](3) + val reused = new GenericRow(values) + val input = rows.iterator.map { + row => + consumed += 1 + values.indices.foreach(index => values(index) = row.get(index)) + reused + } + val snapshot = table.latestSnapshot().get().id() + val output = writer.writeAndCommitRows(input) + assert(consumed == 0) + assert(output.hasNext) + assert(consumed == 3) + assert(output.hasNext) + assert(consumed == 3) + val first = decode(output.next()) + assert(first.newFilesIncrement().newFiles().get(0).firstRowId() == 0L) + assert(consumed == 3) + val second = decode(output.next()) + assert(consumed == 4) + assert(second.newFilesIncrement().newFiles().get(0).firstRowId() == 2L) + assert(!output.hasNext) + assert(!output.hasNext) + intercept[NoSuchElementException](output.next()) + assert(table.latestSnapshot().get().id() == snapshot) + PaimonSparkWriter(table).commit(Seq(first, second), Operation.UPDATE) + assert(table.latestSnapshot().get().id() == snapshot + 1) + checkAnswer( + sql("SELECT id, b, _ROW_ID FROM t"), + Seq(Row(1, 11, 0L), Row(2, null, 1L), Row(3, 31, 2L), Row(4, 41, 3L))) + } + } + + test("accepts contiguous file ranges in either order") { + withWriter { + (table, writer, rows) => + val snapshot = table.latestSnapshot().get().id() + val output = writer.writeAndCommitRows((rows.drop(2) ++ rows.take(2)).iterator) + val starts = + output.map(decode).map(_.newFilesIncrement().newFiles().get(0).firstRowId()).toVector + assert(starts == Vector(2L, 0L)) + assert(table.latestSnapshot().get().id() == snapshot) + } + } + + test("early close stops input consumption and never publishes a partial result") { + withWriter { + (table, writer, rows) => + var consumed = 0 + val snapshot = table.latestSnapshot().get().id() + val output = writer.writeAndCommitRows(rows.iterator.map { row => consumed += 1; row }) + decode(output.next()) + assert(consumed == 3) + writer.close() + writer.close() + assert(!output.hasNext) + assert(consumed == 3) + intercept[NoSuchElementException](output.next()) + assert(table.latestSnapshot().get().id() == snapshot) + checkAnswer( + sql("SELECT id, b, _ROW_ID FROM t"), + Seq(Row(1, 10, 0L), Row(2, null, 1L), Row(3, 30, 2L), Row(4, 40, 3L))) + } + } + + test("input failure after a completed file preserves the failure and stops output") { + withWriter { + (table, writer, rows) => + var consumed = 0 + val failure = new IOException("input failed after first file") + val snapshot = table.latestSnapshot().get().id() + val output = writer.writeAndCommitRows(rows.iterator.map { + row => + consumed += 1 + if (consumed == 4) throw failure + row + }) + decode(output.next()) + assert(consumed == 3) + assert(intercept[IOException](output.hasNext) eq failure) + assert(!output.hasNext) + writer.close() + assert(table.latestSnapshot().get().id() == snapshot) + } + } + + test("empty input completes without producing a message or a snapshot") { + withWriter { + (table, writer, _) => + val snapshot = table.latestSnapshot().get().id() + val output = writer.writeAndCommitRows(Iterator.empty) + assert(!output.hasNext) + assert(!output.hasNext) + intercept[NoSuchElementException](output.next()) + writer.close() + assert(table.latestSnapshot().get().id() == snapshot) + } + } +} diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionTaskCommitStreamingTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionTaskCommitStreamingTest.scala new file mode 100644 index 000000000000..45ddf78ea6df --- /dev/null +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionTaskCommitStreamingTest.scala @@ -0,0 +1,147 @@ +/* + * 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.paimon.spark.commands + +import org.apache.paimon.Snapshot.Operation +import org.apache.paimon.spark.PaimonSparkTestBase +import org.apache.paimon.table.FileStoreTable +import org.apache.paimon.table.sink.CommitMessageImpl +import org.apache.paimon.table.source.DataSplit + +import org.apache.spark.scheduler.{SparkListener, SparkListenerTaskEnd} +import org.apache.spark.sql.{Dataset, Row} +import org.apache.spark.sql.paimon.Utils + +import java.util.concurrent.ConcurrentLinkedQueue + +import scala.collection.JavaConverters._ + +class DataEvolutionTaskCommitStreamingTest extends PaimonSparkTestBase { + + private def withFixture(body: (FileStoreTable, Seq[DataSplit], Dataset[Row]) => Unit): Unit = { + withTable("t") { + sql(""" + |CREATE TABLE t (id INT, b INT) TBLPROPERTIES ( + | 'bucket'='-1', 'row-tracking.enabled'='true', + | 'data-evolution.enabled'='true', 'write-only'='true') + |""".stripMargin) + sql( + "INSERT INTO t SELECT /*+ COALESCE(1) */ * FROM VALUES (1, 10), (2, CAST(NULL AS INT)) AS v(id, b)") + sql("INSERT INTO t SELECT /*+ COALESCE(1) */ * FROM VALUES (3, 30), (4, 40) AS v(id, b)") + val table = loadTable("t") + val splits = table + .newSnapshotReader() + .read() + .splits() + .asScala + .collect { case split: DataSplit => split } + .toSeq + assert(splits.iterator.flatMap(_.dataFiles().asScala.iterator).size == 2) + val data = + sql(""" + |SELECT b + 1 AS b, _ROW_ID, + | CAST(2 * FLOOR(_ROW_ID / 2) AS BIGINT) AS _FIRST_ROW_ID + |FROM t + |""".stripMargin).coalesce(1).sortWithinPartitions("_FIRST_ROW_ID", "_ROW_ID") + body(table, splits, data) + } + } + + test("streaming Task needs no commit replay file after ordinary input planning") { + withFixture { + (table, splits, data) => + val snapshot = table.latestSnapshot().get().id() + val streaming = table.copy( + Map( + "data-evolution.metadata-memory-optimization.mode" -> "streaming", + "data-evolution.metadata-memory-optimization.max-disk-size" -> "8 b").asJava) + val writer = DataEvolutionPaimonWriter(streaming, splits) + val empty = + spark.createDataFrame(spark.sparkContext.parallelize(Seq.empty[Row], 2), data.schema) + assert(writer.writePartialFields(empty, Seq("b")).isEmpty) + assert(writer.writePartialFields(data, Seq("b")).size == 2) + Utils.waitUntilEventEmpty(spark) + assert(table.latestSnapshot().get().id() == snapshot) + checkAnswer( + sql("SELECT id, b, _ROW_ID FROM t"), + Seq(Row(1, 10, 0L), Row(2, null, 1L), Row(3, 30, 2L), Row(4, 40, 3L))) + } + } + + test("streaming Task returns original commit messages before atomic publication") { + withFixture { + (table, splits, data) => + val snapshot = table.latestSnapshot().get().id() + val streaming = + table.copy(Map("data-evolution.metadata-memory-optimization.mode" -> "streaming").asJava) + val messages = + DataEvolutionPaimonWriter(streaming, splits).writePartialFields(data, Seq("b")) + assert(messages.size == 2) + Utils.waitUntilEventEmpty(spark) + assert(table.latestSnapshot().get().id() == snapshot) + PaimonSparkWriter(streaming).commit(messages, Operation.UPDATE) + assert(table.latestSnapshot().get().id() == snapshot + 1) + checkAnswer( + sql("SELECT id, b, _ROW_ID FROM t"), + Seq(Row(1, 11, 0L), Row(2, null, 1L), Row(3, 31, 2L), Row(4, 41, 3L))) + } + } + + test("streaming Task preserves output metrics including filler rows") { + withFixture { + (table, splits, data) => + val snapshot = table.latestSnapshot().get().id() + val streaming = + table.copy(Map("data-evolution.metadata-memory-optimization.mode" -> "streaming").asJava) + val outputs = new ConcurrentLinkedQueue[(Long, Long)]() + val listener = new SparkListener { + override def onTaskEnd(event: SparkListenerTaskEnd): Unit = { + if (event.taskMetrics != null) { + val metrics = event.taskMetrics.outputMetrics + if (metrics.recordsWritten > 0) { + outputs.add((metrics.recordsWritten, metrics.bytesWritten)) + } + } + } + } + Utils.waitUntilEventEmpty(spark) + spark.sparkContext.addSparkListener(listener) + try { + val messages = DataEvolutionPaimonWriter(streaming, splits) + .writePartialFields(data.filter("_ROW_ID % 2 = 0"), Seq("b")) + val files = messages.iterator.flatMap { + message => + message + .asInstanceOf[CommitMessageImpl] + .newFilesIncrement() + .newFiles() + .asScala + .iterator + }.toVector + val rows = files.map(_.rowCount()).sum + val bytes = files.map(_.fileSize()).sum + assert(rows == 4L) + Utils.waitUntilEventEmpty(spark) + assert(outputs.asScala.toVector == Vector((rows, bytes))) + assert(table.latestSnapshot().get().id() == snapshot) + } finally spark.sparkContext.removeSparkListener(listener) + } + } + +} diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/DataEvolutionDeletionTestBase.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/DataEvolutionDeletionTestBase.scala index f850fe664a07..dacbfdafa99e 100644 --- a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/DataEvolutionDeletionTestBase.scala +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/DataEvolutionDeletionTestBase.scala @@ -296,49 +296,57 @@ abstract class DataEvolutionDeletionTestBase extends PaimonSparkTestBase { } } - test("Data Evolution deletion: merge matched update and delete keeps first-match semantics") { - withTable("s", "t") { - sql("CREATE TABLE s (id INT, new_b INT, op STRING)") - sql(""" - |INSERT INTO s VALUES - | (1, 100, 'update'), - | (2, 200, 'delete'), - | (6, 600, 'update'), - | (11, 1100, 'delete') - |""".stripMargin) - - sql(""" - |CREATE TABLE t (id INT, b INT, c INT) - |TBLPROPERTIES ( - | 'row-tracking.enabled' = 'true', - | 'data-evolution.enabled' = 'true', - | 'deletion-vectors.enabled' = 'true') - |""".stripMargin) - sql("INSERT INTO t SELECT /*+ REPARTITION(1) */ id, id AS b, id AS c FROM range(0, 5)") - sql("INSERT INTO t SELECT /*+ REPARTITION(1) */ id, id AS b, id AS c FROM range(5, 10)") - - sql(""" - |MERGE INTO t - |USING s - |ON t.id = s.id - |WHEN MATCHED AND s.op = 'delete' THEN DELETE - |WHEN MATCHED AND s.id IN (1, 2, 6) THEN UPDATE SET t.b = s.new_b - |""".stripMargin) - - checkAnswer( - sql("SELECT id, b, c, _ROW_ID FROM t ORDER BY id"), - Seq( - Row(0, 0, 0, 0L), - Row(1, 100, 1, 1L), - Row(3, 3, 3, 3L), - Row(4, 4, 4, 4L), - Row(5, 5, 5, 5L), - Row(6, 600, 6, 6L), - Row(7, 7, 7, 7L), - Row(8, 8, 8, 8L), - Row(9, 9, 9, 9L)) - ) - } + Seq("off", "lightweight").foreach { + metadataMemoryMode => + test( + s"Data Evolution deletion: merge matched update and delete keeps first-match semantics (metadata memory: $metadataMemoryMode)") { + withTable("s", "t") { + sql("CREATE TABLE s (id INT, new_b INT, op STRING)") + sql(""" + |INSERT INTO s VALUES + | (1, 100, 'update'), + | (2, 200, 'delete'), + | (6, 600, 'update'), + | (11, 1100, 'delete') + |""".stripMargin) + + sql(s""" + |CREATE TABLE t (id INT, b INT, c INT) + |TBLPROPERTIES ( + | 'row-tracking.enabled' = 'true', + | 'data-evolution.metadata-memory-optimization.mode' = '$metadataMemoryMode', + | 'data-evolution.enabled' = 'true', + | 'deletion-vectors.enabled' = 'true') + |""".stripMargin) + assert( + loadTable("t").coreOptions().dataEvolutionMetadataMemoryOptimizationEnabled() == + (metadataMemoryMode != "off")) + sql("INSERT INTO t SELECT /*+ REPARTITION(1) */ id, id AS b, id AS c FROM range(0, 5)") + sql("INSERT INTO t SELECT /*+ REPARTITION(1) */ id, id AS b, id AS c FROM range(5, 10)") + + sql(""" + |MERGE INTO t + |USING s + |ON t.id = s.id + |WHEN MATCHED AND s.op = 'delete' THEN DELETE + |WHEN MATCHED AND s.id IN (1, 2, 6) THEN UPDATE SET t.b = s.new_b + |""".stripMargin) + + checkAnswer( + sql("SELECT id, b, c, _ROW_ID FROM t ORDER BY id"), + Seq( + Row(0, 0, 0, 0L), + Row(1, 100, 1, 1L), + Row(3, 3, 3, 3L), + Row(4, 4, 4, 4L), + Row(5, 5, 5, 5L), + Row(6, 600, 6, 6L), + Row(7, 7, 7, 7L), + Row(8, 8, 8, 8L), + Row(9, 9, 9, 9L)) + ) + } + } } test("Data Evolution deletion: merge not matched by source delete") { diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/RowTrackingTestBase.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/RowTrackingTestBase.scala index 395b145095c9..e81c7867129b 100644 --- a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/RowTrackingTestBase.scala +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/RowTrackingTestBase.scala @@ -52,6 +52,61 @@ abstract class RowTrackingTestBase extends PaimonSparkTestBase with AdaptiveSpar private val MaxRetryAttempts = 20 private val RetryIntervalMillis = 10L + Seq("off", "lightweight").foreach { + metadataMemoryMode => + test( + s"Data Evolution: merge prunes versioned column groups before dropping preparation stats (metadata memory: $metadataMemoryMode)") { + withTable("t", "s") { + sql(s""" + |CREATE TABLE t (id INT, p INT, b INT, c INT) PARTITIONED BY (p) + |TBLPROPERTIES ( + | 'bucket' = '-1', + | 'row-tracking.enabled' = 'true', + | 'data-evolution.enabled' = 'true', + | 'write-only' = 'true', + | 'data-evolution.metadata-memory-optimization.mode' = '$metadataMemoryMode') + |""".stripMargin) + sql("INSERT INTO t VALUES (1, 1, 10, 100)") + sql("INSERT INTO t VALUES (2, 1, 20, 200)") + sql("INSERT INTO t VALUES (3, 2, 30, 300)") + val originalRowIds = sql("SELECT id, _ROW_ID FROM t ORDER BY id").collect().toSeq + sql(""" + |MERGE INTO t USING (SELECT 1 AS id, 11 AS b UNION ALL SELECT 3, 31) u + |ON t.id = u.id + |WHEN MATCHED THEN UPDATE SET b = u.b + |""".stripMargin) + checkAnswer( + sql("SELECT id, b, c FROM t"), + Seq(Row(1, 11, 100), Row(2, 20, 200), Row(3, 31, 300))) + sql("CREATE TABLE s (id INT, p INT, b INT, c INT)") + sql( + "INSERT INTO s VALUES (1, 1, 111, 1111), (2, 1, 222, 2222), (3, 2, 333, 3333), (4, 1, 444, 4444)") + sql(""" + |MERGE INTO t USING s + |ON t.id = s.id AND t.p = s.p AND t.p = 1 AND t.b >= 11 + |WHEN MATCHED THEN UPDATE SET b = s.b + |WHEN NOT MATCHED THEN INSERT (id, p, b, c) VALUES (s.id, s.p, s.b, s.c) + |""".stripMargin) + checkAnswer( + sql("SELECT id, p, b, c FROM t"), + Seq( + Row(1, 1, 111, 100), + Row(2, 1, 222, 200), + Row(3, 2, 31, 300), + Row(3, 2, 333, 3333), + Row(4, 1, 444, 4444))) + checkAnswer(sql("SELECT id, _ROW_ID FROM t WHERE c < 1000"), originalRowIds) + checkAnswer( + sql("SELECT * FROM s"), + Seq( + Row(1, 1, 111, 1111), + Row(2, 1, 222, 2222), + Row(3, 2, 333, 3333), + Row(4, 1, 444, 4444))) + } + } + } + private def doWithRetry(doAction: () => Unit, retryableMessages: String*): Unit = { var attempts = 0 while (true) { @@ -251,60 +306,68 @@ abstract class RowTrackingTestBase extends PaimonSparkTestBase with AdaptiveSpar } } - test("Data Evolution: rebase rejects same-column update after concurrent compact") { - withTable("t") { - sql(s""" - |CREATE TABLE t (id INT, b INT) TBLPROPERTIES ( - | 'row-tracking.enabled' = 'true', - | 'compaction.min.file-num' = '2', - | 'commit.max-retries' = '0', - | 'data-evolution.enabled' = 'true') - |""".stripMargin) - sql("INSERT INTO t VALUES (1, 10)") - sql("INSERT INTO t VALUES (2, 20)") - - val table = loadTable("t") - val readSnapshot = table.latestSnapshot().get() - val dataSplits = table - .newSnapshotReader() - .withSnapshot(readSnapshot) - .read() - .splits() - .asScala - .collect { case split: DataSplit => split } - .toSeq - val firstRowIds = dataSplits - .flatMap(_.dataFiles().asScala) - .map(_.firstRowId().longValue()) - .sorted - val firstRowId = udf((rowId: Long) => firstRowIds.takeWhile(_ <= rowId).last) - val stagedRows = sql("SELECT b + 1 AS b, _ROW_ID FROM t WHERE id = 1") - .withColumn("_FIRST_ROW_ID", firstRowId(col("_ROW_ID"))) - .select("b", "_FIRST_ROW_ID", "_ROW_ID") - val stagedUpdates = - DataEvolutionPaimonWriter(table, dataSplits).writePartialFields(stagedRows, Seq("b")) - - sql("CALL sys.compact(table => 't')").collect() - sql("UPDATE t SET b = 99 WHERE id = 1").collect() + Seq("off", "lightweight").foreach { + metadataMemoryMode => + test( + s"Data Evolution: rebase rejects same-column update after concurrent compact (metadata memory: $metadataMemoryMode)") { + withTable("t") { + sql(s""" + |CREATE TABLE t (id INT, b INT) TBLPROPERTIES ( + | 'row-tracking.enabled' = 'true', + | 'compaction.min.file-num' = '2', + | 'commit.max-retries' = '0', + | 'data-evolution.metadata-memory-optimization.mode' = '$metadataMemoryMode', + | 'data-evolution.enabled' = 'true') + |""".stripMargin) + sql("INSERT INTO t VALUES (1, 10)") + sql("INSERT INTO t VALUES (2, 20)") + + val table = loadTable("t") + assert( + table.coreOptions().dataEvolutionMetadataMemoryOptimizationEnabled() == + (metadataMemoryMode != "off")) + val readSnapshot = table.latestSnapshot().get() + val dataSplits = table + .newSnapshotReader() + .withSnapshot(readSnapshot) + .read() + .splits() + .asScala + .collect { case split: DataSplit => split } + .toSeq + val firstRowIds = dataSplits + .flatMap(_.dataFiles().asScala) + .map(_.firstRowId().longValue()) + .sorted + val firstRowId = udf((rowId: Long) => firstRowIds.takeWhile(_ <= rowId).last) + val stagedRows = sql("SELECT b + 1 AS b, _ROW_ID FROM t WHERE id = 1") + .withColumn("_FIRST_ROW_ID", firstRowId(col("_ROW_ID"))) + .select("b", "_FIRST_ROW_ID", "_ROW_ID") + val stagedUpdates = + DataEvolutionPaimonWriter(table, dataSplits).writePartialFields(stagedRows, Seq("b")) + + sql("CALL sys.compact(table => 't')").collect() + sql("UPDATE t SET b = 99 WHERE id = 1").collect() + + val writer = PaimonSparkWriter(table) + val targetRelation = + PaimonRelation.getPaimonRelation(spark.table("t").queryExecution.analyzed) + val exception = intercept[RuntimeException] { + DataEvolutionRowIdConflictCommitter.commit( + spark, + table, + targetRelation, + writer, + stagedUpdates, + Nil, + readSnapshot.id(), + Operation.MERGE) + } - val writer = PaimonSparkWriter(table) - val targetRelation = - PaimonRelation.getPaimonRelation(spark.table("t").queryExecution.analyzed) - val exception = intercept[RuntimeException] { - DataEvolutionRowIdConflictCommitter.commit( - spark, - table, - targetRelation, - writer, - stagedUpdates, - Nil, - readSnapshot.id(), - Operation.MERGE) + assert(hasMessage(exception, ErrorMessages.DATA_EVOLUTION_ROW_ID_CONFLICT_MESSAGE)) + checkAnswer(sql("SELECT id, b FROM t ORDER BY id"), Seq(Row(1, 99), Row(2, 20))) + } } - - assert(hasMessage(exception, ErrorMessages.DATA_EVOLUTION_ROW_ID_CONFLICT_MESSAGE)) - checkAnswer(sql("SELECT id, b FROM t ORDER BY id"), Seq(Row(1, 99), Row(2, 20))) - } } test("Data Evolution: concurrent merge and merge") { @@ -436,66 +499,76 @@ abstract class RowTrackingTestBase extends PaimonSparkTestBase with AdaptiveSpar } } - test("Data Evolution: rebasing a staged sub-field update keeps a NULL struct null") { - withTable("t") { - sql(s""" - |CREATE TABLE t (id INT, nest STRUCT) TBLPROPERTIES ( - | 'row-tracking.enabled' = 'true', - | 'compaction.min.file-num' = '2', - | 'commit.max-retries' = '0', - | 'data-evolution.row-id-conflict-rewrite.max-size' = '0 B', - | 'data-evolution.enabled' = 'true', - | 'data-evolution.nested-field.enabled' = 'true') - |""".stripMargin) - sql("INSERT INTO t VALUES (1, named_struct('a', 10, 'b', 'x'))") - // a row whose whole struct is NULL, which the rebase has to carry through untouched - sql("INSERT INTO t VALUES (2, CAST(NULL AS STRUCT))") - - val table = loadTable("t") - val readSnapshot = table.latestSnapshot().get() - val dataSplits = table - .newSnapshotReader() - .withSnapshot(readSnapshot) - .read() - .splits() - .asScala - .collect { case split: DataSplit => split } - .toSeq - val firstRowIds = dataSplits - .flatMap(_.dataFiles().asScala) - .map(_.firstRowId().longValue()) - .sorted - val firstRowId = udf((rowId: Long) => firstRowIds.takeWhile(_ <= rowId).last) - // the staged update only covers id = 1; id = 2 is pulled in by the rebase because the - // compacted row-id range covers it - val stagedRows = - sql("SELECT named_struct('a', nest.a + 1) AS nest, _ROW_ID FROM t WHERE id = 1") - .withColumn("_FIRST_ROW_ID", firstRowId(col("_ROW_ID"))) - .select("nest", "_FIRST_ROW_ID", "_ROW_ID") - val stagedUpdates = - DataEvolutionPaimonWriter(table, dataSplits).writePartialFields(stagedRows, Seq("nest.a")) - - sql("CALL sys.compact(table => 't')").collect() - - val writer = PaimonSparkWriter(table) - val targetRelation = - PaimonRelation.getPaimonRelation(spark.table("t").queryExecution.analyzed) - DataEvolutionRowIdConflictCommitter.commit( - spark, - table, - targetRelation, - writer, - stagedUpdates, - Nil, - readSnapshot.id(), - Operation.MERGE) + Seq("off", "lightweight").foreach { + metadataMemoryMode => + test( + s"Data Evolution: rebasing a staged sub-field update keeps a NULL struct null (metadata memory: $metadataMemoryMode)") { + withTable("t") { + sql(s""" + |CREATE TABLE t (id INT, nest STRUCT) TBLPROPERTIES ( + | 'row-tracking.enabled' = 'true', + | 'compaction.min.file-num' = '2', + | 'commit.max-retries' = '0', + | 'data-evolution.row-id-conflict-rewrite.max-size' = '0 B', + | 'data-evolution.metadata-memory-optimization.mode' = '$metadataMemoryMode', + | 'data-evolution.enabled' = 'true', + | 'data-evolution.nested-field.enabled' = 'true') + |""".stripMargin) + sql("INSERT INTO t VALUES (1, named_struct('a', 10, 'b', 'x'))") + // a row whose whole struct is NULL, which the rebase has to carry through untouched + sql("INSERT INTO t VALUES (2, CAST(NULL AS STRUCT))") + + val table = loadTable("t") + assert( + table.coreOptions().dataEvolutionMetadataMemoryOptimizationEnabled() == + (metadataMemoryMode != "off")) + val readSnapshot = table.latestSnapshot().get() + val dataSplits = table + .newSnapshotReader() + .withSnapshot(readSnapshot) + .read() + .splits() + .asScala + .collect { case split: DataSplit => split } + .toSeq + val firstRowIds = dataSplits + .flatMap(_.dataFiles().asScala) + .map(_.firstRowId().longValue()) + .sorted + val firstRowId = udf((rowId: Long) => firstRowIds.takeWhile(_ <= rowId).last) + // the staged update only covers id = 1; id = 2 is pulled in by the rebase because the + // compacted row-id range covers it + val stagedRows = + sql("SELECT named_struct('a', nest.a + 1) AS nest, _ROW_ID FROM t WHERE id = 1") + .withColumn("_FIRST_ROW_ID", firstRowId(col("_ROW_ID"))) + .select("nest", "_FIRST_ROW_ID", "_ROW_ID") + val stagedUpdates = + DataEvolutionPaimonWriter(table, dataSplits).writePartialFields( + stagedRows, + Seq("nest.a")) + + sql("CALL sys.compact(table => 't')").collect() + + val writer = PaimonSparkWriter(table) + val targetRelation = + PaimonRelation.getPaimonRelation(spark.table("t").queryExecution.analyzed) + DataEvolutionRowIdConflictCommitter.commit( + spark, + table, + targetRelation, + writer, + stagedUpdates, + Nil, + readSnapshot.id(), + Operation.MERGE) - checkAnswer( - sql("SELECT id, nest.a, nest.b FROM t ORDER BY id"), - Seq(Row(1, 11, "x"), Row(2, null, null))) - // the NULL struct must not have been resurrected as a struct of NULL children - checkAnswer(sql("SELECT id FROM t WHERE nest IS NULL"), Seq(Row(2))) - } + checkAnswer( + sql("SELECT id, nest.a, nest.b FROM t ORDER BY id"), + Seq(Row(1, 11, "x"), Row(2, null, null))) + // the NULL struct must not have been resurrected as a struct of NULL children + checkAnswer(sql("SELECT id FROM t WHERE nest IS NULL"), Seq(Row(2))) + } + } } test("Data Evolution: concurrent merge and small files compact") { @@ -2284,37 +2357,47 @@ abstract class RowTrackingTestBase extends PaimonSparkTestBase with AdaptiveSpar ) } - test("Data Evolution: V1 update retries concurrent update conflicts") { - withSparkSQLConf( - "spark.paimon.write.use-v2-write" -> "false", - "spark.paimon.write.data-evolution.update-conflict-retry.max-attempts" -> "50", - "spark.paimon.write.data-evolution.update-conflict-retry.wait-ms" -> "10" - ) { - withTable("t") { - sql( - "CREATE TABLE t (id INT, b INT, c INT) TBLPROPERTIES ('row-tracking.enabled' = 'true', 'data-evolution.enabled' = 'true')") - sql("INSERT INTO t VALUES (1, 0, 0)") - - val ready = new CountDownLatch(4) - val start = new CountDownLatch(1) - val updates = (1 to 4).map { - _ => - Future { - ready.countDown() - assert(start.await(30, TimeUnit.SECONDS)) - for (_ <- 1 to 5) { - sql("UPDATE t SET b = b + 1 WHERE id = 1").collect() - } + Seq("off", "lightweight").foreach { + metadataMemoryMode => + test( + s"Data Evolution: V1 update retries concurrent update conflicts (metadata memory: $metadataMemoryMode)") { + withSparkSQLConf( + "spark.paimon.write.use-v2-write" -> "false", + "spark.paimon.write.data-evolution.update-conflict-retry.max-attempts" -> "50", + "spark.paimon.write.data-evolution.update-conflict-retry.wait-ms" -> "10" + ) { + withTable("t") { + sql(s"""CREATE TABLE t (id INT, b INT, c INT) TBLPROPERTIES ( + | 'row-tracking.enabled' = 'true', + | 'data-evolution.metadata-memory-optimization.mode' = '$metadataMemoryMode', + | 'data-evolution.enabled' = 'true') + |""".stripMargin) + assert( + loadTable("t").coreOptions().dataEvolutionMetadataMemoryOptimizationEnabled() == + (metadataMemoryMode != "off")) + sql("INSERT INTO t VALUES (1, 0, 0)") + + val ready = new CountDownLatch(4) + val start = new CountDownLatch(1) + val updates = (1 to 4).map { + _ => + Future { + ready.countDown() + assert(start.await(30, TimeUnit.SECONDS)) + for (_ <- 1 to 5) { + sql("UPDATE t SET b = b + 1 WHERE id = 1").collect() + } + } } - } - assert(ready.await(30, TimeUnit.SECONDS)) - start.countDown() - updates.foreach(Await.result(_, 120.seconds)) + assert(ready.await(30, TimeUnit.SECONDS)) + start.countDown() + updates.foreach(Await.result(_, 120.seconds)) - checkAnswer(sql("SELECT b FROM t"), Seq(Row(20))) + checkAnswer(sql("SELECT b FROM t"), Seq(Row(20))) + } + } } - } } test("Data Evolution: V1 update partition column throws exception") {