From 52694d4c03f9b09b2e52f389701255f3c78dfd9b Mon Sep 17 00:00:00 2001
From: Valery Kharseko <vharseko@3a-systems.ru>
Date: Mon, 30 Nov 2026 08:18:21 +0000
Subject: [PATCH] Bound replication server discovery during failover (#1346)

---
 opendj-server-legacy/src/main/java/org/opends/server/replication/protocol/Session.java                                                   |   60 ++
 opendj-server-legacy/src/main/java/org/opends/server/replication/server/ReplicationServer.java                                           |   18 
 opendj-maven-plugin/src/main/resources/config/xml/org/forgerock/opendj/server/config/ReplicationSynchronizationProviderConfiguration.xml |   13 
 opendj-server-legacy/src/test/java/org/opends/server/replication/server/ReplicationServerConnectFailureTest.java                         |   80 ++++
 opendj-server-legacy/src/main/java/org/opends/server/replication/service/ReplicationBroker.java                                          |  548 +++++++++++++++++++++------
 opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationBrokerStopTest.java                                   |  462 +++++++++++++++++-----
 6 files changed, 938 insertions(+), 243 deletions(-)

diff --git a/opendj-maven-plugin/src/main/resources/config/xml/org/forgerock/opendj/server/config/ReplicationSynchronizationProviderConfiguration.xml b/opendj-maven-plugin/src/main/resources/config/xml/org/forgerock/opendj/server/config/ReplicationSynchronizationProviderConfiguration.xml
index 59ef52c..5027cf2 100644
--- a/opendj-maven-plugin/src/main/resources/config/xml/org/forgerock/opendj/server/config/ReplicationSynchronizationProviderConfiguration.xml
+++ b/opendj-maven-plugin/src/main/resources/config/xml/org/forgerock/opendj/server/config/ReplicationSynchronizationProviderConfiguration.xml
@@ -110,9 +110,16 @@
       replication server which gives no credit, lowering it shortens the time
       before those changes are given up. A replication server which does not
       read what the domain has already written to it gets as long again, after
-      which the domain closes the session without waiting any longer. A value
-      of 0 sets no limit: a connection, an SSL negotiation and a stopping
-      replication domain then wait for as long as it takes.
+      which the domain closes the session without waiting any longer.
+
+      Replication server discovery shares this timeout across candidate probes.
+      A planned switch can use the full discovery window while the domain
+      is running. For other connections, discovery waits up to one more
+      second after a compatible server in the preferred group replies. If
+      the elected connection fails during failover, discovery can resume
+      within the original limit. A value of 0 gives discovery a five-second
+      limit and allows the selected connection, its SSL negotiation, and a
+      stopping replication domain to wait without a limit.
     </adm:description>
     <adm:default-behavior>
       <adm:defined>
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/replication/protocol/Session.java b/opendj-server-legacy/src/main/java/org/opends/server/replication/protocol/Session.java
index 0fa9c14..98b2fca 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/replication/protocol/Session.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/replication/protocol/Session.java
@@ -897,6 +897,39 @@
   public ReplicationMsg receive() throws IOException,
       DataFormatException, NotSupportedOldVersionPDUException
   {
+    return receive(false);
+  }
+
+  /**
+   * Receives the first message of a new connection, distinguishing a disconnect before
+   * any frame bytes arrive from a frame interrupted during transmission.
+   *
+   * @return the first replication message
+   * @throws EarlyPeerDisconnectException if the stream ends or the socket fails before the first byte
+   * @throws IOException if another I/O error occurs
+   * @throws DataFormatException if the frame is malformed
+   * @throws NotSupportedOldVersionPDUException if the message uses an unsupported old protocol
+   */
+  public ReplicationMsg receiveFirstMessage() throws IOException,
+      DataFormatException, NotSupportedOldVersionPDUException
+  {
+    return receive(true);
+  }
+
+  /** The peer disconnected before sending any bytes of its first replication frame. */
+  public static final class EarlyPeerDisconnectException extends IOException
+  {
+    private static final long serialVersionUID = 1L;
+
+    private EarlyPeerDisconnectException(IOException cause)
+    {
+      super(cause.getMessage(), cause);
+    }
+  }
+
+  private ReplicationMsg receive(boolean firstMessage)
+      throws IOException, DataFormatException, NotSupportedOldVersionPDUException
+  {
     try
     {
       /*
@@ -906,13 +939,13 @@
       lastReceiveTime = System.currentTimeMillis();
 
       // Read the first 8 bytes containing the packet length.
-      read(rcvLengthBuf);
+      read(rcvLengthBuf, firstMessage);
       final int totalLength = Integer.parseInt(new String(rcvLengthBuf), 16);
 
       try
       {
         final byte[] buffer = new byte[totalLength];
-        read(buffer);
+        read(buffer, false);
 
         /*
          * We do not want the heartbeat to close the session when we are
@@ -933,19 +966,30 @@
     }
   }
 
-  private void read(byte[] buffer) throws IOException
+  private void read(byte[] buffer, boolean firstFrameHeader) throws IOException
   {
     final int totalLength = buffer.length;
     int length = 0;
     while (length < totalLength)
     {
-      final int read = input.read(buffer, length, totalLength - length);
-      if (read == -1)
+      try
       {
-        lastReceiveTime = 0;
-        throw new EOFException("no more data");
+        final int read = input.read(buffer, length, totalLength - length);
+        if (read == -1)
+        {
+          lastReceiveTime = 0;
+          throw new EOFException("no more data");
+        }
+        length += read;
       }
-      length += read;
+      catch (EOFException | SocketException e)
+      {
+        if (firstFrameHeader && length == 0)
+        {
+          throw new EarlyPeerDisconnectException(e);
+        }
+        throw e;
+      }
     }
   }
 
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/replication/server/ReplicationServer.java b/opendj-server-legacy/src/main/java/org/opends/server/replication/server/ReplicationServer.java
index 5dc7de1..f0809eb 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/replication/server/ReplicationServer.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/replication/server/ReplicationServer.java
@@ -74,6 +74,7 @@
 import org.opends.server.replication.protocol.ReplicationMsg;
 import org.opends.server.replication.protocol.ServerStartMsg;
 import org.opends.server.replication.protocol.Session;
+import org.opends.server.replication.protocol.Session.EarlyPeerDisconnectException;
 import org.opends.server.replication.server.changelog.api.ChangeNumberIndexDB;
 import org.opends.server.replication.server.changelog.api.ChangeNumberIndexRecord;
 import org.opends.server.replication.server.changelog.api.ChangelogDB;
@@ -408,7 +409,22 @@
           continue;
         }
 
-        ReplicationMsg msg = session.receive();
+        final ReplicationMsg msg;
+        try
+        {
+          msg = session.receiveFirstMessage();
+        }
+        catch (EarlyPeerDisconnectException e)
+        {
+          // A discovery probe may be cancelled after TLS but before sending ServerStartMsg.
+          if (logger.isDebugEnabled())
+          {
+            logger.debug(LocalizableMessage.raw("Replication connection from %s closed before the first message: %s",
+                session.getReadableRemoteAddress(), e.getMessage()));
+          }
+          close(session);
+          continue;
+        }
 
         final int queueSize = this.config.getQueueSize();
         final int rcvWindow = this.config.getWindowSize();
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 2bc3caf..176c02d 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
@@ -39,8 +39,14 @@
 import java.util.Set;
 import java.util.TreeMap;
 import java.util.concurrent.ConcurrentSkipListMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorCompletionService;
+import java.util.concurrent.Future;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.RejectedExecutionException;
 import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.Semaphore;
+import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicReference;
@@ -83,6 +89,7 @@
 import org.opends.server.replication.protocol.WindowMsg;
 import org.opends.server.replication.protocol.WindowProbeMsg;
 import org.opends.server.types.HostPort;
+import org.opends.server.util.StaticUtils;
 
 import static org.opends.messages.ReplicationMessages.*;
 import static org.opends.server.replication.protocol.ProtocolVersion.*;
@@ -92,6 +99,14 @@
 /** The broker for Multi-master Replication. */
 public class ReplicationBroker
 {
+  private static final int MAX_DISCOVERY_PROBES = 4;
+  /** Give a fast probe time to finish before opening more handshakes on the other RSs. */
+  private static final long DISCOVERY_PROBE_DELAY_NANOS = TimeUnit.MILLISECONDS.toNanos(250);
+  /** Bound discovery rounds even when the full session handshake has no configured timeout. */
+  private static final int DEFAULT_DISCOVERY_TIMEOUT_MILLIS = 5_000;
+  /** Allow other candidates to reply once a compatible RS in the preferred group is available. */
+  private static final long DISCOVERY_REPLY_GRACE_NANOS = TimeUnit.SECONDS.toNanos(1);
+
   /**
    * Immutable class containing information about whether the broker is
    * connected to an RS and data associated to this connected RS.
@@ -277,6 +292,9 @@
   private int halfRcvWindow = rcvWindow / 2;
   private int timeout;
   private final ReplSessionSecurity replSessionSecurity;
+  private final ThreadPoolExecutor discoveryExecutor;
+  @GuardedBy("connectPhaseLock")
+  private int nextDiscoveryProbe;
   /**
    * The RS this DS is currently connected to.
    * <p>
@@ -396,6 +414,14 @@
     this.state = state;
     this.config = config;
     this.replSessionSecurity = replSessionSecurity;
+    this.discoveryExecutor = new ThreadPoolExecutor(MAX_DISCOVERY_PROBES, MAX_DISCOVERY_PROBES, 30, TimeUnit.SECONDS,
+        new LinkedBlockingQueue<>(), task -> {
+          final DirectoryThread thread = new DirectoryThread(task,
+              "Replica DS(" + getServerId() + ") discovering replication servers for " + getBaseDN());
+          thread.setDaemon(true);
+          return thread;
+        });
+    this.discoveryExecutor.allowCoreThreadTimeOut(true);
     this.rcvWindow = getMaxRcvWindow();
     this.halfRcvWindow = rcvWindow / 2;
     this.shutdown = true;
@@ -421,7 +447,7 @@
       shutdown = false;
       stopping = null;
       this.rcvWindow = getMaxRcvWindow();
-      connectAsDataServer(null);
+      connectAsDataServer(null, false);
     }
   }
 
@@ -832,26 +858,238 @@
     }
   }
 
-  /**
-   * Collects replies for server selection and remembers an RS that did not answer its start message.
-   * Prefer a different RS from the one whose session just ended.
-   */
-  private String collectReplicationServersInfo(Map<Integer, ReplicationServerInfo> rsInfos, String previousRS)
+  private static final class DiscoveryProbe
   {
-    String timedOutRS = null;
-    for (String serverUrl : getReplicationServerUrls())
+    private final String url;
+    private final Socket socket = new Socket();
+    private final long deadline;
+    private volatile boolean started;
+    private volatile boolean awaitingStartReply;
+    private volatile boolean cancelled;
+    private ConnectedRS result;
+    private LocalizableMessage failure;
+    private boolean collected;
+
+    private DiscoveryProbe(String url, long deadline)
     {
-      final ConnectedRS probe = performPhaseOneHandshake(serverUrl, false, false);
-      if (probe.rsInfo != null)
+      this.url = url;
+      this.deadline = deadline;
+    }
+
+    private int remainingTimeoutMillis() throws SocketTimeoutException
+    {
+      final long remaining = deadline - System.nanoTime();
+      if (remaining <= 0)
       {
-        rsInfos.put(probe.getServerId(), probe.rsInfo);
+        throw new SocketTimeoutException("Replication server discovery deadline expired");
       }
-      else if (probe == ConnectedRS.START_REPLY_TIMED_OUT && (timedOutRS == null || timedOutRS.equals(previousRS)))
+      return (int) Math.max(1, TimeUnit.NANOSECONDS.toMillis(remaining));
+    }
+  }
+
+  /** A batch of staggered probes with one deadline across discovery and any continuation. */
+  private final class DiscoveryRound implements AutoCloseable
+  {
+    private final int connectionTimeout = MultimasterReplication.getConnectionTimeoutMS();
+    private final long discoveryDeadline;
+    private final ExecutorCompletionService<DiscoveryProbe> completions = new ExecutorCompletionService<>(
+        discoveryExecutor);
+    private final List<DiscoveryProbe> probes = new ArrayList<>();
+    private final int firstProbe;
+    private long nextProbeAt = System.nanoTime();
+    private int submitted;
+    private int inFlight;
+    private boolean discoveryTimedOut;
+    private boolean closed;
+    private ScheduledFuture<?> expiry;
+
+    private DiscoveryRound()
+    {
+      final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(
+          connectionTimeout == 0 ? DEFAULT_DISCOVERY_TIMEOUT_MILLIS : connectionTimeout);
+      final StopInProgress stop = stopping;
+      discoveryDeadline = stop != null && stop.bounded && stop.writeDeadline - deadline < 0
+          ? stop.writeDeadline : deadline;
+      for (String url : getReplicationServerUrls())
       {
-        timedOutRS = serverUrl;
+        probes.add(new DiscoveryProbe(url, discoveryDeadline));
+      }
+      firstProbe = probes.isEmpty() ? 0 : nextDiscoveryProbe % probes.size();
+    }
+
+    private void collect(Map<Integer, ReplicationServerInfo> rsInfos, boolean useReplyGrace)
+    {
+      if (closed)
+      {
+        return;
+      }
+      long deadline = discoveryDeadline;
+      try
+      {
+        while (inFlight > 0 || submitted < probes.size())
+        {
+          final long now = System.nanoTime();
+          final long remaining = Math.max(0, deadline - now);
+          final boolean canSubmit = submitted < probes.size() && inFlight < MAX_DISCOVERY_PROBES;
+          final long untilNextProbe = Math.max(0, nextProbeAt - now);
+          if (canSubmit && untilNextProbe == 0 && remaining > 0)
+          {
+            final DiscoveryProbe probe = probes.get((firstProbe + submitted) % probes.size());
+            completions.submit(() -> {
+              if (!probe.cancelled && probe.deadline - System.nanoTime() > 0)
+              {
+                probe.started = true;
+                probe.result = performPhaseOneHandshake(probe.url, false, false, probe.socket, probe);
+              }
+              return probe;
+            });
+            submitted++;
+            inFlight++;
+            nextProbeAt = now + DISCOVERY_PROBE_DELAY_NANOS;
+            continue;
+          }
+
+          final long wait = canSubmit ? Math.min(remaining, untilNextProbe) : remaining;
+          final Future<DiscoveryProbe> next = completions.poll(wait, TimeUnit.NANOSECONDS);
+          if (next == null)
+          {
+            if (deadline - System.nanoTime() <= 0)
+            {
+              break;
+            }
+            continue;
+          }
+          inFlight--;
+          final DiscoveryProbe probe = next.get();
+          nextProbeAt = System.nanoTime();
+          if (probe.result == null)
+          {
+            continue;
+          }
+          probe.collected = true;
+          final ReplicationServerInfo info = probe.result.rsInfo;
+          if (useReplyGrace && hasCompatibleGeneration(info) && info.getGroupId() == getGroupId())
+          {
+            final long graceDeadline = System.nanoTime() + DISCOVERY_REPLY_GRACE_NANOS;
+            if (graceDeadline - deadline < 0)
+            {
+              deadline = graceDeadline;
+            }
+          }
+        }
+      }
+      catch (InterruptedException e)
+      {
+        Thread.currentThread().interrupt();
+      }
+      catch (ExecutionException e)
+      {
+        logger.traceException(e);
+      }
+      discoveryTimedOut |= deadline == discoveryDeadline && System.nanoTime() - deadline >= 0;
+
+      // Retain the configured order even if replies arrive out of order.
+      for (DiscoveryProbe probe : probes)
+      {
+        if (probe.collected && probe.result.rsInfo != null)
+        {
+          final ReplicationServerInfo info = probe.result.rsInfo;
+          rsInfos.put(info.getServerId(), info);
+        }
       }
     }
-    return timedOutRS;
+
+    private String timedOutServer(String previousRS)
+    {
+      // With no session timeout, retry a silent server through discovery so other candidates still get a turn.
+      if (connectionTimeout == 0)
+      {
+        return null;
+      }
+      String timedOutRS = null;
+      for (DiscoveryProbe probe : probes)
+      {
+        final boolean timedOut = probe.collected
+            ? probe.result == ConnectedRS.START_REPLY_TIMED_OUT || probe.cancelled && probe.awaitingStartReply
+            : probe.awaitingStartReply;
+        if (timedOut && (timedOutRS == null || timedOutRS.equals(previousRS)))
+        {
+          timedOutRS = probe.url;
+        }
+      }
+      return timedOutRS;
+    }
+
+    /** Keep the discovery deadline even while the elected session has its own timeout. */
+    private void expirePendingProbesAtDeadline()
+    {
+      if (inFlight > 0)
+      {
+        try
+        {
+          expiry = DirectoryServer.getInstance().getServerContext().getCronExecutorService().schedule(
+              this::closeProbeSockets, Math.max(0, discoveryDeadline - System.nanoTime()), TimeUnit.NANOSECONDS);
+        }
+        catch (RejectedExecutionException e)
+        {
+          // Server shutdown stops the scheduler before it finalizes replication.
+          close();
+        }
+      }
+    }
+
+    private void closeProbeSockets()
+    {
+      for (DiscoveryProbe probe : probes)
+      {
+        probe.cancelled = true;
+        StaticUtils.close(probe.socket);
+      }
+    }
+
+    @Override
+    public void close()
+    {
+      if (closed)
+      {
+        return;
+      }
+      closed = true;
+      if (expiry != null)
+      {
+        expiry.cancel(false);
+      }
+      // Discovery runs under connectPhaseLock, so this queue contains only this batch.
+      // Closing the sockets also unblocks TLS and protocol reads in the running probes.
+      discoveryExecutor.getQueue().clear();
+      closeProbeSockets();
+      if (submitted < probes.size())
+      {
+        nextDiscoveryProbe = (firstProbe + submitted) % probes.size();
+      }
+      else if (discoveryTimedOut && probes.size() > MAX_DISCOVERY_PROBES)
+      {
+        // A probe submitted just before the deadline may have had almost no time to answer.
+        nextDiscoveryProbe = (firstProbe + MAX_DISCOVERY_PROBES) % probes.size();
+      }
+      else
+      {
+        nextDiscoveryProbe = 0;
+      }
+
+      for (DiscoveryProbe probe : probes)
+      {
+        if (probe.collected && probe.failure != null)
+        {
+          logPhaseOneHandshakeFailure(probe.failure, false, false);
+        }
+        else if (!probe.collected && probe.started && discoveryTimedOut)
+        {
+          logPhaseOneHandshakeFailure(WARN_TIMEOUT_CONNECTING_TO_RS.get(getServerId(), probe.url, getBaseDN()),
+              false, false);
+        }
+      }
+    }
   }
 
   /**
@@ -878,9 +1116,10 @@
    * finally performed.
    *
    * @param previousRS the RS whose established session just ended, or null outside the first failover attempt
+   * @param planned whether monitoring initiated the switch from that session
    * @throws NumberFormatException address was invalid
    */
-  private void connectAsDataServer(String previousRS)
+  private void connectAsDataServer(String previousRS, boolean planned)
   {
     /*
      * If a first connect or a connection failure occur, we go through here.
@@ -908,68 +1147,44 @@
         debugInfo("phase 1 : will perform PhaseOneH with each RS in order to elect the preferred one");
       }
 
-      // Get info from every available replication servers
       final Map<Integer, ReplicationServerInfo> rsInfos = new ConcurrentSkipListMap<>();
-      final String timedOutRS = collectReplicationServersInfo(rsInfos, previousRS);
-      computeNewTopology(toRSInfos(rsInfos));
+      try (DiscoveryRound discovery = new DiscoveryRound())
+      {
+        // The former RS can still answer a planned switch. Give alternatives the full budget while running.
+        discovery.collect(rsInfos, !planned || stopping != null);
+        if (Thread.currentThread().isInterrupted())
+        {
+          return;
+        }
+        computeNewTopology(toRSInfos(rsInfos));
 
-      final boolean hasReplies = !rsInfos.isEmpty();
-      final boolean canRetry = previousRS != null && stopping == null && !permanentlyStopped;
-      String electedURL = null;
-      if (hasReplies)
-      {
-        final RSEvaluations evals = computeBestReplicationServer(true, -1, state,
-            rsInfos, serverId, getGroupId(), getGenerationID());
-        if (logger.isTraceEnabled())
+        final boolean canRetry = previousRS != null && stopping == null && !permanentlyStopped;
+        final boolean hasReplies = !rsInfos.isEmpty();
+        String electedURL = null;
+        if (hasReplies)
         {
-          debugInfo("phase 2 : will perform PhaseOneH with the preferred RS=" + evals.getBestRS());
+          final RSEvaluations evals = computeBestReplicationServer(true, -1, state,
+              rsInfos, serverId, getGroupId(), getGenerationID());
+          if (logger.isTraceEnabled())
+          {
+            debugInfo("phase 2 : will perform PhaseOneH with the preferred RS=" + evals.getBestRS());
+          }
+          electedURL = evals.getBestRS().getServerURL();
         }
-        electedURL = evals.getBestRS().getServerURL();
-      }
-      else if (canRetry)
-      {
-        // A live RS can miss one start reply under load. Use the retry to establish the
-        // actual session before declaring isolation and rejecting LDAP writes.
-        electedURL = timedOutRS;
-      }
+        else if (canRetry)
+        {
+          // A live RS can miss one start reply under load. Use the retry to establish the
+          // actual session before declaring isolation and rejecting LDAP writes.
+          electedURL = discovery.timedOutServer(previousRS);
+        }
 
-      if (electedURL == null)
-      {
-        setConnectedRS(ConnectedRS.noConnectedRS());
-      }
-      else
-      {
-        final boolean canRetryElected = canRetry && hasReplies;
-        ConnectedRS electedRS = performPhaseOneHandshake(electedURL, true, canRetryElected);
-        if (electedRS.rsInfo == null && canRetryElected && stopping == null && !permanentlyStopped)
+        if (electedURL == null)
         {
-          if (electedRS == ConnectedRS.START_REPLY_TIMED_OUT)
-          {
-            electedRS = performPhaseOneHandshake(electedURL, true, false);
-          }
-          else if (electedURL.equals(previousRS))
-          {
-            final ReplicationServerInfo responder = electedRS == ConnectedRS.CONNECTION_REFUSED
-                ? selectDiscoveryResponder(rsInfos, previousRS) : null;
-            if (responder != null)
-            {
-              electedRS = connectToDiscoveryResponder(responder);
-            }
-            else if (timedOutRS != null && !electedURL.equals(timedOutRS))
-            {
-              // The other RS can still accept a session after missing its discovery reply.
-              electedRS = performPhaseOneHandshake(timedOutRS, true, false);
-            }
-          }
+          setConnectedRS(ConnectedRS.noConnectedRS());
         }
-        final StopInProgress stop = stopping;
-        if (electedRS.rsInfo != null)
+        else
         {
-          finishElectedConnection(electedRS, rsInfos);
-        }
-        else if (stop != null && electedURL.equals(previousRS))
-        {
-          connectToReplacementForStop(stop, previousRS, rsInfos);
+          connectToElectedServer(discovery, rsInfos, electedURL, previousRS, canRetry && hasReplies);
         }
       }
 
@@ -992,7 +1207,7 @@
               rs.replicationServer, getGenerationID(), rsGenId);
         }
       }
-      else
+      else if (!Thread.currentThread().isInterrupted())
       {
          // This server could not find any replicationServer.
          // It's going to start in degraded mode. Log a message.
@@ -1015,6 +1230,80 @@
     }
   }
 
+  private void connectToElectedServer(DiscoveryRound discovery, Map<Integer, ReplicationServerInfo> rsInfos,
+      String electedURL, String previousRS, boolean canRetry)
+  {
+    if (canRetry)
+    {
+      discovery.expirePendingProbesAtDeadline();
+    }
+    else
+    {
+      discovery.close();
+    }
+    ConnectedRS electedRS = performPhaseOneHandshake(electedURL, true, canRetry);
+    if (electedRS.rsInfo == null && canRetry && stopping == null && !permanentlyStopped)
+    {
+      electedRS = retryElectedConnection(discovery, rsInfos, electedURL, previousRS, electedRS);
+    }
+    discovery.close();
+
+    final StopInProgress stop = stopping;
+    if (electedRS.rsInfo != null)
+    {
+      finishElectedConnection(electedRS, rsInfos);
+    }
+    else if (stop != null && electedURL.equals(previousRS) && !Thread.currentThread().isInterrupted())
+    {
+      connectToReplacementForStop(stop, previousRS, rsInfos);
+    }
+  }
+
+  private ConnectedRS retryElectedConnection(DiscoveryRound discovery, Map<Integer, ReplicationServerInfo> rsInfos,
+      String electedURL, String previousRS, ConnectedRS failure)
+  {
+    if (failure == ConnectedRS.START_REPLY_TIMED_OUT)
+    {
+      discovery.close();
+      return performPhaseOneHandshake(electedURL, true, false);
+    }
+    final boolean electedFormerRS = electedURL.equals(previousRS);
+    if (!electedFormerRS && failure != ConnectedRS.CONNECTION_REFUSED)
+    {
+      return failure;
+    }
+
+    ReplicationServerInfo responder = selectDiscoveryResponder(rsInfos, electedURL);
+    if (responder == null)
+    {
+      // Keep listening for candidates still within the original discovery budget.
+      discovery.collect(rsInfos, true);
+      if (Thread.currentThread().isInterrupted())
+      {
+        return failure;
+      }
+      computeNewTopology(toRSInfos(rsInfos));
+      responder = selectDiscoveryResponder(rsInfos, electedURL);
+    }
+    final String timedOutRS = electedFormerRS && responder == null ? discovery.timedOutServer(previousRS) : null;
+    discovery.close();
+
+    if (stopping != null || permanentlyStopped)
+    {
+      return failure;
+    }
+    if (responder != null)
+    {
+      return connectToDiscoveryResponder(responder);
+    }
+    if (timedOutRS != null && !electedURL.equals(timedOutRS))
+    {
+      // The other RS can still accept a session after missing its discovery reply.
+      return performPhaseOneHandshake(timedOutRS, true, false);
+    }
+    return failure;
+  }
+
   /** Opens the selected RS session using the fresh state returned by its start reply. */
   private void finishElectedConnection(ConnectedRS electedRS, Map<Integer, ReplicationServerInfo> rsInfos)
   {
@@ -1029,11 +1318,11 @@
     }
   }
 
-  /** Selects a compatible discovery responder other than the former replication server. */
-  private ReplicationServerInfo selectDiscoveryResponder(Map<Integer, ReplicationServerInfo> rsInfos, String formerURL)
+  /** Selects a compatible discovery responder other than the replication server already tried. */
+  private ReplicationServerInfo selectDiscoveryResponder(Map<Integer, ReplicationServerInfo> rsInfos, String triedURL)
   {
     final Map<Integer, ReplicationServerInfo> candidates = new TreeMap<>(rsInfos);
-    candidates.values().removeIf(info -> formerURL.equals(info.getServerURL()) || !hasCompatibleGeneration(info));
+    candidates.values().removeIf(info -> triedURL.equals(info.getServerURL()) || !hasCompatibleGeneration(info));
     if (candidates.isEmpty())
     {
       return null;
@@ -1309,6 +1598,12 @@
   private ConnectedRS performPhaseOneHandshake(String serverURL, boolean keepSession, boolean retryStartTimeout,
       Socket socket)
   {
+    return performPhaseOneHandshake(serverURL, keepSession, retryStartTimeout, socket, null);
+  }
+
+  private ConnectedRS performPhaseOneHandshake(String serverURL, boolean keepSession, boolean retryStartTimeout,
+      Socket socket, DiscoveryProbe probe)
+  {
     Session newSession = null;
     boolean hasConnected = false;
     ConnectedRS failure = ConnectedRS.noConnectedRS();
@@ -1327,8 +1622,9 @@
         InetSocketAddress local = new InetSocketAddress(config.getSourceAddress(), 0);
         socket.bind(local);
       }
-      int timeoutMS = MultimasterReplication.getConnectionTimeoutMS();
-      socket.connect(HostPort.valueOf(serverURL).toInetSocketAddress(), timeoutMS);
+      final int timeoutMS = MultimasterReplication.getConnectionTimeoutMS();
+      socket.connect(HostPort.valueOf(serverURL).toInetSocketAddress(),
+          probe != null ? probe.remainingTimeoutMillis() : timeoutMS);
       if (isSelfConnection(socket))
       {
         // While the RS is down, the kernel may pick the RS port as the local
@@ -1338,7 +1634,8 @@
         throw new ConnectException("Connection to " + serverURL
             + " is a TCP self-connect, no replication server is listening");
       }
-      newSession = replSessionSecurity.createClientSession(socket, timeoutMS, "DS", getServerId(), getBaseDN());
+      newSession = replSessionSecurity.createClientSession(socket,
+          probe != null ? probe.remainingTimeoutMillis() : timeoutMS, "DS", getServerId(), getBaseDN());
       boolean isSslEncryption = replSessionSecurity.isSslEncryption();
 
       // Send our ServerStartMsg.
@@ -1353,8 +1650,17 @@
       // Read the ReplServerStartMsg or ReplServerStartDSMsg that should
       // come back.
       waitingForStartReply = true;
+      if (probe != null)
+      {
+        probe.awaitingStartReply = true;
+        newSession.setSoTimeout(probe.remainingTimeoutMillis());
+      }
       ReplicationMsg msg = newSession.receive();
       waitingForStartReply = false;
+      if (probe != null)
+      {
+        probe.awaitingStartReply = false;
+      }
       if (logger.isTraceEnabled())
       {
         debugInfo("RB HANDSHAKE SENT:\n" + serverStartMsg + "\nAND RECEIVED:\n"
@@ -1370,7 +1676,7 @@
       if (!getBaseDN().equals(repDN))
       {
         errorMessage = ERR_DS_DN_DOES_NOT_MATCH.get(repDN, getBaseDN());
-        return setConnectedRS(ConnectedRS.noConnectedRS());
+        return keepSession ? setConnectedRS(ConnectedRS.noConnectedRS()) : ConnectedRS.noConnectedRS();
       }
 
       /*
@@ -1434,54 +1740,40 @@
 
       if (!hasConnected && errorMessage != null)
       {
-        if (!connectionError)
+        if (probe != null)
         {
-          /*
-           * Report the cause for every replication server contacted, and not only for the
-           * elected one: none is ever elected when none of them answers, and this is then
-           * the only place naming why -- a refused connection, a rejected certificate, a
-           * wrong port -- next to the "unable to connect to any replication servers"
-           * summary which names none of them.
-           *
-           * connectionError is what bounds the volume, and it bounds it to one line per
-           * replication server and per attempt to connect this broker makes. It is set
-           * when an attempt reaches no replication server at all, and stays set until a
-           * session is established, so the 500 ms loop which retries a total outage
-           * reports its first pass only.
-           *
-           * It is not set while this broker is connected, so the unreachable servers of a
-           * topology which still serves this broker are reported again on each
-           * reconnection -- one line each, so a reconnection costs as many lines as there
-           * are servers it could not reach, where it used to cost none. That is the volume
-           * this reporting is worth: a broker reconnects when its session is lost, not on
-           * a schedule, and a server which cannot be reached over several reconnections is
-           * a server whose configuration or certificate needs looking at.
-           *
-           * An unsuccessful attempt to establish the elected session is an error.
-           * A discovery probe or a start reply timeout scheduled for retry is a warning.
-           * ERR_DS_DN_DOES_NOT_MATCH is the one message which reaches the second branch
-           * under an ERR_ name -- it is set without setting hasConnected -- and it is a
-           * permanent misconfiguration rather than a transient. It still goes out as an
-           * error for the server this broker is electing, which is the one it cannot work
-           * without, and where it is only contacted the broker has another server to work
-           * with. Before this, that path logged nothing above trace either way.
-           */
-          if (keepSession && !(startReplyTimedOut && retryStartTimeout))
-          {
-            logger.error(errorMessage);
-          }
-          else
-          {
-            logger.warn(errorMessage);
-          }
+          probe.failure = errorMessage;
         }
-        logger.trace(errorMessage);
+        else
+        {
+          logPhaseOneHandshakeFailure(errorMessage, keepSession, startReplyTimedOut && retryStartTimeout);
+        }
       }
     }
-    setConnectedRS(ConnectedRS.noConnectedRS());
+    if (keepSession)
+    {
+      setConnectedRS(ConnectedRS.noConnectedRS());
+    }
     return startReplyTimedOut ? ConnectedRS.START_REPLY_TIMED_OUT : failure;
   }
 
+  /** Reports failure details until the broker has declared isolation. */
+  private void logPhaseOneHandshakeFailure(LocalizableMessage message, boolean keepSession, boolean retrying)
+  {
+    if (!connectionError)
+    {
+      if (keepSession && !retrying)
+      {
+        logger.error(message);
+      }
+      else
+      {
+        logger.warn(message);
+      }
+    }
+    logger.trace(message);
+  }
+
   /**
    * Performs the second phase handshake (send StartSessionMsg and receive
    * TopologyMsg messages exchange) and return the reply message from the
@@ -2448,6 +2740,11 @@
    */
   private void reStart(Session failingSession, boolean infiniteTry)
   {
+    reStart(failingSession, infiniteTry, false);
+  }
+
+  private void reStart(Session failingSession, boolean infiniteTry, boolean planned)
+  {
     if (failingSession != null)
     {
       failingSession.close();
@@ -2487,7 +2784,7 @@
           {
             final String failedRS = previousRS;
             previousRS = null;
-            connectAsDataServer(failedRS);
+            connectAsDataServer(failedRS, planned && failedRS != null);
             rs = connectedRS.get();
           }
           catch (Exception e)
@@ -2947,14 +3244,15 @@
         }
         else if (msg instanceof StopMsg)
         {
-          if (!finishPlannedSwitch(session))
+          final boolean wasSwitching = finishPlannedSwitch(session);
+          if (!wasSwitching)
           {
             logger.warn(WARN_REPLICATION_SERVER_PROPERLY_DISCONNECTED, previousRsServerID, rs.replicationServer,
                 serverId, baseDN);
           }
 
           // Try to find a suitable RS
-          reStart(session, true);
+          reStart(session, true, wasSwitching);
         }
         else if (msg instanceof MonitorMsg)
         {
@@ -3057,7 +3355,7 @@
         abortPlannedSwitch(session, e);
         if (reconnectOnFailure)
         {
-          reStart(session, true);
+          reStart(session, true, true);
         }
         else
         {
@@ -3084,7 +3382,7 @@
             break; // does not seem necessary to explicitly disconnect ..
           }
 
-          reStart(session, true);
+          reStart(session, true, wasSwitching);
         }
       }
     }
@@ -3099,7 +3397,7 @@
   {
     if (session.getProtocolVersion() < REPLICATION_PROTOCOL_V4)
     {
-      reStart(session, true);
+      reStart(session, true, true);
       return;
     }
 
@@ -3123,7 +3421,7 @@
     }))
     {
       finishPlannedSwitch(session);
-      reStart(session, true);
+      reStart(session, true, true);
     }
   }
 
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 371d51a..ab8284a 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
@@ -19,6 +19,7 @@
 
 import static org.forgerock.opendj.ldap.ModificationType.*;
 import static org.opends.messages.ReplicationMessages.WARN_REPLICATION_SERVER_BADLY_DISCONNECTED;
