rich7420 commented on code in PR #11874:
URL: https://github.com/apache/ozone/pull/11874#discussion_r4705099151


##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -858,63 +878,358 @@ protected boolean shouldBlockAndWaitAsyncReply(
     return !HddsUtils.isReadOnly(request);
   }
 
+  /**
+   * Sends the request to the given datanode for a caller that waits for the
+   * reply with {@link CompletableFuture#get()}: the response is delivered on
+   * the waiting thread, see {@link CallerRunsReplyFuture}.
+   */
   @VisibleForTesting
   public XceiverClientReply sendCommandAsync(
       ContainerCommandRequestProto request, DatanodeDetails dn)
       throws IOException, InterruptedException {
+    return sendCommandAsync(request, dn, new CallerRunsReplyFuture());
+  }
+
+  /**
+   * @param replyFuture completed with the reply; if it is an {@link Executor}
+   *        the call's callbacks run on it, otherwise on gRPC's default 
executor
+   */
+  private XceiverClientReply sendCommandAsync(
+      ContainerCommandRequestProto request, DatanodeDetails dn,
+      CompletableFuture<ContainerCommandResponseProto> replyFuture)
+      throws IOException, InterruptedException {
     checkOpen(dn);
     DatanodeID dnId = dn.getID();
     if (LOG.isDebugEnabled()) {
       LOG.debug("Send command {} to datanode {}",
           request.getCmdType(), dn);
     }
-    final CompletableFuture<ContainerCommandResponseProto> replyFuture =
-        new CompletableFuture<>();
     semaphore.acquire();
     long requestTime = Time.monotonicNow();
     metrics.incrPendingContainerOpsMetrics(request.getCmdType());
 
+    final ChannelInfo channelInfo = dnChannelInfoMap.get(dnId);
+    final ReplyObserver reply = new ReplyObserver(request, dn, replyFuture, 
requestTime);
+    if (pooledStreamsEnabled && replyFuture instanceof CallerRunsReplyFuture
+        && !Span.current().getSpanContext().isValid()) {
+      // No trace context to send, so a pooled stream carries the same headers 
as a new one would.
+      channelInfo.leaseStream().send(request, reply, (CallerRunsReplyFuture) 
replyFuture,
+          System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout));
+      return new XceiverClientReply(replyFuture);
+    }
+
+    XceiverClientProtocolServiceStub stub = 
channelInfo.getStub().withDeadlineAfter(timeout, TimeUnit.MILLISECONDS);
+    if (replyFuture instanceof Executor) {
+      stub = stub.withExecutor((Executor) replyFuture);
+    }
     // create a new grpc message stream pair for each call.
-    final StreamObserver<ContainerCommandRequestProto> requestObserver =
-        dnChannelInfoMap.get(dnId).getStub().withDeadlineAfter(timeout, 
TimeUnit.MILLISECONDS)
-            .send(new StreamObserver<ContainerCommandResponseProto>() {
-              @Override
-              public void onNext(ContainerCommandResponseProto value) {
-                replyFuture.complete(value);
-                decreasePendingMetricsAndReleaseSemaphore();
-              }
-
-              @Override
-              public void onError(Throwable t) {
-                replyFuture.completeExceptionally(t);
-                decreasePendingMetricsAndReleaseSemaphore();
-              }
-
-              @Override
-              public void onCompleted() {
-                if (!replyFuture.isDone()) {
-                  replyFuture.completeExceptionally(new IOException(
-                      "Stream completed but no reply for request " +
-                          processForDebug(request)));
-                }
-              }
-
-              private void decreasePendingMetricsAndReleaseSemaphore() {
-                metrics.decrPendingContainerOpsMetrics(request.getCmdType());
-                long cost = Time.monotonicNow() - requestTime;
-                metrics.addContainerOpsLatency(request.getCmdType(), cost);
-                if (LOG.isDebugEnabled()) {
-                  LOG.debug("Executed command {} on datanode {}, cost = {}, 
cmdType = {}",
-                      processForDebug(request), dn, cost, 
request.getCmdType());
-                }
-                semaphore.release();
-              }
-            });
+    final StreamObserver<ContainerCommandRequestProto> requestObserver = 
stub.send(reply);
     requestObserver.onNext(request);
     requestObserver.onCompleted();
     return new XceiverClientReply(replyFuture);
   }
 
