OmniaGM commented on code in PR #23639:
URL: https://github.com/apache/kafka/pull/23639#discussion_r4541207766


##########
core/src/main/scala/kafka/zk/KafkaZkClient.scala:
##########
@@ -1764,11 +1764,48 @@ class KafkaZkClient private[zk] (
     initialState.withMigrationZkVersion(0)
   }
 
+  /**

Review Comment:
   Small one: this scaladoc still says the checker handles a 
`ConnectionLossException`. But it runs on any bad version, and a failed 
read-back now throws MigrationConflictException. Could we update it to describe 
that?



##########
core/src/test/scala/integration/kafka/zk/ZkMigrationFailoverTest.scala:
##########
@@ -102,6 +102,7 @@ class ZkMigrationFailoverTest extends Logging {
       .setInitialZkLoadHandler((_: MetadataPublisher) => {})
       .setZkMigrationClient(zkMigrationClient)
       .setFaultHandler(faultHandler)
+      .setMigrationConflictHandler((_: Int) => {})

Review Comment:
   I think this test can't catch conflicts on the new leader any more. 
Conflicts no longer go through `faultHandler`, and the handler here does 
nothing, so the `faultHandler2.checkAndClear(faults => 
assertTrue(faults.isEmpty))` checks would still pass if 3001 hit a conflict. 
Could we record the epochs passed to the conflict handler, return them from 
`buildMigrationDriver`, and assert they're empty for 3001 wherever we check 
`faultHandler2`? WDYT?



##########
core/src/main/scala/kafka/zk/KafkaZkClient.scala:
##########
@@ -1764,11 +1764,46 @@ class KafkaZkClient private[zk] (
     initialState.withMigrationZkVersion(0)
   }
 
+  /**
+   * When there is a ConnectionLossException while updating the /migration 
znode, the update may have actually succeeded
+   * on the server before the connection dropped, so the retried request can 
fail with BadVersionException even though
+   * our own write went through. This checker reads back the current data and, 
if its migration-relevant fields match
+   * what we intended to write, treats it as our own write having succeeded, 
returning the real current version.
+   */
+  private def checkMigrationStateZkData(
+                                         zkClient: KafkaZkClient,
+                                         path: String,
+                                         expectedData: Array[Byte]
+                                       ): (Boolean, Int) = {
+    try {
+      val (writtenDataOpt, writtenStat) = zkClient.getDataAndStat(path)
+      val expected = MigrationZNode.decode(expectedData, 
writtenStat.getVersion, -1)
+      val succeeded = writtenDataOpt.exists { writtenData =>
+        val written = MigrationZNode.decode(writtenData, 
writtenStat.getVersion, -1)
+        expected.kraftControllerId() == written.kraftControllerId() &&
+          expected.kraftControllerEpoch() == written.kraftControllerEpoch() &&
+          expected.kraftMetadataOffset() == written.kraftMetadataOffset() &&
+          expected.kraftMetadataEpoch() == written.kraftMetadataEpoch()
+      }
+      if (succeeded) (true, writtenStat.getVersion) else (false, 
ZkVersion.UnknownVersion)
+    } catch {
+      case _: Exception => (false, ZkVersion.UnknownVersion)
+    }
+  }
+
   def updateMigrationState(migrationState: ZkMigrationLeadershipState): 
