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