+import static org.opends.messages.ReplicationMessages.WARN_TIMEOUT_CONNECTING_TO_RS;
 import static org.opends.server.TestCaseUtils.*;
 import static org.opends.server.protocols.internal.InternalClientConnection.*;
 import static org.opends.server.protocols.internal.Requests.*;
@@ -37,6 +38,7 @@
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
+import java.util.Comparator;
 import java.util.List;
 import java.util.Map;
 import java.util.SortedSet;
@@ -144,12 +146,6 @@
    * writes to fill the socket buffers before the heartbeat monitor gives up on the session.
    */
   private static final long HEARTBEAT_INTERVAL_MS = 4000;
-  /**
-   * The replication servers which answer no connection in the case of a connection under way: each
-   * costs the connection the connection timeout, and together they hold it well past twice that, the
-   * deadline of the watchdog of a stop.
-   */
-  private static final int SILENT_SERVERS = 4;
   /** A value which makes a change of the description one of those messages. */
   private static final String LARGE_VALUE = "x".repeat(LARGE_MESSAGE_SIZE);
 
@@ -852,10 +848,10 @@
 
   /**
    * A connection under way when the watchdog of the stop gives up leaves it no session to close: the
-   * listener lost the session in the stop, and connects again holding the lock of the connection
-   * phase, while replication servers which take a connection but answer none cost it the connection
-   * timeout each. A publish of the stop which waited for that lock must not write to the session the
-   * connection then opens: one which the replication server does not read would hold the stop, with
+   * listener lost the session in the stop and connects again holding the connection phase lock.
+   * The elected server holds its start reply until the watchdog acts. A publish of the stop which
+   * waited for that lock must not write to the session the connection then opens: a write which
+   * the replication server does not read would hold the stop, with
    * nothing left to end it. The entry here goes to a replication server which reads, and must not be
    * written at all.
    */