+  /**
+   * Receives the reply to one request: completes its future, then releases
+   * its semaphore permit and updates the metrics.
+   */
+  @VisibleForTesting
+  final class ReplyObserver implements 
StreamObserver<ContainerCommandResponseProto> {
+    private final ContainerCommandRequestProto request;
+    private final DatanodeDetails dn;
+    private final CompletableFuture<ContainerCommandResponseProto> replyFuture;
+    private final long requestTime;
+
+    ReplyObserver(ContainerCommandRequestProto request, DatanodeDetails dn,
+        CompletableFuture<ContainerCommandResponseProto> replyFuture, long 
requestTime) {
+      this.request = request;
+      this.dn = dn;
+      this.replyFuture = replyFuture;
+      this.requestTime = requestTime;
+    }
+
+    @Override
+    public void onNext(ContainerCommandResponseProto value) {
+      replyFuture.complete(value);
+      decreasePendingMetricsAndReleaseSemaphore();
+    }
+
+    @Override
+    public void onError(Throwable t) {
+      replyFuture.completeExceptionally(t);
+      decreasePendingMetricsAndReleaseSemaphore();
+    }
+
+    @Override
+    public void onCompleted() {
+      if (!replyFuture.isDone()) {
+        replyFuture.completeExceptionally(new IOException(
+            "Stream completed but no reply for request " +
+                processForDebug(request)));
+      }
+    }
+
+    private void decreasePendingMetricsAndReleaseSemaphore() {
+      metrics.decrPendingContainerOpsMetrics(request.getCmdType());
+      long cost = Time.monotonicNow() - requestTime;
+      metrics.addContainerOpsLatency(request.getCmdType(), cost);
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("Executed command {} on datanode {}, cost = {}, cmdType = 
{}",
+            processForDebug(request), dn, cost, request.getCmdType());
+      }
+      semaphore.release();
+    }
+  }
+
+  /**
+   * A send stream kept open across requests, so a request does not pay for
+   * opening and closing an HTTP/2 stream. It carries one request at a time:
+   * the datanode serves the requests of a stream in order and replies to each
+   * one, so the next reply always belongs to the current request. The gRPC
+   * callbacks run on the current request's {@link CallerRunsReplyFuture}, as
+   * for a stream opened per request.
+   */
+  @VisibleForTesting
+  static final class PooledStream implements Executor,
+      ClientResponseObserver<ContainerCommandRequestProto, 
ContainerCommandResponseProto> {
+    private final ChannelInfo owner;
+    private ClientCallStreamObserver<ContainerCommandRequestProto> 
requestStream;
+    private final AtomicReference<ReplyObserver> current = new 
AtomicReference<>();
+    private volatile CallerRunsReplyFuture currentFuture;
+    private volatile boolean closed;
+    private volatile long idleSinceNanos;
+
+    PooledStream(ChannelInfo owner) {
+      this.owner = owner;
+    }
+
+    @Override
+    public void 
beforeStart(ClientCallStreamObserver<ContainerCommandRequestProto> stream) {
+      requestStream = stream;
+    }
+
+    void send(ContainerCommandRequestProto request, ReplyObserver reply, 
CallerRunsReplyFuture future,
+        long deadlineNanos) {
+      future.setDeadline(deadlineNanos, () -> cancel(reply));
+      currentFuture = future;
+      current.set(reply);
+      if (closed && current.compareAndSet(reply, null)) {
+        // the stream ended after it was leased, before the request was 
attached, so its callbacks did not fail it
+        currentFuture = null;
+        reply.onError(Status.UNAVAILABLE.withDescription("pooled stream closed 
before the request was sent")
+            .asRuntimeException());
+        return;
+      }
+      requestStream.onNext(request);
+    }
+
+    @Override
+    public void execute(Runnable task) {
+      final CallerRunsReplyFuture future = current.get() != null ? 
currentFuture : null;
+      if (future != null) {
+        future.execute(task);
+      } else {
+        task.run();
+      }
+    }
+
+    @Override
+    public void onNext(ContainerCommandResponseProto value) {
+      final ReplyObserver reply = current.getAndSet(null);
+      currentFuture = null;
+      if (reply == null) {
+        // no request is attached, e.g. it was abandoned just before this 
reply: never reuse the stream
+        closed = true;
+        requestStream.cancel("reply without a request", null);
+        return;
+      }
+      // back in the pool before the permit is released, so the thread woken 
by the permit finds the stream
+      owner.releaseStream(this);
+      reply.onNext(value);
+    }
+
+    @Override
+    public void onError(Throwable t) {
+      closed = true;
+      final ReplyObserver reply = current.getAndSet(null);
+      currentFuture = null;
+      if (reply != null) {
+        reply.onError(t);
+      }
+    }
+
+    @Override
+    public void onCompleted() {
+      closed = true;
+      final ReplyObserver reply = current.getAndSet(null);
+      currentFuture = null;
+      if (reply != null) {
+        reply.onCompleted();
+      }
+    }
+
+    boolean isClosed() {
+      return closed;
+    }
+
+    void setIdleSince(long nanos) {
+      idleSinceNanos = nanos;
+    }
+
+    long getIdleSince() {
+      return idleSinceNanos;
+    }
+
+    /** Ends an idle stream, the datanode then completes it. */
+    void halfClose() {
+      closed = true;
+      requestStream.onCompleted();
+    }
+
+    /**
+     * Called when the request timed out or its waiter gave up: fails the 
request and drops the stream, unless
+     * its reply already returned the stream to the pool, where the stream may 
carry another request by now.
+     */
+    private void cancel(ReplyObserver reply) {
+      if (current.compareAndSet(reply, null)) {
+        currentFuture = null;
+        closed = true;
+        requestStream.cancel("request abandoned by the client", null);
+        reply.onError(Status.CANCELLED.withDescription("request abandoned by 
the client").asRuntimeException());
+      }
+    }
+  }
+
+  /**
+   * Reply future that is also the gRPC call executor. The callbacks of the
+   * call are queued and run by the thread waiting in {@link #get()}, so the
+   * response is parsed and the future completed on the caller, without a
+   * hand-off through gRPC's shared executor (as gRPC blocking stubs do).
+   * Once the waiter returns, queued and later callbacks run directly.
+   * Only {@code get} runs the callbacks and enforces the deadline: without a
+   * caller in {@code get}, {@code join()} or a dependent stage never 
completes.
+   */
+  @VisibleForTesting
+  static final class CallerRunsReplyFuture
+      extends CompletableFuture<ContainerCommandResponseProto> implements 
Executor {
+    private static final Runnable WAKE_UP = () -> { };
+    private final LinkedBlockingQueue<Runnable> tasks = new 
LinkedBlockingQueue<>();
+    private boolean detached;
+    // set for a request on a pooled stream, which has no gRPC deadline
+    private long deadlineNanos;
+    private Runnable onAbandon;
+
+    /**
+     * The waiter fails the request with DEADLINE_EXCEEDED once {@code 
deadline}
+     * (in {@link System#nanoTime()}) passes, and runs {@code abandon} when it
+     * times out or gives up before the reply.
+     */
+    void setDeadline(long deadline, Runnable abandon) {
+      this.deadlineNanos = deadline;
+      this.onAbandon = abandon;
+    }
+
+    // A pooled stream's callbacks may run on another request's waiter, so 
wake this one up.
+    @Override
+    public boolean complete(ContainerCommandResponseProto value) {
+      final boolean completed = super.complete(value);
+      execute(WAKE_UP);
+      return completed;
+    }
+
+    @Override
+    public boolean completeExceptionally(Throwable ex) {
+      final boolean completed = super.completeExceptionally(ex);
+      execute(WAKE_UP);
+      return completed;
+    }
+
+    @Override
+    public void execute(Runnable task) {
+      synchronized (tasks) {
+        if (!detached) {
+          tasks.add(task);
+          return;
+        }
+      }
+      task.run();
+    }
+
+    @Override
+    public ContainerCommandResponseProto get() throws InterruptedException, 
ExecutionException {
+      try {
+        if (onAbandon == null) {
+          while (!isDone()) {
+            tasks.take().run();
+          }
+        } else {
+          runTasksUntil(deadlineNanos);
+        }
+      } finally {
+        detach();
+      }
+      return super.get();
+    }
+
+    @Override
+    public ContainerCommandResponseProto get(long time, TimeUnit unit)
+        throws InterruptedException, ExecutionException, TimeoutException {
+      final long deadline = System.nanoTime() + unit.toNanos(time);
+      boolean timedOut = false;
+      try {
+        if (onAbandon != null && deadlineNanos - deadline <= 0) {
+          runTasksUntil(deadlineNanos);
+        } else {
+          runTasksUntil(deadline, false);
+          timedOut = !isDone();
+        }
+      } finally {
+        detach();
+      }
+      if (timedOut) {
+        throw new TimeoutException("timed out waiting for the reply");
+      }
+      return super.get(0, TimeUnit.NANOSECONDS);
+    }
+
+    /** Runs the queued callbacks until the reply arrives or the request 
deadline passes. */
+    private void runTasksUntil(long deadline) throws InterruptedException {
+      runTasksUntil(deadline, true);
+    }
+
+    private void runTasksUntil(long deadline, boolean requestDeadline) throws 
InterruptedException {
+      while (!isDone()) {
+        final long remaining = deadline - System.nanoTime();
+        if (remaining <= 0) {
+          if (requestDeadline) {
+            // what the gRPC call deadline reports for a stream opened per 
request
+            completeExceptionally(Status.DEADLINE_EXCEEDED.withDescription(
+                "deadline exceeded waiting for the 
reply").asRuntimeException());
+            onAbandon.run();
+          }
+          return;
+        }
+        final Runnable task = tasks.poll(remaining, TimeUnit.NANOSECONDS);
+        if (task != null) {
+          task.run();
+        }
+      }
+    }
+
+    private void detach() {
+      if (!isDone() && onAbandon != null) {

Review Comment:
   After an interrupt, a late per-call reply ran on `grpc-nio-worker` for me. 
Cancel here too?



##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -858,63 +878,358 @@ protected boolean shouldBlockAndWaitAsyncReply(
     return !HddsUtils.isReadOnly(request);
   }
 
+  /**
+   * Sends the request to the given datanode for a caller that waits for the
+   * reply with {@link CompletableFuture#get()}: the response is delivered on
+   * the waiting thread, see {@link CallerRunsReplyFuture}.
+   */
   @VisibleForTesting
   public XceiverClientReply sendCommandAsync(
       ContainerCommandRequestProto request, DatanodeDetails dn)
       throws IOException, InterruptedException {
+    return sendCommandAsync(request, dn, new CallerRunsReplyFuture());
+  }
+
+  /**
+   * @param replyFuture completed with the reply; if it is an {@link Executor}
+   *        the call's callbacks run on it, otherwise on gRPC's default 
executor
+   */
+  private XceiverClientReply sendCommandAsync(
+      ContainerCommandRequestProto request, DatanodeDetails dn,
+      CompletableFuture<ContainerCommandResponseProto> replyFuture)
+      throws IOException, InterruptedException {
     checkOpen(dn);
     DatanodeID dnId = dn.getID();
     if (LOG.isDebugEnabled()) {
       LOG.debug("Send command {} to datanode {}",
           request.getCmdType(), dn);
     }
-    final CompletableFuture<ContainerCommandResponseProto> replyFuture =
-        new CompletableFuture<>();
     semaphore.acquire();
     long requestTime = Time.monotonicNow();
     metrics.incrPendingContainerOpsMetrics(request.getCmdType());
 
+    final ChannelInfo channelInfo = dnChannelInfoMap.get(dnId);
+    final ReplyObserver reply = new ReplyObserver(request, dn, replyFuture, 
requestTime);
+    if (pooledStreamsEnabled && replyFuture instanceof CallerRunsReplyFuture
+        && !Span.current().getSpanContext().isValid()) {
+      // No trace context to send, so a pooled stream carries the same headers 
as a new one would.
+      channelInfo.leaseStream().send(request, reply, (CallerRunsReplyFuture) 
replyFuture,
+          System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout));
+      return new XceiverClientReply(replyFuture);
+    }
+
+    XceiverClientProtocolServiceStub stub = 
channelInfo.getStub().withDeadlineAfter(timeout, TimeUnit.MILLISECONDS);
+    if (replyFuture instanceof Executor) {
+      stub = stub.withExecutor((Executor) replyFuture);
+    }
     // create a new grpc message stream pair for each call.
-    final StreamObserver<ContainerCommandRequestProto> requestObserver =
-        dnChannelInfoMap.get(dnId).getStub().withDeadlineAfter(timeout, 
TimeUnit.MILLISECONDS)
-            .send(new StreamObserver<ContainerCommandResponseProto>() {
-              @Override
-              public void onNext(ContainerCommandResponseProto value) {
-                replyFuture.complete(value);
-                decreasePendingMetricsAndReleaseSemaphore();
-              }
-
-              @Override
-              public void onError(Throwable t) {
-                replyFuture.completeExceptionally(t);
-                decreasePendingMetricsAndReleaseSemaphore();
-              }
-
-              @Override
-              public void onCompleted() {
-                if (!replyFuture.isDone()) {
-                  replyFuture.completeExceptionally(new IOException(
-                      "Stream completed but no reply for request " +
-                          processForDebug(request)));
-                }
-              }
-
-              private void decreasePendingMetricsAndReleaseSemaphore() {
-                metrics.decrPendingContainerOpsMetrics(request.getCmdType());
-                long cost = Time.monotonicNow() - requestTime;
-                metrics.addContainerOpsLatency(request.getCmdType(), cost);
-                if (LOG.isDebugEnabled()) {
-                  LOG.debug("Executed command {} on datanode {}, cost = {}, 
cmdType = {}",
-                      processForDebug(request), dn, cost, 
request.getCmdType());
-                }
-                semaphore.release();
-              }
-            });
+    final StreamObserver<ContainerCommandRequestProto> requestObserver = 
stub.send(reply);
     requestObserver.onNext(request);
     requestObserver.onCompleted();
     return new XceiverClientReply(replyFuture);
   }
 
+  /**
+   * Receives the reply to one request: completes its future, then releases
+   * its semaphore permit and updates the metrics.
+   */
+  @VisibleForTesting
+  final class ReplyObserver implements 
StreamObserver<ContainerCommandResponseProto> {
+    private final ContainerCommandRequestProto request;
+    private final DatanodeDetails dn;
+    private final CompletableFuture<ContainerCommandResponseProto> replyFuture;
+    private final long requestTime;
+
+    ReplyObserver(ContainerCommandRequestProto request, DatanodeDetails dn,
+        CompletableFuture<ContainerCommandResponseProto> replyFuture, long 
requestTime) {
+      this.request = request;
+      this.dn = dn;
+      this.replyFuture = replyFuture;
+      this.requestTime = requestTime;
+    }
+
+    @Override
+    public void onNext(ContainerCommandResponseProto value) {
+      replyFuture.complete(value);
+      decreasePendingMetricsAndReleaseSemaphore();
+    }
+
+    @Override
+    public void onError(Throwable t) {
+      replyFuture.completeExceptionally(t);
+      decreasePendingMetricsAndReleaseSemaphore();
+    }
+
+    @Override
+    public void onCompleted() {
+      if (!replyFuture.isDone()) {
+        replyFuture.completeExceptionally(new IOException(
+            "Stream completed but no reply for request " +
+                processForDebug(request)));
+      }
+    }
+
+    private void decreasePendingMetricsAndReleaseSemaphore() {
+      metrics.decrPendingContainerOpsMetrics(request.getCmdType());
+      long cost = Time.monotonicNow() - requestTime;
+      metrics.addContainerOpsLatency(request.getCmdType(), cost);
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("Executed command {} on datanode {}, cost = {}, cmdType = 
{}",
+            processForDebug(request), dn, cost, request.getCmdType());
+      }
+      semaphore.release();
+    }
+  }
+
+  /**
+   * A send stream kept open across requests, so a request does not pay for
+   * opening and closing an HTTP/2 stream. It carries one request at a time:
+   * the datanode serves the requests of a stream in order and replies to each
+   * one, so the next reply always belongs to the current request. The gRPC
+   * callbacks run on the current request's {@link CallerRunsReplyFuture}, as
+   * for a stream opened per request.
+   */
+  @VisibleForTesting
+  static final class PooledStream implements Executor,
+      ClientResponseObserver<ContainerCommandRequestProto, 
ContainerCommandResponseProto> {
+    private final ChannelInfo owner;
+    private ClientCallStreamObserver<ContainerCommandRequestProto> 
requestStream;
+    private final AtomicReference<ReplyObserver> current = new 
AtomicReference<>();
+    private volatile CallerRunsReplyFuture currentFuture;
+    private volatile boolean closed;
+    private volatile long idleSinceNanos;
+
+    PooledStream(ChannelInfo owner) {
+      this.owner = owner;
+    }
+
+    @Override
+    public void 
beforeStart(ClientCallStreamObserver<ContainerCommandRequestProto> stream) {
+      requestStream = stream;
+    }
+
+    void send(ContainerCommandRequestProto request, ReplyObserver reply, 
CallerRunsReplyFuture future,
+        long deadlineNanos) {
+      future.setDeadline(deadlineNanos, () -> cancel(reply));
+      currentFuture = future;
+      current.set(reply);
+      if (closed && current.compareAndSet(reply, null)) {
+        // the stream ended after it was leased, before the request was 
attached, so its callbacks did not fail it
+        currentFuture = null;
+        reply.onError(Status.UNAVAILABLE.withDescription("pooled stream closed 
before the request was sent")
+            .asRuntimeException());
+        return;
+      }
+      requestStream.onNext(request);
+    }
+
+    @Override
+    public void execute(Runnable task) {
+      final CallerRunsReplyFuture future = current.get() != null ? 
currentFuture : null;
+      if (future != null) {
+        future.execute(task);
+      } else {
+        task.run();
+      }
+    }
+
+    @Override
+    public void onNext(ContainerCommandResponseProto value) {
+      final ReplyObserver reply = current.getAndSet(null);
+      currentFuture = null;
+      if (reply == null) {
+        // no request is attached, e.g. it was abandoned just before this 
reply: never reuse the stream
+        closed = true;
+        requestStream.cancel("reply without a request", null);
+        return;
+      }
+      // back in the pool before the permit is released, so the thread woken 
by the permit finds the stream
+      owner.releaseStream(this);
+      reply.onNext(value);
+    }
+
+    @Override
+    public void onError(Throwable t) {
+      closed = true;
+      final ReplyObserver reply = current.getAndSet(null);
+      currentFuture = null;
+      if (reply != null) {
+        reply.onError(t);
+      }
+    }
+
+    @Override
+    public void onCompleted() {
+      closed = true;
+      final ReplyObserver reply = current.getAndSet(null);
+      currentFuture = null;
+      if (reply != null) {
+        reply.onCompleted();
+      }
+    }
+
+    boolean isClosed() {
+      return closed;
+    }
+
+    void setIdleSince(long nanos) {
+      idleSinceNanos = nanos;
+    }
+
+    long getIdleSince() {
+      return idleSinceNanos;
+    }
+
+    /** Ends an idle stream, the datanode then completes it. */
+    void halfClose() {
+      closed = true;
+      requestStream.onCompleted();
+    }
+
+    /**
+     * Called when the request timed out or its waiter gave up: fails the 
request and drops the stream, unless
+     * its reply already returned the stream to the pool, where the stream may 
carry another request by now.
+     */
+    private void cancel(ReplyObserver reply) {
+      if (current.compareAndSet(reply, null)) {
+        currentFuture = null;
+        closed = true;
+        requestStream.cancel("request abandoned by the client", null);
+        reply.onError(Status.CANCELLED.withDescription("request abandoned by 
the client").asRuntimeException());
+      }
+    }
+  }
+
+  /**
+   * Reply future that is also the gRPC call executor. The callbacks of the
+   * call are queued and run by the thread waiting in {@link #get()}, so the
+   * response is parsed and the future completed on the caller, without a
+   * hand-off through gRPC's shared executor (as gRPC blocking stubs do).
+   * Once the waiter returns, queued and later callbacks run directly.
+   * Only {@code get} runs the callbacks and enforces the deadline: without a
+   * caller in {@code get}, {@code join()} or a dependent stage never 
completes.
+   */
+  @VisibleForTesting
+  static final class CallerRunsReplyFuture
+      extends CompletableFuture<ContainerCommandResponseProto> implements 
Executor {
+    private static final Runnable WAKE_UP = () -> { };
+    private final LinkedBlockingQueue<Runnable> tasks = new 
LinkedBlockingQueue<>();
+    private boolean detached;
+    // set for a request on a pooled stream, which has no gRPC deadline
+    private long deadlineNanos;
+    private Runnable onAbandon;
+
+    /**
+     * The waiter fails the request with DEADLINE_EXCEEDED once {@code 
deadline}
+     * (in {@link System#nanoTime()}) passes, and runs {@code abandon} when it
+     * times out or gives up before the reply.
+     */
+    void setDeadline(long deadline, Runnable abandon) {
+      this.deadlineNanos = deadline;
+      this.onAbandon = abandon;
+    }
+
+    // A pooled stream's callbacks may run on another request's waiter, so 
wake this one up.
+    @Override
+    public boolean complete(ContainerCommandResponseProto value) {
+      final boolean completed = super.complete(value);
+      execute(WAKE_UP);

Review Comment:
   I removed both `WAKE_UP` calls and all 23 tests still passed. Worth a test?



##########
hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientGrpc.java:
##########
@@ -981,5 +1321,101 @@ public boolean isChannelInactive() {
           || channel.isTerminated()
           || channel.isShutdown();
     }
+
+    /** Takes an idle pooled stream, or opens a new one. */
+    PooledStream leaseStream() {
+      for (PooledStream stream = idleStreams.poll(); stream != null; stream = 
idleStreams.poll()) {
+        if (!stream.isClosed()) {
+          return stream;
+        }
+      }
+      if (watchingState.compareAndSet(false, true)) {
+        onStateChange();
+      }
+      final PooledStream stream = new PooledStream(this);
+      stub.withExecutor(stream).send(stream);
+      return stream;
+    }
+
+    int getIdleStreamCount() {
+      int count = 0;
+      for (PooledStream stream : idleStreams) {
+        if (!stream.isClosed()) {
+          count++;
+        }
+      }
+      return count;
+    }
+
+    void releaseStream(PooledStream stream) {
+      if (stream.isClosed()) {
+        return;
+      }
+      stream.setIdleSince(System.nanoTime());
+      idleStreams.push(stream);
+      if (channel.getState(false) != ConnectivityState.READY) {

Review Comment:
   Removing this check still passed all 23 tests. Maybe `trimIdleStreams` needs 
the same check too?



##########
hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/TestXceiverClientGrpcCallerRuns.java:
##########
@@ -0,0 +1,679 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hdds.scm;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+
+import io.opentelemetry.api.trace.Span;
+import io.opentelemetry.api.trace.SpanContext;
+import io.opentelemetry.api.trace.TraceFlags;
+import io.opentelemetry.api.trace.TraceState;
+import io.opentelemetry.context.Scope;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.DatanodeID;
+import org.apache.hadoop.hdds.protocol.MockDatanodeDetails;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import 
org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ContainerCommandRequestProto;
+import 
org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ContainerCommandResponseProto;
+import 
org.apache.hadoop.hdds.protocol.datanode.proto.XceiverClientProtocolServiceGrpc;
+import org.apache.hadoop.hdds.ratis.conf.RatisClientConfig;
+import org.apache.hadoop.hdds.scm.pipeline.MockPipeline;
+import org.apache.hadoop.ozone.common.utils.BufferUtils;
+import org.apache.ozone.test.GenericTestUtils;
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.apache.ratis.thirdparty.io.grpc.Server;
+import org.apache.ratis.thirdparty.io.grpc.Status;
+import org.apache.ratis.thirdparty.io.grpc.netty.NettyChannelBuilder;
+import org.apache.ratis.thirdparty.io.grpc.netty.NettyServerBuilder;
+import org.apache.ratis.thirdparty.io.grpc.stub.ClientCallStreamObserver;
+import org.apache.ratis.thirdparty.io.grpc.stub.StreamObserver;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests that {@link XceiverClientGrpc} delivers the reply of a blocking call
+ * on the waiting thread, and that the async path is unchanged.
+ */
+class TestXceiverClientGrpcCallerRuns {
+
+  private final List<Server> servers = new ArrayList<>();
+  private Server server;
+  private volatile boolean fail;
+  private volatile ContainerCommandResponseProto response;
+  private volatile boolean hang;
+  private volatile boolean duplicateReply;
+  private volatile Server hangingServer;
+  private volatile CountDownLatch barrier;
+  private final AtomicInteger streamsOpened = new AtomicInteger();
+  private final AtomicInteger streamsEnded = new AtomicInteger();
+  private DatanodeDetails dn;
+  private XceiverClientGrpc client;
+
+  @BeforeEach
+  void setUp() throws Exception {
+    dn = startServer();
+    server = servers.get(0);
+    client = newClient(Collections.singletonList(dn), new 
OzoneConfiguration());
+  }
+
+  /** Starts a server and returns the datanode that it stands for. */
+  private DatanodeDetails startServer() throws IOException {
+    final AtomicReference<Server> self = new AtomicReference<>();
+    final Server started = NettyServerBuilder.forPort(0)
+        .addService(new 
XceiverClientProtocolServiceGrpc.XceiverClientProtocolServiceImplBase() {
+          @Override
+          public StreamObserver<ContainerCommandRequestProto> send(
+              StreamObserver<ContainerCommandResponseProto> responseObserver) {
+            streamsOpened.incrementAndGet();
+            return new StreamObserver<ContainerCommandRequestProto>() {
+              @Override
+              public void onNext(ContainerCommandRequestProto request) {
+                final CountDownLatch latch = barrier;
+                if (latch != null) {
+                  latch.countDown();
+                  try {
+                    latch.await(30, TimeUnit.SECONDS);
+                  } catch (InterruptedException e) {
+                    Thread.currentThread().interrupt();
+                  }
+                }
+                if (hang || self.get() == hangingServer) {
+                  return;
+                }
+                if (fail) {
+                  
responseObserver.onError(Status.INTERNAL.withDescription("injected").asException());
+                  return;
+                }
+                final ContainerCommandResponseProto reply = response;
+                responseObserver.onNext(reply != null ? reply : 
ContainerCommandResponseProto.newBuilder()
+                    .setCmdType(request.getCmdType())
+                    .setResult(ContainerProtos.Result.SUCCESS)
+                    .build());
+                if (duplicateReply) {
+                  
responseObserver.onNext(ContainerCommandResponseProto.newBuilder()
+                      .setCmdType(request.getCmdType())
+                      .setResult(ContainerProtos.Result.SUCCESS)
+                      .build());
+                }
+              }
+
+              @Override
+              public void onError(Throwable t) {
+                streamsEnded.incrementAndGet();
+              }
+
+              @Override
+              public void onCompleted() {
+                streamsEnded.incrementAndGet();
+                // like a datanode, a server that is still serving the request 
does not complete the stream
+                if (!fail && !hang && self.get() != hangingServer) {
+                  responseObserver.onCompleted();
+                }
+              }
+            };
+          }
+        })
+        .build()
+        .start();
+    self.set(started);
+    servers.add(started);
+    return MockDatanodeDetails.createDatanodeDetails(DatanodeID.randomID(), 
"localhost", "127.0.0.1", null,
+        started.getPort());
+  }
+
+  private static XceiverClientGrpc newClient(List<DatanodeDetails> nodes, 
OzoneConfiguration config)
+      throws Exception {
+    XceiverClientGrpc created = new 
XceiverClientGrpc(MockPipeline.createPipeline(nodes), config);
+    created.connect();
+    return created;
+  }
+
+  @AfterEach
+  void tearDown() throws Exception {
+    client.close();
+    for (Server s : servers) {
+      s.shutdownNow();
+      s.awaitTermination(5, TimeUnit.SECONDS);
+    }
+  }
+
+  private ContainerCommandRequestProto readContainer() {
+    return ContainerCommandRequestProto.newBuilder()
+        .setCmdType(ContainerProtos.Type.ReadContainer)
+        .setContainerID(1)
+        .setDatanodeUuid(dn.getUuidString())
+        
.setReadContainer(ContainerProtos.ReadContainerRequestProto.getDefaultInstance())
+        .build();
+  }
+
+  /** Holds the next replies until the test thread has been waiting for a 
while. */
+  private void releaseRepliesLater() {
+    CountDownLatch gate = new CountDownLatch(2);
+    barrier = gate;
+    Thread release = new Thread(() -> {
+      try {
+        Thread.sleep(50);
+      } catch (InterruptedException e) {
+        Thread.currentThread().interrupt();
+      }
+      gate.countDown();
+    });
+    release.setDaemon(true);
+    release.start();
+  }
+
+  @Test
+  void blockingCallCompletesOnCaller() throws Exception {
+    for (int i = 0; i < 10; i++) {
+      releaseRepliesLater();
+      CompletableFuture<ContainerCommandResponseProto> future =
+          client.sendCommandAsync(readContainer(), dn).getResponse();
+      AtomicReference<Thread> completedOn = new AtomicReference<>();
+      CompletableFuture<Void> dependent = future.thenRun(() -> 
completedOn.set(Thread.currentThread()));
+
+      assertEquals(ContainerProtos.Result.SUCCESS, future.get().getResult());
+      dependent.get();
+      assertSame(Thread.currentThread(), completedOn.get());
+    }
+    assertEquals(ContainerProtos.Result.SUCCESS,
+        client.sendCommand(readContainer(), 
Collections.emptyList()).getResult());
+  }
+
+  @Test
+  void blockingCallFailureSurfacesAsIOException() {
+    fail = true;
+    IOException e = assertThrows(IOException.class,
+        () -> client.sendCommand(readContainer(), Collections.emptyList()));
+    assertThat(e).hasMessageContaining("injected");
+  }
+
+  @Test
+  void asyncCallCompletesWithoutWaiter() throws Exception {
+    CompletableFuture<ContainerCommandResponseProto> future =
+        client.sendCommandAsync(readContainer()).getResponse();
+    
assertThat(future).isNotInstanceOf(XceiverClientGrpc.CallerRunsReplyFuture.class);
+    // a plain future's get runs no queued work: the reply arrives on gRPC's 
executor
+    assertEquals(ContainerProtos.Result.SUCCESS, future.get(30, 
TimeUnit.SECONDS).getResult());
+    // the call used a stream of its own, ended with the call and never pooled
+    assertEquals(1, streamsOpened.get());
+    GenericTestUtils.waitFor(() -> streamsEnded.get() == 1, 10, 10_000);
+    assertEquals(0, client.getIdleStreamCount(dn));
+  }
+
+  @Test
+  void callbacksRunDirectlyAfterWaiterLeft() throws Exception {
+    XceiverClientGrpc.CallerRunsReplyFuture future = new 
XceiverClientGrpc.CallerRunsReplyFuture();
+    AtomicReference<Thread> ranOn = new AtomicReference<>();
+    future.execute(() -> ranOn.set(Thread.currentThread()));
+    assertThrows(TimeoutException.class, () -> future.get(10, 
TimeUnit.MILLISECONDS));
+    // the queued task ran on the waiter
+    assertSame(Thread.currentThread(), ranOn.get());
+
+    Thread other = new Thread(() -> future.execute(() -> 
ranOn.set(Thread.currentThread())));
+    other.start();
+    other.join();
+    assertSame(other, ranOn.get());
+
+    future.execute(() -> future.completeExceptionally(new 
IOException("late")));
+    ExecutionException e = assertThrows(ExecutionException.class, future::get);
+    assertThat(e).hasCauseInstanceOf(IOException.class);
+  }
+
+  /**
+   * ChunkInputStream uses {@code limit()} as the size of each reply buffer and
+   * resets it with {@code position(0)}, so the buffers of a received reply 
must
+   * start at position 0, which a response marshaller aliasing one array 
breaks.
+   */
+  @Test
+  void readChunkReplyBuffersStartAtZero() throws Exception {
+    List<ByteString> buffers = new ArrayList<>();
+    for (int i = 0; i < 5; i++) {
+      byte[] data = new byte[16 << 10];
+      ThreadLocalRandom.current().nextBytes(data);
+      buffers.add(ByteString.copyFrom(data));
+    }
+    response = ContainerCommandResponseProto.newBuilder()
+        .setCmdType(ContainerProtos.Type.ReadChunk)
+        .setResult(ContainerProtos.Result.SUCCESS)
+        .setReadChunk(ContainerProtos.ReadChunkResponseProto.newBuilder()
+            
.setBlockID(ContainerProtos.DatanodeBlockID.newBuilder().setContainerID(1).setLocalID(2))
+            .setChunkData(ContainerProtos.ChunkInfo.newBuilder()
+                .setChunkName("chunk").setOffset(0).setLen(5 * (16 << 10))
+                .setChecksumData(ContainerProtos.ChecksumData.newBuilder()
+                    
.setType(ContainerProtos.ChecksumType.CRC32).setBytesPerChecksum(16 << 10)))
+            
.setDataBuffers(ContainerProtos.DataBuffers.newBuilder().addAllBuffers(buffers)))
+        .build();
+
+    List<ContainerCommandResponseProto> replies = new ArrayList<>();
+    replies.add(client.sendCommandAsync(readContainer(), 
dn).getResponse().get());
+    replies.add(client.sendCommandAsync(readContainer()).getResponse().get(30, 
TimeUnit.SECONDS));
+    for (ContainerCommandResponseProto reply : replies) {
+      assertEquals(response, reply);
+      ByteBuffer[] received =
+          
BufferUtils.getReadOnlyByteBuffersArray(reply.getReadChunk().getDataBuffers().getBuffersList());
+      assertEquals(buffers.size(), received.length);
+      for (int i = 0; i < received.length; i++) {
+        assertEquals(0, received[i].position());
+        assertEquals(buffers.get(i).size(), received[i].limit());
+        assertEquals(buffers.get(i).asReadOnlyByteBuffer(), received[i]);
+      }
+    }
+  }
+
+  @Test
+  void sequentialCommandsReuseOneStream() throws Exception {
+    for (int i = 0; i < 10; i++) {
+      assertEquals(ContainerProtos.Result.SUCCESS,
+          client.sendCommand(readContainer(), 
Collections.emptyList()).getResult());
+    }
+    assertEquals(1, streamsOpened.get());
+    assertEquals(0, streamsEnded.get());
+
+    client.close();
+    GenericTestUtils.waitFor(() -> streamsEnded.get() == 1, 10, 10_000);
+  }
+
+  @Test
+  void pooledStreamsCanBeDisabled() throws Exception {
+    OzoneConfiguration config = new OzoneConfiguration();
+    config.setBoolean("ozone.client.grpc.pooled.streams.enabled", false);
+    client.close();
+    client = newClient(Collections.singletonList(dn), config);
+
+    for (int i = 0; i < 3; i++) {
+      assertEquals(ContainerProtos.Result.SUCCESS,
+          client.sendCommand(readContainer(), 
Collections.emptyList()).getResult());
+    }
+    assertEquals(3, streamsOpened.get());
+    assertEquals(0, client.getIdleStreamCount(dn));
+  }
+
+  @Test
+  void concurrentCommandsUseDistinctStreams() throws Exception {
+    final int n = 4;
+    // the server holds each request until all n arrived, so they cannot share 
a stream
+    barrier = new CountDownLatch(n);
+    ExecutorService executor = Executors.newFixedThreadPool(n);
+    try {
+      List<Future<ContainerCommandResponseProto>> futures = new ArrayList<>();
+      for (int i = 0; i < n; i++) {
+        futures.add(executor.submit(() -> client.sendCommand(readContainer(), 
Collections.emptyList())));
+      }
+      for (Future<ContainerCommandResponseProto> f : futures) {
+        assertEquals(ContainerProtos.Result.SUCCESS, f.get(30, 
TimeUnit.SECONDS).getResult());
+      }
+    } finally {
+      executor.shutdownNow();
+    }
+    assertEquals(n, streamsOpened.get());
+
+    // the streams went back to the pool
+    barrier = null;
+    for (int i = 0; i < 2 * n; i++) {
+      client.sendCommand(readContainer(), Collections.emptyList());
+    }
+    assertEquals(n, streamsOpened.get());
+  }
+
+  @Test
+  void streamErrorFailsOnlyItsRequestAndDropsTheStream() throws Exception {
+    client.sendCommand(readContainer(), Collections.emptyList());
+    fail = true;
+    assertThrows(IOException.class, () -> client.sendCommand(readContainer(), 
Collections.emptyList()));
+    fail = false;
+    assertEquals(ContainerProtos.Result.SUCCESS,
+        client.sendCommand(readContainer(), 
Collections.emptyList()).getResult());
+    assertEquals(2, streamsOpened.get());
+  }
+
+  @Test
+  void timeoutFailsWithDeadlineExceededAndCancelsTheStream() throws Exception {
+    final int permits = client.getAvailablePermits();
+    client.setTimeout(1000);
+    hang = true;
+    ExecutionException e = assertThrows(ExecutionException.class,
+        () -> client.sendCommandAsync(readContainer(), 
dn).getResponse().get());
+    assertEquals(Status.Code.DEADLINE_EXCEEDED, 
Status.fromThrowable(e.getCause()).getCode());
+    GenericTestUtils.waitFor(() -> streamsEnded.get() == 1, 10, 10_000);
+
+    hang = false;
+    assertEquals(ContainerProtos.Result.SUCCESS,
+        client.sendCommand(readContainer(), 
Collections.emptyList()).getResult());
+    assertEquals(2, streamsOpened.get());
+    assertEquals(permits, client.getAvailablePermits());
+  }
+
+  @Test
+  void timedGetBeforeTheDeadlineThrowsTimeoutAndCancelsTheStream() throws 
Exception {
+    final int permits = client.getAvailablePermits();
+    hang = true;
+    CompletableFuture<ContainerCommandResponseProto> future = 
client.sendCommandAsync(readContainer(), dn)
+        .getResponse();
+    assertThrows(TimeoutException.class, () -> future.get(10, 
TimeUnit.MILLISECONDS));
+    ExecutionException e = assertThrows(ExecutionException.class, future::get);
+    assertEquals(Status.Code.CANCELLED, 
Status.fromThrowable(e.getCause()).getCode());
+
+    hang = false;
+    assertEquals(ContainerProtos.Result.SUCCESS,
+        client.sendCommand(readContainer(), 
Collections.emptyList()).getResult());
+    assertEquals(permits, client.getAvailablePermits());
+  }
+
+  @Test
+  void abandonedRequestDoesNotCancelTheNextRequestOnTheStream() throws 
Exception {
+    XceiverClientGrpc.PooledStream stream = new 
XceiverClientGrpc.PooledStream(null);
+    @SuppressWarnings("unchecked")
+    ClientCallStreamObserver<ContainerCommandRequestProto> call = 
mock(ClientCallStreamObserver.class);
+    stream.beforeStart(call);
+    XceiverClientGrpc.CallerRunsReplyFuture first = new 
XceiverClientGrpc.CallerRunsReplyFuture();
+    stream.send(readContainer(), client.new ReplyObserver(readContainer(), dn, 
first, 0), first, System.nanoTime());
+    // the reply to the first request returned the stream to the pool and the 
next request leased it,
+    // before the first request's future was completed
+    XceiverClientGrpc.CallerRunsReplyFuture next = new 
XceiverClientGrpc.CallerRunsReplyFuture();
+    stream.send(readContainer(), client.new ReplyObserver(readContainer(), dn, 
next, 0), next,
+        System.nanoTime() + TimeUnit.SECONDS.toNanos(30));
+
+    // the first request's waiter passes its deadline
+    ExecutionException e = assertThrows(ExecutionException.class, first::get);
+    assertEquals(Status.Code.DEADLINE_EXCEEDED, 
Status.fromThrowable(e.getCause()).getCode());
+
+    verify(call, never()).cancel(any(), any());
+    assertFalse(stream.isClosed());
+  }
+
+  @Test
+  void replyWithoutARequestDropsTheStream() {
+    XceiverClientGrpc.PooledStream stream = new 
XceiverClientGrpc.PooledStream(null);
+    @SuppressWarnings("unchecked")
+    ClientCallStreamObserver<ContainerCommandRequestProto> call = 
mock(ClientCallStreamObserver.class);
+    stream.beforeStart(call);
+
+    stream.onNext(ContainerCommandResponseProto.newBuilder()
+        .setCmdType(ContainerProtos.Type.ReadContainer)
+        .setResult(ContainerProtos.Result.SUCCESS)
+        .build());
+
+    assertTrue(stream.isClosed());
+    verify(call).cancel(any(), any());
+  }
+
+  @Test
+  void duplicateReplyDropsTheStreamWithoutLeakingPermits() throws Exception {
+    final int permits = client.getAvailablePermits();
+    duplicateReply = true;
+    assertEquals(ContainerProtos.Result.SUCCESS,
+        client.sendCommand(readContainer(), 
Collections.emptyList()).getResult());
+    GenericTestUtils.waitFor(() -> streamsEnded.get() == 1, 10, 10_000);
+
+    duplicateReply = false;
+    assertEquals(ContainerProtos.Result.SUCCESS,
+        client.sendCommand(readContainer(), 
Collections.emptyList()).getResult());
+    assertEquals(2, streamsOpened.get());
+    assertEquals(permits, client.getAvailablePermits());
+  }
+
+  @Test
+  void interruptedWaiterCancelsTheStream() throws Exception {
+    hang = true;
+    CompletableFuture<ContainerCommandResponseProto> future = 
client.sendCommandAsync(readContainer(), dn)
+        .getResponse();
+    Thread.currentThread().interrupt();
+    assertThrows(InterruptedException.class, future::get);
+    // the stream may be cancelled before the server saw it, so check the 
client side
+    GenericTestUtils.waitFor(future::isDone, 10, 10_000);
+    ExecutionException e = assertThrows(ExecutionException.class, future::get);
+    assertEquals(Status.Code.CANCELLED, 
Status.fromThrowable(e.getCause()).getCode());
+
+    hang = false;
+    assertEquals(ContainerProtos.Result.SUCCESS,
+        client.sendCommand(readContainer(), 
Collections.emptyList()).getResult());
+  }
+
+  @Test
+  void idleStreamsDoNotHoldUpServerShutdown() throws Exception {
+    client.sendCommand(readContainer(), Collections.emptyList());
+    server.shutdown();
+    assertTrue(server.awaitTermination(3, TimeUnit.SECONDS));
+  }
+
+  @Test
+  void tracedCommandsUseStreamPerCall() throws Exception {
+    SpanContext context = 
SpanContext.create("0af7651916cd43dd8448eb211c80319c", "b7ad6b7169203331",
+        TraceFlags.getSampled(), TraceState.getDefault());
+    try (Scope ignored = Span.wrap(context).makeCurrent()) {
+      for (int i = 0; i < 3; i++) {
+        releaseRepliesLater();
+        CompletableFuture<ContainerCommandResponseProto> future =
+            client.sendCommandAsync(readContainer(), dn).getResponse();
+        AtomicReference<Thread> completedOn = new AtomicReference<>();
+        CompletableFuture<Void> dependent = future.thenRun(() -> 
completedOn.set(Thread.currentThread()));
+
+        assertEquals(ContainerProtos.Result.SUCCESS, future.get().getResult());
+        dependent.get();
+        assertSame(Thread.currentThread(), completedOn.get());
+      }
+    }
+    assertEquals(3, streamsOpened.get());
+  }
+
+  @Test
+  void requestOnDeadChannelFailsFastWithoutLeakingPermits() throws Exception {
+    client.sendCommand(readContainer(), Collections.emptyList());
+    final int permits = client.getAvailablePermits();
+    server.shutdownNow();
+    assertTrue(server.awaitTermination(5, TimeUnit.SECONDS));
+    client.setTimeout(30_000);
+    // the first request finds the connection gone, the next one the channel 
backing off: neither waits for the deadline
+    for (int i = 0; i < 2; i++) {
+      final long start = System.nanoTime();
+      ExecutionException e = assertThrows(ExecutionException.class,
+          () -> client.sendCommandAsync(readContainer(), 
dn).getResponse().get());
+      assertThat(System.nanoTime() - 
start).isLessThan(TimeUnit.SECONDS.toNanos(5));
+      assertNotEquals(Status.Code.DEADLINE_EXCEEDED, 
Status.fromThrowable(e.getCause()).getCode());
+      GenericTestUtils.waitFor(() -> client.getAvailablePermits() == permits, 
10, 10_000);
+    }
+  }
+
+  @Test
+  void requestOnAStreamThatEndedAfterTheLeaseFailsAtOnce() throws Exception {
+    final int permits = client.getAvailablePermits();
+    XceiverClientGrpc.PooledStream stream = new 
XceiverClientGrpc.PooledStream(null);
+    @SuppressWarnings("unchecked")
+    ClientCallStreamObserver<ContainerCommandRequestProto> call = 
mock(ClientCallStreamObserver.class);
+    stream.beforeStart(call);
+    // the connection broke after the stream was leased, before the request 
was attached to it
+    stream.onError(Status.UNAVAILABLE.withDescription("connection 
reset").asRuntimeException());
+    XceiverClientGrpc.CallerRunsReplyFuture future = new 
XceiverClientGrpc.CallerRunsReplyFuture();
+    XceiverClientGrpc.ReplyObserver reply = client.new 
ReplyObserver(readContainer(), dn, future, 0);
+
+    stream.send(readContainer(), reply, future, System.nanoTime() + 
TimeUnit.SECONDS.toNanos(30));
+
+    // failed without waiting for the deadline, so the caller can retry 
another datanode
+    assertTrue(future.isDone());
+    ExecutionException e = assertThrows(ExecutionException.class, future::get);
+    assertEquals(Status.Code.UNAVAILABLE, 
Status.fromThrowable(e.getCause()).getCode());
+    verify(call, never()).onNext(any());
+    // the request released its permit, which this test did not acquire
+    assertEquals(permits + 1, client.getAvailablePermits());
+  }
+
+  @Test
+  void saturatedClientOpensNoMoreStreamsThanPermits() throws Exception {
+    final int permits = 2;
+    OzoneConfiguration config = new OzoneConfiguration();
+    RatisClientConfig.RaftConfig raftConfig = 
config.getObject(RatisClientConfig.RaftConfig.class);
+    raftConfig.setMaxOutstandingRequests(permits);
+    config.setFromObject(raftConfig);
+    client.close();
+    client = newClient(Collections.singletonList(dn), config);
+    assertEquals(permits, client.getAvailablePermits());
+
+    final int threads = 4 * permits;
+    ExecutorService executor = Executors.newFixedThreadPool(threads);
+    try {
+      List<Future<?>> futures = new ArrayList<>();
+      for (int i = 0; i < threads; i++) {
+        futures.add(executor.submit(() -> {
+          for (int j = 0; j < 50; j++) {
+            client.sendCommand(readContainer(), Collections.emptyList());
+          }
+          return null;
+        }));
+      }
+      for (Future<?> f : futures) {
+        f.get(60, TimeUnit.SECONDS);
+      }
+    } finally {
+      executor.shutdownNow();
+    }
+    assertThat(streamsOpened.get()).isLessThanOrEqualTo(permits);

Review Comment:
   I swapped the permit release and `releaseStream`, and this only failed 2 of 
5 runs. Something deterministic instead?



##########
hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/TestXceiverClientGrpcCallerRuns.java:
##########
@@ -0,0 +1,679 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hdds.scm;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+
+import io.opentelemetry.api.trace.Span;
+import io.opentelemetry.api.trace.SpanContext;
+import io.opentelemetry.api.trace.TraceFlags;
+import io.opentelemetry.api.trace.TraceState;
+import io.opentelemetry.context.Scope;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.DatanodeID;
+import org.apache.hadoop.hdds.protocol.MockDatanodeDetails;
+import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
+import 
org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ContainerCommandRequestProto;
+import 
org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ContainerCommandResponseProto;
+import 
org.apache.hadoop.hdds.protocol.datanode.proto.XceiverClientProtocolServiceGrpc;
+import org.apache.hadoop.hdds.ratis.conf.RatisClientConfig;
+import org.apache.hadoop.hdds.scm.pipeline.MockPipeline;
+import org.apache.hadoop.ozone.common.utils.BufferUtils;
+import org.apache.ozone.test.GenericTestUtils;
+import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
+import org.apache.ratis.thirdparty.io.grpc.Server;
+import org.apache.ratis.thirdparty.io.grpc.Status;
+import org.apache.ratis.thirdparty.io.grpc.netty.NettyChannelBuilder;
+import org.apache.ratis.thirdparty.io.grpc.netty.NettyServerBuilder;
+import org.apache.ratis.thirdparty.io.grpc.stub.ClientCallStreamObserver;
+import org.apache.ratis.thirdparty.io.grpc.stub.StreamObserver;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests that {@link XceiverClientGrpc} delivers the reply of a blocking call
+ * on the waiting thread, and that the async path is unchanged.
+ */
+class TestXceiverClientGrpcCallerRuns {
+
+  private final List<Server> servers = new ArrayList<>();
+  private Server server;
+  private volatile boolean fail;
+  private volatile ContainerCommandResponseProto response;
+  private volatile boolean hang;
+  private volatile boolean duplicateReply;
+  private volatile Server hangingServer;
+  private volatile CountDownLatch barrier;
+  private final AtomicInteger streamsOpened = new AtomicInteger();
+  private final AtomicInteger streamsEnded = new AtomicInteger();
+  private DatanodeDetails dn;
+  private XceiverClientGrpc client;
+
+  @BeforeEach
+  void setUp() throws Exception {
+    dn = startServer();
+    server = servers.get(0);
+    client = newClient(Collections.singletonList(dn), new 
OzoneConfiguration());
+  }
+
+  /** Starts a server and returns the datanode that it stands for. */
+  private DatanodeDetails startServer() throws IOException {
+    final AtomicReference<Server> self = new AtomicReference<>();
+    final Server started = NettyServerBuilder.forPort(0)
+        .addService(new 
XceiverClientProtocolServiceGrpc.XceiverClientProtocolServiceImplBase() {
+          @Override
+          public StreamObserver<ContainerCommandRequestProto> send(
+              StreamObserver<ContainerCommandResponseProto> responseObserver) {
+            streamsOpened.incrementAndGet();
+            return new StreamObserver<ContainerCommandRequestProto>() {
+              @Override
+              public void onNext(ContainerCommandRequestProto request) {
+                final CountDownLatch latch = barrier;
+                if (latch != null) {
+                  latch.countDown();
+                  try {
+                    latch.await(30, TimeUnit.SECONDS);
+                  } catch (InterruptedException e) {
+                    Thread.currentThread().interrupt();
+                  }
+                }
+                if (hang || self.get() == hangingServer) {
+                  return;
+                }
+                if (fail) {
+                  
responseObserver.onError(Status.INTERNAL.withDescription("injected").asException());
+                  return;
+                }
+                final ContainerCommandResponseProto reply = response;
+                responseObserver.onNext(reply != null ? reply : 
ContainerCommandResponseProto.newBuilder()
+                    .setCmdType(request.getCmdType())
+                    .setResult(ContainerProtos.Result.SUCCESS)
+                    .build());
+                if (duplicateReply) {
+                  
responseObserver.onNext(ContainerCommandResponseProto.newBuilder()
+                      .setCmdType(request.getCmdType())
+                      .setResult(ContainerProtos.Result.SUCCESS)
+                      .build());
+                }
+              }
+
+              @Override
+              public void onError(Throwable t) {
+                streamsEnded.incrementAndGet();
+              }
+
+              @Override
+              public void onCompleted() {
+                streamsEnded.incrementAndGet();
+                // like a datanode, a server that is still serving the request 
does not complete the stream
+                if (!fail && !hang && self.get() != hangingServer) {
+                  responseObserver.onCompleted();
+                }
+              }
+            };
+          }
+        })
+        .build()
+        .start();
+    self.set(started);
+    servers.add(started);
+    return MockDatanodeDetails.createDatanodeDetails(DatanodeID.randomID(), 
"localhost", "127.0.0.1", null,
+        started.getPort());
+  }
+
+  private static XceiverClientGrpc newClient(List<DatanodeDetails> nodes, 
OzoneConfiguration config)
+      throws Exception {
+    XceiverClientGrpc created = new 
XceiverClientGrpc(MockPipeline.createPipeline(nodes), config);
+    created.connect();
+    return created;
+  }
+
+  @AfterEach
+  void tearDown() throws Exception {
+    client.close();
+    for (Server s : servers) {
+      s.shutdownNow();
+      s.awaitTermination(5, TimeUnit.SECONDS);
+    }
+  }
+
+  private ContainerCommandRequestProto readContainer() {
+    return ContainerCommandRequestProto.newBuilder()
+        .setCmdType(ContainerProtos.Type.ReadContainer)
+        .setContainerID(1)
+        .setDatanodeUuid(dn.getUuidString())
+        
.setReadContainer(ContainerProtos.ReadContainerRequestProto.getDefaultInstance())
+        .build();
+  }
+
+  /** Holds the next replies until the test thread has been waiting for a 
while. */
+  private void releaseRepliesLater() {
+    CountDownLatch gate = new CountDownLatch(2);
+    barrier = gate;
+    Thread release = new Thread(() -> {
+      try {
+        Thread.sleep(50);

Review Comment:
   Could the reply be released after `thenRun` is registered instead of 
sleeping? A late `thenRun` hides the wrong thread.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

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


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to