This is an automated email from the ASF dual-hosted git repository.

JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git


The following commit(s) were added to refs/heads/master by this push:
     new 367ae6cd60 [core] Acquire REST commit leases only on retries (#11147)
367ae6cd60 is described below

commit 367ae6cd606152f19fd66c96ca0938b0db3a02f7
Author: YeJunHao <[email protected]>
AuthorDate: Mon Nov 16 00:05:35 2026 +0800

    [core] Acquire REST commit leases only on retries (#11147)
---
 docs/generated/core_configuration.html             |   8 +-
 docs/static/rest-catalog-open-api.yaml             |   4 +-
 .../main/java/org/apache/paimon/CoreOptions.java   |  15 +-
 .../DataEvolutionRowIdReassigner.java              | 150 ++++-----
 .../org/apache/paimon/catalog/SnapshotCommit.java  |   6 +-
 .../paimon/operation/FileStoreCommitImpl.java      |  40 +--
 .../java/org/apache/paimon/operation/Lock.java     |  25 +-
 .../operation/RemoveUnexistingManifests.java       |  22 +-
 .../org/apache/paimon/rest/RESTCatalogLock.java    |  20 ++
 .../apache/paimon/rest/RESTCatalogLockFactory.java |   4 +-
 .../apache/paimon/rest/CommitLockProtocolTest.java |   2 +-
 .../paimon/rest/RESTCommitLockIntegrationTest.java | 361 ++++++++++++++++++++-
 12 files changed, 506 insertions(+), 151 deletions(-)

diff --git a/docs/generated/core_configuration.html 
b/docs/generated/core_configuration.html
index 3f6b5b725b..accf6c72dc 100644
--- a/docs/generated/core_configuration.html
+++ b/docs/generated/core_configuration.html
@@ -1531,16 +1531,16 @@ For an internal format table in a REST catalog, it also 
makes the catalog own th
             <td>Time field for record level expire. It supports the following 
types: `timestamps in seconds with INT`,`timestamps in seconds with BIGINT`, 
`timestamps in milliseconds with BIGINT` or `timestamp`.</td>
         </tr>
         <tr>
-            <td><h5>rest.commit.acquire-lock</h5></td>
+            <td><h5>rest.commit.lock-enabled</h5></td>
             <td style="word-wrap: break-word;">false</td>
             <td>Boolean</td>
-            <td>Whether this writer acquires a REST commit lease for each 
publication attempt. Can be set dynamically for a writer and requires 
rest.commit.lock-enabled on the server-side table.</td>
+            <td>Enable the REST catalog's server-side table commit lease 
capability. Writers acquire a lease only when rest.commit.retry-acquire-lock is 
enabled.</td>
         </tr>
         <tr>
-            <td><h5>rest.commit.lock-enabled</h5></td>
+            <td><h5>rest.commit.retry-acquire-lock</h5></td>
             <td style="word-wrap: break-word;">false</td>
             <td>Boolean</td>
-            <td>Enable the REST catalog's server-side table commit lease 
capability. Writers acquire a lease only when rest.commit.acquire-lock is 
enabled.</td>
+            <td>Whether this writer acquires a REST commit lease when retrying 
a conflicting publication. The first attempt is optimistic for retryable 
operations. Rollback as latest and manifest repair acquire the lease before 
preparing their single attempt. Can be set dynamically for a writer and 
requires rest.commit.lock-enabled on the server-side table.</td>
         </tr>
         <tr>
             <td><h5>row-tracking.enabled</h5></td>
diff --git a/docs/static/rest-catalog-open-api.yaml 
b/docs/static/rest-catalog-open-api.yaml
index dfcfdd672a..b33566a5e3 100644
--- a/docs/static/rest-catalog-open-api.yaml
+++ b/docs/static/rest-catalog-open-api.yaml
@@ -751,7 +751,9 @@ paths:
       description: >-
         Requires the server-side table property rest.commit.lock-enabled=true 
and the same
         permission as committing snapshots. Clients opt into acquisition 
separately using
-        rest.commit.acquire-lock=true; that client option does not enable the 
table capability.
+        rest.commit.retry-acquire-lock=true. Retryable operations start 
optimistically.
+        Rollback as latest and manifest repair acquire the lease before 
preparing their
+        single attempt. The client option does not enable the table capability.
         Ownership is the exact commitUser: authorized callers that send the 
same commitUser
         share the lease, so each logical writer must use a unique commitUser. 
Contention
         returns HTTP 200 with acquired=false. A grant includes the 
authoritative snapshot head.
diff --git a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java 
b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java
index ee9386002f..7ef992afab 100644
--- a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java
+++ b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java
@@ -1026,15 +1026,16 @@ public class CoreOptions implements Serializable {
                     .defaultValue(false)
                     .withDescription(
                             "Enable the REST catalog's server-side table 
commit lease capability. "
-                                    + "Writers acquire a lease only when 
rest.commit.acquire-lock is enabled.");
+                                    + "Writers acquire a lease only when 
rest.commit.retry-acquire-lock is enabled.");
 
-    public static final ConfigOption<Boolean> REST_COMMIT_ACQUIRE_LOCK =
-            key("rest.commit.acquire-lock")
+    public static final ConfigOption<Boolean> REST_COMMIT_RETRY_ACQUIRE_LOCK =
+            key("rest.commit.retry-acquire-lock")
                     .booleanType()
                     .defaultValue(false)
                     .withDescription(
-                            "Whether this writer acquires a REST commit lease 
for each publication "
-                                    + "attempt. Can be set dynamically for a 
writer and requires "
+                            "Whether this writer acquires a REST commit lease 
when retrying a conflicting publication. "
+                                    + "The first attempt is optimistic for 
retryable operations. Rollback as latest and "
+                                    + "manifest repair acquire the lease 
before preparing their single attempt. Can be set dynamically for a writer and 
requires "
                                     + "rest.commit.lock-enabled on the 
server-side table.");
 
     public static final ConfigOption<Duration> COMMIT_TIMEOUT =
@@ -4057,8 +4058,8 @@ public class CoreOptions implements Serializable {
         return options.get(REST_COMMIT_LOCK_ENABLED);
     }
 
-    public boolean restCommitAcquireLock() {
-        return options.get(REST_COMMIT_ACQUIRE_LOCK);
+    public boolean restCommitRetryAcquireLock() {
+        return options.get(REST_COMMIT_RETRY_ACQUIRE_LOCK);
     }
 
     public long commitTimeout() {
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/append/dataevolution/DataEvolutionRowIdReassigner.java
 
b/paimon-core/src/main/java/org/apache/paimon/append/dataevolution/DataEvolutionRowIdReassigner.java
index 6a6d87dc46..390e6ac560 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/append/dataevolution/DataEvolutionRowIdReassigner.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/append/dataevolution/DataEvolutionRowIdReassigner.java
@@ -145,8 +145,7 @@ public class DataEvolutionRowIdReassigner {
 
         ManifestFile manifestFile = 
table.store().manifestFileFactory().create();
         ManifestList manifestList = 
table.store().manifestListFactory().create();
-        Optional<AssignmentPlan> optionalPlan =
-                planAssignment(manifestList.readDataManifests(latest));
+        Optional<AssignmentPlan> optionalPlan = planAssignment(latest, 
manifestList);
         if (!optionalPlan.isPresent()) {
             LOG.info(
                     "Skip reassigning row IDs for table {} because no 
partition requires reassignment.",
@@ -155,31 +154,31 @@ public class DataEvolutionRowIdReassigner {
                     latest.id(), nextRowId, "no partition requires row-id 
reassignment");
         }
 
-        CommittedAssignment committed =
+        AssignmentAttempt committed =
                 commitAssignmentWithRetry(
-                        optionalPlan.get(), latest, manifestFile, 
manifestList, commitUser);
+                        optionalPlan.get(), manifestFile, manifestList, 
commitUser);
         Assignment assignment = committed.assignment;
-        CommitAssignmentResult commitResult = committed.commitResult;
         LOG.info(
                 "Reassigned row IDs for table {} from {} to {}, partitions={}, 
files={}, rows={}.",
                 table.name(),
                 assignment.firstAssignedRowId,
                 assignment.nextRowId,
                 assignment.rowIdMappings.size(),
-                commitResult.fileCount,
+                committed.fileCount,
                 assignment.logicalRowCount());
 
         return new Result(
                 assignment.snapshot.id(),
                 assignment.snapshot.id() + 1,
-                commitResult.fileCount,
+                committed.fileCount,
                 assignment.logicalRowCount(),
-                commitResult.indexFileCount,
+                committed.indexFileCount,
                 assignment.firstAssignedRowId,
                 assignment.nextRowId);
     }
 
-    private Optional<AssignmentPlan> planAssignment(List<ManifestFileMeta> 
manifestMetas) {
+    private Optional<AssignmentPlan> planAssignment(Snapshot snapshot, 
ManifestList manifestList) {
+        List<ManifestFileMeta> manifestMetas = 
manifestList.readDataManifests(snapshot);
         List<List<ManifestFileMeta>> manifestGroups = 
manifestGroupsByPartition(manifestMetas);
         List<List<ManifestFileMeta>> includedGroups = new ArrayList<>();
         for (List<ManifestFileMeta> manifestGroup : manifestGroups) {
@@ -204,6 +203,7 @@ public class DataEvolutionRowIdReassigner {
 
         return Optional.of(
                 new AssignmentPlan(
+                        snapshot,
                         manifestMetasToRewrite,
                         new RelativeRowIdMappings(
                                 compactPlan.rowIdMappings, 
compactPlan.totalOffset)));
@@ -354,14 +354,12 @@ public class DataEvolutionRowIdReassigner {
         return partitionPredicate != null;
     }
 
-    private CommittedAssignment commitAssignmentWithRetry(
+    private AssignmentAttempt commitAssignmentWithRetry(
             AssignmentPlan initialAssignmentPlan,
-            Snapshot initialSnapshot,
             ManifestFile manifestFile,
             ManifestList manifestList,
             String commitUser) {
         AssignmentPlan assignmentPlan = initialAssignmentPlan;
-        Snapshot latest = initialSnapshot;
         int retryCount = 0;
         long startMillis = System.currentTimeMillis();
         CoreOptions options = table.coreOptions();
@@ -369,55 +367,60 @@ public class DataEvolutionRowIdReassigner {
                 new RetryWaiter(options.commitMinRetryWait(), 
options.commitMaxRetryWait());
 
         while (true) {
-            Snapshot observedLatest = table.snapshotManager().latestSnapshot();
-            checkState(
-                    observedLatest != null,
-                    "Latest snapshot disappeared while reassigning row IDs.");
-            if (observedLatest.id() > latest.id()) {
-                assignmentPlan =
-                        advanceAssignmentPlan(
-                                assignmentPlan, latest, observedLatest, 
manifestFile, manifestList);
-                latest = observedLatest;
+            AssignmentPlan currentPlan = assignmentPlan;
+            AssignmentAttempt attempt;
+            try (FileStoreCommitImpl commit =
+                    (FileStoreCommitImpl) table.store().newCommit(commitUser, 
table)) {
+                attempt =
+                        commit.runWithLock(
+                                () ->
+                                        commitAssignment(
+                                                currentPlan, manifestFile, 
manifestList, commit),
+                                retryCount == 0);
             }
-
-            Assignment assignment = assignmentPlan.createAssignment(latest);
-            CommitAssignmentResult commitResult =
-                    commitAssignment(assignment, manifestFile, manifestList, 
commitUser);
-            if (commitResult.success) {
-                return new CommittedAssignment(assignment, commitResult);
+            if (attempt.success) {
+                return attempt;
             }
+            assignmentPlan = attempt.plan;
 
             if (System.currentTimeMillis() - startMillis > 
options.commitTimeout()
                     || retryCount >= options.commitMaxRetries()) {
                 throw new RuntimeException(
                         String.format(
-                                "Failed to reassign row IDs after %s millis 
with %s retries because newer snapshots kept being committed.",
+                                "Failed to commit row-id reassignment after %s 
millis with %s retries.",
                                 System.currentTimeMillis() - startMillis, 
retryCount));
             }
 
-            Snapshot newLatest = table.snapshotManager().latestSnapshot();
-            checkState(newLatest != null, "Latest snapshot disappeared while 
reassigning row IDs.");
-            assignmentPlan =
-                    advanceAssignmentPlan(
-                            assignmentPlan, latest, newLatest, manifestFile, 
manifestList);
             LOG.info(
-                    "Failed to commit row-id reassignment for table {} based 
on snapshot {} because snapshot {} has been committed. Retrying {}/{} with the 
updated assignment plan.",
+                    "Failed to commit row-id reassignment for table {} based 
on snapshot {}. Retrying {}/{}.",
                     table.name(),
-                    latest.id(),
-                    newLatest.id(),
+                    assignmentPlan.snapshot.id(),
                     retryCount + 1,
                     options.commitMaxRetries());
             retryWaiter.retryWait(retryCount);
             retryCount++;
-            latest = newLatest;
         }
     }
 
-    private CommitAssignmentResult commitAssignment(
-            Assignment assignment,
+    private AssignmentAttempt commitAssignment(
+            AssignmentPlan plan,
             ManifestFile manifestFile,
             ManifestList manifestList,
-            String commitUser) {
+            FileStoreCommitImpl commit) {
+        Snapshot latest = table.snapshotManager().latestSnapshot();
+        checkState(latest != null, "Latest snapshot disappeared while 
reassigning row IDs.");
+        if (!latest.equals(plan.snapshot)) {
+            checkState(
+                    latest.id() > plan.snapshot.id(),
+                    "Cannot reassign row IDs because snapshot %s (UUID %s) was 
replaced by snapshot %s (UUID %s).",
+                    plan.snapshot.id(),
+                    plan.snapshot.uuid(),
+                    latest.id(),
+                    latest.uuid());
+            plan = advanceAssignmentPlan(plan, latest, manifestFile, 
manifestList);
+        }
+
+        Assignment assignment = plan.createAssignment();
         RewrittenDataManifests rewrittenDataManifests =
                 writeManifestReplacements(assignment, manifestFile);
         Pair<String, Long> baseManifestList =
@@ -436,36 +439,30 @@ public class DataEvolutionRowIdReassigner {
                         assignment.firstAssignedRowId,
                         assignment.nextRowId);
 
-        boolean success;
-        try (FileStoreCommitImpl commit =
-                (FileStoreCommitImpl) table.store().newCommit(commitUser, 
table)) {
-            beforeCommit.run();
-            success =
-                    commit.replaceManifestList(
-                            assignment.snapshot,
-                            assignment.snapshot.totalRecordCount(),
-                            baseManifestList,
-                            deltaManifestList,
-                            rewrittenIndexManifest.indexManifest,
-                            assignment.nextRowId,
-                            properties);
-        }
-        return new CommitAssignmentResult(
-                success, rewrittenDataManifests.fileCount, 
rewrittenIndexManifest.indexFileCount);
+        beforeCommit.run();
+        boolean success =
+                commit.replaceManifestList(
+                        assignment.snapshot,
+                        assignment.snapshot.totalRecordCount(),
+                        baseManifestList,
+                        deltaManifestList,
+                        rewrittenIndexManifest.indexManifest,
+                        assignment.nextRowId,
+                        properties);
+        return new AssignmentAttempt(
+                plan,
+                assignment,
+                success,
+                rewrittenDataManifests.fileCount,
+                rewrittenIndexManifest.indexFileCount);
     }
 
     private AssignmentPlan advanceAssignmentPlan(
             AssignmentPlan assignmentPlan,
-            Snapshot previous,
             Snapshot latest,
             ManifestFile manifestFile,
             ManifestList manifestList) {
-        checkState(
-                latest.id() > previous.id(),
-                "Cannot advance row-id assignment from snapshot %s to %s.",
-                previous.id(),
-                latest.id());
-
+        Snapshot previous = assignmentPlan.snapshot;
         Set<String> previousManifestFiles = new HashSet<>();
         for (ManifestFileMeta manifestMeta : 
manifestList.readDataManifests(previous)) {
             previousManifestFiles.add(manifestMeta.fileName());
@@ -534,6 +531,7 @@ public class DataEvolutionRowIdReassigner {
                 !reboundManifestMetasToRewrite.isEmpty(),
                 "Cannot advance row-id assignment because no current manifest 
contains the planned row-id ranges.");
         return new AssignmentPlan(
+                latest,
                 new ArrayList<>(reboundManifestMetasToRewrite.values()),
                 assignmentPlan.relativeRowIdMappings);
     }
@@ -911,17 +909,20 @@ public class DataEvolutionRowIdReassigner {
     }
 
     private static class AssignmentPlan {
+        private final Snapshot snapshot;
         private final List<ManifestFileMeta> manifestMetasToRewrite;
         private final RelativeRowIdMappings relativeRowIdMappings;
 
         private AssignmentPlan(
+                Snapshot snapshot,
                 List<ManifestFileMeta> manifestMetasToRewrite,
                 RelativeRowIdMappings relativeRowIdMappings) {
+            this.snapshot = snapshot;
             this.manifestMetasToRewrite = new 
ArrayList<>(manifestMetasToRewrite);
             this.relativeRowIdMappings = relativeRowIdMappings;
         }
 
-        private Assignment createAssignment(Snapshot snapshot) {
+        private Assignment createAssignment() {
             Long firstAssignedRowId = snapshot.nextRowId();
             checkState(
                     firstAssignedRowId != null,
@@ -994,22 +995,21 @@ public class DataEvolutionRowIdReassigner {
         }
     }
 
-    private static class CommittedAssignment {
+    private static class AssignmentAttempt {
+        private final AssignmentPlan plan;
         private final Assignment assignment;
-        private final CommitAssignmentResult commitResult;
-
-        private CommittedAssignment(Assignment assignment, 
CommitAssignmentResult commitResult) {
-            this.assignment = assignment;
-            this.commitResult = commitResult;
-        }
-    }
-
-    private static class CommitAssignmentResult {
         private final boolean success;
         private final long fileCount;
         private final long indexFileCount;
 
-        private CommitAssignmentResult(boolean success, long fileCount, long 
indexFileCount) {
+        private AssignmentAttempt(
+                AssignmentPlan plan,
+                Assignment assignment,
+                boolean success,
+                long fileCount,
+                long indexFileCount) {
+            this.plan = plan;
+            this.assignment = assignment;
             this.success = success;
             this.fileCount = fileCount;
             this.indexFileCount = indexFileCount;
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/catalog/SnapshotCommit.java 
b/paimon-core/src/main/java/org/apache/paimon/catalog/SnapshotCommit.java
index e4f0f5e47c..6f6d4059f3 100644
--- a/paimon-core/src/main/java/org/apache/paimon/catalog/SnapshotCommit.java
+++ b/paimon-core/src/main/java/org/apache/paimon/catalog/SnapshotCommit.java
@@ -55,8 +55,8 @@ public abstract class SnapshotCommit implements Lock {
     }
 
     @Override
-    public final <T> T runWithLock(Callable<T> callable) throws Exception {
-        return lock.runWithLock(callable);
+    public final <T> T runWithLock(Callable<T> callable, boolean firstCommit) 
throws Exception {
+        return lock.runWithLock(callable, firstCommit);
     }
 
     @Override
@@ -73,7 +73,7 @@ public abstract class SnapshotCommit implements Lock {
         }
     }
 
-    /** Backend publication, invoked only after acquiring and validating the 
bound lock. */
+    /** Backend publication after entering and validating the bound lock 
scope. */
     protected abstract boolean commitImpl(
             @Nullable String baseSnapshotUuid,
             Snapshot snapshot,
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreCommitImpl.java
 
b/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreCommitImpl.java
index 7e7c14da49..9cf8b882a2 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreCommitImpl.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreCommitImpl.java
@@ -245,9 +245,13 @@ public class FileStoreCommitImpl implements 
FileStoreCommit {
         this.commitCleaner = new CommitCleaner(manifestList, manifestFile, 
indexManifestFile);
     }
 
-    private <T> T runWithLock(Callable<T> callable) {
+    /**
+     * Run metadata preparation and publication with this commit's lock. Pass 
{@code false} when the
+     * operation requires the configured lock even on its first attempt.
+     */
+    public <T> T runWithLock(Callable<T> callable, boolean firstCommit) {
         try {
-            return snapshotCommit.runWithLock(callable);
+            return snapshotCommit.runWithLock(callable, firstCommit);
         } catch (RuntimeException e) {
             throw e;
         } catch (Exception e) {
@@ -1190,7 +1194,8 @@ public class FileStoreCommitImpl implements 
FileStoreCommit {
                                     allowRollback,
                                     latestSnapshotSupplier.get(),
                                     detectConflicts,
-                                    newStatsFileName));
+                                    newStatsFileName),
+                    retryResult == null);
         } catch (Lock.AcquisitionException | RuntimeException e) {
             throw e;
         } catch (Exception e) {
@@ -1675,24 +1680,6 @@ public class FileStoreCommitImpl implements 
FileStoreCommit {
             @Nullable String indexManifest,
             @Nullable Long nextRowId,
             @Nullable Map<String, String> properties) {
-        return replaceManifestListOnce(
-                latest,
-                totalRecordCount,
-                baseManifestList,
-                deltaManifestList,
-                indexManifest,
-                nextRowId,
-                properties);
-    }
-
-    private boolean replaceManifestListOnce(
-            Snapshot latest,
-            long totalRecordCount,
-            Pair<String, Long> baseManifestList,
-            Pair<String, Long> deltaManifestList,
-            @Nullable String indexManifest,
-            @Nullable Long nextRowId,
-            @Nullable Map<String, String> properties) {
         return runWithLock(
                 () ->
                         replaceManifestListOnceWithoutLock(
@@ -1702,7 +1689,8 @@ public class FileStoreCommitImpl implements 
FileStoreCommit {
                                 deltaManifestList,
                                 indexManifest,
                                 nextRowId,
-                                properties));
+                                properties),
+                false);
     }
 
     private boolean replaceManifestListOnceWithoutLock(
@@ -1756,7 +1744,7 @@ public class FileStoreCommitImpl implements 
FileStoreCommit {
     }
 
     private Pair<Boolean, CommitCallback.Context> 
rollbackToAsLatestOnce(Snapshot targetSnapshot) {
-        return runWithLock(() -> 
rollbackToAsLatestOnceWithoutLock(targetSnapshot));
+        return runWithLock(() -> 
rollbackToAsLatestOnceWithoutLock(targetSnapshot), false);
     }
 
     private Pair<Boolean, CommitCallback.Context> 
rollbackToAsLatestOnceWithoutLock(
@@ -1920,7 +1908,7 @@ public class FileStoreCommitImpl implements 
FileStoreCommit {
         int retryCount = 0;
         long startMillis = System.currentTimeMillis();
         while (true) {
-            boolean success = compactManifestOnce();
+            boolean success = compactManifestOnce(retryCount == 0);
             if (success) {
                 break;
             }
@@ -1938,8 +1926,8 @@ public class FileStoreCommitImpl implements 
FileStoreCommit {
         }
     }
 
-    private boolean compactManifestOnce() {
-        return runWithLock(this::compactManifestOnceWithoutLock);
+    private boolean compactManifestOnce(boolean firstCommit) {
+        return runWithLock(this::compactManifestOnceWithoutLock, firstCommit);
     }
 
     private boolean compactManifestOnceWithoutLock() {
diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/Lock.java 
b/paimon-core/src/main/java/org/apache/paimon/operation/Lock.java
index aa658c657c..623aa3eafa 100644
--- a/paimon-core/src/main/java/org/apache/paimon/operation/Lock.java
+++ b/paimon-core/src/main/java/org/apache/paimon/operation/Lock.java
@@ -36,15 +36,25 @@ public interface Lock extends AutoCloseable {
      */
     AutoCloseable acquire() throws Exception;
 
+    /** Acquire the scope for the given commit attempt. */
+    default AutoCloseable acquire(boolean firstCommit) throws Exception {
+        return acquire();
+    }
+
     /**
      * Run an operation under the lock. Acquisition failures are distinguished 
from operation
      * failures; interruption stops acquisition. Releasing a scope must not 
replace the operation's
      * result or exception.
      */
     default <T> T runWithLock(Callable<T> callable) throws Exception {
+        return runWithLock(callable, false);
+    }
+
+    /** Run a commit attempt with the scope required by this lock. */
+    default <T> T runWithLock(Callable<T> callable, boolean firstCommit) 
throws Exception {
         AutoCloseable scope;
         try {
-            scope = acquire();
+            scope = acquire(firstCommit);
         } catch (Exception e) {
             if (ExceptionUtils.findThrowable(e, 
InterruptedException.class).isPresent()) {
                 Thread.currentThread().interrupt();
@@ -101,7 +111,7 @@ public interface Lock extends AutoCloseable {
         }
 
         @Override
-        public <T> T runWithLock(Callable<T> callable) throws Exception {
+        public <T> T runWithLock(Callable<T> callable, boolean firstCommit) 
throws Exception {
             return callable.call();
         }
 
@@ -127,11 +137,16 @@ public interface Lock extends AutoCloseable {
 
         @Override
         public AutoCloseable acquire() throws Exception {
+            return acquire(false);
+        }
+
+        @Override
+        public AutoCloseable acquire(boolean firstCommit) throws Exception {
             if (held.get()) {
                 delegate.ensureValid();
                 return () -> {};
             }
-            AutoCloseable scope = delegate.acquire();
+            AutoCloseable scope = delegate.acquire(firstCommit);
             try {
                 delegate.ensureValid();
                 held.set(true);
@@ -146,12 +161,12 @@ public interface Lock extends AutoCloseable {
         }
 
         @Override
-        public <T> T runWithLock(Callable<T> callable) throws Exception {
+        public <T> T runWithLock(Callable<T> callable, boolean firstCommit) 
throws Exception {
             if (held.get()) {
                 delegate.ensureValid();
                 return callable.call();
             }
-            return Lock.super.runWithLock(callable);
+            return Lock.super.runWithLock(callable, firstCommit);
         }
 
         @Override
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/operation/RemoveUnexistingManifests.java
 
b/paimon-core/src/main/java/org/apache/paimon/operation/RemoveUnexistingManifests.java
index d2ed729581..659900d557 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/operation/RemoveUnexistingManifests.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/operation/RemoveUnexistingManifests.java
@@ -63,6 +63,14 @@ public class RemoveUnexistingManifests {
      * @return {@code true} if a repair snapshot was committed
      */
     public boolean execute() {
+        try (FileStoreCommitImpl commit =
+                (FileStoreCommitImpl)
+                        table.store().newCommit("Repair-table-" + 
UUID.randomUUID(), table)) {
+            return commit.runWithLock(() -> repairManifests(commit), false);
+        }
+    }
+
+    private boolean repairManifests(FileStoreCommitImpl commit) {
         FileIO fileIO = table.fileIO();
         Snapshot latest = table.snapshotManager().latestSnapshot();
         if (latest == null) {
@@ -101,16 +109,10 @@ public class RemoveUnexistingManifests {
         Pair<String, Long> baseManifestList = 
manifestList.write(existingManifestFiles);
         Pair<String, Long> deltaManifestList = 
manifestList.write(Collections.emptyList());
 
-        try (FileStoreCommitImpl fileStoreCommit =
-                (FileStoreCommitImpl)
-                        table.store().newCommit("Repair-table-" + 
UUID.randomUUID(), table)) {
-            boolean result =
-                    fileStoreCommit.replaceManifestList(
-                            latest, totalRecordCount, baseManifestList, 
deltaManifestList);
-            if (!result) {
-                throw new RuntimeException(
-                        "Failed, snapshot conflict, maybe multiple jobs is 
running to commit snapshots.");
-            }
+        if (!commit.replaceManifestList(
+                latest, totalRecordCount, baseManifestList, 
deltaManifestList)) {
+            throw new RuntimeException(
+                    "Failed, snapshot conflict, maybe multiple jobs is running 
to commit snapshots.");
         }
         return true;
     }
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/rest/RESTCatalogLock.java 
b/paimon-core/src/main/java/org/apache/paimon/rest/RESTCatalogLock.java
index 5818810484..a4c2585f15 100644
--- a/paimon-core/src/main/java/org/apache/paimon/rest/RESTCatalogLock.java
+++ b/paimon-core/src/main/java/org/apache/paimon/rest/RESTCatalogLock.java
@@ -58,6 +58,7 @@ public class RESTCatalogLock implements Lock {
     private final LongSupplier nanoTime;
     private final long acquireTimeoutMillis;
     private final ThreadLocal<Lease> currentLease = new ThreadLocal<>();
+    private final ThreadLocal<Boolean> optimistic = ThreadLocal.withInitial(() 
-> false);
 
     public RESTCatalogLock(
             RESTApi api,
@@ -163,8 +164,27 @@ public class RESTCatalogLock implements Lock {
         }
     }
 
+    @Override
+    public AutoCloseable acquire(boolean firstCommit) throws Exception {
+        if (optimistic.get()) {
+            return () -> {};
+        }
+        if (currentLease.get() != null) {
+            ensureValid();
+            return () -> {};
+        }
+        if (!firstCommit) {
+            return acquire();
+        }
+        optimistic.set(true);
+        return optimistic::remove;
+    }
+
     @Override
     public void ensureValid() {
+        if (optimistic.get()) {
+            return;
+        }
         Lease lease = currentLease.get();
         if (lease == null) {
             throw new IllegalStateException("No commit lease is held by this 
thread.");
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/rest/RESTCatalogLockFactory.java 
b/paimon-core/src/main/java/org/apache/paimon/rest/RESTCatalogLockFactory.java
index bb91fd016b..2242f41099 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/rest/RESTCatalogLockFactory.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/rest/RESTCatalogLockFactory.java
@@ -47,12 +47,12 @@ public class RESTCatalogLockFactory implements 
CatalogLockFactory {
             @Nullable String commitUser,
             Options tableOptions) {
         CoreOptions options = new CoreOptions(tableOptions);
-        if (!options.restCommitAcquireLock()) {
+        if (!options.restCommitRetryAcquireLock()) {
             return Lock.empty();
         }
         checkArgument(
                 options.restCommitLockEnabled(),
-                "rest.commit.acquire-lock requires rest.commit.lock-enabled on 
the table.");
+                "rest.commit.retry-acquire-lock requires 
rest.commit.lock-enabled on the table.");
         return new RESTCatalogLock(
                 new RESTApi(context.options(), false),
                 identifier,
diff --git 
a/paimon-core/src/test/java/org/apache/paimon/rest/CommitLockProtocolTest.java 
b/paimon-core/src/test/java/org/apache/paimon/rest/CommitLockProtocolTest.java
index 6e0ce6c987..b14d7187c2 100644
--- 
a/paimon-core/src/test/java/org/apache/paimon/rest/CommitLockProtocolTest.java
+++ 
b/paimon-core/src/test/java/org/apache/paimon/rest/CommitLockProtocolTest.java
@@ -209,7 +209,7 @@ class CommitLockProtocolTest {
                                             true, "morax-job", 100000, 60000, 
snapshot(1)))));
             Options tableOptions = Options.fromMap(table.options());
             tableOptions.set(CoreOptions.REST_COMMIT_LOCK_ENABLED, true);
-            tableOptions.set(CoreOptions.REST_COMMIT_ACQUIRE_LOCK, true);
+            tableOptions.set(CoreOptions.REST_COMMIT_RETRY_ACQUIRE_LOCK, true);
             try (Catalog writerCatalog = environment.catalogLoader().load();
                     Lock lock =
                             writerCatalog.createLock(
diff --git 
a/paimon-core/src/test/java/org/apache/paimon/rest/RESTCommitLockIntegrationTest.java
 
b/paimon-core/src/test/java/org/apache/paimon/rest/RESTCommitLockIntegrationTest.java
index 89b8123334..5857c1a8fc 100644
--- 
a/paimon-core/src/test/java/org/apache/paimon/rest/RESTCommitLockIntegrationTest.java
+++ 
b/paimon-core/src/test/java/org/apache/paimon/rest/RESTCommitLockIntegrationTest.java
@@ -21,9 +21,11 @@ package org.apache.paimon.rest;
 import org.apache.paimon.CoreOptions;
 import org.apache.paimon.Snapshot;
 import org.apache.paimon.append.AppendCompactTask;
+import org.apache.paimon.append.dataevolution.DataEvolutionRowIdReassigner;
 import org.apache.paimon.catalog.CatalogContext;
 import org.apache.paimon.catalog.CatalogLockContext;
 import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.data.BinaryString;
 import org.apache.paimon.data.GenericRow;
 import org.apache.paimon.data.InternalRow;
 import org.apache.paimon.io.CompactIncrement;
@@ -34,6 +36,7 @@ import org.apache.paimon.operation.BaseAppendFileStoreWrite;
 import org.apache.paimon.operation.FileStoreCommit;
 import org.apache.paimon.operation.FileStoreWrite;
 import org.apache.paimon.operation.Lock;
+import org.apache.paimon.operation.RemoveUnexistingManifests;
 import org.apache.paimon.options.Options;
 import org.apache.paimon.reader.RecordReader;
 import org.apache.paimon.rest.requests.CommitLockRequest;
@@ -52,6 +55,7 @@ import org.apache.paimon.table.sink.BatchTableWrite;
 import org.apache.paimon.table.sink.BatchWriteBuilder;
 import org.apache.paimon.table.sink.CommitMessage;
 import org.apache.paimon.table.sink.CommitMessageImpl;
+import org.apache.paimon.table.sink.TableCommitImpl;
 import org.apache.paimon.table.sink.TableWriteImpl;
 import org.apache.paimon.table.source.ReadBuilder;
 import org.apache.paimon.types.DataTypes;
@@ -74,6 +78,7 @@ import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
@@ -118,7 +123,7 @@ class RESTCommitLockIntegrationTest {
     @Test
     void acquisitionRequiresTheTableCapabilityBeforeRestRequests() {
         Options options = new Options();
-        options.set("rest.commit.acquire-lock", "true");
+        options.set("rest.commit.retry-acquire-lock", "true");
         assertThatThrownBy(
                         () ->
                                 new RESTCatalogLockFactory()
@@ -137,7 +142,7 @@ class RESTCommitLockIntegrationTest {
         "false,false,false", "false,false,true", "true,false,false",
         "true,false,true", "true,true,false", "true,true,true"
     })
-    void commitsAcquireBeforeHeadAndReacquireAfterConflict(
+    void commitsAcquireOnlyAfterPublicationConflicts(
             boolean capability,
             boolean locking,
             boolean firstPublicationConflicts,
@@ -145,7 +150,7 @@ class RESTCommitLockIntegrationTest {
             throws Exception {
         Options tableOptions = new Options();
         tableOptions.set(CoreOptions.REST_COMMIT_LOCK_ENABLED, capability);
-        tableOptions.set(CoreOptions.REST_COMMIT_ACQUIRE_LOCK, locking);
+        tableOptions.set(CoreOptions.REST_COMMIT_RETRY_ACQUIRE_LOCK, locking);
         tableOptions.set(CoreOptions.COMMIT_MAX_RETRIES, 2);
         tableOptions.set(CoreOptions.COMMIT_MIN_RETRY_WAIT, 
Duration.ofMillis(1));
         tableOptions.set(CoreOptions.COMMIT_MAX_RETRY_WAIT, 
Duration.ofMillis(1));
@@ -193,9 +198,11 @@ class RESTCommitLockIntegrationTest {
                                                 true, "morax-job", 100000, 
60000, head.get()));
                             }
                             if (path.endsWith("/snapshot")) {
-                                if (locking) {
-                                    assertThat(lease.get()).isTrue();
-                                }
+                                assertThat(lease.get())
+                                        .isEqualTo(
+                                                locking
+                                                        && 
firstPublicationConflicts
+                                                        && publications.get() 
== 1);
                                 events.add("head");
                                 Snapshot snapshot = head.get();
                                 return json(
@@ -205,9 +212,11 @@ class RESTCommitLockIntegrationTest {
                                                         : new 
TableSnapshot(snapshot, 0, 0, 0, 0)));
                             }
                             if (path.endsWith("/commit")) {
-                                if (locking) {
-                                    assertThat(lease.get()).isTrue();
-                                }
+                                assertThat(lease.get())
+                                        .isEqualTo(
+                                                locking
+                                                        && 
firstPublicationConflicts
+                                                        && publications.get() 
== 1);
                                 CommitTableRequest commit =
                                         fromJson(request, 
CommitTableRequest.class);
                                 
assertThat(commit.getTableId()).isEqualTo("table-id");
@@ -260,6 +269,157 @@ class RESTCommitLockIntegrationTest {
         }
     }
 
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void reassignRetriesWithLeaseAndRefreshesSnapshot(
+            boolean appendBeforeGrant, @TempDir Path directory) throws 
Exception {
+        String reassignUser = "reassign-writer";
+        Schema schema =
+                Schema.newBuilder()
+                        .column("id", DataTypes.INT())
+                        .column("pt", DataTypes.STRING())
+                        .partitionKeys("pt")
+                        .option(CoreOptions.ROW_TRACKING_ENABLED.key(), "true")
+                        .option(CoreOptions.DATA_EVOLUTION_ENABLED.key(), 
"true")
+                        .option(CoreOptions.REST_COMMIT_LOCK_ENABLED.key(), 
"true")
+                        
.option(CoreOptions.REST_COMMIT_RETRY_ACQUIRE_LOCK.key(), "true")
+                        .option(CoreOptions.COMMIT_MAX_RETRIES.key(), "1")
+                        .option(CoreOptions.COMMIT_MIN_RETRY_WAIT.key(), "1 
ms")
+                        .option(CoreOptions.COMMIT_MAX_RETRY_WAIT.key(), "1 
ms")
+                        .build();
+        GetTableResponse tableResponse =
+                new GetTableResponse(
+                        "table-id",
+                        "db",
+                        "table",
+                        directory.toUri().toString(),
+                        false,
+                        0,
+                        schema,
+                        null,
+                        0,
+                        null,
+                        0,
+                        null);
+        AtomicReference<Snapshot> head = new AtomicReference<>();
+        AtomicReference<FileStoreTable> tableRef = new AtomicReference<>();
+        AtomicBoolean leaseAcquired = new AtomicBoolean();
+        List<String> events = Collections.synchronizedList(new ArrayList<>());
+        try (MockWebServer server = new MockWebServer()) {
+            server.setDispatcher(
+                    new Dispatcher() {
+                        @Override
+                        public MockResponse dispatch(RecordedRequest request) {
+                            String path = request.getPath();
+                            if (path.endsWith("/commit-lock")) {
+                                CommitLockRequest acquire =
+                                        fromJson(request, 
CommitLockRequest.class);
+                                
assertThat(acquire.getCommitUser()).isEqualTo(reassignUser);
+                                if (appendBeforeGrant) {
+                                    // Publish an append before granting the 
lease.
+                                    try {
+                                        
appendRow(tableRef.get().newBatchWriteBuilder(), 3, "c");
+                                    } catch (Exception e) {
+                                        throw new AssertionError("Concurrent 
append failed", e);
+                                    }
+                                    events.add("append");
+                                }
+                                leaseAcquired.set(true);
+                                events.add("acquire");
+                                return json(
+                                        new CommitLockResponse(
+                                                true, reassignUser, 100000, 
60000, head.get()));
+                            }
+                            if (path.endsWith("/snapshot")) {
+                                Snapshot snapshot = head.get();
+                                return json(
+                                        new GetTableSnapshotResponse(
+                                                snapshot == null
+                                                        ? null
+                                                        : new 
TableSnapshot(snapshot, 0, 0, 0, 0)));
+                            }
+                            if (path.endsWith("/commit")) {
+                                CommitTableRequest commit =
+                                        fromJson(request, 
CommitTableRequest.class);
+                                Snapshot previous = head.get();
+                                assertThat(commit.getBaseSnapshotUuid())
+                                        .isEqualTo(previous == null ? null : 
previous.uuid());
+                                if 
(reassignUser.equals(commit.getSnapshot().commitUser())) {
+                                    if (!leaseAcquired.get()) {
+                                        events.add("reject");
+                                        return 
json(Collections.singletonMap("success", false));
+                                    }
+                                    events.add("publish");
+                                }
+                                Snapshot snapshot = commit.getSnapshot();
+                                FileStoreTable table = tableRef.get();
+                                try {
+                                    table.fileIO()
+                                            .writeFile(
+                                                    table.snapshotManager()
+                                                            
.snapshotPath(snapshot.id()),
+                                                    snapshot.toJson(),
+                                                    false);
+                                } catch (Exception e) {
+                                    throw new AssertionError("Failed to write 
snapshot", e);
+                                }
+                                head.set(snapshot);
+                                return 
json(Collections.singletonMap("success", true));
+                            }
+                            if ("GET".equals(request.getMethod()) && 
!path.contains("/schemas/")) {
+                                return json(tableResponse);
+                            }
+                            return new MockResponse().setResponseCode(400);
+                        }
+                    });
+            server.start();
+            Options catalogOptions = new Options();
+            catalogOptions.set(RESTCatalogOptions.URI, 
server.url("/").toString());
+            catalogOptions.set(RESTCatalogOptions.TOKEN_PROVIDER, "bear");
+            catalogOptions.set(RESTCatalogOptions.TOKEN, "token");
+            catalogOptions.set(RESTTokenFileIO.DATA_TOKEN_ENABLED, false);
+            catalogOptions.set(RESTCatalogInternalOptions.PREFIX, "catalog");
+            try (RESTCatalog catalog =
+                    new RESTCatalog(CatalogContext.create(catalogOptions), 
false)) {
+                FileStoreTable table =
+                        (FileStoreTable) catalog.getTable(new Identifier("db", 
"table"));
+                new FileSystemSchemaManager(table.fileIO(), 
table.location()).createTable(schema);
+                tableRef.set(table);
+                BatchWriteBuilder builder = table.newBatchWriteBuilder();
+                for (int i = 0; i < 3; i++) {
+                    appendRow(builder, i, i == 1 ? "b" : "a");
+                }
+
+                Snapshot before = head.get();
+                DataEvolutionRowIdReassigner.Result result =
+                        new 
DataEvolutionRowIdReassigner(table).reassign(reassignUser);
+
+                if (appendBeforeGrant) {
+                    assertThat(events).containsExactly("reject", "append", 
"acquire", "publish");
+                } else {
+                    assertThat(events).containsExactly("reject", "acquire", 
"publish");
+                }
+                int appends = appendBeforeGrant ? 1 : 0;
+                assertThat(result.reassigned).isTrue();
+                assertThat(result.previousSnapshotId).isEqualTo(before.id() + 
appends);
+                
assertThat(result.firstAssignedRowId).isEqualTo(before.nextRowId() + appends);
+                assertThat(head.get().id()).isEqualTo(before.id() + appends + 
1);
+
+                List<Integer> values = new ArrayList<>();
+                ReadBuilder read = table.newReadBuilder();
+                try (RecordReader<InternalRow> reader =
+                        read.newRead().createReader(read.newScan().plan())) {
+                    reader.forEachRemaining(row -> values.add(row.getInt(0)));
+                }
+                if (appendBeforeGrant) {
+                    assertThat(values).containsExactlyInAnyOrder(0, 1, 2, 3);
+                } else {
+                    assertThat(values).containsExactlyInAnyOrder(0, 1, 2);
+                }
+            }
+        }
+    }
+
     @ParameterizedTest
     @ValueSource(booleans = {false, true})
     void compactionConflictRollsBackWithoutWriterContextAndReacquires(
@@ -269,7 +429,9 @@ class RESTCommitLockIntegrationTest {
                         .column("id", DataTypes.INT())
                         
.option(CoreOptions.COMMIT_AUTO_ROLLBACK_ENABLED.key(), "true")
                         .option(CoreOptions.REST_COMMIT_LOCK_ENABLED.key(), 
"true")
-                        .option(CoreOptions.REST_COMMIT_ACQUIRE_LOCK.key(), 
String.valueOf(locking))
+                        .option(
+                                
CoreOptions.REST_COMMIT_RETRY_ACQUIRE_LOCK.key(),
+                                String.valueOf(locking))
                         .option(CoreOptions.COMMIT_MIN_RETRY_WAIT.key(), "1 
ms")
                         .option(CoreOptions.COMMIT_MAX_RETRY_WAIT.key(), "1 
ms")
                         .build();
@@ -326,9 +488,7 @@ class RESTCommitLockIntegrationTest {
                                 
assertThat(requestBody.getTableId()).isEqualTo("branch-id");
                                 assertThat(requestBody.getFromSnapshot())
                                         .isEqualTo(head.get().id());
-                                if (locking) {
-                                    assertThat(owner.get()).isNotNull();
-                                }
+                                assertThat(owner.get()).isNull();
                                 head.set(
                                         snapshots.get(
                                                 ((Instant.SnapshotInstant) 
requestBody.getInstant())
@@ -342,7 +502,7 @@ class RESTCommitLockIntegrationTest {
                                 CommitTableRequest commit =
                                         fromJson(request, 
CommitTableRequest.class);
                                 
assertThat(commit.getTableId()).isEqualTo("branch-id");
-                                if (locking) {
+                                if (owner.get() != null) {
                                     
assertThat(commit.getSnapshot().commitUser())
                                             .isEqualTo(owner.get());
                                 }
@@ -428,8 +588,7 @@ class RESTCommitLockIntegrationTest {
                         .isEqualTo(5L);
                 if (locking) {
                     assertThat(events)
-                            .containsSubsequence(
-                                    "acquire", "head", "rollback", "acquire", 
"head", "publish");
+                            .containsSubsequence("head", "rollback", 
"acquire", "head", "publish");
                 } else {
                     assertThat(events)
                             .containsSubsequence("head", "rollback", "head", 
"publish")
@@ -446,10 +605,169 @@ class RESTCommitLockIntegrationTest {
         }
     }
 
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void maintenanceWaitsForLeaseBeforeReadingHead(boolean repairManifests, 
@TempDir Path directory)
+            throws Exception {
+        Schema schema =
+                Schema.newBuilder()
+                        .column("id", DataTypes.INT())
+                        .column("pt", DataTypes.STRING())
+                        .partitionKeys("pt")
+                        .option(CoreOptions.REST_COMMIT_LOCK_ENABLED.key(), 
"true")
+                        
.option(CoreOptions.REST_COMMIT_RETRY_ACQUIRE_LOCK.key(), "true")
+                        .option(CoreOptions.COMMIT_TIMEOUT.key(), "5 s")
+                        .build();
+        GetTableResponse tableResponse =
+                new GetTableResponse(
+                        "table-id",
+                        "db",
+                        "table",
+                        directory.toUri().toString(),
+                        false,
+                        0,
+                        schema,
+                        null,
+                        0,
+                        null,
+                        0,
+                        null);
+        AtomicReference<Snapshot> head = new AtomicReference<>();
+        AtomicReference<FileStoreTable> tableRef = new AtomicReference<>();
+        AtomicReference<String> leaseOwner = new AtomicReference<>();
+        AtomicReference<org.apache.paimon.fs.Path> manifestToDelete = new 
AtomicReference<>();
+        List<String> events = Collections.synchronizedList(new ArrayList<>());
+        try (MockWebServer server = new MockWebServer()) {
+            server.setDispatcher(
+                    new Dispatcher() {
+                        @Override
+                        public MockResponse dispatch(RecordedRequest request) {
+                            String path = request.getPath();
+                            if (path.endsWith("/commit-lock")) {
+                                CommitLockRequest acquire =
+                                        fromJson(request, 
CommitLockRequest.class);
+                                if ("append-writer".equals(leaseOwner.get())) {
+                                    events.add("busy");
+                                    FileStoreTable table = tableRef.get();
+                                    try (BatchTableWrite write =
+                                                    
table.newBatchWriteBuilder().newWrite();
+                                            TableCommitImpl commit =
+                                                    
table.newCommit("append-writer")) {
+                                        write.write(GenericRow.of(2, 
BinaryString.fromString("b")));
+                                        commit.commit(write.prepareCommit());
+                                        if (repairManifests) {
+                                            boolean deleted =
+                                                    table.fileIO()
+                                                            
.delete(manifestToDelete.get(), false);
+                                            assertThat(deleted).isTrue();
+                                        }
+                                    } catch (Exception e) {
+                                        throw new AssertionError("Concurrent 
append failed", e);
+                                    }
+                                    return 
json(CommitLockResponse.unavailable());
+                                }
+                                events.add("acquire");
+                                leaseOwner.set(acquire.getCommitUser());
+                                return json(
+                                        new CommitLockResponse(
+                                                true,
+                                                acquire.getCommitUser(),
+                                                100000,
+                                                60000,
+                                                head.get()));
+                            }
+                            if (path.endsWith("/snapshot")) {
+                                events.add("head");
+                                Snapshot snapshot = head.get();
+                                return json(
+                                        new GetTableSnapshotResponse(
+                                                snapshot == null
+                                                        ? null
+                                                        : new 
TableSnapshot(snapshot, 0, 0, 0, 0)));
+                            }
+                            if (path.endsWith("/commit")) {
+                                CommitTableRequest commit =
+                                        fromJson(request, 
CommitTableRequest.class);
+                                Snapshot previous = head.get();
+                                String owner = leaseOwner.get();
+                                Snapshot snapshot = commit.getSnapshot();
+                                if ((owner != null && 
!owner.equals(snapshot.commitUser()))
+                                        || !Objects.equals(
+                                                commit.getBaseSnapshotUuid(),
+                                                previous == null ? null : 
previous.uuid())) {
+                                    return 
json(Collections.singletonMap("success", false));
+                                }
+                                events.add(
+                                        snapshot.commitKind() == 
Snapshot.CommitKind.APPEND
+                                                ? "append"
+                                                : "publish");
+                                head.set(snapshot);
+                                leaseOwner.set(null);
+                                return 
json(Collections.singletonMap("success", true));
+                            }
+                            if ("GET".equals(request.getMethod()) && 
!path.contains("/schemas/")) {
+                                return json(tableResponse);
+                            }
+                            return new MockResponse().setResponseCode(400);
+                        }
+                    });
+            server.start();
+            Options catalogOptions = new Options();
+            catalogOptions.set(RESTCatalogOptions.URI, 
server.url("/").toString());
+            catalogOptions.set(RESTCatalogOptions.TOKEN_PROVIDER, "bear");
+            catalogOptions.set(RESTCatalogOptions.TOKEN, "token");
+            catalogOptions.set(RESTTokenFileIO.DATA_TOKEN_ENABLED, false);
+            catalogOptions.set(RESTCatalogInternalOptions.PREFIX, "catalog");
+            try (RESTCatalog catalog =
+                    new RESTCatalog(CatalogContext.create(catalogOptions), 
false)) {
+                FileStoreTable table =
+                        (FileStoreTable) catalog.getTable(new Identifier("db", 
"table"));
+                tableRef.set(table);
+                new FileSystemSchemaManager(table.fileIO(), 
table.location()).createTable(schema);
+                appendRow(table.newBatchWriteBuilder(), 1, "a");
+                Snapshot target = head.get();
+                if (repairManifests) {
+                    String manifest =
+                            table.store()
+                                    .manifestListFactory()
+                                    .create()
+                                    .readDeltaManifests(target)
+                                    .get(0)
+                                    .fileName();
+                    
manifestToDelete.set(table.store().pathFactory().toManifestFilePath(manifest));
+                }
+
+                events.clear();
+                leaseOwner.set("append-writer");
+                if (repairManifests) {
+                    assertThat(new 
RemoveUnexistingManifests(table).execute()).isTrue();
+                } else {
+                    try (FileStoreCommit commit =
+                            table.store().newCommit("rollback-writer", table)) 
{
+                        assertThat(commit.rollbackToAsLatest(target)).isTrue();
+                    }
+                }
+                assertThat(events)
+                        .startsWith("busy")
+                        .containsSubsequence("append", "acquire", "head", 
"publish");
+                assertThat(head.get().id()).isEqualTo(target.id() + 2);
+                assertThat(head.get().totalRecordCount()).isEqualTo(1L);
+
+                List<Integer> values = new ArrayList<>();
+                ReadBuilder read = table.newReadBuilder();
+                try (RecordReader<InternalRow> reader =
+                        read.newRead().createReader(read.newScan().plan())) {
+                    reader.forEachRemaining(row -> values.add(row.getInt(0)));
+                }
+                assertThat(values).containsExactly(repairManifests ? 2 : 1);
+            }
+        }
+    }
+
     private static List<String> expected(boolean locking, boolean retry) {
         List<String> events = new ArrayList<>();
         for (int attempt = 0; attempt < (retry ? 2 : 1); attempt++) {
-            if (locking) {
+            if (locking && attempt > 0) {
                 events.add("acquire");
             }
             events.add("head");
@@ -458,6 +776,15 @@ class RESTCommitLockIntegrationTest {
         return events;
     }
 
+    private static void appendRow(BatchWriteBuilder builder, int id, String 
partition)
+            throws Exception {
+        try (BatchTableWrite write = builder.newWrite();
+                BatchTableCommit commit = builder.newCommit()) {
+            write.write(GenericRow.of(id, BinaryString.fromString(partition)));
+            commit.commit(write.prepareCommit());
+        }
+    }
+
     private static <T> T fromJson(RecordedRequest request, Class<T> type) {
         try {
             return RESTApi.fromJson(request.getBody().readUtf8(), type);

Reply via email to