@@ -864,19 +860,12 @@
   {
     final WithholdingReplicationServer rs = new WithholdingReplicationServer(LARGE_WINDOW);
     rs.start();
-    final List<SilentReplicationServer> silentServers = new ArrayList<>();
-    final SortedSet<String> urls = new TreeSet<>(Collections.singleton("127.0.0.1:" + rs.getPort()));
-    for (int i = 0; i < SILENT_SERVERS; i++)
-    {
-      final SilentReplicationServer silent = new SilentReplicationServer();
-      silent.start();
-      silentServers.add(silent);
-      urls.add("127.0.0.1:" + silent.getPort());
-    }
+    final CountDownLatch electedStartReceived = new CountDownLatch(1);
+    final CountDownLatch replyToElectedStart = new CountDownLatch(1);
+    final SortedSet<String> urls = new TreeSet<>(Collections.singleton(rs.getAddress()));
     final DomainFakeCfg config = new DomainFakeCfg(baseDN, OTHER_DS_ID, urls);
     config.setHeartbeatInterval(100000);
     final AtomicReference<ReplicationBroker> brokerRef = new AtomicReference<>();
-    final AtomicReference<Thread> listenerRef = new AtomicReference<>();
     final ReplicationBroker broker = new ReplicationBroker(new DummyReplicationDomain(getGenerationId(baseDN))
     {
       @Override
@@ -884,15 +873,19 @@
       {
         try
         {
-          for (SilentReplicationServer silent : silentServers)
-          {
-            silent.answerNothing();
-          }
-          // The replication server ends the session in order, and the listener connects again.
+          // The watchdog already has its short deadline. Keep the elected connection open past it.
+          setConnectionTimeout(30_000);
+          final AtomicInteger starts = new AtomicInteger();
+          rs.beforeStartReply = () -> {
+            if (starts.incrementAndGet() == 2)
+            {
+              electedStartReceived.countDown();
+              await(replyToElectedStart);
+            }
+            return null;
+          };
           rs.closeTheSession();
-          newTimer().repeatUntilSuccess(() -> assertTrue(
-              isIn(listenerRef.get(), ReplicationBroker.class, "collectReplicationServersInfo"),
-              "the listener does not connect again"));
+          await(electedStartReceived);
         }
         catch (Exception e)
         {
@@ -921,8 +914,6 @@
           throw new IllegalStateException(e);
         }
       });
-      listenerRef.set(listener);
-
       final long beforeTheStop = System.nanoTime();
       final Thread stop = startThread("stop", broker::stop);
       stopping = stop;
@@ -935,6 +926,8 @@
       assertFalse(watchdogRuns(), "the watchdog of the stop did not act at its deadline");
       assertTrue(isIn(listener, ReplicationBroker.class, "connectAsDataServer"),
           "the connection ended before the watchdog of the stop acted: the case tests nothing");
+      replyToElectedStart.countDown();
+      setConnectionTimeout(SHORT_CONNECTION_TIMEOUT_MS);
 
       stop.join(stopBoundMS());
       assertFalse(stop.isAlive(), "stop() did not end once the connection did");
@@ -947,11 +940,15 @@
     }
     finally
     {
-      for (SilentReplicationServer silent : silentServers)
+      replyToElectedStart.countDown();
+      try
       {
-        silent.shutdown();
+        cleanUp(rs, stopping, listener);
       }
-      cleanUp(rs, stopping, listener);
+      finally
+      {
+        setConnectionTimeout(SHORT_CONNECTION_TIMEOUT_MS);
+      }
     }
   }
 
