From 2863452733f1815ce5557ff01cfe148b49e182b0 Mon Sep 17 00:00:00 2001
From: Valery Kharseko <vharseko@3a-systems.ru>
Date: Mon, 30 Nov 2026 16:00:33 +0000
Subject: [PATCH] [#1208] Retry the discovery responder before declaring replication isolation (#1349)

---
 opendj-server-legacy/src/test/java/org/opends/server/crypto/RsaSveKeyTransportTestCase.java            |   19 +--
 opendj-server-legacy/src/main/java/org/opends/server/replication/service/ReplicationBroker.java        |   37 +++++--
 opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationBrokerStopTest.java |  209 ++++++++++++++++++++++++++++++++++++-----
 3 files changed, 216 insertions(+), 49 deletions(-)

diff --git a/opendj-server-legacy/src/main/java/org/opends/server/replication/service/ReplicationBroker.java b/opendj-server-legacy/src/main/java/org/opends/server/replication/service/ReplicationBroker.java
index 176c02d..5662bbd 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/replication/service/ReplicationBroker.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/replication/service/ReplicationBroker.java
@@ -49,6 +49,7 @@
 import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicReference;
 
 import net.jcip.annotations.GuardedBy;
@@ -192,7 +193,7 @@
   }
 
   /**
-   * A stop of the broker, from the moment {@link #stop()} begins until {@link #start()} clears it.
+   * A registered stop of the broker, kept until {@link #start()} clears it.
    * <p>
    * What a publish gives up for the stop is marked on the stop, and not on the broker: a publish
    * which found the stop past its deadline may mark it only after start() cleared it, and then the
@@ -266,9 +267,9 @@
   /** A backend whose state could not be restored must never reconnect through this broker. */
   private volatile boolean permanentlyStopped;
   /**
-   * The stop in progress: set by {@link #stop()} before anything else it does, and cleared to
-   * {@code null} by {@link #start()}. While it is set, a publish which finds no window credit by
-   * its deadline gives its message up instead of waiting on.
+   * The stop in progress, registered under {@link #startStopLock} and cleared to {@code null}
+   * by {@link #start()}. While it is set, a publish which finds no window credit by its deadline
+   * gives its message up instead of waiting on.
    * <p>
    * stop() publishes the replica offline message before it sets {@link #shutdown}, the flag which
    * ends the wait for credit, and that message needs credit too, and the lock of the pending
@@ -282,6 +283,8 @@
    */
   private volatile StopInProgress stopping;
   private final Object startStopLock = new Object();
+  /** Stop requests waiting for the lock are visible to the reconnect that holds it. */
+  private final AtomicInteger pendingStopRequests = new AtomicInteger();
   private volatile ReplicationDomainCfg config;
   /** String reported under CSN=monitor when there is no connected RS. */
   static final HostPort NO_CONNECTED_SERVER = new HostPort(null, 0);
@@ -1158,7 +1161,7 @@
         }
         computeNewTopology(toRSInfos(rsInfos));
 
-        final boolean canRetry = previousRS != null && stopping == null && !permanentlyStopped;
+        final boolean canRetry = previousRS != null && canRetryFailover();
         final boolean hasReplies = !rsInfos.isEmpty();
         String electedURL = null;
         if (hasReplies)
@@ -1242,7 +1245,7 @@
       discovery.close();
     }
     ConnectedRS electedRS = performPhaseOneHandshake(electedURL, true, canRetry);
-    if (electedRS.rsInfo == null && canRetry && stopping == null && !permanentlyStopped)
+    if (electedRS.rsInfo == null && canRetry && canRetryFailover())
     {
       electedRS = retryElectedConnection(discovery, rsInfos, electedURL, previousRS, electedRS);
     }
@@ -1288,7 +1291,7 @@
     final String timedOutRS = electedFormerRS && responder == null ? discovery.timedOutServer(previousRS) : null;
     discovery.close();
 
-    if (stopping != null || permanentlyStopped)
+    if (!canRetryFailover())
     {
       return failure;
     }
@@ -1304,6 +1307,11 @@
     return failure;
   }
 
