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

adoroszlai pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ozone.git


The following commit(s) were added to refs/heads/master by this push:
     new c32ba28982b HDDS-17668. PutBlock reply handlers of BlockOutputStream 
can run out of order (#12065)
c32ba28982b is described below

commit c32ba28982b57ca812a5cbc33a6b88aa38869321
Author: len548 <[email protected]>
AuthorDate: Sun Nov 22 20:43:36 2026 +0900

    HDDS-17668. PutBlock reply handlers of BlockOutputStream can run out of 
order (#12065)
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 .../hadoop/hdds/scm/storage/BlockOutputStream.java |  12 +-
 .../storage/TestBlockOutputStreamCorrectness.java  | 153 +++++++++++++++++++--
 2 files changed, 154 insertions(+), 11 deletions(-)

diff --git 
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/BlockOutputStream.java
 
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/BlockOutputStream.java
index 8e3bcf5e068..ff6fddf0719 100644
--- 
a/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/BlockOutputStream.java
+++ 
b/hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/BlockOutputStream.java
@@ -158,6 +158,10 @@ public class BlockOutputStream extends OutputStream {
 
   private CompletableFuture<Void> lastFlushFuture;
   private CompletableFuture<Void> allPendingFlushFutures = 
CompletableFuture.completedFuture(null);
+  // Completes once the reply of the latest PutBlock is handled. The next 
reply is handled only after it, since the
+  // responseExecutor may run the handlers in any order, and an earlier 
PutBlock handled last would move the bcsId back
+  // and leave acknowledged buffers that are not a prefix of the block.
+  private CompletableFuture<?> putBlockReplyHandled = 
CompletableFuture.completedFuture(null);
 
   /**
    * Creates a new BlockOutputStream.
@@ -592,7 +596,7 @@ CompletableFuture<PutBlockResult> executePutBlock(boolean 
close,
       boolean isBlockFull = (blockSize != -1 && flushPos == blockSize);
       asyncReply = putBlockAsync(xceiverClient, blockData, close || 
isBlockFull, tokenString, containerAutoCreate());
       CompletableFuture<ContainerCommandResponseProto> future = 
asyncReply.getResponse();
-      flushFuture = future.thenApplyAsync(e -> {
+      flushFuture = future.thenCombineAsync(putBlockReplyHandled, (e, ignored) 
-> {
         try {
           validateResponse(e);
         } catch (IOException sce) {
@@ -614,6 +618,7 @@ CompletableFuture<PutBlockResult> executePutBlock(boolean 
close,
         setIoException(ce);
         throw ce;
       });
+      putBlockReplyHandled = flushFuture.handle((r, e) -> null);
     } catch (IOException | ExecutionException e) {
       throw new IOException(EXCEPTION_MSG + e.toString(), e);
     } catch (InterruptedException ex) {
@@ -960,7 +965,7 @@ private CompletableFuture<PutBlockResult> 
writeChunkToContainer(
           blockID.get(), data, tokenString, replicationIndex, blockData, 
close, containerAutoCreate());
       CompletableFuture<ContainerCommandResponseProto>
           respFuture = asyncReply.getResponse();
-      validateFuture = respFuture.thenApplyAsync(e -> {
+      validateFuture = respFuture.thenCombineAsync(putBlockReplyHandled, (e, 
ignored) -> {
         try {
           validateResponse(e);
         } catch (IOException sce) {
@@ -980,6 +985,9 @@ private CompletableFuture<PutBlockResult> 
writeChunkToContainer(
         setIoException(ce);
         throw ce;
       });
+      if (putBlockPiggybacking) {
+        putBlockReplyHandled = validateFuture.handle((r, e) -> null);
+      }
       clientMetrics.recordWriteChunk(pipeline, chunkInfo.getLen());
 
     } catch (IOException | ExecutionException e) {
diff --git 
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/storage/TestBlockOutputStreamCorrectness.java
 
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/storage/TestBlockOutputStreamCorrectness.java
index edc58b4d19c..b9ea29066cc 100644
--- 
a/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/storage/TestBlockOutputStreamCorrectness.java
+++ 
b/hadoop-hdds/client/src/test/java/org/apache/hadoop/hdds/scm/storage/TestBlockOutputStreamCorrectness.java
@@ -18,6 +18,8 @@
 package org.apache.hadoop.hdds.scm.storage;
 
 import static java.util.concurrent.Executors.newFixedThreadPool;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -28,8 +30,15 @@
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import java.io.IOException;
+import java.util.ArrayDeque;
+import java.util.Collections;
+import java.util.Deque;
+import java.util.List;
 import java.util.Map;
+import java.util.concurrent.AbstractExecutorService;
 import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 import org.apache.commons.lang3.RandomUtils;
 import org.apache.hadoop.hdds.client.BlockID;
@@ -54,6 +63,7 @@
 import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
 import org.apache.hadoop.ozone.ClientVersion;
 import org.apache.hadoop.ozone.OzoneConsts;
+import org.apache.hadoop.ozone.common.ChunkBuffer;
 import org.apache.hadoop.ozone.container.common.helpers.BlockData;
 import org.apache.hadoop.ozone.container.common.helpers.ChunkInfo;
 import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
@@ -70,6 +80,8 @@
 class TestBlockOutputStreamCorrectness {
 
   private static final int DATA_SIZE = 16 * (int) OzoneConsts.MB;
+  private static final int BUFFER_SIZE = 1024 * 1024 / 4;
+  private static final int FLUSH_SIZE = 1024 * 1024;
   private static final byte[] DATA = 
RandomUtils.secure().randomBytes(DATA_SIZE);
 
   @ParameterizedTest
@@ -92,6 +104,54 @@ void test(final int writeSize) throws IOException {
     }
   }
 
+  /**
+   * The reply handler of a later PutBlock runs before the one of an earlier 
PutBlock.
+   * The block must still end up with the bcsId of the latest PutBlock.
+   */
+  @Test
+  void testBcsIdOfLatestPutBlockWhenReplyHandlersRunLate() throws IOException {
+    final HeldExecutor executor = new HeldExecutor();
+    final MockXceiverClientSpi xceiverClient = new 
MockXceiverClientSpi(MockPipeline.createRatisPipeline());
+    try (BlockOutputStream outputStream = createBlockOutputStream(new 
BufferPool(BUFFER_SIZE, 16), xceiverClient,
+        executor)) {
+      outputStream.write(DATA, 0, 2 * FLUSH_SIZE);
+      executor.runDirectly();
+
+      assertThat(outputStream.getBlockID().getBlockCommitSequenceId())
+          .isEqualTo(xceiverClient.getLastPutBlockIndex());
+    }
+  }
+
+  /**
+   * The reply handler of a later PutBlock runs, then a later WriteChunk 
fails, then the reply handler of an earlier
+   * PutBlock runs. The buffers not acknowledged yet must hold exactly the 
data after the acknowledged length, since
+   * that is the data rewritten to a new block.
+   */
+  @Test
+  void testUnackedBuffersFollowAckedLengthWhenReplyHandlersRunLate() throws 
IOException {
+    final HeldExecutor executor = new HeldExecutor();
+    final MockXceiverClientSpi xceiverClient = new 
MockXceiverClientSpi(MockPipeline.createRatisPipeline());
+    final BufferPool bufferPool = new BufferPool(BUFFER_SIZE, 16);
+    final BlockOutputStream outputStream = createBlockOutputStream(bufferPool, 
xceiverClient, executor);
+    outputStream.write(DATA, 0, 2 * FLUSH_SIZE);
+    executor.runLatest();
+    xceiverClient.setReplyResult(Result.CLOSED_CONTAINER_IO);
+    outputStream.write(DATA, 2 * FLUSH_SIZE, BUFFER_SIZE);
+    executor.runLatest();
+    executor.runDirectly();
+    assertThat(outputStream.getIoException()).isNotNull();
+
+    final int acked = (int) outputStream.getTotalAckDataLength();
+    ByteString unacked = ByteString.EMPTY;
+    for (ChunkBuffer buffer : bufferPool.getAllocatedBuffers()) {
+      unacked = unacked.concat(buffer.duplicate(0, 
buffer.position()).toByteString(bufferPool.byteStringConversion()));
+    }
+    assertThat(unacked).as("unacknowledged data after %d acknowledged bytes", 
acked)
+        .isEqualTo(ByteString.copyFrom(DATA, acked, 2 * FLUSH_SIZE + 
BUFFER_SIZE - acked));
+
+    assertThatThrownBy(outputStream::close).isInstanceOf(IOException.class);
+  }
+
   /**
    * Tests an EC offline reconstruction scenario in which none of the 
ChunkInfo in an EC stripe have stripeChecksum.
    * Such ChunkInfo will exist for any EC data that was written in a version 
in which the ChunkInfo protobuf message did
@@ -194,18 +254,24 @@ private BlockData[] 
createBlockDataWithoutStripeChecksum(BlockID blockID, ECRepl
 
   private BlockOutputStream createBlockOutputStream(BufferPool bufferPool)
       throws IOException {
+    return createBlockOutputStream(bufferPool, new 
MockXceiverClientSpi(MockPipeline.createRatisPipeline()),
+        newFixedThreadPool(10));
+  }
+
+  private BlockOutputStream createBlockOutputStream(BufferPool bufferPool, 
XceiverClientSpi xceiverClient,
+      ExecutorService responseExecutor) throws IOException {
 
-    final Pipeline pipeline = MockPipeline.createRatisPipeline();
+    final Pipeline pipeline = xceiverClient.getPipeline();
 
     final XceiverClientManager xcm = mock(XceiverClientManager.class);
     when(xcm.acquireClient(any()))
-        .thenReturn(new MockXceiverClientSpi(pipeline));
+        .thenReturn(xceiverClient);
 
     OzoneClientConfig config = new OzoneClientConfig();
-    config.setStreamBufferSize(1024 * 1024 / 4);
+    config.setStreamBufferSize(BUFFER_SIZE);
     config.setStreamBufferMaxSize(2 * 1024 * 1024);
     config.setStreamBufferFlushDelay(true);
-    config.setStreamBufferFlushSize(1024 * 1024);
+    config.setStreamBufferFlushSize(FLUSH_SIZE);
     config.setChecksumType(ChecksumType.NONE);
     config.setBytesPerChecksum(16 * 1024);
     StreamBufferArgs streamBufferArgs =
@@ -221,7 +287,7 @@ private BlockOutputStream 
createBlockOutputStream(BufferPool bufferPool)
         null,
         ContainerClientMetrics.acquire(),
         streamBufferArgs,
-        () -> newFixedThreadPool(10));
+        () -> responseExecutor);
   }
 
   private ECBlockOutputStream createECBlockOutputStream(OzoneClientConfig 
clientConfig,
@@ -253,6 +319,8 @@ private static class MockXceiverClientSpi extends 
XceiverClientSpi {
 
     private final AtomicInteger counter = new AtomicInteger();
     private int i;
+    private Result replyResult = Result.SUCCESS;
+    private long lastPutBlockIndex;
 
     MockXceiverClientSpi(Pipeline pipeline) {
       super();
@@ -281,18 +349,20 @@ public XceiverClientReply 
sendCommandAsync(ContainerCommandRequestProto request)
         request = ContainerCommandRequestProto.newBuilder(request)
             .setVersion(ClientVersion.CURRENT.serialize()).build();
       }
+      final long logIndex = counter.incrementAndGet();
       final ContainerCommandResponseProto.Builder builder =
           ContainerCommandResponseProto.newBuilder()
-              .setResult(Result.SUCCESS)
+              .setResult(replyResult)
               .setCmdType(request.getCmdType());
 
       switch (request.getCmdType()) {
       case PutBlock:
+        lastPutBlockIndex = logIndex;
         builder.setPutBlock(PutBlockResponseProto.newBuilder()
             .setCommittedBlockLength(
                 GetCommittedBlockLengthResponseProto.newBuilder()
-                    .setBlockID(
-                        request.getPutBlock().getBlockData().getBlockID())
+                    
.setBlockID(request.getPutBlock().getBlockData().getBlockID().toBuilder()
+                        .setBlockCommitSequenceId(logIndex))
                     .setBlockLength(
                         request.getPutBlock().getBlockData().getSize())
                     .build())
@@ -311,11 +381,19 @@ public XceiverClientReply 
sendCommandAsync(ContainerCommandRequestProto request)
       }
       final XceiverClientReply result = new XceiverClientReply(
           CompletableFuture.completedFuture(builder.build()));
-      result.setLogIndex(counter.incrementAndGet());
+      result.setLogIndex(logIndex);
       return result;
 
     }
 
+    void setReplyResult(Result replyResult) {
+      this.replyResult = replyResult;
+    }
+
+    long getLastPutBlockIndex() {
+      return lastPutBlockIndex;
+    }
+
     @Override
     public ReplicationType getPipelineType() {
       return null;
@@ -345,4 +423,61 @@ public long getReplicatedMinCommitIndex() {
     }
   }
 
+  /**
+   * Holds the submitted tasks until the test runs them, to control the order 
in which reply handlers run.
+   */
+  private static class HeldExecutor extends AbstractExecutorService {
+
+    private final Deque<Runnable> tasks = new ArrayDeque<>();
+    private boolean direct;
+
+    @Override
+    public void execute(Runnable task) {
+      if (direct) {
+        task.run();
+      } else {
+        tasks.addLast(task);
+      }
+    }
+
+    /** Run the most recently submitted task. */
+    void runLatest() {
+      tasks.removeLast().run();
+    }
+
+    /**
+     * Run the held tasks, the most recently submitted first, including those 
submitted meanwhile.
+     * Then run each new task when it is submitted.
+     */
+    void runDirectly() {
+      while (!tasks.isEmpty()) {
+        runLatest();
+      }
+      direct = true;
+    }
+
+    @Override
+    public void shutdown() {
+    }
+
+    @Override
+    public List<Runnable> shutdownNow() {
+      return Collections.emptyList();
+    }
+
+    @Override
+    public boolean isShutdown() {
+      return false;
+    }
+
+    @Override
+    public boolean isTerminated() {
+      return false;
+    }
+
+    @Override
+    public boolean awaitTermination(long timeout, TimeUnit unit) {
+      return true;
+    }
+  }
 }


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

Reply via email to