@@ -1084,6 +1081,312 @@
   }
 
   @Test(timeOut = 120_000)
+  public void failoverUsesAResponderWhileAnotherProbeIsWaiting() throws Exception
+  {
+    TestCaseUtils.initializeTestBackend(true);
+    final WithholdingReplicationServer former = new WithholdingReplicationServer(LARGE_WINDOW);
+    final WithholdingReplicationServer survivor = new WithholdingReplicationServer(LARGE_WINDOW, 4);
+    final CountDownLatch probeStarted = new CountDownLatch(1);
+    final CountDownLatch releaseProbe = new CountDownLatch(1);
+    try
+    {
+      setConnectionTimeout(30_000);
+      survivor.differentGroup = true;
+      survivor.start();
+      final LDAPReplicationDomain domain = startDomain(former, 100000, survivor.getAddress());
+      assertEquals(domain.getRsServerId(), former.serverId);
+      newTimer().repeatUntilSuccess(() -> assertNotNull(former.session.get()));
+
+      survivor.differentGroup = false;
+      former.beforeStartReply = () -> {
+        probeStarted.countDown();
+        releaseProbe.await();
+        return null;
+      };
+      former.dropTheSession();
+
+      await(probeStarted);
+      newTimer().repeatUntilSuccess(() ->
+          assertEquals(domain.getRsServerId(), survivor.serverId, "a pending discovery probe blocked failover"));
+      assertFalse(domain.hasConnectionError());
+      assertEquals(replaceDescription("replicated while the former server is silent"), ResultCode.SUCCESS);
+      survivor.waitForUpdates(1);
+    }
+    finally
+    {
+      releaseProbe.countDown();
+      try
+      {
+        survivor.shutdown();
+      }
+      finally
+      {
+        try
+        {
+          cleanUp(former);
+        }
+        finally
+        {
+          setConnectionTimeout(SHORT_CONNECTION_TIMEOUT_MS);
+        }
+      }
+    }
+  }
+
+  @Test(timeOut = 120_000)
+  public void plannedSwitchReachesASlowerReplacement() throws Exception
+  {
+    TestCaseUtils.initializeTestBackend(true);
+    final WithholdingReplicationServer former = new WithholdingReplicationServer(LARGE_WINDOW, 4);
+    final WithholdingReplicationServer replacement = new WithholdingReplicationServer(LARGE_WINDOW);
+    try
+    {
+      setConnectionTimeout(5_000);
+      replacement.differentGroup = true;
+      replacement.start();
+      final LDAPReplicationDomain domain = startDomain(former, 100000, replacement.getAddress());
+      assertEquals(domain.getRsServerId(), former.serverId);
+      newTimer().repeatUntilSuccess(() -> assertNotNull(former.session.get()));
+
+      // The lower RS ID wins the balanced election once its discovery reply arrives.
+      replacement.beforeStartReply = () -> {
+        Thread.sleep(1_800);
+        return null;
+      };
+      replacement.differentGroup = false;
+      former.advertiseRebalance(replacement, domain);
+      newTimer().repeatUntilSuccess(() -> assertEquals(former.count(StopMsg.class), 1));
+      former.closeTheSession();
+
+      newTimer().repeatUntilSuccess(() ->
+          assertTrue(domain.getRsServerId() == replacement.serverId || former.sessionsStarted() > 1));
+      assertEquals(domain.getRsServerId(), replacement.serverId, "the switch reconnected to the former RS");
+      newTimer().repeatUntilSuccess(() -> assertNotNull(replacement.session.get()));
+      final ReplicationBroker broker = brokerOf(domain);
+      final Session session = broker.getSession();
+
+      final int sendWindow = broker.getCurrentSendWindow();
+      replacement.advertiseLoad(former, domain, former.serverId);
+      // This credit is processed after the topology and both monitor messages.
+      replacement.giveCredit(1);
+      newTimer().repeatUntilSuccess(() -> assertEquals(broker.getCurrentSendWindow(), sendWindow + 1));
+      assertSame(broker.getSession(), session);
+      assertFalse(session.isClosingForSwitch(), "monitoring started another switch from the replacement RS");
+      assertEquals(former.sessionsStarted(), 1);
+      assertEquals(replaceDescription("after the planned switch"), ResultCode.SUCCESS);
+      replacement.waitForUpdates(1);
+    }
+    finally
+    {
+      try
+      {
+        replacement.shutdown();
+      }
+      finally
+      {
+        try
+        {
+          cleanUp(former);
+        }
+        finally
+        {
+          setConnectionTimeout(SHORT_CONNECTION_TIMEOUT_MS);
+        }
+      }
+    }
+  }
+
+  @Test(timeOut = 120_000)
+  public void failoverContinuesAfterTheFastDiscoveryResponderDisappears() throws Exception
+  {
+    TestCaseUtils.initializeTestBackend(true);
+    final WithholdingReplicationServer former = new WithholdingReplicationServer(LARGE_WINDOW);
+    final WithholdingReplicationServer first = new WithholdingReplicationServer(LARGE_WINDOW, 4);
+    final WithholdingReplicationServer second = new WithholdingReplicationServer(LARGE_WINDOW, 6);
+    final boolean firstSortsFirst = first.getAddress().compareTo(second.getAddress()) < 0;
+    final WithholdingReplicationServer silent = firstSortsFirst ? first : second;
+    final WithholdingReplicationServer survivor = firstSortsFirst ? second : first;
+    final CountDownLatch releaseSilent = new CountDownLatch(1);
+    final CountDownLatch survivorSessionStart = new CountDownLatch(1);
+    final CountDownLatch releaseSurvivor = new CountDownLatch(1);
+    final AtomicInteger silentStarts = new AtomicInteger();
+    final AtomicInteger survivorStarts = new AtomicInteger();
+    Thread writer = null;
+    try
+    {
+      setConnectionTimeout(5_000);
+      silent.differentGroup = true;
+      survivor.differentGroup = true;
+      silent.start();
+      survivor.start();
+      final LDAPReplicationDomain domain = startDomain(former, 100000, silent.getAddress(), survivor.getAddress());
+      assertEquals(domain.getRsServerId(), former.serverId);
+      newTimer().repeatUntilSuccess(() -> assertNotNull(former.session.get()));
+
+      silent.beforeStartReply = () -> {
+        silentStarts.incrementAndGet();
+        releaseSilent.await();
+        return null;
+      };
+      survivor.beforeStartReply = () -> {
+        if (survivorStarts.incrementAndGet() == 1)
+        {
+          Thread.sleep(1_800);
+        }
+        else
+        {
+          survivorSessionStart.countDown();
+          releaseSurvivor.await();
+        }
+        return null;
+      };
+      silent.differentGroup = false;
+      survivor.differentGroup = false;
+      former.beforeStartReply = () -> {
+        former.listenSocket.close();
+        return null;
+      };
+      former.dropTheSession();
+
+      await(survivorSessionStart);
+      assertFalse(domain.hasConnectionError(), "the broker declared isolation before using the survivor");
+      assertEquals(silentStarts.get(), 1, "the broker retried a silent probe before connecting to the survivor");
+      final AtomicReference<ResultCode> result = new AtomicReference<>();
+      final Thread localWrite = startThread("write during continued discovery",
+          () -> result.set(replaceDescription("after the elected RS disappeared")));
+      writer = localWrite;
+      newTimer().repeatUntilSuccess(() -> assertTrue(isIn(localWrite, ReplicationBroker.class, "publish"),
+          "the write should wait for the surviving RS instead of being rejected"));
+      releaseSurvivor.countDown();
+      newTimer().repeatUntilSuccess(() -> assertEquals(domain.getRsServerId(), survivor.serverId));
+      localWrite.join(10_000);
+      assertEquals(result.get(), ResultCode.SUCCESS);
+      survivor.waitForUpdates(1);
+    }
+    finally
+    {
+      releaseSilent.countDown();
+      releaseSurvivor.countDown();
+      try
+      {
+        silent.shutdown();
+      }
+      finally
+      {
+        try
+        {
+          survivor.shutdown();
+        }
+        finally
+        {
+          try
+          {
+            cleanUp(former, writer);
+          }
+          finally
+          {
+            setConnectionTimeout(SHORT_CONNECTION_TIMEOUT_MS);
+          }
+        }
+      }
+    }
+  }
+
+  @DataProvider
+  public Object[][] discoveryTimeouts()
+  {
+    return new Object[][] { { 0 }, { 5000 } };
+  }
+
+  @Test(dataProvider = "discoveryTimeouts", timeOut = 120_000)
+  public void discoveryReachesResponsiveServersWhenThereAreMoreCandidatesThanWorkers(int timeoutMillis)
+      throws Exception
+  {
+    TestCaseUtils.initializeTestBackend(true);
+    final List<WithholdingReplicationServer> servers = new ArrayList<>();
+    final CountDownLatch releaseReplies = new CountDownLatch(1);
+    final CompletableFuture<LDAPReplicationDomain> connected = new CompletableFuture<>();
+    final AtomicReference<Thread> starting = new AtomicReference<>();
+    try
+    {
+      setConnectionTimeout(timeoutMillis);
+      for (int id = 2; id <= 6; id++)
+      {
+        servers.add(new WithholdingReplicationServer(LARGE_WINDOW, id));
+      }
+      servers.sort(Comparator.comparing(WithholdingReplicationServer::getAddress));
+      final WithholdingReplicationServer last = servers.get(servers.size() - 1);
+      for (WithholdingReplicationServer server : servers)
+      {
+        if (timeoutMillis != 0)
+        {
+          // Each reply fits the configured connection timeout, even when discovery has two batches.
+          server.beforeStartReply = () -> {
+            releaseReplies.await(3, SECONDS);
+            return null;
+          };
+        }
+        else if (server != last)
+        {
+          // Only the last configured server can answer while the test waits.
+          server.beforeStartReply = () -> {
+            releaseReplies.await();
+            return null;
+          };
+        }
+        if (server != last)
+        {
+          server.start();
+        }
+      }
+      final String[] otherUrls = servers.subList(0, servers.size() - 1).stream()
+          .map(WithholdingReplicationServer::getAddress).toArray(String[]::new);
+      final List<String> records = errorLogRecordsOf(() -> {
+        starting.set(startThread("domain startup", () -> {
+          try
+          {
+            connected.complete(startDomain(last, 100000, otherUrls));
+          }
+          catch (Exception | AssertionError e)
+          {
+            connected.completeExceptionally(e);
+          }
+        }));
+        newTimer().repeatUntilSuccess(() ->
+            assertTrue(connected.isDone(), "discovery did not connect to a responsive server"));
+        return null;
+      });
+      final LDAPReplicationDomain domain = connected.get();
+      assertTrue(domain.isConnected());
+      if (timeoutMillis == 0)
+      {
+        assertEquals(domain.getRsServerId(), last.serverId);
+        assertNotNull(recordOf(records, WARN_TIMEOUT_CONNECTING_TO_RS.get(DS_ID, otherUrls[0], baseDN)));
+      }
+    }
+    finally
+    {
+      releaseReplies.countDown();
+      try
+      {
+        if (starting.get() != null)
+        {
+          starting.get().join(15_000);
+        }
+        for (WithholdingReplicationServer server : servers)
+        {
+          server.shutdown();
+        }
+        MultimasterReplication.deleteDomain(baseDN);
+      }
+      finally
+      {
+        setConnectionTimeout(SHORT_CONNECTION_TIMEOUT_MS);
+      }
+    }
+  }
+
+  @Test(timeOut = 120_000)
   public void failoverTriesAnotherDiscoveryResponderWhenTheFormerRsRefusesConnection() throws Exception
   {
     TestCaseUtils.initializeTestBackend(true);
@@ -1328,10 +1631,6 @@
       oldRS.advertiseRebalance(nextRS, domain);
       newTimer().repeatUntilSuccess(() -> assertEquals(oldRS.count(StopMsg.class), 1));
 
-      if (withholdTopology)
-      {
-        setConnectionTimeout(SHORT_CONNECTION_TIMEOUT_MS);
-      }
       final long stopBound = stopBoundMS();
       final CSN previous = offlineAnnouncementOfTheReplica();
       final Thread stop = startThread("disable after switch StopMsg", domain::disable);
@@ -1361,7 +1660,8 @@
         }
         if (withholdTopology)
         {
-          // A new handshake timeout must not extend the deadline already set by the stop.
+          // The stop's existing deadline leaves time to reach the topology exchange under load.
+          // The much longer handshake timeout must not extend it.
           setConnectionTimeout(60_000);
         }
         oldRS.closeTheSession();
