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

SteNicholas pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/celeborn.git


The following commit(s) were added to refs/heads/main by this push:
     new 517a9b196d [CELEBORN-2183] Do not connect to fetch-excluded workers 
when opening shuffle read streams
517a9b196d is described below

commit 517a9b196d20d2f7f2e2f366b0cf392060ff127f
Author: Zihan Dai <[email protected]>
AuthorDate: Wed Nov 11 13:29:08 2026 +0800

    [CELEBORN-2183] Do not connect to fetch-excluded workers when opening 
shuffle read streams
    
    ### What changes were proposed in this pull request?
    
    With `celeborn.client.fetch.excludeWorkerOnFailure.enabled`, the reduce 
side no longer connects to a worker that is already fetch-excluded. When 
`CelebornShuffleReader` decides which copy of a replicated location to open a 
stream on, it now uses the peer if the worker is excluded.
    
    - `CelebornShuffleReader`: the per-partition location choice moves into 
`selectReadLocations`, which picks the copy of each location through 
`chooseReadLocation`. A task attempt that prefers the replica still starts from 
the peer (CELEBORN-2032). If the chosen worker is excluded, the stream is 
opened on its peer. The two reasons are computed separately before the 
skew-partition guard is applied.
    - `ShuffleClient.shouldSkipFetchLocation(PartitionLocation)` and 
`ShuffleClient.hasFetchExcludedWorkers()`: new methods that expose the client's 
fetch-exclusion state to the reader. When nothing is excluded, the second one 
lets the reader skip the per-location lookup. Both return `false` by default 
and `ShuffleClientImpl` overrides them, so other `ShuffleClient` subclasses 
keep compiling unchanged.
    - The rule is the one `CelebornInputStream` already applies, moved 
unchanged from `CelebornInputStreamImpl.isExcluded` into a static 
`CelebornInputStream.isExcluded`. Both `CelebornInputStream` and 
`ShuffleClientImpl.shouldSkipFetchLocation` use it, so the reader and the input 
stream cannot disagree. The rule includes the expiry and the "both copies 
excluded, try the one excluded earlier" tie-break.
    - Nothing changes when no worker is excluded: the reader keeps the original 
location set. Nothing changes for skewed partitions read without a map range 
either, since they must stay on the copy they started with.
    
    ### Why are the changes needed?
    
    CELEBORN-2183 reports a user who ran on Kubernetes with 3 workers, push 
replication and `celeborn.client.fetch.excludeWorkerOnFailure.enabled=true`, 
and scaled the workers down to 2 in the middle of a job. Reduce tasks kept 
logging `Retry create client, times n/3 with error: Connecting to ... timed out 
(10000 ms)` for the removed worker, and each shuffle read took about 30 seconds 
longer. The stack trace points at the batch open stream in 
`CelebornShuffleReader.read`.
    
    `excludeFailedFetchLocation` does record the worker, and 
`CelebornInputStream` honors it: it throws `Fetch data from excluded worker!` 
and switches to the peer. The batch open stream in `CelebornShuffleReader.read` 
never looks at that list, though. So every task still spends 
`TransportClientFactory`'s full retry budget on the excluded worker 
(`celeborn.data.io.maxRetries`, default 3, with `celeborn.data.io.retryWait` of 
5s between tries). Only then does the input stream throw that res [...]
    
    I reproduced this locally with a 3-worker mini cluster, replication and 
fetch exclusion enabled, Spark `local[1]`, and `reduceByKey` into 24 
partitions. The test runs the job once, stops one worker, and runs the same RDD 
again so that only the reduce stage reads. A stopped local port refuses the 
connection immediately, so each try fails fast. The time below is just the 2 
retry waits, not the connect timeouts the reporter saw.
    
    Before (current main; v0.7.0 gives the same numbers, 80481 ms and 8 slow 
tasks):
    
    ```
    REPRO second read took 80430 ms
    second-job tasks with BatchOpenStream >= 1000 ms: 8 of 24 (10008-10016 ms 
each)
    'Failed to create client for ...' warnings for the stopped worker: 8
    'Fetch data from excluded worker' exceptions: 8
    ```
    
    After:
    
    ```
    REPRO second read took 10341 ms
    second-job tasks with BatchOpenStream >= 1000 ms: 1 of 24 (10015 ms, the 
task that hit the failure first)
    'Failed to create client for ...' warnings for the stopped worker: 1
    'Fetch data from excluded worker' exceptions: 1
    ```
    
    An earlier PR, #3517, changed the peer switch inside `CelebornInputStream` 
