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 ed0bac7d3d [common] Honor changelog retention when expiring snapshots
(#10928)
ed0bac7d3d is described below
commit ed0bac7d3d53baca2e067fe50e5c2cc9a28165ba
Author: csurong <[email protected]>
AuthorDate: Mon Nov 2 22:43:50 2026 +0800
[common] Honor changelog retention when expiring snapshots (#10928)
---
docs/docs/maintenance/manage-snapshots.mdx | 12 ++-
.../org/apache/paimon/utils/ProcedureUtils.java | 16 ++++
...SnapshotChangelogRetentionVerificationTest.java | 105 ++++++++++++++++++++
.../procedure/ExpireSnapshotsProcedureITCase.java | 87 +++++++++++++++++
.../procedure/ExpireSnapshotsProcedureTest.scala | 106 +++++++++++++++++++++
5 files changed, 325 insertions(+), 1 deletion(-)
diff --git a/docs/docs/maintenance/manage-snapshots.mdx
b/docs/docs/maintenance/manage-snapshots.mdx
index 656a8a76ee..d8d2e6d5b7 100644
--- a/docs/docs/maintenance/manage-snapshots.mdx
+++ b/docs/docs/maintenance/manage-snapshots.mdx
@@ -242,7 +242,17 @@ batch mode, it is not recommended to use asynchronous
expiration mode, as the ex
may fail to complete successfully.
## Manually expire snapshot
-Manually expire a table's snapshots
+Manually expire a table's snapshots.
+
+Retention overrides such as `retain_max` and dynamic `options` apply only to
that expiration
+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.
+
<Tabs groupId="manually-expire-snapshot">
<TabItem value="flink-sql" label="Flink SQL">
diff --git
a/paimon-common/src/main/java/org/apache/paimon/utils/ProcedureUtils.java
b/paimon-common/src/main/java/org/apache/paimon/utils/ProcedureUtils.java
index 9e4f966beb..e88bcdb582 100644
--- a/paimon-common/src/main/java/org/apache/paimon/utils/ProcedureUtils.java
+++ b/paimon-common/src/main/java/org/apache/paimon/utils/ProcedureUtils.java
@@ -86,6 +86,22 @@ public class ProcedureUtils {
.snapshotMaxDeletes(
Optional.ofNullable(maxDeletes).orElse(tableOptions.snapshotExpireLimit()))
.snapshotTimeRetain(tableOptions.snapshotTimeRetain());
+ // Unset changelog options must follow the effective snapshot options,
including overrides.
+ builder.changelogRetainMin(
+ tableOptions
+ .toConfiguration()
+
.getOptional(CoreOptions.CHANGELOG_NUM_RETAINED_MIN)
+ .orElse(null))
+ .changelogRetainMax(
+ tableOptions
+ .toConfiguration()
+
.getOptional(CoreOptions.CHANGELOG_NUM_RETAINED_MAX)
+ .orElse(null))
+ .changelogTimeRetain(
+ tableOptions
+ .toConfiguration()
+
.getOptional(CoreOptions.CHANGELOG_TIME_RETAINED)
+ .orElse(null));
if (!StringUtils.isNullOrWhitespaceOnly(olderThanStr)) {
long olderThanMills =
DateTimeUtils.parseTimestampData(olderThanStr, 3,
TimeZone.getDefault())
diff --git
a/paimon-common/src/test/java/org/apache/paimon/utils/SnapshotChangelogRetentionVerificationTest.java
b/paimon-common/src/test/java/org/apache/paimon/utils/SnapshotChangelogRetentionVerificationTest.java
new file mode 100644
index 0000000000..3f57cd4df8
--- /dev/null
+++
b/paimon-common/src/test/java/org/apache/paimon/utils/SnapshotChangelogRetentionVerificationTest.java
@@ -0,0 +1,105 @@
+/*
+ * 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.utils;
+
+import org.apache.paimon.CoreOptions;
+import org.apache.paimon.options.ExpireConfig;
+import org.apache.paimon.options.Options;
+
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.sql.Timestamp;
+import java.time.Duration;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Verifies snapshot procedure retention against the table expiration
configuration. */
+class SnapshotChangelogRetentionVerificationTest {
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testChangelogRetention(boolean independent) {
+ Options options = new Options();
+ options.setString("snapshot.num-retained.min", "1");
+ options.setString("snapshot.num-retained.max", "100");
+ options.setString("snapshot.time-retained", "2 s");
+ if (independent) {
+ options.setString("changelog.time-retained", "7 d");
+ }
+ CoreOptions table = new CoreOptions(options);
+ ExpireConfig expected = table.expireConfig();
+ ExpireConfig actual =
+ ProcedureUtils.fillInSnapshotOptions(table, null, null, null,
null).build();
+ assertThat(expected.getChangelogTimeRetain())
+ .isEqualTo(independent ? Duration.ofDays(7) :
Duration.ofSeconds(2));
+
assertThat(actual.getChangelogTimeRetain()).isEqualTo(expected.getChangelogTimeRetain());
+
assertThat(actual.isChangelogDecoupled()).isEqualTo(expected.isChangelogDecoupled());
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "changelog.num-retained.min, 10",
+ "changelog.num-retained.max, 1000",
+ "changelog.time-retained, 7 d"
+ })
+ void testPartialChangelogOptionsWithOverrides(String key, String value) {
+ Options options = new Options();
+ options.setString(key, value);
+ ExpireConfig config =
+ ProcedureUtils.fillInSnapshotOptions(new CoreOptions(options),
3, 1, null, 2)
+ .build();
+ assertThat(config.isChangelogDecoupled()).isTrue();
+ assertThat(config.getSnapshotRetainMax()).isEqualTo(3);
+ assertThat(config.getSnapshotRetainMin()).isEqualTo(1);
+ assertThat(config.getSnapshotMaxDeletes()).isEqualTo(2);
+ assertThat(config.getChangelogRetainMax())
+ .isEqualTo(key.equals("changelog.num-retained.max") ? 1000 :
3);
+ assertThat(config.getChangelogRetainMin())
+ .isEqualTo(key.equals("changelog.num-retained.min") ? 10 : 1);
+ assertThat(config.getChangelogTimeRetain())
+ .isEqualTo(
+ key.equals("changelog.time-retained")
+ ? Duration.ofDays(7)
+ : config.getSnapshotTimeRetain());
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testOlderThanOverride(boolean independent) {
+ Options options = new Options();
+ if (independent) {
+ options.setString("changelog.time-retained", "7 d");
+ }
+ long cutoff = System.currentTimeMillis() -
Duration.ofHours(1).toMillis();
+ long before = System.currentTimeMillis();
+ ExpireConfig config =
+ ProcedureUtils.fillInSnapshotOptions(
+ new CoreOptions(options), 3, 1, new
Timestamp(cutoff).toString(), 2)
+ .build();
+ assertThat(config.getSnapshotTimeRetain().toMillis())
+ .isBetween(before - cutoff, System.currentTimeMillis() -
cutoff);
+ assertThat(config.getChangelogTimeRetain())
+ .isEqualTo(independent ? Duration.ofDays(7) :
config.getSnapshotTimeRetain());
+ assertThat(config.getChangelogRetainMax()).isEqualTo(3);
+ assertThat(config.getChangelogRetainMin()).isEqualTo(1);
+ assertThat(config.getChangelogMaxDeletes()).isEqualTo(2);
+ assertThat(config.isChangelogDecoupled()).isEqualTo(independent);
+ }
+}
diff --git
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/procedure/ExpireSnapshotsProcedureITCase.java
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/procedure/ExpireSnapshotsProcedureITCase.java
index 0c590510ab..35edfd0af6 100644
---
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/procedure/ExpireSnapshotsProcedureITCase.java
+++
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/procedure/ExpireSnapshotsProcedureITCase.java
@@ -18,20 +18,34 @@
package org.apache.paimon.flink.procedure;
+import org.apache.paimon.data.GenericRow;
+import org.apache.paimon.data.InternalRow;
import org.apache.paimon.flink.CatalogITCaseBase;
import org.apache.paimon.flink.action.ActionBase;
import org.apache.paimon.flink.action.ActionFactory;
import org.apache.paimon.flink.action.ExpireSnapshotsAction;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.io.DataFileMeta;
+import org.apache.paimon.reader.RecordReader;
import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.sink.StreamTableCommit;
+import org.apache.paimon.table.sink.StreamTableWrite;
+import org.apache.paimon.table.sink.StreamWriteBuilder;
+import org.apache.paimon.table.source.DataSplit;
+import org.apache.paimon.table.source.Split;
+import org.apache.paimon.table.source.StreamTableScan;
import org.apache.paimon.utils.SnapshotManager;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
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.ValueSource;
import java.io.IOException;
import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@@ -205,6 +219,79 @@ public class ExpireSnapshotsProcedureITCase extends
CatalogITCaseBase {
checkSnapshots(snapshotManager, 3, 6);
}
+ @ParameterizedTest
+ @CsvSource({"false, false", "false, true", "true, false", "true, true"})
+ public void testChangelogRetention(boolean useAction, boolean
independentRetention)
+ throws Exception {
+ sql(
+ "CREATE TABLE changelog_retention (id 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' = '1'"
+ + (independentRetention ? ", 'changelog.time-retained'
= '7 d'" : "")
+ + ")");
+ FileStoreTable table = paimonTable("changelog_retention");
+ StreamWriteBuilder builder =
table.newStreamWriteBuilder().withCommitUser("test");
+ try (StreamTableWrite write = builder.newWrite();
+ StreamTableCommit commit = builder.newCommit()) {
+ for (int i = 1; i <= 4; i++) {
+ write.write(GenericRow.of(i, i * 10));
+ commit.commit(i, write.prepareCommit(true, i));
+ }
+ }
+ checkSnapshots(table.snapshotManager(), 1, 4);
+ StreamTableScan scan = table.newReadBuilder().newStreamScan();
+ scan.restore(1L);
+ List<Split> firstChangelog = scan.plan().splits();
+ assertThat(readIds(table, firstChangelog)).containsExactly(1);
+ if (useAction) {
+ createAction(
+ ExpireSnapshotsAction.class,
+ "expire_snapshots",
+ "--warehouse",
+ path,
+ "--database",
+ "default",
+ "--table",
+ "changelog_retention")
+ .run();
+ } else {
+ sql("CALL sys.expire_snapshots(`table` =>
'default.changelog_retention')");
+ }
+ checkSnapshots(table.snapshotManager(), 4, 4);
+ for (Split split : firstChangelog) {
+ DataSplit dataSplit = (DataSplit) split;
+ for (DataFileMeta file : dataSplit.dataFiles()) {
+ assertThat(table.fileIO().exists(new
Path(dataSplit.bucketPath(), file.fileName())))
+ .isEqualTo(independentRetention);
+ }
+ }
+ if (independentRetention) {
+
assertThat(table.changelogManager().earliestLongLivedChangelogId()).isEqualTo(1);
+
assertThat(table.changelogManager().latestLongLivedChangelogId()).isEqualTo(3);
+ assertThat(readIds(table, firstChangelog)).containsExactly(1);
+ // Re-plan after expiration to verify retained metadata as well as
data files.
+ StreamTableScan restored = table.newReadBuilder().newStreamScan();
+ restored.restore(1L);
+ for (int i = 1; i <= 4; i++) {
+ assertThat(readIds(table,
restored.plan().splits())).containsExactly(i);
+ }
+ } else {
+
assertThat(table.changelogManager().safelyGetAllChangelogs()).isEmpty();
+ }
+ assertThat(readIds(table,
table.newReadBuilder().newScan().plan().splits()))
+ .containsExactlyInAnyOrder(1, 2, 3, 4);
+ }
+
+ private List<Integer> readIds(FileStoreTable table, List<Split> splits)
throws IOException {
+ List<Integer> ids = new ArrayList<>();
+ try (RecordReader<InternalRow> reader =
+ table.newReadBuilder().newRead().createReader(splits)) {
+ reader.forEachRemaining(row -> ids.add(row.getInt(0)));
+ }
+ return ids;
+ }
+
protected void checkSnapshots(SnapshotManager sm, int earliest, int
latest) throws IOException {
assertThat(sm.snapshotCount()).isEqualTo(latest - earliest + 1);
assertThat(sm.earliestSnapshotId()).isEqualTo(earliest);
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 510c74bded..71c897a632 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
@@ -18,7 +18,11 @@
package org.apache.paimon.spark.procedure
+import org.apache.paimon.data.GenericRow
+import org.apache.paimon.fs.Path
import org.apache.paimon.spark.PaimonSparkTestBase
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.table.source.{DataSplit, Split}
import org.apache.paimon.utils.SnapshotManager
import org.apache.spark.sql.{Dataset, Row}
@@ -27,6 +31,9 @@ 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._
class ExpireSnapshotsProcedureTest extends PaimonSparkTestBase with StreamTest
{
@@ -276,6 +283,105 @@ class ExpireSnapshotsProcedureTest extends
PaimonSparkTestBase with StreamTest {
}
}
+ Seq("none", "table", "dynamic", "retain_max").foreach {
+ retentionSource =>
+ test(s"Paimon Procedure: expire snapshots changelog retention from
$retentionSource") {
+ val independent = retentionSource != "none"
+ val snapshotRetainMax = if (retentionSource == "retain_max") 4 else 1
+ val tableRetention = retentionSource match {
+ case "table" => ", 'changelog.time-retained' = '7 d'"
+ case "retain_max" => ", 'changelog.num-retained.max' = '4'"
+ case _ => ""
+ }
+ 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', " +
+ s"'snapshot.num-retained.max' = '$snapshotRetainMax'" +
tableRetention + ")")
+ val table = loadTable("T")
+ val builder = table.newStreamWriteBuilder().withCommitUser("test")
+ val writer = builder.newWrite()
+ val commit = builder.newCommit()
+ try {
+ (1 to 4).foreach {
+ i =>
+ 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()
+ }
+ checkSnapshots(table.snapshotManager(), 1, 4)
+ val scan = table.newReadBuilder().newStreamScan()
+ scan.restore(1L)
+ val firstChangelog = scan.plan().splits()
+ assert(readChangelogIds(table, firstChangelog) == List(1))
+
+ val procedureArgs = retentionSource match {
+ case "dynamic" => ", options => 'changelog.time-retained=7 d'"
+ case "retain_max" => ", retain_max => 1"
+ case _ => ""
+ }
+ checkAnswer(
+ spark.sql(s"CALL paimon.sys.expire_snapshots(table =>
'test.T'$procedureArgs)"),
+ Row(3) :: Nil)
+ checkSnapshots(table.snapshotManager(), 4, 4)
+ firstChangelog.asScala.foreach {
+ split =>
+ val dataSplit = split.asInstanceOf[DataSplit]
+ dataSplit.dataFiles().asScala.foreach {
+ file =>
+ assert(
+ table
+ .fileIO()
+ .exists(new Path(dataSplit.bucketPath(), file.fileName()))
== independent)
+ }
+ }
+ if (independent) {
+ 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
+ }
+ val restored = readTable.newReadBuilder().newStreamScan()
+ restored.restore(1L)
+ (1 to 4).foreach(
+ i => assert(readChangelogIds(readTable, restored.plan().splits())
== List(i)))
+ } else {
+ assert(table.changelogManager().safelyGetAllChangelogs().isEmpty)
+ }
+ if (retentionSource == "dynamic") {
+
assert(!loadTable("T").options().containsKey("changelog.time-retained"))
+ }
+ checkAnswer(sql("SELECT * FROM T"), (1 to 4).map(i => Row(i, i * 10)))
+ }
+ }
+
+ private def readChangelogIds(table: FileStoreTable, splits:
java.util.List[Split]): List[Int] = {
+ val iter =
table.newReadBuilder().newRead().createReader(splits).toCloseableIterator()
+ try {
+ iter.asScala.map(_.getInt(0)).toList
+ } finally {
+ iter.close()
+ }
+ }
+
def checkSnapshots(sm: SnapshotManager, earliest: Int, latest: Int): Unit = {
assertThat(sm.snapshotCount).isEqualTo(latest - earliest + 1)
assertThat(sm.earliestSnapshotId).isEqualTo(earliest)