@@ -1506,7 +1806,7 @@
         {
           assertEquals(nextRS.receivedUpdateCSNs(), missing.subList(0, 1));
         }
-        assertNull(offlineAnnouncementOfTheReplica(), "the undelivered marker was not withdrawn");
+        assertFalse(marker.equals(offlineAnnouncementOfTheReplica()), "the undelivered marker was not withdrawn");
       }
     }
     finally
@@ -1751,8 +2051,7 @@
     final boolean firstSortsFirst = first.getAddress().compareTo(second.getAddress()) < 0;
     final WithholdingReplicationServer oldRS = firstSortsFirst ? first : second;
     final WithholdingReplicationServer nextRS = firstSortsFirst ? second : first;
-    final DelayedFailoverHandshake handshake = new DelayedFailoverHandshake(successfulProbes, timedOutReplies,
-        formerRs == FormerRsDuringFailover.DISAPPEARS_AFTER_PROBE ? oldRS.listenSocket : null);
+    final DelayedFailoverHandshake handshake = new DelayedFailoverHandshake(successfulProbes, timedOutReplies);
     final DelayedFailoverHandshake oldHandshake = new DelayedFailoverHandshake(0, 2);
     Thread writer = null;
     try
@@ -1775,6 +2074,14 @@
         {
           oldRS.delayedFailoverHandshake = oldHandshake;
         }