and was closed as stale. It did not touch the batch open path where the 
reported stack trace is.
    
    ### Does this PR resolve a correctness bug?
    
    - [ ] Yes
    
    ### Does this PR introduce _any_ user-facing change?
    
    - [ ] Yes
    
    No configuration change. With fetch exclusion enabled, reduce tasks stop 
waiting on a worker that is already excluded.
    
    ### How was this patch tested?
    
    - New `CelebornShuffleReaderSuite` test for `chooseReadLocation`, driven by 
`CelebornInputStream.isExcluded` over a real exclusion map. It covers nothing 
excluded, the primary excluded, the replica excluded, both excluded (the one 
excluded earlier is kept), and a location without a peer.
    - New `CelebornShuffleReaderSuite` test for `selectReadLocations` with a 
stubbed client. It covers the exclusion switch, the replica preference, push 
replication off, and the skew-partition guard for both reasons, and it checks 
that nothing is looked up when no worker is excluded.
    - New `CelebornShuffleReaderSuite` test that drives `read()` with a real 
`ShuffleClientImpl` whose RPC endpoint and worker connections are mocked. With 
the primary excluded, the batch open stream's first connection goes to the 
replica's host.
    - New `ShuffleClientSuiteJ` tests. After `excludeFailedFetchLocation` with 
a connect failure, `shouldSkipFetchLocation` is true for that worker and false 
for its peer. With a 1 ms expiry, the exclusion lapses and the lookup removes 
the stale entry.
    - The whole `CelebornShuffleReaderSuite` (13 tests) and the two 
`ShuffleClientSuiteJ` tests pass with `-Pspark-3.5`. The first commit also ran 
the whole `ShuffleClientSuiteJ` and `CelebornInputStreamPeerFailoverTest`.
    - Mutation checks:
      - Dropping the skew-partition guard fails the `selectReadLocations` test.
      - Ignoring exclusions in the reader fails that test and the `read()` 
test. In the `read()` test the first connection goes to `worker-0`, not 
`worker-1`.
    - The reproduction above was run on the Spark 3.5 profile. It is not added 
as a test because its signal is elapsed time.
    - `build/mvn spotless:check -Pspark-3.5 -pl client,client-spark/spark-3` 
passes.
    - I did not run the other Spark profiles or the full suites locally; I am 
leaving those to CI.
    
    Closes #3943 from PDGGK/CELEBORN-2183-skip-excluded-batch-open.
    
    Authored-by: Zihan Dai <[email protected]>
    Signed-off-by: Nicholas Jiang <[email protected]>
---
 .../shuffle/celeborn/CelebornShuffleReader.scala   |  63 ++++--
 .../celeborn/CelebornShuffleReaderSuite.scala      | 216 ++++++++++++++++++++-
 .../org/apache/celeborn/client/ShuffleClient.java  |  18 ++
 .../apache/celeborn/client/ShuffleClientImpl.java  |  11 ++
 .../celeborn/client/read/CelebornInputStream.java  |  48 +++--
 .../celeborn/client/ShuffleClientSuiteJ.java       |  58 ++++++
 6 files changed, 379 insertions(+), 35 deletions(-)

diff --git 
a/client-spark/spark-3/src/main/scala/org/apache/spark/shuffle/celeborn/CelebornShuffleReader.scala
 