ZkMigrationLeadershipState = {
-    val req = SetDataRequest(MigrationZNode.path, 
MigrationZNode.encode(migrationState), migrationState.migrationZkVersion())
-    val resp = retryRequestUntilConnected(req)
-    resp.maybeThrow()
-    migrationState.withMigrationZkVersion(resp.stat.getVersion)
+    val path = MigrationZNode.path
+    val data = MigrationZNode.encode(migrationState)
+    val expectedVersion = migrationState.migrationZkVersion()
+    val (succeeded, newVersion) = conditionalUpdatePath(
+      path, data, expectedVersion, Some(checkMigrationStateZkData))
+
+    if (succeeded && (expectedVersion == ZkVersion.MatchAnyVersion || 
expectedVersion + 1 == newVersion)) {
+      migrationState.withMigrationZkVersion(newVersion)

Review Comment:
   Thanks, agreed that stalling dual-write is worse. I followed what happens 
after the renounce: if the new leader still has the migration offset in memory, 
`getOrCreateMigrationRecoveryState` recreates `/migration` with it and 
`SYNC_KRAFT_TO_ZK` re-syncs ZK as you said. I believe a controller that has 
been a follower since before the migration finished would still have `-1` 
there, but in that case `WaitForControllerQuorumEvent` sees `MIGRATION` in 
KRaft but not in ZK and stays `INACTIVE` with an error, so it can't re-run the 
migration. Fine to keep as is, since this only happens if /migration is deleted.
   
   Small nit: for this case the message now reads Current zkVersion = -2. Could 
we say the znode is missing instead?



##########
metadata/src/main/java/org/apache/kafka/controller/QuorumController.java:
##########
@@ -1266,6 +1266,16 @@ public void processBatchEndOffset(long offset) {
         }
     }
 
+    public CompletableFuture<Void> forceRenounce() {
+        CompletableFuture<Void> future = new CompletableFuture<>();
+        appendControlEvent("forceRenounce", () -> {
+            if (isActiveController())
+                renounce();
+            future.complete(null);
+        });
+        return future;
+    }
+

Review Comment:
    Thanks, looks good. The in-flight epoch test is a nice addition.



##########
core/src/main/scala/kafka/server/ControllerServer.scala:
##########
@@ -304,6 +304,17 @@ class ControllerServer(
             fatal = false,
             () => {}
           ))
+          
.setMigrationConflictFaultHandler(sharedServer.faultHandlerFactory.build(
+            "zk migration conflict",
+            fatal = false,
+            () => {
+              try {
+                controller.forceRenounce().get(10, TimeUnit.SECONDS)
+              } catch {
+                case e: TimeoutException => 
sharedServer.fatalQuorumControllerFaultHandler.handleFault("Failed to renounce 
leadership", e)

Review Comment:
   Thanks for explaining, that makes sense. I hadn't considered that the 
controller keeps committing metadata while the driver is `INACTIVE`, so ZK 
keeps falling behind until a leader change. Agree the timeout is a reasonable 
fail-safe.



##########
core/src/main/scala/kafka/zk/KafkaZkClient.scala:
##########
@@ -1764,11 +1764,46 @@ class KafkaZkClient private[zk] (
     initialState.withMigrationZkVersion(0)
   }
 
+  /**
+   * When there is a ConnectionLossException while updating the /migration 
znode, the update may have actually succeeded
+   * on the server before the connection dropped, so the retried request can 
fail with BadVersionException even though
+   * our own write went through. This checker reads back the current data and, 
if its migration-relevant fields match
+   * what we intended to write, treats it as our own write having succeeded, 
returning the real current version.
+   */
+  private def checkMigrationStateZkData(
+                                         zkClient: KafkaZkClient,
+                                         path: String,
+                                         expectedData: Array[Byte]
+                                       ): (Boolean, Int) = {
+    try {
+      val (writtenDataOpt, writtenStat) = zkClient.getDataAndStat(path)
+      val expected = MigrationZNode.decode(expectedData, 
writtenStat.getVersion, -1)
+      val succeeded = writtenDataOpt.exists { writtenData =>
+        val written = MigrationZNode.decode(writtenData, 
writtenStat.getVersion, -1)
+        expected.kraftControllerId() == written.kraftControllerId() &&
+          expected.kraftControllerEpoch() == written.kraftControllerEpoch() &&
+          expected.kraftMetadataOffset() == written.kraftMetadataOffset() &&
+          expected.kraftMetadataEpoch() == written.kraftMetadataEpoch()
+      }
+      if (succeeded) (true, writtenStat.getVersion) else (false, 
ZkVersion.UnknownVersion)
+    } catch {
+      case _: Exception => (false, ZkVersion.UnknownVersion)

Review Comment:
    Thanks @mwesterby, that makes sense. I missed that nothing retries the 
`MetadataChangeEvent`, and that the next write would carry a newer offset, so 
the field check would fail anyway and report our own write as a conflict. 
Failing straight away with the read error as the cause is clearer.
   



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to