+        else
+        {
+          oldRS.beforeStartReply = () -> {
+            // Its current discovery connection can still answer after it stops accepting new ones.
+            oldRS.listenSocket.close();
+            return null;
+          };
+        }
         oldRS.dropTheSession();
       }
 
@@ -2264,15 +2571,21 @@
 
     void advertiseRebalance(WithholdingReplicationServer nextRS, LDAPReplicationDomain domain) throws IOException
     {
+      advertiseLoad(nextRS, domain, serverId);
+    }
+
+    void advertiseLoad(WithholdingReplicationServer peer, LDAPReplicationDomain domain, int otherDsRsId)
+        throws IOException
+    {
       final long generationId = domain.getGenerationID();
       final byte groupId = domain.getGroupId();
-      final DSInfo otherDS = new DSInfo(OTHER_DS_ID, "", serverId, generationId, ServerStatus.NORMAL_STATUS,
+      final DSInfo otherDS = new DSInfo(OTHER_DS_ID, "", otherDsRsId, generationId, ServerStatus.NORMAL_STATUS,
           false, AssuredMode.SAFE_DATA_MODE, (byte) 0, groupId, Collections.emptyList(), Collections.emptyList(),
           Collections.emptyList(), ProtocolVersion.getCurrentVersion());
       final Session current = session.get();
       current.publish(new TopologyMsg(Collections.singletonList(otherDS), Arrays.asList(
           new RSInfo(serverId, getAddress(), generationId, groupId, 1),
-          new RSInfo(nextRS.serverId, nextRS.getAddress(), generationId, groupId, 1))));
+          new RSInfo(peer.serverId, peer.getAddress(), generationId, groupId, 1))));
       final MonitorMsg monitor = new MonitorMsg(serverId, DS_ID);
       monitor.setReplServerDbState(state.duplicate());
       assertTrue(current.publish(monitor, null));