b/client-spark/spark-3/src/main/scala/org/apache/spark/shuffle/celeborn/CelebornShuffleReader.scala
index 69202f7039..1c51d943fe 100644
--- 
a/client-spark/spark-3/src/main/scala/org/apache/spark/shuffle/celeborn/CelebornShuffleReader.scala
+++ 
b/client-spark/spark-3/src/main/scala/org/apache/spark/shuffle/celeborn/CelebornShuffleReader.scala
@@ -299,17 +299,14 @@ class CelebornShuffleReader[K, C](
         // a different physical chunk range for the same logical 
sub-partition, causing
         // CRC/byte-count mismatches on retry. So we skip the replica 
preference in that case
         // and always stick with the primary (or previously chosen) location.
-        val originLocations = fileGroups.partitionGroups.get(partitionId)
-        val hasReplicate = pushReplicateEnabled &&
-          originLocations.asScala.exists(p => p != null && p.hasPeer)
-        var locations =
-          if (preferReplicaRead && hasReplicate && 
!splitSkewPartitionWithoutMapRange) {
-            originLocations.asScala.map { p =>
-              if (p != null && p.hasPeer) p.getPeer else p
-            }.asJava
-          } else {
-            originLocations
-          }
+        // CELEBORN-2183. Likewise, open the stream on the peer of a worker 
that is excluded
+        // after a fetch failure, instead of connecting to the excluded worker 
again.
+        var locations = CelebornShuffleReader.selectReadLocations(
+          fileGroups.partitionGroups.get(partitionId),
+          pushReplicateEnabled,
+          splitSkewPartitionWithoutMapRange,
+          preferReplicaRead,
+          shuffleClient)
 
         if (splitSkewPartitionWithoutMapRange) {
           val partitionLocation2ChunkRange = 
CelebornPartitionUtil.splitSkewedPartitionLocations(
@@ -652,6 +649,50 @@ class CelebornShuffleReader[K, C](
 object CelebornShuffleReader {
   var streamCreatorPool: ThreadPoolExecutor = null
 
+  /**
+   * Chooses the locations of a partition to open streams on: the peers of 
replicated locations for
+   * a task attempt that prefers the replica (CELEBORN-2032) or when a 
location's worker is excluded
+   * after a fetch failure (CELEBORN-2183), and the original locations 
otherwise. Skew partitions
+   * read without a map range always keep the original locations.
+   */
+  @VisibleForTesting
+  private[celeborn] def selectReadLocations(
+      originLocations: JSet[PartitionLocation],
+      pushReplicateEnabled: Boolean,
+      splitSkewPartitionWithoutMapRange: Boolean,
+      preferReplicaRead: Boolean,
+      shuffleClient: ShuffleClient): JSet[PartitionLocation] = {
+    val hasReplicate = pushReplicateEnabled &&
+      originLocations.asScala.exists(p => p != null && p.hasPeer)
+    val shouldSkip = (p: PartitionLocation) => 
shuffleClient.shouldSkipFetchLocation(p)
+    val preferPeer = preferReplicaRead || 
(shuffleClient.hasFetchExcludedWorkers &&
+      originLocations.asScala.exists(p => p != null && p.hasPeer && 
shouldSkip(p)))
+    if (hasReplicate && !splitSkewPartitionWithoutMapRange && preferPeer) {
+      originLocations.asScala.map(p => chooseReadLocation(p, 
preferReplicaRead, shouldSkip)).asJava
+    } else {
+      originLocations
+    }
+  }
+
+  /**
+   * Chooses which copy of a replicated location to open a stream on. A task 
attempt with
+   * `preferReplica` starts from the peer (CELEBORN-2032). If the chosen 
worker is excluded after a
+   * fetch failure, use its peer instead: CelebornInputStream would not read 
from the excluded
+   * worker anyway, and connecting to it again costs every task the full 
connection retry budget.
+   */
+  @VisibleForTesting
+  private[celeborn] def chooseReadLocation(
+      location: PartitionLocation,
+      preferReplica: Boolean,
+      shouldSkip: PartitionLocation => Boolean): PartitionLocation = {
+    if (location == null || !location.hasPeer) {
+      location
+    } else {
+      val preferred = if (preferReplica) location.getPeer else location
+      if (preferred.hasPeer && shouldSkip(preferred)) preferred.getPeer else 
preferred
+    }
+  }
+
   @VisibleForTesting
   private[celeborn] def tryCreateClient(
       location: PartitionLocation,
diff --git 
a/client-spark/spark-3/src/test/scala/org/apache/spark/shuffle/celeborn/CelebornShuffleReaderSuite.scala
 
b/client-spark/spark-3/src/test/scala/org/apache/spark/shuffle/celeborn/CelebornShuffleReaderSuite.scala
index ea64b0534d..85dc6e6c43 100644
--- 
a/client-spark/spark-3/src/test/scala/org/apache/spark/shuffle/celeborn/CelebornShuffleReaderSuite.scala
+++ 
b/client-spark/spark-3/src/test/scala/org/apache/spark/shuffle/celeborn/CelebornShuffleReaderSuite.scala
@@ -18,25 +18,38 @@
 package org.apache.spark.shuffle.celeborn
 
 import java.io.IOException
+import java.lang.{Long => JLong}
 import java.nio.file.Files
+import java.util
 import java.util.HashSet
-import java.util.concurrent.{CountDownLatch, TimeoutException, TimeUnit}
+import java.util.concurrent.{ConcurrentHashMap, CopyOnWriteArrayList, 
CountDownLatch, TimeoutException, TimeUnit}
 import java.util.concurrent.atomic.{AtomicBoolean, AtomicInteger, 
AtomicReference}
 
-import org.apache.spark.{Dependency, ShuffleDependency, TaskContext}
+import scala.collection.JavaConverters._
+
+import org.apache.spark.{Dependency, ShuffleDependency, SparkConf, TaskContext}
 import org.apache.spark.celeborn.ExceptionMakerHelper
+import org.apache.spark.executor.TaskMetrics
+import org.apache.spark.serializer.JavaSerializer
 import org.apache.spark.shuffle.ShuffleReadMetricsReporter
-import org.mockito.ArgumentMatchers.any
+import org.mockito.Answers
+import org.mockito.ArgumentMatchers.{any, anyInt, anyString}
 import org.mockito.Mockito
 import org.mockito.Mockito._
+import org.mockito.invocation.InvocationOnMock
+import org.mockito.stubbing.Answer
 import org.scalatest.funsuite.AnyFunSuite
 
-import org.apache.celeborn.client.{DummyShuffleClient, ShuffleClient}
+import org.apache.celeborn.client.{DummyShuffleClient, ShuffleClient, 
ShuffleClientImpl}
+import org.apache.celeborn.client.read.CelebornInputStream
 import org.apache.celeborn.common.CelebornConf
 import org.apache.celeborn.common.exception.CelebornIOException
 import org.apache.celeborn.common.identity.UserIdentifier
-import org.apache.celeborn.common.network.client.TransportClient
-import org.apache.celeborn.common.protocol.PartitionLocation
+import org.apache.celeborn.common.network.client.{TransportClient, 
TransportClientFactory}
+import org.apache.celeborn.common.protocol.{PartitionLocation, PbGetShuffleId, 
PbGetShuffleIdResponse, PbGetStageEnd, PbGetStageEndResponse, 
PbReportShuffleFetchFailure, PbReportShuffleFetchFailureResponse}
+import 
org.apache.celeborn.common.protocol.message.ControlMessages.{GetReducerFileGroup,
 GetReducerFileGroupResponse}
+import org.apache.celeborn.common.protocol.message.StatusCode
+import org.apache.celeborn.common.rpc.RpcEndpointRef
 import org.apache.celeborn.common.util.ThreadUtils
 
 class CelebornShuffleReaderSuite extends AnyFunSuite {
@@ -356,6 +369,197 @@ class CelebornShuffleReaderSuite extends AnyFunSuite {
     }
   }
 
+  test("open the stream on the peer of a fetch-excluded worker") {
+    val primary = newLocation(0, "worker-0", 19098)
+    val replica =
+      new PartitionLocation(0, 0, "worker-1", 0, 0, 19098, 0, 
PartitionLocation.Mode.REPLICA)
+    primary.setPeer(replica)
+    replica.setPeer(primary)
+    val excludedWorkers = new ConcurrentHashMap[String, JLong]()
+    val shouldSkip = (location: PartitionLocation) =>
+      CelebornInputStream.isExcluded(excludedWorkers, 
TimeUnit.MINUTES.toMillis(10), location)
+
+    // Nothing excluded: the primary, or the replica for a task attempt that 
prefers it.
+    assert(CelebornShuffleReader.chooseReadLocation(primary, false, 
shouldSkip) eq primary)
+    assert(CelebornShuffleReader.chooseReadLocation(primary, true, shouldSkip) 
eq replica)
+
+    excludedWorkers.put(primary.hostAndFetchPort, System.currentTimeMillis())
+    assert(CelebornShuffleReader.chooseReadLocation(primary, false, 
shouldSkip) eq replica)
+    assert(CelebornShuffleReader.chooseReadLocation(primary, true, shouldSkip) 
eq replica)
+
+    excludedWorkers.clear()
+    excludedWorkers.put(replica.hostAndFetchPort, System.currentTimeMillis())
+    assert(CelebornShuffleReader.chooseReadLocation(primary, false, 
shouldSkip) eq primary)
+    assert(CelebornShuffleReader.chooseReadLocation(primary, true, shouldSkip) 
eq primary)
+
+    // Both excluded: keep the one excluded earlier, as CelebornInputStream 
does.
+    excludedWorkers.put(primary.hostAndFetchPort, System.currentTimeMillis() - 
1000)
+    assert(CelebornShuffleReader.chooseReadLocation(primary, false, 
shouldSkip) eq primary)
+    assert(CelebornShuffleReader.chooseReadLocation(primary, true, shouldSkip) 
eq primary)
+
+    // Without a peer there is nothing to switch to.
+    val single = newLocation(1, "worker-0", 19098)
+    assert(CelebornShuffleReader.chooseReadLocation(single, false, shouldSkip) 
eq single)
+  }
+
+  test("select read locations for a partition") {
+    val primary = newLocation(0, "worker-0", 19098)
+    val replica =
+      new PartitionLocation(0, 0, "worker-1", 0, 0, 19098, 0, 
PartitionLocation.Mode.REPLICA)
+    primary.setPeer(replica)
+    replica.setPeer(primary)
+    val originLocations: util.Set[PartitionLocation] = new 
HashSet[PartitionLocation]()
+    originLocations.add(primary)
+
+    def select(
+        client: ShuffleClient,
+        pushReplicateEnabled: Boolean = true,
+        splitSkewPartitionWithoutMapRange: Boolean = false,
+        preferReplicaRead: Boolean = false): util.Set[PartitionLocation] =
+      CelebornShuffleReader.selectReadLocations(
+        originLocations,
+        pushReplicateEnabled,
+        splitSkewPartitionWithoutMapRange,
+        preferReplicaRead,
+        client)
+
+    // Nothing excluded: the per-location lookup is skipped altogether.
+    val noneExcluded = mock(classOf[ShuffleClient])
+    assert(select(noneExcluded) eq originLocations)
+    verify(noneExcluded, 
never()).shouldSkipFetchLocation(any[PartitionLocation]())
+    assert(select(noneExcluded, preferReplicaRead = true).asScala.toSet == 
Set(replica))
+
+    val primaryExcluded = mock(classOf[ShuffleClient])
+    when(primaryExcluded.hasFetchExcludedWorkers).thenReturn(true)
+    when(primaryExcluded.shouldSkipFetchLocation(primary)).thenReturn(true)
+    assert(select(primaryExcluded).asScala.toSet == Set(replica))
+    assert(select(primaryExcluded, pushReplicateEnabled = false) eq 
originLocations)
+    // Skew partitions read without a map range keep their locations 
(CELEBORN-2032).
+    assert(select(primaryExcluded, splitSkewPartitionWithoutMapRange = true) 
eq originLocations)
+    assert(select(
+      primaryExcluded,
+      splitSkewPartitionWithoutMapRange = true,
+      preferReplicaRead = true) eq originLocations)
+  }
+
+  test("batch open stream connects to the peer of a fetch-excluded worker") {
+    val shuffleId = 3
+    val partitionId = 0
+    val primary =
+      new PartitionLocation(
+        partitionId,
+        0,
+        "worker-0",
+        0,
+        0,
+        19098,
+        0,
+        PartitionLocation.Mode.PRIMARY)
+    val replica =
+      new PartitionLocation(
+        partitionId,
+        0,
+        "worker-1",
+        0,
+        0,
+        19098,
+        0,
+        PartitionLocation.Mode.REPLICA)
+    primary.setPeer(replica)
+    replica.setPeer(primary)
+    val fileGroups = new util.HashMap[Integer, util.Set[PartitionLocation]]()
+    fileGroups.put(partitionId, util.Collections.singleton(primary))
+    val conf = new CelebornConf()
+      .set(CelebornConf.CLIENT_PUSH_REPLICATE_ENABLED.key, "true")
+      .set(CelebornConf.CLIENT_FETCH_EXCLUDE_WORKER_ON_FAILURE_ENABLED.key, 
"true")
+      .set(CelebornConf.CLIENT_FETCH_MAX_RETRIES_FOR_EACH_REPLICA.key, "1")
+      .set("celeborn.data.io.retryWait", "0ms")
+
+    // Every worker connection fails, so the read ends with an error; what 
matters is which worker
+    // the batch open stream connects to first.
+    val connectedHosts = new CopyOnWriteArrayList[String]()
+    val workerFactory = mock(classOf[TransportClientFactory])
+    when(workerFactory.createClient(anyString(), anyInt())).thenAnswer(new 
Answer[TransportClient] {
+      override def answer(invocation: InvocationOnMock): TransportClient = {
+        connectedHosts.add(invocation.getArgument[String](0))
+        throw new IOException("Connection refused")
+      }
+    })
+    val endpoint = mock(
+      classOf[RpcEndpointRef],
+      new Answer[AnyRef] {
+        override def answer(invocation: InvocationOnMock): AnyRef = {
+          if (invocation.getMethod.getName != "askSync") {
+            Answers.RETURNS_DEFAULTS.answer(invocation)
+          } else {
+            invocation.getArgument[AnyRef](0) match {
+              case _: GetReducerFileGroup =>
+                GetReducerFileGroupResponse(StatusCode.SUCCESS, fileGroups, 
Array(0))
+              case _: PbGetShuffleId =>
+                
PbGetShuffleIdResponse.newBuilder().setShuffleId(shuffleId).setSuccess(true).build()
+              case _: PbReportShuffleFetchFailure =>
+                
PbReportShuffleFetchFailureResponse.newBuilder().setSuccess(true).build()
+              case _: PbGetStageEnd =>
+                PbGetStageEndResponse.newBuilder().setStageEnd(true).build()
+              case other => throw new AssertionError(s"Unexpected RPC: $other")
+            }
+          }
+        }
+      })
+    val client = new ShuffleClientImpl("excluded-peer-test", conf, 
UserIdentifier("test", "test")) {
+      // Replace the factory itself, so that both the batch open stream and 
the partition read
+      // use the mock and no real worker connection is attempted.
+      dataClientFactory.close()
+      dataClientFactory = workerFactory
+    }
+    client.setupLifecycleManagerRef(endpoint)
+    client.excludeFailedFetchLocation(
+      primary.hostAndFetchPort,
+      new CelebornIOException("Connecting to worker-0:19098 timed out (10000 
ms)"))
+
+    val dependency = mock(classOf[ShuffleDependency[Int, Int, Int]])
+    when(dependency.serializer).thenReturn(new JavaSerializer(new 
SparkConf(false)))
+    when(dependency.keyOrdering).thenReturn(None)
+    when(dependency.aggregator).thenReturn(None)
+    val handle = new CelebornShuffleHandle[Int, Int, Int](
+      "excluded-peer-test",
+      "localhost",
+      0,
+      UserIdentifier("test", "test"),
+      shuffleId,
+      false,
+      1,
+      dependency)
+    val context = mock(classOf[TaskContext])
+    when(context.taskMetrics()).thenReturn(TaskMetrics.empty)
+    try {
+      val factory = mockStatic(classOf[ShuffleClient])
+      val reader =
+        try {
+          factory.when(() => ShuffleClient.get(any(), any(), any(), any(), 
any(), any(), any()))
+            .thenReturn(client)
+          new CelebornShuffleReader[Int, Int](
+            handle,
+            partitionId,
+            partitionId + 1,
+            0,
+            Int.MaxValue,
+            context,
+            conf,
+            mock(classOf[ShuffleReadMetricsReporter]),
+            new ExecutorShuffleIdTracker())
+        } finally {
+          factory.close()
+        }
+
+      intercept[Exception](reader.read().foreach(_ => ()))
+      assert(!connectedHosts.isEmpty)
+      assert(connectedHosts.get(0) === replica.getHost)
+    } finally {
+      client.shutdown()
+    }
+  }
+
   test("FetchFailureException message includes workerHost") {
     val workerHost = "celeborn-worker-1"
     val e = ExceptionMakerHelper.SHUFFLE_FETCH_FAILURE_EXCEPTION_MAKER
diff --git a/client/src/main/java/org/apache/celeborn/client/ShuffleClient.java 
b/client/src/main/java/org/apache/celeborn/client/ShuffleClient.java
index dd39d5bc61..7d39dd0370 100644
--- a/client/src/main/java/org/apache/celeborn/client/ShuffleClient.java
+++ b/client/src/main/java/org/apache/celeborn/client/ShuffleClient.java
@@ -500,6 +500,24 @@ public abstract class ShuffleClient {
 
   public abstract void excludeFailedFetchLocation(String hostAndFetchPort, 
Exception e);
 
+  /**
+   * Whether a stream on {@code location} should be opened on its peer 
instead, because its worker
+   * was excluded by {@link #excludeFailedFetchLocation}. This is not a plain 
lookup of the excluded
+   * workers: when both copies of a replicated location are excluded, the copy 
excluded earlier is
+   * read again, so this returns {@code false} for it although its worker is 
excluded.
+   */
+  public boolean shouldSkipFetchLocation(PartitionLocation location) {
+    return false;
+  }
+
+  /**
+   * Whether any worker may be excluded by {@link 
#excludeFailedFetchLocation}, so that callers can
+   * skip {@link #shouldSkipFetchLocation} when none is.
+   */
+  public boolean hasFetchExcludedWorkers() {
+    return false;
+  }
+
   public static void registerDeserializeReducerFileGroupResponseFunction(
       BiFunction<Integer, byte[], ControlMessages.GetReducerFileGroupResponse> 
function) {
     if (!deserializeReducerFileGroupResponseFunction.isPresent()) {
diff --git 
a/client/src/main/java/org/apache/celeborn/client/ShuffleClientImpl.java 
b/client/src/main/java/org/apache/celeborn/client/ShuffleClientImpl.java
index 0a6048a0cd..bc1adf0856 100644
--- a/client/src/main/java/org/apache/celeborn/client/ShuffleClientImpl.java
+++ b/client/src/main/java/org/apache/celeborn/client/ShuffleClientImpl.java
@@ -2282,4 +2282,15 @@ public class ShuffleClientImpl extends ShuffleClient {
       fetchExcludedWorkers.put(hostAndFetchPort, System.currentTimeMillis());
     }
   }
+
+  @Override
+  public boolean shouldSkipFetchLocation(PartitionLocation location) {
+    return CelebornInputStream.isExcluded(
+        fetchExcludedWorkers, conf.clientFetchExcludedWorkerExpireTimeout(), 
location);
+  }
+
+  @Override
+  public boolean hasFetchExcludedWorkers() {
+    return !fetchExcludedWorkers.isEmpty();
+  }
 }
diff --git 
a/client/src/main/java/org/apache/celeborn/client/read/CelebornInputStream.java 
b/client/src/main/java/org/apache/celeborn/client/read/CelebornInputStream.java
index 23d7342e21..bad5da819f 100644
--- 
a/client/src/main/java/org/apache/celeborn/client/read/CelebornInputStream.java
+++ 
b/client/src/main/java/org/apache/celeborn/client/read/CelebornInputStream.java
@@ -200,6 +200,34 @@ public abstract class CelebornInputStream extends 
InputStream {
     return true;
   }
 
+  /**
+   * Whether {@code location} must not be read because its worker was excluded 
after a fetch
+   * failure. If its peer was excluded earlier, the location is tried again 
instead.
+   */
+  public static boolean isExcluded(
+      ConcurrentHashMap<String, Long> fetchExcludedWorkers,
+      long fetchExcludedWorkerExpireTimeout,
+      PartitionLocation location) {
+    Long timestamp = fetchExcludedWorkers.get(location.hostAndFetchPort());
+    if (timestamp == null) {
+      return false;
+    } else if (System.currentTimeMillis() - timestamp > 
fetchExcludedWorkerExpireTimeout) {
+      fetchExcludedWorkers.remove(location.hostAndFetchPort());
+      return false;
+    } else if (location.getPeer() != null) {
+      Long peerTimestamp = 
fetchExcludedWorkers.get(location.getPeer().hostAndFetchPort());
+      // To avoid both replicate locations is excluded, if peer add to 
excluded list earlier,
+      // change to try peer.
+      if (peerTimestamp == null || peerTimestamp < timestamp) {
+        return true;
+      } else {
+        return false;
+      }
+    } else {
+      return true;
+    }
+  }
+
   private static final class CelebornInputStreamImpl extends 
CelebornInputStream {
     private static final Random RAND = new Random();
 
@@ -443,24 +471,8 @@ public abstract class CelebornInputStream extends 
InputStream {
     }
 
     private boolean isExcluded(PartitionLocation location) {
-      Long timestamp = fetchExcludedWorkers.get(location.hostAndFetchPort());
-      if (timestamp == null) {
-        return false;
-      } else if (System.currentTimeMillis() - timestamp > 
fetchExcludedWorkerExpireTimeout) {
-        fetchExcludedWorkers.remove(location.hostAndFetchPort());
-        return false;
-      } else if (location.getPeer() != null) {
-        Long peerTimestamp = 
fetchExcludedWorkers.get(location.getPeer().hostAndFetchPort());
-        // To avoid both replicate locations is excluded, if peer add to 
excluded list earlier,
-        // change to try peer.
-        if (peerTimestamp == null || peerTimestamp < timestamp) {
-          return true;
-        } else {
-          return false;
-        }
-      } else {
-        return true;
-      }
+      return CelebornInputStream.isExcluded(
+          fetchExcludedWorkers, fetchExcludedWorkerExpireTimeout, location);
     }
 
     private static boolean isInterruption(Throwable throwable) {
diff --git 
a/client/src/test/java/org/apache/celeborn/client/ShuffleClientSuiteJ.java 
b/client/src/test/java/org/apache/celeborn/client/ShuffleClientSuiteJ.java
index 82da671a31..677428fb50 100644
--- a/client/src/test/java/org/apache/celeborn/client/ShuffleClientSuiteJ.java
+++ b/client/src/test/java/org/apache/celeborn/client/ShuffleClientSuiteJ.java
@@ -170,6 +170,64 @@ public class ShuffleClientSuiteJ {
     }
   }
 
+  @Test
+  public void testShouldSkipFetchLocationAfterFetchFailure() {
+    CelebornConf conf = new CelebornConf();
+    conf.set(CelebornConf.CLIENT_PUSH_REPLICATE_ENABLED().key(), "true");
+    
conf.set(CelebornConf.CLIENT_FETCH_EXCLUDE_WORKER_ON_FAILURE_ENABLED().key(), 
"true");
+    ShuffleClientImpl client =
+        new ShuffleClientImpl(TEST_APPLICATION_ID, conf, new 
UserIdentifier("mock", "mock"));
+    PartitionLocation primary =
+        new PartitionLocation(0, 0, "worker-0", 1, 2, 3, 4, 
PartitionLocation.Mode.PRIMARY);
+    PartitionLocation replica =
+        new PartitionLocation(0, 0, "worker-1", 1, 2, 3, 4, 
PartitionLocation.Mode.REPLICA);
+    primary.setPeer(replica);
+    replica.setPeer(primary);
+    try {
+      assertFalse(client.hasFetchExcludedWorkers());
+      assertFalse(client.shouldSkipFetchLocation(primary));
+
+      client.excludeFailedFetchLocation(
+          primary.hostAndFetchPort(),
+          new CelebornIOException("Connecting to worker-0:3 timed out (10000 
ms)"));
+
+      assertTrue(client.hasFetchExcludedWorkers());
+      assertTrue(client.shouldSkipFetchLocation(primary));
+      assertFalse(client.shouldSkipFetchLocation(replica));
+    } finally {
+      client.shutdown();
+    }
+  }
+
+  @Test
+  public void testShouldSkipFetchLocationAfterExclusionExpires() throws 
InterruptedException {
+    CelebornConf conf = new CelebornConf();
+    conf.set(CelebornConf.CLIENT_PUSH_REPLICATE_ENABLED().key(), "true");
+    
conf.set(CelebornConf.CLIENT_FETCH_EXCLUDE_WORKER_ON_FAILURE_ENABLED().key(), 
"true");
+    conf.set(CelebornConf.CLIENT_FETCH_EXCLUDED_WORKER_EXPIRE_TIMEOUT().key(), 
"1ms");
+    ShuffleClientImpl client =
+        new ShuffleClientImpl(TEST_APPLICATION_ID, conf, new 
UserIdentifier("mock", "mock"));
+    PartitionLocation primary =
+        new PartitionLocation(0, 0, "worker-0", 1, 2, 3, 4, 
PartitionLocation.Mode.PRIMARY);
+    PartitionLocation replica =
+        new PartitionLocation(0, 0, "worker-1", 1, 2, 3, 4, 
PartitionLocation.Mode.REPLICA);
+    primary.setPeer(replica);
+    replica.setPeer(primary);
+    try {
+      client.excludeFailedFetchLocation(
+          primary.hostAndFetchPort(),
+          new CelebornIOException("Connecting to worker-0:3 timed out (10000 
ms)"));
+      assertTrue(client.hasFetchExcludedWorkers());
+      Thread.sleep(10);
+
+      // The expired exclusion no longer applies, and the lookup drops the 
stale entry.
+      assertFalse(client.shouldSkipFetchLocation(primary));
+      assertFalse(client.hasFetchExcludedWorkers());
+    } finally {
+      client.shutdown();
+    }
+  }
+
   @Test
   public void testHardSplitPushSchedulesRetryAndClearsBatchAfterRevive() 
throws Exception {
     CelebornConf conf = retryIntegrationTestConf();

Reply via email to