You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@fluss.apache.org by "zcoo (via GitHub)" <gi...@apache.org> on 2026/03/03 06:56:33 UTC

[PR] [server] Coordinator Server Supports High-Available [fluss]

zcoo opened a new pull request, #2781:
URL: https://github.com/apache/fluss/pull/2781

   <!--
   *Thank you very much for contributing to Fluss - we are happy that you want to help us improve Fluss. To help the community review your contribution in the best possible way, please go through the checklist below, which will get the contribution into a shape in which it can be best reviewed.*
   
   ## Contribution Checklist
   
     - Make sure that the pull request corresponds to a [GitHub issue](https://github.com/apache/fluss/issues). Exceptions are made for typos in JavaDoc or documentation files, which need no issue.
   
     - Name the pull request in the format "[component] Title of the pull request", where *[component]* should be replaced by the name of the component being changed. Typically, this corresponds to the component label assigned to the issue (e.g., [kv], [log], [client], [flink]). Skip *[component]* if you are unsure about which is the best component.
   
     - Fill out the template below to describe the changes contributed by the pull request. That will give reviewers the context they need to do the review.
   
     - Make sure that the change passes the automated tests, i.e., `mvn clean verify` passes.
   
     - Each pull request should address only one issue, not mix up code from multiple issues.
   
   
   **(The sections below can be removed for hotfixes or typos)**
   -->
   
   ### Purpose
   
   <!-- Linking this pull request to the issue -->
   Linked issue: close #2778
   
   <!-- What is the purpose of the change -->
   
   ### Brief change log
   see https://cwiki.apache.org/confluence/display/FLUSS/FIP-9%3A+Support+CoordinatorServer+High+Availability
   
   <!-- Please describe the changes made in this pull request and explain how they address the issue -->
   
   ### Tests
   
   <!-- List UT and IT cases to verify this change -->
   
   ### API and Format
   
   <!-- Does this change affect API or storage format -->
   
   ### Documentation
   
   <!-- Does this change introduce a new feature -->
   


-- 
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


Re: [PR] [Feature] Coordinator Server Supports coordinator epoch protect [fluss]

Posted by "wuchong (via GitHub)" <gi...@apache.org>.
wuchong commented on code in PR #2781:
URL: https://github.com/apache/fluss/pull/2781#discussion_r3035276900


##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/MetadataManager.java:
##########
@@ -337,7 +338,9 @@ public void completeDeleteTable(long tableId) {
         // delete bucket assignments node, which will also delete the bucket state node,
         // so that all the zk nodes related to this table are deleted.
         rethrowIfIsNotNoNodeException(
-                () -> zookeeperClient.deleteTableAssignment(tableId),
+                () ->
+                        zookeeperClient.deleteTableAssignment(
+                                tableId, ZkVersion.MATCH_ANY_VERSION.getVersion()),

Review Comment:
   This async cleanup can run after delete work has already been queued.
   Passing MATCH_ANY_VERSION disables coordinator epoch fencing, so a stale coordinator can still delete the table-assignment znode after leadership changes. We should pass in the coordinator zk version for a safe deletion. The coordiantor zk version can be got from CoordinatorContext when calling MetadataManager. 



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/MetadataManager.java:
##########
@@ -399,7 +404,8 @@ public long createTable(
                     long tableId = zookeeperClient.getTableIdAndIncrement();
                     if (tableAssignment != null) {
                         // register table assignment
-                        zookeeperClient.registerTableAssignment(tableId, tableAssignment);
+                        zookeeperClient.registerTableAssignment(
+                                tableId, tableAssignment, ZkVersion.MATCH_ANY_VERSION.getVersion());

Review Comment:
   ditto



##########
fluss-server/src/main/java/org/apache/fluss/server/zk/ZooKeeperClient.java:
##########
@@ -127,11 +129,19 @@
 
 import static java.util.stream.Collectors.toMap;
 import static org.apache.fluss.metadata.ResolvedPartitionSpec.fromPartitionName;
+import static org.apache.fluss.server.zk.ZooKeeperOp.multiRequest;
 import static org.apache.fluss.utils.Preconditions.checkNotNull;
 
 /**
  * This class includes methods for write/read various metadata (leader address, tablet server
  * registration, table assignment, table, schema) in Zookeeper.
+ *
+ * <p>In some method, 'expectedZkVersion' is used to execute an epoch Zookeeper version check. We
+ * have the following principals to judge if it's necessary to execute epoch Zookeeper version
+ * check. If all condition met, we need to execute epoch Zookeeper version check. 1. The method
+ * create/modify/delete Zk node. 2. It's executed by coordinator server. 3. It is about
+ * metadata(table/partition/leaderAndIsr) rather than server info or ACL info. 4. The Zk node is
+ * persistent rather than ephemeral.

Review Comment:
   I think current epoch check is not clear about which type of operations should be added epoch check. I think not all zk nodes need the epoch check, only the assignment and LeaderAndIsr nodes need. So, could you update the principles with following? 
   
   
   ```
   Conditions requiring epoch checks (all must be met):
   ┌─────────────────────────────────────────────────────────┐
   │ 1. Invoked by the Coordinator (not the TabletServer)    │
   │ 2. Operates on persistent nodes (not ephemeral)         │
   │ 3. Constitutes a "control plane" operation:             │
   │    partition assignment or LeaderAndIsr election        │
   │ 4. Concurrent access to the same path by old and new    │
   │    leaders during leader failover                       │
   │ 5. No other mechanisms (optimistic locking,             │
   │    idempotency, or reloading) provide fallback          │
   └─────────────────────────────────────────────────────────┘
   
   In practice, only two types of operations truly require this:
   - CRUD for Table/Partition Assignment (assignment decisions).
   - CRUD for LeaderAndIsr (leader election results).
   
   These operations are inevitably executed concurrently by the old and new coordinators during failover (as the new leader immediately reassigns partitions), and overwrites cannot be automatically recovered.
   
   All other operations do not require epoch checks because:
   - DDL operations are protected against concurrency by client reconnection mechanisms.
   - TabletServer operations are unaffected by coordinator failovers.
   - ACLs and Configs have their own version control or idempotency guarantees.
   - Ephemeral nodes are managed via session lifecycle.
   ```



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/MetadataManager.java:
##########
@@ -346,7 +349,9 @@ public void completeDeletePartition(long partitionId) {
         // delete partition assignments node, which will also delete the bucket state node,
         // so that all the zk nodes related to this partition are deleted.
         rethrowIfIsNotNoNodeException(
-                () -> zookeeperClient.deletePartitionAssignment(partitionId),
+                () ->
+                        zookeeperClient.deletePartitionAssignment(
+                                partitionId, ZkVersion.MATCH_ANY_VERSION.getVersion()),

Review Comment:
   ditto, we need the true zk version here. 



##########
fluss-server/src/main/java/org/apache/fluss/server/zk/ZooKeeperClient.java:
##########
@@ -197,6 +209,43 @@ public void registerCoordinatorServer(CoordinatorAddress coordinatorAddress) thr
         LOG.info("Registered Coordinator server {} at path {}.", coordinatorAddress, path);
     }
 
+    /**
+     * Become coordinator leader. This method is a step after electCoordinatorLeader() and before
+     * registerCoordinatorLeader(). This is to ensure the coordinator get and update the coordinator
+     * epoch and coordinator epoch zk version.
+     */
+    public Optional<ZkEpoch> fenceBecomeCoordinatorLeader(String coordinatorId) throws Exception {
+        ensureEpochZnodeExists();
+
+        try {
+            ZkEpoch getEpoch = getCurrentEpoch();
+            int currentCoordinatorEpoch = getEpoch.getCoordinatorEpoch();
+            int currentCoordinatorEpochZkVersion = getEpoch.getCoordinatorEpochZkVersion();
+            int newCoordinatorEpoch = currentCoordinatorEpoch + 1;
+            LOG.info(
+                    "Coordinator leader {} tries to update epoch. Current epoch={}, Zookeeper version={}, new epoch={}",
+                    coordinatorId,
+                    currentCoordinatorEpoch,
+                    currentCoordinatorEpochZkVersion,
+                    newCoordinatorEpoch);
+
+            // atomically update epoch
+            zkClient.setData()
+                    .withVersion(currentCoordinatorEpochZkVersion)
+                    .forPath(
+                            ZkData.CoordinatorEpochZNode.path(),
+                            ZkData.CoordinatorEpochZNode.encode(newCoordinatorEpoch));
+
+            return Optional.of(getEpoch.nextZkEpoch());

Review Comment:
   The `ZkEpoch.nextZkEpoch()` simply increments ZK version by exactly 1. While this is guaranteed by ZK spec for a successful conditional `setData`, it would be more defensive to capture
   the `Stat` returned by `setData()`.
   
   
   ```java
   Stat stat =
                       zkClient.setData()
                               .withVersion(currentCoordinatorEpochZkVersion)
                               .forPath(
                                       ZkData.CoordinatorEpochZNode.path(),
                                       ZkData.CoordinatorEpochZNode.encode(newCoordinatorEpoch));
   
               return Optional.of(new ZkEpoch(newCoordinatorEpoch, stat.getVersion()));
   ```



##########
fluss-server/src/main/java/org/apache/fluss/server/zk/ZooKeeperClient.java:
##########
@@ -346,15 +428,16 @@ public void updatePartitionAssignment(long partitionId, PartitionAssignment part
                 partitionId);
     }
 
-    public void deleteTableAssignment(long tableId) throws Exception {
+    public void deleteTableAssignment(long tableId, int expectedZkVersion) throws Exception {
         String path = TableIdZNode.path(tableId);
-        zkClient.delete().deletingChildrenIfNeeded().forPath(path);
+        deleteRecursiveWithEpochCheck(path, expectedZkVersion, false);
         LOG.info("Deleted table assignment for table id {}.", tableId);
     }
 
-    public void deletePartitionAssignment(long partitionId) throws Exception {
+    public void deletePartitionAssignment(long partitionId, int expectedZkVersion)
+            throws Exception {
         String path = PartitionIdZNode.path(partitionId);
-        zkClient.delete().deletingChildrenIfNeeded().forPath(path);
+        deleteRecursiveWithEpochCheck(path, expectedZkVersion, false);

Review Comment:
   `deleteTableAssignment` and `deletePartitionAssignment` don't need epoch check. The only production caller is `MetadataManager.completeDeleteTable/completeDeletePartition`, which already passes `MATCH_ANY_VERSION` — so the epoch check is effectively a no-op today.
   
   More importantly, these are **idempotent cleanup operations** at the end of the DDL delete flow. By the time they're called, all replicas are already in `DeletionSuccessful` state. Even if a stale coordinator executes this cleanup, it won't corrupt any live metadata — the table/partition is already marked for deletion, and the new leader won't recreate the assignment for it.
   
   Since epoch check provides no safety benefit here, I'd suggest removing the `expectedZkVersion` parameter from these two methods and reverting to the original `zkClient.delete().deletingChildrenIfNeeded().forPath(path)`. This avoids the significant performance overhead of `deleteRecursiveWithEpochCheck` (which turns 1 ZK call into O(2N) calls for a path with N children) without sacrificing correctness.
   
   If we can remove epoch check on these 2 methods, we can also remove the `deleteRecursiveWithEpochCheck()` method. 
   



##########
fluss-server/src/test/java/org/apache/fluss/server/testutils/FlussClusterExtension.java:
##########
@@ -200,6 +200,10 @@ public void afterEach(ExtensionContext extensionContext) throws Exception {
             }
         }
         CompletableFuture.allOf(dropFutures.toArray(new CompletableFuture[0])).join();
+
+        for (TabletServer tabletServer : tabletServers.values()) {
+            tabletServer.getReplicaManager().resetCoordinatorEpoch();

Review Comment:
   Why is it necessary to manually reset the coordinator epoch? Would tests fail if this step were omitted? Since there are no coordinator restarts before or after each test, the coordinator epoch should remain unchanged. Even in the event of a coordinator restart, the TabletServer should receive the updated coordinator epoch via `UpdateMetadata`, rendering manual epoch resets unnecessary.



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorContext.java:
##########
@@ -709,11 +720,12 @@ private void clearTablesState() {
     public void resetContext() {
         tablesToBeDeleted.clear();
         coordinatorEpoch = 0;

Review Comment:
   nit: use `INITIAL_COORDINATOR_EPOCH` like how you updated `coordinatorEpochZkVersion`.



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorLeaderElection.java:
##########
@@ -122,7 +130,25 @@ public void isLeader() {
                                                 e);
                                     }
                                     try {
+                                        // to avoid split-brain
+                                        Optional<ZkEpoch> optionalEpoch =
+                                                zkClient.fenceBecomeCoordinatorLeader(serverId);
+                                        optionalEpoch.ifPresent(
+                                                integer ->
+                                                        coordinatorContext
+                                                                .setCoordinatorEpochAndZkVersion(
+                                                                        optionalEpoch
+                                                                                .get()
+                                                                                .getCoordinatorEpoch(),
+                                                                        optionalEpoch
+                                                                                .get()
+                                                                                .getCoordinatorEpochZkVersion()));
                                         initLeaderServices.run();
+                                    } catch (CoordinatorEpochFencedException e) {

Review Comment:
   The catch block below is dead code because `fenceBecomeCoordinatorLeader()` never throws `CoordinatorEpochFencedException` -- it returns `Optional.empty()` on `BadVersionException` instead.



##########
fluss-server/src/main/java/org/apache/fluss/server/zk/ZooKeeperClient.java:
##########
@@ -471,18 +565,21 @@ public void batchUpdateLeaderAndIsr(Map<TableBucket, LeaderAndIsr> leaderAndIsrL
             CuratorOp updateOp = zkClient.transactionOp().setData().forPath(path, data);
             ops.add(updateOp);
             if (ops.size() == MAX_BATCH_SIZE) {
-                zkClient.transaction().forOperations(ops);
+                List<CuratorOp> wrapOps = wrapRequestsWithEpochCheck(ops, expectedZkVersion);
+                zkClient.transaction().forOperations(wrapOps);
                 ops.clear();
             }
         }
         if (!ops.isEmpty()) {
-            zkClient.transaction().forOperations(ops);
+            List<CuratorOp> wrapOps = wrapRequestsWithEpochCheck(ops, expectedZkVersion);
+            zkClient.transaction().forOperations(wrapOps);
         }
     }
 
-    public void deleteLeaderAndIsr(TableBucket tableBucket) throws Exception {
+    public void deleteLeaderAndIsr(TableBucket tableBucket, int expectedZkVersion)

Review Comment:
   `deleteLeaderAndIsr` is only used in test, so we don't need epoch check, and we can change the visible modifier to `protected`. 



##########
fluss-server/src/main/java/org/apache/fluss/server/zk/ZooKeeperClient.java:
##########


Review Comment:
   `updatePartitionAssignment` is not epoch-fenced, A stale coordinator can overwrite partition assignments after leadership changes.



##########
fluss-server/src/main/java/org/apache/fluss/server/zk/ZooKeeperClient.java:
##########
@@ -274,13 +352,13 @@ public int[] getSortedTabletServerList() throws Exception {
     // --------------------------------------------------------------------------------------------
 
     /** Register table assignment to ZK. */
-    public void registerTableAssignment(long tableId, TableAssignment tableAssignment)
-            throws Exception {
+    public void registerTableAssignment(
+            long tableId, TableAssignment tableAssignment, int expectedZkVersion) throws Exception {

Review Comment:
   This is a special case that we don't need the epoch check, because it is only invoked when table creation and the unique tableId can has natural concurrent guard (table ID conflicts, node existence).



##########
fluss-server/src/test/java/org/apache/fluss/server/zk/ZooKeeperClientTest.java:
##########
@@ -193,23 +197,26 @@ void testLeaderAndIsr() throws Exception {
         assertThat(zookeeperClient.getLeaderAndIsr(tableBucket2)).isEmpty();
 
         // try to register bucket leaderAndIsr
-        LeaderAndIsr leaderAndIsr1 = new LeaderAndIsr(1, 10, Arrays.asList(1, 2, 3), 100, 1000);
-        LeaderAndIsr leaderAndIsr2 = new LeaderAndIsr(2, 10, Arrays.asList(4, 5, 6), 100, 1000);
+        LeaderAndIsr leaderAndIsr1 = new LeaderAndIsr(1, 10, Arrays.asList(1, 2, 3), 0, 1000);
+        LeaderAndIsr leaderAndIsr2 = new LeaderAndIsr(2, 10, Arrays.asList(4, 5, 6), 0, 1000);
 
-        zookeeperClient.registerLeaderAndIsr(tableBucket1, leaderAndIsr1);
-        zookeeperClient.registerLeaderAndIsr(tableBucket2, leaderAndIsr2);
+        zookeeperClient.registerLeaderAndIsr(
+                tableBucket1, leaderAndIsr1, ZkVersion.MATCH_ANY_VERSION.getVersion());
+        zookeeperClient.registerLeaderAndIsr(
+                tableBucket2, leaderAndIsr2, ZkVersion.MATCH_ANY_VERSION.getVersion());

Review Comment:
   It appears that all tests involving ZK epoch versions currently use `MATCH_ANY_VERSION`, which fails to validate the behavior of the production code. I suggest creating the ZK epoch node in `beforeAll()` and using the actual ZK epoch version in the test logic to ensure accurate verification.



-- 
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


Re: [PR] [Feature] Coordinator Server Supports coordinator epoch protect [fluss]

Posted by "zcoo (via GitHub)" <gi...@apache.org>.
zcoo commented on PR #2781:
URL: https://github.com/apache/fluss/pull/2781#issuecomment-4207340259

   @wuchong @swuferhong Thanks for all your comments. Now they are all addressed. PLAT~


-- 
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


Re: [PR] [Feature] Coordinator Server Supports coordinator epoch protect [fluss]

Posted by "wuchong (via GitHub)" <gi...@apache.org>.
wuchong merged PR #2781:
URL: https://github.com/apache/fluss/pull/2781


-- 
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


Re: [PR] [Feature] Coordinator Server Supports coordinator epoch protect [fluss]

Posted by "swuferhong (via GitHub)" <gi...@apache.org>.
swuferhong commented on code in PR #2781:
URL: https://github.com/apache/fluss/pull/2781#discussion_r2945691319


##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorServer.java:
##########
@@ -259,6 +288,12 @@ protected void startServices() throws Exception {
                     new AutoPartitionManager(metadataCache, metadataManager, conf);
             autoPartitionManager.start();
 
+            int ioExecutorPoolSize = conf.get(ConfigOptions.COORDINATOR_IO_POOL_SIZE);
+            this.ioExecutor =
+                    Executors.newFixedThreadPool(
+                            ioExecutorPoolSize, new ExecutorThreadFactory("coordinator-io"));
+

Review Comment:
   `ioExecutor` is initialized twice; it was already serialized once previously. This will cause the first thread pool to never be shutdown.



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorLeaderElection.java:
##########
@@ -0,0 +1,177 @@
+/*
+ * 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.exception.CoordinatorEpochFencedException;
+import org.apache.fluss.server.zk.ZkEpoch;
+import org.apache.fluss.server.zk.ZooKeeperClient;
+import org.apache.fluss.server.zk.data.ZkData;
+import org.apache.fluss.shaded.curator5.org.apache.curator.framework.recipes.leader.LeaderLatch;
+import org.apache.fluss.shaded.curator5.org.apache.curator.framework.recipes.leader.LeaderLatchListener;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/** Using by coordinator server. Coordinator servers listen ZK node and elect leadership. */
+public class CoordinatorLeaderElection implements AutoCloseable {
+    private static final Logger LOG = LoggerFactory.getLogger(CoordinatorLeaderElection.class);
+
+    private final int serverId;
+    private final ZooKeeperClient zkClient;
+    private final CoordinatorContext coordinatorContext;
+    private final LeaderLatch leaderLatch;
+    private final AtomicBoolean isLeader = new AtomicBoolean(false);
+    private final CompletableFuture<Void> leaderReadyFuture = new CompletableFuture<>();
+    private volatile Thread electionThread;
+
+    public CoordinatorLeaderElection(
+            ZooKeeperClient zkClient, int serverId, CoordinatorContext coordinatorContext) {
+        this.serverId = serverId;
+        this.zkClient = zkClient;
+        this.coordinatorContext = coordinatorContext;
+        this.leaderLatch =
+                new LeaderLatch(
+                        zkClient.getCuratorClient(),
+                        ZkData.CoordinatorElectionZNode.path(),
+                        String.valueOf(serverId));
+    }
+
+    /**
+     * Starts the leader election process asynchronously. The returned future completes when this
+     * server becomes the leader and initializes the leader services.
+     *
+     * @param initLeaderServices the runnable to initialize leader services once elected
+     * @return a CompletableFuture that completes when this server becomes leader
+     */
+    public CompletableFuture<Void> startElectLeaderAsync(Runnable initLeaderServices) {
+        leaderLatch.addListener(
+                new LeaderLatchListener() {
+                    @Override
+                    public void isLeader() {
+                        LOG.info("Coordinator server {} has become the leader.", serverId);
+                        isLeader.set(true);
+                    }
+
+                    @Override
+                    public void notLeader() {
+                        relinquishLeadership();
+                        LOG.warn("Coordinator server {} has lost the leadership.", serverId);
+                    }
+                });
+
+        try {
+            leaderLatch.start();
+            LOG.info("Coordinator server {} started leader election.", serverId);
+        } catch (Exception e) {
+            LOG.error("Failed to start LeaderLatch for server {}", serverId, e);
+            leaderReadyFuture.completeExceptionally(
+                    new RuntimeException("Leader election start failed", e));
+            return leaderReadyFuture;
+        }
+
+        // Run the await and initialization in a separate thread to avoid blocking
+        electionThread =
+                new Thread(
+                        () -> {
+                            try {
+                                // todo: Currently, we await the leader latch and do nothing until
+                                // it becomes leader.
+                                // Later we can make it as a hot backup server to continuously
+                                // synchronize metadata from
+                                // Zookeeper, which save time from recovering context
+                                leaderLatch.await();
+                                doInitLeaderServices(initLeaderServices);
+                                leaderReadyFuture.complete(null);
+                            } catch (InterruptedException e) {
+                                Thread.currentThread().interrupt();
+                                LOG.info(
+                                        "Leader election for server {} was interrupted.", serverId);
+                                leaderReadyFuture.completeExceptionally(e);
+                            } catch (Exception e) {
+                                LOG.error(
+                                        "Failed during leader election for server {}", serverId, e);
+                                leaderReadyFuture.completeExceptionally(e);
+                            }
+                        },
+                        "coordinator-leader-election-" + serverId);
+        electionThread.start();
+
+        return leaderReadyFuture;
+    }
+
+    public void doInitLeaderServices(Runnable initLeaderServices) {
+        try {
+            // to avoid split-brain
+            Optional<ZkEpoch> optionalEpoch = zkClient.fenceBecomeCoordinatorLeader(serverId);
+            optionalEpoch.ifPresent(

Review Comment:
    The handling when returning `Optional.empty()` here is problematic? When `BadVersionException` is caught,
       `fenceBecomeCoordinatorLeader` returns `Optional.empty()`, but `doInitLeaderServices` only relinquishes leadership on
       `CoordinatorEpochFencedException`. If the epoch update fails (returning empty), the code continues to execute
       `initLeaderServices.run()`, causing a coordinator that did not successfully acquire the epoch to still run as a leader, which may result in a split-brain.



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorContext.java:
##########
@@ -67,6 +68,7 @@ public class CoordinatorContext {
     // a success deletion.
     private final Map<TableBucketReplica, Integer> failDeleteNumbers = new HashMap<>();
 
+    private final Set<Integer> liveCoordinatorServers = new HashSet<>();

Review Comment:
   `resetContext()` need to clear `liveCoordinatorServers`?  also need to clear `coordinatorEpochZkVersion`.



##########
fluss-server/src/main/java/org/apache/fluss/server/zk/ZooKeeperClient.java:
##########
@@ -178,20 +189,105 @@ public Optional<byte[]> getOrEmpty(String path) throws Exception {
     // Coordinator server
     // --------------------------------------------------------------------------------------------
 
-    /** Register a coordinator leader server to ZK. */
+    /** Register a coordinator server to ZK. */
+    public void registerCoordinatorServer(int coordinatorId) throws Exception {
+        String path = ZkData.CoordinatorIdZNode.path(coordinatorId);
+        zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path);
+        LOG.info("Registered Coordinator server {} at path {}.", coordinatorId, path);
+    }
+
+    /**
+     * Become coordinator leader. This method is a step after electCoordinatorLeader() and before
+     * registerCoordinatorLeader(). This is to ensure the coordinator get and update the coordinator
+     * epoch and coordinator epoch zk version.
+     */
+    public Optional<ZkEpoch> fenceBecomeCoordinatorLeader(int coordinatorId) throws Exception {
+        ensureEpochZnodeExists();
+
+        try {
+            ZkEpoch getEpoch = getCurrentEpoch();
+            int currentCoordinatorEpoch = getEpoch.getCoordinatorEpoch();
+            int currentCoordinatorEpochZkVersion = getEpoch.getCoordinatorEpochZkVersion();
+            int newCoordinatorEpoch = currentCoordinatorEpoch + 1;
+            LOG.info(
+                    "Coordinator leader {} tries to update epoch. Current epoch={}, Zookeeper version={}, new epoch={}",
+                    coordinatorId,
+                    currentCoordinatorEpoch,
+                    currentCoordinatorEpochZkVersion,
+                    newCoordinatorEpoch);
+
+            // atomically update epoch
+            zkClient.setData()
+                    .withVersion(currentCoordinatorEpochZkVersion)
+                    .forPath(
+                            ZkData.CoordinatorEpochZNode.path(),
+                            ZkData.CoordinatorEpochZNode.encode(newCoordinatorEpoch));
+
+            return Optional.of(getEpoch.nextZkEpoch());
+        } catch (KeeperException.BadVersionException e) {
+            // Other coordinator leader has updated epoch.
+            // If this happens, it means our fence is in effect.
+            LOG.info("Coordinator leader {} failed to update epoch.", coordinatorId);
+        }
+
+        return Optional.empty();
+    }
+
+    /** Register a coordinator leader to ZK. */
     public void registerCoordinatorLeader(CoordinatorAddress coordinatorAddress) throws Exception {
-        String path = CoordinatorZNode.path();
+        String path = ZkData.CoordinatorLeaderZNode.path();
         zkClient.create()
                 .creatingParentsIfNeeded()
                 .withMode(CreateMode.EPHEMERAL)
-                .forPath(path, CoordinatorZNode.encode(coordinatorAddress));
-        LOG.info("Registered leader {} at path {}.", coordinatorAddress, path);
+                .forPath(path, ZkData.CoordinatorLeaderZNode.encode(coordinatorAddress));
+        LOG.info("Registered Coordinator leader {} at path {}.", coordinatorAddress, path);
     }
 
     /** Get the leader address registered in ZK. */
-    public Optional<CoordinatorAddress> getCoordinatorAddress() throws Exception {
-        Optional<byte[]> bytes = getOrEmpty(CoordinatorZNode.path());
-        return bytes.map(CoordinatorZNode::decode);
+    public Optional<CoordinatorAddress> getCoordinatorLeaderAddress() throws Exception {
+        Optional<byte[]> bytes = getOrEmpty(ZkData.CoordinatorLeaderZNode.path());
+        return bytes.map(
+                data ->
+                        // maybe an empty node when a leader is elected but not registered
+                        data.length == 0 ? null : ZkData.CoordinatorLeaderZNode.decode(data));
+    }
+
+    /** Gets the list of coordinator server Ids. */
+    public int[] getCoordinatorServerList() throws Exception {
+        List<String> coordinatorServers = getChildren(ZkData.CoordinatorIdsZNode.path());
+        return coordinatorServers.stream().mapToInt(Integer::parseInt).toArray();
+    }
+
+    /** Ensure epoch znode exists. */
+    public void ensureEpochZnodeExists() throws Exception {
+        String path = ZkData.CoordinatorEpochZNode.path();
+        if (zkClient.checkExists().forPath(path) == null) {

Review Comment:
    If two `coordinators` execute almost simultaneously and both pass `checkExists == null`, the first one creates successfully, while the second one will throw `NodeExistsException` which is wrapped as `RuntimeException` causing startup failure. So I think `NodeExistsException` should be ignored here, not thrown `RuntimeException`.



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorLeaderElection.java:
##########
@@ -0,0 +1,177 @@
+/*
+ * 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.exception.CoordinatorEpochFencedException;
+import org.apache.fluss.server.zk.ZkEpoch;
+import org.apache.fluss.server.zk.ZooKeeperClient;
+import org.apache.fluss.server.zk.data.ZkData;
+import org.apache.fluss.shaded.curator5.org.apache.curator.framework.recipes.leader.LeaderLatch;
+import org.apache.fluss.shaded.curator5.org.apache.curator.framework.recipes.leader.LeaderLatchListener;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/** Using by coordinator server. Coordinator servers listen ZK node and elect leadership. */
+public class CoordinatorLeaderElection implements AutoCloseable {
+    private static final Logger LOG = LoggerFactory.getLogger(CoordinatorLeaderElection.class);
+
+    private final int serverId;
+    private final ZooKeeperClient zkClient;
+    private final CoordinatorContext coordinatorContext;
+    private final LeaderLatch leaderLatch;
+    private final AtomicBoolean isLeader = new AtomicBoolean(false);
+    private final CompletableFuture<Void> leaderReadyFuture = new CompletableFuture<>();
+    private volatile Thread electionThread;
+
+    public CoordinatorLeaderElection(
+            ZooKeeperClient zkClient, int serverId, CoordinatorContext coordinatorContext) {
+        this.serverId = serverId;
+        this.zkClient = zkClient;
+        this.coordinatorContext = coordinatorContext;
+        this.leaderLatch =
+                new LeaderLatch(
+                        zkClient.getCuratorClient(),
+                        ZkData.CoordinatorElectionZNode.path(),
+                        String.valueOf(serverId));
+    }
+
+    /**
+     * Starts the leader election process asynchronously. The returned future completes when this
+     * server becomes the leader and initializes the leader services.
+     *
+     * @param initLeaderServices the runnable to initialize leader services once elected
+     * @return a CompletableFuture that completes when this server becomes leader
+     */
+    public CompletableFuture<Void> startElectLeaderAsync(Runnable initLeaderServices) {
+        leaderLatch.addListener(
+                new LeaderLatchListener() {
+                    @Override
+                    public void isLeader() {
+                        LOG.info("Coordinator server {} has become the leader.", serverId);
+                        isLeader.set(true);
+                    }
+
+                    @Override
+                    public void notLeader() {
+                        relinquishLeadership();
+                        LOG.warn("Coordinator server {} has lost the leadership.", serverId);
+                    }
+                });
+
+        try {
+            leaderLatch.start();
+            LOG.info("Coordinator server {} started leader election.", serverId);
+        } catch (Exception e) {
+            LOG.error("Failed to start LeaderLatch for server {}", serverId, e);
+            leaderReadyFuture.completeExceptionally(
+                    new RuntimeException("Leader election start failed", e));
+            return leaderReadyFuture;
+        }
+
+        // Run the await and initialization in a separate thread to avoid blocking
+        electionThread =
+                new Thread(
+                        () -> {
+                            try {
+                                // todo: Currently, we await the leader latch and do nothing until
+                                // it becomes leader.
+                                // Later we can make it as a hot backup server to continuously
+                                // synchronize metadata from
+                                // Zookeeper, which save time from recovering context
+                                leaderLatch.await();
+                                doInitLeaderServices(initLeaderServices);
+                                leaderReadyFuture.complete(null);
+                            } catch (InterruptedException e) {
+                                Thread.currentThread().interrupt();
+                                LOG.info(
+                                        "Leader election for server {} was interrupted.", serverId);
+                                leaderReadyFuture.completeExceptionally(e);
+                            } catch (Exception e) {
+                                LOG.error(
+                                        "Failed during leader election for server {}", serverId, e);
+                                leaderReadyFuture.completeExceptionally(e);
+                            }
+                        },
+                        "coordinator-leader-election-" + serverId);
+        electionThread.start();
+
+        return leaderReadyFuture;
+    }
+
+    public void doInitLeaderServices(Runnable initLeaderServices) {
+        try {
+            // to avoid split-brain
+            Optional<ZkEpoch> optionalEpoch = zkClient.fenceBecomeCoordinatorLeader(serverId);
+            optionalEpoch.ifPresent(
+                    integer ->
+                            coordinatorContext.setCoordinatorEpochAndZkVersion(
+                                    optionalEpoch.get().getCoordinatorEpoch(),
+                                    optionalEpoch.get().getCoordinatorEpochZkVersion()));
+        } catch (CoordinatorEpochFencedException e) {
+            relinquishLeadership();
+            LOG.warn(
+                    "Coordinator server {} has been fence and not become leader successfully.",

Review Comment:
   `has been fence` -> `has been fenced`.



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorLeaderElection.java:
##########
@@ -0,0 +1,177 @@
+/*
+ * 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.exception.CoordinatorEpochFencedException;
+import org.apache.fluss.server.zk.ZkEpoch;
+import org.apache.fluss.server.zk.ZooKeeperClient;
+import org.apache.fluss.server.zk.data.ZkData;
+import org.apache.fluss.shaded.curator5.org.apache.curator.framework.recipes.leader.LeaderLatch;
+import org.apache.fluss.shaded.curator5.org.apache.curator.framework.recipes.leader.LeaderLatchListener;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/** Using by coordinator server. Coordinator servers listen ZK node and elect leadership. */
+public class CoordinatorLeaderElection implements AutoCloseable {
+    private static final Logger LOG = LoggerFactory.getLogger(CoordinatorLeaderElection.class);
+
+    private final int serverId;
+    private final ZooKeeperClient zkClient;
+    private final CoordinatorContext coordinatorContext;
+    private final LeaderLatch leaderLatch;
+    private final AtomicBoolean isLeader = new AtomicBoolean(false);
+    private final CompletableFuture<Void> leaderReadyFuture = new CompletableFuture<>();
+    private volatile Thread electionThread;
+
+    public CoordinatorLeaderElection(
+            ZooKeeperClient zkClient, int serverId, CoordinatorContext coordinatorContext) {
+        this.serverId = serverId;
+        this.zkClient = zkClient;
+        this.coordinatorContext = coordinatorContext;
+        this.leaderLatch =
+                new LeaderLatch(
+                        zkClient.getCuratorClient(),
+                        ZkData.CoordinatorElectionZNode.path(),
+                        String.valueOf(serverId));
+    }
+
+    /**
+     * Starts the leader election process asynchronously. The returned future completes when this
+     * server becomes the leader and initializes the leader services.
+     *
+     * @param initLeaderServices the runnable to initialize leader services once elected
+     * @return a CompletableFuture that completes when this server becomes leader
+     */
+    public CompletableFuture<Void> startElectLeaderAsync(Runnable initLeaderServices) {
+        leaderLatch.addListener(
+                new LeaderLatchListener() {
+                    @Override
+                    public void isLeader() {
+                        LOG.info("Coordinator server {} has become the leader.", serverId);
+                        isLeader.set(true);
+                    }
+
+                    @Override
+                    public void notLeader() {
+                        relinquishLeadership();
+                        LOG.warn("Coordinator server {} has lost the leadership.", serverId);
+                    }
+                });
+
+        try {
+            leaderLatch.start();
+            LOG.info("Coordinator server {} started leader election.", serverId);
+        } catch (Exception e) {
+            LOG.error("Failed to start LeaderLatch for server {}", serverId, e);
+            leaderReadyFuture.completeExceptionally(
+                    new RuntimeException("Leader election start failed", e));
+            return leaderReadyFuture;
+        }
+
+        // Run the await and initialization in a separate thread to avoid blocking
+        electionThread =
+                new Thread(
+                        () -> {
+                            try {
+                                // todo: Currently, we await the leader latch and do nothing until
+                                // it becomes leader.
+                                // Later we can make it as a hot backup server to continuously
+                                // synchronize metadata from
+                                // Zookeeper, which save time from recovering context
+                                leaderLatch.await();
+                                doInitLeaderServices(initLeaderServices);
+                                leaderReadyFuture.complete(null);
+                            } catch (InterruptedException e) {
+                                Thread.currentThread().interrupt();
+                                LOG.info(
+                                        "Leader election for server {} was interrupted.", serverId);
+                                leaderReadyFuture.completeExceptionally(e);
+                            } catch (Exception e) {
+                                LOG.error(
+                                        "Failed during leader election for server {}", serverId, e);
+                                leaderReadyFuture.completeExceptionally(e);
+                            }
+                        },
+                        "coordinator-leader-election-" + serverId);
+        electionThread.start();
+
+        return leaderReadyFuture;
+    }
+
+    public void doInitLeaderServices(Runnable initLeaderServices) {

Review Comment:
   private ? 



-- 
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


Re: [PR] [Feature] Coordinator Server Supports coordinator epoch protect [fluss]

Posted by "wuchong (via GitHub)" <gi...@apache.org>.
wuchong commented on PR #2781:
URL: https://github.com/apache/fluss/pull/2781#issuecomment-4212545286

   This commit fixes a **race condition in leader election** and **refactors coordinator epoch to be immutable**.
   
   ### Key Changes
   
   - **`CoordinatorLeaderElection`**: Moved `isLeader.set(true)` from **before** to **after** `initLeaderServices.run()`, preventing the coordinator from accepting requests before initialization completes. Removed unnecessary `zkClient` and `coordinatorContext` fields.
   
   - **`CoordinatorContext`**: Made `coordinatorEpoch` and `coordinatorEpochZkVersion` **final** fields initialized via `ZkEpoch` in the constructor. Removed the mutable setter. Renamed `getCoordinatorEpochZkVersion()` → `getCoordinatorZkVersion()`.
   
   - **`CoordinatorServer`**: `CoordinatorContext` is now created **locally** in `initCoordinatorLeader()` per election cycle instead of being a long-lived server field. Removed redundant `resetContext()` calls from cleanup/close paths.
   
   - **`CoordinatorEventProcessor`**: Removed `ZkEpoch` constructor parameter (epoch now comes via `CoordinatorContext`). Added `resetContext()` in `close()`.
   
   - **`ReplicaManager`**: Added `getCoordinatorEpoch()` getter and epoch update logging; removed `resetCoordinatorEpoch()`.
   
   - **`ZkEpoch`**: Added `INITIAL_EPOCH` constant for test convenience.
   
   - **`ZooKeeperClient`**: Fixed Javadoc formatting (inline text → `<pre>` and `<ul>` blocks).
   
   - **Tests**: Deleted `TestCoordinatorContext`; updated HA tests to `waitUntil` leader is ready (since `isLeader` is now set after init); replaced manual `UpdateMetadataRequest` workaround with natural epoch propagation wait.
   - **ITCase**: Updated `CoordinatorHighAvailabilityITCase#testTabletServerRejectsStaleCoordinatorEpochAfterLeaderSwitch` to update the coordinator epoch of TabletServer by coordinator itself, rather than manually update it in IT case. 
   


-- 
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


Re: [PR] [Feature] Coordinator Server Supports coordinator epoch protect [fluss]

Posted by "wuchong (via GitHub)" <gi...@apache.org>.
wuchong commented on code in PR #2781:
URL: https://github.com/apache/fluss/pull/2781#discussion_r3035093684


##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorLeaderElection.java:
##########
@@ -122,7 +130,25 @@ public void isLeader() {
                                                 e);
                                     }
                                     try {
+                                        // to avoid split-brain
+                                        Optional<ZkEpoch> optionalEpoch =
+                                                zkClient.fenceBecomeCoordinatorLeader(serverId);
+                                        optionalEpoch.ifPresent(
+                                                integer ->
+                                                        coordinatorContext
+                                                                .setCoordinatorEpochAndZkVersion(
+                                                                        optionalEpoch
+                                                                                .get()
+                                                                                .getCoordinatorEpoch(),
+                                                                        optionalEpoch
+                                                                                .get()
+                                                                                .getCoordinatorEpochZkVersion()));
                                         initLeaderServices.run();
+                                    } catch (CoordinatorEpochFencedException e) {
+                                        LOG.warn(
+                                                "Coordinator server {} has been fenced and not become leader successfully.",
+                                                serverId);
+                                        throw e;

Review Comment:
   When encountering a `FencedException`, we need to transition the current coordinator back to the standby state, for example, by invoking `notLeader()`.



##########
fluss-common/src/main/java/org/apache/fluss/config/ConfigOptions.java:
##########
@@ -392,6 +392,12 @@ public class ConfigOptions {
                                     + " (“50100,50101”), ranges (“50100-50200”) or a combination of both."
                                     + "This option is deprecated. Please use bind.listeners instead, which provides a more flexible configuration for multiple ports");
 
+    public static final ConfigOption<Integer> COORDINATOR_ID =

Review Comment:
   unused, remove



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorEventProcessor.java:
##########


Review Comment:
   this partitioned-table reassignment path still updates ZK without a coordinator epoch / version check, so a fenced coordinator can overwrite `/partitionIds/<partitionId>` after leadership changes.



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorLeaderElection.java:
##########
@@ -122,7 +130,25 @@ public void isLeader() {
                                                 e);
                                     }
                                     try {
+                                        // to avoid split-brain
+                                        Optional<ZkEpoch> optionalEpoch =
+                                                zkClient.fenceBecomeCoordinatorLeader(serverId);
+                                        optionalEpoch.ifPresent(
+                                                integer ->
+                                                        coordinatorContext
+                                                                .setCoordinatorEpochAndZkVersion(
+                                                                        optionalEpoch
+                                                                                .get()
+                                                                                .getCoordinatorEpoch(),
+                                                                        optionalEpoch
+                                                                                .get()
+                                                                                .getCoordinatorEpochZkVersion()));

Review Comment:
   The `coordinatorContext` is not thread-safe and must only be updated and accessed within the `CoordinatorEventProcessor`. Since `leaderCallbackExecutor` operates on an asynchronous thread, mutating the context there violates thread safety. 
   
   To resolve this, move the `zkClient.fenceBecomeCoordinatorLeader` call into `org.apache.fluss.server.coordinator.CoordinatorServer#initCoordinatorLeader`, placing it before the synchronized lock block. Similarly, move `registerCoordinatorLeader()` before the synchronized block. Capture the `ZkEpoch` returned by `fenceBecomeCoordinatorLeader` and pass it to the `CoordinatorEventProcessor` constructor to represent the current leader epoch. 
   
   This allows `CoordinatorEventProcessor.startup()` to safely initialize `CoordinatorContext` with the `ZkEpoch`, as the operation remains within the single-threaded execution scope of the processor.



-- 
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


Re: [PR] [Feature] Coordinator Server Supports coordinator epoch protect [fluss]

Posted by "wuchong (via GitHub)" <gi...@apache.org>.
wuchong commented on code in PR #2781:
URL: https://github.com/apache/fluss/pull/2781#discussion_r3035277072


##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/MetadataManager.java:
##########
@@ -346,7 +349,9 @@ public void completeDeletePartition(long partitionId) {
         // delete partition assignments node, which will also delete the bucket state node,
         // so that all the zk nodes related to this partition are deleted.
         rethrowIfIsNotNoNodeException(
-                () -> zookeeperClient.deletePartitionAssignment(partitionId),
+                () ->
+                        zookeeperClient.deletePartitionAssignment(
+                                partitionId, ZkVersion.MATCH_ANY_VERSION.getVersion()),

Review Comment:
   ditto, we need the true zk version here. 



##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/MetadataManager.java:
##########
@@ -399,7 +404,8 @@ public long createTable(
                     long tableId = zookeeperClient.getTableIdAndIncrement();
                     if (tableAssignment != null) {
                         // register table assignment
-                        zookeeperClient.registerTableAssignment(tableId, tableAssignment);
+                        zookeeperClient.registerTableAssignment(
+                                tableId, tableAssignment, ZkVersion.MATCH_ANY_VERSION.getVersion());

Review Comment:
   ditto



-- 
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


Re: [PR] [Feature] Coordinator Server Supports coordinator epoch protect [fluss]

Posted by "wuchong (via GitHub)" <gi...@apache.org>.
wuchong commented on code in PR #2781:
URL: https://github.com/apache/fluss/pull/2781#discussion_r3035276900


##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/MetadataManager.java:
##########
@@ -337,7 +338,9 @@ public void completeDeleteTable(long tableId) {
         // delete bucket assignments node, which will also delete the bucket state node,
         // so that all the zk nodes related to this table are deleted.
         rethrowIfIsNotNoNodeException(
-                () -> zookeeperClient.deleteTableAssignment(tableId),
+                () ->
+                        zookeeperClient.deleteTableAssignment(
+                                tableId, ZkVersion.MATCH_ANY_VERSION.getVersion()),

Review Comment:
   This async cleanup can run after delete work has already been queued.
   Passing MATCH_ANY_VERSION disables coordinator epoch fencing, so a stale coordinator can still delete the table-assignment znode after leadership changes. We should pass in the coordinator zk version for a safe deletion. The coordiantor zk version can be got from CoordinatorContext when calling MetadataManager. 



-- 
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


Re: [PR] [Feature] Coordinator Server Supports coordinator epoch protect [fluss]

Posted by "zcoo (via GitHub)" <gi...@apache.org>.
zcoo commented on code in PR #2781:
URL: https://github.com/apache/fluss/pull/2781#discussion_r3049780653


##########
fluss-server/src/main/java/org/apache/fluss/server/zk/ZooKeeperClient.java:
##########
@@ -127,11 +129,19 @@
 
 import static java.util.stream.Collectors.toMap;
 import static org.apache.fluss.metadata.ResolvedPartitionSpec.fromPartitionName;
+import static org.apache.fluss.server.zk.ZooKeeperOp.multiRequest;
 import static org.apache.fluss.utils.Preconditions.checkNotNull;
 
 /**
  * This class includes methods for write/read various metadata (leader address, tablet server
  * registration, table assignment, table, schema) in Zookeeper.
+ *
+ * <p>In some method, 'expectedZkVersion' is used to execute an epoch Zookeeper version check. We
+ * have the following principals to judge if it's necessary to execute epoch Zookeeper version
+ * check. If all condition met, we need to execute epoch Zookeeper version check. 1. The method
+ * create/modify/delete Zk node. 2. It's executed by coordinator server. 3. It is about
+ * metadata(table/partition/leaderAndIsr) rather than server info or ACL info. 4. The Zk node is
+ * persistent rather than ephemeral.

Review Comment:
   yes thank you for detailed description



-- 
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


Re: [PR] [Feature] Coordinator Server Supports coordinator epoch protect [fluss]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #2781:
URL: https://github.com/apache/fluss/pull/2781#discussion_r3035045013


##########
fluss-server/src/main/java/org/apache/fluss/server/zk/ZooKeeperClient.java:
##########
@@ -127,11 +129,19 @@
 
 import static java.util.stream.Collectors.toMap;
 import static org.apache.fluss.metadata.ResolvedPartitionSpec.fromPartitionName;
+import static org.apache.fluss.server.zk.ZooKeeperOp.multiRequest;
 import static org.apache.fluss.utils.Preconditions.checkNotNull;
 
 /**
  * This class includes methods for write/read various metadata (leader address, tablet server
  * registration, table assignment, table, schema) in Zookeeper.
+ *
+ * <p>In some method, 'expectedZkVersion' is used to execute an epoch Zookeeper version check. We
+ * have the following principals to judge if it's necessary to execute epoch Zookeeper version

Review Comment:
   Spelling: "principals" should be "principles" in the class-level JavaDoc describing the epoch version check rules.
   ```suggestion
    * have the following principles to judge if it's necessary to execute epoch Zookeeper version
   ```



##########
fluss-server/src/main/java/org/apache/fluss/server/zk/ZooKeeperClient.java:
##########
@@ -1781,6 +1878,109 @@ public static <K> Map<K, List<String>> processGetChildrenResponses(
         return result;
     }
 
+    /**
+     * create a node (recursively if parent path not exists) with Zk epoch version check.
+     *
+     * @param path the path to create
+     * @param data the data to write
+     * @param throwIfPathExists whether to throw exception if path exist
+     * @throws Exception if any error occurs
+     */
+    public void createRecursiveWithEpochCheck(
+            String path, byte[] data, int expectedZkVersion, boolean throwIfPathExists)
+            throws Exception {
+        CuratorOp createOp = zkOp.createOp(path, data, CreateMode.PERSISTENT);

Review Comment:
   `createRecursiveWithEpochCheck` recursively calls itself with `data = null` for parent paths, but `ZooKeeperOp.createOp(...).forPath(path, data)` typically expects a non-null byte array. This can cause NPE/IAE during parent creation. Consider using Curator's create builder that omits data for parent nodes (or pass an explicit empty byte array) and only attach `data` to the final target node.
   ```suggestion
           byte[] nodeData = data == null ? new byte[0] : data;
           CuratorOp createOp = zkOp.createOp(path, nodeData, CreateMode.PERSISTENT);
   ```



##########
fluss-server/src/main/java/org/apache/fluss/server/zk/ZooKeeperClient.java:
##########
@@ -1781,6 +1878,109 @@ public static <K> Map<K, List<String>> processGetChildrenResponses(
         return result;
     }
 
+    /**
+     * create a node (recursively if parent path not exists) with Zk epoch version check.
+     *
+     * @param path the path to create
+     * @param data the data to write
+     * @param throwIfPathExists whether to throw exception if path exist
+     * @throws Exception if any error occurs
+     */
+    public void createRecursiveWithEpochCheck(
+            String path, byte[] data, int expectedZkVersion, boolean throwIfPathExists)
+            throws Exception {
+        CuratorOp createOp = zkOp.createOp(path, data, CreateMode.PERSISTENT);
+        List<CuratorOp> ops = wrapRequestWithEpochCheck(createOp, expectedZkVersion);
+
+        try {
+            // try to directly create
+            zkClient.transaction().forOperations(ops);
+        } catch (KeeperException.NodeExistsException e) {
+            // should not exist
+            if (throwIfPathExists) {
+                throw e;
+            }
+        } catch (KeeperException.NoNodeException e) {
+            // if parent does not exist, create parent first
+            int indexOfLastSlash = path.lastIndexOf("/");
+            if (indexOfLastSlash == -1) {
+                throw new IllegalArgumentException("Invalid path: " + path);
+            } else if (indexOfLastSlash == 0) {
+                // root path can be directly create without fence
+                try {
+                    zkClient.create()
+                            .creatingParentsIfNeeded()
+                            .withMode(CreateMode.PERSISTENT)
+                            .forPath(path);
+                } catch (KeeperException.NodeExistsException ignored) {
+                    // ignore
+                }
+            } else {
+                // indexOfLastSlash > 0
+                String parentPath = path.substring(0, indexOfLastSlash);
+                createRecursiveWithEpochCheck(
+                        parentPath, null, expectedZkVersion, throwIfPathExists);

Review Comment:
   `createRecursiveWithEpochCheck` propagates `throwIfPathExists` into the recursive parent creation call. If `throwIfPathExists` is true for the leaf node, this will also throw when *parent* paths already exist, which breaks the usual contract of recursive-create (only the target path should be subject to the existence check). Consider passing `false` when creating parent paths, and applying `throwIfPathExists` only to the final `path` creation attempt.
   ```suggestion
                   createRecursiveWithEpochCheck(parentPath, null, expectedZkVersion, false);
   ```



##########
fluss-server/src/main/java/org/apache/fluss/server/zk/data/ZkData.java:
##########
@@ -366,6 +366,24 @@ public static CoordinatorAddress decode(byte[] json) {
         }
     }
 
+    /**
+     * The znode for the coordinator epoch. The znode path is:
+     *
+     * <p>/coordinators/epoch
+     */
+    public static final class CoordinatorEpochZNode {
+        public static String path() {
+            return "/coordinators/epoch";
+        }
+
+        public static byte[] encode(int epoch) {
+            return String.valueOf(epoch).getBytes();
+        }
+
+        public static int decode(byte[] bytes) {
+            return Integer.parseInt(new String(bytes));

Review Comment:
   `CoordinatorEpochZNode.encode/decode` uses the platform default charset via `String.getBytes()` / `new String(bytes)`, which can be non-deterministic across environments. Prefer an explicit charset (e.g., UTF-8) for stable encoding/decoding of ZK node contents.
   ```suggestion
               return String.valueOf(epoch).getBytes(StandardCharsets.UTF_8);
           }
   
           public static int decode(byte[] bytes) {
               return Integer.parseInt(new String(bytes, StandardCharsets.UTF_8));
   ```



-- 
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


Re: [PR] [Feature] Coordinator Server Supports coordinator epoch protect [fluss]

Posted by "zcoo (via GitHub)" <gi...@apache.org>.
zcoo commented on PR #2781:
URL: https://github.com/apache/fluss/pull/2781#issuecomment-4211546824

   @wuchong To improve test coverage for coordinator epoch propagation to TabletServer/Zookeeper after leader switch, I just add 2 test cases in CoordinatorHighAvailabilityITCase:
   ```
   testTabletServerRejectsStaleCoordinatorEpochAfterLeaderSwitch
   testZooKeeperRejectsStaleCoordinatorRequestAfterLeaderSwitch
   ```


-- 
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


Re: [PR] [Feature] Coordinator Server Supports coordinator epoch protect [fluss]

Posted by "zcoo (via GitHub)" <gi...@apache.org>.
zcoo commented on PR #2781:
URL: https://github.com/apache/fluss/pull/2781#issuecomment-4211200521

   @wuchong We already have test case to ensure tablet server only accepts request from coordinator leader.
   see `testLeaderLosesLeadershipAndReElected
   `
   Additionally, I add a test case to ensure Zookeeper only accepts request from coordinator leader, while stale will get a KeeperException.BadVersionException
   
   > Missing test coverage for coordinator epoch propagation to TabletServer after leader switch
   
   


-- 
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