@@ -2614,67 +2927,4 @@
       }
     }
   }
-
-  /**
-   * A replication server which takes each connection and, once told to, answers nothing on it, as
-   * one which hangs does: a connection to it waits for the connection timeout in its SSL
-   * negotiation. Until then it closes each connection at once, which fails it at once.
-   */
-  private static final class SilentReplicationServer extends Thread
-  {
-    private final ServerSocket listenSocket;
-    private final List<Socket> held = new CopyOnWriteArrayList<>();
-    private volatile boolean silent;
-
-    SilentReplicationServer() throws IOException
-    {
-      super(ReplicationBrokerStopTest.class.getSimpleName() + " silent replication server");
-      setDaemon(true);
-      listenSocket = new ServerSocket(0, 50, InetAddress.getLoopbackAddress());
-    }
-
-    int getPort()
-    {
-      return listenSocket.getLocalPort();
-    }
-
-    @Override
-    public void run()
-    {
-      while (!listenSocket.isClosed())
-      {
-        try
-        {
-          final Socket socket = listenSocket.accept();
-          if (silent)
-          {
-            held.add(socket);
-          }
-          else
-          {
-            socket.close();
-          }
-        }
-        catch (IOException e)
-        {
-          // The test closed this server.
-        }
-      }
-    }
-
-    void answerNothing()
-    {
-      silent = true;
-    }
-
-    void shutdown() throws Exception
-    {
-      listenSocket.close();
-      for (Socket socket : held)
-      {
-        socket.close();
-      }
-      join(30000);
-    }
-  }
 }
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/replication/server/ReplicationServerConnectFailureTest.java b/opendj-server-legacy/src/test/java/org/opends/server/replication/server/ReplicationServerConnectFailureTest.java
index cb97d2c..7bf9e9a 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/replication/server/ReplicationServerConnectFailureTest.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/replication/server/ReplicationServerConnectFailureTest.java
@@ -15,6 +15,7 @@
  */
 package org.opends.server.replication.server;
 
