You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@fluss.apache.org by "wuchong (via GitHub)" <gi...@apache.org> on 2026/02/07 17:12:07 UTC

Re: [PR] [kv] Support kv snapshot lease [fluss]

wuchong commented on code in PR #2179:
URL: https://github.com/apache/fluss/pull/2179#discussion_r2767987165


##########
fluss-rpc/src/main/proto/FlussApi.proto:
##########
@@ -1129,4 +1150,15 @@ message PbBucketOffset {
 message PbProducerTableOffsets {
   required int64 table_id = 1;
   repeated PbBucketOffset bucket_offsets = 2;
+}
+
+message PbKvSnapshotLeaseForTable {
+  required int64 table_id = 1;
+  repeated PbKvSnapshotLeaseForBucket buckets_req = 2;

Review Comment:
   `PbKvSnapshotLeaseForTable` is also used as response, `buckets_req` is not good for this,  rename to `bucket_snapshots`?



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorEventProcessor.java:
##########
@@ -2035,6 +2073,53 @@ private ControlledShutdownResponse tryProcessControlledShutdown(
         return response;
     }
 
+    private AcquireKvSnapshotLeaseResponse tryProcessAcquireKvSnapshotLease(
+            AcquireKvSnapshotLeaseEvent event) throws Exception {
+        AcquireKvSnapshotLeaseResponse response = new AcquireKvSnapshotLeaseResponse();
+        Map<TableBucket, Long> unavailableSnapshots =
+                kvSnapshotLeaseManager.acquireLease(
+                        event.getLeaseId(),
+                        event.getLeaseDuration(),
+                        event.getTableIdToLeasedBucket());
+
+        Map<Long, List<PbKvSnapshotLeaseForBucket>> pbFailedTables = new HashMap<>();
+        for (Map.Entry<TableBucket, Long> entry : unavailableSnapshots.entrySet()) {
+            TableBucket tb = entry.getKey();
+            Long snapshotId = entry.getValue();
+            PbKvSnapshotLeaseForBucket pbBucket =
+                    new PbKvSnapshotLeaseForBucket().setBucketId(tb.getBucket());
+            if (tb.getPartitionId() != null) {
+                pbBucket.setPartitionId(tb.getPartitionId());
+            }
+            pbBucket.setSnapshotId(snapshotId);
+            pbFailedTables.computeIfAbsent(tb.getTableId(), k -> new ArrayList<>()).add(pbBucket);
+        }
+
+        for (Map.Entry<Long, List<PbKvSnapshotLeaseForBucket>> entry : pbFailedTables.entrySet()) {
+            response.addTablesLeaseRe()
+                    .setTableId(entry.getKey())
+                    .addAllBucketsReqs(entry.getValue());
+        }
+        return response;

Review Comment:
   Move this to `ServerRpcMessageUtils`



##########
fluss-rpc/src/main/proto/FlussApi.proto:
##########
@@ -375,6 +372,29 @@ message GetKvSnapshotMetadataResponse {
   repeated PbRemotePathAndLocalFile snapshot_files = 2;
 }
 
+message AcquireKvSnapshotLeaseRequest {
+  required string lease_id = 1;
+  required int64 lease_duration = 2;
+  repeated PbKvSnapshotLeaseForTable table_lease_req = 3;

Review Comment:
   rename to `all_snapshots_to_lease`?



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/KvSnapshotLeaseManager.java:
##########
@@ -0,0 +1,459 @@
+/*
+ * 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.fluss.server.coordinator;
+
+import org.apache.fluss.annotation.VisibleForTesting;
+import org.apache.fluss.config.ConfigOptions;
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.metadata.KvSnapshotLeaseForBucket;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.metrics.MetricNames;
+import org.apache.fluss.server.metrics.group.CoordinatorMetricGroup;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLease;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLeaseMetadataManager;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotTableLease;
+import org.apache.fluss.utils.MapUtils;
+import org.apache.fluss.utils.clock.Clock;
+import org.apache.fluss.utils.concurrent.ExecutorThreadFactory;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.stream.Collectors;
+
+import static org.apache.fluss.utils.concurrent.LockUtils.inReadLock;
+import static org.apache.fluss.utils.concurrent.LockUtils.inWriteLock;
+
+/** A manager to manage kv snapshot lease acquire, renew, release and drop. */
+@ThreadSafe
+public class KvSnapshotLeaseManager {
+    private static final Logger LOG = LoggerFactory.getLogger(KvSnapshotLeaseManager.class);
+
+    private final KvSnapshotLeaseMetadataManager metadataManager;
+    private final CoordinatorContext coordinatorContext;
+    private final Clock clock;
+    private final ScheduledExecutorService scheduledExecutor;
+    private final Configuration conf;
+
+    private final Map<String, ReadWriteLock> leaseLocks = MapUtils.newConcurrentHashMap();
+    /** lease id to kv snapshot lease. */
+    @GuardedBy("leaseLocks")
+    private final Map<String, KvSnapshotLease> kvSnapshotLeaseMap;
+
+    private final ReadWriteLock refCountLock = new ReentrantReadWriteLock();
+
+    /**
+     * KvSnapshotLeaseForBucket to the ref count, which means this table bucket + snapshotId has
+     * been leased by how many lease id.
+     */
+    private final Map<KvSnapshotLeaseForBucket, AtomicInteger> refCount =
+            MapUtils.newConcurrentHashMap();
+
+    /** For metrics. */
+    private final AtomicInteger leasedBucketCount = new AtomicInteger(0);
+
+    public KvSnapshotLeaseManager(
+            Configuration conf,
+            KvSnapshotLeaseMetadataManager metadataManager,
+            CoordinatorContext coordinatorContext,
+            Clock clock,
+            CoordinatorMetricGroup coordinatorMetricGroup) {
+        this(
+                conf,
+                metadataManager,
+                coordinatorContext,
+                Executors.newScheduledThreadPool(
+                        1, new ExecutorThreadFactory("kv-snapshot-lease-cleaner")),
+                clock,
+                coordinatorMetricGroup);
+    }
+
+    @VisibleForTesting
+    public KvSnapshotLeaseManager(
+            Configuration conf,
+            KvSnapshotLeaseMetadataManager metadataManager,
+            CoordinatorContext coordinatorContext,
+            ScheduledExecutorService scheduledExecutor,
+            Clock clock,
+            CoordinatorMetricGroup coordinatorMetricGroup) {
+        this.metadataManager = metadataManager;
+        this.conf = conf;
+        this.scheduledExecutor = scheduledExecutor;
+        this.coordinatorContext = coordinatorContext;
+        this.clock = clock;
+        this.kvSnapshotLeaseMap = MapUtils.newConcurrentHashMap();
+
+        registerMetrics(coordinatorMetricGroup);
+    }
+
+    public void start() {
+        LOG.info("kv snapshot lease manager has been started.");
+        scheduledExecutor.scheduleWithFixedDelay(
+                this::expireLeases,
+                0L,
+                conf.get(ConfigOptions.KV_SNAPSHOT_LEASE_EXPIRATION_CHECK_INTERVAL).toMillis(),
+                TimeUnit.MILLISECONDS);
+    }
+
+    public void initialize() throws Exception {
+        for (String leaseId : metadataManager.getLeasesList()) {
+            Optional<KvSnapshotLease> kvSnapshotLeaseOpt = metadataManager.getLease(leaseId);
+            if (kvSnapshotLeaseOpt.isPresent()) {
+                KvSnapshotLease kvSnapshotLease = kvSnapshotLeaseOpt.get();
+                this.leaseLocks.put(leaseId, new ReentrantReadWriteLock());
+                this.kvSnapshotLeaseMap.put(leaseId, kvSnapshotLease);
+
+                initializeRefCount(kvSnapshotLease);
+
+                leasedBucketCount.addAndGet(kvSnapshotLease.getLeasedSnapshotCount());
+            }
+        }
+    }
+
+    public boolean snapshotLeaseNotExist(KvSnapshotLeaseForBucket kvSnapshotLeaseForBucket) {
+        return inReadLock(
+                refCountLock,
+                () -> {
+                    AtomicInteger count = refCount.get(kvSnapshotLeaseForBucket);
+                    return count == null || count.get() <= 0;
+                });
+    }
+
+    /**
+     * Acquire kv snapshot lease.
+     *
+     * @param leaseId the lease id
+     * @param leaseDuration the lease duration
+     * @param tableIdToLeaseBucket the table id to lease bucket
+     * @return the map of unavailable snapshots that failed to be leased
+     */
+    public Map<TableBucket, Long> acquireLease(
+            String leaseId,
+            long leaseDuration,
+            Map<Long, List<KvSnapshotLeaseForBucket>> tableIdToLeaseBucket)
+            throws Exception {
+        ReadWriteLock lock = leaseLocks.computeIfAbsent(leaseId, k -> new ReentrantReadWriteLock());
+        return inWriteLock(
+                lock,
+                () -> {
+                    // To record the unavailable snapshots such as the kv snapshotId to lease not
+                    // exists.
+                    Map<TableBucket, Long> unavailableSnapshots = new HashMap<>();
+
+                    boolean update = kvSnapshotLeaseMap.containsKey(leaseId);
+                    // set the expiration time as: current time + leaseDuration
+                    long newExpirationTime = clock.milliseconds() + leaseDuration;
+                    KvSnapshotLease kvSnapshotLease =
+                            kvSnapshotLeaseMap.compute(
+                                    leaseId,
+                                    (key, existingLease) -> {
+                                        if (existingLease == null) {
+                                            LOG.info(
+                                                    "kv snapshot lease '{}' has been acquired. The lease expiration "
+                                                            + "time is {}",
+                                                    leaseId,
+                                                    newExpirationTime);
+                                            return new KvSnapshotLease(newExpirationTime);
+                                        } else {
+                                            existingLease.setExpirationTime(newExpirationTime);
+                                            return existingLease;
+                                        }
+                                    });
+
+                    for (Map.Entry<Long, List<KvSnapshotLeaseForBucket>> entry :
+                            tableIdToLeaseBucket.entrySet()) {
+                        Long tableId = entry.getKey();
+                        TableInfo tableInfo = coordinatorContext.getTableInfoById(tableId);
+                        int numBuckets = tableInfo.getNumBuckets();
+                        List<KvSnapshotLeaseForBucket> buckets = entry.getValue();
+                        for (KvSnapshotLeaseForBucket bucket : buckets) {
+
+                            TableBucket tableBucket = bucket.getTableBucket();
+                            long kvSnapshotId = bucket.getKvSnapshotId();
+                            try {
+                                boolean snapshotExists =
+                                        metadataManager.isSnapshotExists(tableBucket, kvSnapshotId);
+                                if (!snapshotExists) {
+                                    unavailableSnapshots.put(tableBucket, kvSnapshotId);
+                                    continue;
+                                }
+                            } catch (Exception e) {
+                                LOG.error(
+                                        "Failed to check snapshotExists for tableBucket when acquire kv "
+                                                + "snapshot kvSnapshotLease {}.",
+                                        tableBucket,
+                                        e);
+                                unavailableSnapshots.put(tableBucket, kvSnapshotId);
+                                continue;
+                            }
+
+                            long originalSnapshotId =
+                                    kvSnapshotLease.acquireBucket(
+                                            tableBucket, kvSnapshotId, numBuckets);
+                            if (originalSnapshotId == -1L) {
+                                leasedBucketCount.incrementAndGet();
+                            } else {
+                                // clear the original ref.
+                                decrementRefCount(
+                                        new KvSnapshotLeaseForBucket(
+                                                tableBucket, originalSnapshotId));
+                            }
+                            incrementRefCount(bucket);
+                        }
+                    }
+
+                    if (update) {
+                        metadataManager.updateLease(leaseId, kvSnapshotLease);
+                    } else {
+                        metadataManager.registerLease(leaseId, kvSnapshotLease);
+                    }
+
+                    return unavailableSnapshots;
+                });
+    }
+
+    public void release(String leaseId, Map<Long, List<TableBucket>> tableIdToUnregisterBucket)
+            throws Exception {
+        ReadWriteLock lock = leaseLocks.get(leaseId);
+        if (lock == null) {
+            return;
+        }
+
+        inWriteLock(
+                lock,
+                () -> {
+                    KvSnapshotLease lease = kvSnapshotLeaseMap.get(leaseId);
+                    if (lease == null) {
+                        return;
+                    }
+
+                    for (Map.Entry<Long, List<TableBucket>> entry :
+                            tableIdToUnregisterBucket.entrySet()) {
+                        List<TableBucket> buckets = entry.getValue();
+                        for (TableBucket bucket : buckets) {
+                            long snapshotId = lease.releaseBucket(bucket);
+                            if (snapshotId != -1L) {
+                                leasedBucketCount.decrementAndGet();
+                                decrementRefCount(new KvSnapshotLeaseForBucket(bucket, snapshotId));
+                            }
+                        }
+                    }
+
+                    if (lease.isEmpty()) {
+                        releaseAll(leaseId);
+                    } else {
+                        metadataManager.updateLease(leaseId, lease);
+                    }
+                });
+    }
+
+    /**
+     * Release kv snapshot lease.
+     *
+     * @param leaseId the lease id
+     * @return true if clear success, false if lease not exist
+     */
+    public boolean releaseAll(String leaseId) throws Exception {
+        ReadWriteLock lock = leaseLocks.get(leaseId);
+        if (lock == null) {
+            return false;
+        }
+
+        boolean exist =
+                inWriteLock(
+                        lock,
+                        () -> {
+                            KvSnapshotLease kvSnapshotLease = kvSnapshotLeaseMap.remove(leaseId);
+                            if (kvSnapshotLease == null) {
+                                return false;
+                            }
+
+                            clearRefCount(kvSnapshotLease);
+                            metadataManager.deleteLease(leaseId);
+
+                            LOG.info(
+                                    "kv snapshots of lease '"
+                                            + leaseId
+                                            + "' has been all released.");
+                            return true;
+                        });
+
+        leaseLocks.remove(leaseId);
+        return exist;
+    }
+
+    private void initializeRefCount(KvSnapshotLease lease) {
+        for (Map.Entry<Long, KvSnapshotTableLease> tableEntry :
+                lease.getTableIdToTableLease().entrySet()) {
+            long tableId = tableEntry.getKey();
+            KvSnapshotTableLease tableLease = tableEntry.getValue();
+            if (tableLease.getBucketSnapshots() != null) {
+                Long[] snapshots = tableLease.getBucketSnapshots();
+                for (int i = 0; i < snapshots.length; i++) {
+                    if (snapshots[i] == -1L) {
+                        continue;
+                    }
+
+                    incrementRefCount(
+                            new KvSnapshotLeaseForBucket(
+                                    new TableBucket(tableId, i), snapshots[i]));
+                }
+            } else {
+                Map<Long, Long[]> partitionSnapshots = tableLease.getPartitionSnapshots();
+                for (Map.Entry<Long, Long[]> entry : partitionSnapshots.entrySet()) {
+                    Long partitionId = entry.getKey();
+                    Long[] snapshots = entry.getValue();
+                    for (int i = 0; i < snapshots.length; i++) {
+                        if (snapshots[i] == -1L) {
+                            continue;
+                        }
+
+                        incrementRefCount(
+                                new KvSnapshotLeaseForBucket(
+                                        new TableBucket(tableId, partitionId, i), snapshots[i]));
+                    }
+                }
+            }
+        }
+    }
+
+    private void clearRefCount(KvSnapshotLease lease) {
+        for (Map.Entry<Long, KvSnapshotTableLease> tableEntry :
+                lease.getTableIdToTableLease().entrySet()) {
+            long tableId = tableEntry.getKey();
+            KvSnapshotTableLease tableLease = tableEntry.getValue();
+            if (tableLease.getBucketSnapshots() != null) {
+                Long[] snapshots = tableLease.getBucketSnapshots();
+                for (int i = 0; i < snapshots.length; i++) {
+                    if (snapshots[i] == -1L) {
+                        continue;
+                    }
+                    decrementRefCount(
+                            new KvSnapshotLeaseForBucket(
+                                    new TableBucket(tableId, i), snapshots[i]));
+                    leasedBucketCount.decrementAndGet();
+                }
+            } else {
+                Map<Long, Long[]> partitionSnapshots = tableLease.getPartitionSnapshots();
+                for (Map.Entry<Long, Long[]> entry : partitionSnapshots.entrySet()) {
+                    Long partitionId = entry.getKey();
+                    Long[] snapshots = entry.getValue();
+                    for (int i = 0; i < snapshots.length; i++) {
+                        if (snapshots[i] == -1L) {
+                            continue;
+                        }
+
+                        decrementRefCount(
+                                new KvSnapshotLeaseForBucket(
+                                        new TableBucket(tableId, partitionId, i), snapshots[i]));
+                        leasedBucketCount.decrementAndGet();
+                    }
+                }
+            }
+        }
+    }
+
+    private void incrementRefCount(KvSnapshotLeaseForBucket kvSnapshotLeaseForBucket) {
+        inWriteLock(
+                refCountLock,
+                () ->
+                        refCount.computeIfAbsent(
+                                        kvSnapshotLeaseForBucket, k -> new AtomicInteger(0))
+                                .incrementAndGet());
+    }
+
+    private void decrementRefCount(KvSnapshotLeaseForBucket kvSnapshotLeaseForBucket) {
+        inWriteLock(
+                refCountLock,
+                () -> {
+                    AtomicInteger atomicInteger = refCount.get(kvSnapshotLeaseForBucket);
+                    if (atomicInteger != null) {
+                        int decrementAndGet = atomicInteger.decrementAndGet();
+                        if (decrementAndGet <= 0) {
+                            refCount.remove(kvSnapshotLeaseForBucket);
+                        }
+                    }
+                });

Review Comment:
   We can remove the writeLock if we refactor this into using the atomic API `computeIfPresent`.
   
   ```java
   refCount.computeIfPresent(
                               kvSnapshotLeaseForBucket,
                               (k, v) -> {
                                   int newCount = v.decrementAndGet();
                                   return newCount <= 0 ? null : v;
                               });
   ```



##########
fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/source/enumerator/FlinkSourceEnumerator.java:
##########
@@ -531,22 +537,88 @@ private List<SourceSplitBase> initPrimaryKeyTablePartitionSplits(
         List<SourceSplitBase> splits = new ArrayList<>();
         for (Partition partition : newPartitions) {
             String partitionName = partition.getPartitionName();
-            // get the table snapshot info
-            final KvSnapshots kvSnapshots;
-            try {
-                kvSnapshots = flussAdmin.getLatestKvSnapshots(tablePath, partitionName).get();
-            } catch (Exception e) {
-                throw new FlinkRuntimeException(
-                        String.format(
-                                "Failed to get table snapshot for table %s and partition %s",
-                                tablePath, partitionName),
-                        ExceptionUtils.stripCompletionException(e));
-            }
-            splits.addAll(getSnapshotAndLogSplits(kvSnapshots, partitionName));
+            splits.addAll(
+                    getSnapshotAndLogSplits(
+                            getLatestKvSnapshotsAndRegister(partitionName), partitionName));
         }
         return splits;
     }
 
+    private KvSnapshots getLatestKvSnapshotsAndRegister(@Nullable String partitionName) {
+        long tableId;
+        Long partitionId;
+        Map<Integer, Long> snapshotIds = new HashMap<>();
+        Map<Integer, Long> logOffsets = new HashMap<>();
+
+        // retry to get the latest kv snapshots and acquire kvSnapshot lease.
+        try {
+            KvSnapshots kvSnapshots = getLatestKvSnapshots(partitionName);
+            Set<TableBucket> remainingTableBuckets = new HashSet<>(kvSnapshots.getTableBuckets());
+
+            tableId = kvSnapshots.getTableId();
+            partitionId = kvSnapshots.getPartitionId();
+
+            Set<TableBucket> ignoreBuckets = new HashSet<>();
+            Map<TableBucket, Long> bucketsToLease = new HashMap<>();
+            for (TableBucket tb : remainingTableBuckets) {
+                int bucket = tb.getBucket();
+                OptionalLong snapshotIdOpt = kvSnapshots.getSnapshotId(bucket);
+                OptionalLong logOffsetOpt = kvSnapshots.getLogOffset(bucket);
+                if (snapshotIdOpt.isPresent() && !ignoreTableBucket(tb)) {
+                    bucketsToLease.put(tb, snapshotIdOpt.getAsLong());
+                } else {
+                    ignoreBuckets.add(tb);
+                }
+
+                snapshotIds.put(
+                        bucket, snapshotIdOpt.isPresent() ? snapshotIdOpt.getAsLong() : null);
+                logOffsets.put(bucket, logOffsetOpt.isPresent() ? logOffsetOpt.getAsLong() : null);
+            }
+
+            if (!ignoreBuckets.isEmpty()) {
+                remainingTableBuckets.removeAll(ignoreBuckets);

Review Comment:
   I don't see the usage of `remainingTableBuckets`, it is overriden by the following return value of `flussAdmin.acquireKvSnapshotLease`. 



##########
fluss-flink/fluss-flink-common/src/test/java/org/apache/fluss/flink/source/FlinkTableSourceITCase.java:
##########
@@ -352,6 +354,51 @@ void testPkTableReadMixSnapshotAndLog() throws Exception {
         assertResultsIgnoreOrder(rowIter, expectedRows, true);
     }
 
+    @Test
+    void testPkTableReadWithKvSnapshotLease() throws Exception {
+        tEnv.executeSql(
+                "create table pk_table_with_kv_snapshot_lease (a int not null primary key not enforced, b varchar)");
+        TablePath tablePath = TablePath.of(DEFAULT_DB, "pk_table_with_kv_snapshot_lease");
+
+        List<InternalRow> rows = Arrays.asList(row(1, "v1"), row(2, "v2"), row(3, "v3"));
+
+        // write records
+        writeRows(conn, tablePath, rows, false);
+
+        FLUSS_CLUSTER_EXTENSION.triggerAndWaitSnapshot(tablePath);
+
+        // enable checkpoint to make sure the kv snapshot lease will be cleared.
+        execEnv.enableCheckpointing(100);
+
+        List<String> expectedRows = Arrays.asList("+I[1, v1]", "+I[2, v2]", "+I[3, v3]");
+        org.apache.flink.util.CloseableIterator<Row> rowIter =
+                tEnv.executeSql(
+                                "select * from pk_table_with_kv_snapshot_lease "
+                                        + "/*+ OPTIONS('scan.kv.snapshot.lease.id' = 'test-lease-10001') */")

Review Comment:
   Can we add a test without the dynamic option or modify this? I think that is the common way that users will use and we should cover that in tests. We can assert lease is dropped by using `zkClient.getKvSnapshotLeasesList()` method.



##########
fluss-rpc/src/main/proto/FlussApi.proto:
##########
@@ -378,6 +378,29 @@ message GetKvSnapshotMetadataResponse {
   repeated PbRemotePathAndLocalFile snapshot_files = 2;
 }
 
+message AcquireKvSnapshotLeaseRequest {
+  required string lease_id = 1;
+  required int64 lease_duration = 2;

Review Comment:
   `lease_duration` -> `lease_duration_ms`



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/KvSnapshotLeaseManager.java:
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.fluss.server.coordinator;
+
+import org.apache.fluss.annotation.VisibleForTesting;
+import org.apache.fluss.config.ConfigOptions;
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.metadata.KvSnapshotLeaseForBucket;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.metrics.MetricNames;
+import org.apache.fluss.server.metrics.group.CoordinatorMetricGroup;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLease;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLeaseMetadataHelper;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotTableLease;
+import org.apache.fluss.utils.MapUtils;
+import org.apache.fluss.utils.clock.Clock;
+import org.apache.fluss.utils.concurrent.ExecutorThreadFactory;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.stream.Collectors;
+
+import static org.apache.fluss.utils.concurrent.LockUtils.inReadLock;
+import static org.apache.fluss.utils.concurrent.LockUtils.inWriteLock;
+
+/** A manager to manage kv snapshot lease acquire, renew, release and drop. */
+@ThreadSafe
+public class KvSnapshotLeaseManager {
+    private static final Logger LOG = LoggerFactory.getLogger(KvSnapshotLeaseManager.class);
+
+    private final KvSnapshotLeaseMetadataHelper metadataHelper;
+    private final CoordinatorContext coordinatorContext;
+    private final Clock clock;
+    private final ScheduledExecutorService scheduledExecutor;
+    private final Configuration conf;
+
+    private final Map<String, ReadWriteLock> leaseLocks = MapUtils.newConcurrentHashMap();
+    /** lease id to kv snapshot lease. */
+    @GuardedBy("leaseLocks")
+    private final Map<String, KvSnapshotLease> kvSnapshotLeaseMap;
+
+    private final ReadWriteLock refCountLock = new ReentrantReadWriteLock();
+
+    /**
+     * KvSnapshotLeaseForBucket to the ref count, which means this table bucket + snapshotId has
+     * been leased by how many lease id.
+     */
+    @GuardedBy("refCountLock")
+    private final Map<KvSnapshotLeaseForBucket, AtomicInteger> refCount =
+            MapUtils.newConcurrentHashMap();
+
+    /** For metrics. */
+    private final AtomicInteger leasedBucketCount = new AtomicInteger(0);
+
+    public KvSnapshotLeaseManager(
+            Configuration conf,
+            KvSnapshotLeaseMetadataHelper metadataHelper,
+            CoordinatorContext coordinatorContext,
+            Clock clock,
+            CoordinatorMetricGroup coordinatorMetricGroup) {
+        this(
+                conf,
+                metadataHelper,
+                coordinatorContext,
+                Executors.newScheduledThreadPool(
+                        1, new ExecutorThreadFactory("kv-snapshot-lease-cleaner")),
+                clock,
+                coordinatorMetricGroup);
+    }
+
+    @VisibleForTesting
+    public KvSnapshotLeaseManager(
+            Configuration conf,
+            KvSnapshotLeaseMetadataHelper metadataHelper,
+            CoordinatorContext coordinatorContext,
+            ScheduledExecutorService scheduledExecutor,
+            Clock clock,
+            CoordinatorMetricGroup coordinatorMetricGroup) {
+        this.metadataHelper = metadataHelper;
+        this.conf = conf;
+        this.scheduledExecutor = scheduledExecutor;
+        this.coordinatorContext = coordinatorContext;
+        this.clock = clock;
+        this.kvSnapshotLeaseMap = MapUtils.newConcurrentHashMap();
+
+        registerMetrics(coordinatorMetricGroup);
+    }
+
+    public void start() {
+        LOG.info("kv snapshot lease manager has been started.");
+        scheduledExecutor.scheduleWithFixedDelay(
+                this::expireLeases,
+                0L,
+                conf.get(ConfigOptions.KV_SNAPSHOT_LEASE_EXPIRATION_CHECK_INTERVAL).toMillis(),
+                TimeUnit.MILLISECONDS);
+    }
+
+    public void initialize() throws Exception {
+        List<String> leaseIds = metadataHelper.getLeasesList();
+        for (String leaseId : leaseIds) {
+            Optional<KvSnapshotLease> kvSnapshotLeaseOpt = metadataHelper.getLease(leaseId);
+            if (kvSnapshotLeaseOpt.isPresent()) {
+                KvSnapshotLease kvSnapshotLease = kvSnapshotLeaseOpt.get();
+                this.leaseLocks.put(leaseId, new ReentrantReadWriteLock());
+                this.kvSnapshotLeaseMap.put(leaseId, kvSnapshotLease);
+
+                initializeRefCount(kvSnapshotLease);
+
+                leasedBucketCount.addAndGet(kvSnapshotLease.getLeasedSnapshotCount());
+            }
+        }
+    }
+
+    public boolean snapshotLeaseNotExist(KvSnapshotLeaseForBucket kvSnapshotLeaseForBucket) {
+        return inReadLock(
+                refCountLock,
+                () ->
+                        !refCount.containsKey(kvSnapshotLeaseForBucket)
+                                || refCount.get(kvSnapshotLeaseForBucket).get() <= 0);
+    }
+
+    /**
+     * Acquire kv snapshot lease.
+     *
+     * @param leaseId the lease id
+     * @param leaseDuration the lease duration
+     * @param tableIdToLeaseBucket the table id to lease bucket
+     * @return the map of unavailable snapshots that failed to be leased
+     */
+    public Map<TableBucket, Long> acquireLease(
+            String leaseId,
+            long leaseDuration,
+            Map<Long, List<KvSnapshotLeaseForBucket>> tableIdToLeaseBucket)
+            throws Exception {
+        ReadWriteLock lock = leaseLocks.computeIfAbsent(leaseId, k -> new ReentrantReadWriteLock());

Review Comment:
   I agree with @platinumhamburg—the current use of `leaseLocks` feels like a hack. If thread safety is required for `KvSnapshotLease`, then the class itself should be made inherently thread-safe, which would also significantly simplify the surrounding code.
   
   To achieve atomicity and thread safety, we should refactor the existing `KvSnapshotLease#acquireBucket` method into a single, cohesive operation:
   
   ```java
   KvSnapshotLease#acquireSnapshots(
       long leaseDurationMs,
       Map<Long, List<KvSnapshotLeaseForBucket>> tableIdToLeaseBucket,
       ConcurrentHashMap<KvSnapshotLeaseForBucket, AtomicInteger> refCount
   )
   ```
   
   This method should:
   - Perform all necessary validations and state updates **atomically**.
   - Update reference counts internally as part of the acquisition logic.
   
   Once this method completes successfully, the ZooKeeper metadata update should be performed **outside the lock**, but with **version-based consistency** to ensure correctness in concurrent scenarios. Specifically:
   - Use conditional ZK writes based on the current version of the lease node.
   - Follow the pattern established in `ProducerOffsetsStore#xxxVersion()` methods, which use versioned ZK operations to avoid race conditions during metadata updates.
   
   This approach eliminates the need for external locking, improves code clarity, and ensures both memory and ZK state remain consistent under concurrency.



##########
fluss-rpc/src/main/proto/FlussApi.proto:
##########
@@ -375,6 +372,29 @@ message GetKvSnapshotMetadataResponse {
   repeated PbRemotePathAndLocalFile snapshot_files = 2;
 }
 
+message AcquireKvSnapshotLeaseRequest {
+  required string lease_id = 1;
+  required int64 lease_duration = 2;
+  repeated PbKvSnapshotLeaseForTable table_lease_req = 3;
+}
+
+message AcquireKvSnapshotLeaseResponse {
+  repeated PbKvSnapshotLeaseForTable tables_lease_res = 3;

Review Comment:
   rename to `unavailable_snapshots_to_lease`?



##########
fluss-client/src/main/java/org/apache/fluss/client/admin/Admin.java:
##########
@@ -428,6 +430,57 @@ CompletableFuture<Void> dropPartition(
     CompletableFuture<KvSnapshotMetadata> getKvSnapshotMetadata(
             TableBucket bucket, long snapshotId);
 
+    /**
+     * Acquires a lease for specific KV snapshots of the given tableBuckets asynchronously.
+     *
+     * <p>Once acquired, the specified KV snapshots will be protected from garbage collection for
+     * the duration of the {@code leaseDuration}. The client must call {@link
+     * #releaseKvSnapshotLease} to release the lock early when reading is finished.
+     *
+     * <p>If the lease expires (no renew received within duration), the server is free to delete the
+     * snapshot files.
+     *
+     * <p>The following exceptions can be anticipated when calling {@code get()} on returned future:
+     *
+     * <ul>
+     *   <li>{@link TableNotExistException} if the table does not exist.
+     *   <li>{@link PartitionNotExistException} if the partition does not exist.
+     * </ul>
+     *
+     * @param leaseId The unique ID for this lease session (usually a UUID generated by client).
+     * @param snapshotIds The snapshots to lease, a map from TableBucket to kvSnapshotId.
+     * @param leaseDuration The duration (in milliseconds) for which the snapshots should be kept.
+     * @return The result of the acquire operation, containing any buckets that failed to be locked.
+     */
+    CompletableFuture<AcquireKvSnapshotLeaseResult> acquireKvSnapshotLease(
+            String leaseId, Map<TableBucket, Long> snapshotIds, long leaseDuration);
+
+    /**
+     * Releases the lease for specific tableBuckets asynchronously.
+     *
+     * <p>This is typically called when a client finishes reading a specific bucket (or a batch of
+     * buckets) but is still reading others under the same leaseId.
+     *
+     * <p>If {@code bucketsToRelease} contains all buckets under this leaseId, the lease itself will
+     * be removed.
+     *
+     * @param leaseId The lease id.
+     * @param bucketsToRelease The specific tableBuckets to release.
+     */
+    CompletableFuture<Void> releaseKvSnapshotLease(
+            String leaseId, Set<TableBucket> bucketsToRelease);
+
+    /**
+     * Releases the entire lease asynchronously for all leased snapshots for all table buckets of
+     * specified leaseId.
+     *
+     * <p>All snapshots locked under this {@code leaseId} will be released immediately. This is
+     * equivalent to calling {@link #releaseKvSnapshotLease} with all held buckets.
+     *
+     * @param leaseId The lease id to release.
+     */
+    CompletableFuture<Void> releaseAllKvSnapshotLease(String leaseId);

Review Comment:
   I have concerns about the current naming of `releaseKvSnapshotLease` and `releaseAllKvSnapshotLease`. The names are misleading:
   
   - `releaseKvSnapshotLease` sounds like it releases a lease, but it actually releases **snapshots** associated with that lease.
   - `releaseAllKvSnapshotLease` implies releasing *all* leases, yet it only releases snapshots for **a single lease**.
   
   This confusion stems from a deeper design issue: all snapshot lease–related methods are crammed into the already large `Admin` interface. To disambiguate method names, we’re forced to prefix everything with `KvSnapshotLease`, which leads to awkward and inconsistent semantics.
   
   To improve clarity and maintainability, I propose extracting all snapshot lease functionality into a dedicated, well-defined interface:
   
   ```java
   interface Admin {
       /**
        * Creates a new KV snapshot lease with the given ID and duration.
        *
        * @param leaseId the unique identifier for the lease
        * @param leaseDurationMs the lease duration in milliseconds
        * @return a {@link KvSnapshotLease} instance representing the created lease
        */
       KvSnapshotLease createKvSnapshotLease(String leaseId, long leaseDurationMs);
   }
   
   /**
    * Represents a lease for managing KV snapshots. A lease allows acquiring,
    * renewing, releasing, and dropping snapshot references under a time-bound agreement.
    */
   @PublicEvolving
   public interface KvSnapshotLease {
   
       /** Returns the unique identifier of this lease. */
       String leaseId();
   
       /** Returns the lease duration in milliseconds. */
       long leaseDurationMs();
   
       /**
        * Acquires snapshots for the specified table buckets under this lease.
        *
        * @param snapshotIds mapping from table buckets to desired snapshot IDs
        * @return a future containing the result of the acquisition
        */
       CompletableFuture<AcquireKvSnapshotLeaseResult> acquireSnapshots(
               Map<TableBucket, Long> snapshotIds);
   
       /**
        * Renews the lease, extending its validity period.
        *
        * @return a future that completes when the renewal is acknowledged
        */
       CompletableFuture<Void> renew();
   
       /**
        * Releases snapshots for the specified table buckets, freeing associated resources.
        *
        * @param bucketsToRelease the set of table buckets whose snapshots should be released
        * @return a future that completes when the release is processed
        */
       CompletableFuture<Void> releaseSnapshots(Set<TableBucket> bucketsToRelease);
   
       /**
        * Drops the entire lease, releasing all held snapshots and invalidating the lease.
        *
        * @return a future that completes when the lease is fully dropped
        */
       CompletableFuture<Void> dropLease();
   }
   ```
   



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorEventProcessor.java:
##########
@@ -2035,6 +2073,53 @@ private ControlledShutdownResponse tryProcessControlledShutdown(
         return response;
     }
 
+    private AcquireKvSnapshotLeaseResponse tryProcessAcquireKvSnapshotLease(
+            AcquireKvSnapshotLeaseEvent event) throws Exception {
+        AcquireKvSnapshotLeaseResponse response = new AcquireKvSnapshotLeaseResponse();
+        Map<TableBucket, Long> unavailableSnapshots =
+                kvSnapshotLeaseManager.acquireLease(
+                        event.getLeaseId(),
+                        event.getLeaseDuration(),
+                        event.getTableIdToLeasedBucket());
+
+        Map<Long, List<PbKvSnapshotLeaseForBucket>> pbFailedTables = new HashMap<>();
+        for (Map.Entry<TableBucket, Long> entry : unavailableSnapshots.entrySet()) {
+            TableBucket tb = entry.getKey();
+            Long snapshotId = entry.getValue();
+            PbKvSnapshotLeaseForBucket pbBucket =
+                    new PbKvSnapshotLeaseForBucket().setBucketId(tb.getBucket());
+            if (tb.getPartitionId() != null) {
+                pbBucket.setPartitionId(tb.getPartitionId());
+            }
+            pbBucket.setSnapshotId(snapshotId);
+            pbFailedTables.computeIfAbsent(tb.getTableId(), k -> new ArrayList<>()).add(pbBucket);
+        }
+
+        for (Map.Entry<Long, List<PbKvSnapshotLeaseForBucket>> entry : pbFailedTables.entrySet()) {
+            response.addTablesLeaseRe()
+                    .setTableId(entry.getKey())
+                    .addAllBucketsReqs(entry.getValue());
+        }
+        return response;
+    }
+
+    private ReleaseKvSnapshotLeaseResponse tryProcessReleaseKvSnapshotLease(
+            ReleaseKvSnapshotLeaseEvent event) throws Exception {
+        ReleaseKvSnapshotLeaseResponse response = new ReleaseKvSnapshotLeaseResponse();
+        Map<Long, List<TableBucket>> tableIdToReleasedBucket = event.getTableIdToReleasedBucket();
+        if (tableIdToReleasedBucket.isEmpty()) {
+            // release all
+            boolean exist = kvSnapshotLeaseManager.releaseAll(event.getLeaseId());
+            if (!exist) {
+                throw new KvSnapshotLeaseNotExistException(

Review Comment:
   Should this throw an error?  Dropping a lease should be idempotent and reentrant; otherwise, client-side handling becomes very cumbersome.  
   
   Additionally, if we're going to throw a `LeaseNotExistException` here, why doesn't the `release(leaseId, bucket)` method below throw the same exception?   Fundamentally, these two operations are equivalent in this regard.



##########
fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/source/FlussSourceBuilder.java:
##########
@@ -300,6 +313,9 @@ public FlussSource<OUT> build() {
                 offsetsInitializer,
                 scanPartitionDiscoveryIntervalMs,
                 deserializationSchema,
-                true);
+                true,
+                hasPrimaryKey
+                        ? new LeaseContext(kvSnapshotLeaseId, kvSnapshotLeaseDurationMs)
+                        : new LeaseContext(null, null));

Review Comment:
   ditto. we don't need to check primary key table.



##########
fluss-server/src/main/java/org/apache/fluss/server/zk/data/lease/KvSnapshotLease.java:
##########
@@ -0,0 +1,198 @@
+/*
+ * 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.fluss.server.zk.data.lease;

Review Comment:
   The purpose of the package `org.apache.fluss.server.zk.data` is to contain **only** POJO classes that represent ZNode data entities, along with their corresponding JSON serialization/deserialization logic. These classes should be pure data carriers and **must not include any business logic**.
   
   However, `KvSnapshotLease` does not belong here because:
   - It is **not a ZNode data entity** (i.e., it is not serialized into or stored in ZooKeeper).
   - It encapsulates substantial business logic, such as `acquireBucket()` and `releaseBucket()`.
   
   Therefore, it should **not** reside under `org.apache.fluss.server.zk.data.lease`.
   
   Instead, we propose moving it to `org.apache.fluss.server.coordinator.lease`, alongside related components like `KvSnapshotLeaseManager` and `KvSnapshotLeaseMetadataManager`.
   
   Additionally, to avoid confusion with a potential public-facing `KvSnapshotLease` interface (e.g., one exposed via the `Admin` API), we suggest renaming this internal class to **`KvSnapshotLeaseHandle`**, clearly signaling its role as an internal coordination handle rather than a user-facing abstraction.



##########
fluss-server/src/main/java/org/apache/fluss/server/kv/snapshot/CompletedSnapshotStore.java:
##########
@@ -178,7 +186,7 @@ private static Optional<CompletedSnapshot> subsume(
         Iterator<CompletedSnapshot> iterator = snapshots.iterator();
         while (snapshots.size() > numRetain && iterator.hasNext()) {
             CompletedSnapshot next = iterator.next();
-            if (canSubsume(next, latest)) {
+            if (canSubsume(next, latest, subsumptionChecker)) {

Review Comment:
   
   I believe the current snapshot/SST expiration mechanism is insufficient.  
   
   Currently, we rely on the `subsumptionChecker` to retain leased snapshots while cleaning up newer ones. For example, given snapshots `[1, 2, 3, 4, 5]`, if we lease snapshot `1` and configure retention to keep only **2** snapshots, the `subsume()` operation will retain `[1, 5]`.
   
   However, in `CompletedSnapshotStore#addSnapshotAndSubsumeOldestOne`, the cleanup logic calls `findLowest(completedSnapshots)`, which returns `1` as the `lowestSnapshotID`. This ID is then used to determine which SST files to delete—**but since `1` is still leased, no SST files are cleaned up at all**. As a result, **all files remain until the lease expires (e.g., after 24 hours)**, even though most are no longer needed.
   
   ### ✅ Expected Behavior
   When snapshot `1` is leased:
   - The system should retain the **newest N snapshots** (e.g., `[4, 5]` for N=2) for normal subsumption.
   - Snapshot `1` should be placed in a separate **`stillInUse` set**, indicating it’s protected by a lease but not part of the standard retention window.
   - During cleanup (`sharedKvFileRegistry.unregisterUnusedKvFile` and `snapshotsCleaner.cleanSubsumedSnapshots`), the **effective lowest snapshot ID** should be `4` (not `1`), **and** any snapshot in `stillInUse` (the `1`) must be excluded from deletion.
   
   ### 🔧 Proposed Solution
   
   1. **Track Leased Snapshots Separately**  
      Introduce a `Map<Long, CompletedSnapshot> stillInUseSnapshots` in `CompletedSnapshotStore`.  
      - When `subsume()` is called, if a snapshot is leased, **do not remove it** from the store or delete its ZK metadata.  
      - Instead, add it to `stillInUseSnapshots`.
   
   2. **Update Cleanup Logic**  
      Both `sharedKvFileRegistry.unregisterUnusedKvFile()` and `snapshotsCleaner.cleanSubsumedSnapshots()` must:
      - Compute the effective `lowestSnapshotID` **from the retained (non-leased) snapshots only**.
      - Skip deletion of any file referenced by snapshots in `stillInUseSnapshots`.
   
   3. **Enhance `SharedKvEntry` Metadata**  
      Currently, `SharedKvEntry` only tracks `lastUsedSnapshotID`. We should add `firstUsedSnapshotID` to support accurate cleanup, so it track the min and max snapshot range of this kv file. 
      Then, in `SharedKvFileRegistry#unregisterUnusedKvFile()`, a KV file can only be deleted if **no snapshot in `stillInUseSnapshots` falls within `[min, max]`** of that file’s referencing range.
   
   **Please also add tests for the kv file cleanup when lease involved, like in `CompletedSnapshotStoreTest`.**
   



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/KvSnapshotLeaseManager.java:
##########
@@ -0,0 +1,459 @@
+/*
+ * 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.fluss.server.coordinator;
+
+import org.apache.fluss.annotation.VisibleForTesting;
+import org.apache.fluss.config.ConfigOptions;
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.metadata.KvSnapshotLeaseForBucket;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.metrics.MetricNames;
+import org.apache.fluss.server.metrics.group.CoordinatorMetricGroup;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLease;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLeaseMetadataManager;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotTableLease;
+import org.apache.fluss.utils.MapUtils;
+import org.apache.fluss.utils.clock.Clock;
+import org.apache.fluss.utils.concurrent.ExecutorThreadFactory;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.stream.Collectors;
+
+import static org.apache.fluss.utils.concurrent.LockUtils.inReadLock;
+import static org.apache.fluss.utils.concurrent.LockUtils.inWriteLock;
+
+/** A manager to manage kv snapshot lease acquire, renew, release and drop. */
+@ThreadSafe
+public class KvSnapshotLeaseManager {
+    private static final Logger LOG = LoggerFactory.getLogger(KvSnapshotLeaseManager.class);
+
+    private final KvSnapshotLeaseMetadataManager metadataManager;
+    private final CoordinatorContext coordinatorContext;
+    private final Clock clock;
+    private final ScheduledExecutorService scheduledExecutor;
+    private final Configuration conf;
+
+    private final Map<String, ReadWriteLock> leaseLocks = MapUtils.newConcurrentHashMap();
+    /** lease id to kv snapshot lease. */
+    @GuardedBy("leaseLocks")
+    private final Map<String, KvSnapshotLease> kvSnapshotLeaseMap;
+
+    private final ReadWriteLock refCountLock = new ReentrantReadWriteLock();
+
+    /**
+     * KvSnapshotLeaseForBucket to the ref count, which means this table bucket + snapshotId has
+     * been leased by how many lease id.
+     */
+    private final Map<KvSnapshotLeaseForBucket, AtomicInteger> refCount =
+            MapUtils.newConcurrentHashMap();
+
+    /** For metrics. */
+    private final AtomicInteger leasedBucketCount = new AtomicInteger(0);
+
+    public KvSnapshotLeaseManager(
+            Configuration conf,
+            KvSnapshotLeaseMetadataManager metadataManager,

Review Comment:
   This isn't an interface—it's essentially an inner class—so there's no need to expose it in the constructor parameters. Instead, just accept the atomic parameters directly: `ZooKeeperClient zkClient` and `String remoteDataDir` and contruct the inner class in the constructor. 



##########
fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/catalog/FlinkTableFactory.java:
##########
@@ -142,6 +143,15 @@ public DynamicTableSource createDynamicTableSource(Context context) {
                         .get(FlinkConnectorOptions.SCAN_PARTITION_DISCOVERY_INTERVAL)
                         .toMillis();
 
+        LeaseContext leaseContext =
+                primaryKeyIndexes.length > 0
+                        ? new LeaseContext(
+                                tableOptions.get(FlinkConnectorOptions.SCAN_KV_SNAPSHOT_LEASE_ID),
+                                tableOptions
+                                        .get(FlinkConnectorOptions.SCAN_KV_SNAPSHOT_LEASE_DURATION)
+                                        .toMillis())
+                        : new LeaseContext(null, null);

Review Comment:
   We can simplify this into one line `LeaseContext.fromConf(tableOptions)` by providing a `fromConf` static method on `LeaseContext`. No matter it is a PK table or LOG table, it's fine to have default values of lease context. 



##########
fluss-rpc/src/main/proto/FlussApi.proto:
##########
@@ -378,6 +378,29 @@ message GetKvSnapshotMetadataResponse {
   repeated PbRemotePathAndLocalFile snapshot_files = 2;
 }
 
+message AcquireKvSnapshotLeaseRequest {
+  required string lease_id = 1;
+  required int64 lease_duration = 2;
+  repeated PbKvSnapshotLeaseForTable table_lease_req = 3;
+}
+
+message AcquireKvSnapshotLeaseResponse {
+  repeated PbKvSnapshotLeaseForTable tables_lease_res = 3;

Review Comment:
   rename the `tables_lease_res` to `unavailable_snapshots`. This `tables_lease_res` is very confusing, I thought it is the snapshot that acquired, but it is opposite. 



##########
fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/source/enumerator/FlinkSourceEnumerator.java:
##########
@@ -923,11 +1007,55 @@ public void addReader(int subtaskId) {
     public SourceEnumeratorState snapshotState(long checkpointId) {
         final SourceEnumeratorState enumeratorState =
                 new SourceEnumeratorState(
-                        assignedTableBuckets, assignedPartitions, pendingHybridLakeFlussSplits);
+                        assignedTableBuckets,
+                        assignedPartitions,
+                        pendingHybridLakeFlussSplits,
+                        leaseContext);
         LOG.debug("Source Checkpoint is {}", enumeratorState);
         return enumeratorState;
     }
 
+    @Override
+    public void notifyCheckpointComplete(long checkpointId) throws Exception {
+        // lower than this checkpoint id.
+        Set<TableBucket> consumedKvSnapshots = getAndRemoveConsumedBucketsUpTo(checkpointId);
+
+        LOG.info(
+                "kv snapshot has already consumed and try to release kv snapshot lease for: {}, checkpoint id: {}",
+                consumedKvSnapshots,
+                checkpointId);
+
+        // send request to fluss to unregister the kv snapshot lease.
+        try {
+            flussAdmin
+                    .releaseKvSnapshotLease(

Review Comment:
   I don't see `drop_lease` or `release_all`. What happens in batch mode? There is no checkpoints, so the `notifyCheckpointComplete` will not be invoked. I suggest to drop lease in `close()` method, if it works in batch mode and has registered lease. 



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/KvSnapshotLeaseManager.java:
##########
@@ -0,0 +1,459 @@
+/*
+ * 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.fluss.server.coordinator;
+
+import org.apache.fluss.annotation.VisibleForTesting;
+import org.apache.fluss.config.ConfigOptions;
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.metadata.KvSnapshotLeaseForBucket;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.metrics.MetricNames;
+import org.apache.fluss.server.metrics.group.CoordinatorMetricGroup;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLease;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLeaseMetadataManager;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotTableLease;
+import org.apache.fluss.utils.MapUtils;
+import org.apache.fluss.utils.clock.Clock;
+import org.apache.fluss.utils.concurrent.ExecutorThreadFactory;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.stream.Collectors;
+
+import static org.apache.fluss.utils.concurrent.LockUtils.inReadLock;
+import static org.apache.fluss.utils.concurrent.LockUtils.inWriteLock;
+
+/** A manager to manage kv snapshot lease acquire, renew, release and drop. */
+@ThreadSafe
+public class KvSnapshotLeaseManager {
+    private static final Logger LOG = LoggerFactory.getLogger(KvSnapshotLeaseManager.class);
+
+    private final KvSnapshotLeaseMetadataManager metadataManager;
+    private final CoordinatorContext coordinatorContext;
+    private final Clock clock;
+    private final ScheduledExecutorService scheduledExecutor;
+    private final Configuration conf;
+
+    private final Map<String, ReadWriteLock> leaseLocks = MapUtils.newConcurrentHashMap();
+    /** lease id to kv snapshot lease. */
+    @GuardedBy("leaseLocks")
+    private final Map<String, KvSnapshotLease> kvSnapshotLeaseMap;

Review Comment:
   ```suggestion
       private final ConcurrentHashMap<String, KvSnapshotLease> kvSnapshotLeaseMap =
               MapUtils.newConcurrentHashMap();
   ```
   
   Mark the field type `ConcurrentHashMap` and assign it inline to make the semantic clear. 



##########
fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/FlinkConnectorOptions.java:
##########
@@ -76,6 +77,23 @@ public class FlinkConnectorOptions {
                             "A list of host/port pairs to use for establishing the initial connection to the Fluss cluster. "
                                     + "The list should be in the form host1:port1,host2:port2,....");
 
+    public static final ConfigOption<String> SCAN_KV_SNAPSHOT_LEASE_ID =
+            ConfigOptions.key("scan.kv.snapshot.lease.id")
+                    .stringType()
+                    .defaultValue(String.valueOf(UUID.randomUUID()))
+                    .withDescription(
+                            "The lease id to ping kv snapshots. If set, the acquired kv snapshots will not be deleted "
+                                    + "until the consumer finished consuming all the snapshots or the lease duration time "
+                                    + "is reached. If not set, an UUID will be set.");

Review Comment:
   Change to this (and also the doc):
   
   The lease ID used to protect acquired KV snapshots from deletion. If specified, the snapshots will be retained until either the consumer finishes processing all of them or the lease duration expires.  By default, this value is set to a randomly generated UUID string if not explicitly provided.



##########
fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/source/enumerator/FlinkSourceEnumerator.java:
##########
@@ -531,22 +537,88 @@ private List<SourceSplitBase> initPrimaryKeyTablePartitionSplits(
         List<SourceSplitBase> splits = new ArrayList<>();
         for (Partition partition : newPartitions) {
             String partitionName = partition.getPartitionName();
-            // get the table snapshot info
-            final KvSnapshots kvSnapshots;
-            try {
-                kvSnapshots = flussAdmin.getLatestKvSnapshots(tablePath, partitionName).get();
-            } catch (Exception e) {
-                throw new FlinkRuntimeException(
-                        String.format(
-                                "Failed to get table snapshot for table %s and partition %s",
-                                tablePath, partitionName),
-                        ExceptionUtils.stripCompletionException(e));
-            }
-            splits.addAll(getSnapshotAndLogSplits(kvSnapshots, partitionName));
+            splits.addAll(
+                    getSnapshotAndLogSplits(
+                            getLatestKvSnapshotsAndRegister(partitionName), partitionName));
         }
         return splits;
     }
 
+    private KvSnapshots getLatestKvSnapshotsAndRegister(@Nullable String partitionName) {
+        long tableId;
+        Long partitionId;
+        Map<Integer, Long> snapshotIds = new HashMap<>();
+        Map<Integer, Long> logOffsets = new HashMap<>();
+
+        // retry to get the latest kv snapshots and acquire kvSnapshot lease.
+        try {
+            KvSnapshots kvSnapshots = getLatestKvSnapshots(partitionName);
+            Set<TableBucket> remainingTableBuckets = new HashSet<>(kvSnapshots.getTableBuckets());
+
+            tableId = kvSnapshots.getTableId();
+            partitionId = kvSnapshots.getPartitionId();
+
+            Set<TableBucket> ignoreBuckets = new HashSet<>();
+            Map<TableBucket, Long> bucketsToLease = new HashMap<>();
+            for (TableBucket tb : remainingTableBuckets) {
+                int bucket = tb.getBucket();
+                OptionalLong snapshotIdOpt = kvSnapshots.getSnapshotId(bucket);
+                OptionalLong logOffsetOpt = kvSnapshots.getLogOffset(bucket);
+                if (snapshotIdOpt.isPresent() && !ignoreTableBucket(tb)) {
+                    bucketsToLease.put(tb, snapshotIdOpt.getAsLong());
+                } else {
+                    ignoreBuckets.add(tb);
+                }
+
+                snapshotIds.put(
+                        bucket, snapshotIdOpt.isPresent() ? snapshotIdOpt.getAsLong() : null);
+                logOffsets.put(bucket, logOffsetOpt.isPresent() ? logOffsetOpt.getAsLong() : null);
+            }
+
+            if (!ignoreBuckets.isEmpty()) {
+                remainingTableBuckets.removeAll(ignoreBuckets);
+            }
+
+            if (!bucketsToLease.isEmpty()) {
+                String kvSnapshotLeaseId = leaseContext.getKvSnapshotLeaseId();
+                LOG.info(
+                        "Try to acquire kv snapshot lease {} for table {}",
+                        kvSnapshotLeaseId,
+                        tablePath);
+                Long kvSnapshotLeaseDurationMs = leaseContext.getKvSnapshotLeaseDurationMs();
+                checkNotNull(kvSnapshotLeaseDurationMs, "kv snapshot lease duration is null.");
+                remainingTableBuckets =
+                        flussAdmin
+                                .acquireKvSnapshotLease(
+                                        kvSnapshotLeaseId,
+                                        bucketsToLease,
+                                        kvSnapshotLeaseDurationMs)
+                                .get()
+                                .getUnavailableTableBucketSet();
+                if (!remainingTableBuckets.isEmpty()) {
+                    LOG.info(
+                            "Failed to acquire kv snapshot lease for table {}: {}. Retry to re-acquire",

Review Comment:
   I don't see the `Retry to re-acquire` logic. 



##########
fluss-common/src/main/java/org/apache/fluss/metadata/KvSnapshotLeaseForBucket.java:
##########
@@ -0,0 +1,66 @@
+/*
+ * 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.fluss.metadata;
+
+import java.util.Objects;
+
+/** An entity for kv snapshot lease for bucket. */
+public class KvSnapshotLeaseForBucket {
+    private final TableBucket tableBucket;
+    private final long kvSnapshotId;
+
+    public KvSnapshotLeaseForBucket(TableBucket tableBucket, long kvSnapshotId) {
+        this.tableBucket = tableBucket;
+        this.kvSnapshotId = kvSnapshotId;
+    }
+
+    public TableBucket getTableBucket() {
+        return tableBucket;
+    }
+
+    public long getKvSnapshotId() {

Review Comment:
   rename to `getSnapshotId()`.



##########
fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/source/state/FlussSourceEnumeratorStateSerializer.java:
##########
@@ -260,4 +287,39 @@ private List<SourceSplitBase> deserializeRemainingHybridLakeFlussSplits(
             return null;
         }
     }
+
+    private void serializeLeaseContext(final DataOutputSerializer out, SourceEnumeratorState state)
+            throws IOException {
+        LeaseContext leaseContext = state.getLeaseContext();
+        String kvSnapshotLeaseId = leaseContext.getKvSnapshotLeaseId();
+        if (kvSnapshotLeaseId != null) {
+            out.writeBoolean(true);
+            out.writeUTF(kvSnapshotLeaseId);
+        } else {
+            out.writeBoolean(false);
+        }
+
+        Long kvSnapshotLeaseDurationMs = leaseContext.getKvSnapshotLeaseDurationMs();
+        if (kvSnapshotLeaseDurationMs != null) {
+            out.writeBoolean(true);
+            out.writeLong(kvSnapshotLeaseDurationMs);

Review Comment:
   We don't need to serialize the duration config into state. It's not a state. Actually, we shoulld support the reconfigure for the duration config, setting it into state will block use to reconfigure it after job restarts. 



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/KvSnapshotLeaseManager.java:
##########
@@ -0,0 +1,459 @@
+/*
+ * 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.fluss.server.coordinator;
+
+import org.apache.fluss.annotation.VisibleForTesting;
+import org.apache.fluss.config.ConfigOptions;
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.metadata.KvSnapshotLeaseForBucket;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.metrics.MetricNames;
+import org.apache.fluss.server.metrics.group.CoordinatorMetricGroup;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLease;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLeaseMetadataManager;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotTableLease;
+import org.apache.fluss.utils.MapUtils;
+import org.apache.fluss.utils.clock.Clock;
+import org.apache.fluss.utils.concurrent.ExecutorThreadFactory;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.stream.Collectors;
+
+import static org.apache.fluss.utils.concurrent.LockUtils.inReadLock;
+import static org.apache.fluss.utils.concurrent.LockUtils.inWriteLock;
+
+/** A manager to manage kv snapshot lease acquire, renew, release and drop. */
+@ThreadSafe
+public class KvSnapshotLeaseManager {
+    private static final Logger LOG = LoggerFactory.getLogger(KvSnapshotLeaseManager.class);
+
+    private final KvSnapshotLeaseMetadataManager metadataManager;
+    private final CoordinatorContext coordinatorContext;
+    private final Clock clock;
+    private final ScheduledExecutorService scheduledExecutor;
+    private final Configuration conf;

Review Comment:
   only have lease expiration check interval as member variable is enought, remove the conf.



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/KvSnapshotLeaseManager.java:
##########
@@ -0,0 +1,459 @@
+/*
+ * 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.fluss.server.coordinator;
+
+import org.apache.fluss.annotation.VisibleForTesting;
+import org.apache.fluss.config.ConfigOptions;
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.metadata.KvSnapshotLeaseForBucket;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.metrics.MetricNames;
+import org.apache.fluss.server.metrics.group.CoordinatorMetricGroup;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLease;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLeaseMetadataManager;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotTableLease;
+import org.apache.fluss.utils.MapUtils;
+import org.apache.fluss.utils.clock.Clock;
+import org.apache.fluss.utils.concurrent.ExecutorThreadFactory;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.stream.Collectors;
+
+import static org.apache.fluss.utils.concurrent.LockUtils.inReadLock;
+import static org.apache.fluss.utils.concurrent.LockUtils.inWriteLock;
+
+/** A manager to manage kv snapshot lease acquire, renew, release and drop. */
+@ThreadSafe
+public class KvSnapshotLeaseManager {
+    private static final Logger LOG = LoggerFactory.getLogger(KvSnapshotLeaseManager.class);
+
+    private final KvSnapshotLeaseMetadataManager metadataManager;
+    private final CoordinatorContext coordinatorContext;
+    private final Clock clock;
+    private final ScheduledExecutorService scheduledExecutor;
+    private final Configuration conf;
+
+    private final Map<String, ReadWriteLock> leaseLocks = MapUtils.newConcurrentHashMap();
+    /** lease id to kv snapshot lease. */
+    @GuardedBy("leaseLocks")
+    private final Map<String, KvSnapshotLease> kvSnapshotLeaseMap;
+
+    private final ReadWriteLock refCountLock = new ReentrantReadWriteLock();
+
+    /**
+     * KvSnapshotLeaseForBucket to the ref count, which means this table bucket + snapshotId has
+     * been leased by how many lease id.
+     */
+    private final Map<KvSnapshotLeaseForBucket, AtomicInteger> refCount =
+            MapUtils.newConcurrentHashMap();
+
+    /** For metrics. */
+    private final AtomicInteger leasedBucketCount = new AtomicInteger(0);
+
+    public KvSnapshotLeaseManager(
+            Configuration conf,
+            KvSnapshotLeaseMetadataManager metadataManager,
+            CoordinatorContext coordinatorContext,
+            Clock clock,
+            CoordinatorMetricGroup coordinatorMetricGroup) {
+        this(
+                conf,
+                metadataManager,
+                coordinatorContext,
+                Executors.newScheduledThreadPool(
+                        1, new ExecutorThreadFactory("kv-snapshot-lease-cleaner")),
+                clock,
+                coordinatorMetricGroup);
+    }
+
+    @VisibleForTesting
+    public KvSnapshotLeaseManager(
+            Configuration conf,
+            KvSnapshotLeaseMetadataManager metadataManager,
+            CoordinatorContext coordinatorContext,
+            ScheduledExecutorService scheduledExecutor,
+            Clock clock,
+            CoordinatorMetricGroup coordinatorMetricGroup) {
+        this.metadataManager = metadataManager;
+        this.conf = conf;
+        this.scheduledExecutor = scheduledExecutor;
+        this.coordinatorContext = coordinatorContext;
+        this.clock = clock;
+        this.kvSnapshotLeaseMap = MapUtils.newConcurrentHashMap();
+
+        registerMetrics(coordinatorMetricGroup);
+    }
+
+    public void start() {
+        LOG.info("kv snapshot lease manager has been started.");
+        scheduledExecutor.scheduleWithFixedDelay(
+                this::expireLeases,
+                0L,
+                conf.get(ConfigOptions.KV_SNAPSHOT_LEASE_EXPIRATION_CHECK_INTERVAL).toMillis(),
+                TimeUnit.MILLISECONDS);
+    }
+
+    public void initialize() throws Exception {
+        for (String leaseId : metadataManager.getLeasesList()) {
+            Optional<KvSnapshotLease> kvSnapshotLeaseOpt = metadataManager.getLease(leaseId);
+            if (kvSnapshotLeaseOpt.isPresent()) {
+                KvSnapshotLease kvSnapshotLease = kvSnapshotLeaseOpt.get();
+                this.leaseLocks.put(leaseId, new ReentrantReadWriteLock());
+                this.kvSnapshotLeaseMap.put(leaseId, kvSnapshotLease);
+
+                initializeRefCount(kvSnapshotLease);
+
+                leasedBucketCount.addAndGet(kvSnapshotLease.getLeasedSnapshotCount());
+            }
+        }
+    }
+
+    public boolean snapshotLeaseNotExist(KvSnapshotLeaseForBucket kvSnapshotLeaseForBucket) {
+        return inReadLock(
+                refCountLock,
+                () -> {
+                    AtomicInteger count = refCount.get(kvSnapshotLeaseForBucket);
+                    return count == null || count.get() <= 0;
+                });
+    }
+
+    /**
+     * Acquire kv snapshot lease.
+     *
+     * @param leaseId the lease id
+     * @param leaseDuration the lease duration
+     * @param tableIdToLeaseBucket the table id to lease bucket
+     * @return the map of unavailable snapshots that failed to be leased
+     */
+    public Map<TableBucket, Long> acquireLease(
+            String leaseId,
+            long leaseDuration,
+            Map<Long, List<KvSnapshotLeaseForBucket>> tableIdToLeaseBucket)
+            throws Exception {
+        ReadWriteLock lock = leaseLocks.computeIfAbsent(leaseId, k -> new ReentrantReadWriteLock());
+        return inWriteLock(
+                lock,
+                () -> {
+                    // To record the unavailable snapshots such as the kv snapshotId to lease not
+                    // exists.
+                    Map<TableBucket, Long> unavailableSnapshots = new HashMap<>();
+
+                    boolean update = kvSnapshotLeaseMap.containsKey(leaseId);
+                    // set the expiration time as: current time + leaseDuration
+                    long newExpirationTime = clock.milliseconds() + leaseDuration;
+                    KvSnapshotLease kvSnapshotLease =
+                            kvSnapshotLeaseMap.compute(
+                                    leaseId,
+                                    (key, existingLease) -> {
+                                        if (existingLease == null) {
+                                            LOG.info(
+                                                    "kv snapshot lease '{}' has been acquired. The lease expiration "
+                                                            + "time is {}",
+                                                    leaseId,
+                                                    newExpirationTime);
+                                            return new KvSnapshotLease(newExpirationTime);
+                                        } else {
+                                            existingLease.setExpirationTime(newExpirationTime);
+                                            return existingLease;
+                                        }
+                                    });
+
+                    for (Map.Entry<Long, List<KvSnapshotLeaseForBucket>> entry :
+                            tableIdToLeaseBucket.entrySet()) {
+                        Long tableId = entry.getKey();
+                        TableInfo tableInfo = coordinatorContext.getTableInfoById(tableId);
+                        int numBuckets = tableInfo.getNumBuckets();

Review Comment:
   Actually, we don't need to access the `coordinatorContext` for the `numBuckets`. We can grow the snapshot array size in lease if the new acquired bucket id is larger than the previous array size. 



##########
fluss-server/src/main/java/org/apache/fluss/server/zk/data/lease/KvSnapshotLeaseMetadataManager.java:
##########
@@ -0,0 +1,226 @@
+/*
+ * 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.fluss.server.zk.data.lease;
+
+import org.apache.fluss.fs.FSDataInputStream;
+import org.apache.fluss.fs.FSDataOutputStream;
+import org.apache.fluss.fs.FileSystem;
+import org.apache.fluss.fs.FsPath;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.server.zk.ZooKeeperClient;
+import org.apache.fluss.server.zk.data.BucketSnapshot;
+import org.apache.fluss.utils.FlussPaths;
+import org.apache.fluss.utils.IOUtils;
+import org.apache.fluss.utils.types.Tuple2;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.ByteArrayOutputStream;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/**
+ * The manager to handle {@link KvSnapshotLease} to register/update/delete metadata from zk and
+ * remote fs.
+ */
+public class KvSnapshotLeaseMetadataManager {

Review Comment:
   ditto. it's not an entity class for znode. should be moved to `org.apache.fluss.server.coordinator.lease`.



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/KvSnapshotLeaseManager.java:
##########
@@ -0,0 +1,459 @@
+/*
+ * 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.fluss.server.coordinator;
+
+import org.apache.fluss.annotation.VisibleForTesting;
+import org.apache.fluss.config.ConfigOptions;
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.metadata.KvSnapshotLeaseForBucket;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.metrics.MetricNames;
+import org.apache.fluss.server.metrics.group.CoordinatorMetricGroup;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLease;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLeaseMetadataManager;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotTableLease;
+import org.apache.fluss.utils.MapUtils;
+import org.apache.fluss.utils.clock.Clock;
+import org.apache.fluss.utils.concurrent.ExecutorThreadFactory;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.stream.Collectors;
+
+import static org.apache.fluss.utils.concurrent.LockUtils.inReadLock;
+import static org.apache.fluss.utils.concurrent.LockUtils.inWriteLock;
+
+/** A manager to manage kv snapshot lease acquire, renew, release and drop. */
+@ThreadSafe
+public class KvSnapshotLeaseManager {
+    private static final Logger LOG = LoggerFactory.getLogger(KvSnapshotLeaseManager.class);
+
+    private final KvSnapshotLeaseMetadataManager metadataManager;
+    private final CoordinatorContext coordinatorContext;
+    private final Clock clock;
+    private final ScheduledExecutorService scheduledExecutor;
+    private final Configuration conf;
+
+    private final Map<String, ReadWriteLock> leaseLocks = MapUtils.newConcurrentHashMap();
+    /** lease id to kv snapshot lease. */
+    @GuardedBy("leaseLocks")
+    private final Map<String, KvSnapshotLease> kvSnapshotLeaseMap;
+
+    private final ReadWriteLock refCountLock = new ReentrantReadWriteLock();
+
+    /**
+     * KvSnapshotLeaseForBucket to the ref count, which means this table bucket + snapshotId has
+     * been leased by how many lease id.
+     */
+    private final Map<KvSnapshotLeaseForBucket, AtomicInteger> refCount =
+            MapUtils.newConcurrentHashMap();
+
+    /** For metrics. */
+    private final AtomicInteger leasedBucketCount = new AtomicInteger(0);
+
+    public KvSnapshotLeaseManager(
+            Configuration conf,
+            KvSnapshotLeaseMetadataManager metadataManager,
+            CoordinatorContext coordinatorContext,
+            Clock clock,
+            CoordinatorMetricGroup coordinatorMetricGroup) {
+        this(
+                conf,
+                metadataManager,
+                coordinatorContext,
+                Executors.newScheduledThreadPool(
+                        1, new ExecutorThreadFactory("kv-snapshot-lease-cleaner")),
+                clock,
+                coordinatorMetricGroup);
+    }
+
+    @VisibleForTesting
+    public KvSnapshotLeaseManager(
+            Configuration conf,
+            KvSnapshotLeaseMetadataManager metadataManager,
+            CoordinatorContext coordinatorContext,
+            ScheduledExecutorService scheduledExecutor,
+            Clock clock,
+            CoordinatorMetricGroup coordinatorMetricGroup) {
+        this.metadataManager = metadataManager;
+        this.conf = conf;
+        this.scheduledExecutor = scheduledExecutor;
+        this.coordinatorContext = coordinatorContext;
+        this.clock = clock;
+        this.kvSnapshotLeaseMap = MapUtils.newConcurrentHashMap();
+
+        registerMetrics(coordinatorMetricGroup);
+    }
+
+    public void start() {
+        LOG.info("kv snapshot lease manager has been started.");
+        scheduledExecutor.scheduleWithFixedDelay(
+                this::expireLeases,
+                0L,
+                conf.get(ConfigOptions.KV_SNAPSHOT_LEASE_EXPIRATION_CHECK_INTERVAL).toMillis(),
+                TimeUnit.MILLISECONDS);
+    }
+
+    public void initialize() throws Exception {
+        for (String leaseId : metadataManager.getLeasesList()) {
+            Optional<KvSnapshotLease> kvSnapshotLeaseOpt = metadataManager.getLease(leaseId);
+            if (kvSnapshotLeaseOpt.isPresent()) {
+                KvSnapshotLease kvSnapshotLease = kvSnapshotLeaseOpt.get();
+                this.leaseLocks.put(leaseId, new ReentrantReadWriteLock());
+                this.kvSnapshotLeaseMap.put(leaseId, kvSnapshotLease);
+
+                initializeRefCount(kvSnapshotLease);
+
+                leasedBucketCount.addAndGet(kvSnapshotLease.getLeasedSnapshotCount());
+            }
+        }
+    }
+
+    public boolean snapshotLeaseNotExist(KvSnapshotLeaseForBucket kvSnapshotLeaseForBucket) {
+        return inReadLock(
+                refCountLock,
+                () -> {
+                    AtomicInteger count = refCount.get(kvSnapshotLeaseForBucket);
+                    return count == null || count.get() <= 0;
+                });
+    }
+
+    /**
+     * Acquire kv snapshot lease.
+     *
+     * @param leaseId the lease id
+     * @param leaseDuration the lease duration
+     * @param tableIdToLeaseBucket the table id to lease bucket
+     * @return the map of unavailable snapshots that failed to be leased
+     */
+    public Map<TableBucket, Long> acquireLease(
+            String leaseId,
+            long leaseDuration,
+            Map<Long, List<KvSnapshotLeaseForBucket>> tableIdToLeaseBucket)
+            throws Exception {
+        ReadWriteLock lock = leaseLocks.computeIfAbsent(leaseId, k -> new ReentrantReadWriteLock());
+        return inWriteLock(
+                lock,
+                () -> {
+                    // To record the unavailable snapshots such as the kv snapshotId to lease not
+                    // exists.
+                    Map<TableBucket, Long> unavailableSnapshots = new HashMap<>();
+
+                    boolean update = kvSnapshotLeaseMap.containsKey(leaseId);
+                    // set the expiration time as: current time + leaseDuration
+                    long newExpirationTime = clock.milliseconds() + leaseDuration;
+                    KvSnapshotLease kvSnapshotLease =
+                            kvSnapshotLeaseMap.compute(
+                                    leaseId,
+                                    (key, existingLease) -> {
+                                        if (existingLease == null) {
+                                            LOG.info(
+                                                    "kv snapshot lease '{}' has been acquired. The lease expiration "
+                                                            + "time is {}",
+                                                    leaseId,
+                                                    newExpirationTime);
+                                            return new KvSnapshotLease(newExpirationTime);
+                                        } else {
+                                            existingLease.setExpirationTime(newExpirationTime);
+                                            return existingLease;
+                                        }
+                                    });
+
+                    for (Map.Entry<Long, List<KvSnapshotLeaseForBucket>> entry :
+                            tableIdToLeaseBucket.entrySet()) {
+                        Long tableId = entry.getKey();
+                        TableInfo tableInfo = coordinatorContext.getTableInfoById(tableId);
+                        int numBuckets = tableInfo.getNumBuckets();
+                        List<KvSnapshotLeaseForBucket> buckets = entry.getValue();
+                        for (KvSnapshotLeaseForBucket bucket : buckets) {
+
+                            TableBucket tableBucket = bucket.getTableBucket();
+                            long kvSnapshotId = bucket.getKvSnapshotId();
+                            try {
+                                boolean snapshotExists =
+                                        metadataManager.isSnapshotExists(tableBucket, kvSnapshotId);
+                                if (!snapshotExists) {
+                                    unavailableSnapshots.put(tableBucket, kvSnapshotId);
+                                    continue;
+                                }
+                            } catch (Exception e) {
+                                LOG.error(
+                                        "Failed to check snapshotExists for tableBucket when acquire kv "
+                                                + "snapshot kvSnapshotLease {}.",
+                                        tableBucket,
+                                        e);
+                                unavailableSnapshots.put(tableBucket, kvSnapshotId);
+                                continue;
+                            }
+
+                            long originalSnapshotId =
+                                    kvSnapshotLease.acquireBucket(
+                                            tableBucket, kvSnapshotId, numBuckets);
+                            if (originalSnapshotId == -1L) {
+                                leasedBucketCount.incrementAndGet();
+                            } else {
+                                // clear the original ref.
+                                decrementRefCount(
+                                        new KvSnapshotLeaseForBucket(
+                                                tableBucket, originalSnapshotId));
+                            }
+                            incrementRefCount(bucket);
+                        }
+                    }
+
+                    if (update) {
+                        metadataManager.updateLease(leaseId, kvSnapshotLease);
+                    } else {
+                        metadataManager.registerLease(leaseId, kvSnapshotLease);
+                    }
+
+                    return unavailableSnapshots;
+                });
+    }
+
+    public void release(String leaseId, Map<Long, List<TableBucket>> tableIdToUnregisterBucket)
+            throws Exception {
+        ReadWriteLock lock = leaseLocks.get(leaseId);
+        if (lock == null) {
+            return;
+        }
+
+        inWriteLock(
+                lock,
+                () -> {
+                    KvSnapshotLease lease = kvSnapshotLeaseMap.get(leaseId);
+                    if (lease == null) {
+                        return;
+                    }
+
+                    for (Map.Entry<Long, List<TableBucket>> entry :
+                            tableIdToUnregisterBucket.entrySet()) {
+                        List<TableBucket> buckets = entry.getValue();
+                        for (TableBucket bucket : buckets) {
+                            long snapshotId = lease.releaseBucket(bucket);
+                            if (snapshotId != -1L) {
+                                leasedBucketCount.decrementAndGet();
+                                decrementRefCount(new KvSnapshotLeaseForBucket(bucket, snapshotId));
+                            }
+                        }
+                    }
+
+                    if (lease.isEmpty()) {
+                        releaseAll(leaseId);
+                    } else {
+                        metadataManager.updateLease(leaseId, lease);
+                    }
+                });
+    }
+
+    /**
+     * Release kv snapshot lease.
+     *
+     * @param leaseId the lease id
+     * @return true if clear success, false if lease not exist
+     */
+    public boolean releaseAll(String leaseId) throws Exception {
+        ReadWriteLock lock = leaseLocks.get(leaseId);
+        if (lock == null) {
+            return false;
+        }
+
+        boolean exist =
+                inWriteLock(
+                        lock,
+                        () -> {
+                            KvSnapshotLease kvSnapshotLease = kvSnapshotLeaseMap.remove(leaseId);
+                            if (kvSnapshotLease == null) {
+                                return false;
+                            }
+
+                            clearRefCount(kvSnapshotLease);
+                            metadataManager.deleteLease(leaseId);
+
+                            LOG.info(
+                                    "kv snapshots of lease '"
+                                            + leaseId
+                                            + "' has been all released.");
+                            return true;
+                        });
+
+        leaseLocks.remove(leaseId);
+        return exist;
+    }
+
+    private void initializeRefCount(KvSnapshotLease lease) {
+        for (Map.Entry<Long, KvSnapshotTableLease> tableEntry :
+                lease.getTableIdToTableLease().entrySet()) {
+            long tableId = tableEntry.getKey();
+            KvSnapshotTableLease tableLease = tableEntry.getValue();
+            if (tableLease.getBucketSnapshots() != null) {
+                Long[] snapshots = tableLease.getBucketSnapshots();
+                for (int i = 0; i < snapshots.length; i++) {
+                    if (snapshots[i] == -1L) {
+                        continue;
+                    }
+
+                    incrementRefCount(
+                            new KvSnapshotLeaseForBucket(
+                                    new TableBucket(tableId, i), snapshots[i]));
+                }
+            } else {
+                Map<Long, Long[]> partitionSnapshots = tableLease.getPartitionSnapshots();
+                for (Map.Entry<Long, Long[]> entry : partitionSnapshots.entrySet()) {
+                    Long partitionId = entry.getKey();
+                    Long[] snapshots = entry.getValue();
+                    for (int i = 0; i < snapshots.length; i++) {
+                        if (snapshots[i] == -1L) {
+                            continue;
+                        }
+
+                        incrementRefCount(
+                                new KvSnapshotLeaseForBucket(
+                                        new TableBucket(tableId, partitionId, i), snapshots[i]));
+                    }
+                }
+            }
+        }
+    }
+
+    private void clearRefCount(KvSnapshotLease lease) {
+        for (Map.Entry<Long, KvSnapshotTableLease> tableEntry :
+                lease.getTableIdToTableLease().entrySet()) {
+            long tableId = tableEntry.getKey();
+            KvSnapshotTableLease tableLease = tableEntry.getValue();
+            if (tableLease.getBucketSnapshots() != null) {
+                Long[] snapshots = tableLease.getBucketSnapshots();
+                for (int i = 0; i < snapshots.length; i++) {
+                    if (snapshots[i] == -1L) {
+                        continue;
+                    }
+                    decrementRefCount(
+                            new KvSnapshotLeaseForBucket(
+                                    new TableBucket(tableId, i), snapshots[i]));
+                    leasedBucketCount.decrementAndGet();
+                }
+            } else {
+                Map<Long, Long[]> partitionSnapshots = tableLease.getPartitionSnapshots();
+                for (Map.Entry<Long, Long[]> entry : partitionSnapshots.entrySet()) {
+                    Long partitionId = entry.getKey();
+                    Long[] snapshots = entry.getValue();
+                    for (int i = 0; i < snapshots.length; i++) {
+                        if (snapshots[i] == -1L) {
+                            continue;
+                        }
+
+                        decrementRefCount(
+                                new KvSnapshotLeaseForBucket(
+                                        new TableBucket(tableId, partitionId, i), snapshots[i]));
+                        leasedBucketCount.decrementAndGet();
+                    }
+                }
+            }
+        }
+    }
+
+    private void incrementRefCount(KvSnapshotLeaseForBucket kvSnapshotLeaseForBucket) {
+        inWriteLock(
+                refCountLock,
+                () ->
+                        refCount.computeIfAbsent(
+                                        kvSnapshotLeaseForBucket, k -> new AtomicInteger(0))
+                                .incrementAndGet());
+    }

Review Comment:
   We can remove the `inWriteLock` because `refCount` is already a `ConcurrentHashMap`, which is thread-safe by design. Eliminating the lock will also improve performance.
   
   The current `inWriteLock` is highly contended: methods like `initializeRefCount` frequently invoke `incrementRefCount` and `decrementRefCount`, leading to excessive lock acquisition and release overhead. This should be optimized.
   
   Since `ConcurrentHashMap` provides sufficient concurrency guarantees for reference counting, we don’t need an additional lock. Alternatively, if a non-concurrent map were used, a read-write lock might be justified—but in this case, sticking with `ConcurrentHashMap` alone is simpler and more efficient.



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/KvSnapshotLeaseManager.java:
##########
@@ -0,0 +1,459 @@
+/*
+ * 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.fluss.server.coordinator;
+
+import org.apache.fluss.annotation.VisibleForTesting;
+import org.apache.fluss.config.ConfigOptions;
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.metadata.KvSnapshotLeaseForBucket;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.metrics.MetricNames;
+import org.apache.fluss.server.metrics.group.CoordinatorMetricGroup;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLease;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLeaseMetadataManager;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotTableLease;
+import org.apache.fluss.utils.MapUtils;
+import org.apache.fluss.utils.clock.Clock;
+import org.apache.fluss.utils.concurrent.ExecutorThreadFactory;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.stream.Collectors;
+
+import static org.apache.fluss.utils.concurrent.LockUtils.inReadLock;
+import static org.apache.fluss.utils.concurrent.LockUtils.inWriteLock;
+
+/** A manager to manage kv snapshot lease acquire, renew, release and drop. */
+@ThreadSafe
+public class KvSnapshotLeaseManager {
+    private static final Logger LOG = LoggerFactory.getLogger(KvSnapshotLeaseManager.class);
+
+    private final KvSnapshotLeaseMetadataManager metadataManager;
+    private final CoordinatorContext coordinatorContext;
+    private final Clock clock;
+    private final ScheduledExecutorService scheduledExecutor;
+    private final Configuration conf;
+
+    private final Map<String, ReadWriteLock> leaseLocks = MapUtils.newConcurrentHashMap();
+    /** lease id to kv snapshot lease. */
+    @GuardedBy("leaseLocks")
+    private final Map<String, KvSnapshotLease> kvSnapshotLeaseMap;
+
+    private final ReadWriteLock refCountLock = new ReentrantReadWriteLock();
+
+    /**
+     * KvSnapshotLeaseForBucket to the ref count, which means this table bucket + snapshotId has
+     * been leased by how many lease id.
+     */
+    private final Map<KvSnapshotLeaseForBucket, AtomicInteger> refCount =
+            MapUtils.newConcurrentHashMap();
+
+    /** For metrics. */
+    private final AtomicInteger leasedBucketCount = new AtomicInteger(0);
+
+    public KvSnapshotLeaseManager(
+            Configuration conf,
+            KvSnapshotLeaseMetadataManager metadataManager,
+            CoordinatorContext coordinatorContext,
+            Clock clock,
+            CoordinatorMetricGroup coordinatorMetricGroup) {
+        this(
+                conf,
+                metadataManager,
+                coordinatorContext,
+                Executors.newScheduledThreadPool(
+                        1, new ExecutorThreadFactory("kv-snapshot-lease-cleaner")),

Review Comment:
   We should avoid start one after another threads. Could you reuse the scheduler with `ProducerOffsetsManager`? The `KvSnapshotLeaseManager` should be moved into `CoordinatorService`, so it should be easy to share the thread pool.



##########
fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/source/state/SourceEnumeratorState.java:
##########
@@ -41,13 +42,18 @@ public class SourceEnumeratorState {
     // lake snapshot
     @Nullable private final List<SourceSplitBase> remainingHybridLakeFlussSplits;
 
+    // lease context for restore.
+    private final LeaseContext leaseContext;
+
     public SourceEnumeratorState(
             Set<TableBucket> assignedBuckets,
             Map<Long, String> assignedPartitions,
-            @Nullable List<SourceSplitBase> remainingHybridLakeFlussSplits) {
+            @Nullable List<SourceSplitBase> remainingHybridLakeFlussSplits,
+            @Nullable LeaseContext leaseContext) {

Review Comment:
   Just serialize enumerator state with lease id



##########
fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/source/enumerator/FlinkSourceEnumerator.java:
##########
@@ -531,22 +537,88 @@ private List<SourceSplitBase> initPrimaryKeyTablePartitionSplits(
         List<SourceSplitBase> splits = new ArrayList<>();
         for (Partition partition : newPartitions) {
             String partitionName = partition.getPartitionName();
-            // get the table snapshot info
-            final KvSnapshots kvSnapshots;
-            try {
-                kvSnapshots = flussAdmin.getLatestKvSnapshots(tablePath, partitionName).get();
-            } catch (Exception e) {
-                throw new FlinkRuntimeException(
-                        String.format(
-                                "Failed to get table snapshot for table %s and partition %s",
-                                tablePath, partitionName),
-                        ExceptionUtils.stripCompletionException(e));
-            }
-            splits.addAll(getSnapshotAndLogSplits(kvSnapshots, partitionName));
+            splits.addAll(
+                    getSnapshotAndLogSplits(
+                            getLatestKvSnapshotsAndRegister(partitionName), partitionName));
         }
         return splits;
     }
 
+    private KvSnapshots getLatestKvSnapshotsAndRegister(@Nullable String partitionName) {
+        long tableId;
+        Long partitionId;
+        Map<Integer, Long> snapshotIds = new HashMap<>();
+        Map<Integer, Long> logOffsets = new HashMap<>();
+
+        // retry to get the latest kv snapshots and acquire kvSnapshot lease.
+        try {
+            KvSnapshots kvSnapshots = getLatestKvSnapshots(partitionName);
+            Set<TableBucket> remainingTableBuckets = new HashSet<>(kvSnapshots.getTableBuckets());
+
+            tableId = kvSnapshots.getTableId();
+            partitionId = kvSnapshots.getPartitionId();
+
+            Set<TableBucket> ignoreBuckets = new HashSet<>();
+            Map<TableBucket, Long> bucketsToLease = new HashMap<>();
+            for (TableBucket tb : remainingTableBuckets) {
+                int bucket = tb.getBucket();
+                OptionalLong snapshotIdOpt = kvSnapshots.getSnapshotId(bucket);
+                OptionalLong logOffsetOpt = kvSnapshots.getLogOffset(bucket);
+                if (snapshotIdOpt.isPresent() && !ignoreTableBucket(tb)) {
+                    bucketsToLease.put(tb, snapshotIdOpt.getAsLong());
+                } else {
+                    ignoreBuckets.add(tb);
+                }
+
+                snapshotIds.put(
+                        bucket, snapshotIdOpt.isPresent() ? snapshotIdOpt.getAsLong() : null);
+                logOffsets.put(bucket, logOffsetOpt.isPresent() ? logOffsetOpt.getAsLong() : null);
+            }
+
+            if (!ignoreBuckets.isEmpty()) {
+                remainingTableBuckets.removeAll(ignoreBuckets);
+            }
+
+            if (!bucketsToLease.isEmpty()) {
+                String kvSnapshotLeaseId = leaseContext.getKvSnapshotLeaseId();
+                LOG.info(
+                        "Try to acquire kv snapshot lease {} for table {}",
+                        kvSnapshotLeaseId,
+                        tablePath);

Review Comment:
   nit: we should print the nullable partition name as well in the log. 



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/KvSnapshotLeaseManager.java:
##########
@@ -0,0 +1,459 @@
+/*
+ * 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.fluss.server.coordinator;
+
+import org.apache.fluss.annotation.VisibleForTesting;
+import org.apache.fluss.config.ConfigOptions;
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.metadata.KvSnapshotLeaseForBucket;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.metrics.MetricNames;
+import org.apache.fluss.server.metrics.group.CoordinatorMetricGroup;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLease;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLeaseMetadataManager;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotTableLease;
+import org.apache.fluss.utils.MapUtils;
+import org.apache.fluss.utils.clock.Clock;
+import org.apache.fluss.utils.concurrent.ExecutorThreadFactory;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.stream.Collectors;
+
+import static org.apache.fluss.utils.concurrent.LockUtils.inReadLock;
+import static org.apache.fluss.utils.concurrent.LockUtils.inWriteLock;
+
+/** A manager to manage kv snapshot lease acquire, renew, release and drop. */
+@ThreadSafe
+public class KvSnapshotLeaseManager {
+    private static final Logger LOG = LoggerFactory.getLogger(KvSnapshotLeaseManager.class);
+
+    private final KvSnapshotLeaseMetadataManager metadataManager;
+    private final CoordinatorContext coordinatorContext;
+    private final Clock clock;
+    private final ScheduledExecutorService scheduledExecutor;
+    private final Configuration conf;
+
+    private final Map<String, ReadWriteLock> leaseLocks = MapUtils.newConcurrentHashMap();
+    /** lease id to kv snapshot lease. */
+    @GuardedBy("leaseLocks")
+    private final Map<String, KvSnapshotLease> kvSnapshotLeaseMap;
+
+    private final ReadWriteLock refCountLock = new ReentrantReadWriteLock();
+
+    /**
+     * KvSnapshotLeaseForBucket to the ref count, which means this table bucket + snapshotId has
+     * been leased by how many lease id.
+     */
+    private final Map<KvSnapshotLeaseForBucket, AtomicInteger> refCount =
+            MapUtils.newConcurrentHashMap();
+
+    /** For metrics. */
+    private final AtomicInteger leasedBucketCount = new AtomicInteger(0);
+
+    public KvSnapshotLeaseManager(
+            Configuration conf,
+            KvSnapshotLeaseMetadataManager metadataManager,
+            CoordinatorContext coordinatorContext,
+            Clock clock,
+            CoordinatorMetricGroup coordinatorMetricGroup) {
+        this(
+                conf,
+                metadataManager,
+                coordinatorContext,
+                Executors.newScheduledThreadPool(
+                        1, new ExecutorThreadFactory("kv-snapshot-lease-cleaner")),
+                clock,
+                coordinatorMetricGroup);
+    }
+
+    @VisibleForTesting
+    public KvSnapshotLeaseManager(
+            Configuration conf,
+            KvSnapshotLeaseMetadataManager metadataManager,
+            CoordinatorContext coordinatorContext,
+            ScheduledExecutorService scheduledExecutor,
+            Clock clock,
+            CoordinatorMetricGroup coordinatorMetricGroup) {
+        this.metadataManager = metadataManager;
+        this.conf = conf;
+        this.scheduledExecutor = scheduledExecutor;
+        this.coordinatorContext = coordinatorContext;
+        this.clock = clock;
+        this.kvSnapshotLeaseMap = MapUtils.newConcurrentHashMap();
+
+        registerMetrics(coordinatorMetricGroup);
+    }
+
+    public void start() {
+        LOG.info("kv snapshot lease manager has been started.");
+        scheduledExecutor.scheduleWithFixedDelay(
+                this::expireLeases,
+                0L,
+                conf.get(ConfigOptions.KV_SNAPSHOT_LEASE_EXPIRATION_CHECK_INTERVAL).toMillis(),
+                TimeUnit.MILLISECONDS);
+    }
+
+    public void initialize() throws Exception {
+        for (String leaseId : metadataManager.getLeasesList()) {
+            Optional<KvSnapshotLease> kvSnapshotLeaseOpt = metadataManager.getLease(leaseId);
+            if (kvSnapshotLeaseOpt.isPresent()) {
+                KvSnapshotLease kvSnapshotLease = kvSnapshotLeaseOpt.get();
+                this.leaseLocks.put(leaseId, new ReentrantReadWriteLock());
+                this.kvSnapshotLeaseMap.put(leaseId, kvSnapshotLease);
+
+                initializeRefCount(kvSnapshotLease);
+
+                leasedBucketCount.addAndGet(kvSnapshotLease.getLeasedSnapshotCount());
+            }
+        }
+    }
+
+    public boolean snapshotLeaseNotExist(KvSnapshotLeaseForBucket kvSnapshotLeaseForBucket) {
+        return inReadLock(
+                refCountLock,
+                () -> {
+                    AtomicInteger count = refCount.get(kvSnapshotLeaseForBucket);
+                    return count == null || count.get() <= 0;
+                });
+    }
+
+    /**
+     * Acquire kv snapshot lease.
+     *
+     * @param leaseId the lease id
+     * @param leaseDuration the lease duration
+     * @param tableIdToLeaseBucket the table id to lease bucket
+     * @return the map of unavailable snapshots that failed to be leased
+     */
+    public Map<TableBucket, Long> acquireLease(
+            String leaseId,
+            long leaseDuration,
+            Map<Long, List<KvSnapshotLeaseForBucket>> tableIdToLeaseBucket)
+            throws Exception {
+        ReadWriteLock lock = leaseLocks.computeIfAbsent(leaseId, k -> new ReentrantReadWriteLock());
+        return inWriteLock(
+                lock,
+                () -> {
+                    // To record the unavailable snapshots such as the kv snapshotId to lease not
+                    // exists.
+                    Map<TableBucket, Long> unavailableSnapshots = new HashMap<>();
+
+                    boolean update = kvSnapshotLeaseMap.containsKey(leaseId);
+                    // set the expiration time as: current time + leaseDuration
+                    long newExpirationTime = clock.milliseconds() + leaseDuration;
+                    KvSnapshotLease kvSnapshotLease =
+                            kvSnapshotLeaseMap.compute(
+                                    leaseId,
+                                    (key, existingLease) -> {
+                                        if (existingLease == null) {
+                                            LOG.info(
+                                                    "kv snapshot lease '{}' has been acquired. The lease expiration "
+                                                            + "time is {}",
+                                                    leaseId,
+                                                    newExpirationTime);
+                                            return new KvSnapshotLease(newExpirationTime);
+                                        } else {
+                                            existingLease.setExpirationTime(newExpirationTime);
+                                            return existingLease;
+                                        }
+                                    });
+
+                    for (Map.Entry<Long, List<KvSnapshotLeaseForBucket>> entry :
+                            tableIdToLeaseBucket.entrySet()) {
+                        Long tableId = entry.getKey();
+                        TableInfo tableInfo = coordinatorContext.getTableInfoById(tableId);
+                        int numBuckets = tableInfo.getNumBuckets();
+                        List<KvSnapshotLeaseForBucket> buckets = entry.getValue();
+                        for (KvSnapshotLeaseForBucket bucket : buckets) {
+
+                            TableBucket tableBucket = bucket.getTableBucket();
+                            long kvSnapshotId = bucket.getKvSnapshotId();
+                            try {
+                                boolean snapshotExists =
+                                        metadataManager.isSnapshotExists(tableBucket, kvSnapshotId);

Review Comment:
   **This is a VERY HEAVY operation, if there is 100K bucket, retain 10 snapshots, this will involve 1 million ZK IO operations! AND IN THE LOCK!**
   
   This will soon become a bottleneck of the system and the Flink job. 
   
   I think a better solution is to check the availability (and also pin snapshots) via `CompletedSnapshotStoreManager`. But I think this will involve a lot of code refactoring. I remembered we have discussed this, we have increased the retained snapshot number to `2` (this is the reason we increased it), so it's rarely to happen there is unavailable snapshots when we leasing it. And we can implement the unavailabe check in the future task. 
   
   So could you remove the zk snapshot check here, and create an issue for this, and add a TODO comment about the missing check with the issue id.



##########
fluss-server/src/main/java/org/apache/fluss/server/zk/data/lease/KvSnapshotLeaseMetadataManager.java:
##########
@@ -0,0 +1,226 @@
+/*
+ * 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.fluss.server.zk.data.lease;
+
+import org.apache.fluss.fs.FSDataInputStream;
+import org.apache.fluss.fs.FSDataOutputStream;
+import org.apache.fluss.fs.FileSystem;
+import org.apache.fluss.fs.FsPath;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.server.zk.ZooKeeperClient;
+import org.apache.fluss.server.zk.data.BucketSnapshot;
+import org.apache.fluss.utils.FlussPaths;
+import org.apache.fluss.utils.IOUtils;
+import org.apache.fluss.utils.types.Tuple2;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.ByteArrayOutputStream;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/**
+ * The manager to handle {@link KvSnapshotLease} to register/update/delete metadata from zk and
+ * remote fs.
+ */
+public class KvSnapshotLeaseMetadataManager {
+    private static final Logger LOG = LoggerFactory.getLogger(KvSnapshotLeaseMetadataManager.class);
+
+    private final ZooKeeperClient zkClient;
+    private final String remoteDataDir;
+
+    public KvSnapshotLeaseMetadataManager(ZooKeeperClient zkClient, String remoteDataDir) {
+        this.zkClient = zkClient;
+        this.remoteDataDir = remoteDataDir;
+    }
+
+    public List<String> getLeasesList() throws Exception {
+        return zkClient.getKvSnapshotLeasesList();
+    }
+
+    /**
+     * Register a new kv snapshot lease to zk and remote fs.
+     *
+     * @param leaseId the lease id.
+     * @param lease the kv snapshot lease.
+     */
+    public void registerLease(String leaseId, KvSnapshotLease lease) throws Exception {
+        Map<Long, FsPath> tableIdToRemoteMetadataFsPath = generateMetadataFile(leaseId, lease);
+
+        // generate remote fsPath of metadata.
+        KvSnapshotLeaseMetadata leaseMetadata =
+                new KvSnapshotLeaseMetadata(
+                        lease.getExpirationTime(), tableIdToRemoteMetadataFsPath);
+
+        // register kv snapshot metadata to zk.
+        try {
+            zkClient.registerKvSnapshotLeaseMetadata(leaseId, leaseMetadata);
+        } catch (Exception e) {
+            LOG.warn("Failed to register kv snapshot lease metadata to zk.", e);
+            leaseMetadata.discard();

Review Comment:
   This looks very dangerous, will this remove previous success metadata files if there is exception happen this time? Could you learn from `ProducerOffsetsStore.tryStoreOffsets` to cleanup only the `createdFiles`?



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/KvSnapshotLeaseManager.java:
##########
@@ -0,0 +1,459 @@
+/*
+ * 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.fluss.server.coordinator;
+
+import org.apache.fluss.annotation.VisibleForTesting;
+import org.apache.fluss.config.ConfigOptions;
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.metadata.KvSnapshotLeaseForBucket;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.metrics.MetricNames;
+import org.apache.fluss.server.metrics.group.CoordinatorMetricGroup;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLease;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLeaseMetadataManager;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotTableLease;
+import org.apache.fluss.utils.MapUtils;
+import org.apache.fluss.utils.clock.Clock;
+import org.apache.fluss.utils.concurrent.ExecutorThreadFactory;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.stream.Collectors;
+
+import static org.apache.fluss.utils.concurrent.LockUtils.inReadLock;
+import static org.apache.fluss.utils.concurrent.LockUtils.inWriteLock;
+
+/** A manager to manage kv snapshot lease acquire, renew, release and drop. */
+@ThreadSafe
+public class KvSnapshotLeaseManager {
+    private static final Logger LOG = LoggerFactory.getLogger(KvSnapshotLeaseManager.class);
+
+    private final KvSnapshotLeaseMetadataManager metadataManager;
+    private final CoordinatorContext coordinatorContext;
+    private final Clock clock;
+    private final ScheduledExecutorService scheduledExecutor;
+    private final Configuration conf;
+
+    private final Map<String, ReadWriteLock> leaseLocks = MapUtils.newConcurrentHashMap();
+    /** lease id to kv snapshot lease. */
+    @GuardedBy("leaseLocks")
+    private final Map<String, KvSnapshotLease> kvSnapshotLeaseMap;
+
+    private final ReadWriteLock refCountLock = new ReentrantReadWriteLock();
+
+    /**
+     * KvSnapshotLeaseForBucket to the ref count, which means this table bucket + snapshotId has
+     * been leased by how many lease id.
+     */
+    private final Map<KvSnapshotLeaseForBucket, AtomicInteger> refCount =
+            MapUtils.newConcurrentHashMap();
+
+    /** For metrics. */
+    private final AtomicInteger leasedBucketCount = new AtomicInteger(0);
+
+    public KvSnapshotLeaseManager(
+            Configuration conf,
+            KvSnapshotLeaseMetadataManager metadataManager,
+            CoordinatorContext coordinatorContext,
+            Clock clock,
+            CoordinatorMetricGroup coordinatorMetricGroup) {
+        this(
+                conf,
+                metadataManager,
+                coordinatorContext,
+                Executors.newScheduledThreadPool(
+                        1, new ExecutorThreadFactory("kv-snapshot-lease-cleaner")),
+                clock,
+                coordinatorMetricGroup);
+    }
+
+    @VisibleForTesting
+    public KvSnapshotLeaseManager(
+            Configuration conf,
+            KvSnapshotLeaseMetadataManager metadataManager,
+            CoordinatorContext coordinatorContext,
+            ScheduledExecutorService scheduledExecutor,
+            Clock clock,
+            CoordinatorMetricGroup coordinatorMetricGroup) {
+        this.metadataManager = metadataManager;
+        this.conf = conf;
+        this.scheduledExecutor = scheduledExecutor;
+        this.coordinatorContext = coordinatorContext;
+        this.clock = clock;
+        this.kvSnapshotLeaseMap = MapUtils.newConcurrentHashMap();
+
+        registerMetrics(coordinatorMetricGroup);
+    }
+
+    public void start() {
+        LOG.info("kv snapshot lease manager has been started.");
+        scheduledExecutor.scheduleWithFixedDelay(
+                this::expireLeases,
+                0L,
+                conf.get(ConfigOptions.KV_SNAPSHOT_LEASE_EXPIRATION_CHECK_INTERVAL).toMillis(),
+                TimeUnit.MILLISECONDS);
+    }
+
+    public void initialize() throws Exception {

Review Comment:
   move `initialize()` into  `start()`, and schedule the cleanup task after the `initialize()`. It's strange we have 2 start up methods. Besides



##########
fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/source/enumerator/FlinkSourceEnumerator.java:
##########
@@ -531,22 +537,88 @@ private List<SourceSplitBase> initPrimaryKeyTablePartitionSplits(
         List<SourceSplitBase> splits = new ArrayList<>();
         for (Partition partition : newPartitions) {
             String partitionName = partition.getPartitionName();
-            // get the table snapshot info
-            final KvSnapshots kvSnapshots;
-            try {
-                kvSnapshots = flussAdmin.getLatestKvSnapshots(tablePath, partitionName).get();
-            } catch (Exception e) {
-                throw new FlinkRuntimeException(
-                        String.format(
-                                "Failed to get table snapshot for table %s and partition %s",
-                                tablePath, partitionName),
-                        ExceptionUtils.stripCompletionException(e));
-            }
-            splits.addAll(getSnapshotAndLogSplits(kvSnapshots, partitionName));
+            splits.addAll(
+                    getSnapshotAndLogSplits(
+                            getLatestKvSnapshotsAndRegister(partitionName), partitionName));
         }
         return splits;
     }
 
+    private KvSnapshots getLatestKvSnapshotsAndRegister(@Nullable String partitionName) {
+        long tableId;
+        Long partitionId;
+        Map<Integer, Long> snapshotIds = new HashMap<>();
+        Map<Integer, Long> logOffsets = new HashMap<>();
+
+        // retry to get the latest kv snapshots and acquire kvSnapshot lease.
+        try {
+            KvSnapshots kvSnapshots = getLatestKvSnapshots(partitionName);
+            Set<TableBucket> remainingTableBuckets = new HashSet<>(kvSnapshots.getTableBuckets());
+
+            tableId = kvSnapshots.getTableId();
+            partitionId = kvSnapshots.getPartitionId();
+
+            Set<TableBucket> ignoreBuckets = new HashSet<>();
+            Map<TableBucket, Long> bucketsToLease = new HashMap<>();
+            for (TableBucket tb : remainingTableBuckets) {
+                int bucket = tb.getBucket();
+                OptionalLong snapshotIdOpt = kvSnapshots.getSnapshotId(bucket);
+                OptionalLong logOffsetOpt = kvSnapshots.getLogOffset(bucket);
+                if (snapshotIdOpt.isPresent() && !ignoreTableBucket(tb)) {
+                    bucketsToLease.put(tb, snapshotIdOpt.getAsLong());
+                } else {
+                    ignoreBuckets.add(tb);
+                }
+
+                snapshotIds.put(
+                        bucket, snapshotIdOpt.isPresent() ? snapshotIdOpt.getAsLong() : null);
+                logOffsets.put(bucket, logOffsetOpt.isPresent() ? logOffsetOpt.getAsLong() : null);
+            }
+
+            if (!ignoreBuckets.isEmpty()) {
+                remainingTableBuckets.removeAll(ignoreBuckets);
+            }
+
+            if (!bucketsToLease.isEmpty()) {
+                String kvSnapshotLeaseId = leaseContext.getKvSnapshotLeaseId();
+                LOG.info(
+                        "Try to acquire kv snapshot lease {} for table {}",
+                        kvSnapshotLeaseId,
+                        tablePath);
+                Long kvSnapshotLeaseDurationMs = leaseContext.getKvSnapshotLeaseDurationMs();
+                checkNotNull(kvSnapshotLeaseDurationMs, "kv snapshot lease duration is null.");
+                remainingTableBuckets =

Review Comment:
   Please use a separate variable `unavailableSnapshots` for the return value of `acquireKvSnapshotLease`. Overwrite the existing `remainingTableBuckets` is very confusing and no sense. 



##########
fluss-server/src/main/java/org/apache/fluss/server/zk/data/lease/KvSnapshotTableLease.java:
##########
@@ -0,0 +1,188 @@
+/*
+ * 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.fluss.server.zk.data.lease;
+
+import org.apache.fluss.utils.MapUtils;
+
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.NotThreadSafe;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Objects;
+
+/** The lease of kv snapshot for a table. */
+@NotThreadSafe
+public class KvSnapshotTableLease {
+    private final long tableId;
+    private final @Nullable Long[] bucketSnapshots;
+    private final Map<Long, Long[]> partitionSnapshots;
+
+    public KvSnapshotTableLease(long tableId) {
+        this(tableId, null, MapUtils.newConcurrentHashMap());

Review Comment:
   Mark `partitionSnapshots` as `ConcurrnetHashMap`, if it needs to be thread-safe. I see many places assigns different hash maps to the same variable. 



##########
fluss-common/src/main/java/org/apache/fluss/metadata/KvSnapshotLeaseForBucket.java:
##########
@@ -0,0 +1,66 @@
+/*
+ * 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.fluss.metadata;
+
+import java.util.Objects;
+
+/** An entity for kv snapshot lease for bucket. */
+public class KvSnapshotLeaseForBucket {

Review Comment:
   rename the class to `TableBucketSnapshot`, so that it can be reused not only for lease.



##########
fluss-server/src/test/java/org/apache/fluss/server/coordinator/KvSnapshotLeaseManagerTest.java:
##########
@@ -0,0 +1,470 @@
+/*
+ * 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.fluss.server.coordinator;
+
+import org.apache.fluss.config.ConfigOptions;
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.metadata.KvSnapshotLeaseForBucket;
+import org.apache.fluss.metadata.PhysicalTablePath;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.server.metrics.group.TestingMetricGroups;
+import org.apache.fluss.server.zk.NOPErrorHandler;
+import org.apache.fluss.server.zk.ZooKeeperClient;
+import org.apache.fluss.server.zk.ZooKeeperExtension;
+import org.apache.fluss.server.zk.data.BucketSnapshot;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLease;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLeaseMetadataManager;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotTableLease;
+import org.apache.fluss.testutils.common.AllCallbackWrapper;
+import org.apache.fluss.testutils.common.ManuallyTriggeredScheduledExecutorService;
+import org.apache.fluss.utils.clock.ManualClock;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.junit.jupiter.api.io.TempDir;
+
+import java.nio.file.Path;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.fluss.record.TestData.DATA1_TABLE_ID_PK;
+import static org.apache.fluss.record.TestData.DATA1_TABLE_INFO_PK;
+import static org.apache.fluss.record.TestData.DATA1_TABLE_PATH_PK;
+import static org.apache.fluss.record.TestData.PARTITION_TABLE_ID;
+import static org.apache.fluss.record.TestData.PARTITION_TABLE_INFO;
+import static org.apache.fluss.record.TestData.PARTITION_TABLE_PATH;
+import static org.apache.fluss.server.coordinator.CoordinatorTestUtils.createServers;
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Test for {@link KvSnapshotLeaseManager}. */
+public class KvSnapshotLeaseManagerTest {
+
+    @RegisterExtension
+    public static final AllCallbackWrapper<ZooKeeperExtension> ZOO_KEEPER_EXTENSION_WRAPPER =
+            new AllCallbackWrapper<>(new ZooKeeperExtension());
+
+    private static final long PARTITION_ID_1 = 19001L;
+    private static final PhysicalTablePath PARTITION_TABLE_PATH_1 =
+            PhysicalTablePath.of(PARTITION_TABLE_PATH, "2024");
+
+    private static final long PARTITION_ID_2 = 19002L;
+    private static final PhysicalTablePath PARTITION_TABLE_PATH_2 =
+            PhysicalTablePath.of(PARTITION_TABLE_PATH, "2025");
+
+    private static final int NUM_BUCKETS = DATA1_TABLE_INFO_PK.getNumBuckets();
+    private static final TableBucket t0b0 = new TableBucket(DATA1_TABLE_ID_PK, 0);
+    private static final TableBucket t0b1 = new TableBucket(DATA1_TABLE_ID_PK, 1);
+    private static final TableBucket t1p0b0 =
+            new TableBucket(PARTITION_TABLE_ID, PARTITION_ID_1, 0);
+    private static final TableBucket t1p0b1 =
+            new TableBucket(PARTITION_TABLE_ID, PARTITION_ID_1, 1);
+    private static final TableBucket t1p1b0 =
+            new TableBucket(PARTITION_TABLE_ID, PARTITION_ID_2, 0);
+
+    protected static ZooKeeperClient zookeeperClient;
+
+    private CoordinatorContext coordinatorContext;
+    private ManualClock manualClock;
+    private ManuallyTriggeredScheduledExecutorService clearLeaseScheduler;
+    private KvSnapshotLeaseManager kvSnapshotLeaseManager;
+    private KvSnapshotLeaseMetadataManager metadataManager;
+
+    private @TempDir Path tempDir;
+
+    @BeforeAll
+    static void beforeAll() {
+        zookeeperClient =
+                ZOO_KEEPER_EXTENSION_WRAPPER
+                        .getCustomExtension()
+                        .getZooKeeperClient(NOPErrorHandler.INSTANCE);
+    }
+
+    @BeforeEach
+    void beforeEach() throws Exception {
+        initCoordinatorContext();
+        Configuration conf = new Configuration();
+        // set a huge expiration check interval to avoid expiration check.
+        conf.set(ConfigOptions.KV_SNAPSHOT_LEASE_EXPIRATION_CHECK_INTERVAL, Duration.ofDays(7));
+        manualClock = new ManualClock(System.currentTimeMillis());
+        clearLeaseScheduler = new ManuallyTriggeredScheduledExecutorService();
+        metadataManager = new KvSnapshotLeaseMetadataManager(zookeeperClient, tempDir.toString());
+        kvSnapshotLeaseManager =
+                new KvSnapshotLeaseManager(
+                        conf,
+                        metadataManager,
+                        coordinatorContext,
+                        clearLeaseScheduler,
+                        manualClock,
+                        TestingMetricGroups.COORDINATOR_METRICS);
+        kvSnapshotLeaseManager.start();
+        initialZookeeper();
+    }
+
+    @AfterEach
+    void afterEach() {
+        ZOO_KEEPER_EXTENSION_WRAPPER.getCustomExtension().cleanupRoot();
+    }
+
+    private static void initialZookeeper() throws Exception {
+        List<TableBucket> tableBuckets = Arrays.asList(t0b0, t0b1, t1p0b0, t1p0b1, t1p1b0);
+        for (TableBucket tb : tableBuckets) {
+            zookeeperClient.registerTableBucketSnapshot(
+                    tb, new BucketSnapshot(0L, 0L, "test-path"));
+        }
+    }
+
+    @Test
+    void testInitialize() throws Exception {
+        assertThat(
+                        snapshotLeaseNotExists(
+                                Arrays.asList(
+                                        new KvSnapshotLeaseForBucket(t0b0, 0L),
+                                        new KvSnapshotLeaseForBucket(t0b1, 0L),
+                                        new KvSnapshotLeaseForBucket(t1p0b0, 0L),
+                                        new KvSnapshotLeaseForBucket(t1p0b1, 0L),
+                                        new KvSnapshotLeaseForBucket(t1p1b0, 0L))))
+                .isTrue();
+        assertThat(kvSnapshotLeaseManager.getLeasedBucketCount()).isEqualTo(0);
+
+        // test initialize from zookeeper when coordinator is started.
+        KvSnapshotLease kvSnapshotLease = new KvSnapshotLease(1000L);
+        acquire(kvSnapshotLease, new KvSnapshotLeaseForBucket(t0b0, 0L));
+        acquire(kvSnapshotLease, new KvSnapshotLeaseForBucket(t0b1, 0L));
+        acquire(kvSnapshotLease, new KvSnapshotLeaseForBucket(t1p0b0, 0L));
+        acquire(kvSnapshotLease, new KvSnapshotLeaseForBucket(t1p0b1, 0L));
+        acquire(kvSnapshotLease, new KvSnapshotLeaseForBucket(t1p1b0, 0L));
+        metadataManager.registerLease("lease1", kvSnapshotLease);
+
+        kvSnapshotLeaseManager.initialize();
+
+        assertThat(
+                        snapshotLeaseExists(
+                                Arrays.asList(
+                                        new KvSnapshotLeaseForBucket(t0b0, 0L),
+                                        new KvSnapshotLeaseForBucket(t0b1, 0L),
+                                        new KvSnapshotLeaseForBucket(t1p0b0, 0L),
+                                        new KvSnapshotLeaseForBucket(t1p0b1, 0L),
+                                        new KvSnapshotLeaseForBucket(t1p1b0, 0L))))
+                .isTrue();
+        assertThat(kvSnapshotLeaseManager.getLeasedBucketCount()).isEqualTo(5);
+
+        // check detail content.
+        Map<Long, KvSnapshotTableLease> tableIdToTableLease = new HashMap<>();
+        tableIdToTableLease.put(
+                DATA1_TABLE_ID_PK,
+                new KvSnapshotTableLease(DATA1_TABLE_ID_PK, new Long[] {0L, 0L, -1L}));
+        KvSnapshotTableLease leaseForPartitionTable = new KvSnapshotTableLease(PARTITION_TABLE_ID);
+        leaseForPartitionTable.addPartitionSnapshots(PARTITION_ID_1, new Long[] {0L, 0L, -1L});
+        leaseForPartitionTable.addPartitionSnapshots(PARTITION_ID_2, new Long[] {0L, -1L, -1L});
+        tableIdToTableLease.put(PARTITION_TABLE_ID, leaseForPartitionTable);
+        KvSnapshotLease expectedLease = new KvSnapshotLease(1000L, tableIdToTableLease);
+        assertThat(kvSnapshotLeaseManager.getKvSnapshotLease("lease1")).isEqualTo(expectedLease);
+        assertThat(metadataManager.getLease("lease1")).hasValue(expectedLease);
+    }
+
+    @Test
+    void testAcquireAndRelease() throws Exception {
+        Map<Long, List<KvSnapshotLeaseForBucket>> tableIdToRegisterBucket = initRegisterBuckets();
+        acquire("lease1", tableIdToRegisterBucket);
+
+        // first register snapshot to zk.
+        zookeeperClient.registerTableBucketSnapshot(
+                t1p0b0, new BucketSnapshot(1L, 10L, "test-path"));
+        zookeeperClient.registerTableBucketSnapshot(
+                t1p0b1, new BucketSnapshot(1L, 10L, "test-path"));
+
+        tableIdToRegisterBucket = new HashMap<>();
+        tableIdToRegisterBucket.put(
+                PARTITION_TABLE_ID,
+                Arrays.asList(
+                        new KvSnapshotLeaseForBucket(t1p0b0, 1L),
+                        new KvSnapshotLeaseForBucket(t1p0b1, 1L)));
+        acquire("lease2", tableIdToRegisterBucket);
+
+        assertThat(
+                        snapshotLeaseExists(
+                                Arrays.asList(
+                                        new KvSnapshotLeaseForBucket(t0b0, 0L),
+                                        new KvSnapshotLeaseForBucket(t0b1, 0L),
+                                        new KvSnapshotLeaseForBucket(t1p0b0, 0),
+                                        new KvSnapshotLeaseForBucket(t1p0b1, 0L),
+                                        new KvSnapshotLeaseForBucket(t1p1b0, 0L),
+                                        new KvSnapshotLeaseForBucket(t1p0b0, 1L),
+                                        new KvSnapshotLeaseForBucket(t1p0b1, 1L))))
+                .isTrue();
+        assertThat(kvSnapshotLeaseManager.getLeasedBucketCount()).isEqualTo(7);
+        assertThat(kvSnapshotLeaseManager.getLeaseCount()).isEqualTo(2);
+
+        // update lease register.
+        tableIdToRegisterBucket = new HashMap<>();
+        zookeeperClient.registerTableBucketSnapshot(t0b0, new BucketSnapshot(1L, 10L, "test-path"));
+        tableIdToRegisterBucket.put(
+                DATA1_TABLE_ID_PK,
+                Collections.singletonList(new KvSnapshotLeaseForBucket(t0b0, 1L)));
+        acquire("lease1", tableIdToRegisterBucket);
+        assertThat(kvSnapshotLeaseManager.getLeasedBucketCount()).isEqualTo(7);
+
+        // new insert.
+        tableIdToRegisterBucket = new HashMap<>();
+        TableBucket newTableBucket = new TableBucket(DATA1_TABLE_ID_PK, 2);
+
+        zookeeperClient.registerTableBucketSnapshot(
+                newTableBucket, new BucketSnapshot(1L, 10L, "test-path"));
+        tableIdToRegisterBucket.put(
+                DATA1_TABLE_ID_PK,
+                Collections.singletonList(new KvSnapshotLeaseForBucket(newTableBucket, 1L)));
+        acquire("lease1", tableIdToRegisterBucket);
+        assertThat(kvSnapshotLeaseManager.getLeasedBucketCount()).isEqualTo(8);
+
+        // release
+        Map<Long, List<TableBucket>> tableIdToUnregisterBucket = new HashMap<>();
+        tableIdToUnregisterBucket.put(DATA1_TABLE_ID_PK, Collections.singletonList(newTableBucket));
+        release("lease1", tableIdToUnregisterBucket);
+        assertThat(kvSnapshotLeaseManager.getLeasedBucketCount()).isEqualTo(7);
+
+        // release a non-exist bucket.
+        tableIdToUnregisterBucket = new HashMap<>();
+        tableIdToUnregisterBucket.put(
+                DATA1_TABLE_ID_PK,
+                Collections.singletonList(new TableBucket(DATA1_TABLE_ID_PK, PARTITION_ID_1, 2)));
+        release("lease1", tableIdToUnregisterBucket);
+        assertThat(kvSnapshotLeaseManager.getLeasedBucketCount()).isEqualTo(7);
+
+        // check detail content for lease1.
+        Map<Long, KvSnapshotTableLease> tableIdToTableLease = new HashMap<>();
+        tableIdToTableLease.put(
+                DATA1_TABLE_ID_PK,
+                new KvSnapshotTableLease(DATA1_TABLE_ID_PK, new Long[] {1L, 0L, -1L}));
+        KvSnapshotTableLease leaseForPartitionTable = new KvSnapshotTableLease(PARTITION_TABLE_ID);
+        leaseForPartitionTable.addPartitionSnapshots(PARTITION_ID_1, new Long[] {0L, 0L, -1L});
+        leaseForPartitionTable.addPartitionSnapshots(PARTITION_ID_2, new Long[] {0L, -1L, -1L});
+        tableIdToTableLease.put(PARTITION_TABLE_ID, leaseForPartitionTable);
+        KvSnapshotLease expectedLease =
+                new KvSnapshotLease(manualClock.milliseconds() + 1000L, tableIdToTableLease);
+        assertThat(kvSnapshotLeaseManager.getKvSnapshotLease("lease1")).isEqualTo(expectedLease);
+        assertThat(metadataManager.getLease("lease1")).hasValue(expectedLease);
+
+        // check detail content for lease2.
+        tableIdToTableLease = new HashMap<>();
+        leaseForPartitionTable = new KvSnapshotTableLease(PARTITION_TABLE_ID);
+        leaseForPartitionTable.addPartitionSnapshots(PARTITION_ID_1, new Long[] {1L, 1L, -1L});
+        tableIdToTableLease.put(PARTITION_TABLE_ID, leaseForPartitionTable);
+        KvSnapshotLease expectedLease2 =
+                new KvSnapshotLease(manualClock.milliseconds() + 1000L, tableIdToTableLease);
+        assertThat(kvSnapshotLeaseManager.getKvSnapshotLease("lease2")).isEqualTo(expectedLease2);
+        assertThat(metadataManager.getLease("lease2")).hasValue(expectedLease2);
+    }
+
+    @Test
+    void testUnregisterAll() throws Exception {
+        Map<Long, List<KvSnapshotLeaseForBucket>> tableIdToRegisterBucket = initRegisterBuckets();
+        acquire("lease1", tableIdToRegisterBucket);
+        assertThat(kvSnapshotLeaseManager.getLeasedBucketCount()).isEqualTo(5);
+        assertThat(kvSnapshotLeaseManager.getLeaseCount()).isEqualTo(1);
+        assertThat(zookeeperClient.getKvSnapshotLeaseMetadata("lease1")).isPresent();
+
+        Map<Long, List<TableBucket>> tableIdToUnregisterBucket = new HashMap<>();
+        tableIdToUnregisterBucket.put(DATA1_TABLE_ID_PK, Arrays.asList(t0b0, t0b1));
+        tableIdToUnregisterBucket.put(PARTITION_TABLE_ID, Arrays.asList(t1p0b0, t1p0b1, t1p1b0));
+
+        // unregister all will clear this lease.
+        release("lease1", tableIdToUnregisterBucket);
+        assertThat(kvSnapshotLeaseManager.getLeasedBucketCount()).isEqualTo(0);
+        assertThat(kvSnapshotLeaseManager.getLeaseCount()).isEqualTo(0);
+        assertThat(zookeeperClient.getKvSnapshotLeaseMetadata("lease1")).isNotPresent();
+    }
+
+    @Test
+    void testClear() throws Exception {
+        Map<Long, List<KvSnapshotLeaseForBucket>> tableIdToRegisterBucket = initRegisterBuckets();
+        acquire("lease1", tableIdToRegisterBucket);
+
+        // first register snapshot to zk.
+        zookeeperClient.registerTableBucketSnapshot(
+                t1p0b0, new BucketSnapshot(1L, 10L, "test-path"));
+        zookeeperClient.registerTableBucketSnapshot(
+                t1p0b1, new BucketSnapshot(1L, 10L, "test-path"));
+        tableIdToRegisterBucket = new HashMap<>();
+        tableIdToRegisterBucket.put(
+                PARTITION_TABLE_ID,
+                Arrays.asList(
+                        new KvSnapshotLeaseForBucket(t0b0, 0L), // same ref.
+                        new KvSnapshotLeaseForBucket(t1p0b0, 1L),
+                        new KvSnapshotLeaseForBucket(t1p0b1, 1L)));
+        acquire("lease2", tableIdToRegisterBucket);
+
+        assertThat(
+                        snapshotLeaseExists(
+                                Arrays.asList(
+                                        new KvSnapshotLeaseForBucket(t0b0, 0L),
+                                        new KvSnapshotLeaseForBucket(t0b1, 0L),
+                                        new KvSnapshotLeaseForBucket(t1p0b0, 0L),
+                                        new KvSnapshotLeaseForBucket(t1p0b1, 0L),
+                                        new KvSnapshotLeaseForBucket(t1p1b0, 0L),
+                                        new KvSnapshotLeaseForBucket(t1p0b0, 1L),
+                                        new KvSnapshotLeaseForBucket(t1p0b1, 1L))))
+                .isTrue();
+        assertThat(kvSnapshotLeaseManager.getRefCount(new KvSnapshotLeaseForBucket(t0b0, 0L)))
+                .isEqualTo(2);
+        assertThat(kvSnapshotLeaseManager.getLeasedBucketCount()).isEqualTo(8);
+        assertThat(kvSnapshotLeaseManager.getLeaseCount()).isEqualTo(2);
+
+        kvSnapshotLeaseManager.releaseAll("lease1");
+        assertThat(kvSnapshotLeaseManager.getRefCount(new KvSnapshotLeaseForBucket(t0b0, 0L)))
+                .isEqualTo(1);
+        assertThat(kvSnapshotLeaseManager.getLeasedBucketCount()).isEqualTo(3);
+        assertThat(kvSnapshotLeaseManager.getLeaseCount()).isEqualTo(1);
+        assertThat(zookeeperClient.getKvSnapshotLeaseMetadata("lease1")).isEmpty();
+
+        kvSnapshotLeaseManager.releaseAll("lease2");
+        assertThat(kvSnapshotLeaseManager.getRefCount(new KvSnapshotLeaseForBucket(t0b0, 0L)))
+                .isEqualTo(0);
+        assertThat(kvSnapshotLeaseManager.getLeasedBucketCount()).isEqualTo(0);
+        assertThat(kvSnapshotLeaseManager.getLeaseCount()).isEqualTo(0);
+        assertThat(zookeeperClient.getKvSnapshotLeaseMetadata("lease2")).isEmpty();
+
+        assertThat(kvSnapshotLeaseManager.releaseAll("non-exist")).isFalse();
+    }
+
+    @Test
+    void testExpireLeases() throws Exception {
+        // test lease expire by expire thread.
+        Map<Long, List<KvSnapshotLeaseForBucket>> tableIdToLeaseBucket = initRegisterBuckets();
+
+        // expire after 1000ms.
+        kvSnapshotLeaseManager.acquireLease("lease1", 1000L, tableIdToLeaseBucket);
+
+        tableIdToLeaseBucket = new HashMap<>();
+        zookeeperClient.registerTableBucketSnapshot(
+                t1p0b0, new BucketSnapshot(1L, 10L, "test-path"));
+        zookeeperClient.registerTableBucketSnapshot(
+                t1p0b1, new BucketSnapshot(1L, 10L, "test-path"));
+        tableIdToLeaseBucket.put(
+                PARTITION_TABLE_ID,
+                Arrays.asList(
+                        new KvSnapshotLeaseForBucket(t0b0, 0L), // same ref.
+                        new KvSnapshotLeaseForBucket(t1p0b0, 1L),
+                        new KvSnapshotLeaseForBucket(t1p0b1, 1L)));
+        // expire after 2000ms.
+        kvSnapshotLeaseManager.acquireLease("lease2", 2000L, tableIdToLeaseBucket);
+
+        clearLeaseScheduler.triggerPeriodicScheduledTasks();
+        // no lease expire.
+        assertThat(kvSnapshotLeaseManager.getLeasedBucketCount()).isEqualTo(8);
+        assertThat(kvSnapshotLeaseManager.getLeaseCount()).isEqualTo(2);
+        assertThat(zookeeperClient.getKvSnapshotLeaseMetadata("lease1")).isPresent();
+        assertThat(zookeeperClient.getKvSnapshotLeaseMetadata("lease2")).isPresent();
+
+        manualClock.advanceTime(1005L, TimeUnit.MILLISECONDS);
+        clearLeaseScheduler.triggerPeriodicScheduledTasks();
+        // lease1 expire.
+        assertThat(kvSnapshotLeaseManager.getLeasedBucketCount()).isEqualTo(3);
+        assertThat(kvSnapshotLeaseManager.getLeaseCount()).isEqualTo(1);
+        assertThat(zookeeperClient.getKvSnapshotLeaseMetadata("lease1")).isNotPresent();
+        assertThat(zookeeperClient.getKvSnapshotLeaseMetadata("lease2")).isPresent();
+
+        manualClock.advanceTime(1005L, TimeUnit.MILLISECONDS);
+        clearLeaseScheduler.triggerPeriodicScheduledTasks();
+        // lease2 expire.
+        assertThat(kvSnapshotLeaseManager.getLeasedBucketCount()).isEqualTo(0);
+        assertThat(kvSnapshotLeaseManager.getLeaseCount()).isEqualTo(0);
+        assertThat(zookeeperClient.getKvSnapshotLeaseMetadata("lease1")).isNotPresent();
+        assertThat(zookeeperClient.getKvSnapshotLeaseMetadata("lease2")).isNotPresent();
+    }
+
+    @Test
+    void registerWithNotExistSnapshotId() throws Exception {
+        Map<Long, List<KvSnapshotLeaseForBucket>> tableIdToRegisterBucket = new HashMap<>();
+        tableIdToRegisterBucket.put(
+                DATA1_TABLE_ID_PK,
+                Arrays.asList(
+                        new KvSnapshotLeaseForBucket(t0b0, 1000L),
+                        new KvSnapshotLeaseForBucket(t0b1, 1000L)));
+        assertThat(
+                        kvSnapshotLeaseManager
+                                .acquireLease("lease1", 1000L, tableIdToRegisterBucket)
+                                .keySet())
+                .contains(t0b0);

Review Comment:
   ```suggestion
                   .containsExactlyInAnyOrder(t0b0, t0b1);
   ```



##########
fluss-flink/fluss-flink-common/src/test/java/org/apache/fluss/flink/source/FlussSourceITCase.java:
##########
@@ -151,6 +156,8 @@ public void testRowDataPKTableSource() throws Exception {
                         .setTable(pkTableName)
                         .setStartingOffsets(OffsetsInitializer.earliest())
                         .setScanPartitionDiscoveryIntervalMs(1000L)
+                        .setKvSnapshotLeaseId("test-lease-sdafa3")
+                        .setKvSnapshotLeaseDurationMs(Duration.ofDays(1).toMillis())

Review Comment:
   remove this. all existing DataStream API jobs should work without modification, otherwise, it's an in-compatible.



##########
fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/source/enumerator/FlinkSourceEnumerator.java:
##########
@@ -531,22 +537,88 @@ private List<SourceSplitBase> initPrimaryKeyTablePartitionSplits(
         List<SourceSplitBase> splits = new ArrayList<>();
         for (Partition partition : newPartitions) {
             String partitionName = partition.getPartitionName();
-            // get the table snapshot info
-            final KvSnapshots kvSnapshots;
-            try {
-                kvSnapshots = flussAdmin.getLatestKvSnapshots(tablePath, partitionName).get();
-            } catch (Exception e) {
-                throw new FlinkRuntimeException(
-                        String.format(
-                                "Failed to get table snapshot for table %s and partition %s",
-                                tablePath, partitionName),
-                        ExceptionUtils.stripCompletionException(e));
-            }
-            splits.addAll(getSnapshotAndLogSplits(kvSnapshots, partitionName));
+            splits.addAll(
+                    getSnapshotAndLogSplits(
+                            getLatestKvSnapshotsAndRegister(partitionName), partitionName));
         }
         return splits;
     }
 
+    private KvSnapshots getLatestKvSnapshotsAndRegister(@Nullable String partitionName) {
+        long tableId;
+        Long partitionId;
+        Map<Integer, Long> snapshotIds = new HashMap<>();
+        Map<Integer, Long> logOffsets = new HashMap<>();
+
+        // retry to get the latest kv snapshots and acquire kvSnapshot lease.
+        try {
+            KvSnapshots kvSnapshots = getLatestKvSnapshots(partitionName);
+            Set<TableBucket> remainingTableBuckets = new HashSet<>(kvSnapshots.getTableBuckets());
+
+            tableId = kvSnapshots.getTableId();
+            partitionId = kvSnapshots.getPartitionId();
+
+            Set<TableBucket> ignoreBuckets = new HashSet<>();
+            Map<TableBucket, Long> bucketsToLease = new HashMap<>();
+            for (TableBucket tb : remainingTableBuckets) {
+                int bucket = tb.getBucket();
+                OptionalLong snapshotIdOpt = kvSnapshots.getSnapshotId(bucket);
+                OptionalLong logOffsetOpt = kvSnapshots.getLogOffset(bucket);
+                if (snapshotIdOpt.isPresent() && !ignoreTableBucket(tb)) {
+                    bucketsToLease.put(tb, snapshotIdOpt.getAsLong());
+                } else {
+                    ignoreBuckets.add(tb);
+                }
+
+                snapshotIds.put(
+                        bucket, snapshotIdOpt.isPresent() ? snapshotIdOpt.getAsLong() : null);
+                logOffsets.put(bucket, logOffsetOpt.isPresent() ? logOffsetOpt.getAsLong() : null);
+            }
+
+            if (!ignoreBuckets.isEmpty()) {
+                remainingTableBuckets.removeAll(ignoreBuckets);
+            }
+
+            if (!bucketsToLease.isEmpty()) {
+                String kvSnapshotLeaseId = leaseContext.getKvSnapshotLeaseId();

Review Comment:
   The `kvSnapshotLeaseId` can be `null` when a job is recovered from an older version, since the enumerator state did not include a lease ID previously. This currently triggers exceptions because the code assumes the lease ID is always non-null.
   
   A clean solution is to ensure that both `kvSnapshotLeaseId` and `kvSnapshotLeaseDurationMs` in `LeaseContext` are never null by providing sensible defaults. Specifically:
   
   - Introduce a static factory method `LeaseContext.default()` that generates a random UUID for the lease ID and sets the lease duration to **1 day**.
   - This aligns with the default behavior of the `SCAN_KV_SNAPSHOT_LEASE_ID` configuration option, which also uses a random UUID when unspecified.
   
   With this approach, during deserialization of legacy enumerator state (where `kvSnapshotLeaseId` is missing or null), we can safely use `LeaseContext.default()` to maintain consistent semantics across versions.



##########
website/docs/engine-flink/procedures.md:
##########
@@ -487,4 +487,38 @@ CALL sys.cancel_rebalance();
 
 -- Cancel a specific rebalance operation by ID
 CALL sys.cancel_rebalance('rebalance-12345');
+```
+
+## kv snapshot lease
+
+Fluss provides procedures to manage KV snapshot leases, allowing you to release leased kv snapshots.
+
+### release_all_kv_snapshot_lease
+
+Release all KV snapshots leased under a specified leaseId. This is typically used for handle the scenario of lease
+remnants. After a normal job completion, the registered lease is not released, requiring a manual trigger of the
+procedure for cleanup.

Review Comment:
   `After a normal job completion, the registered lease is not released` This sounds very terrible. It sounds by design, the lease will not be released, and requires a manual release. 
   
   I think this should be "After an abnormal job termination (e.g., crash or forced cancellation), the registered lease may not be released automatically and could require manual cleanup."
   



##########
fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/procedure/ProcedureManager.java:
##########
@@ -77,7 +77,9 @@ private enum ProcedureEnum {
         REMOVE_SERVER_TAG("sys.remove_server_tag", RemoveServerTagProcedure.class),
         REBALANCE("sys.rebalance", RebalanceProcedure.class),
         CANCEL_REBALANCE("sys.cancel_rebalance", CancelRebalanceProcedure.class),
-        LIST_REBALANCE_PROGRESS("sys.list_rebalance", ListRebalanceProcessProcedure.class);
+        LIST_REBALANCE_PROGRESS("sys.list_rebalance", ListRebalanceProcessProcedure.class),
+        RELEASE_ALL_KV_SNAPSHOT_LEASE(
+                "sys.release_all_kv_snapshot_lease", ReleaseAllKvSnapshotLeaseProcedure.class);

Review Comment:
   `release_all_kv_snapshot_lease` -> `drop_kv_snapshot_lease`



##########
fluss-server/src/main/java/org/apache/fluss/server/zk/data/lease/KvSnapshotLeaseMetadata.java:
##########
@@ -0,0 +1,94 @@
+/*
+ * 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.fluss.server.zk.data.lease;
+
+import org.apache.fluss.fs.FileSystem;
+import org.apache.fluss.fs.FsPath;
+
+import java.io.IOException;
+import java.util.Map;
+import java.util.Objects;
+
+import static org.apache.fluss.metrics.registry.MetricRegistry.LOG;
+
+/** The zkNode data of kv snapshot lease. */
+public class KvSnapshotLeaseMetadata {
+    private final long expirationTime;
+    private final Map<Long, FsPath> tableIdToRemoteMetadataFilePath;
+
+    public KvSnapshotLeaseMetadata(
+            long expirationTime, Map<Long, FsPath> tableIdToRemoteMetadataFilePath) {
+        this.expirationTime = expirationTime;
+        this.tableIdToRemoteMetadataFilePath = tableIdToRemoteMetadataFilePath;
+    }
+
+    public long getExpirationTime() {
+        return expirationTime;
+    }
+
+    public Map<Long, FsPath> getTableIdToRemoteMetadataFilePath() {
+        return tableIdToRemoteMetadataFilePath;
+    }
+
+    public void discard() {
+        // delete all remote metadata file.
+        tableIdToRemoteMetadataFilePath.values().forEach(this::delete);
+    }
+
+    private void delete(FsPath fsPath) {

Review Comment:
   `KvSnapshotLeaseMetadata` is a zk entity class (POJO class), we should move the clean logic out of the class to keep the entity clean. 



##########
fluss-server/src/main/java/org/apache/fluss/server/zk/data/lease/KvSnapshotLeaseMetadataManager.java:
##########
@@ -0,0 +1,226 @@
+/*
+ * 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.fluss.server.zk.data.lease;
+
+import org.apache.fluss.fs.FSDataInputStream;
+import org.apache.fluss.fs.FSDataOutputStream;
+import org.apache.fluss.fs.FileSystem;
+import org.apache.fluss.fs.FsPath;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.server.zk.ZooKeeperClient;
+import org.apache.fluss.server.zk.data.BucketSnapshot;
+import org.apache.fluss.utils.FlussPaths;
+import org.apache.fluss.utils.IOUtils;
+import org.apache.fluss.utils.types.Tuple2;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.ByteArrayOutputStream;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/**
+ * The manager to handle {@link KvSnapshotLease} to register/update/delete metadata from zk and
+ * remote fs.
+ */
+public class KvSnapshotLeaseMetadataManager {
+    private static final Logger LOG = LoggerFactory.getLogger(KvSnapshotLeaseMetadataManager.class);
+
+    private final ZooKeeperClient zkClient;
+    private final String remoteDataDir;
+
+    public KvSnapshotLeaseMetadataManager(ZooKeeperClient zkClient, String remoteDataDir) {
+        this.zkClient = zkClient;
+        this.remoteDataDir = remoteDataDir;
+    }
+
+    public List<String> getLeasesList() throws Exception {
+        return zkClient.getKvSnapshotLeasesList();
+    }
+
+    /**
+     * Register a new kv snapshot lease to zk and remote fs.
+     *
+     * @param leaseId the lease id.
+     * @param lease the kv snapshot lease.
+     */
+    public void registerLease(String leaseId, KvSnapshotLease lease) throws Exception {
+        Map<Long, FsPath> tableIdToRemoteMetadataFsPath = generateMetadataFile(leaseId, lease);
+
+        // generate remote fsPath of metadata.
+        KvSnapshotLeaseMetadata leaseMetadata =
+                new KvSnapshotLeaseMetadata(
+                        lease.getExpirationTime(), tableIdToRemoteMetadataFsPath);
+
+        // register kv snapshot metadata to zk.
+        try {
+            zkClient.registerKvSnapshotLeaseMetadata(leaseId, leaseMetadata);
+        } catch (Exception e) {
+            LOG.warn("Failed to register kv snapshot lease metadata to zk.", e);
+            leaseMetadata.discard();
+            throw e;
+        }
+    }
+
+    /**
+     * Update a kv snapshot lease to zk and remote fs.
+     *
+     * @param leaseId the lease id.
+     * @param kvSnapshotLease the kv snapshot lease.
+     */
+    public void updateLease(String leaseId, KvSnapshotLease kvSnapshotLease) throws Exception {
+        // TODO change this to incremental update to avoid create too many remote metadata files.
+
+        Optional<KvSnapshotLeaseMetadata> originalLeaseMetadata =
+                zkClient.getKvSnapshotLeaseMetadata(leaseId);
+
+        Map<Long, FsPath> tableIdToNewRemoteMetadataFsPath =
+                generateMetadataFile(leaseId, kvSnapshotLease);
+
+        // generate  new kv snapshot lease metadata.
+        KvSnapshotLeaseMetadata newLeaseMetadata =
+                new KvSnapshotLeaseMetadata(
+                        kvSnapshotLease.getExpirationTime(), tableIdToNewRemoteMetadataFsPath);
+        // register new snapshot metadata to zk.
+        try {
+            zkClient.updateKvSnapshotLeaseMetadata(leaseId, newLeaseMetadata);
+        } catch (Exception e) {
+            LOG.warn("Failed to update kv snapshot lease metadata to zk.", e);
+            newLeaseMetadata.discard();

Review Comment:
   ditto



##########
fluss-rpc/src/main/proto/FlussApi.proto:
##########
@@ -378,6 +378,29 @@ message GetKvSnapshotMetadataResponse {
   repeated PbRemotePathAndLocalFile snapshot_files = 2;
 }
 
+message AcquireKvSnapshotLeaseRequest {
+  required string lease_id = 1;
+  required int64 lease_duration = 2;
+  repeated PbKvSnapshotLeaseForTable table_lease_req = 3;
+}
+
+message AcquireKvSnapshotLeaseResponse {
+  repeated PbKvSnapshotLeaseForTable tables_lease_res = 3;
+}
+
+message ReleaseKvSnapshotLeaseRequest {
+  required string lease_id = 1;
+  repeated PbTable release_tables = 2;

Review Comment:
   We should add `optional bool release_all` to indicate it is a drop lease operation (or use the `DropKvSnapshotLeaseRequest` for dropping lease), rather than relying on empty `release_tables`. Usually, empty set means there is nothing to release, not release all...
   
   
   Besides, could you reuse the `PbTableBucket` structure to avoid introducing new type? And rename the field name to `buckets_to_release`.
   



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/KvSnapshotLeaseManager.java:
##########
@@ -0,0 +1,459 @@
+/*
+ * 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.fluss.server.coordinator;
+
+import org.apache.fluss.annotation.VisibleForTesting;
+import org.apache.fluss.config.ConfigOptions;
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.metadata.KvSnapshotLeaseForBucket;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.metrics.MetricNames;
+import org.apache.fluss.server.metrics.group.CoordinatorMetricGroup;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLease;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotLeaseMetadataManager;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotTableLease;
+import org.apache.fluss.utils.MapUtils;
+import org.apache.fluss.utils.clock.Clock;
+import org.apache.fluss.utils.concurrent.ExecutorThreadFactory;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.stream.Collectors;
+
+import static org.apache.fluss.utils.concurrent.LockUtils.inReadLock;
+import static org.apache.fluss.utils.concurrent.LockUtils.inWriteLock;
+
+/** A manager to manage kv snapshot lease acquire, renew, release and drop. */
+@ThreadSafe
+public class KvSnapshotLeaseManager {
+    private static final Logger LOG = LoggerFactory.getLogger(KvSnapshotLeaseManager.class);
+
+    private final KvSnapshotLeaseMetadataManager metadataManager;
+    private final CoordinatorContext coordinatorContext;
+    private final Clock clock;
+    private final ScheduledExecutorService scheduledExecutor;
+    private final Configuration conf;
+
+    private final Map<String, ReadWriteLock> leaseLocks = MapUtils.newConcurrentHashMap();
+    /** lease id to kv snapshot lease. */
+    @GuardedBy("leaseLocks")
+    private final Map<String, KvSnapshotLease> kvSnapshotLeaseMap;
+
+    private final ReadWriteLock refCountLock = new ReentrantReadWriteLock();
+
+    /**
+     * KvSnapshotLeaseForBucket to the ref count, which means this table bucket + snapshotId has
+     * been leased by how many lease id.
+     */
+    private final Map<KvSnapshotLeaseForBucket, AtomicInteger> refCount =
+            MapUtils.newConcurrentHashMap();
+
+    /** For metrics. */
+    private final AtomicInteger leasedBucketCount = new AtomicInteger(0);
+
+    public KvSnapshotLeaseManager(
+            Configuration conf,
+            KvSnapshotLeaseMetadataManager metadataManager,
+            CoordinatorContext coordinatorContext,
+            Clock clock,
+            CoordinatorMetricGroup coordinatorMetricGroup) {
+        this(
+                conf,
+                metadataManager,
+                coordinatorContext,
+                Executors.newScheduledThreadPool(
+                        1, new ExecutorThreadFactory("kv-snapshot-lease-cleaner")),
+                clock,
+                coordinatorMetricGroup);
+    }
+
+    @VisibleForTesting
+    public KvSnapshotLeaseManager(
+            Configuration conf,
+            KvSnapshotLeaseMetadataManager metadataManager,
+            CoordinatorContext coordinatorContext,
+            ScheduledExecutorService scheduledExecutor,
+            Clock clock,
+            CoordinatorMetricGroup coordinatorMetricGroup) {
+        this.metadataManager = metadataManager;
+        this.conf = conf;
+        this.scheduledExecutor = scheduledExecutor;
+        this.coordinatorContext = coordinatorContext;
+        this.clock = clock;
+        this.kvSnapshotLeaseMap = MapUtils.newConcurrentHashMap();
+
+        registerMetrics(coordinatorMetricGroup);
+    }
+
+    public void start() {
+        LOG.info("kv snapshot lease manager has been started.");
+        scheduledExecutor.scheduleWithFixedDelay(
+                this::expireLeases,
+                0L,
+                conf.get(ConfigOptions.KV_SNAPSHOT_LEASE_EXPIRATION_CHECK_INTERVAL).toMillis(),
+                TimeUnit.MILLISECONDS);
+    }
+
+    public void initialize() throws Exception {
+        for (String leaseId : metadataManager.getLeasesList()) {
+            Optional<KvSnapshotLease> kvSnapshotLeaseOpt = metadataManager.getLease(leaseId);
+            if (kvSnapshotLeaseOpt.isPresent()) {
+                KvSnapshotLease kvSnapshotLease = kvSnapshotLeaseOpt.get();
+                this.leaseLocks.put(leaseId, new ReentrantReadWriteLock());
+                this.kvSnapshotLeaseMap.put(leaseId, kvSnapshotLease);
+
+                initializeRefCount(kvSnapshotLease);
+
+                leasedBucketCount.addAndGet(kvSnapshotLease.getLeasedSnapshotCount());
+            }
+        }
+    }
+
+    public boolean snapshotLeaseNotExist(KvSnapshotLeaseForBucket kvSnapshotLeaseForBucket) {
+        return inReadLock(
+                refCountLock,
+                () -> {
+                    AtomicInteger count = refCount.get(kvSnapshotLeaseForBucket);
+                    return count == null || count.get() <= 0;
+                });
+    }
+
+    /**
+     * Acquire kv snapshot lease.
+     *
+     * @param leaseId the lease id
+     * @param leaseDuration the lease duration
+     * @param tableIdToLeaseBucket the table id to lease bucket
+     * @return the map of unavailable snapshots that failed to be leased
+     */
+    public Map<TableBucket, Long> acquireLease(
+            String leaseId,
+            long leaseDuration,
+            Map<Long, List<KvSnapshotLeaseForBucket>> tableIdToLeaseBucket)
+            throws Exception {
+        ReadWriteLock lock = leaseLocks.computeIfAbsent(leaseId, k -> new ReentrantReadWriteLock());
+        return inWriteLock(
+                lock,
+                () -> {
+                    // To record the unavailable snapshots such as the kv snapshotId to lease not
+                    // exists.
+                    Map<TableBucket, Long> unavailableSnapshots = new HashMap<>();
+
+                    boolean update = kvSnapshotLeaseMap.containsKey(leaseId);
+                    // set the expiration time as: current time + leaseDuration
+                    long newExpirationTime = clock.milliseconds() + leaseDuration;
+                    KvSnapshotLease kvSnapshotLease =
+                            kvSnapshotLeaseMap.compute(
+                                    leaseId,
+                                    (key, existingLease) -> {
+                                        if (existingLease == null) {
+                                            LOG.info(
+                                                    "kv snapshot lease '{}' has been acquired. The lease expiration "
+                                                            + "time is {}",
+                                                    leaseId,
+                                                    newExpirationTime);
+                                            return new KvSnapshotLease(newExpirationTime);
+                                        } else {
+                                            existingLease.setExpirationTime(newExpirationTime);
+                                            return existingLease;
+                                        }
+                                    });
+
+                    for (Map.Entry<Long, List<KvSnapshotLeaseForBucket>> entry :
+                            tableIdToLeaseBucket.entrySet()) {
+                        Long tableId = entry.getKey();
+                        TableInfo tableInfo = coordinatorContext.getTableInfoById(tableId);
+                        int numBuckets = tableInfo.getNumBuckets();
+                        List<KvSnapshotLeaseForBucket> buckets = entry.getValue();
+                        for (KvSnapshotLeaseForBucket bucket : buckets) {
+
+                            TableBucket tableBucket = bucket.getTableBucket();
+                            long kvSnapshotId = bucket.getKvSnapshotId();
+                            try {
+                                boolean snapshotExists =
+                                        metadataManager.isSnapshotExists(tableBucket, kvSnapshotId);
+                                if (!snapshotExists) {
+                                    unavailableSnapshots.put(tableBucket, kvSnapshotId);
+                                    continue;
+                                }
+                            } catch (Exception e) {
+                                LOG.error(
+                                        "Failed to check snapshotExists for tableBucket when acquire kv "
+                                                + "snapshot kvSnapshotLease {}.",
+                                        tableBucket,
+                                        e);
+                                unavailableSnapshots.put(tableBucket, kvSnapshotId);
+                                continue;
+                            }
+
+                            long originalSnapshotId =
+                                    kvSnapshotLease.acquireBucket(
+                                            tableBucket, kvSnapshotId, numBuckets);
+                            if (originalSnapshotId == -1L) {
+                                leasedBucketCount.incrementAndGet();
+                            } else {
+                                // clear the original ref.
+                                decrementRefCount(
+                                        new KvSnapshotLeaseForBucket(
+                                                tableBucket, originalSnapshotId));
+                            }
+                            incrementRefCount(bucket);
+                        }
+                    }
+
+                    if (update) {
+                        metadataManager.updateLease(leaseId, kvSnapshotLease);
+                    } else {
+                        metadataManager.registerLease(leaseId, kvSnapshotLease);
+                    }
+
+                    return unavailableSnapshots;
+                });
+    }
+
+    public void release(String leaseId, Map<Long, List<TableBucket>> tableIdToUnregisterBucket)
+            throws Exception {
+        ReadWriteLock lock = leaseLocks.get(leaseId);
+        if (lock == null) {
+            return;
+        }
+
+        inWriteLock(
+                lock,
+                () -> {
+                    KvSnapshotLease lease = kvSnapshotLeaseMap.get(leaseId);
+                    if (lease == null) {
+                        return;
+                    }
+
+                    for (Map.Entry<Long, List<TableBucket>> entry :
+                            tableIdToUnregisterBucket.entrySet()) {
+                        List<TableBucket> buckets = entry.getValue();
+                        for (TableBucket bucket : buckets) {
+                            long snapshotId = lease.releaseBucket(bucket);
+                            if (snapshotId != -1L) {
+                                leasedBucketCount.decrementAndGet();
+                                decrementRefCount(new KvSnapshotLeaseForBucket(bucket, snapshotId));
+                            }
+                        }
+                    }
+
+                    if (lease.isEmpty()) {
+                        releaseAll(leaseId);
+                    } else {
+                        metadataManager.updateLease(leaseId, lease);
+                    }
+                });
+    }
+
+    /**
+     * Release kv snapshot lease.
+     *
+     * @param leaseId the lease id
+     * @return true if clear success, false if lease not exist
+     */
+    public boolean releaseAll(String leaseId) throws Exception {
+        ReadWriteLock lock = leaseLocks.get(leaseId);
+        if (lock == null) {
+            return false;
+        }
+
+        boolean exist =
+                inWriteLock(
+                        lock,
+                        () -> {
+                            KvSnapshotLease kvSnapshotLease = kvSnapshotLeaseMap.remove(leaseId);
+                            if (kvSnapshotLease == null) {
+                                return false;
+                            }
+
+                            clearRefCount(kvSnapshotLease);
+                            metadataManager.deleteLease(leaseId);
+
+                            LOG.info(
+                                    "kv snapshots of lease '"
+                                            + leaseId
+                                            + "' has been all released.");

Review Comment:
   nit: use `{}` in logging



##########
fluss-rpc/src/main/proto/FlussApi.proto:
##########
@@ -378,6 +378,29 @@ message GetKvSnapshotMetadataResponse {
   repeated PbRemotePathAndLocalFile snapshot_files = 2;
 }
 
+message AcquireKvSnapshotLeaseRequest {
+  required string lease_id = 1;
+  required int64 lease_duration = 2;
+  repeated PbKvSnapshotLeaseForTable table_lease_req = 3;

Review Comment:
   rename to `snapshots_to_lease` or `snapshots_to_acquire`



##########
fluss-server/src/main/java/org/apache/fluss/server/zk/data/lease/KvSnapshotLeaseMetadataManager.java:
##########
@@ -0,0 +1,226 @@
+/*
+ * 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.fluss.server.zk.data.lease;
+
+import org.apache.fluss.fs.FSDataInputStream;
+import org.apache.fluss.fs.FSDataOutputStream;
+import org.apache.fluss.fs.FileSystem;
+import org.apache.fluss.fs.FsPath;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.server.zk.ZooKeeperClient;
+import org.apache.fluss.server.zk.data.BucketSnapshot;
+import org.apache.fluss.utils.FlussPaths;
+import org.apache.fluss.utils.IOUtils;
+import org.apache.fluss.utils.types.Tuple2;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.ByteArrayOutputStream;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/**
+ * The manager to handle {@link KvSnapshotLease} to register/update/delete metadata from zk and
+ * remote fs.
+ */
+public class KvSnapshotLeaseMetadataManager {
+    private static final Logger LOG = LoggerFactory.getLogger(KvSnapshotLeaseMetadataManager.class);
+
+    private final ZooKeeperClient zkClient;
+    private final String remoteDataDir;
+
+    public KvSnapshotLeaseMetadataManager(ZooKeeperClient zkClient, String remoteDataDir) {
+        this.zkClient = zkClient;
+        this.remoteDataDir = remoteDataDir;
+    }
+
+    public List<String> getLeasesList() throws Exception {
+        return zkClient.getKvSnapshotLeasesList();
+    }
+
+    /**
+     * Register a new kv snapshot lease to zk and remote fs.
+     *
+     * @param leaseId the lease id.
+     * @param lease the kv snapshot lease.
+     */
+    public void registerLease(String leaseId, KvSnapshotLease lease) throws Exception {
+        Map<Long, FsPath> tableIdToRemoteMetadataFsPath = generateMetadataFile(leaseId, lease);

Review Comment:
   It would be better to wrap the `generateMetadataFile` call into the following try-catch block, as it involves multiple remote I/O operations and has a high likelihood of throwing an `IOException`. And we should fallback and cleanup created files.



##########
fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/source/reader/FlinkSourceReader.java:
##########
@@ -77,13 +88,53 @@ public FlinkSourceReader(
                 recordEmitter,
                 context.getConfiguration(),
                 context);
+        this.finishedKvSnapshotConsumeBuckets = new HashSet<>();
     }
 
     @Override
     protected void onSplitFinished(Map<String, SourceSplitState> map) {
         // do nothing
     }
 
+    @Override
+    public List<SourceSplitBase> snapshotState(long checkpointId) {
+        Set<TableBucket> bucketsFinishedConsumeKvSnapshot = new HashSet<>();
+
+        // do not modify this state.
+        List<SourceSplitBase> sourceSplitBases = super.snapshotState(checkpointId);
+        for (SourceSplitBase sourceSplitBase : sourceSplitBases) {
+            TableBucket tableBucket = sourceSplitBase.getTableBucket();
+            if (finishedKvSnapshotConsumeBuckets.contains(tableBucket)) {
+                continue;
+            }
+
+            if (sourceSplitBase.isHybridSnapshotLogSplit()) {
+                HybridSnapshotLogSplit hybridSnapshotLogSplit =
+                        sourceSplitBase.asHybridSnapshotLogSplit();
+                if (hybridSnapshotLogSplit.isSnapshotFinished()) {
+                    bucketsFinishedConsumeKvSnapshot.add(tableBucket);
+                }
+            }
+        }
+
+        // report finished kv snapshot consume event.
+        if (!bucketsFinishedConsumeKvSnapshot.isEmpty()) {
+            LOG.info(
+                    "reader has finished kv snapshot read for bucket: {}, checkpoint id {}",
+                    bucketsFinishedConsumeKvSnapshot,
+                    checkpointId);
+
+            context.sendSourceEventToCoordinator(

Review Comment:
   This introduces external IO operation here which I have concerns. But I don't have other solutions yet. Could you please add `TODO` comments before this code to outline the IO problem and future improvements?



##########
fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/source/FlussSourceBuilder.java:
##########
@@ -71,6 +72,8 @@ public class FlussSourceBuilder<OUT> {
     private Long scanPartitionDiscoveryIntervalMs;
     private OffsetsInitializer offsetsInitializer;
     private FlussDeserializationSchema<OUT> deserializationSchema;
+    private String kvSnapshotLeaseId;
+    private long kvSnapshotLeaseDurationMs;

Review Comment:
   They should have default values (use the config option defaults), otherwise, DataStream API jobs will fail without setting these 2 parameters. (backward-incompatible)



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorService.java:
##########
@@ -856,6 +864,35 @@ public CompletableFuture<ControlledShutdownResponse> controlledShutdown(
         return response;
     }
 
+    @Override
+    public CompletableFuture<AcquireKvSnapshotLeaseResponse> acquireKvSnapshotLease(
+            AcquireKvSnapshotLeaseRequest request) {
+        CompletableFuture<AcquireKvSnapshotLeaseResponse> response = new CompletableFuture<>();
+        eventManagerSupplier
+                .get()
+                .put(
+                        new AcquireKvSnapshotLeaseEvent(
+                                request.getLeaseId(),
+                                request.getLeaseDuration(),
+                                getAcquireKvSnapshotLeaseData(request),
+                                response));
+        return response;
+    }
+
+    @Override
+    public CompletableFuture<ReleaseKvSnapshotLeaseResponse> releaseKvSnapshotLease(
+            ReleaseKvSnapshotLeaseRequest request) {
+        CompletableFuture<ReleaseKvSnapshotLeaseResponse> response = new CompletableFuture<>();

Review Comment:
   ditto. check READ permission. and add tests



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorEventProcessor.java:
##########
@@ -633,6 +659,18 @@ public void process(CoordinatorEvent event) {
             completeFromCallable(
                     listRebalanceProgressEvent.getRespCallback(),
                     () -> processListRebalanceProgress(listRebalanceProgressEvent));
+        } else if (event instanceof AcquireKvSnapshotLeaseEvent) {
+            AcquireKvSnapshotLeaseEvent acquireKvSnapshotLeaseEvent =
+                    (AcquireKvSnapshotLeaseEvent) event;
+            completeFromCallable(
+                    acquireKvSnapshotLeaseEvent.getRespCallback(),
+                    () -> tryProcessAcquireKvSnapshotLease(acquireKvSnapshotLeaseEvent));

Review Comment:
   The lease requests don't need to access `CoordinatorContext` and should be processed in coordinator queue. The lease operation involves heavy lock operation and IO operations, I have concenrs it will make the coordinator queue much worse. We should handle the lease requests directly in `CoordinatorService`.



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorService.java:
##########
@@ -856,6 +864,35 @@ public CompletableFuture<ControlledShutdownResponse> controlledShutdown(
         return response;
     }
 
+    @Override
+    public CompletableFuture<AcquireKvSnapshotLeaseResponse> acquireKvSnapshotLease(
+            AcquireKvSnapshotLeaseRequest request) {
+        CompletableFuture<AcquireKvSnapshotLeaseResponse> response = new CompletableFuture<>();

Review Comment:
   We should add permission check. We should throw auth exception if the session user doesn't have READ permission on the table id. 



##########
fluss-flink/fluss-flink-common/src/test/java/org/apache/fluss/flink/source/enumerator/FlinkSourceEnumeratorTest.java:
##########
@@ -427,7 +434,12 @@ void testDiscoverPartitionsPeriodically(boolean isPrimaryKeyTable) throws Throwa
                                 streaming,
                                 null,
                                 null,
-                                workExecutor)) {
+                                workExecutor,
+                                isPrimaryKeyTable
+                                        ? new LeaseContext(
+                                                "kv_snapshot_lease1", Duration.ofDays(1).toMillis())
+                                        : new LeaseContext(null, null))) {

Review Comment:
   This conditional processing looks too verbose and make the code unreadable. As I suggested before, we can use `LeaseContext.default()` directly here. Having default values for the lease id and duration has no cost, but can improve a lot of code. 



##########
fluss-rpc/src/main/proto/FlussApi.proto:
##########
@@ -1138,4 +1171,15 @@ message PbDatabaseSummary {
   required string database_name = 1;
   required int64 created_time = 2;
   required int32 table_count = 3;
+}
+
+message PbKvSnapshotLeaseForTable {
+  required int64 table_id = 1;
+  repeated PbKvSnapshotLeaseForBucket buckets_req = 2;

Review Comment:
   rename to `bucket_snapshots`. This is also used in response, so having `req` in the field name is not a good idea.



-- 
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@fluss.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org