This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git
The following commit(s) were added to refs/heads/master by this push:
new 37bc1dc2ae [core] Discover retained changelogs in streaming reads
(#11040)
37bc1dc2ae is described below
commit 37bc1dc2ae955e0a36dc305927c41c7466318b10
Author: csurong <[email protected]>
AuthorDate: Fri Nov 13 21:24:01 2026 +0800
[core] Discover retained changelogs in streaming reads (#11040)
---
docs/docs/maintenance/manage-snapshots.mdx | 14 +-
.../paimon/table/source/AbstractDataTableScan.java | 19 +-
.../paimon/table/source/DataTableStreamScan.java | 25 +-
.../paimon/table/source/StreamDataTableScan.java | 8 +
.../table/source/snapshot/TimeTravelUtil.java | 82 ++-
.../apache/paimon/table/system/AuditLogTable.java | 5 +
.../apache/paimon/utils/NextSnapshotFetcher.java | 13 +-
.../table/source/RetainedChangelogScanTest.java | 572 +++++++++++++++++++++
.../CreationTimestampStartingScannerTest.java | 10 +-
.../paimon/flink/lookup/LookupDataTableScan.java | 7 +
.../paimon/flink/FlinkJobRecoveryITCase.java | 109 ++++
.../flink/lookup/LookupDataTableScanTest.java | 137 +++++
.../spark/sources/PaimonMicroBatchStream.scala | 20 +-
.../apache/paimon/spark/sources/StreamHelper.scala | 2 +
.../procedure/ExpireSnapshotsProcedureTest.scala | 22 +-
.../sources/PaimonMicroBatchStreamITCase.scala | 266 +++++++++-
16 files changed, 1263 insertions(+), 48 deletions(-)
diff --git a/docs/docs/maintenance/manage-snapshots.mdx
b/docs/docs/maintenance/manage-snapshots.mdx
index d8d2e6d5b7..0a904a9d51 100644
--- a/docs/docs/maintenance/manage-snapshots.mdx
+++ b/docs/docs/maintenance/manage-snapshots.mdx
@@ -248,10 +248,16 @@ Retention overrides such as `retain_max` and dynamic
`options` apply only to tha
operation; they do not update the table properties. An override can cause
changelogs to be retained
independently even though the persisted snapshot and changelog retention
settings are equal.
For example, with both maximum counts set to `4` and otherwise matching
retention settings,
-calling `expire_snapshots` with `retain_max=1` can leave changelog history
after its snapshots expire. A new streaming reader using the unchanged
-`4`/`4` settings does not discover that independent history. The reader must
also use a configuration
-that enables independent changelog retention, such as a changelog maximum
count greater than the
-snapshot maximum count. Retaining the files alone does not enable their
discovery by that reader.
+calling `expire_snapshots` with `retain_max=1` can leave changelog history
after its snapshots expire.
+Ordinary streaming readers with `changelog-producer` set to `input`, `lookup`,
or `full-compaction`
+can discover this retained history without repeating the retention overrides.
The changelog
+metadata and the files it references must still be available. This does not
restore expired
+snapshots for full reads, and does not apply to streaming overwrite reads or
special scans
+such as file monitoring and compaction. Flink lookup joins keep their existing
discovery rules.
+If a timestamp-based start cannot be located safely because retained metadata
has a gap,
+the reader reports the missing history instead of skipping it, even if the
next retained commit
+matches the requested timestamp. Starting from an explicit retained snapshot
ID avoids this
+ambiguity when that starting point is intended.
<Tabs groupId="manually-expire-snapshot">
diff --git
a/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataTableScan.java
b/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataTableScan.java
index 4ac5cda74f..e126cd4a40 100644
---
a/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataTableScan.java
+++
b/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataTableScan.java
@@ -463,6 +463,10 @@ abstract class AbstractDataTableScan implements
DataTableScan {
return options;
}
+ protected boolean readRetainedChangelog() {
+ return options.changelogLifecycleDecoupled();
+ }
+
protected StartingScanner createStartingScanner(boolean isStreaming) {
SnapshotManager snapshotManager = snapshotReader.snapshotManager();
ChangelogManager changelogManager = snapshotReader.changelogManager();
@@ -490,7 +494,7 @@ abstract class AbstractDataTableScan implements
DataTableScan {
snapshotManager,
changelogManager,
consumer.get().nextSnapshot(),
- options.changelogLifecycleDecoupled());
+ readRetainedChangelog());
}
}
@@ -539,7 +543,7 @@ abstract class AbstractDataTableScan implements
DataTableScan {
snapshotManager,
changelogManager,
startupMillis,
- options.changelogLifecycleDecoupled())
+ readRetainedChangelog())
: new
StaticFromTimestampStartingScanner(snapshotManager, startupMillis);
case FROM_FILE_CREATION_TIME:
Long fileCreationTimeMills =
options.scanFileCreationTimeMills();
@@ -550,7 +554,7 @@ abstract class AbstractDataTableScan implements
DataTableScan {
snapshotManager,
changelogManager,
creationTimeMills,
- options.changelogLifecycleDecoupled(),
+ readRetainedChangelog(),
isStreaming);
case FROM_SNAPSHOT:
@@ -560,7 +564,7 @@ abstract class AbstractDataTableScan implements
DataTableScan {
snapshotManager,
changelogManager,
options.scanSnapshotId(),
- options.changelogLifecycleDecoupled())
+ readRetainedChangelog())
: new StaticFromSnapshotStartingScanner(
snapshotManager, options.scanSnapshotId());
} else if (options.scanWatermark() != null) {
@@ -598,12 +602,13 @@ abstract class AbstractDataTableScan implements
DataTableScan {
long creationMillis,
boolean changelogDecoupled,
boolean isStreaming) {
+ // Batch reads need full snapshots; only streaming reads can start
from changelog metadata.
Long startingSnapshotPrevId =
TimeTravelUtil.earlierThanTimeMills(
snapshotManager,
changelogManager,
creationMillis,
- changelogDecoupled,
+ isStreaming && changelogDecoupled,
true);
final StartingScanner scanner;
Optional<Long> startingSnapshotId =
@@ -612,7 +617,9 @@ abstract class AbstractDataTableScan implements
DataTableScan {
.filter(
id ->
snapshotManager.snapshotExists(id)
- ||
changelogManager.longLivedChangelogExists(id));
+ || (isStreaming
+ && changelogManager
+
.longLivedChangelogExists(id)));
if (startingSnapshotId.isPresent()) {
scanner =
isStreaming
diff --git
a/paimon-core/src/main/java/org/apache/paimon/table/source/DataTableStreamScan.java
b/paimon-core/src/main/java/org/apache/paimon/table/source/DataTableStreamScan.java
index 02806cfe33..2d3c349f58 100644
---
a/paimon-core/src/main/java/org/apache/paimon/table/source/DataTableStreamScan.java
+++
b/paimon-core/src/main/java/org/apache/paimon/table/source/DataTableStreamScan.java
@@ -94,7 +94,10 @@ public class DataTableStreamScan extends
AbstractDataTableScan implements Stream
this.supportStreamingReadOverwrite = supportStreamingReadOverwrite;
this.nextSnapshotProvider =
new NextSnapshotFetcher(
- snapshotManager, changelogManager,
options.changelogLifecycleDecoupled());
+ snapshotManager,
+ changelogManager,
+ options.changelogLifecycleDecoupled(),
+ readRetainedChangelog());
this.hasPk = hasPk;
if (options.bucket() == BucketMode.POSTPONE_BUCKET
@@ -103,6 +106,16 @@ public class DataTableStreamScan extends
AbstractDataTableScan implements Stream
}
}
+ @Override
+ public boolean readRetainedChangelog() {
+ // Retained changelog manifests are enough for changelog scans, but
not for scans
+ // requiring historical table files (for example streaming overwrite
reads).
+ return options.changelogLifecycleDecoupled()
+ || (scanMode == StreamScanMode.NONE
+ && options.changelogProducer() !=
CoreOptions.ChangelogProducer.NONE
+ && !supportStreamingReadOverwrite);
+ }
+
@Override
public DataTableStreamScan withFilter(Predicate predicate) {
super.withFilter(predicate);
@@ -114,7 +127,7 @@ public class DataTableStreamScan extends
AbstractDataTableScan implements Stream
if (!initialized) {
initScanner();
}
- return startingScanner.startingContext();
+ return startingScanner().startingContext();
}
@Override
@@ -136,10 +149,15 @@ public class DataTableStreamScan extends
AbstractDataTableScan implements Stream
"List Partition Entries is not supported in Stream Scan.");
}
- private void initScanner() {
+ private StartingScanner startingScanner() {
+ // A restored scan must not resolve its original startup options
against expired history.
if (startingScanner == null) {
startingScanner = createStartingScanner(true);
}
+ return startingScanner;
+ }
+
+ private void initScanner() {
if (followUpScanner == null) {
followUpScanner = createFollowUpScanner();
}
@@ -153,6 +171,7 @@ public class DataTableStreamScan extends
AbstractDataTableScan implements Stream
}
private Plan tryFirstPlan() {
+ StartingScanner startingScanner = startingScanner();
StartingScanner.Result result;
if (scanMode == FILE_MONITOR) {
result = startingScanner.scan(snapshotReader);
diff --git
a/paimon-core/src/main/java/org/apache/paimon/table/source/StreamDataTableScan.java
b/paimon-core/src/main/java/org/apache/paimon/table/source/StreamDataTableScan.java
index f5e6e3a0aa..f6f2affa5f 100644
---
a/paimon-core/src/main/java/org/apache/paimon/table/source/StreamDataTableScan.java
+++
b/paimon-core/src/main/java/org/apache/paimon/table/source/StreamDataTableScan.java
@@ -27,6 +27,14 @@ public interface StreamDataTableScan extends DataTableScan,
StreamTableScan {
StartingContext startingContext();
+ /**
+ * Whether this scan can read retained changelog metadata after its
snapshot expires. Wrappers
+ * should delegate this capability to their underlying scan.
+ */
+ default boolean readRetainedChangelog() {
+ return false;
+ }
+
/** Restore from checkpoint next snapshot id with scan kind. */
void restore(@Nullable Long nextSnapshotId, boolean scanAllSnapshot);
}
diff --git
a/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/TimeTravelUtil.java
b/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/TimeTravelUtil.java
index 47d7bc6d44..e5eedcef84 100644
---
a/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/TimeTravelUtil.java
+++
b/paimon-core/src/main/java/org/apache/paimon/table/source/snapshot/TimeTravelUtil.java
@@ -25,6 +25,7 @@ import org.apache.paimon.manifest.ManifestEntry;
import org.apache.paimon.options.Options;
import org.apache.paimon.schema.TableSchema;
import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.source.OutOfRangeException;
import org.apache.paimon.utils.ChangelogManager;
import org.apache.paimon.utils.FunctionWithException;
import org.apache.paimon.utils.SnapshotManager;
@@ -36,6 +37,8 @@ import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -43,6 +46,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.TimeZone;
import java.util.stream.Collectors;
+import java.util.stream.Stream;
import static org.apache.paimon.CoreOptions.SCAN_SNAPSHOT_ID;
import static org.apache.paimon.CoreOptions.SCAN_TAG_NAME;
@@ -50,6 +54,7 @@ import static org.apache.paimon.CoreOptions.SCAN_TIMESTAMP;
import static org.apache.paimon.CoreOptions.SCAN_TIMESTAMP_MILLIS;
import static org.apache.paimon.CoreOptions.SCAN_WATERMARK;
import static org.apache.paimon.utils.DateTimeUtils.parseTimestampData;
+import static org.apache.paimon.utils.FileUtils.listVersionedFiles;
import static org.apache.paimon.utils.Preconditions.checkArgument;
import static org.apache.paimon.utils.SnapshotManager.retryEarliestSnapshot;
@@ -191,17 +196,34 @@ public class TimeTravelUtil {
return latest - 1;
}
- if (earliestSnapshot.timeMillis() >= timestampMills) {
+ if (earliestSnapshot.timeMillis() > timestampMills) {
return returnNullIfTooEarly ? null : earliestSnapshot.id() - 1;
}
+ if (earliestSnapshot.timeMillis() == timestampMills) {
+ return earliestSnapshot.id() - 1;
+ }
long earliest = earliestSnapshot.id();
+ long latestRetainedId = latest;
while (earliest < latest) {
long mid = (earliest + latest + 1) / 2;
- Snapshot snapshot =
- startFromChangelog
- ? changelogOrSnapshot(snapshotManager,
changelogManager, mid)
- : snapshotManager.snapshot(mid);
+ Snapshot snapshot;
+ if (startFromChangelog) {
+ try {
+ snapshot = tryGetChangelogOrSnapshot(snapshotManager,
changelogManager, mid);
+ } catch (FileNotFoundException e) {
+ // Operation-local retention can leave disjoint ranges of
changelogs and
+ // snapshots. Search their actual IDs instead of assuming
a continuous range.
+ return earlierThanTimeMillsWithGaps(
+ snapshotManager,
+ changelogManager,
+ timestampMills,
+ earliestSnapshot.id(),
+ latestRetainedId);
+ }
+ } else {
+ snapshot = snapshotManager.snapshot(mid);
+ }
if (snapshot.timeMillis() < timestampMills) {
earliest = mid;
} else {
@@ -211,6 +233,56 @@ public class TimeTravelUtil {
return earliest;
}
+ private static @Nullable Long earlierThanTimeMillsWithGaps(
+ SnapshotManager snapshotManager,
+ ChangelogManager changelogManager,
+ long timestampMills,
+ long earliestId,
+ long latestId) {
+ List<Long> ids;
+ try (Stream<Long> snapshots = snapshotManager.snapshotIdStream();
+ Stream<Long> changelogs =
+ listVersionedFiles(
+ changelogManager.fileIO(),
+ changelogManager.changelogDirectory(),
+ ChangelogManager.CHANGELOG_PREFIX)) {
+ ids =
+ Stream.concat(snapshots, changelogs)
+ .filter(id -> id >= earliestId && id <= latestId)
+ .distinct()
+ .sorted()
+ .collect(Collectors.toList());
+ } catch (IOException e) {
+ throw new UncheckedIOException("Failed to list retained snapshot
and changelog IDs", e);
+ }
+ if (ids.isEmpty()) {
+ return null;
+ }
+ int left = 0;
+ int right = ids.size();
+ while (left < right) {
+ int mid = (left + right) / 2;
+ Snapshot snapshot =
+ changelogOrSnapshot(snapshotManager, changelogManager,
ids.get(mid));
+ if (snapshot.timeMillis() < timestampMills) {
+ left = mid + 1;
+ } else {
+ right = mid;
+ }
+ }
+ long previousId = left == 0 ? ids.get(0) - 1 : ids.get(left - 1);
+ if (left < ids.size() && ids.get(left) > previousId + 1) {
+ // Missing commits may have the same timestamp as the next
retained commit.
+ // Without their metadata, we cannot safely choose a starting
point across the gap.
+ throw new OutOfRangeException(
+ String.format(
+ "Cannot determine the starting snapshot for
timestamp %d: "
+ + "snapshot and changelog metadata are
missing for IDs %d to %d.",
+ timestampMills, previousId + 1, ids.get(left) -
1));
+ }
+ return previousId;
+ }
+
private static @Nullable Snapshot earliestSnapshot(
SnapshotManager snapshotManager,
ChangelogManager changelogManager,
diff --git
a/paimon-core/src/main/java/org/apache/paimon/table/system/AuditLogTable.java
b/paimon-core/src/main/java/org/apache/paimon/table/system/AuditLogTable.java
index 5ccc84886e..32fb8b3b26 100644
---
a/paimon-core/src/main/java/org/apache/paimon/table/system/AuditLogTable.java
+++
b/paimon-core/src/main/java/org/apache/paimon/table/system/AuditLogTable.java
@@ -659,6 +659,11 @@ public class AuditLogTable implements DataTable,
ReadonlyTable {
return this;
}
+ @Override
+ public boolean readRetainedChangelog() {
+ return streamScan.readRetainedChangelog();
+ }
+
@Override
public StartingContext startingContext() {
return streamScan.startingContext();
diff --git
a/paimon-core/src/main/java/org/apache/paimon/utils/NextSnapshotFetcher.java
b/paimon-core/src/main/java/org/apache/paimon/utils/NextSnapshotFetcher.java
index 23664216b7..89e4915ab9 100644
--- a/paimon-core/src/main/java/org/apache/paimon/utils/NextSnapshotFetcher.java
+++ b/paimon-core/src/main/java/org/apache/paimon/utils/NextSnapshotFetcher.java
@@ -35,7 +35,9 @@ public class NextSnapshotFetcher {
private final SnapshotManager snapshotManager;
private final ChangelogManager changelogManager;
+ // Keep the configured missing-history policy separate from changelog
discovery.
private final boolean changelogDecoupled;
+ private final boolean readRetainedChangelog;
private int rangeCheckCnt = 0;
@@ -43,9 +45,18 @@ public class NextSnapshotFetcher {
SnapshotManager snapshotManager,
ChangelogManager changelogManager,
boolean changelogDecoupled) {
+ this(snapshotManager, changelogManager, changelogDecoupled,
changelogDecoupled);
+ }
+
+ public NextSnapshotFetcher(
+ SnapshotManager snapshotManager,
+ ChangelogManager changelogManager,
+ boolean changelogDecoupled,
+ boolean readRetainedChangelog) {
this.snapshotManager = snapshotManager;
this.changelogManager = changelogManager;
this.changelogDecoupled = changelogDecoupled;
+ this.readRetainedChangelog = readRetainedChangelog;
}
@Nullable
@@ -55,7 +66,7 @@ public class NextSnapshotFetcher {
return snapshotManager.snapshot(nextSnapshotId);
}
- if (changelogDecoupled &&
changelogManager.longLivedChangelogExists(nextSnapshotId)) {
+ if (readRetainedChangelog &&
changelogManager.longLivedChangelogExists(nextSnapshotId)) {
return changelogManager.changelog(nextSnapshotId);
}
diff --git
a/paimon-core/src/test/java/org/apache/paimon/table/source/RetainedChangelogScanTest.java
b/paimon-core/src/test/java/org/apache/paimon/table/source/RetainedChangelogScanTest.java
new file mode 100644
index 0000000000..2b28b7b883
--- /dev/null
+++
b/paimon-core/src/test/java/org/apache/paimon/table/source/RetainedChangelogScanTest.java
@@ -0,0 +1,572 @@
+/*
+ * 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.CoreOptions;
+import org.apache.paimon.consumer.Consumer;
+import org.apache.paimon.disk.IOManager;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.options.Options;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.FileStoreTableFactory;
+import org.apache.paimon.table.sink.StreamTableCommit;
+import org.apache.paimon.table.sink.StreamTableWrite;
+import org.apache.paimon.table.source.snapshot.ScannerTestBase;
+import org.apache.paimon.utils.JsonSerdeUtil;
+import org.apache.paimon.utils.NextSnapshotFetcher;
+import org.apache.paimon.utils.ProcedureUtils;
+
+import
org.apache.paimon.shade.jackson2.com.fasterxml.jackson.databind.node.ObjectNode;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Tests discovering retained changelogs without read-time retention
overrides. */
+public class RetainedChangelogScanTest extends ScannerTestBase {
+
+ @Override
+ protected FileStoreTable createFileStoreTable() throws Exception {
+ Options options = new Options();
+ options.set(CoreOptions.WRITE_ONLY, true);
+ options.set(CoreOptions.CHANGELOG_PRODUCER,
CoreOptions.ChangelogProducer.INPUT);
+ options.set(CoreOptions.SNAPSHOT_NUM_RETAINED_MIN, 1);
+ options.set(CoreOptions.SNAPSHOT_NUM_RETAINED_MAX, 4);
+ options.set(CoreOptions.CHANGELOG_NUM_RETAINED_MAX, 4);
+ return createFileStoreTable(options);
+ }
+
+ @Test
+ public void testRestoreAfterSnapshotRetentionOverride() throws Exception {
+ writeFourCommits();
+ expireSnapshots();
+ FileStoreTable reloaded = FileStoreTableFactory.create(fileIO,
tablePath);
+
assertThat(reloaded.coreOptions().changelogLifecycleDecoupled()).isFalse();
+ StreamTableScan scan = reloaded.newReadBuilder().newStreamScan();
+ scan.restore(1L);
+ assertHistory(reloaded, scan);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"timestamp", "creation-timestamp"})
+ public void testRestoreAfterTimestampHistoryExpires(String start) throws
Exception {
+ writeFourCommits();
+ expireSnapshots();
+ try (StreamTableWrite write = table.newWrite(commitUser);
+ StreamTableCommit commit = table.newCommit(commitUser)) {
+ for (int i = 5; i <= 8; i++) {
+ waitForNextCommitMillis();
+ write.write(rowData(1, i, (long) i));
+ commit.commit(i, write.prepareCommit(true, i));
+ }
+ }
+ long timestamp = table.snapshotManager().snapshot(5L).timeMillis();
+
table.newExpireSnapshots().config(table.coreOptions().expireConfig()).expire();
+
assertThat(table.changelogManager().longLivedChangelogExists(3L)).isTrue();
+ assertThat(table.snapshotManager().snapshotExists(4L)).isFalse();
+
assertThat(table.changelogManager().longLivedChangelogExists(4L)).isFalse();
+
+ Options options = new Options();
+ options.set(
+ start.equals("timestamp")
+ ? CoreOptions.SCAN_TIMESTAMP_MILLIS
+ : CoreOptions.SCAN_CREATION_TIME_MILLIS,
+ timestamp);
+ FileStoreTable reloaded =
+ FileStoreTableFactory.create(fileIO,
tablePath).copy(options.toMap());
+ // Fresh startup cannot resolve the original timestamp across the gap.
+ assertThatThrownBy(() ->
reloaded.newReadBuilder().newStreamScan().plan())
+ .isInstanceOf(OutOfRangeException.class)
+ .hasMessageContaining("IDs 4 to 4");
+
+ StreamTableScan scan = reloaded.newReadBuilder().newStreamScan();
+ scan.restore(7L);
+ for (int i = 7; i <= 8; i++) {
+ assertThat(getResult(reloaded.newRead(), scan.plan().splits()))
+ .containsExactly("+I 1|" + i + "|" + i);
+ }
+ assertThat(scan.checkpoint()).isEqualTo(9L);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"snapshot", "timestamp", "consumer"})
+ public void testStartAfterSnapshotRetentionOverride(String start) throws
Exception {
+ writeFourCommits();
+ expireSnapshots();
+ Options readOptions = new Options();
+ if (start.equals("snapshot")) {
+ readOptions.set(CoreOptions.SCAN_SNAPSHOT_ID, 1L);
+ } else if (start.equals("timestamp")) {
+ readOptions.set(CoreOptions.SCAN_TIMESTAMP_MILLIS, 0L);
+ } else {
+ table.consumerManager().resetConsumer("reader", new Consumer(1L));
+ readOptions.set(CoreOptions.CONSUMER_ID, "reader");
+ }
+ FileStoreTable reloaded =
+ FileStoreTableFactory.create(fileIO,
tablePath).copy(readOptions.toMap());
+ StreamTableScan scan = reloaded.newReadBuilder().newStreamScan();
+ // Starting scanners select the next snapshot before planning its
changes.
+ assertThat(scan.plan().splits()).isEmpty();
+ assertHistory(reloaded, scan);
+ }
+
+ @Test
+ public void testStartFromCreationTimestamp() throws Exception {
+ writeFourCommits();
+ long timestamp = table.snapshotManager().snapshot(2L).timeMillis();
+
assertThat(timestamp).isGreaterThan(table.snapshotManager().snapshot(1L).timeMillis());
+ expireSnapshots();
+ Options options = new Options();
+ options.set(CoreOptions.SCAN_CREATION_TIME_MILLIS, timestamp);
+ FileStoreTable reloaded =
+ FileStoreTableFactory.create(fileIO,
tablePath).copy(options.toMap());
+ StreamTableScan scan = reloaded.newReadBuilder().newStreamScan();
+ assertThat(scan.plan().splits()).isEmpty();
+ for (int i = 2; i <= 4; i++) {
+ assertThat(getResult(reloaded.newRead(), scan.plan().splits()))
+ .containsExactly("+I 1|" + i + "|" + i);
+ }
+ assertThat(scan.checkpoint()).isEqualTo(5L);
+ }
+
+ @ParameterizedTest
+ @CsvSource({"true,0", "true,-1", "false,0", "false,-1"})
+ public void testCreationTimestampAtEarliestHistory(boolean expire, long
timeOffset)
+ throws Exception {
+ try (StreamTableWrite write = table.newWrite(commitUser);
+ StreamTableCommit commit = table.newCommit(commitUser)) {
+ for (int i = 1; i <= 4; i++) {
+ waitForNextCommitMillis();
+ write.write(rowData(1, 1, (long) i));
+ commit.commit(i, write.prepareCommit(true, i));
+ }
+ }
+ long timestamp = table.snapshotManager().snapshot(1L).timeMillis();
+ if (expire) {
+ expireSnapshots();
+ assertThat(table.snapshotManager().snapshotExists(1L)).isFalse();
+
assertThat(table.changelogManager().longLivedChangelogExists(1L)).isTrue();
+ }
+ Options options = new Options();
+ options.set(CoreOptions.SCAN_CREATION_TIME_MILLIS, timestamp +
timeOffset);
+ FileStoreTable reloaded =
+ FileStoreTableFactory.create(fileIO,
tablePath).copy(options.toMap());
+ StreamTableScan scan = reloaded.newReadBuilder().newStreamScan();
+ if (timeOffset < 0) {
+ // A strictly older timestamp still falls back to scanning current
table files.
+ assertThat(getResult(reloaded.newRead(), scan.plan().splits()))
+ .containsExactly("+I 1|1|4");
+ } else {
+ assertThat(scan.plan().splits()).isEmpty();
+ for (int i = 1; i <= 4; i++) {
+ assertThat(getResult(reloaded.newRead(), scan.plan().splits()))
+ .containsExactly("+I 1|1|" + i);
+ }
+ }
+ assertThat(scan.checkpoint()).isEqualTo(5L);
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "true,1,4", "true,2,4", "true,3,3", "true,4,4",
+ "false,1,4", "false,2,4", "false,3,3", "false,4,4"
+ })
+ public void testBatchCreationTimestampUsesSnapshotHistory(
+ boolean independent, int requestedId, int expectedValue) throws
Exception {
+ Options tableOptions = new Options(table.options());
+ tableOptions.set(CoreOptions.SNAPSHOT_NUM_RETAINED_MAX, 2);
+ tableOptions.set(CoreOptions.CHANGELOG_NUM_RETAINED_MAX, independent ?
4 : 2);
+ tablePath = new Path(tablePath, "batch");
+ table = createFileStoreTable(tableOptions);
+ long[] timestamps = new long[4];
+ try (StreamTableWrite write = table.newWrite(commitUser);
+ StreamTableCommit commit = table.newCommit(commitUser)) {
+ for (int i = 1; i <= 4; i++) {
+ waitForNextCommitMillis();
+ write.write(rowData(1, 1, (long) i));
+ commit.commit(i, write.prepareCommit(true, i));
+ timestamps[i - 1] =
table.snapshotManager().snapshot(i).timeMillis();
+ }
+ }
+
table.newExpireSnapshots().config(table.coreOptions().expireConfig()).expire();
+ assertThat(table.snapshotManager().earliestSnapshotId()).isEqualTo(3L);
+ assertThat(table.snapshotManager().snapshotExists(1L)).isFalse();
+
assertThat(table.changelogManager().longLivedChangelogExists(1L)).isEqualTo(independent);
+
+ Options readOptions = new Options();
+ readOptions.set(CoreOptions.SCAN_CREATION_TIME_MILLIS,
timestamps[requestedId - 1]);
+ FileStoreTable reloaded =
+ FileStoreTableFactory.create(fileIO,
tablePath).copy(readOptions.toMap());
+
assertThat(reloaded.coreOptions().changelogLifecycleDecoupled()).isEqualTo(independent);
+ // Times before snapshot 3 use the current files. Within the snapshot
range, read
+ // the selected full snapshot, regardless of whether older changelogs
are retained.
+ assertThat(getResult(reloaded.newRead(),
reloaded.newScan().plan().splits()))
+ .containsExactly("+I 1|1|" + expectedValue);
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "timestamp,false,5,8",
+ "creation-timestamp,false,5,8",
+ "timestamp,true,5,8",
+ "creation-timestamp,true,5,8",
+ "timestamp,false,6,8",
+ "timestamp,true,6,8",
+ "creation-timestamp,false,6,8",
+ "creation-timestamp,true,6,8",
+ "snapshot,false,5,8",
+ "snapshot,true,5,8",
+ "timestamp,false,2,8",
+ "timestamp,true,2,8",
+ "timestamp,false,4,8",
+ "timestamp,true,4,8",
+ "creation-timestamp,false,4,8",
+ "creation-timestamp,true,4,8",
+ "timestamp,false,7,9",
+ "timestamp,true,7,9"
+ })
+ public void testStartAfterMultipleExpirations(
+ String start, boolean independentAgain, int requestedId, int
lastId) throws Exception {
+ writeFourCommits();
+ expireSnapshots();
+ try (StreamTableWrite write = table.newWrite(commitUser);
+ StreamTableCommit commit = table.newCommit(commitUser)) {
+ for (int i = 5; i <= lastId; i++) {
+ waitForNextCommitMillis();
+ write.write(rowData(1, i, (long) i));
+ commit.commit(i, write.prepareCommit(true, i));
+ }
+ }
+ long timestamp =
+ requestedId < 4
+ ?
table.changelogManager().changelog(requestedId).timeMillis()
+ :
table.snapshotManager().snapshot(requestedId).timeMillis();
+
table.newExpireSnapshots().config(table.coreOptions().expireConfig()).expire();
+ if (independentAgain) {
+ expireSnapshots();
+ }
+
assertThat(table.changelogManager().longLivedChangelogExists(1L)).isTrue();
+ assertThat(table.snapshotManager().snapshotExists(4L)).isFalse();
+
assertThat(table.changelogManager().longLivedChangelogExists(4L)).isFalse();
+ Options options = new Options();
+ if (start.equals("snapshot")) {
+ options.set(CoreOptions.SCAN_SNAPSHOT_ID, (long) requestedId);
+ } else {
+ options.set(
+ start.equals("timestamp")
+ ? CoreOptions.SCAN_TIMESTAMP_MILLIS
+ : CoreOptions.SCAN_CREATION_TIME_MILLIS,
+ timestamp);
+ }
+ FileStoreTable reloaded =
+ FileStoreTableFactory.create(fileIO,
tablePath).copy(options.toMap());
+ StreamTableScan scan = reloaded.newReadBuilder().newStreamScan();
+ if (!start.equals("snapshot") && (requestedId == 4 || requestedId ==
5)) {
+ // The missing ID 4 may belong to the requested time, even when ID
5 matches it.
+ assertThatThrownBy(scan::plan)
+ .isInstanceOf(OutOfRangeException.class)
+ .hasMessageContaining("IDs 4 to 4");
+ return;
+ }
+ assertThat(scan.plan().splits()).isEmpty();
+ int lastReadableId = requestedId <= 4 ? 3 : lastId;
+ for (int i = requestedId; i <= lastReadableId; i++) {
+ assertThat(getResult(reloaded.newRead(), scan.plan().splits()))
+ .containsExactly("+I 1|" + i + "|" + i);
+ }
+ if (requestedId <= 4) {
+ assertExpired(scan, 4L);
+ } else {
+ assertThat(scan.checkpoint()).isEqualTo((long) lastId + 1);
+ }
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "timestamp,false,true",
+ "timestamp,true,true",
+ "creation-timestamp,false,true",
+ "creation-timestamp,true,true",
+ "timestamp,false,false",
+ "creation-timestamp,false,false"
+ })
+ public void testTimestampWithEqualCommitTimes(String start, boolean
independent, boolean gap)
+ throws Exception {
+ writeFourCommits();
+ long timestamp = table.snapshotManager().snapshot(4L).timeMillis();
+ expireSnapshots();
+ try (StreamTableWrite write = table.newWrite(commitUser);
+ StreamTableCommit commit = table.newCommit(commitUser)) {
+ for (int i = 5; i <= 8; i++) {
+ write.write(rowData(1, i, (long) i));
+ commit.commit(i, write.prepareCommit(true, i));
+ }
+ }
+ // Commit timestamps have millisecond precision and need not be
distinct.
+ Path snapshotPath = table.snapshotManager().snapshotPath(5L);
+ ObjectNode snapshot =
+ (ObjectNode)
+ JsonSerdeUtil.OBJECT_MAPPER_INSTANCE.readTree(
+ fileIO.readFileUtf8(snapshotPath));
+ snapshot.put("timeMillis", timestamp);
+ fileIO.overwriteFileUtf8(
+ snapshotPath,
JsonSerdeUtil.OBJECT_MAPPER_INSTANCE.writeValueAsString(snapshot));
+ table = FileStoreTableFactory.create(fileIO, tablePath);
+
assertThat(table.snapshotManager().snapshot(5L).timeMillis()).isEqualTo(timestamp);
+ if (gap) {
+
table.newExpireSnapshots().config(table.coreOptions().expireConfig()).expire();
+ assertThat(table.snapshotManager().snapshotExists(4L)).isFalse();
+
assertThat(table.changelogManager().longLivedChangelogExists(4L)).isFalse();
+ }
+ Options options = new Options();
+ options.set(
+ start.equals("timestamp")
+ ? CoreOptions.SCAN_TIMESTAMP_MILLIS
+ : CoreOptions.SCAN_CREATION_TIME_MILLIS,
+ timestamp);
+ if (independent) {
+ options.set(CoreOptions.CHANGELOG_NUM_RETAINED_MAX, 5);
+ }
+ FileStoreTable reloaded = table.copy(options.toMap());
+ StreamTableScan scan = reloaded.newReadBuilder().newStreamScan();
+ if (gap) {
+ assertThatThrownBy(scan::plan)
+ .isInstanceOf(OutOfRangeException.class)
+ .hasMessageContaining("Cannot determine the starting
snapshot")
+ .hasMessageContaining("IDs 4 to 4");
+ } else {
+ assertThat(scan.plan().splits()).isEmpty();
+ for (int i = 4; i <= 8; i++) {
+ assertThat(getResult(reloaded.newRead(), scan.plan().splits()))
+ .containsExactly("+I 1|" + i + "|" + i);
+ }
+ assertThat(scan.checkpoint()).isEqualTo(9L);
+ }
+ }
+
+ @Test
+ public void testNoIndependentRetention() throws Exception {
+ Options options = new Options(table.options());
+ options.remove(CoreOptions.CHANGELOG_NUM_RETAINED_MAX);
+ table = createFileStoreTable(true, options, new Path(tablePath,
"coupled"));
+ writeFourCommits();
+ expireSnapshots();
+
assertThat(table.changelogManager().earliestLongLivedChangelogId()).isNull();
+ StreamTableScan scan = table.newReadBuilder().newStreamScan();
+ scan.restore(1L);
+ assertExpired(scan, 1L);
+ }
+
+ @Test
+ public void testMissingChangelogDoesNotSkipHistory() throws Exception {
+ writeFourCommits();
+ expireSnapshots();
+ fileIO.delete(table.changelogManager().longLivedChangelogPath(2L),
false);
+ StreamTableScan scan = table.newReadBuilder().newStreamScan();
+ scan.restore(1L);
+ assertThat(getResult(table.newRead(),
scan.plan().splits())).containsExactly("+I 1|1|1");
+ assertExpired(scan, 2L);
+ }
+
+ @Test
+ public void testMissingChangelogFileFailsReading() throws Exception {
+ writeFourCommits();
+ expireSnapshots();
+ StreamTableScan scan = table.newReadBuilder().newStreamScan();
+ scan.restore(1L);
+ List<Split> splits = scan.plan().splits();
+ DataSplit split = (DataSplit) splits.get(0);
+ fileIO.delete(new Path(split.bucketPath(),
split.dataFiles().get(0).fileName()), false);
+ assertThatThrownBy(() -> getResult(table.newRead(), splits))
+ .hasStackTraceContaining("FileNotFoundException");
+ }
+
+ @Test
+ public void testEmptyChangelogCanBeSkipped() throws Exception {
+ try (StreamTableWrite write = table.newWrite(commitUser);
+ StreamTableCommit commit =
table.newCommit(commitUser).ignoreEmptyCommit(false)) {
+ write.write(rowData(1, 1, 1L));
+ commit.commit(1, write.prepareCommit(true, 1));
+ commit.commit(2, Collections.emptyList());
+ write.write(rowData(1, 3, 3L));
+ commit.commit(3, write.prepareCommit(true, 3));
+ }
+ assertThat(table.snapshotManager().latestSnapshotId()).isEqualTo(3L);
+ expireSnapshots();
+
assertThat(table.changelogManager().longLivedChangelogExists(2L)).isTrue();
+ StreamTableScan scan = table.newReadBuilder().newStreamScan();
+ scan.restore(1L);
+ assertThat(getResult(table.newRead(),
scan.plan().splits())).containsExactly("+I 1|1|1");
+ assertThat(getResult(table.newRead(),
scan.plan().splits())).containsExactly("+I 1|3|3");
+ assertThat(scan.checkpoint()).isEqualTo(4L);
+ }
+
+ @ParameterizedTest
+ @EnumSource(
+ value = CoreOptions.ChangelogProducer.class,
+ names = {"FULL_COMPACTION", "LOOKUP"})
+ public void testCompactionProducedChangelog(CoreOptions.ChangelogProducer
producer)
+ throws Exception {
+ Options options = new Options(table.options());
+ options.set(CoreOptions.CHANGELOG_PRODUCER, producer);
+ options.set(CoreOptions.SNAPSHOT_NUM_RETAINED_MAX, 20);
+ options.set(CoreOptions.CHANGELOG_NUM_RETAINED_MAX, 20);
+ options.set(CoreOptions.WRITE_ONLY, false);
+ tablePath = new Path(tablePath, producer.toString());
+ table = createFileStoreTable(true, options, tablePath);
+ try (IOManager ioManager =
IOManager.create(tempDir.resolve("io").toString());
+ StreamTableWrite write =
table.newWrite(commitUser).withIOManager(ioManager);
+ StreamTableCommit commit =
table.newCommit(commitUser).ignoreEmptyCommit(false)) {
+ for (int i = 1; i <= 4; i++) {
+ write.write(rowData(1, i, (long) i));
+ commit.commit(i, write.prepareCommit(true, i));
+ }
+ write.compact(binaryRow(1), 0, true);
+ commit.commit(5, write.prepareCommit(true, 5));
+ commit.commit(6, Collections.emptyList());
+ }
+ if (producer == CoreOptions.ChangelogProducer.FULL_COMPACTION) {
+
assertThat(table.snapshotManager().snapshot(1L).changelogManifestList()).isNull();
+ }
+ expireSnapshots();
+ FileStoreTable reloaded = FileStoreTableFactory.create(fileIO,
tablePath);
+
assertThat(reloaded.coreOptions().changelogLifecycleDecoupled()).isFalse();
+ StreamTableScan scan = reloaded.newReadBuilder().newStreamScan();
+ scan.restore(1L);
+ List<String> rows = new ArrayList<>();
+ long latest = table.snapshotManager().latestSnapshotId();
+ for (int i = 0; i < latest && scan.checkpoint() <= latest; i++) {
+ rows.addAll(getResult(reloaded.newRead(), scan.plan().splits()));
+ }
+ assertThat(rows).containsExactlyInAnyOrder("+I 1|1|1", "+I 1|2|2", "+I
1|3|3", "+I 1|4|4");
+ assertThat(scan.checkpoint()).isEqualTo(latest + 1);
+ }
+
+ @Test
+ public void testFullReadsStillUseSnapshots() throws Exception {
+ writeFourCommits();
+ expireSnapshots();
+ assertThat(getResult(table.newRead(), table.newScan().plan().splits()))
+ .containsExactlyInAnyOrder("+I 1|1|1", "+I 1|2|2", "+I 1|3|3",
"+I 1|4|4");
+ Options options = new Options();
+ options.set(CoreOptions.SCAN_MODE,
CoreOptions.StartupMode.FROM_SNAPSHOT_FULL);
+ options.set(CoreOptions.SCAN_SNAPSHOT_ID, 1L);
+ StreamTableScan scan =
table.copy(options.toMap()).newReadBuilder().newStreamScan();
+ // Full startup continues to use the earliest available snapshot, not
changelog 1.
+ assertThat(getResult(table.newRead(), scan.plan().splits()))
+ .containsExactlyInAnyOrder("+I 1|1|1", "+I 1|2|2", "+I 1|3|3",
"+I 1|4|4");
+ assertThat(scan.checkpoint()).isEqualTo(5L);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"overwrite", "file-monitor",
"compact-bucket-table", "none"})
+ public void testScansRequiringSnapshotFilesDoNotDiscoverChangelogs(String
mode)
+ throws Exception {
+ writeFourCommits();
+ expireSnapshots();
+ Options options = new Options();
+ if (mode.equals("overwrite")) {
+ options.set(CoreOptions.STREAMING_READ_OVERWRITE, true);
+ } else if (mode.equals("none")) {
+ options.set(CoreOptions.CHANGELOG_PRODUCER,
CoreOptions.ChangelogProducer.NONE);
+ } else {
+ options.set(CoreOptions.STREAM_SCAN_MODE.key(), mode);
+ }
+ StreamTableScan scan =
table.copy(options.toMap()).newReadBuilder().newStreamScan();
+ scan.restore(1L);
+ assertExpired(scan, 1L);
+ }
+
+ @Test
+ public void testNormalSnapshotsAndNewCommits() throws Exception {
+ writeFourCommits();
+ StreamTableScan scan = table.newReadBuilder().newStreamScan();
+ scan.restore(1L);
+ assertHistory(table, scan);
+ try (StreamTableWrite write = table.newWrite(commitUser);
+ StreamTableCommit commit =
table.newCommit(commitUser).ignoreEmptyCommit(false)) {
+ write.write(rowData(1, 5, 5L));
+ commit.commit(5, write.prepareCommit(true, 5));
+ }
+ assertThat(getResult(table.newRead(),
scan.plan().splits())).containsExactly("+I 1|5|5");
+ assertThat(scan.checkpoint()).isEqualTo(6L);
+ }
+
+ private void assertExpired(StreamTableScan scan, long nextSnapshot) {
+ assertThatThrownBy(
+ () -> {
+ for (int i = 0; i <
NextSnapshotFetcher.RANGE_CHECK_INTERVAL; i++) {
+ assertThat(scan.plan().splits()).isEmpty();
+ }
+ })
+ .isInstanceOf(OutOfRangeException.class);
+ assertThat(scan.checkpoint()).isEqualTo(nextSnapshot);
+ }
+
+ private void writeFourCommits() throws Exception {
+ try (StreamTableWrite write = table.newWrite(commitUser);
+ StreamTableCommit commit =
table.newCommit(commitUser).ignoreEmptyCommit(false)) {
+ for (int i = 1; i <= 4; i++) {
+ waitForNextCommitMillis();
+ write.write(rowData(1, i, (long) i));
+ commit.commit(i, write.prepareCommit(true, i));
+ }
+ }
+ }
+
+ private void waitForNextCommitMillis() throws InterruptedException {
+ Long latest = table.snapshotManager().latestSnapshotId();
+ if (latest != null) {
+ long previousTime =
table.snapshotManager().snapshot(latest).timeMillis();
+ // Timestamp startup tests require distinct commit times, even on
a fast filesystem.
+ while (System.currentTimeMillis() <= previousTime) {
+ Thread.sleep(1);
+ }
+ }
+ }
+
+ private void expireSnapshots() {
+ table.newExpireSnapshots()
+ .config(
+ ProcedureUtils.fillInSnapshotOptions(
+ table.coreOptions(), 1, null, null,
null)
+ .build())
+ .expire();
+ assertThat(table.snapshotManager().earliestSnapshotId())
+ .isEqualTo(table.snapshotManager().latestSnapshotId());
+ }
+
+ private void assertHistory(FileStoreTable readTable, StreamTableScan scan)
throws Exception {
+ for (int i = 1; i <= 4; i++) {
+ assertThat(getResult(readTable.newRead(), scan.plan().splits()))
+ .containsExactly("+I 1|" + i + "|" + i);
+ }
+ assertThat(scan.checkpoint()).isEqualTo(5L);
+ assertThat(scan.plan().splits()).isEmpty();
+ }
+}
diff --git
a/paimon-core/src/test/java/org/apache/paimon/table/source/snapshot/CreationTimestampStartingScannerTest.java
b/paimon-core/src/test/java/org/apache/paimon/table/source/snapshot/CreationTimestampStartingScannerTest.java
index d7fee6801c..5910193ba4 100644
---
a/paimon-core/src/test/java/org/apache/paimon/table/source/snapshot/CreationTimestampStartingScannerTest.java
+++
b/paimon-core/src/test/java/org/apache/paimon/table/source/snapshot/CreationTimestampStartingScannerTest.java
@@ -40,18 +40,18 @@ public class CreationTimestampStartingScannerTest extends
ScannerTestBase {
write.write(rowData(1, 20, 200L));
write.write(rowData(1, 40, 400L));
- long t1 = System.currentTimeMillis();
commit.commit(0, write.prepareCommit(true, 0));
- long t2 = System.currentTimeMillis();
write.write(rowData(1, 11, 100L));
write.write(rowData(1, 21, 200L));
write.write(rowData(1, 41, 400L));
commit.commit(0, write.prepareCommit(true, 0));
- long t3 = System.currentTimeMillis();
write.close();
commit.close();
+ long t1 = snapshotManager.earliestSnapshot().timeMillis() - 1;
+ long t2 = snapshotManager.earliestSnapshot().timeMillis();
+ long t3 = snapshotManager.latestSnapshot().timeMillis() + 1;
StartingScanner scanner =
createCreationTimestampStartingScanner(
snapshotManager, table.changelogManager(), t1, false,
true);
@@ -86,7 +86,7 @@ public class CreationTimestampStartingScannerTest extends
ScannerTestBase {
snapshotManager.earliestSnapshot().timeMillis(),
true,
true);
- assertThat(scanner instanceof
FileCreationTimeStartingScanner).isTrue();
+ assertThat(scanner instanceof
ContinuousFromSnapshotStartingScanner).isTrue();
scanner =
createCreationTimestampStartingScanner(
snapshotManager,
@@ -94,7 +94,7 @@ public class CreationTimestampStartingScannerTest extends
ScannerTestBase {
snapshotManager.earliestSnapshot().timeMillis(),
false,
false);
- assertThat(scanner instanceof
FileCreationTimeStartingScanner).isTrue();
+ assertThat(scanner instanceof
StaticFromSnapshotStartingScanner).isTrue();
scanner =
createCreationTimestampStartingScanner(
diff --git
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/lookup/LookupDataTableScan.java
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/lookup/LookupDataTableScan.java
index 7356c670f3..1ef632a7bf 100644
---
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/lookup/LookupDataTableScan.java
+++
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/lookup/LookupDataTableScan.java
@@ -84,6 +84,13 @@ public class LookupDataTableScan extends DataTableStreamScan
{
}
}
+ @Override
+ public boolean readRetainedChangelog() {
+ // Lookup scans may need data manifests for file monitoring or
overwrite detection.
+ // Keep their existing discovery rule instead of enabling automatic
changelog discovery.
+ return options().changelogLifecycleDecoupled();
+ }
+
public void setScanPartitions(List<BinaryRow> scanPartitions) {
this.scanPartitions = scanPartitions;
}
diff --git
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/FlinkJobRecoveryITCase.java
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/FlinkJobRecoveryITCase.java
index fdd12ae2a7..75d45fe328 100644
---
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/FlinkJobRecoveryITCase.java
+++
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/FlinkJobRecoveryITCase.java
@@ -18,8 +18,14 @@
package org.apache.paimon.flink;
+import org.apache.paimon.CoreOptions;
import org.apache.paimon.Snapshot;
+import org.apache.paimon.data.GenericRow;
import org.apache.paimon.table.BucketMode;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.sink.StreamTableCommit;
+import org.apache.paimon.table.sink.StreamTableWrite;
+import org.apache.paimon.types.RowKind;
import org.apache.paimon.utils.Pair;
import org.apache.flink.api.common.JobID;
@@ -38,12 +44,14 @@ import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
+import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.assertj.core.api.Assertions.assertThat;
@@ -195,6 +203,107 @@ public class FlinkJobRecoveryITCase extends
CatalogITCaseBase {
StateRecoveryOptions.SAVEPOINT_IGNORE_UNCLAIMED_STATE.key(), "true"));
}
+ @Test
+ @Timeout(180)
+ public void testRestoreCheckpointAfterSnapshotExpiration() throws
Exception {
+ batchSql(
+ "CREATE TABLE retained_source (k INT PRIMARY KEY NOT ENFORCED,
v INT) WITH ("
+ + "'bucket'='1', 'write-only'='true',
'changelog-producer'='input', "
+ + "'snapshot.num-retained.min'='1',
'snapshot.num-retained.max'='4', "
+ + "'changelog.num-retained.max'='4',
'continuous.discovery-interval'='10ms')");
+ // An append sink preserves every change, so duplicates cannot be
hidden by primary keys.
+ batchSql(
+ "CREATE TABLE retained_sink (kind STRING, k INT, v INT) WITH ("
+ + "'bucket'='1', 'bucket-key'='k',
'commit.force-create-snapshot'='true')");
+ FileStoreTable source = paimonTable("retained_source");
+ writeRetainedChanges(source, 1, GenericRow.of(1, 10));
+ Configuration config = sEnv.getConfig().getConfiguration();
+ config.setString(
+ "state.checkpoints.dir", new File(path,
"retained-checkpoints").toURI().toString());
+ config.setString("restart-strategy.type", "none");
+ String query =
+ "INSERT INTO retained_sink SELECT rowkind, k, v FROM
`retained_source$audit_log`";
+ JobClient job = sEnv.executeSql(query).getJobClient().get();
+ try {
+ String checkpoint = triggerCheckpointAndWaitForWrites(job,
"retained_sink", 1);
+ job.cancel().get(30, TimeUnit.SECONDS);
+ job = null;
+ assertThat(batchSql("SELECT * FROM retained_sink"))
+ .containsExactly(Row.of("+I", 1, 10));
+
+ // These changes are committed while the reader is stopped and
cannot be in its state.
+ writeRetainedChanges(
+ source,
+ 2,
+ GenericRow.ofKind(RowKind.UPDATE_BEFORE, 1, 10),
+ GenericRow.ofKind(RowKind.UPDATE_AFTER, 1, 11),
+ GenericRow.of(2, 20));
+ writeRetainedChanges(source, 3, GenericRow.ofKind(RowKind.DELETE,
2, 20));
+ writeRetainedChanges(source, 4, GenericRow.of(3, 30));
+ batchSql(
+ "CALL sys.expire_snapshots(`table` =>
'default.retained_source', retain_max => 1)");
+ FileStoreTable reloaded = paimonTable("retained_source");
+
assertThat(reloaded.snapshotManager().earliestSnapshotId()).isEqualTo(4L);
+
assertThat(reloaded.snapshotManager().snapshotExists(2L)).isFalse();
+
assertThat(reloaded.snapshotManager().snapshotExists(3L)).isFalse();
+
assertThat(reloaded.changelogManager().longLivedChangelogExists(2L)).isTrue();
+
assertThat(reloaded.changelogManager().longLivedChangelogExists(3L)).isTrue();
+
assertThat(reloaded.options().get(CoreOptions.SNAPSHOT_NUM_RETAINED_MAX.key()))
+ .isEqualTo("4");
+
assertThat(reloaded.options().get(CoreOptions.CHANGELOG_NUM_RETAINED_MAX.key()))
+ .isEqualTo("4");
+
assertThat(reloaded.coreOptions().changelogLifecycleDecoupled()).isFalse();
+
+ config.setString("execution.state-recovery.path", checkpoint);
+ job = sEnv.executeSql(query).getJobClient().get();
+ triggerCheckpointAndWaitForWrites(job, "retained_sink", 6);
+ assertThat(batchSql("SELECT * FROM retained_sink"))
+ .containsExactlyInAnyOrder(
+ Row.of("+I", 1, 10),
+ Row.of("-U", 1, 10),
+ Row.of("+U", 1, 11),
+ Row.of("+I", 2, 20),
+ Row.of("-D", 2, 20),
+ Row.of("+I", 3, 30));
+
+ // The restored job must also keep consuming new commits after
catching up.
+ writeRetainedChanges(reloaded, 5, GenericRow.of(4, 40));
+ triggerCheckpointAndWaitForWrites(job, "retained_sink", 7);
+ assertThat(batchSql("SELECT * FROM retained_sink"))
+ .containsExactlyInAnyOrder(
+ Row.of("+I", 1, 10),
+ Row.of("-U", 1, 10),
+ Row.of("+U", 1, 11),
+ Row.of("+I", 2, 20),
+ Row.of("-D", 2, 20),
+ Row.of("+I", 3, 30),
+ Row.of("+I", 4, 40));
+ } catch (Exception e) {
+ if (job != null && job.getJobStatus().get(30, TimeUnit.SECONDS) ==
JobStatus.FAILED) {
+ // Surface the job failure instead of only the subsequent
checkpoint failure.
+ job.getJobExecutionResult().get(30, TimeUnit.SECONDS);
+ }
+ throw e;
+ } finally {
+ config.removeKey("execution.state-recovery.path");
+ if (job != null
+ && !job.getJobStatus().get(30,
TimeUnit.SECONDS).isGloballyTerminalState()) {
+ job.cancel().get(30, TimeUnit.SECONDS);
+ }
+ }
+ }
+
+ private void writeRetainedChanges(FileStoreTable table, long identifier,
GenericRow... rows)
+ throws Exception {
+ try (StreamTableWrite write = table.newWrite("retained-recovery");
+ StreamTableCommit commit =
table.newCommit("retained-recovery")) {
+ for (GenericRow row : rows) {
+ write.write(row);
+ }
+ commit.commit(identifier, write.prepareCommit(true, identifier));
+ }
+ }
+
private void testRecoverFromSavepoint(
String beforeRecoverSql,
String beforeRecoverCheckSql,
diff --git
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/lookup/LookupDataTableScanTest.java
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/lookup/LookupDataTableScanTest.java
new file mode 100644
index 0000000000..6eb408917c
--- /dev/null
+++
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/lookup/LookupDataTableScanTest.java
@@ -0,0 +1,137 @@
+/*
+ * 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.flink.lookup;
+
+import org.apache.paimon.CoreOptions;
+import org.apache.paimon.options.Options;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.FileStoreTableFactory;
+import org.apache.paimon.table.sink.StreamTableCommit;
+import org.apache.paimon.table.sink.StreamTableWrite;
+import org.apache.paimon.table.source.OutOfRangeException;
+import org.apache.paimon.table.source.StreamTableScan;
+import org.apache.paimon.table.source.snapshot.ScannerTestBase;
+import org.apache.paimon.utils.NextSnapshotFetcher;
+import org.apache.paimon.utils.ProcedureUtils;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.Collections;
+
+import static
org.apache.paimon.flink.lookup.LookupFileStoreTable.LookupStreamScanMode.CHANGELOG;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Tests retained-history discovery boundaries for lookup scans. */
+class LookupDataTableScanTest extends ScannerTestBase {
+
+ @Override
+ protected FileStoreTable createFileStoreTable() throws Exception {
+ Options options = new Options();
+ options.set(CoreOptions.WRITE_ONLY, true);
+ options.set(CoreOptions.CHANGELOG_PRODUCER,
CoreOptions.ChangelogProducer.INPUT);
+ options.set(CoreOptions.SNAPSHOT_NUM_RETAINED_MIN, 1);
+ options.set(CoreOptions.SNAPSHOT_NUM_RETAINED_MAX, 4);
+ options.set(CoreOptions.CHANGELOG_NUM_RETAINED_MAX, 4);
+ return createFileStoreTable(options);
+ }
+
+ @Test
+ void testAutomaticLookupFileMonitoringKeepsSnapshotExpiration() throws
Exception {
+ writeFourCommits();
+ expireSnapshots();
+ FileStoreTable reloaded = FileStoreTableFactory.create(fileIO,
tablePath);
+ LookupFileStoreTable lookup = new LookupFileStoreTable(reloaded,
reloaded.primaryKeys());
+ assertExpired(lookup.newStreamScan());
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testLookupChangelogKeepsConfiguredDiscovery(boolean independent)
throws Exception {
+ writeFourCommits();
+ expireSnapshots();
+ FileStoreTable reloaded = FileStoreTableFactory.create(fileIO,
tablePath);
+ if (independent) {
+ reloaded =
+ reloaded.copy(
+ Collections.singletonMap(
+
CoreOptions.CHANGELOG_NUM_RETAINED_MAX.key(), "5"));
+ }
+ StreamTableScan scan = new LookupFileStoreTable(reloaded,
CHANGELOG).newStreamScan();
+ if (independent) {
+ scan.restore(1L);
+ for (int i = 1; i <= 4; i++) {
+ assertThat(getResult(reloaded.newRead(), scan.plan().splits()))
+ .containsExactly("+I 1|" + i + "|" + i);
+ }
+ assertThat(scan.checkpoint()).isEqualTo(5L);
+ } else {
+ assertExpired(scan);
+ }
+ }
+
+ @Test
+ void testLookupFileMonitoringReadsAvailableSnapshots() throws Exception {
+ writeFourCommits();
+ FileStoreTable reloaded = FileStoreTableFactory.create(fileIO,
tablePath);
+ StreamTableScan scan =
+ new LookupFileStoreTable(reloaded,
reloaded.primaryKeys()).newStreamScan();
+ scan.restore(1L);
+ for (int i = 1; i <= 4; i++) {
+ assertThat(getResult(reloaded.newRead(), scan.plan().splits()))
+ .containsExactly("+I 1|" + i + "|" + i);
+ }
+ assertThat(scan.checkpoint()).isEqualTo(5L);
+ }
+
+ private void writeFourCommits() throws Exception {
+ try (StreamTableWrite write = table.newWrite(commitUser);
+ StreamTableCommit commit = table.newCommit(commitUser)) {
+ for (int i = 1; i <= 4; i++) {
+ write.write(rowData(1, i, (long) i));
+ commit.commit(i, write.prepareCommit(true, i));
+ }
+ }
+ }
+
+ private void expireSnapshots() {
+ table.newExpireSnapshots()
+ .config(
+ ProcedureUtils.fillInSnapshotOptions(
+ table.coreOptions(), 1, null, null,
null)
+ .build())
+ .expire();
+ assertThat(table.snapshotManager().earliestSnapshotId()).isEqualTo(4L);
+
assertThat(table.changelogManager().longLivedChangelogExists(1L)).isTrue();
+ }
+
+ private void assertExpired(StreamTableScan scan) {
+ scan.restore(1L);
+ assertThatThrownBy(
+ () -> {
+ for (int i = 0; i <
NextSnapshotFetcher.RANGE_CHECK_INTERVAL; i++) {
+ assertThat(scan.plan().splits()).isEmpty();
+ }
+ })
+ .isInstanceOf(OutOfRangeException.class);
+ assertThat(scan.checkpoint()).isEqualTo(1L);
+ }
+}
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/sources/PaimonMicroBatchStream.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/sources/PaimonMicroBatchStream.scala
index 8ebc613dde..7bc9c12f75 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/sources/PaimonMicroBatchStream.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/sources/PaimonMicroBatchStream.scala
@@ -72,8 +72,8 @@ class PaimonMicroBatchStream(
// It will be reset when there is non-empty PaimonSourceOffset returned by
calling "latestOffset".
var lastTriggerMillis = 0L
- // the latest offset when call "prepareForTriggerAvailableNow"
- // the query will be terminated when data is consumed to this offset in
"TriggerAvailableNow" mode.
+ // The snapshot upper bound captured by prepareForTriggerAvailableNow. Only
actual split
+ // offsets within this bound are returned to Spark.
private var offsetForTriggerAvailableNow: Option[PaimonSourceOffset] = None
private lazy val defaultReadLimit: ReadLimit = {
@@ -123,7 +123,17 @@ class PaimonMicroBatchStream(
override def getDefaultReadLimit: ReadLimit = defaultReadLimit
override def prepareForTriggerAvailableNow(): Unit = {
- offsetForTriggerAvailableNow = getLatestOffset(initOffset, None,
ReadLimit.allAvailable())
+ coreOptions.startupMode() match {
+ case CoreOptions.StartupMode.FROM_TIMESTAMP |
+ CoreOptions.StartupMode.FROM_CREATION_TIMESTAMP =>
+ // Timestamp startup may refer to expired history when restoring a
checkpoint.
+ // Capture the bound now and plan actual offsets from Spark's supplied
start offset.
+ val latestSnapshotId =
Option(table.snapshotManager().latestSnapshotId()).map(_.longValue())
+ offsetForTriggerAvailableNow = Some(
+ PaimonSourceOffset(latestSnapshotId.getOrElse(0L), Long.MaxValue,
scanSnapshot = false))
+ case _ =>
+ offsetForTriggerAvailableNow = getLatestOffset(initOffset, None,
ReadLimit.allAvailable())
+ }
}
override def latestOffset(): Offset = {
@@ -272,7 +282,9 @@ class PaimonMicroBatchStream(
private def earliestReadableId(scanSnapshot: Boolean): Long = {
val earliestId: JLong =
- if (!scanSnapshot && coreOptions.changelogLifecycleDecoupled()) {
+ if (
+ !scanSnapshot && (coreOptions.changelogLifecycleDecoupled() ||
canReadRetainedChangelog)
+ ) {
val earliestChangelogId =
table.changelogManager().earliestLongLivedChangelogId()
if (earliestChangelogId == null) {
table.snapshotManager().earliestSnapshotId()
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/sources/StreamHelper.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/sources/StreamHelper.scala
index c00673009f..0589dc5cd1 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/sources/StreamHelper.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/sources/StreamHelper.scala
@@ -82,6 +82,8 @@ private[spark] trait StreamHelper {
// Used to get the initial offset.
lazy val streamScanStartingContext: StartingContext =
streamScan.startingContext()
+ protected def canReadRetainedChangelog: Boolean =
streamScan.readRetainedChangelog()
+
protected def notifyConsumerCheckpointComplete(nextSnapshot: Long): Unit =
streamScan.notifyCheckpointComplete(nextSnapshot)
diff --git
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/procedure/ExpireSnapshotsProcedureTest.scala
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/procedure/ExpireSnapshotsProcedureTest.scala
index 71c897a632..4734850a84 100644
---
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/procedure/ExpireSnapshotsProcedureTest.scala
+++
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/procedure/ExpireSnapshotsProcedureTest.scala
@@ -31,7 +31,6 @@ import org.apache.spark.sql.streaming.StreamTest
import org.assertj.core.api.Assertions.{assertThat,
assertThatIllegalArgumentException}
import java.sql.Timestamp
-import java.util.Collections
import scala.collection.JavaConverters._
@@ -342,22 +341,11 @@ class ExpireSnapshotsProcedureTest extends
PaimonSparkTestBase with StreamTest {
assert(table.changelogManager().earliestLongLivedChangelogId() == 1L)
assert(table.changelogManager().latestLongLivedChangelogId() == 3L)
assert(readChangelogIds(table, firstChangelog) == List(1))
- // Operation-local overrides do not change the reader's persisted
configuration.
- // Retained history is discovered only when the reader also uses
decoupled retention.
- val reloaded = loadTable("T")
- val readTable = retentionSource match {
- case "dynamic" =>
-
reloaded.copy(Collections.singletonMap("changelog.time-retained", "7 d"))
- case "retain_max" =>
- assert(reloaded.options().get("snapshot.num-retained.max") ==
"4")
- assert(reloaded.options().get("changelog.num-retained.max") ==
"4")
- val coupledScan = reloaded.newReadBuilder().newStreamScan()
- coupledScan.restore(1L)
- // This first plan cannot discover the retained changelog
through coupled options.
- assert(coupledScan.plan().splits().isEmpty)
- assert(readChangelogIds(reloaded, firstChangelog) == List(1))
-
reloaded.copy(Collections.singletonMap("changelog.num-retained.max", "5"))
- case _ => reloaded
+ // Readers discover retained history without repeating
operation-local overrides.
+ val readTable = loadTable("T")
+ if (retentionSource == "retain_max") {
+ assert(readTable.options().get("snapshot.num-retained.max") == "4")
+ assert(readTable.options().get("changelog.num-retained.max") ==
"4")
}
val restored = readTable.newReadBuilder().newStreamScan()
restored.restore(1L)
diff --git
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sources/PaimonMicroBatchStreamITCase.scala
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sources/PaimonMicroBatchStreamITCase.scala
index ca3add928b..c890fe0831 100644
---
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sources/PaimonMicroBatchStreamITCase.scala
+++
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sources/PaimonMicroBatchStreamITCase.scala
@@ -20,13 +20,17 @@ package org.apache.paimon.spark.sources
import org.apache.paimon.CoreOptions
import org.apache.paimon.consumer.Consumer
+import org.apache.paimon.data.GenericRow
import org.apache.paimon.spark.PaimonSparkTestBase
-import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.table.{DataTable, FileStoreTable}
import org.apache.paimon.table.source.OutOfRangeException
+import org.apache.paimon.table.system.AuditLogTable
-import org.apache.spark.sql.Row
+import org.apache.spark.sql.{DataFrame, Row}
import org.apache.spark.sql.connector.read.streaming.ReadLimit
+import org.apache.spark.sql.streaming.Trigger
+import java.io.File
import java.util.{Collections, HashMap}
class PaimonMicroBatchStreamITCase extends PaimonSparkTestBase {
@@ -407,6 +411,262 @@ class PaimonMicroBatchStreamITCase extends
PaimonSparkTestBase {
}
}
+ Seq("table", "audit-path", "audit-catalog").foreach {
+ source =>
+ test(s"Spark $source query discovers retained changelogs without
retention overrides") {
+ withTempDir {
+ checkpointDir =>
+ val sourceTable = createChangelogTable()
+ appendChangelogRows(sourceTable, 1, 4)
+ spark.sql("CALL paimon.sys.expire_snapshots(table => 'test.T',
retain_max => 1)")
+ assert(sourceTable.snapshotManager().earliestSnapshotId() == 4L)
+
assert(sourceTable.changelogManager().earliestLongLivedChangelogId() == 1L)
+ assert(!loadTable("T").coreOptions().changelogLifecycleDecoupled())
+
+ val query = retainedChangelogStream(
+ source,
+ sourceTable,
+ Map(CoreOptions.SCAN_SNAPSHOT_ID.key() -> "1")).writeStream
+ .format("memory")
+ .option("checkpointLocation", checkpointDir.getCanonicalPath)
+ .queryName("retained_changelog_rows")
+ .outputMode("append")
+ .start()
+ try {
+ query.processAllAvailable()
+ checkAnswer(
+ spark.table("retained_changelog_rows"),
+ expectedChangelogRows(source, 1, 4))
+ } finally {
+ query.stop()
+ spark.catalog.dropTempView("retained_changelog_rows")
+ }
+ }
+ }
+
+ test(s"Spark $source query restores retained changelogs from its
checkpoint") {
+ withTempDir {
+ directory =>
+ val sourceTable = createChangelogTable()
+ appendChangelogRows(sourceTable, 1, 1)
+ val checkpoint = new File(directory, "checkpoint").getCanonicalPath
+ val output = new File(directory, "output").getCanonicalPath
+ val writer = retainedChangelogStream(
+ source,
+ sourceTable,
+ Map(CoreOptions.CONSUMER_ID.key() -> consumerId)).writeStream
+ .format("parquet")
+ .option("checkpointLocation", checkpoint)
+ .outputMode("append")
+ val first = writer.start(output)
+ try {
+ first.processAllAvailable()
+ checkAnswer(spark.read.parquet(output),
expectedChangelogRows(source, 1, 1))
+ } finally {
+ first.stop()
+ }
+ appendChangelogRows(sourceTable, 2, 4)
+ spark.sql("CALL paimon.sys.expire_snapshots(table => 'test.T',
retain_max => 1)")
+ assert(sourceTable.snapshotManager().earliestSnapshotId() == 4L)
+ assert(sourceTable.changelogManager().longLivedChangelogExists(2L))
+ assert(!loadTable("T").coreOptions().changelogLifecycleDecoupled())
+
+ val restarted = writer.start(output)
+ try {
+ restarted.processAllAvailable()
+ checkAnswer(spark.read.parquet(output),
expectedChangelogRows(source, 1, 4))
+ } finally {
+ restarted.stop()
+ }
+ }
+ }
+
+ }
+
+ for {
+ timestampOption <- Seq(CoreOptions.SCAN_TIMESTAMP_MILLIS,
CoreOptions.SCAN_CREATION_TIME_MILLIS)
+ availableNow <- Seq(false, true)
+ } {
+ test(
+ s"restore after timestamp history expires (${timestampOption.key()},
availableNow=$availableNow)") {
+ withTempDir {
+ directory =>
+ val sourceTable = createChangelogTable()
+ appendChangelogRows(sourceTable, 1, 4)
+ spark.sql("CALL paimon.sys.expire_snapshots(table => 'test.T',
retain_max => 1)")
+ appendChangelogRows(sourceTable, 5, 6)
+ val timestamp =
sourceTable.snapshotManager().snapshot(5L).timeMillis()
+ val checkpoint = new File(directory, "checkpoint").getCanonicalPath
+ val output = new File(directory, "output").getCanonicalPath
+ val writer = retainedChangelogStream(
+ "table",
+ sourceTable,
+ Map(timestampOption.key() -> timestamp.toString)).writeStream
+ .format("parquet")
+ .option("checkpointLocation", checkpoint)
+ .outputMode("append")
+ if (availableNow) {
+ writer.trigger(Trigger.AvailableNow())
+ }
+ val first = writer.start(output)
+ try {
+ if (availableNow) {
+ assert(first.awaitTermination(60000L))
+ } else {
+ first.processAllAvailable()
+ }
+ checkAnswer(spark.read.parquet(output),
expectedChangelogRows("table", 5, 6))
+ } finally {
+ first.stop()
+ }
+
+ appendChangelogRows(sourceTable, 7, 8)
+
sourceTable.newExpireSnapshots().config(sourceTable.coreOptions().expireConfig()).expire()
+ assert(!sourceTable.snapshotManager().snapshotExists(4L))
+ assert(!sourceTable.changelogManager().longLivedChangelogExists(4L))
+ assert(sourceTable.changelogManager().longLivedChangelogExists(3L))
+ // Keep the saved position readable only through changelog metadata
as well.
+ spark.sql("CALL paimon.sys.expire_snapshots(table => 'test.T',
retain_max => 1)")
+ assert(!sourceTable.snapshotManager().snapshotExists(7L))
+ assert(sourceTable.changelogManager().longLivedChangelogExists(7L))
+ assert(!loadTable("T").coreOptions().changelogLifecycleDecoupled())
+ val readTable =
+
loadTable("T").copy(Collections.singletonMap(timestampOption.key(),
timestamp.toString))
+ intercept[OutOfRangeException] {
+ readTable.newStreamScan().plan()
+ }
+
+ val restarted = writer.start(output)
+ try {
+ if (availableNow) {
+ assert(restarted.awaitTermination(60000L))
+ } else {
+ restarted.processAllAvailable()
+ }
+ // The same checkpoint must resume at 7 without replaying 5 or 6.
+ checkAnswer(spark.read.parquet(output),
expectedChangelogRows("table", 5, 8))
+ } finally {
+ restarted.stop()
+ }
+ }
+ }
+ }
+
+ test("AvailableNow keeps its full startup snapshot when a new commit
arrives") {
+ val sourceTable = createChangelogTable()
+ appendChangelogRows(sourceTable, 1, 4)
+ val stream = createStream(sourceTable)
+ // Spark prepares AvailableNow before asking for the initial offset of a
fresh query.
+ stream.prepareForTriggerAvailableNow()
+ appendChangelogRows(sourceTable, 5, 5)
+ val initial = stream.initialOffset().asInstanceOf[PaimonSourceOffset]
+ assert(initial.snapshotId == 4L)
+ assert(initial.scanSnapshot)
+ val end = latestOffset(stream, initial, ReadLimit.allAvailable())
+ assert(end.snapshotId == 4L)
+ assert(stream.planInputPartitions(initial, end).nonEmpty)
+ }
+
+ Seq(false, true).foreach {
+ initiallyEmpty =>
+ test(s"AvailableNow excludes commits after preparation
(initiallyEmpty=$initiallyEmpty)") {
+ val sourceTable = createChangelogTable()
+ if (!initiallyEmpty) {
+ appendChangelogRows(sourceTable, 1, 4)
+ }
+ val stream = createStream(
+
sourceTable.copy(Collections.singletonMap(CoreOptions.SCAN_TIMESTAMP_MILLIS.key(),
"0")))
+ var offset = stream.initialOffset().asInstanceOf[PaimonSourceOffset]
+ stream.prepareForTriggerAvailableNow()
+ val nextId = if (initiallyEmpty) 1 else 5
+ appendChangelogRows(sourceTable, nextId, nextId)
+ if (!initiallyEmpty) {
+ (1 to 4).foreach {
+ id =>
+ val next = latestOffset(stream, offset, ReadLimit.maxFiles(1))
+ assert(next.snapshotId == id.toLong)
+ assert(stream.planInputPartitions(offset, next).length == 1)
+ offset = next
+ }
+ }
+ assert(stream.latestOffset(offset, ReadLimit.allAvailable()) == null)
+ }
+ }
+
+ Seq(false, true).foreach {
+ audit =>
+ test(
+ s"retained changelogs do not replace full or overwrite startup
snapshots (audit=$audit)") {
+ val table = createChangelogTable()
+ appendChangelogRows(table, 1, 4)
+ spark.sql("CALL paimon.sys.expire_snapshots(table => 'test.T',
retain_max => 1)")
+ val readTable = loadTable("T")
+ val fullSource: DataTable = if (audit) new AuditLogTable(readTable)
else readTable
+ val full =
createStream(fullSource).initialOffset().asInstanceOf[PaimonSourceOffset]
+ assert(full.snapshotId == 4L)
+ assert(full.scanSnapshot)
+ val options = new HashMap[String, String]()
+ options.put(CoreOptions.SCAN_SNAPSHOT_ID.key(), "1")
+ options.put(CoreOptions.STREAMING_READ_OVERWRITE.key(), "true")
+ val overwriteTable = readTable.copy(options)
+ val overwriteSource: DataTable =
+ if (audit) new AuditLogTable(overwriteTable) else overwriteTable
+ val overwrite =
+
createStream(overwriteSource).initialOffset().asInstanceOf[PaimonSourceOffset]
+ assert(overwrite.snapshotId == 4L)
+ assert(!overwrite.scanSnapshot)
+ }
+
+ }
+
+ private def retainedChangelogStream(
+ source: String,
+ table: FileStoreTable,
+ options: Map[String, String]): DataFrame = {
+ val reader = spark.readStream.format("paimon").options(options)
+ source match {
+ case "audit-path" => reader.option("read.changelog",
"true").load(table.location().toString)
+ case "audit-catalog" => reader.table("`T$audit_log`")
+ case _ => reader.load(table.location().toString)
+ }
+ }
+
+ private def expectedChangelogRows(source: String, from: Int, last: Int):
Seq[Row] = {
+ (from to last).map(i => if (source == "table") Row(i, i * 10) else
Row("+I", i, i * 10))
+ }
+
+ private def createChangelogTable(): FileStoreTable = {
+ spark.sql("""CREATE TABLE T (a INT, b INT) TBLPROPERTIES (
+ |'primary-key' = 'a', 'bucket' = '1', 'write-only' = 'true',
+ |'changelog-producer' = 'input', 'snapshot.num-retained.min' =
'1',
+ |'snapshot.num-retained.max' = '4',
'changelog.num-retained.max' = '4',
+ |'consumer.changelog-only' = 'true')""".stripMargin)
+ loadTable("T")
+ }
+
+ private def appendChangelogRows(table: FileStoreTable, from: Int, last:
Int): Unit = {
+ val builder =
table.newStreamWriteBuilder().withCommitUser("retained-changelog-test")
+ val writer = builder.newWrite()
+ val commit = builder.newCommit()
+ try {
+ (from to last).foreach {
+ i =>
+ Option(table.snapshotManager().latestSnapshotId()).foreach {
+ latest =>
+ val previousTime =
table.snapshotManager().snapshot(latest).timeMillis()
+ while (System.currentTimeMillis() <= previousTime) {
+ Thread.sleep(1L)
+ }
+ }
+ writer.write(GenericRow.of(Int.box(i), Int.box(i * 10)))
+ commit.commit(i.toLong, writer.prepareCommit(true, i.toLong))
+ }
+ } finally {
+ writer.close()
+ commit.close()
+ }
+ }
+
private def createTableWithOneSnapshot(): FileStoreTable = {
createTableWithoutSnapshot()
spark.sql("INSERT INTO T VALUES (10, 'v_10'), (11, 'v_11'), (12, 'v_12')")
@@ -428,7 +688,7 @@ class PaimonMicroBatchStreamITCase extends
PaimonSparkTestBase {
table.copy(Collections.singletonMap(CoreOptions.CONSUMER_ID.key(),
consumerId))
}
- private def createStream(table: FileStoreTable): PaimonMicroBatchStream = {
+ private def createStream(table: DataTable): PaimonMicroBatchStream = {
new PaimonMicroBatchStream(table, table.newReadBuilder(), "unused")
}