You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@paimon.apache.org by "wzhero1 (via GitHub)" <gi...@apache.org> on 2026/01/13 10:04:18 UTC
[PR] [flink] Support parallelism snapshot expire [paimon]
wzhero1 opened a new pull request, #7027:
URL: https://github.com/apache/paimon/pull/7027
### Purpose
<!-- What is the purpose of the change -->
This PR implements parallel snapshot expiration to improve the performance of large-scale cleanup operations.
**Motivation:**
- Serial file deletion becomes a performance bottleneck for tables with large amounts of data
- Current implementation cannot leverage Flink's distributed computing capabilities
**Changes:**
1. **Core module refactoring** - Split the original serial expiration logic into Planner/Executor architecture:
- [ExpireSnapshotsPlanner](cci:2://file:///Users/steven/code/gitspace/paimon/paimon-core/src/main/java/org/apache/paimon/operation/expire/ExpireSnapshotsPlanner.java:57:0-280:1): Computes expiration plan including snapshot range and four types of tasks
- [ExpireSnapshotsExecutor](cci:2://file:///Users/steven/code/gitspace/paimon/paimon-core/src/main/java/org/apache/paimon/operation/expire/ExpireSnapshotsExecutor.java:56:0-231:1): Executes deletion tasks based on task type
- [ExpireSnapshotsPlan](cci:2://file:///Users/steven/code/gitspace/paimon/paimon-core/src/main/java/org/apache/paimon/operation/expire/ExpireSnapshotsPlan.java:39:0-217:1): Data structure containing task lists and protection set
- [SnapshotExpireTask](cci:2://file:///Users/steven/code/gitspace/paimon/paimon-core/src/main/java/org/apache/paimon/operation/expire/SnapshotExpireTask.java:42:0-135:1): Represents a single expiration task with `TaskType` enum
- [ProtectionSet](cci:2://file:///Users/steven/code/gitspace/paimon/paimon-core/src/main/java/org/apache/paimon/operation/expire/ProtectionSet.java:37:0-62:1): Immutable set of protected manifests and tagged snapshots
- [DeletionReport](cci:2://file:///Users/steven/code/gitspace/paimon/paimon-core/src/main/java/org/apache/paimon/operation/expire/DeletionReport.java:28:0-125:1): Execution report for each task
2. **Flink Action parallel mode** - [ExpireSnapshotsAction](cci:2://file:///Users/steven/code/gitspace/paimon/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/ExpireSnapshotsAction.java:66:0-263:1) supports `--parallelism` parameter:
- **Worker Phase**: Parallel deletion of data files and changelog files using [RangePartitionedExpireFunction](cci:2://file:///Users/steven/code/gitspace/paimon/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/expire/RangePartitionedExpireFunction.java:53:0-109:1)
- **Sink Phase**: Serial deletion of manifests and snapshot metadata using [SnapshotExpireSink](cci:2://file:///Users/steven/code/gitspace/paimon/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/expire/SnapshotExpireSink.java:59:0-173:1)
- Tasks are partitioned by snapshot ID range to maximize cache locality
**Execution modes:**
- Serial mode (default): `parallelism=null or ≤1` → Uses `ExpireSnapshotsImpl`
- Parallel mode: `parallelism>1 + --force_start_flink_job` → Uses Flink distributed execution
### Tests
<!-- List UT and IT cases to verify this change -->
**Unit Tests:**
- `ExpireSnapshotsPlanTest` - Tests task partitioning logic ([partitionTasksBySnapshotRange](cci:1://file:///Users/steven/code/gitspace/paimon/paimon-core/src/main/java/org/apache/paimon/operation/expire/ExpireSnapshotsPlan.java:109:4-184:5))
- `DeletionReportTest` - Tests deletion report serialization
- `ExpireSnapshotsTest` - Core expiration logic tests (refactored to use new Planner/Executor)
**Integration Tests:**
- `ExpireSnapshotsActionITCase` - Flink parallel mode integration tests
- `ExpireSnapshotsProcedureITCase` - Procedure integration tests
### API and Format
<!-- Does this change affect API or storage format -->
**New CLI parameters for `expire-snapshots` action:**
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `--parallelism` | Integer | null | Parallelism for parallel mode (requires >1) |
**No storage format changes.**
**Backward compatible:** Default behavior (serial mode) remains unchanged.
### Documentation
<!-- Does this change introduce a new feature -->
Yes, this introduces a new feature: parallel snapshot expiration.
Documentation should be added to describe:
- New `--parallelism` parameter for `expire-snapshots` action
- Requirement: parallel mode needs both `--parallelism > 1` and `--force_start_flink_job`
- Performance recommendations for large-scale cleanup
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r2922784732
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/expire/SnapshotExpireSink.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.expire;
+
+import org.apache.paimon.annotation.VisibleForTesting;
+import org.apache.paimon.catalog.Catalog;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.flink.FlinkCatalogFactory;
+import org.apache.paimon.operation.expire.DeletionReport;
+import org.apache.paimon.operation.expire.ExpireSnapshotsExecutor;
+import org.apache.paimon.operation.expire.SnapshotExpireTask;
+import org.apache.paimon.options.Options;
+import org.apache.paimon.table.FileStoreTable;
+
+import org.apache.flink.api.connector.sink2.InitContext;
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.api.connector.sink2.SinkWriter;
+import org.apache.flink.api.connector.sink2.WriterInitContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Sink that collects deletion reports from parallel expire workers, aggregates the results, and
+ * performs the final commit operations using Sink V2 API.
+ *
+ * <p>In the sink phase (committer), this sink:
+ *
+ * <ul>
+ * <li>Collects all deletion reports from workers
+ * <li>Deletes manifest files serially in snapshot ID order (to avoid concurrent deletion issues)
+ * <li>Deletes snapshot metadata files
+ * <li>Commits changelogs (for changelogDecoupled mode)
+ * <li>Cleans empty directories
+ * <li>Updates earliest hint
+ * </ul>
+ */
+public class SnapshotExpireSink implements Sink<DeletionReport> {
+
+ private static final long serialVersionUID = 1L;
+
+ private static final Logger LOG = LoggerFactory.getLogger(SnapshotExpireSink.class);
+
+ private final Map<String, String> catalogConfig;
+ private final Identifier identifier;
+ private final long endExclusiveId;
+ private final Set<String> manifestSkippingSet;
+ private final List<SnapshotExpireTask> manifestTasks;
+ private final List<SnapshotExpireTask> snapshotFileTasks;
+
+ public SnapshotExpireSink(
+ Map<String, String> catalogConfig,
+ Identifier identifier,
+ long endExclusiveId,
+ Set<String> manifestSkippingSet,
+ List<SnapshotExpireTask> manifestTasks,
+ List<SnapshotExpireTask> snapshotFileTasks) {
+ this.catalogConfig = catalogConfig;
+ this.identifier = identifier;
+ this.endExclusiveId = endExclusiveId;
+ this.manifestSkippingSet = manifestSkippingSet;
+ this.manifestTasks = manifestTasks;
+ this.snapshotFileTasks = snapshotFileTasks;
+ }
+
+ /**
+ * Do not annotate with <code>@override</code> here to maintain compatibility with Flink 2.0+.
+ */
+ public SinkWriter<DeletionReport> createWriter(InitContext context) throws IOException {
+ return new ExpireSinkWriter(initExecutor());
+ }
+
+ @Override
Review Comment:
done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r3013717929
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/expire/ExpireSnapshotsPlanner.java:
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.expire;
+
+import org.apache.paimon.Snapshot;
+import org.apache.paimon.annotation.VisibleForTesting;
+import org.apache.paimon.consumer.ConsumerManager;
+import org.apache.paimon.operation.SnapshotDeletion;
+import org.apache.paimon.options.ExpireConfig;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.utils.Preconditions;
+import org.apache.paimon.utils.SnapshotManager;
+import org.apache.paimon.utils.TagManager;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executor;
+
+import static org.apache.paimon.utils.SnapshotManager.findPreviousOrEqualSnapshot;
+import static org.apache.paimon.utils.SnapshotManager.findPreviousSnapshot;
+
+/**
+ * Planner for snapshot expiration. This class computes the expiration plan including:
+ *
+ * <ul>
+ * <li>The range of snapshots to expire [beginInclusiveId, endExclusiveId)
+ * <li>Protection set containing manifests that should not be deleted
+ * <li>Four groups of tasks organized by deletion phase
+ * </ul>
+ *
+ * <p>Tag data files are loaded on-demand by workers using {@link
+ * SnapshotDeletion#createDataFileSkipperForTags}, which has internal caching to avoid repeated
+ * reads.
+ */
+public class ExpireSnapshotsPlanner {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ExpireSnapshotsPlanner.class);
+
+ private final SnapshotManager snapshotManager;
+ private final ConsumerManager consumerManager;
+ private final SnapshotDeletion snapshotDeletion;
+ private final TagManager tagManager;
+
+ public ExpireSnapshotsPlanner(
+ SnapshotManager snapshotManager,
+ ConsumerManager consumerManager,
+ SnapshotDeletion snapshotDeletion,
+ TagManager tagManager) {
+ this.snapshotManager = snapshotManager;
+ this.consumerManager = consumerManager;
+ this.snapshotDeletion = snapshotDeletion;
+ this.tagManager = tagManager;
+ }
+
+ /** Creates an ExpireSnapshotsPlanner from a FileStoreTable. */
+ public static ExpireSnapshotsPlanner create(FileStoreTable table) {
+ SnapshotManager snapshotManager = table.snapshotManager();
+ ConsumerManager consumerManager =
+ new ConsumerManager(table.fileIO(), table.location(), snapshotManager.branch());
+ return new ExpireSnapshotsPlanner(
+ table.snapshotManager(),
+ consumerManager,
+ table.store().newSnapshotDeletion(),
+ table.tagManager());
+ }
+
+ /**
+ * Plan the snapshot expiration.
+ *
+ * @param config expiration configuration
+ * @return the expiration plan with three groups of tasks, or empty plan if nothing to expire
+ */
+ public ExpireSnapshotsPlan plan(ExpireConfig config) {
+ snapshotDeletion.setChangelogDecoupled(config.isChangelogDecoupled());
+ int retainMax = config.getSnapshotRetainMax();
+ int retainMin = config.getSnapshotRetainMin();
+ int maxDeletes = config.getSnapshotMaxDeletes();
+ long olderThanMills =
+ System.currentTimeMillis() - config.getSnapshotTimeRetain().toMillis();
+
+ // 1. Get snapshot range
+ Long latestSnapshotId = snapshotManager.latestSnapshotId();
+ if (latestSnapshotId == null) {
+ // no snapshot, nothing to expire
+ return ExpireSnapshotsPlan.empty();
+ }
+
+ Long earliestId = snapshotManager.earliestSnapshotId();
+ if (earliestId == null) {
+ return ExpireSnapshotsPlan.empty();
+ }
+
+ Preconditions.checkArgument(
+ retainMax >= retainMin,
+ String.format(
+ "retainMax (%s) must not be less than retainMin (%s).",
+ retainMax, retainMin));
+
+ // the min snapshot to retain from 'snapshot.num-retained.max'
+ // (the maximum number of snapshots to retain)
+ long min = Math.max(latestSnapshotId - retainMax + 1, earliestId);
+
+ // the max exclusive snapshot to expire until
+ // protected by 'snapshot.num-retained.min'
+ // (the minimum number of completed snapshots to retain)
+ long endExclusiveId = latestSnapshotId - retainMin + 1;
+
+ // the snapshot being read by the consumer cannot be deleted
+ long consumerProtection = consumerManager.minNextSnapshot().orElse(Long.MAX_VALUE);
+ endExclusiveId = Math.min(endExclusiveId, consumerProtection);
Review Comment:
Done. Extracted `computeSnapshotExpireRange()` as a static method in `ExpireSnapshotsImpl` with an `ExpireRange` return type. Both `ExpireSnapshotsImpl.expire()` and `ExpireSnapshotsPlanner.plan() `now call this shared method instead of duplicating the range computation logic. Also removed the duplicated `findSkippingTags()` from `ExpireSnapshotsPlanner` — it now uses the one in `ExpireSnapshotsImpl`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r2973183685
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/ExpireSnapshotsAction.java:
##########
@@ -50,12 +93,135 @@ public ExpireSnapshotsAction(
this.olderThan = olderThan;
this.maxDeletes = maxDeletes;
this.options = options;
+ this.parallelism = resolveParallelism(parallelism);
+ }
+
+ private int resolveParallelism(Integer parallelism) {
+ if (parallelism != null) {
+ return parallelism;
+ }
+ int envParallelism = env.getParallelism();
+ return envParallelism > 0 ? envParallelism : 1;
}
+ @Override
+ public void run() throws Exception {
+ if (forceStartFlinkJob) {
+ // Parallel mode: build custom multi-parallelism Flink pipeline
+ build();
+ execute(this.getClass().getSimpleName());
+ } else {
+ // Default: ActionBase handles LocalAction → executeLocally()
+ super.run();
+ }
+ }
+
+ @Override
public void executeLocally() throws Exception {
ExpireSnapshotsProcedure expireSnapshotsProcedure = new ExpireSnapshotsProcedure();
expireSnapshotsProcedure.withCatalog(catalog);
expireSnapshotsProcedure.call(
null, database + "." + table, retainMax, retainMin, olderThan, maxDeletes, options);
}
+
+ @Override
+ public void build() throws Exception {
+ Identifier identifier = new Identifier(database, table);
+
+ // Prepare table with dynamic options
+ HashMap<String, String> dynamicOptions = new HashMap<>();
+ ProcedureUtils.putAllOptions(dynamicOptions, options);
+ FileStoreTable fileStoreTable =
+ (FileStoreTable) catalog.getTable(identifier).copy(dynamicOptions);
+
+ // Build expire config
+ CoreOptions tableOptions = fileStoreTable.store().options();
+ ExpireConfig expireConfig =
+ ProcedureUtils.fillInSnapshotOptions(
+ tableOptions, retainMax, retainMin, olderThan, maxDeletes)
+ .build();
+
+ // Create planner using factory method
+ ExpireSnapshotsPlanner planner = ExpireSnapshotsPlanner.create(fileStoreTable);
+
+ // Plan the expiration
+ ExpireSnapshotsPlan plan = planner.plan(expireConfig);
+ if (plan.isEmpty()) {
+ LOG.info("No snapshots to expire");
+ return;
+ }
+
+ LOG.info(
+ "Planning to expire {} snapshots, range=[{}, {})",
+ plan.endExclusiveId() - plan.beginInclusiveId(),
+ plan.beginInclusiveId(),
+ plan.endExclusiveId());
+
+ // Build worker phase
+ DataStream<DeletionReport> reports = buildWorkerPhase(plan, identifier, expireConfig);
+
+ // Build sink phase
+ buildSinkPhase(reports, plan, identifier, expireConfig);
+ }
+
+ /**
+ * Build the worker phase of the Flink job.
+ *
+ * <p>Workers process data file and changelog file deletion tasks in parallel. Tasks are
+ * partitioned by snapshot range to ensure:
+ *
+ * <ul>
+ * <li>Same snapshot range tasks are processed by the same worker
+ * <li>Within each worker, data files are deleted before changelog files
+ * <li>Cache locality is maximized (adjacent snapshots often share manifest files)
+ * </ul>
+ */
+ private DataStream<DeletionReport> buildWorkerPhase(
+ ExpireSnapshotsPlan plan, Identifier identifier, ExpireConfig expireConfig) {
+ // Partition by snapshot range: each worker gets a contiguous range of snapshots
+ // with dataFileTasks first, then changelogFileTasks
+ List<List<SnapshotExpireTask>> partitionedGroups =
+ plan.partitionTasksBySnapshotRange(parallelism);
+
+ DataStreamSource<List<SnapshotExpireTask>> source =
+ env.fromCollection(partitionedGroups).setParallelism(1);
+
+ return source.rebalance()
+ .flatMap(
+ new RangePartitionedExpireFunction(
+ catalogOptions.toMap(),
+ identifier,
+ plan.protectionSet().taggedSnapshots(),
+ expireConfig.isChangelogDecoupled()))
+ // Use JavaTypeInfo to ensure proper Java serialization of DeletionReport,
+ // avoiding Kryo's FieldSerializer which cannot handle BinaryRow correctly.
+ // This approach is compatible with both Flink 1.x and 2.x.
+ .returns(new JavaTypeInfo<>(DeletionReport.class))
+ .setParallelism(parallelism)
+ .name("RangePartitionedExpire");
+ }
+
+ /**
+ * Build the sink phase of the Flink job.
+ *
+ * <p>The sink collects deletion reports from workers, then serially deletes manifests and
+ * snapshot metadata files to avoid concurrent deletion issues.
+ */
+ private void buildSinkPhase(
+ DataStream<DeletionReport> reports,
+ ExpireSnapshotsPlan plan,
+ Identifier identifier,
+ ExpireConfig expireConfig) {
+ reports.sinkTo(
+ new SnapshotExpireSink(
+ catalogOptions.toMap(),
+ identifier,
+ plan.endExclusiveId(),
+ plan.protectionSet().manifestSkippingSet(),
+ plan.manifestTasks(),
+ plan.snapshotFileTasks(),
+ expireConfig.isChangelogDecoupled()))
+ .setParallelism(1)
+ .name("SnapshotExpire");
Review Comment:
Renamed to "SnapshotExpireCommit" to distinguish from the upstream worker phase.
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/expire/RangePartitionedExpireFunction.java:
##########
@@ -0,0 +1,115 @@
+/*
+ * 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.expire;
+
+import org.apache.paimon.Snapshot;
+import org.apache.paimon.catalog.Catalog;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.flink.FlinkCatalogFactory;
+import org.apache.paimon.operation.SnapshotDeletion;
+import org.apache.paimon.operation.expire.DeletionReport;
+import org.apache.paimon.operation.expire.ExpireSnapshotsExecutor;
+import org.apache.paimon.operation.expire.SnapshotExpireTask;
+import org.apache.paimon.options.Options;
+import org.apache.paimon.table.FileStoreTable;
+
+import org.apache.flink.api.common.functions.OpenContext;
+import org.apache.flink.api.common.functions.RichFlatMapFunction;
+import org.apache.flink.util.Collector;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Flink flatMap function for range-partitioned snapshot expiration (worker phase).
+ *
+ * <p>This function processes a batch of {@link SnapshotExpireTask}s that belong to the same
+ * contiguous range. Each subtask receives a list of tasks (e.g., subtask 0 gets snap 1-4, subtask 1
+ * gets snap 5-8) and processes them sequentially in order.
+ *
+ * <p>Processing tasks in order within each subtask maximizes cache locality since adjacent
+ * snapshots often share manifest files.
+ *
+ * <p>In worker phase, this function only deletes data files and changelog data files. Manifest and
+ * snapshot metadata deletion is deferred to the sink phase to avoid concurrent deletion issues.
+ *
+ * <p>This function uses {@link ExpireSnapshotsExecutor#execute} which loads tag data files
+ * on-demand with internal caching.
+ */
+public class RangePartitionedExpireFunction
+ extends RichFlatMapFunction<List<SnapshotExpireTask>, DeletionReport> {
+
+ private static final long serialVersionUID = 1L;
+
+ private final Map<String, String> catalogConfig;
+ private final Identifier identifier;
+ private final List<Snapshot> taggedSnapshots;
+ private final boolean changelogDecoupled;
+
+ private transient ExpireSnapshotsExecutor executor;
+
+ public RangePartitionedExpireFunction(
+ Map<String, String> catalogConfig,
+ Identifier identifier,
+ List<Snapshot> taggedSnapshots,
+ boolean changelogDecoupled) {
+ this.catalogConfig = catalogConfig;
+ this.identifier = identifier;
+ this.taggedSnapshots = taggedSnapshots;
+ this.changelogDecoupled = changelogDecoupled;
+ }
+
+ @Override
+ public void open(OpenContext openContext) throws Exception {
+ this.executor = initExecutor();
+ }
+
+ /**
+ * Initializes and returns the executor for processing expire tasks. Subclasses can override
+ * this method to provide a custom executor for testing without catalog access.
+ *
+ * <p>Default implementation creates executor from catalog using {@link #catalogConfig} and
+ * {@link #identifier}.
+ */
+ protected ExpireSnapshotsExecutor initExecutor() throws Exception {
+ Options options = Options.fromMap(catalogConfig);
+ Catalog catalog = FlinkCatalogFactory.createPaimonCatalog(options);
+ FileStoreTable table = (FileStoreTable) catalog.getTable(identifier);
+ SnapshotDeletion deletion = table.store().newSnapshotDeletion();
+ deletion.setChangelogDecoupled(changelogDecoupled);
+ return new ExpireSnapshotsExecutor(table.snapshotManager(), deletion);
+ }
+
+ @Override
+ public void flatMap(List<SnapshotExpireTask> tasks, Collector<DeletionReport> out)
+ throws Exception {
+ // Process tasks sequentially in order to maximize cache locality
+ for (SnapshotExpireTask task : tasks) {
+ DeletionReport report = processTask(task);
+ out.collect(report);
+ }
+ }
+
+ private DeletionReport processTask(SnapshotExpireTask task) {
Review Comment:
Done. Inlined processTask into flatMap.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r2973191986
##########
paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/action/ExpireSnapshotsActionITCase.java:
##########
@@ -0,0 +1,231 @@
+/*
+ * 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.action;
+
+import org.apache.paimon.Snapshot;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.consumer.ConsumerManager;
+import org.apache.paimon.flink.expire.RangePartitionedExpireFunction;
+import org.apache.paimon.flink.expire.SnapshotExpireSink;
+import org.apache.paimon.flink.util.MiniClusterWithClientExtension;
+import org.apache.paimon.flink.utils.JavaTypeInfo;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.operation.ExpireSnapshotsTest;
+import org.apache.paimon.operation.SnapshotDeletion;
+import org.apache.paimon.operation.expire.DeletionReport;
+import org.apache.paimon.operation.expire.ExpireSnapshotsExecutor;
+import org.apache.paimon.operation.expire.ExpireSnapshotsPlan;
+import org.apache.paimon.operation.expire.ExpireSnapshotsPlanner;
+import org.apache.paimon.operation.expire.SnapshotExpireTask;
+import org.apache.paimon.options.ExpireConfig;
+
+import org.apache.flink.api.common.RuntimeExecutionMode;
+import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.datastream.DataStreamSource;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Supplier;
+
+/**
+ * IT Case for parallel expire snapshots using Flink execution. This class extends {@link
+ * ExpireSnapshotsTest} and overrides {@link #doExpire} to test parallel execution mode with real
+ * Flink DataStream API.
+ *
+ * <p>This test validates that the Flink-based parallel expire logic produces the same results as
+ * the serial implementation. It extends the production {@link RangePartitionedExpireFunction} and
+ * {@link SnapshotExpireSink} classes, overriding {@code initExecutor} to inject test executors.
+ */
+public class ExpireSnapshotsActionITCase extends ExpireSnapshotsTest {
+
+ private static final int TEST_PARALLELISM = 2;
+
+ // Placeholder identifier for test (not actually used since we override initExecutor)
+ private static final Identifier TEST_IDENTIFIER = Identifier.create("default", "test_table");
+
+ @RegisterExtension
+ protected static final MiniClusterWithClientExtension MINI_CLUSTER_EXTENSION =
+ new MiniClusterWithClientExtension(
+ new MiniClusterResourceConfiguration.Builder()
+ .setNumberTaskManagers(1)
+ .setNumberSlotsPerTaskManager(TEST_PARALLELISM)
+ .build());
+
+ // Static supplier for test executor (used by inner test classes)
+ private static volatile Supplier<ExpireSnapshotsExecutor> executorSupplier;
+
+ @Override
+ protected int doExpire(ExpireConfig config) {
+ // 1. Create planner and generate plan
+ SnapshotDeletion snapshotDeletion = store.newSnapshotDeletion();
+ ExpireSnapshotsPlanner planner =
+ new ExpireSnapshotsPlanner(
+ snapshotManager,
+ new ConsumerManager(
+ fileIO, new Path(tempDir.toUri()), snapshotManager.branch()),
+ snapshotDeletion,
+ store.newTagManager());
+ ExpireSnapshotsPlan plan = planner.plan(config);
+
+ if (plan.isEmpty()) {
+ return 0;
+ }
+
+ // 2. Set up executor supplier for test subclasses.
+ executorSupplier =
+ () -> {
+ SnapshotDeletion deletion = store.newSnapshotDeletion();
+ deletion.setChangelogDecoupled(config.isChangelogDecoupled());
+ return new ExpireSnapshotsExecutor(snapshotManager, deletion, changelogManager);
+ };
+
+ try {
+ // 3. Create Flink execution environment
+ StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
+ env.setRuntimeMode(RuntimeExecutionMode.BATCH);
+ env.setParallelism(TEST_PARALLELISM);
+
+ // 4. Build worker phase: partition tasks by snapshot range
+ List<List<SnapshotExpireTask>> partitionedGroups =
+ plan.partitionTasksBySnapshotRange(TEST_PARALLELISM);
+
+ DataStreamSource<List<SnapshotExpireTask>> source =
+ env.fromCollection(partitionedGroups).setParallelism(1);
+
+ // 5. Apply test worker function (extends production class, overrides initExecutor)
+ DataStream<DeletionReport> reports =
+ source.rebalance()
+ .flatMap(
+ new TestExpireFunction(
+ Collections.emptyMap(),
+ TEST_IDENTIFIER,
+ plan.protectionSet().taggedSnapshots(),
+ config.isChangelogDecoupled()))
+ .returns(new JavaTypeInfo<>(DeletionReport.class))
+ .setParallelism(TEST_PARALLELISM)
+ .name("RangePartitionedExpire");
+
+ // 6. Apply test sink (extends SnapshotExpireSink, overrides initExecutor)
+ reports.sinkTo(
+ new TestExpireSink(
+ Collections.emptyMap(),
+ TEST_IDENTIFIER,
+ plan.endExclusiveId(),
+ plan.protectionSet().manifestSkippingSet(),
+ plan.manifestTasks(),
+ plan.snapshotFileTasks(),
+ config.isChangelogDecoupled()))
+ .setParallelism(1)
+ .name("SnapshotExpireSink");
+
+ // 7. Execute Flink job
+ env.execute("ExpireSnapshotsFlinkTest");
+
+ return plan.snapshotFileTasks().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ } finally {
+ executorSupplier = null;
+ }
+ }
+
+ // ==================== Test Subclasses ====================
+
+ /**
+ * Test subclass of {@link RangePartitionedExpireFunction} that overrides {@code initExecutor}
+ * to use the test executor supplier, completely bypassing catalog access.
+ */
+ private static class TestExpireFunction extends RangePartitionedExpireFunction {
+
+ private static final long serialVersionUID = 1L;
+
+ public TestExpireFunction(
+ Map<String, String> catalogConfig,
+ Identifier identifier,
+ List<Snapshot> taggedSnapshots,
+ boolean changelogDecoupled) {
+ super(catalogConfig, identifier, taggedSnapshots, changelogDecoupled);
+ }
+
+ @Override
+ protected ExpireSnapshotsExecutor initExecutor() {
+ // Use the static executor supplier from test setup, bypassing catalog
+ return executorSupplier.get();
+ }
+ }
+
+ /**
+ * Test subclass of {@link SnapshotExpireSink} that overrides {@code initExecutor} to use the
+ * test executor supplier, completely bypassing catalog access.
+ */
+ private static class TestExpireSink extends SnapshotExpireSink {
+
+ private static final long serialVersionUID = 1L;
+
+ public TestExpireSink(
+ Map<String, String> catalogConfig,
+ Identifier identifier,
+ long endExclusiveId,
+ Set<String> manifestSkippingSet,
+ List<SnapshotExpireTask> manifestTasks,
+ List<SnapshotExpireTask> snapshotFileTasks,
+ boolean changelogDecoupled) {
+ super(
+ catalogConfig,
+ identifier,
+ endExclusiveId,
+ manifestSkippingSet,
+ manifestTasks,
+ snapshotFileTasks,
+ changelogDecoupled);
+ }
+
+ @Override
+ protected ExpireSnapshotsExecutor initExecutor() {
+ // Use the static executor supplier from test setup, bypassing catalog
+ return executorSupplier.get();
+ }
+ }
+
+ // ==================== Disabled Tests ====================
+ // The following tests are disabled because they are not suitable for parallel Flink execution.
+
+ @Test
+ @Disabled("Tests SnapshotDeletion directly, not the full expire flow")
+ @Override
+ public void testExpireExtraFiles() {}
+
+ @Test
+ @Disabled("Tests SnapshotDeletion directly, not the full expire flow")
+ @Override
+ public void testExpireExtraFilesWithExternalPath() {}
+
+ @Test
+ @Disabled(
+ "Tests concurrent expire scenario which has different semantics in Flink parallel mode")
Review Comment:
done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r2973186715
##########
paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/action/ExpireSnapshotsActionITCase.java:
##########
@@ -0,0 +1,231 @@
+/*
+ * 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.action;
+
+import org.apache.paimon.Snapshot;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.consumer.ConsumerManager;
+import org.apache.paimon.flink.expire.RangePartitionedExpireFunction;
+import org.apache.paimon.flink.expire.SnapshotExpireSink;
+import org.apache.paimon.flink.util.MiniClusterWithClientExtension;
+import org.apache.paimon.flink.utils.JavaTypeInfo;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.operation.ExpireSnapshotsTest;
+import org.apache.paimon.operation.SnapshotDeletion;
+import org.apache.paimon.operation.expire.DeletionReport;
+import org.apache.paimon.operation.expire.ExpireSnapshotsExecutor;
+import org.apache.paimon.operation.expire.ExpireSnapshotsPlan;
+import org.apache.paimon.operation.expire.ExpireSnapshotsPlanner;
+import org.apache.paimon.operation.expire.SnapshotExpireTask;
+import org.apache.paimon.options.ExpireConfig;
+
+import org.apache.flink.api.common.RuntimeExecutionMode;
+import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.datastream.DataStreamSource;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Supplier;
+
+/**
+ * IT Case for parallel expire snapshots using Flink execution. This class extends {@link
+ * ExpireSnapshotsTest} and overrides {@link #doExpire} to test parallel execution mode with real
+ * Flink DataStream API.
+ *
+ * <p>This test validates that the Flink-based parallel expire logic produces the same results as
+ * the serial implementation. It extends the production {@link RangePartitionedExpireFunction} and
+ * {@link SnapshotExpireSink} classes, overriding {@code initExecutor} to inject test executors.
+ */
+public class ExpireSnapshotsActionITCase extends ExpireSnapshotsTest {
Review Comment:
Done. Added testExpireRecoveryAfterPartialFailure: uses a failAfterTasks flag in TestExpireFunction to simulate a mid-job crash during the worker phase (some data files deleted, but snapshot metadata intact). Then runs expire again and verifies it completes successfully despite missing files.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi closed pull request #7027: [core][flink] Support parallelism snapshot expire
URL: https://github.com/apache/paimon/pull/7027
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "yunfengzhou-hub (via GitHub)" <gi...@apache.org>.
yunfengzhou-hub commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r3004547134
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/expire/ExpireSnapshotsPlanner.java:
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.expire;
+
+import org.apache.paimon.Snapshot;
+import org.apache.paimon.annotation.VisibleForTesting;
+import org.apache.paimon.consumer.ConsumerManager;
+import org.apache.paimon.operation.SnapshotDeletion;
+import org.apache.paimon.options.ExpireConfig;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.utils.Preconditions;
+import org.apache.paimon.utils.SnapshotManager;
+import org.apache.paimon.utils.TagManager;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executor;
+
+import static org.apache.paimon.utils.SnapshotManager.findPreviousOrEqualSnapshot;
+import static org.apache.paimon.utils.SnapshotManager.findPreviousSnapshot;
+
+/**
+ * Planner for snapshot expiration. This class computes the expiration plan including:
+ *
+ * <ul>
+ * <li>The range of snapshots to expire [beginInclusiveId, endExclusiveId)
+ * <li>Protection set containing manifests that should not be deleted
+ * <li>Four groups of tasks organized by deletion phase
+ * </ul>
+ *
+ * <p>Tag data files are loaded on-demand by workers using {@link
+ * SnapshotDeletion#createDataFileSkipperForTags}, which has internal caching to avoid repeated
+ * reads.
+ */
+public class ExpireSnapshotsPlanner {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ExpireSnapshotsPlanner.class);
+
+ private final SnapshotManager snapshotManager;
+ private final ConsumerManager consumerManager;
+ private final SnapshotDeletion snapshotDeletion;
+ private final TagManager tagManager;
+
+ public ExpireSnapshotsPlanner(
+ SnapshotManager snapshotManager,
+ ConsumerManager consumerManager,
+ SnapshotDeletion snapshotDeletion,
+ TagManager tagManager) {
+ this.snapshotManager = snapshotManager;
+ this.consumerManager = consumerManager;
+ this.snapshotDeletion = snapshotDeletion;
+ this.tagManager = tagManager;
+ }
+
+ /** Creates an ExpireSnapshotsPlanner from a FileStoreTable. */
+ public static ExpireSnapshotsPlanner create(FileStoreTable table) {
+ SnapshotManager snapshotManager = table.snapshotManager();
+ ConsumerManager consumerManager =
+ new ConsumerManager(table.fileIO(), table.location(), snapshotManager.branch());
+ return new ExpireSnapshotsPlanner(
+ table.snapshotManager(),
+ consumerManager,
+ table.store().newSnapshotDeletion(),
+ table.tagManager());
+ }
+
+ /**
+ * Plan the snapshot expiration.
+ *
+ * @param config expiration configuration
+ * @return the expiration plan with three groups of tasks, or empty plan if nothing to expire
+ */
+ public ExpireSnapshotsPlan plan(ExpireConfig config) {
+ snapshotDeletion.setChangelogDecoupled(config.isChangelogDecoupled());
+ int retainMax = config.getSnapshotRetainMax();
+ int retainMin = config.getSnapshotRetainMin();
+ int maxDeletes = config.getSnapshotMaxDeletes();
+ long olderThanMills =
+ System.currentTimeMillis() - config.getSnapshotTimeRetain().toMillis();
+
+ // 1. Get snapshot range
+ Long latestSnapshotId = snapshotManager.latestSnapshotId();
+ if (latestSnapshotId == null) {
+ // no snapshot, nothing to expire
+ return ExpireSnapshotsPlan.empty();
+ }
+
+ Long earliestId = snapshotManager.earliestSnapshotId();
+ if (earliestId == null) {
+ return ExpireSnapshotsPlan.empty();
+ }
+
+ Preconditions.checkArgument(
+ retainMax >= retainMin,
+ String.format(
+ "retainMax (%s) must not be less than retainMin (%s).",
+ retainMax, retainMin));
+
+ // the min snapshot to retain from 'snapshot.num-retained.max'
+ // (the maximum number of snapshots to retain)
+ long min = Math.max(latestSnapshotId - retainMax + 1, earliestId);
+
+ // the max exclusive snapshot to expire until
+ // protected by 'snapshot.num-retained.min'
+ // (the minimum number of completed snapshots to retain)
+ long endExclusiveId = latestSnapshotId - retainMin + 1;
+
+ // the snapshot being read by the consumer cannot be deleted
+ long consumerProtection = consumerManager.minNextSnapshot().orElse(Long.MAX_VALUE);
+ endExclusiveId = Math.min(endExclusiveId, consumerProtection);
Review Comment:
This logic to compute begin and end snapshot id is also repeated in `ExpireSnapshotsImpl` and `ExpireChangelogImpl`. It might be better to extract a common method for this code part, like whtat this PR has done for `FileDeletionBase#cleanEmptyDirectories`.
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/expire/ExpireSnapshotsPlan.java:
##########
@@ -0,0 +1,230 @@
+/*
+ * 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.expire;
+
+import org.apache.paimon.Snapshot;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The plan for snapshot expiration, containing four groups of tasks organized by deletion phase.
+ *
+ * <p>The plan organizes tasks into four groups for correct deletion order:
+ *
+ * <ul>
+ * <li>{@link #dataFileTasks()}: Phase 1a - Delete data files (can be parallelized)
+ * <li>{@link #changelogFileTasks()}: Phase 1b - Delete changelog files (can be parallelized)
+ * <li>{@link #manifestTasks()}: Phase 2a - Delete manifest files (serial)
+ * <li>{@link #snapshotFileTasks()}: Phase 2b - Delete snapshot metadata files (serial)
+ * </ul>
+ */
+public class ExpireSnapshotsPlan implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private static final ExpireSnapshotsPlan EMPTY =
+ new ExpireSnapshotsPlan(
+ Collections.emptyList(),
+ Collections.emptyList(),
+ Collections.emptyList(),
+ Collections.emptyList(),
+ null,
+ 0,
+ 0,
+ Collections.emptyMap());
+
+ private final List<SnapshotExpireTask> dataFileTasks;
+ private final List<SnapshotExpireTask> changelogFileTasks;
+ private final List<SnapshotExpireTask> manifestTasks;
+ private final List<SnapshotExpireTask> snapshotFileTasks;
+ private final ProtectionSet protectionSet;
+ private final long beginInclusiveId;
+ private final long endExclusiveId;
+
+ /** Pre-collected snapshot cache from planner to avoid redundant snapshot reads. */
+ private final Map<Long, Snapshot> snapshotCache;
+
+ public ExpireSnapshotsPlan(
+ List<SnapshotExpireTask> dataFileTasks,
+ List<SnapshotExpireTask> changelogFileTasks,
+ List<SnapshotExpireTask> manifestTasks,
+ List<SnapshotExpireTask> snapshotFileTasks,
+ ProtectionSet protectionSet,
+ long beginInclusiveId,
+ long endExclusiveId,
+ Map<Long, Snapshot> snapshotCache) {
+ this.dataFileTasks = dataFileTasks;
+ this.changelogFileTasks = changelogFileTasks;
+ this.manifestTasks = manifestTasks;
+ this.snapshotFileTasks = snapshotFileTasks;
+ this.protectionSet = protectionSet;
+ this.beginInclusiveId = beginInclusiveId;
+ this.endExclusiveId = endExclusiveId;
+ this.snapshotCache = snapshotCache;
+ }
+
+ public static ExpireSnapshotsPlan empty() {
+ return EMPTY;
+ }
+
+ public boolean isEmpty() {
+ return dataFileTasks.isEmpty()
+ && changelogFileTasks.isEmpty()
+ && manifestTasks.isEmpty()
+ && snapshotFileTasks.isEmpty();
+ }
+
+ /** Get data file deletion tasks (Phase 1a). These can be executed in parallel. */
+ public List<SnapshotExpireTask> dataFileTasks() {
Review Comment:
unused method.
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/expire/ExpireSnapshotsPlan.java:
##########
@@ -0,0 +1,230 @@
+/*
+ * 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.expire;
+
+import org.apache.paimon.Snapshot;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The plan for snapshot expiration, containing four groups of tasks organized by deletion phase.
+ *
+ * <p>The plan organizes tasks into four groups for correct deletion order:
+ *
+ * <ul>
+ * <li>{@link #dataFileTasks()}: Phase 1a - Delete data files (can be parallelized)
+ * <li>{@link #changelogFileTasks()}: Phase 1b - Delete changelog files (can be parallelized)
+ * <li>{@link #manifestTasks()}: Phase 2a - Delete manifest files (serial)
+ * <li>{@link #snapshotFileTasks()}: Phase 2b - Delete snapshot metadata files (serial)
+ * </ul>
+ */
+public class ExpireSnapshotsPlan implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private static final ExpireSnapshotsPlan EMPTY =
+ new ExpireSnapshotsPlan(
+ Collections.emptyList(),
+ Collections.emptyList(),
+ Collections.emptyList(),
+ Collections.emptyList(),
+ null,
+ 0,
+ 0,
+ Collections.emptyMap());
+
+ private final List<SnapshotExpireTask> dataFileTasks;
+ private final List<SnapshotExpireTask> changelogFileTasks;
+ private final List<SnapshotExpireTask> manifestTasks;
+ private final List<SnapshotExpireTask> snapshotFileTasks;
+ private final ProtectionSet protectionSet;
+ private final long beginInclusiveId;
+ private final long endExclusiveId;
+
+ /** Pre-collected snapshot cache from planner to avoid redundant snapshot reads. */
+ private final Map<Long, Snapshot> snapshotCache;
+
+ public ExpireSnapshotsPlan(
+ List<SnapshotExpireTask> dataFileTasks,
+ List<SnapshotExpireTask> changelogFileTasks,
+ List<SnapshotExpireTask> manifestTasks,
+ List<SnapshotExpireTask> snapshotFileTasks,
+ ProtectionSet protectionSet,
+ long beginInclusiveId,
+ long endExclusiveId,
+ Map<Long, Snapshot> snapshotCache) {
+ this.dataFileTasks = dataFileTasks;
+ this.changelogFileTasks = changelogFileTasks;
+ this.manifestTasks = manifestTasks;
+ this.snapshotFileTasks = snapshotFileTasks;
+ this.protectionSet = protectionSet;
+ this.beginInclusiveId = beginInclusiveId;
+ this.endExclusiveId = endExclusiveId;
+ this.snapshotCache = snapshotCache;
+ }
+
+ public static ExpireSnapshotsPlan empty() {
+ return EMPTY;
+ }
+
+ public boolean isEmpty() {
+ return dataFileTasks.isEmpty()
+ && changelogFileTasks.isEmpty()
+ && manifestTasks.isEmpty()
+ && snapshotFileTasks.isEmpty();
+ }
+
+ /** Get data file deletion tasks (Phase 1a). These can be executed in parallel. */
+ public List<SnapshotExpireTask> dataFileTasks() {
+ return dataFileTasks;
+ }
+
+ /** Get changelog file deletion tasks (Phase 1b). These can be executed in parallel. */
+ public List<SnapshotExpireTask> changelogFileTasks() {
Review Comment:
unused method.
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/ExpireSnapshotsAction.java:
##########
@@ -50,12 +95,139 @@ public ExpireSnapshotsAction(
this.olderThan = olderThan;
this.maxDeletes = maxDeletes;
this.options = options;
+ this.parallelism = resolveParallelism(parallelism);
+ }
+
+ private int resolveParallelism(Integer parallelism) {
+ if (parallelism != null) {
+ return parallelism;
+ }
+ int envParallelism = env.getParallelism();
+ return envParallelism > 0 ? envParallelism : 1;
}
+ @Override
+ public void run() throws Exception {
+ if (forceStartFlinkJob || parallelism > 1) {
+ // Parallel mode: build custom multi-parallelism Flink pipeline
+ build();
+ if (!env.getTransformations().isEmpty()) {
+ execute(this.getClass().getSimpleName());
+ }
+ } else {
+ // Default: ActionBase handles LocalAction → executeLocally()
+ super.run();
+ }
+ }
+
+ @Override
public void executeLocally() throws Exception {
ExpireSnapshotsProcedure expireSnapshotsProcedure = new ExpireSnapshotsProcedure();
expireSnapshotsProcedure.withCatalog(catalog);
expireSnapshotsProcedure.call(
null, database + "." + table, retainMax, retainMin, olderThan, maxDeletes, options);
}
+
+ @Override
+ public void build() throws Exception {
+ Identifier identifier = new Identifier(database, table);
+
+ // Prepare table with dynamic options
+ HashMap<String, String> dynamicOptions = new HashMap<>();
+ ProcedureUtils.putAllOptions(dynamicOptions, options);
+ FileStoreTable fileStoreTable =
+ (FileStoreTable) catalog.getTable(identifier).copy(dynamicOptions);
+
+ // Build expire config
+ CoreOptions tableOptions = fileStoreTable.store().options();
+ ExpireConfig expireConfig =
+ ProcedureUtils.fillInSnapshotOptions(
+ tableOptions, retainMax, retainMin, olderThan, maxDeletes)
+ .build();
+
+ // Create planner using factory method
+ ExpireSnapshotsPlanner planner = ExpireSnapshotsPlanner.create(fileStoreTable);
+
+ // Plan the expiration
+ ExpireSnapshotsPlan plan = planner.plan(expireConfig);
+ if (plan.isEmpty()) {
+ LOG.info("No snapshots to expire, skipping Flink job submission.");
+ return;
+ }
+
+ LOG.info(
+ "Planning to expire {} snapshots, range=[{}, {})",
+ plan.endExclusiveId() - plan.beginInclusiveId(),
+ plan.beginInclusiveId(),
+ plan.endExclusiveId());
+
+ // Build worker phase
+ DataStream<DeletionReport> reports = buildWorkerPhase(plan, identifier, expireConfig);
+
+ // Build sink phase
+ buildSinkPhase(reports, plan, identifier, expireConfig);
+ }
+
+ /**
+ * Build the worker phase of the Flink job.
+ *
+ * <p>Workers process data file and changelog file deletion tasks in parallel. Tasks are
+ * partitioned by snapshot range to ensure:
+ *
+ * <ul>
+ * <li>Same snapshot range tasks are processed by the same worker
+ * <li>Within each worker, data files are deleted before changelog files
+ * <li>Cache locality is maximized (adjacent snapshots often share manifest files)
+ * </ul>
+ */
+ private DataStream<DeletionReport> buildWorkerPhase(
+ ExpireSnapshotsPlan plan, Identifier identifier, ExpireConfig expireConfig) {
+ // Partition by snapshot range: each worker gets a contiguous range of snapshots
+ // with dataFileTasks first, then changelogFileTasks
+ List<List<SnapshotExpireTask>> partitionedGroups =
+ plan.partitionTasksBySnapshotRange(parallelism);
+
+ DataStreamSource<List<SnapshotExpireTask>> source =
+ env.fromCollection(partitionedGroups).setParallelism(1);
+
+ return source.rebalance()
+ .flatMap(
+ new RangePartitionedExpireFunction(
+ catalogOptions.toMap(),
+ identifier,
+ plan.protectionSet().taggedSnapshots(),
+ plan.snapshotCache(),
+ expireConfig.isChangelogDecoupled()))
+ // Use JavaTypeInfo to ensure proper Java serialization of DeletionReport,
+ // avoiding Kryo's FieldSerializer which cannot handle BinaryRow correctly.
+ // This approach is compatible with both Flink 1.x and 2.x.
Review Comment:
This comment is a little redundant. Most Flink APIs used by Paimon are compatible with both Flink 1.x and 2.x, and there is no need to amplify this point.
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/ExpireSnapshotsAction.java:
##########
@@ -50,12 +95,168 @@ public ExpireSnapshotsAction(
this.olderThan = olderThan;
this.maxDeletes = maxDeletes;
this.options = options;
+ this.parallelism = parallelism;
}
+ /** Returns true if forceStartFlinkJob is enabled and parallelism is greater than 1. */
+ private boolean isParallelMode() {
+ return forceStartFlinkJob && parallelism != null && parallelism > 1;
+ }
+
+ @Override
+ public void run() throws Exception {
Review Comment:
In the current implementation, the DAG of the Flink job would change, if the user configures its parallelism from 1 to 2. This would bring additional complexity to the Job's operation process.
Given the problem above, I prefer to use the same DAG for the job no matter what parallelism the job has.
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/expire/DeletionReport.java:
##########
@@ -0,0 +1,86 @@
+/*
+ * 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.expire;
+
+import org.apache.paimon.data.BinaryRow;
+
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+/** Report of a single snapshot expiration task. */
+public class DeletionReport implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final long snapshotId;
+
+ /** Whether this task was skipped (e.g., snapshot already deleted). */
+ private boolean skipped;
+
+ /** Buckets that had files deleted (for empty directory cleanup in parallel phase). */
+ private Map<BinaryRow, Set<Integer>> deletionBuckets;
+
+ public DeletionReport(long snapshotId) {
+ this.snapshotId = snapshotId;
+ this.skipped = false;
+ this.deletionBuckets = new HashMap<>();
+ }
+
+ /**
+ * Create a skipped report for a snapshot that was already deleted.
+ *
+ * @param snapshotId the snapshot ID
+ * @return a skipped deletion report
+ */
+ public static DeletionReport skipped(long snapshotId) {
+ DeletionReport report = new DeletionReport(snapshotId);
+ report.skipped = true;
+ return report;
+ }
+
+ public long snapshotId() {
Review Comment:
This field is only used in tests
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r2973188179
##########
paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/action/ParallelExpireSnapshotsActionITCase.java:
##########
@@ -0,0 +1,231 @@
+/*
+ * 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.action;
+
+import org.apache.paimon.Snapshot;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.consumer.ConsumerManager;
+import org.apache.paimon.flink.expire.RangePartitionedExpireFunction;
+import org.apache.paimon.flink.expire.SnapshotExpireSink;
+import org.apache.paimon.flink.util.MiniClusterWithClientExtension;
+import org.apache.paimon.flink.utils.JavaTypeInfo;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.operation.ExpireSnapshotsTest;
+import org.apache.paimon.operation.SnapshotDeletion;
+import org.apache.paimon.operation.expire.DeletionReport;
+import org.apache.paimon.operation.expire.ExpireSnapshotsExecutor;
+import org.apache.paimon.operation.expire.ExpireSnapshotsPlan;
+import org.apache.paimon.operation.expire.ExpireSnapshotsPlanner;
+import org.apache.paimon.operation.expire.SnapshotExpireTask;
+import org.apache.paimon.options.ExpireConfig;
+
+import org.apache.flink.api.common.RuntimeExecutionMode;
+import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.datastream.DataStreamSource;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Supplier;
+
+/**
+ * IT Case for parallel expire snapshots using Flink execution. This class extends {@link
Review Comment:
Done. Renamed ExpireSnapshotsActionITCase to ParallelExpireSnapshotsActionITCase to clarify that this test class is specifically for parallel mode.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r2973198787
##########
paimon-core/src/main/java/org/apache/paimon/table/ExpireSnapshotsImpl.java:
##########
@@ -18,49 +18,43 @@
package org.apache.paimon.table;
-import org.apache.paimon.Changelog;
-import org.apache.paimon.Snapshot;
import org.apache.paimon.annotation.VisibleForTesting;
import org.apache.paimon.consumer.ConsumerManager;
-import org.apache.paimon.manifest.ExpireFileEntry;
import org.apache.paimon.operation.SnapshotDeletion;
+import org.apache.paimon.operation.expire.ExpireSnapshotsExecutor;
+import org.apache.paimon.operation.expire.ExpireSnapshotsPlan;
+import org.apache.paimon.operation.expire.ExpireSnapshotsPlanner;
+import org.apache.paimon.operation.expire.SnapshotExpireTask;
import org.apache.paimon.options.ExpireConfig;
import org.apache.paimon.utils.ChangelogManager;
-import org.apache.paimon.utils.Preconditions;
import org.apache.paimon.utils.SnapshotManager;
import org.apache.paimon.utils.TagManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.UncheckedIOException;
-import java.util.ArrayList;
import java.util.HashSet;
-import java.util.List;
-import java.util.Optional;
import java.util.Set;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Executor;
-import java.util.function.Predicate;
-import java.util.stream.Collectors;
-import static org.apache.paimon.utils.SnapshotManager.findPreviousOrEqualSnapshot;
-import static org.apache.paimon.utils.SnapshotManager.findPreviousSnapshot;
-
-/** An implementation for {@link ExpireSnapshots}. */
+/**
+ * An implementation for {@link ExpireSnapshots}.
+ *
+ * <p>This implementation uses serial execution mode, which is suitable for local execution. The
+ * execution follows four phases:
+ *
+ * <ul>
+ * <li>Phase 1a: Delete all data files (using dataFileTasks)
+ * <li>Phase 1b: Delete all changelog files (using changelogFileTasks)
+ * <li>Phase 2a: Delete all manifests (using manifestTasks)
+ * <li>Phase 2b: Delete all snapshot files (using snapshotFileTasks)
+ * </ul>
+ */
public class ExpireSnapshotsImpl implements ExpireSnapshots {
Review Comment:
done, remove the complete re-structure to ExpireSnapshotsImpl.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r3013706217
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/expire/ExpireSnapshotsPlan.java:
##########
@@ -0,0 +1,230 @@
+/*
+ * 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.expire;
+
+import org.apache.paimon.Snapshot;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The plan for snapshot expiration, containing four groups of tasks organized by deletion phase.
+ *
+ * <p>The plan organizes tasks into four groups for correct deletion order:
+ *
+ * <ul>
+ * <li>{@link #dataFileTasks()}: Phase 1a - Delete data files (can be parallelized)
+ * <li>{@link #changelogFileTasks()}: Phase 1b - Delete changelog files (can be parallelized)
+ * <li>{@link #manifestTasks()}: Phase 2a - Delete manifest files (serial)
+ * <li>{@link #snapshotFileTasks()}: Phase 2b - Delete snapshot metadata files (serial)
+ * </ul>
+ */
+public class ExpireSnapshotsPlan implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private static final ExpireSnapshotsPlan EMPTY =
+ new ExpireSnapshotsPlan(
+ Collections.emptyList(),
+ Collections.emptyList(),
+ Collections.emptyList(),
+ Collections.emptyList(),
+ null,
+ 0,
+ 0,
+ Collections.emptyMap());
+
+ private final List<SnapshotExpireTask> dataFileTasks;
+ private final List<SnapshotExpireTask> changelogFileTasks;
+ private final List<SnapshotExpireTask> manifestTasks;
+ private final List<SnapshotExpireTask> snapshotFileTasks;
+ private final ProtectionSet protectionSet;
+ private final long beginInclusiveId;
+ private final long endExclusiveId;
+
+ /** Pre-collected snapshot cache from planner to avoid redundant snapshot reads. */
+ private final Map<Long, Snapshot> snapshotCache;
+
+ public ExpireSnapshotsPlan(
+ List<SnapshotExpireTask> dataFileTasks,
+ List<SnapshotExpireTask> changelogFileTasks,
+ List<SnapshotExpireTask> manifestTasks,
+ List<SnapshotExpireTask> snapshotFileTasks,
+ ProtectionSet protectionSet,
+ long beginInclusiveId,
+ long endExclusiveId,
+ Map<Long, Snapshot> snapshotCache) {
+ this.dataFileTasks = dataFileTasks;
+ this.changelogFileTasks = changelogFileTasks;
+ this.manifestTasks = manifestTasks;
+ this.snapshotFileTasks = snapshotFileTasks;
+ this.protectionSet = protectionSet;
+ this.beginInclusiveId = beginInclusiveId;
+ this.endExclusiveId = endExclusiveId;
+ this.snapshotCache = snapshotCache;
+ }
+
+ public static ExpireSnapshotsPlan empty() {
+ return EMPTY;
+ }
+
+ public boolean isEmpty() {
+ return dataFileTasks.isEmpty()
+ && changelogFileTasks.isEmpty()
+ && manifestTasks.isEmpty()
+ && snapshotFileTasks.isEmpty();
+ }
+
+ /** Get data file deletion tasks (Phase 1a). These can be executed in parallel. */
+ public List<SnapshotExpireTask> dataFileTasks() {
Review Comment:
Removed.
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/expire/ExpireSnapshotsPlan.java:
##########
@@ -0,0 +1,230 @@
+/*
+ * 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.expire;
+
+import org.apache.paimon.Snapshot;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The plan for snapshot expiration, containing four groups of tasks organized by deletion phase.
+ *
+ * <p>The plan organizes tasks into four groups for correct deletion order:
+ *
+ * <ul>
+ * <li>{@link #dataFileTasks()}: Phase 1a - Delete data files (can be parallelized)
+ * <li>{@link #changelogFileTasks()}: Phase 1b - Delete changelog files (can be parallelized)
+ * <li>{@link #manifestTasks()}: Phase 2a - Delete manifest files (serial)
+ * <li>{@link #snapshotFileTasks()}: Phase 2b - Delete snapshot metadata files (serial)
+ * </ul>
+ */
+public class ExpireSnapshotsPlan implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private static final ExpireSnapshotsPlan EMPTY =
+ new ExpireSnapshotsPlan(
+ Collections.emptyList(),
+ Collections.emptyList(),
+ Collections.emptyList(),
+ Collections.emptyList(),
+ null,
+ 0,
+ 0,
+ Collections.emptyMap());
+
+ private final List<SnapshotExpireTask> dataFileTasks;
+ private final List<SnapshotExpireTask> changelogFileTasks;
+ private final List<SnapshotExpireTask> manifestTasks;
+ private final List<SnapshotExpireTask> snapshotFileTasks;
+ private final ProtectionSet protectionSet;
+ private final long beginInclusiveId;
+ private final long endExclusiveId;
+
+ /** Pre-collected snapshot cache from planner to avoid redundant snapshot reads. */
+ private final Map<Long, Snapshot> snapshotCache;
+
+ public ExpireSnapshotsPlan(
+ List<SnapshotExpireTask> dataFileTasks,
+ List<SnapshotExpireTask> changelogFileTasks,
+ List<SnapshotExpireTask> manifestTasks,
+ List<SnapshotExpireTask> snapshotFileTasks,
+ ProtectionSet protectionSet,
+ long beginInclusiveId,
+ long endExclusiveId,
+ Map<Long, Snapshot> snapshotCache) {
+ this.dataFileTasks = dataFileTasks;
+ this.changelogFileTasks = changelogFileTasks;
+ this.manifestTasks = manifestTasks;
+ this.snapshotFileTasks = snapshotFileTasks;
+ this.protectionSet = protectionSet;
+ this.beginInclusiveId = beginInclusiveId;
+ this.endExclusiveId = endExclusiveId;
+ this.snapshotCache = snapshotCache;
+ }
+
+ public static ExpireSnapshotsPlan empty() {
+ return EMPTY;
+ }
+
+ public boolean isEmpty() {
+ return dataFileTasks.isEmpty()
+ && changelogFileTasks.isEmpty()
+ && manifestTasks.isEmpty()
+ && snapshotFileTasks.isEmpty();
+ }
+
+ /** Get data file deletion tasks (Phase 1a). These can be executed in parallel. */
+ public List<SnapshotExpireTask> dataFileTasks() {
+ return dataFileTasks;
+ }
+
+ /** Get changelog file deletion tasks (Phase 1b). These can be executed in parallel. */
+ public List<SnapshotExpireTask> changelogFileTasks() {
Review Comment:
Removed.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r3013704053
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/ExpireSnapshotsAction.java:
##########
@@ -50,12 +95,139 @@ public ExpireSnapshotsAction(
this.olderThan = olderThan;
this.maxDeletes = maxDeletes;
this.options = options;
+ this.parallelism = resolveParallelism(parallelism);
+ }
+
+ private int resolveParallelism(Integer parallelism) {
+ if (parallelism != null) {
+ return parallelism;
+ }
+ int envParallelism = env.getParallelism();
+ return envParallelism > 0 ? envParallelism : 1;
}
+ @Override
+ public void run() throws Exception {
+ if (forceStartFlinkJob || parallelism > 1) {
+ // Parallel mode: build custom multi-parallelism Flink pipeline
+ build();
+ if (!env.getTransformations().isEmpty()) {
+ execute(this.getClass().getSimpleName());
+ }
+ } else {
+ // Default: ActionBase handles LocalAction → executeLocally()
+ super.run();
+ }
+ }
+
+ @Override
public void executeLocally() throws Exception {
ExpireSnapshotsProcedure expireSnapshotsProcedure = new ExpireSnapshotsProcedure();
expireSnapshotsProcedure.withCatalog(catalog);
expireSnapshotsProcedure.call(
null, database + "." + table, retainMax, retainMin, olderThan, maxDeletes, options);
}
+
+ @Override
+ public void build() throws Exception {
+ Identifier identifier = new Identifier(database, table);
+
+ // Prepare table with dynamic options
+ HashMap<String, String> dynamicOptions = new HashMap<>();
+ ProcedureUtils.putAllOptions(dynamicOptions, options);
+ FileStoreTable fileStoreTable =
+ (FileStoreTable) catalog.getTable(identifier).copy(dynamicOptions);
+
+ // Build expire config
+ CoreOptions tableOptions = fileStoreTable.store().options();
+ ExpireConfig expireConfig =
+ ProcedureUtils.fillInSnapshotOptions(
+ tableOptions, retainMax, retainMin, olderThan, maxDeletes)
+ .build();
+
+ // Create planner using factory method
+ ExpireSnapshotsPlanner planner = ExpireSnapshotsPlanner.create(fileStoreTable);
+
+ // Plan the expiration
+ ExpireSnapshotsPlan plan = planner.plan(expireConfig);
+ if (plan.isEmpty()) {
+ LOG.info("No snapshots to expire, skipping Flink job submission.");
+ return;
+ }
+
+ LOG.info(
+ "Planning to expire {} snapshots, range=[{}, {})",
+ plan.endExclusiveId() - plan.beginInclusiveId(),
+ plan.beginInclusiveId(),
+ plan.endExclusiveId());
+
+ // Build worker phase
+ DataStream<DeletionReport> reports = buildWorkerPhase(plan, identifier, expireConfig);
+
+ // Build sink phase
+ buildSinkPhase(reports, plan, identifier, expireConfig);
+ }
+
+ /**
+ * Build the worker phase of the Flink job.
+ *
+ * <p>Workers process data file and changelog file deletion tasks in parallel. Tasks are
+ * partitioned by snapshot range to ensure:
+ *
+ * <ul>
+ * <li>Same snapshot range tasks are processed by the same worker
+ * <li>Within each worker, data files are deleted before changelog files
+ * <li>Cache locality is maximized (adjacent snapshots often share manifest files)
+ * </ul>
+ */
+ private DataStream<DeletionReport> buildWorkerPhase(
+ ExpireSnapshotsPlan plan, Identifier identifier, ExpireConfig expireConfig) {
+ // Partition by snapshot range: each worker gets a contiguous range of snapshots
+ // with dataFileTasks first, then changelogFileTasks
+ List<List<SnapshotExpireTask>> partitionedGroups =
+ plan.partitionTasksBySnapshotRange(parallelism);
+
+ DataStreamSource<List<SnapshotExpireTask>> source =
+ env.fromCollection(partitionedGroups).setParallelism(1);
+
+ return source.rebalance()
+ .flatMap(
+ new RangePartitionedExpireFunction(
+ catalogOptions.toMap(),
+ identifier,
+ plan.protectionSet().taggedSnapshots(),
+ plan.snapshotCache(),
+ expireConfig.isChangelogDecoupled()))
+ // Use JavaTypeInfo to ensure proper Java serialization of DeletionReport,
+ // avoiding Kryo's FieldSerializer which cannot handle BinaryRow correctly.
+ // This approach is compatible with both Flink 1.x and 2.x.
Review Comment:
Done. Removed the parallelism > 1 condition. Now only forceStartFlinkJob controls whether to use Flink mode. The DAG stays the same regardless of parallelism setting.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r2973182531
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/ExpireSnapshotsAction.java:
##########
@@ -50,12 +93,135 @@ public ExpireSnapshotsAction(
this.olderThan = olderThan;
this.maxDeletes = maxDeletes;
this.options = options;
+ this.parallelism = resolveParallelism(parallelism);
+ }
+
+ private int resolveParallelism(Integer parallelism) {
+ if (parallelism != null) {
+ return parallelism;
+ }
+ int envParallelism = env.getParallelism();
+ return envParallelism > 0 ? envParallelism : 1;
}
+ @Override
+ public void run() throws Exception {
+ if (forceStartFlinkJob) {
+ // Parallel mode: build custom multi-parallelism Flink pipeline
+ build();
+ execute(this.getClass().getSimpleName());
+ } else {
+ // Default: ActionBase handles LocalAction → executeLocally()
+ super.run();
+ }
+ }
+
+ @Override
public void executeLocally() throws Exception {
ExpireSnapshotsProcedure expireSnapshotsProcedure = new ExpireSnapshotsProcedure();
expireSnapshotsProcedure.withCatalog(catalog);
expireSnapshotsProcedure.call(
null, database + "." + table, retainMax, retainMin, olderThan, maxDeletes, options);
}
+
+ @Override
+ public void build() throws Exception {
+ Identifier identifier = new Identifier(database, table);
+
+ // Prepare table with dynamic options
+ HashMap<String, String> dynamicOptions = new HashMap<>();
+ ProcedureUtils.putAllOptions(dynamicOptions, options);
+ FileStoreTable fileStoreTable =
+ (FileStoreTable) catalog.getTable(identifier).copy(dynamicOptions);
+
+ // Build expire config
+ CoreOptions tableOptions = fileStoreTable.store().options();
+ ExpireConfig expireConfig =
+ ProcedureUtils.fillInSnapshotOptions(
+ tableOptions, retainMax, retainMin, olderThan, maxDeletes)
+ .build();
+
+ // Create planner using factory method
+ ExpireSnapshotsPlanner planner = ExpireSnapshotsPlanner.create(fileStoreTable);
+
+ // Plan the expiration
+ ExpireSnapshotsPlan plan = planner.plan(expireConfig);
+ if (plan.isEmpty()) {
+ LOG.info("No snapshots to expire");
+ return;
Review Comment:
Prefer to keep the early return here. Submitting an empty Flink job still involves cluster resource allocation and scheduling overhead for zero useful work. I've improved the log message to make the skip behavior clear to users.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r2973193068
##########
paimon-core/src/main/java/org/apache/paimon/operation/expire/ExpireSnapshotsExecutor.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.expire;
+
+import org.apache.paimon.Changelog;
+import org.apache.paimon.Snapshot;
+import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.manifest.ExpireFileEntry;
+import org.apache.paimon.operation.SnapshotDeletion;
+import org.apache.paimon.utils.ChangelogManager;
+import org.apache.paimon.utils.SnapshotManager;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Predicate;
+
+import static org.apache.paimon.utils.Preconditions.checkNotNull;
+
+/**
+ * Executor for snapshot expire tasks. This class handles the actual deletion logic based on the
+ * task type defined by {@link SnapshotExpireTask.TaskType}.
+ *
+ * <p>The executor uses switch-based dispatch on task type:
+ *
+ * <ul>
+ * <li>{@link SnapshotExpireTask.TaskType#DELETE_DATA_FILES} → delete data files
+ * <li>{@link SnapshotExpireTask.TaskType#DELETE_CHANGELOG_FILES} → delete changelog files
+ * <li>{@link SnapshotExpireTask.TaskType#DELETE_MANIFESTS} → delete manifest files
+ * <li>{@link SnapshotExpireTask.TaskType#DELETE_SNAPSHOT} → delete snapshot metadata file
+ * </ul>
+ */
+public class ExpireSnapshotsExecutor {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ExpireSnapshotsExecutor.class);
+
+ private final SnapshotManager snapshotManager;
+ private final SnapshotDeletion snapshotDeletion;
+ @Nullable private final ChangelogManager changelogManager;
+
+ /** Pre-collected snapshot cache. Empty map means no cache (read on demand). */
+ private Map<Long, Snapshot> snapshotCache = Collections.emptyMap();
+
+ public ExpireSnapshotsExecutor(
+ SnapshotManager snapshotManager, SnapshotDeletion snapshotDeletion) {
+ this(snapshotManager, snapshotDeletion, null);
+ }
+
+ public ExpireSnapshotsExecutor(
+ SnapshotManager snapshotManager,
+ SnapshotDeletion snapshotDeletion,
+ @Nullable ChangelogManager changelogManager) {
+ this.snapshotManager = snapshotManager;
+ this.snapshotDeletion = snapshotDeletion;
+ this.changelogManager = changelogManager;
+ }
+
+ /** Set pre-collected snapshot cache to avoid redundant reads. */
+ public void setSnapshotCache(Map<Long, Snapshot> snapshotCache) {
+ this.snapshotCache = snapshotCache;
+ }
+
+ /**
+ * Execute a snapshot expire task based on its task type.
+ *
+ * @param task the task to execute
+ * @param taggedSnapshots taggedSnapshots set for data file deletion (required for
+ * DELETE_DATA_FILES)
+ * @param skippingSet manifest skipping set (required for DELETE_MANIFESTS)
+ * @return deletion report with execution results
+ */
+ public DeletionReport execute(
+ SnapshotExpireTask task,
+ @Nullable List<Snapshot> taggedSnapshots,
+ @Nullable Set<String> skippingSet) {
+
+ Snapshot snapshot = snapshotCache.get(task.snapshotId());
+ if (snapshot == null) {
+ try {
+ snapshot = snapshotManager.tryGetSnapshot(task.snapshotId());
+ } catch (FileNotFoundException e) {
+ LOG.warn("Snapshot {} not found, skipping task", task.snapshotId());
+ return DeletionReport.skipped(task.snapshotId());
+ }
+ }
+
+ switch (task.taskType()) {
+ case DELETE_DATA_FILES:
+ return executeDeleteDataFiles(task, snapshot, taggedSnapshots);
+ case DELETE_CHANGELOG_FILES:
+ return executeDeleteChangelogFiles(task, snapshot);
+ case DELETE_MANIFESTS:
+ return executeDeleteManifests(task, snapshot, skippingSet);
+ case DELETE_SNAPSHOT:
+ return executeDeleteSnapshot(task, snapshot);
Review Comment:
done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r2922769763
##########
paimon-core/src/main/java/org/apache/paimon/operation/expire/DeletionReport.java:
##########
@@ -0,0 +1,126 @@
+/*
+ * 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.expire;
+
+import org.apache.paimon.data.BinaryRow;
+
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+/** Report of a single snapshot expiration task. */
+public class DeletionReport implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final long snapshotId;
+
+ /** Whether this task was skipped (e.g., snapshot already deleted). */
+ private boolean skipped;
+
+ /** Whether data files were deleted. */
+ private boolean dataFilesDeleted;
+
+ /** Whether changelog data files were deleted. */
+ private boolean changelogDeleted;
+
+ /** Whether manifest files were deleted. */
+ private boolean manifestsDeleted;
+
+ /** Whether snapshot metadata file was deleted. */
+ private boolean snapshotDeleted;
+
+ /** Buckets that had files deleted (for empty directory cleanup in parallel phase). */
+ private Map<BinaryRow, Set<Integer>> deletionBuckets;
+
+ public DeletionReport(long snapshotId) {
+ this.snapshotId = snapshotId;
+ this.skipped = false;
+ this.dataFilesDeleted = false;
+ this.changelogDeleted = false;
+ this.manifestsDeleted = false;
+ this.snapshotDeleted = false;
+ this.deletionBuckets = new HashMap<>();
+ }
+
+ /**
+ * Create a skipped report for a snapshot that was already deleted.
+ *
+ * @param snapshotId the snapshot ID
+ * @return a skipped deletion report
+ */
+ public static DeletionReport skipped(long snapshotId) {
+ DeletionReport report = new DeletionReport(snapshotId);
+ report.skipped = true;
+ return report;
+ }
+
+ public long snapshotId() {
+ return snapshotId;
+ }
+
+ public boolean isSkipped() {
+ return skipped;
+ }
+
+ public void setDataFilesDeleted(boolean dataFilesDeleted) {
+ this.dataFilesDeleted = dataFilesDeleted;
Review Comment:
Removed the unused fields (dataFilesDeleted, changelogDeleted, manifestsDeleted, snapshotDeleted) and their setters from DeletionReport. Also cleaned up the corresponding setter calls in
ExpireSnapshotsExecutor and updated the test.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r2922764789
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/ExpireSnapshotsAction.java:
##########
@@ -50,12 +95,168 @@ public ExpireSnapshotsAction(
this.olderThan = olderThan;
this.maxDeletes = maxDeletes;
this.options = options;
+ this.parallelism = parallelism;
}
+ /** Returns true if forceStartFlinkJob is enabled and parallelism is greater than 1. */
+ private boolean isParallelMode() {
+ return forceStartFlinkJob && parallelism != null && parallelism > 1;
+ }
+
+ @Override
+ public void run() throws Exception {
+ if (parallelism != null && parallelism > 1 && !forceStartFlinkJob) {
+ throw new IllegalArgumentException(
+ "Parallel expire mode requires both --parallelism > 1 and --force_start_flink_job enabled.");
+ }
+ if (isParallelMode()) {
+ // Parallel mode: build and execute Flink job (multi parallelism)
+ build();
+ execute(this.getClass().getSimpleName());
+ } else if (forceStartFlinkJob) {
+ // Serial mode but forced to run as Flink job (single parallelism)
+ super.run();
+ } else {
+ // Serial mode: execute locally
+ executeLocally();
+ }
+ }
+
+ @Override
public void executeLocally() throws Exception {
ExpireSnapshotsProcedure expireSnapshotsProcedure = new ExpireSnapshotsProcedure();
expireSnapshotsProcedure.withCatalog(catalog);
expireSnapshotsProcedure.call(
null, database + "." + table, retainMax, retainMin, olderThan, maxDeletes, options);
}
+
+ @Override
+ public void build() throws Exception {
+ if (!isParallelMode()) {
+ // Not in parallel mode, nothing to build
+ return;
+ }
+
+ // Prepare table and config using shared method
+ Pair<FileStoreTable, ExpireConfig> prepared =
+ resolveExpireTableAndConfig(
Review Comment:
done
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/ExpireSnapshotsAction.java:
##########
@@ -50,12 +95,168 @@ public ExpireSnapshotsAction(
this.olderThan = olderThan;
this.maxDeletes = maxDeletes;
this.options = options;
+ this.parallelism = parallelism;
}
+ /** Returns true if forceStartFlinkJob is enabled and parallelism is greater than 1. */
+ private boolean isParallelMode() {
+ return forceStartFlinkJob && parallelism != null && parallelism > 1;
+ }
+
+ @Override
+ public void run() throws Exception {
+ if (parallelism != null && parallelism > 1 && !forceStartFlinkJob) {
+ throw new IllegalArgumentException(
+ "Parallel expire mode requires both --parallelism > 1 and --force_start_flink_job enabled.");
+ }
+ if (isParallelMode()) {
+ // Parallel mode: build and execute Flink job (multi parallelism)
+ build();
+ execute(this.getClass().getSimpleName());
+ } else if (forceStartFlinkJob) {
+ // Serial mode but forced to run as Flink job (single parallelism)
+ super.run();
+ } else {
+ // Serial mode: execute locally
+ executeLocally();
+ }
+ }
+
+ @Override
public void executeLocally() throws Exception {
ExpireSnapshotsProcedure expireSnapshotsProcedure = new ExpireSnapshotsProcedure();
expireSnapshotsProcedure.withCatalog(catalog);
expireSnapshotsProcedure.call(
null, database + "." + table, retainMax, retainMin, olderThan, maxDeletes, options);
}
+
+ @Override
+ public void build() throws Exception {
+ if (!isParallelMode()) {
+ // Not in parallel mode, nothing to build
+ return;
+ }
+
+ // Prepare table and config using shared method
+ Pair<FileStoreTable, ExpireConfig> prepared =
+ resolveExpireTableAndConfig(
+ catalog.getTable(Identifier.fromString(database + "." + table)),
Review Comment:
done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r2922790705
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/expire/SnapshotExpireSink.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.expire;
+
+import org.apache.paimon.annotation.VisibleForTesting;
+import org.apache.paimon.catalog.Catalog;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.flink.FlinkCatalogFactory;
+import org.apache.paimon.operation.expire.DeletionReport;
+import org.apache.paimon.operation.expire.ExpireSnapshotsExecutor;
+import org.apache.paimon.operation.expire.SnapshotExpireTask;
+import org.apache.paimon.options.Options;
+import org.apache.paimon.table.FileStoreTable;
+
+import org.apache.flink.api.connector.sink2.InitContext;
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.api.connector.sink2.SinkWriter;
+import org.apache.flink.api.connector.sink2.WriterInitContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Sink that collects deletion reports from parallel expire workers, aggregates the results, and
+ * performs the final commit operations using Sink V2 API.
+ *
+ * <p>In the sink phase (committer), this sink:
+ *
+ * <ul>
+ * <li>Collects all deletion reports from workers
+ * <li>Deletes manifest files serially in snapshot ID order (to avoid concurrent deletion issues)
+ * <li>Deletes snapshot metadata files
+ * <li>Commits changelogs (for changelogDecoupled mode)
+ * <li>Cleans empty directories
+ * <li>Updates earliest hint
+ * </ul>
+ */
+public class SnapshotExpireSink implements Sink<DeletionReport> {
+
+ private static final long serialVersionUID = 1L;
+
+ private static final Logger LOG = LoggerFactory.getLogger(SnapshotExpireSink.class);
+
+ private final Map<String, String> catalogConfig;
+ private final Identifier identifier;
+ private final long endExclusiveId;
+ private final Set<String> manifestSkippingSet;
+ private final List<SnapshotExpireTask> manifestTasks;
+ private final List<SnapshotExpireTask> snapshotFileTasks;
+
+ public SnapshotExpireSink(
+ Map<String, String> catalogConfig,
+ Identifier identifier,
+ long endExclusiveId,
+ Set<String> manifestSkippingSet,
+ List<SnapshotExpireTask> manifestTasks,
+ List<SnapshotExpireTask> snapshotFileTasks) {
+ this.catalogConfig = catalogConfig;
+ this.identifier = identifier;
+ this.endExclusiveId = endExclusiveId;
+ this.manifestSkippingSet = manifestSkippingSet;
+ this.manifestTasks = manifestTasks;
+ this.snapshotFileTasks = snapshotFileTasks;
+ }
+
+ /**
+ * Do not annotate with <code>@override</code> here to maintain compatibility with Flink 2.0+.
+ */
+ public SinkWriter<DeletionReport> createWriter(InitContext context) throws IOException {
+ return new ExpireSinkWriter(initExecutor());
+ }
+
+ @Override
+ public SinkWriter<DeletionReport> createWriter(WriterInitContext context) throws IOException {
+ return new ExpireSinkWriter(initExecutor());
+ }
+
+ /**
+ * Initializes and returns the executor. Subclasses can override this method to provide a custom
+ * executor for testing.
+ */
+ @VisibleForTesting
+ protected ExpireSnapshotsExecutor initExecutor() {
+ try {
+ Options options = Options.fromMap(catalogConfig);
+ Catalog catalog = FlinkCatalogFactory.createPaimonCatalog(options);
+ FileStoreTable table = (FileStoreTable) catalog.getTable(identifier);
+ return new ExpireSnapshotsExecutor(
+ table.snapshotManager(),
+ table.store().newSnapshotDeletion(),
+ table.changelogManager());
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to initialize executor", e);
+ }
+ }
+
+ /** SinkWriter that collects reports and performs commit on flush. */
+ private class ExpireSinkWriter implements SinkWriter<DeletionReport> {
+
+ private final Map<BinaryRow, Set<Integer>> globalDeletionBuckets = new HashMap<>();
+ private final ExpireSnapshotsExecutor executor;
+
+ ExpireSinkWriter(ExpireSnapshotsExecutor executor) {
+ this.executor = executor;
+ }
+
+ @Override
+ public void write(DeletionReport report, Context context) {
+ if (!report.isSkipped()) {
+ report.deletionBuckets()
+ .forEach(
+ (partition, buckets) ->
+ globalDeletionBuckets
+ .computeIfAbsent(partition, k -> new HashSet<>())
+ .addAll(buckets));
+ }
+ }
+
+ @Override
+ public void flush(boolean endOfInput) {
+ if (!endOfInput) {
+ return;
+ }
+
+ LOG.info(
+ "Expire sink received: {} manifest tasks, {} snapshot tasks",
+ manifestTasks.size(),
+ snapshotFileTasks.size());
+
+ // 1. Clean empty directories
+ executor.cleanEmptyDirectories(globalDeletionBuckets);
Review Comment:
This is already handled. The snapshotDeletion is initialized with options.cleanEmptyDirectories(), so it respects the configuration automatically when cleanEmptyDirectories() is called.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r2922827667
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/ExpireSnapshotsAction.java:
##########
@@ -50,12 +95,168 @@ public ExpireSnapshotsAction(
this.olderThan = olderThan;
this.maxDeletes = maxDeletes;
this.options = options;
+ this.parallelism = parallelism;
}
+ /** Returns true if forceStartFlinkJob is enabled and parallelism is greater than 1. */
+ private boolean isParallelMode() {
+ return forceStartFlinkJob && parallelism != null && parallelism > 1;
Review Comment:
Thanks for the suggestions! I've made --parallelism optional — when not specified, it falls back to env.getParallelism(), so users can control it via Flink configuration naturally. (Automatic parallelism inference based on workload is out of scope for this PR.)
Regarding the dynamic task fetching approach (env.fromSequence(startId, endId).flatMap(...)), the current design intentionally separates deletion into two phases:
- Worker phase (parallel): deletes data files and changelog files
- Sink phase (serial): deletes manifests and snapshot metadata files
This separation is necessary because:
1. manifestSkippingSet is global and mutable: Built from all tags + endSnapshot manifests. Parallel manifest deletion would require distributed coordination to safely update this set — significantly more complex.
2. Serial deletion ensures consistency: Parallel snapshot deletion could leave gaps (e.g., snapshots 1, 3, 5 exist but 2, 4 are deleted), which is confusing for users. Serial execution in the sink ensures clean, contiguous
deletion.
3. Range partitioning maximizes cache locality: createDataFileSkipperForTags caches tag data files internally. Adjacent snapshots typically share the same nearest tag, so processing contiguous ranges avoids expensive cache rebuilds. Dynamic task fetching (each subtask fetching the next available split) would scatter snapshots across subtasks and break this cache benefit.
Data file deletion is the most time-consuming part and is safely parallelizable. Manifest/snapshot deletion is lightweight but requires ordering guarantees, so serial execution in the sink is the right trade-off.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r2973193068
##########
paimon-core/src/main/java/org/apache/paimon/operation/expire/ExpireSnapshotsExecutor.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.expire;
+
+import org.apache.paimon.Changelog;
+import org.apache.paimon.Snapshot;
+import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.manifest.ExpireFileEntry;
+import org.apache.paimon.operation.SnapshotDeletion;
+import org.apache.paimon.utils.ChangelogManager;
+import org.apache.paimon.utils.SnapshotManager;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Predicate;
+
+import static org.apache.paimon.utils.Preconditions.checkNotNull;
+
+/**
+ * Executor for snapshot expire tasks. This class handles the actual deletion logic based on the
+ * task type defined by {@link SnapshotExpireTask.TaskType}.
+ *
+ * <p>The executor uses switch-based dispatch on task type:
+ *
+ * <ul>
+ * <li>{@link SnapshotExpireTask.TaskType#DELETE_DATA_FILES} → delete data files
+ * <li>{@link SnapshotExpireTask.TaskType#DELETE_CHANGELOG_FILES} → delete changelog files
+ * <li>{@link SnapshotExpireTask.TaskType#DELETE_MANIFESTS} → delete manifest files
+ * <li>{@link SnapshotExpireTask.TaskType#DELETE_SNAPSHOT} → delete snapshot metadata file
+ * </ul>
+ */
+public class ExpireSnapshotsExecutor {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ExpireSnapshotsExecutor.class);
+
+ private final SnapshotManager snapshotManager;
+ private final SnapshotDeletion snapshotDeletion;
+ @Nullable private final ChangelogManager changelogManager;
+
+ /** Pre-collected snapshot cache. Empty map means no cache (read on demand). */
+ private Map<Long, Snapshot> snapshotCache = Collections.emptyMap();
+
+ public ExpireSnapshotsExecutor(
+ SnapshotManager snapshotManager, SnapshotDeletion snapshotDeletion) {
+ this(snapshotManager, snapshotDeletion, null);
+ }
+
+ public ExpireSnapshotsExecutor(
+ SnapshotManager snapshotManager,
+ SnapshotDeletion snapshotDeletion,
+ @Nullable ChangelogManager changelogManager) {
+ this.snapshotManager = snapshotManager;
+ this.snapshotDeletion = snapshotDeletion;
+ this.changelogManager = changelogManager;
+ }
+
+ /** Set pre-collected snapshot cache to avoid redundant reads. */
+ public void setSnapshotCache(Map<Long, Snapshot> snapshotCache) {
+ this.snapshotCache = snapshotCache;
+ }
+
+ /**
+ * Execute a snapshot expire task based on its task type.
+ *
+ * @param task the task to execute
+ * @param taggedSnapshots taggedSnapshots set for data file deletion (required for
+ * DELETE_DATA_FILES)
+ * @param skippingSet manifest skipping set (required for DELETE_MANIFESTS)
+ * @return deletion report with execution results
+ */
+ public DeletionReport execute(
+ SnapshotExpireTask task,
+ @Nullable List<Snapshot> taggedSnapshots,
+ @Nullable Set<String> skippingSet) {
+
+ Snapshot snapshot = snapshotCache.get(task.snapshotId());
+ if (snapshot == null) {
+ try {
+ snapshot = snapshotManager.tryGetSnapshot(task.snapshotId());
+ } catch (FileNotFoundException e) {
+ LOG.warn("Snapshot {} not found, skipping task", task.snapshotId());
+ return DeletionReport.skipped(task.snapshotId());
+ }
+ }
+
+ switch (task.taskType()) {
+ case DELETE_DATA_FILES:
+ return executeDeleteDataFiles(task, snapshot, taggedSnapshots);
+ case DELETE_CHANGELOG_FILES:
+ return executeDeleteChangelogFiles(task, snapshot);
+ case DELETE_MANIFESTS:
+ return executeDeleteManifests(task, snapshot, skippingSet);
+ case DELETE_SNAPSHOT:
+ return executeDeleteSnapshot(task, snapshot);
Review Comment:
Refactored as suggested. Replaced the ExpireSnapshotsExecutor switch-based dispatch with polymorphic SnapshotExpireTask subclasses (DeleteDataFilesTask, DeleteChangelogFilesTask,
DeleteManifestsTask, DeleteSnapshotTask). Each subclass encapsulates its own deletion logic via execute(ExpireContext). Also simplified ExpireContext by removing delegate methods — callers now access underlying objects directly (e.g., context.snapshotDeletion().cleanUnusedDataFiles()). taggedSnapshots and snapshotCache are now constructor parameters of ExpireContext instead of setters.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r2922844126
##########
paimon-core/src/main/java/org/apache/paimon/operation/expire/ExpireSnapshotsPlan.java:
##########
@@ -0,0 +1,218 @@
+/*
+ * 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.expire;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The plan for snapshot expiration, containing four groups of tasks organized by deletion phase.
+ *
+ * <p>The plan organizes tasks into four groups for correct deletion order:
+ *
+ * <ul>
+ * <li>{@link #dataFileTasks()}: Phase 1a - Delete data files (can be parallelized)
+ * <li>{@link #changelogFileTasks()}: Phase 1b - Delete changelog files (can be parallelized)
+ * <li>{@link #manifestTasks()}: Phase 2a - Delete manifest files (serial)
+ * <li>{@link #snapshotFileTasks()}: Phase 2b - Delete snapshot metadata files (serial)
+ * </ul>
+ */
+public class ExpireSnapshotsPlan implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private static final ExpireSnapshotsPlan EMPTY =
+ new ExpireSnapshotsPlan(
+ Collections.emptyList(),
+ Collections.emptyList(),
+ Collections.emptyList(),
+ Collections.emptyList(),
+ null,
+ 0,
+ 0);
+
+ private final List<SnapshotExpireTask> dataFileTasks;
+ private final List<SnapshotExpireTask> changelogFileTasks;
+ private final List<SnapshotExpireTask> manifestTasks;
+ private final List<SnapshotExpireTask> snapshotFileTasks;
+ private final ProtectionSet protectionSet;
+ private final long beginInclusiveId;
+ private final long endExclusiveId;
+
+ public ExpireSnapshotsPlan(
+ List<SnapshotExpireTask> dataFileTasks,
+ List<SnapshotExpireTask> changelogFileTasks,
+ List<SnapshotExpireTask> manifestTasks,
+ List<SnapshotExpireTask> snapshotFileTasks,
+ ProtectionSet protectionSet,
+ long beginInclusiveId,
+ long endExclusiveId) {
+ this.dataFileTasks = dataFileTasks;
+ this.changelogFileTasks = changelogFileTasks;
+ this.manifestTasks = manifestTasks;
+ this.snapshotFileTasks = snapshotFileTasks;
+ this.protectionSet = protectionSet;
+ this.beginInclusiveId = beginInclusiveId;
+ this.endExclusiveId = endExclusiveId;
+ }
+
+ public static ExpireSnapshotsPlan empty() {
+ return EMPTY;
+ }
+
+ public boolean isEmpty() {
+ return dataFileTasks.isEmpty()
+ && changelogFileTasks.isEmpty()
+ && manifestTasks.isEmpty()
+ && snapshotFileTasks.isEmpty();
+ }
+
+ /** Get data file deletion tasks (Phase 1a). These can be executed in parallel. */
+ public List<SnapshotExpireTask> dataFileTasks() {
+ return dataFileTasks;
+ }
+
+ /** Get changelog file deletion tasks (Phase 1b). These can be executed in parallel. */
+ public List<SnapshotExpireTask> changelogFileTasks() {
+ return changelogFileTasks;
+ }
+
+ /** Get manifest deletion tasks (Phase 2a). These should be executed serially. */
+ public List<SnapshotExpireTask> manifestTasks() {
+ return manifestTasks;
+ }
+
+ /** Get snapshot file deletion tasks (Phase 2b). These should be executed serially. */
+ public List<SnapshotExpireTask> snapshotFileTasks() {
+ return snapshotFileTasks;
+ }
+
+ /**
+ * Partition tasks into groups by snapshot ID range for parallel mode execution.
+ *
+ * <p>Each group contains tasks for a contiguous range of snapshots, with dataFileTasks first,
+ * then changelogFileTasks. This ensures:
+ *
+ * <ul>
+ * <li>Same snapshot range tasks are processed by the same worker
+ * <li>Within each worker, data files are deleted before changelog files
+ * </ul>
+ *
+ * <p>For example, with beginInclusiveId=1, endExclusiveId=11, parallelism=3:
+ *
+ * <ul>
+ * <li>Worker 0 (snapshot 1-4): [dataTask(2,3,4), changelogTask(1,2,3,4)]
+ * <li>Worker 1 (snapshot 5-8): [dataTask(5,6,7,8), changelogTask(5,6,7,8)]
+ * <li>Worker 2 (snapshot 9-11): [dataTask(9,10,11), changelogTask(9,10)]
+ * </ul>
+ *
+ * @param parallelism target parallelism for distribution
+ * @return list of task groups, one per worker
+ */
+ public List<List<SnapshotExpireTask>> partitionTasksBySnapshotRange(int parallelism) {
Review Comment:
The simplified approach (env.fromSequence + flatMap) has two main issues:
1. Gap problem: Parallel deletion could leave gaps in snapshot history (e.g., 1, 3, 5 exist but 2, 4 are deleted), which is confusing for users.
2. Cache locality: Adjacent snapshots typically share the same nearest tag. Range partitioning allows each subtask to reuse createDataFileSkipperForTags cache, while dynamic fetching would scatter snapshots and break this benefit.
See my response in comment#2 for more details.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r2973185462
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/expire/RangePartitionedExpireFunction.java:
##########
@@ -0,0 +1,115 @@
+/*
+ * 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.expire;
+
+import org.apache.paimon.Snapshot;
+import org.apache.paimon.catalog.Catalog;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.flink.FlinkCatalogFactory;
+import org.apache.paimon.operation.SnapshotDeletion;
+import org.apache.paimon.operation.expire.DeletionReport;
+import org.apache.paimon.operation.expire.ExpireSnapshotsExecutor;
+import org.apache.paimon.operation.expire.SnapshotExpireTask;
+import org.apache.paimon.options.Options;
+import org.apache.paimon.table.FileStoreTable;
+
+import org.apache.flink.api.common.functions.OpenContext;
+import org.apache.flink.api.common.functions.RichFlatMapFunction;
+import org.apache.flink.util.Collector;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Flink flatMap function for range-partitioned snapshot expiration (worker phase).
+ *
+ * <p>This function processes a batch of {@link SnapshotExpireTask}s that belong to the same
+ * contiguous range. Each subtask receives a list of tasks (e.g., subtask 0 gets snap 1-4, subtask 1
+ * gets snap 5-8) and processes them sequentially in order.
+ *
+ * <p>Processing tasks in order within each subtask maximizes cache locality since adjacent
+ * snapshots often share manifest files.
+ *
+ * <p>In worker phase, this function only deletes data files and changelog data files. Manifest and
+ * snapshot metadata deletion is deferred to the sink phase to avoid concurrent deletion issues.
+ *
+ * <p>This function uses {@link ExpireSnapshotsExecutor#execute} which loads tag data files
+ * on-demand with internal caching.
+ */
+public class RangePartitionedExpireFunction
+ extends RichFlatMapFunction<List<SnapshotExpireTask>, DeletionReport> {
+
+ private static final long serialVersionUID = 1L;
+
+ private final Map<String, String> catalogConfig;
+ private final Identifier identifier;
+ private final List<Snapshot> taggedSnapshots;
+ private final boolean changelogDecoupled;
+
+ private transient ExpireSnapshotsExecutor executor;
+
+ public RangePartitionedExpireFunction(
+ Map<String, String> catalogConfig,
+ Identifier identifier,
+ List<Snapshot> taggedSnapshots,
+ boolean changelogDecoupled) {
+ this.catalogConfig = catalogConfig;
+ this.identifier = identifier;
+ this.taggedSnapshots = taggedSnapshots;
+ this.changelogDecoupled = changelogDecoupled;
+ }
+
+ @Override
+ public void open(OpenContext openContext) throws Exception {
+ this.executor = initExecutor();
+ }
+
+ /**
+ * Initializes and returns the executor for processing expire tasks. Subclasses can override
+ * this method to provide a custom executor for testing without catalog access.
+ *
+ * <p>Default implementation creates executor from catalog using {@link #catalogConfig} and
+ * {@link #identifier}.
+ */
+ protected ExpireSnapshotsExecutor initExecutor() throws Exception {
+ Options options = Options.fromMap(catalogConfig);
+ Catalog catalog = FlinkCatalogFactory.createPaimonCatalog(options);
+ FileStoreTable table = (FileStoreTable) catalog.getTable(identifier);
+ SnapshotDeletion deletion = table.store().newSnapshotDeletion();
+ deletion.setChangelogDecoupled(changelogDecoupled);
+ return new ExpireSnapshotsExecutor(table.snapshotManager(), deletion);
+ }
+
+ @Override
+ public void flatMap(List<SnapshotExpireTask> tasks, Collector<DeletionReport> out)
+ throws Exception {
+ // Process tasks sequentially in order to maximize cache locality
+ for (SnapshotExpireTask task : tasks) {
Review Comment:
Done. Added progress logging: batch-level start/end at INFO with elapsed time, per-task detail with task type, snapshot ID and progress counter.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "yunfengzhou-hub (via GitHub)" <gi...@apache.org>.
yunfengzhou-hub commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r2845262054
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/ExpireSnapshotsAction.java:
##########
@@ -50,12 +95,168 @@ public ExpireSnapshotsAction(
this.olderThan = olderThan;
this.maxDeletes = maxDeletes;
this.options = options;
+ this.parallelism = parallelism;
}
+ /** Returns true if forceStartFlinkJob is enabled and parallelism is greater than 1. */
+ private boolean isParallelMode() {
+ return forceStartFlinkJob && parallelism != null && parallelism > 1;
+ }
+
+ @Override
+ public void run() throws Exception {
+ if (parallelism != null && parallelism > 1 && !forceStartFlinkJob) {
+ throw new IllegalArgumentException(
+ "Parallel expire mode requires both --parallelism > 1 and --force_start_flink_job enabled.");
+ }
+ if (isParallelMode()) {
+ // Parallel mode: build and execute Flink job (multi parallelism)
+ build();
+ execute(this.getClass().getSimpleName());
+ } else if (forceStartFlinkJob) {
+ // Serial mode but forced to run as Flink job (single parallelism)
+ super.run();
+ } else {
+ // Serial mode: execute locally
+ executeLocally();
+ }
+ }
+
+ @Override
public void executeLocally() throws Exception {
ExpireSnapshotsProcedure expireSnapshotsProcedure = new ExpireSnapshotsProcedure();
expireSnapshotsProcedure.withCatalog(catalog);
expireSnapshotsProcedure.call(
null, database + "." + table, retainMax, retainMin, olderThan, maxDeletes, options);
}
+
+ @Override
+ public void build() throws Exception {
+ if (!isParallelMode()) {
+ // Not in parallel mode, nothing to build
+ return;
+ }
+
+ // Prepare table and config using shared method
+ Pair<FileStoreTable, ExpireConfig> prepared =
+ resolveExpireTableAndConfig(
+ catalog.getTable(Identifier.fromString(database + "." + table)),
Review Comment:
In line 168 there is
```java
Identifier identifier = new Identifier(database, table);
```
We can move this line to above to reuse the created identifier variable here.
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/ExpireSnapshotsAction.java:
##########
@@ -50,12 +95,168 @@ public ExpireSnapshotsAction(
this.olderThan = olderThan;
this.maxDeletes = maxDeletes;
this.options = options;
+ this.parallelism = parallelism;
}
+ /** Returns true if forceStartFlinkJob is enabled and parallelism is greater than 1. */
+ private boolean isParallelMode() {
+ return forceStartFlinkJob && parallelism != null && parallelism > 1;
+ }
+
+ @Override
+ public void run() throws Exception {
Review Comment:
In case this method is overridden, this class needs not implement `LocalAction` anymore. Still you can keep the `executeLocally` method for internal use.
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/ExpireSnapshotsAction.java:
##########
@@ -50,12 +95,168 @@ public ExpireSnapshotsAction(
this.olderThan = olderThan;
this.maxDeletes = maxDeletes;
this.options = options;
+ this.parallelism = parallelism;
}
+ /** Returns true if forceStartFlinkJob is enabled and parallelism is greater than 1. */
+ private boolean isParallelMode() {
+ return forceStartFlinkJob && parallelism != null && parallelism > 1;
Review Comment:
Forcing users to set the parallelism of this action might increase their burden to understand the logic of Paimon. It might be better to derive the parallelism of the job automatically on its own by default.
I noticed that `parallelism` is mainly used to distribute `SnapshotExpireTask`s evenly between the `RangePartitionedExpireFunction` subtasks, so this PR created a `List<List<SnapshotExpireTask>>` with `parallelism` batches. Compared with this design, a better way for Flink might be to have the subtasks directly fetch from the original list, continuing to consume the next task after completing the former one. On the one hand, this would make it unnecessary to decide the parallelism of the job from the beginning. On the other hand, this could also achieve better dynamic rebalancing during runtime in case different `SnapshotExpireTask`s have different workloads.
Besides, the Flink configuration might be a better place to set the job's parallelism, compared with Action arguments.
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/expire/SnapshotExpireSink.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.expire;
+
+import org.apache.paimon.annotation.VisibleForTesting;
+import org.apache.paimon.catalog.Catalog;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.flink.FlinkCatalogFactory;
+import org.apache.paimon.operation.expire.DeletionReport;
+import org.apache.paimon.operation.expire.ExpireSnapshotsExecutor;
+import org.apache.paimon.operation.expire.SnapshotExpireTask;
+import org.apache.paimon.options.Options;
+import org.apache.paimon.table.FileStoreTable;
+
+import org.apache.flink.api.connector.sink2.InitContext;
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.api.connector.sink2.SinkWriter;
+import org.apache.flink.api.connector.sink2.WriterInitContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Sink that collects deletion reports from parallel expire workers, aggregates the results, and
+ * performs the final commit operations using Sink V2 API.
+ *
+ * <p>In the sink phase (committer), this sink:
+ *
+ * <ul>
+ * <li>Collects all deletion reports from workers
+ * <li>Deletes manifest files serially in snapshot ID order (to avoid concurrent deletion issues)
+ * <li>Deletes snapshot metadata files
+ * <li>Commits changelogs (for changelogDecoupled mode)
+ * <li>Cleans empty directories
+ * <li>Updates earliest hint
+ * </ul>
+ */
+public class SnapshotExpireSink implements Sink<DeletionReport> {
+
+ private static final long serialVersionUID = 1L;
+
+ private static final Logger LOG = LoggerFactory.getLogger(SnapshotExpireSink.class);
+
+ private final Map<String, String> catalogConfig;
+ private final Identifier identifier;
+ private final long endExclusiveId;
+ private final Set<String> manifestSkippingSet;
+ private final List<SnapshotExpireTask> manifestTasks;
+ private final List<SnapshotExpireTask> snapshotFileTasks;
+
+ public SnapshotExpireSink(
+ Map<String, String> catalogConfig,
+ Identifier identifier,
+ long endExclusiveId,
+ Set<String> manifestSkippingSet,
+ List<SnapshotExpireTask> manifestTasks,
+ List<SnapshotExpireTask> snapshotFileTasks) {
+ this.catalogConfig = catalogConfig;
+ this.identifier = identifier;
+ this.endExclusiveId = endExclusiveId;
+ this.manifestSkippingSet = manifestSkippingSet;
+ this.manifestTasks = manifestTasks;
+ this.snapshotFileTasks = snapshotFileTasks;
+ }
+
+ /**
+ * Do not annotate with <code>@override</code> here to maintain compatibility with Flink 2.0+.
+ */
+ public SinkWriter<DeletionReport> createWriter(InitContext context) throws IOException {
+ return new ExpireSinkWriter(initExecutor());
+ }
+
+ @Override
+ public SinkWriter<DeletionReport> createWriter(WriterInitContext context) throws IOException {
+ return new ExpireSinkWriter(initExecutor());
+ }
+
+ /**
+ * Initializes and returns the executor. Subclasses can override this method to provide a custom
+ * executor for testing.
+ */
+ @VisibleForTesting
+ protected ExpireSnapshotsExecutor initExecutor() {
+ try {
+ Options options = Options.fromMap(catalogConfig);
+ Catalog catalog = FlinkCatalogFactory.createPaimonCatalog(options);
+ FileStoreTable table = (FileStoreTable) catalog.getTable(identifier);
+ return new ExpireSnapshotsExecutor(
+ table.snapshotManager(),
+ table.store().newSnapshotDeletion(),
+ table.changelogManager());
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to initialize executor", e);
+ }
+ }
+
+ /** SinkWriter that collects reports and performs commit on flush. */
+ private class ExpireSinkWriter implements SinkWriter<DeletionReport> {
+
+ private final Map<BinaryRow, Set<Integer>> globalDeletionBuckets = new HashMap<>();
+ private final ExpireSnapshotsExecutor executor;
+
+ ExpireSinkWriter(ExpireSnapshotsExecutor executor) {
+ this.executor = executor;
+ }
+
+ @Override
+ public void write(DeletionReport report, Context context) {
+ if (!report.isSkipped()) {
+ report.deletionBuckets()
+ .forEach(
+ (partition, buckets) ->
+ globalDeletionBuckets
+ .computeIfAbsent(partition, k -> new HashSet<>())
+ .addAll(buckets));
+ }
+ }
+
+ @Override
+ public void flush(boolean endOfInput) {
+ if (!endOfInput) {
+ return;
+ }
+
+ LOG.info(
+ "Expire sink received: {} manifest tasks, {} snapshot tasks",
+ manifestTasks.size(),
+ snapshotFileTasks.size());
+
+ // 1. Clean empty directories
+ executor.cleanEmptyDirectories(globalDeletionBuckets);
Review Comment:
The implementation here should be aware of the configuration `snapshot.clean-empty-directories`.
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/ExpireSnapshotsAction.java:
##########
@@ -50,12 +95,168 @@ public ExpireSnapshotsAction(
this.olderThan = olderThan;
this.maxDeletes = maxDeletes;
this.options = options;
+ this.parallelism = parallelism;
}
+ /** Returns true if forceStartFlinkJob is enabled and parallelism is greater than 1. */
+ private boolean isParallelMode() {
+ return forceStartFlinkJob && parallelism != null && parallelism > 1;
+ }
+
+ @Override
+ public void run() throws Exception {
+ if (parallelism != null && parallelism > 1 && !forceStartFlinkJob) {
+ throw new IllegalArgumentException(
+ "Parallel expire mode requires both --parallelism > 1 and --force_start_flink_job enabled.");
+ }
+ if (isParallelMode()) {
+ // Parallel mode: build and execute Flink job (multi parallelism)
+ build();
+ execute(this.getClass().getSimpleName());
+ } else if (forceStartFlinkJob) {
+ // Serial mode but forced to run as Flink job (single parallelism)
+ super.run();
+ } else {
+ // Serial mode: execute locally
+ executeLocally();
+ }
+ }
+
+ @Override
public void executeLocally() throws Exception {
ExpireSnapshotsProcedure expireSnapshotsProcedure = new ExpireSnapshotsProcedure();
expireSnapshotsProcedure.withCatalog(catalog);
expireSnapshotsProcedure.call(
null, database + "." + table, retainMax, retainMin, olderThan, maxDeletes, options);
}
+
+ @Override
+ public void build() throws Exception {
+ if (!isParallelMode()) {
+ // Not in parallel mode, nothing to build
+ return;
+ }
+
+ // Prepare table and config using shared method
+ Pair<FileStoreTable, ExpireConfig> prepared =
+ resolveExpireTableAndConfig(
Review Comment:
The introduction of method `resolveExpireTableAndConfig` seems to increase the code complexity a little bit. It might be better to directly put its implementation here.
##########
paimon-core/src/main/java/org/apache/paimon/operation/expire/ExpireSnapshotsPlan.java:
##########
@@ -0,0 +1,218 @@
+/*
+ * 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.expire;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The plan for snapshot expiration, containing four groups of tasks organized by deletion phase.
+ *
+ * <p>The plan organizes tasks into four groups for correct deletion order:
+ *
+ * <ul>
+ * <li>{@link #dataFileTasks()}: Phase 1a - Delete data files (can be parallelized)
+ * <li>{@link #changelogFileTasks()}: Phase 1b - Delete changelog files (can be parallelized)
+ * <li>{@link #manifestTasks()}: Phase 2a - Delete manifest files (serial)
+ * <li>{@link #snapshotFileTasks()}: Phase 2b - Delete snapshot metadata files (serial)
+ * </ul>
+ */
+public class ExpireSnapshotsPlan implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private static final ExpireSnapshotsPlan EMPTY =
+ new ExpireSnapshotsPlan(
+ Collections.emptyList(),
+ Collections.emptyList(),
+ Collections.emptyList(),
+ Collections.emptyList(),
+ null,
+ 0,
+ 0);
+
+ private final List<SnapshotExpireTask> dataFileTasks;
+ private final List<SnapshotExpireTask> changelogFileTasks;
+ private final List<SnapshotExpireTask> manifestTasks;
+ private final List<SnapshotExpireTask> snapshotFileTasks;
+ private final ProtectionSet protectionSet;
+ private final long beginInclusiveId;
+ private final long endExclusiveId;
+
+ public ExpireSnapshotsPlan(
+ List<SnapshotExpireTask> dataFileTasks,
+ List<SnapshotExpireTask> changelogFileTasks,
+ List<SnapshotExpireTask> manifestTasks,
+ List<SnapshotExpireTask> snapshotFileTasks,
+ ProtectionSet protectionSet,
+ long beginInclusiveId,
+ long endExclusiveId) {
+ this.dataFileTasks = dataFileTasks;
+ this.changelogFileTasks = changelogFileTasks;
+ this.manifestTasks = manifestTasks;
+ this.snapshotFileTasks = snapshotFileTasks;
+ this.protectionSet = protectionSet;
+ this.beginInclusiveId = beginInclusiveId;
+ this.endExclusiveId = endExclusiveId;
+ }
+
+ public static ExpireSnapshotsPlan empty() {
+ return EMPTY;
+ }
+
+ public boolean isEmpty() {
+ return dataFileTasks.isEmpty()
+ && changelogFileTasks.isEmpty()
+ && manifestTasks.isEmpty()
+ && snapshotFileTasks.isEmpty();
+ }
+
+ /** Get data file deletion tasks (Phase 1a). These can be executed in parallel. */
+ public List<SnapshotExpireTask> dataFileTasks() {
+ return dataFileTasks;
+ }
+
+ /** Get changelog file deletion tasks (Phase 1b). These can be executed in parallel. */
+ public List<SnapshotExpireTask> changelogFileTasks() {
+ return changelogFileTasks;
+ }
+
+ /** Get manifest deletion tasks (Phase 2a). These should be executed serially. */
+ public List<SnapshotExpireTask> manifestTasks() {
+ return manifestTasks;
+ }
+
+ /** Get snapshot file deletion tasks (Phase 2b). These should be executed serially. */
+ public List<SnapshotExpireTask> snapshotFileTasks() {
+ return snapshotFileTasks;
+ }
+
+ /**
+ * Partition tasks into groups by snapshot ID range for parallel mode execution.
+ *
+ * <p>Each group contains tasks for a contiguous range of snapshots, with dataFileTasks first,
+ * then changelogFileTasks. This ensures:
+ *
+ * <ul>
+ * <li>Same snapshot range tasks are processed by the same worker
+ * <li>Within each worker, data files are deleted before changelog files
+ * </ul>
+ *
+ * <p>For example, with beginInclusiveId=1, endExclusiveId=11, parallelism=3:
+ *
+ * <ul>
+ * <li>Worker 0 (snapshot 1-4): [dataTask(2,3,4), changelogTask(1,2,3,4)]
+ * <li>Worker 1 (snapshot 5-8): [dataTask(5,6,7,8), changelogTask(5,6,7,8)]
+ * <li>Worker 2 (snapshot 9-11): [dataTask(9,10,11), changelogTask(9,10)]
+ * </ul>
+ *
+ * @param parallelism target parallelism for distribution
+ * @return list of task groups, one per worker
+ */
+ public List<List<SnapshotExpireTask>> partitionTasksBySnapshotRange(int parallelism) {
Review Comment:
It seems that this PR divides the expire process of a snapshot into different `SnapshotExpireTask`s first, and then sends the tasks of the same snapshot to the same Flink subtask. If this is the case, why should this PR make the division first? Would the following implementation simpler?
```java
// calculates the start and end snapshot id before this part of code
env.fromSequence(startId, endId)
.flatMap(new SnapshotExpireFunction()) // deletes the data, manifest, and snapshot file sequentially
.sinkTo(new SnapshotExpireSink());
```
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/expire/SnapshotExpireSink.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.expire;
+
+import org.apache.paimon.annotation.VisibleForTesting;
+import org.apache.paimon.catalog.Catalog;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.flink.FlinkCatalogFactory;
+import org.apache.paimon.operation.expire.DeletionReport;
+import org.apache.paimon.operation.expire.ExpireSnapshotsExecutor;
+import org.apache.paimon.operation.expire.SnapshotExpireTask;
+import org.apache.paimon.options.Options;
+import org.apache.paimon.table.FileStoreTable;
+
+import org.apache.flink.api.connector.sink2.InitContext;
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.api.connector.sink2.SinkWriter;
+import org.apache.flink.api.connector.sink2.WriterInitContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Sink that collects deletion reports from parallel expire workers, aggregates the results, and
+ * performs the final commit operations using Sink V2 API.
+ *
+ * <p>In the sink phase (committer), this sink:
+ *
+ * <ul>
+ * <li>Collects all deletion reports from workers
+ * <li>Deletes manifest files serially in snapshot ID order (to avoid concurrent deletion issues)
+ * <li>Deletes snapshot metadata files
+ * <li>Commits changelogs (for changelogDecoupled mode)
+ * <li>Cleans empty directories
+ * <li>Updates earliest hint
+ * </ul>
+ */
+public class SnapshotExpireSink implements Sink<DeletionReport> {
+
+ private static final long serialVersionUID = 1L;
+
+ private static final Logger LOG = LoggerFactory.getLogger(SnapshotExpireSink.class);
+
+ private final Map<String, String> catalogConfig;
+ private final Identifier identifier;
+ private final long endExclusiveId;
+ private final Set<String> manifestSkippingSet;
+ private final List<SnapshotExpireTask> manifestTasks;
+ private final List<SnapshotExpireTask> snapshotFileTasks;
+
+ public SnapshotExpireSink(
+ Map<String, String> catalogConfig,
+ Identifier identifier,
+ long endExclusiveId,
+ Set<String> manifestSkippingSet,
+ List<SnapshotExpireTask> manifestTasks,
+ List<SnapshotExpireTask> snapshotFileTasks) {
+ this.catalogConfig = catalogConfig;
+ this.identifier = identifier;
+ this.endExclusiveId = endExclusiveId;
+ this.manifestSkippingSet = manifestSkippingSet;
+ this.manifestTasks = manifestTasks;
+ this.snapshotFileTasks = snapshotFileTasks;
+ }
+
+ /**
+ * Do not annotate with <code>@override</code> here to maintain compatibility with Flink 2.0+.
+ */
+ public SinkWriter<DeletionReport> createWriter(InitContext context) throws IOException {
+ return new ExpireSinkWriter(initExecutor());
+ }
+
+ @Override
Review Comment:
Do we need the following javadoc here?
```java
/**
* Do not annotate with <code>@override</code> here to maintain compatibility with Flink 1.18-.
*/
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r3013705158
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/expire/DeletionReport.java:
##########
@@ -0,0 +1,86 @@
+/*
+ * 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.expire;
+
+import org.apache.paimon.data.BinaryRow;
+
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+/** Report of a single snapshot expiration task. */
+public class DeletionReport implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final long snapshotId;
+
+ /** Whether this task was skipped (e.g., snapshot already deleted). */
+ private boolean skipped;
+
+ /** Buckets that had files deleted (for empty directory cleanup in parallel phase). */
+ private Map<BinaryRow, Set<Integer>> deletionBuckets;
+
+ public DeletionReport(long snapshotId) {
+ this.snapshotId = snapshotId;
+ this.skipped = false;
+ this.deletionBuckets = new HashMap<>();
+ }
+
+ /**
+ * Create a skipped report for a snapshot that was already deleted.
+ *
+ * @param snapshotId the snapshot ID
+ * @return a skipped deletion report
+ */
+ public static DeletionReport skipped(long snapshotId) {
+ DeletionReport report = new DeletionReport(snapshotId);
+ report.skipped = true;
+ return report;
+ }
+
+ public long snapshotId() {
Review Comment:
Added @VisibleForTesting annotation to snapshotId().
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "yunfengzhou-hub (via GitHub)" <gi...@apache.org>.
yunfengzhou-hub commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r2850272412
##########
paimon-core/src/main/java/org/apache/paimon/operation/expire/DeletionReport.java:
##########
@@ -0,0 +1,126 @@
+/*
+ * 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.expire;
+
+import org.apache.paimon.data.BinaryRow;
+
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+/** Report of a single snapshot expiration task. */
+public class DeletionReport implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final long snapshotId;
+
+ /** Whether this task was skipped (e.g., snapshot already deleted). */
+ private boolean skipped;
+
+ /** Whether data files were deleted. */
+ private boolean dataFilesDeleted;
+
+ /** Whether changelog data files were deleted. */
+ private boolean changelogDeleted;
+
+ /** Whether manifest files were deleted. */
+ private boolean manifestsDeleted;
+
+ /** Whether snapshot metadata file was deleted. */
+ private boolean snapshotDeleted;
+
+ /** Buckets that had files deleted (for empty directory cleanup in parallel phase). */
+ private Map<BinaryRow, Set<Integer>> deletionBuckets;
+
+ public DeletionReport(long snapshotId) {
+ this.snapshotId = snapshotId;
+ this.skipped = false;
+ this.dataFilesDeleted = false;
+ this.changelogDeleted = false;
+ this.manifestsDeleted = false;
+ this.snapshotDeleted = false;
+ this.deletionBuckets = new HashMap<>();
+ }
+
+ /**
+ * Create a skipped report for a snapshot that was already deleted.
+ *
+ * @param snapshotId the snapshot ID
+ * @return a skipped deletion report
+ */
+ public static DeletionReport skipped(long snapshotId) {
+ DeletionReport report = new DeletionReport(snapshotId);
+ report.skipped = true;
+ return report;
+ }
+
+ public long snapshotId() {
+ return snapshotId;
+ }
+
+ public boolean isSkipped() {
+ return skipped;
+ }
+
+ public void setDataFilesDeleted(boolean dataFilesDeleted) {
+ this.dataFilesDeleted = dataFilesDeleted;
Review Comment:
Seems that these fields are only updated, but unused except in `toString` method.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r2922827667
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/ExpireSnapshotsAction.java:
##########
@@ -50,12 +95,168 @@ public ExpireSnapshotsAction(
this.olderThan = olderThan;
this.maxDeletes = maxDeletes;
this.options = options;
+ this.parallelism = parallelism;
}
+ /** Returns true if forceStartFlinkJob is enabled and parallelism is greater than 1. */
+ private boolean isParallelMode() {
+ return forceStartFlinkJob && parallelism != null && parallelism > 1;
Review Comment:
Thanks for the suggestions! I've made --parallelism optional — when not specified, it falls back to env.getParallelism(), so users can control it via Flink configuration naturally. (Automatic parallelism inference based on workload is out of scope for this PR.)
Regarding the dynamic task fetching approach (env.fromSequence(startId, endId).flatMap(...)), the current design intentionally separates deletion into two phases:
- Worker phase (parallel): deletes data files and changelog files
- Sink phase (serial): deletes manifests and snapshot metadata files
This separation is necessary because:
1. manifestSkippingSet is global and mutable: Built from all tags + endSnapshot manifests. Parallel manifest deletion would require distributed coordination to safely update this set — significantly more complex.
2. Serial deletion ensures consistency: Parallel snapshot deletion could leave gaps (e.g., snapshots 1, 3, 5 exist but 2, 4 are deleted), which is confusing for users. Serial execution in the sink ensures clean, contiguous
deletion.
3. Range partitioning maximizes cache locality: createDataFileSkipperForTags caches tag data files internally. Adjacent snapshots typically share the same nearest tag, so processing contiguous ranges avoids expensive cache rebuilds. Dynamic task fetching (each subtask fetching the next available split) would scatter snapshots across subtasks and break this cache benefit.
Data file deletion is the most time-consuming part and is safely parallelizable. Manifest/snapshot deletion is lightweight but requires ordering guarantees, so serial execution in the sink is the right trade-off.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on code in PR #7027:
URL: https://github.com/apache/paimon/pull/7027#discussion_r2923088655
##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/ExpireSnapshotsAction.java:
##########
@@ -50,12 +95,168 @@ public ExpireSnapshotsAction(
this.olderThan = olderThan;
this.maxDeletes = maxDeletes;
this.options = options;
+ this.parallelism = parallelism;
}
+ /** Returns true if forceStartFlinkJob is enabled and parallelism is greater than 1. */
+ private boolean isParallelMode() {
+ return forceStartFlinkJob && parallelism != null && parallelism > 1;
+ }
+
+ @Override
+ public void run() throws Exception {
Review Comment:
Prefer to keep LocalAction here. By default (without forceStartFlinkJob), the action runs locally via `super.run() → executeLocally()`, which is sufficient for normal scenarios and safer. Only when
forceStartFlinkJob is set, we start a Flink job with multi-parallelism for large-scale expiration. This also leaves room for future adjustments.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [core][flink] Support parallelism snapshot expire [paimon]
Posted by "wzhero1 (via GitHub)" <gi...@apache.org>.
wzhero1 commented on PR #7027:
URL: https://github.com/apache/paimon/pull/7027#issuecomment-4108413248
Based on actual implementation:
PR Comment work items:
1. Empty plan logging: Adjusted log message to "No snapshots to expire, skipping Flink job submission." (still returns early, not submitting an empty job)
2. Sink operator rename: Renamed sink operator from "SnapshotExpire" to "SnapshotExpireCommit" to distinguish from worker phase
3. Inline executeTask: Removed single-use method, inlined task execution directly into flatMap
4. Progress logging: Added per-task progress log ("Processing expire task {}/{}, {}"), start/end logs with elapsed time
5. Failure recovery test: Added testExpireRecoveryAfterPartialFailure with failure injection via volatile int failAfterTasks
6. Test class rename: ExpireSnapshotsActionITCase → ParallelExpireSnapshotsActionITCase
7. Disabled test comments: Added @Disabled annotations with explanations for tests not suitable for parallel mode
8. Polymorphic refactoring: Replaced TaskType enum + ExpireSnapshotsExecutor switch dispatch with 4 polymorphic SnapshotExpireTask subclasses, deleted ExpireSnapshotsExecutor
9. Logic migration: Moved planner/plan/task/report classes from paimon-core to paimon-flink package
Additional changes (not from comments):
- ExpireContext simplification: Removed delegate methods, callers access underlying objects directly (context.snapshotDeletion().xxx()). Made taggedSnapshots and snapshotCache
final constructor parameters, only skippingSet retains a setter (mutated during manifest deletion)
- snapshotCache in parallel mode: Propagated planner's pre-collected snapshot cache to both workers and sink via serialization, avoiding redundant snapshot file reads
- Trigger condition: Changed to forceStartFlinkJob || parallelism > 1 — either condition enters Flink parallel pipeline
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org