+  private boolean canRetryFailover()
+  {
+    return pendingStopRequests.get() == 0 && stopping == null && !permanentlyStopped;
+  }
+
   /** Opens the selected RS session using the fresh state returned by its start reply. */
   private void finishElectedConnection(ConnectedRS electedRS, Map<Integer, ReplicationServerInfo> rsInfos)
   {
@@ -1333,7 +1341,12 @@
 
   private ConnectedRS connectToDiscoveryResponder(ReplicationServerInfo responder)
   {
-    final ConnectedRS replacement = performPhaseOneHandshake(responder.getServerURL(), true, false);
+    final String url = responder.getServerURL();
+    ConnectedRS replacement = performPhaseOneHandshake(url, true, true);
+    if (replacement == ConnectedRS.START_REPLY_TIMED_OUT && canRetryFailover())
+    {
+      replacement = performPhaseOneHandshake(url, true, false);
+    }
     // The generation may have changed since discovery.
     if (replacement.rsInfo != null && !hasCompatibleGeneration(replacement.rsInfo))
     {
@@ -3556,8 +3569,12 @@
     }
     final StopInProgress stop;
     final boolean newStop;
-    synchronized (startStopLock) {
-      if (shutdown) {
+    pendingStopRequests.incrementAndGet();
+    synchronized (startStopLock)
+    {
+      pendingStopRequests.decrementAndGet();
+      if (shutdown)
+      {
         return;
       }
       // A stop which overlaps one in progress keeps its deadlines and what it gave up.
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/crypto/RsaSveKeyTransportTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/crypto/RsaSveKeyTransportTestCase.java
index af31ca5..10f7b10 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/crypto/RsaSveKeyTransportTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/crypto/RsaSveKeyTransportTestCase.java
@@ -120,19 +120,18 @@
   @Test
   public void testAnotherPrivateKeyCannotUnwrap() throws Exception
   {
-    KeyPair other;
-    do
-    {
-      other = rsaKeyPair(2048);
-    }
-    while (modulus(other).compareTo(modulus(keyPair)) <= 0);
-    final KeyPair otherKeyPair = other;
+    final KeyPair secondKeyPair = rsaKeyPair(2048);
+    final int modulusOrder = modulus(keyPair).compareTo(modulus(secondKeyPair));
+    assertThat(modulusOrder).as("the two RSA moduli must differ").isNotZero();
+    final KeyPair wrappingKeyPair = modulusOrder < 0 ? keyPair : secondKeyPair;
+    final KeyPair wrongKeyPair = modulusOrder < 0 ? secondKeyPair : keyPair;
     final SecretKey key = new SecretKeySpec(bytes(16, 0x3C), "AES");
     inProviders(BC_FIPS, () ->
     {
-      final byte[] wrapped = RsaSveKeyTransport.wrap(keyPair.getPublic(), key, KEY_ID, random);
-      assertThatThrownBy(() -> RsaSveKeyTransport.unwrap(otherKeyPair, wrapped, "AES", KEY_ID))
-          .isInstanceOf(GeneralSecurityException.class);
+      final byte[] wrapped = RsaSveKeyTransport.wrap(wrappingKeyPair.getPublic(), key, KEY_ID, random);
+      assertThatThrownBy(() -> RsaSveKeyTransport.unwrap(wrongKeyPair, wrapped, "AES", KEY_ID))
+          .isInstanceOf(InvalidKeyException.class)
+          .hasMessage(RsaSveKeyTransport.NAME + " cannot unwrap the key");
       return null;
     });
   }
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationBrokerStopTest.java b/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationBrokerStopTest.java
index ab8284a..8b93bf1 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationBrokerStopTest.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationBrokerStopTest.java
@@ -178,6 +178,8 @@
     TestCaseUtils.initializeTestBackend(true);
     setConnectionTimeout(LONG_CONNECTION_TIMEOUT_MS);
     final WithholdingReplicationServer rs = new WithholdingReplicationServer();
+    final DSRSShutdownSync shutdownSync = shutdownSync();
+    CSN previousAnnouncement = null;
     Thread disabling = null;
     try
     {
@@ -186,9 +188,21 @@
       // The only credit of the window goes to a change of our own.
       assertEquals(replaceDescription("first"), ResultCode.SUCCESS);
       rs.waitForUpdates(1);
+      final CSN firstChange = rs.receivedUpdateCSNs().get(0);
+      // The previous domain used the same clock tick and had a higher sequence number.
+      previousAnnouncement = new CSN(firstChange.getTime(), firstChange.getSeqnum() + 2, DS_ID);
+      final CompletableFuture<CSN> announcementAtFirstProbe = new CompletableFuture<>();
+      rs.onFirstWindowProbe = () -> {
+        announcementAtFirstProbe.complete(offlineAnnouncementOfTheReplica());
+        return null;
+      };
+      shutdownSync.replicaOfflineMsgSent(baseDN, previousAnnouncement);
 
       final long beforeTheDisable = System.nanoTime();
       disabling = startThread("disable", domain::disable);
+      final CSN stopAnnouncement = announcementAtFirstProbe.get(10, SECONDS);
+      assertNotNull(stopAnnouncement, "the stop must announce going offline before waiting for credit");
+      assertFalse(previousAnnouncement.equals(stopAnnouncement), "the stop must announce its own CSN");
       disabling.join(stopBoundMS());
       final long disableMS = NANOSECONDS.toMillis(System.nanoTime() - beforeTheDisable);
       assertFalse(disabling.isAlive(),
@@ -199,17 +213,24 @@
       assertEquals(rs.count(ReplicaOfflineMsg.class), 0, "the replica offline message was written with no credit");
       assertEquals(rs.count(StopMsg.class), 1, "the session was closed as a failed one, not ended in order");
 
-      /* The grace period of the announcement has run out by now, so whether the shutdown of a
-       * collocated replication server would wait for it says nothing: what is left announced does.
-       * An announcement older than the change is one of an earlier stop of the replica. */
-      final CSN announced = offlineAnnouncementOfTheReplica();
-      assertTrue(announced == null || !announced.isNewerThan(rs.receivedUpdateCSNs().get(0)),
-          "the replica offline message given up is still announced: " + announced);
+      final CSN remainingAnnouncement = offlineAnnouncementOfTheReplica();
+      assertTrue(remainingAnnouncement == null || previousAnnouncement.equals(remainingAnnouncement),
+          "expected the stop to withdraw " + stopAnnouncement + ", but found " + remainingAnnouncement);
     }
     finally
     {
-      cleanUp(rs, disabling);
-      setConnectionTimeout(SHORT_CONNECTION_TIMEOUT_MS);
+      try
+      {
+        cleanUp(rs, disabling);
+      }
+      finally
+      {
+        if (previousAnnouncement != null)
+        {
+          shutdownSync.replicaOfflineMsgNotSent(baseDN, previousAnnouncement);
+        }
+        setConnectionTimeout(SHORT_CONNECTION_TIMEOUT_MS);
+      }
     }
   }
 
@@ -1386,15 +1407,20 @@
     }
   }
 
-  @Test(timeOut = 120_000)
-  public void failoverTriesAnotherDiscoveryResponderWhenTheFormerRsRefusesConnection() throws Exception
+  @DataProvider
+  public Object[][] discoveryResponderStartReplyTimeouts()
+  {
+    return new Object[][] { { 0 }, { 1 } };
+  }
+
+  @Test(dataProvider = "discoveryResponderStartReplyTimeouts", timeOut = 120_000)
+  public void failoverTriesAnotherDiscoveryResponderWhenTheFormerRsRefusesConnection(int timedOutReplies)
+      throws Exception
   {
     TestCaseUtils.initializeTestBackend(true);
     final WithholdingReplicationServer former = new WithholdingReplicationServer(LARGE_WINDOW);
     final WithholdingReplicationServer survivor = new WithholdingReplicationServer(LARGE_WINDOW, 4);
-    final AtomicInteger survivorStarts = new AtomicInteger();
-    final CountDownLatch survivorRetry = new CountDownLatch(1);
-    final CountDownLatch finishRetry = new CountDownLatch(1);
+    final DelayedFailoverHandshake handshake = new DelayedFailoverHandshake(1, timedOutReplies);
     try
     {
       survivor.differentGroup = true;
@@ -1416,19 +1442,13 @@
         former.listenSocket.close();
         return null;
       };
-      survivor.beforeStartReply = () -> {
-        if (survivorStarts.incrementAndGet() == 2)
-        {
-          survivorRetry.countDown();
-          await(finishRetry);
-        }
-        return null;
-      };
+      survivor.delayedFailoverHandshake = handshake;
       former.closeTheSession();
 
-      await(survivorRetry);
-      assertFalse(domain.hasConnectionError(), "the broker declared isolation before trying the discovery responder");
-      finishRetry.countDown();
+      await(handshake.nextStartReceived);
+      assertFalse(domain.hasConnectionError(),
+          "the broker declared isolation before connecting to the discovery responder");
+      handshake.sendNextReply.countDown();
       newTimer().repeatUntilSuccess(() -> {
         assertEquals(domain.getRsServerId(), survivor.serverId);
         assertFalse(domain.hasConnectionError());
@@ -1436,11 +1456,12 @@
       assertEquals(replaceDescription("after failover to the discovery responder"), ResultCode.SUCCESS);
       survivor.waitForUpdates(2);
       assertEquals(survivor.receivedUpdateCSNs(), List.of(beforeFailover, domain.getServerState().getCSN(DS_ID)));
-      assertEquals(survivorStarts.get(), 2, "the survivor must receive one discovery probe and one session start");
+      assertEquals(handshake.starts.get(), 2 + timedOutReplies,
+          "the survivor must receive one discovery probe and the expected session starts");
     }
     finally
     {
-      finishRetry.countDown();
+      handshake.sendNextReply.countDown();
       try
       {
         survivor.shutdown();
@@ -1453,6 +1474,121 @@
   }
 
   @Test(timeOut = 120_000)
+  public void queuedStopSkipsTheDiscoveryResponderRetry() throws Exception
+  {
+    TestCaseUtils.initializeTestBackend(true);
+    setConnectionTimeout(LONG_CONNECTION_TIMEOUT_MS);
+    final WithholdingReplicationServer former = new WithholdingReplicationServer(LARGE_WINDOW);
+    final WithholdingReplicationServer responder = new WithholdingReplicationServer(LARGE_WINDOW, 4);
+    final DelayedFailoverHandshake handshake = new DelayedFailoverHandshake(1, 1);
+    Thread stopping = null;
+    try
+    {
+      responder.differentGroup = true;
+      responder.start();
+      final LDAPReplicationDomain domain = startDomain(former, 100000, responder.getAddress());
+      final ReplicationBroker broker = brokerOf(domain);
+      assertEquals(domain.getRsServerId(), former.serverId);
+      assertEquals(replaceDescription("elect the former replication server at failover"), ResultCode.SUCCESS);
+      former.waitForUpdates(1);
+
+      responder.differentGroup = false;
+      former.beforeStartReply = () -> {
+        former.listenSocket.close();
+        return null;
+      };
+      responder.delayedFailoverHandshake = handshake;
+      handshake.sendNextReply.countDown();
+      former.closeTheSession();
+
+      newTimer().repeatUntilSuccess(() -> assertEquals(handshake.starts.get(), 2,
+          "the responder must be withholding its first session start reply"));
+      final Thread stop = startThread("stop during the responder's start handshake", broker::stop);
+      stopping = stop;
+      newTimer().repeatUntilSuccess(() -> assertTrue(
+          stop.getState() == Thread.State.BLOCKED && isIn(stop, ReplicationBroker.class, "stop"),
+          "stop must be waiting for the reconnect to release its lock"));
+      stop.join(stopBoundMS());
+      assertFalse(stop.isAlive(), "stop did not finish after the first start reply timed out");
+      assertEquals(handshake.starts.get(), 2, "the broker retried the responder with a stop queued");
+    }
+    finally
+    {
+      try
+      {
+        responder.shutdown();
+      }
+      finally
+      {
+        cleanUp(former, stopping);
+        setConnectionTimeout(SHORT_CONNECTION_TIMEOUT_MS);
+      }
+    }
+  }
+
+  @Test(timeOut = 120_000)
+  public void queuedStopSkipsTheFallbackAfterContinuedDiscovery() throws Exception
+  {
+    TestCaseUtils.initializeTestBackend(true);
+    final WithholdingReplicationServer former = new WithholdingReplicationServer(LARGE_WINDOW);
+    final WithholdingReplicationServer responder = new WithholdingReplicationServer(LARGE_WINDOW, 4);
+    final DelayedFailoverHandshake handshake = new DelayedFailoverHandshake(0, 0);
+    Thread stopping = null;
+    try
+    {
+      setConnectionTimeout(LONG_CONNECTION_TIMEOUT_MS);
+      responder.differentGroup = true;
+      responder.start();
+      final LDAPReplicationDomain domain = startDomain(former, 100000, responder.getAddress());
+      final ReplicationBroker broker = brokerOf(domain);
+      assertEquals(domain.getRsServerId(), former.serverId);
+      newTimer().repeatUntilSuccess(() -> assertNotNull(former.session.get()));
+
+      responder.differentGroup = false;
+      responder.delayedFailoverHandshake = handshake;
+      former.beforeStartReply = () -> {
+        former.listenSocket.close();
+        return null;
+      };
+      former.dropTheSession();
+
+      await(handshake.nextStartReceived);
+      newTimer().repeatUntilSuccess(() -> assertTrue(Thread.getAllStackTraces().keySet().stream()
+          .anyMatch(thread -> waitsIn(thread, ReplicationBroker.class, "retryElectedConnection")),
+          "the broker must be waiting for the responder in continued discovery"));
+      final Thread stop = startThread("stop during continued discovery", broker::stop);
+      stopping = stop;
+      newTimer().repeatUntilSuccess(() -> assertTrue(
+          stop.getState() == Thread.State.BLOCKED && isIn(stop, ReplicationBroker.class, "stop"),
+          "stop must be waiting for the reconnect to release its lock"));
+
+      handshake.sendNextReply.countDown();
+      stop.join(stopBoundMS());
+      assertFalse(stop.isAlive(), "stop did not finish after the discovery reply");
+      assertEquals(handshake.starts.get(), 1, "the responder must receive only the discovery probe");
+    }
+    finally
+    {
+      handshake.sendNextReply.countDown();
+      try
+      {
+        responder.shutdown();
+      }
+      finally
+      {
+        try
+        {
+          cleanUp(former, stopping);
+        }
+        finally
+        {
+          setConnectionTimeout(SHORT_CONNECTION_TIMEOUT_MS);
+        }
+      }
+    }
+  }
+
+  @Test(timeOut = 120_000)
   public void reconnectClosesTheSessionWhenTopologyTimesOut() throws Exception
   {
     TestCaseUtils.initializeTestBackend(true);
@@ -2377,17 +2513,22 @@
     return false;
   }
 
+  private static DSRSShutdownSync shutdownSync() throws Exception
+  {
+    final Field shutdownSync = MultimasterReplication.class.getDeclaredField("dsrsShutdownSync");
+    shutdownSync.setAccessible(true);
+    return (DSRSShutdownSync) shutdownSync.get(null);
+  }
+
   /**
    * Returns the CSN of the announcement that the replica of the domain went offline which the
    * shutdown of a collocated replication server would wait for the forward of, if there is one.
    */
   private CSN offlineAnnouncementOfTheReplica() throws Exception
   {
-    final Field shutdownSync = MultimasterReplication.class.getDeclaredField("dsrsShutdownSync");
-    shutdownSync.setAccessible(true);
     final Field announcements = DSRSShutdownSync.class.getDeclaredField("replicaOfflineMsgs");
     announcements.setAccessible(true);
-    final Map<?, ?> byDomain = (Map<?, ?>) announcements.get(shutdownSync.get(null));
+    final Map<?, ?> byDomain = (Map<?, ?>) announcements.get(shutdownSync());
     final Map<?, ?> byReplica = (Map<?, ?>) byDomain.get(baseDN);
     final Object announcement = byReplica != null ? byReplica.get(DS_ID) : null;
     if (announcement == null)
@@ -2535,6 +2676,7 @@
     /** Whether this server is away: it then sends no heartbeat, and answers no connection either. */
     private volatile boolean away;
     private volatile Callable<Void> beforeStartReply;
+    private volatile Callable<Void> onFirstWindowProbe;
     /** If set, read from the next session after StartSessionMsg instead of sending its topology. */
     private final AtomicReference<CompletableFuture<ReplicationMsg>> readInsteadOfSendingTopology =
         new AtomicReference<>();
@@ -2694,6 +2836,15 @@
           {
             lastOffline = (ReplicaOfflineMsg) msg;
           }
+          else if (msg instanceof WindowProbeMsg)
+          {
+            final Callable<Void> onProbe = onFirstWindowProbe;
+            if (onProbe != null)
+            {
+              onFirstWindowProbe = null;
+              onProbe.call();
+            }
+          }
         }
       }
       catch (Exception e)

--
Gitblit v1.10.0