+import static java.nio.charset.StandardCharsets.US_ASCII;
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.forgerock.opendj.ldap.ModificationType.REPLACE;
 import static org.opends.messages.ReplicationMessages.*;
@@ -40,6 +41,9 @@
 import java.util.concurrent.TimeoutException;
 import java.util.concurrent.atomic.AtomicBoolean;
 
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
+
 import org.forgerock.opendj.ldap.DN;
 import org.forgerock.opendj.ldap.ResultCode;
 import org.opends.server.TestCaseUtils;
@@ -104,6 +108,82 @@
   private static final String TRACE_TLS_FAILURES = "org.opends.server.replication.traceTlsFailures";
 
   @DataProvider
+  public Object[][] abortedFirstFrames()
+  {
+    return new Object[][] {
+        { "", false, 0 },
+        { "", true, 0 },
+        { "0", false, 1 },
+        { "00000001", false, 1 }
+    };
+  }
+
+  @Test(dataProvider = "abortedFirstFrames")
+  public void logsAnAbortedFirstFrameOnlyAfterReceivingBytes(String frame, boolean reset, int expectedErrors)
+      throws Exception
+  {
+    TestCaseUtils.startServer();
+    final int port = TestCaseUtils.findFreePort();
+    final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
+    final ReplicationServer rs = new ReplicationServer(new ReplServerFakeConfiguration(
+        port, "replicationServerFirstFrameDb", 0, RS_ID, 0, 100, null));
+    final ReplicationBroker broker = new ReplicationBroker(
+        new DummyReplicationDomain(0), new ServerState(), newFakeCfg(baseDN, 8243, port),
+        getReplSessionSecurity());
+    try
+    {
+      final List<String> records = errorLogRecordsOf(() -> {
+        abortFirstFrame(port, frame, reset);
+        // This succeeds only after the listener has disposed of the previous connection.
+        connect(broker, 0);
+        return null;
+      });
+      assertThat(countRecordsOf(records, "category=SYNC severity=ERROR msgID=86 "))
+          .as("listener errors after receiving %s first-frame bytes, reset=%s", frame.length(), reset)
+          .isEqualTo(expectedErrors);
+    }
+    finally
+    {
+      try
+      {
+        stop(broker);
+      }
+      finally
+      {
+        remove(rs);
+      }
+    }
+  }
+
+  private static void abortFirstFrame(int port, String frame, boolean reset) throws Exception
+  {
+    final SSLSocketFactory factory = getServerContext().getCryptoManager()
+        .getSslContext("Replication Client", null).getSocketFactory();
+    try (Socket socket = new Socket())
+    {
+      socket.connect(new InetSocketAddress("127.0.0.1", port), SOCKET_TIMEOUT_MS);
+      try (SSLSocket tls = (SSLSocket) factory.createSocket(socket, "127.0.0.1", port, false))
+      {
+        tls.setSoTimeout(SOCKET_TIMEOUT_MS);
+        // In a full TLS 1.2 handshake the server sends the last handshake message.
+        tls.setEnabledProtocols(new String[] { "TLSv1.2" });
+        tls.startHandshake();
+        tls.getOutputStream().write(frame.getBytes(US_ASCII));
+        tls.getOutputStream().flush();
+        if (reset)
+        {
+          socket.setSoLinger(true, 0);
+          socket.close();
+        }
+        else
+        {
+          tls.shutdownOutput();
+        }
+      }
+    }
+  }
+
+  @DataProvider
   public Object[][] generationDuringPeerStart()
   {
     return new Object[][] { { false }, { true } };

--
Gitblit v1.10.0