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

Caideyipi pushed a commit to branch codex/cp-c2ed594d-dev-1.3
in repository https://gitbox.apache.org/repos/asf/iotdb.git

commit 0bb1f14f2d1e682d3c84b3e5be047c366d76916e
Author: Caideyipi <[email protected]>
AuthorDate: Wed Dec 2 22:41:35 2026 +0800

    Fix RPC buffer accounting during transport and pipe shutdown (#19504)
    
    (cherry picked from commit c2ed594d84a2db0c82984f4440dfebd047c4e53b)
---
 .../apache/iotdb/rpc/TElasticFramedTransport.java  |  20 +++-
 .../apache/iotdb/rpc/AutoResizingBufferTest.java   |  48 ++++++++
 .../apache/iotdb/db/i18n/DataNodePipeMessages.java |   4 +
 .../apache/iotdb/db/i18n/DataNodePipeMessages.java |   4 +
 .../exchange/sender/TwoStageAggregateSender.java   |  73 +++++++++++-
 .../sender/TwoStageAggregateSenderTest.java        | 127 +++++++++++++++++++++
 6 files changed, 267 insertions(+), 9 deletions(-)

diff --git 
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TElasticFramedTransport.java
 
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TElasticFramedTransport.java
index d9b1749ed77..fad00d53e53 100644
--- 
a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TElasticFramedTransport.java
+++ 
b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/TElasticFramedTransport.java
@@ -122,9 +122,23 @@ public class TElasticFramedTransport extends TTransport {
 
   @Override
   public synchronized void open() throws TTransportException {
-    underlying.open();
-    if (serverBufferPool != null) {
-      serverBufferPool.register(this);
+    final boolean wasOpen = underlying.isOpen();
+    try {
+      underlying.open();
+      if (serverBufferPool != null) {
+        serverBufferPool.register(this);
+      }
+    } catch (TTransportException | RuntimeException | Error failure) {
+      if (!wasOpen) {
+        try {
+          close();
+        } catch (RuntimeException | Error closeFailure) {
+          if (closeFailure != failure) {
+            failure.addSuppressed(closeFailure);
+          }
+        }
+      }
+      throw failure;
     }
   }
 
diff --git 
a/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/AutoResizingBufferTest.java
 
b/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/AutoResizingBufferTest.java
index 1d82186d169..365120e111f 100644
--- 
a/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/AutoResizingBufferTest.java
+++ 
b/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/AutoResizingBufferTest.java
@@ -20,6 +20,7 @@
 package org.apache.iotdb.rpc;
 
 import org.apache.thrift.transport.TMemoryBuffer;
+import org.apache.thrift.transport.TSocket;
 import org.apache.thrift.transport.TTransport;
 import org.apache.thrift.transport.TTransportException;
 import org.junit.After;
@@ -125,6 +126,53 @@ public class AutoResizingBufferTest {
     }
   }
 
+  @Test
+  public void testOpenFailureReleasesBufferReservations() throws Exception {
+    AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+    for (boolean compressed : new boolean[] {false, true}) {
+      TTransportException failure = new 
TTransportException(TTransportException.NOT_OPEN);
+      TSocket socket =
+          new TSocket("localhost", 0) {
+            @Override
+            public void open() throws TTransportException {
+              throw failure;
+            }
+          };
+      try (TElasticFramedTransport transport =
+          compressed
+              ? new TSnappyElasticFramedTransport(socket, 32, 128, false)
+              : new TElasticFramedTransport(socket, 32, 128, false)) {
+        Assert.assertEquals(compressed ? 128 : 64, 
memoryControl.getUsedMemoryInBytes());
+        Assert.assertSame(failure, 
Assert.assertThrows(TTransportException.class, transport::open));
+        Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+      }
+    }
+  }
+
+  @Test
+  public void testOpenFailureDoesNotReleaseAnAlreadyOpenTransport() throws 
Exception {
+    AutoResizingBufferMemoryManager.setMemoryControl(memoryControl);
+    TSocket socket =
+        new TSocket("localhost", 0) {
+          @Override
+          public boolean isOpen() {
+            return true;
+          }
+
+          @Override
+          public void open() throws TTransportException {
+            throw new TTransportException(TTransportException.ALREADY_OPEN);
+          }
+        };
+    try (TElasticFramedTransport transport = new 
TElasticFramedTransport(socket, 32, 128, false)) {
+      Assert.assertEquals(
+          TTransportException.ALREADY_OPEN,
+          Assert.assertThrows(TTransportException.class, 
transport::open).getType());
+      Assert.assertEquals(64, memoryControl.getUsedMemoryInBytes());
+    }
+    Assert.assertEquals(0, memoryControl.getUsedMemoryInBytes());
+  }
+
   @Test
   public void testMemoryPressureReclaimsIdleServerTransportBuffers() throws 
Exception {
     memoryControl.setLimit(96);
diff --git 
a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
 
b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
index b151b057fba..fb2a9741d7c 100644
--- 
a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
+++ 
b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
@@ -29,6 +29,10 @@ public final class DataNodePipeMessages {
       
MESSAGE_PIPE_DATA_INSERTION_IS_DISABLED_WHEN_DATA_REGION_CONSENSUS_PROTOCOL_IS_RATIS_7D669ECC
 =
           "Pipe synchronization with data insertion is disabled when data 
region consensus protocol is Ratis.";
 
+  public static final String
+      
EXCEPTION_TWO_STAGE_AGGREGATE_SENDER_FOR_PIPE_ARG_CREATION_TIME_ARG_IS_CLOSED_D76F95EA
 =
+          "Two-stage aggregate sender for Pipe %s (creation time %d) is 
closed.";
+
   private DataNodePipeMessages() {}
 
   public static final String 
EXCEPTION_THE_AGGREGATOR_AND_OUTPUT_NAME_ARG_IS_INVALID_2C76EEE3 =
diff --git 
a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
 
b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
index f8d405c337f..d36e8f7c041 100644
--- 
a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
+++ 
b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
@@ -29,6 +29,10 @@ public final class DataNodePipeMessages {
       
MESSAGE_PIPE_DATA_INSERTION_IS_DISABLED_WHEN_DATA_REGION_CONSENSUS_PROTOCOL_IS_RATIS_7D669ECC
 =
           "当数据区域共识协议为 Ratis 时,包含 data.insert 的 Pipe 同步不可用。";
 
+  public static final String
+      
EXCEPTION_TWO_STAGE_AGGREGATE_SENDER_FOR_PIPE_ARG_CREATION_TIME_ARG_IS_CLOSED_D76F95EA
 =
+          "Pipe %s(创建时间 %d)的两阶段聚合发送端已关闭。";
+
   private DataNodePipeMessages() {}
 
   public static final String 
EXCEPTION_THE_AGGREGATOR_AND_OUTPUT_NAME_ARG_IS_INVALID_2C76EEE3 =
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/twostage/exchange/sender/TwoStageAggregateSender.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/twostage/exchange/sender/TwoStageAggregateSender.java
index ccb5454b381..e4979015ca5 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/twostage/exchange/sender/TwoStageAggregateSender.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/twostage/exchange/sender/TwoStageAggregateSender.java
@@ -28,6 +28,7 @@ import org.apache.iotdb.commons.pipe.config.PipeConfig;
 import org.apache.iotdb.commons.pipe.sink.client.IoTDBSyncClient;
 import org.apache.iotdb.confignode.rpc.thrift.TDataNodeInfo;
 import org.apache.iotdb.confignode.rpc.thrift.TShowDataNodesResp;
+import org.apache.iotdb.db.i18n.DataNodePipeMessages;
 import 
org.apache.iotdb.db.pipe.processor.twostage.combiner.PipeCombineHandlerManager;
 import org.apache.iotdb.db.protocol.client.ConfigNodeClient;
 import org.apache.iotdb.db.protocol.client.ConfigNodeClientManager;
@@ -41,6 +42,7 @@ import org.apache.iotdb.service.rpc.thrift.TSOpenSessionResp;
 import org.apache.iotdb.service.rpc.thrift.TSProtocolVersion;
 
 import org.apache.thrift.TException;
+import org.apache.thrift.transport.TTransportException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -50,7 +52,6 @@ import java.util.HashSet;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.atomic.AtomicLong;
 import java.util.concurrent.atomic.AtomicReference;
 
@@ -71,9 +72,15 @@ public class TwoStageAggregateSender implements 
AutoCloseable {
   private static final AtomicReference<Map<Integer, TEndPoint>> 
DATANODE_ID_2_END_POINTS =
       new AtomicReference<>();
 
+  private enum State {
+    IDLE,
+    REQUEST_IN_PROGRESS,
+    CLOSED
+  }
+
+  private final AtomicReference<State> state = new 
AtomicReference<>(State.IDLE);
   private TEndPoint[] endPoints;
-  private final Map<TEndPoint, IoTDBSyncClient> endPointIoTDBSyncClientMap =
-      new ConcurrentHashMap<>();
+  private final Map<TEndPoint, IoTDBSyncClient> endPointIoTDBSyncClientMap = 
new HashMap<>();
 
   public TwoStageAggregateSender(String pipeName, long creationTime) {
     this(pipeName, creationTime, null, null);
@@ -89,7 +96,21 @@ public class TwoStageAggregateSender implements 
AutoCloseable {
 
   public synchronized TPipeTransferResp request(long watermark, 
TPipeTransferReq req)
       throws TException {
+    if (!state.compareAndSet(State.IDLE, State.REQUEST_IN_PROGRESS)) {
+      throw closedException();
+    }
+    try {
+      return sendRequest(watermark, req);
+    } finally {
+      if (!state.compareAndSet(State.REQUEST_IN_PROGRESS, State.IDLE)) {
+        closeClients();
+      }
+    }
+  }
+
+  private TPipeTransferResp sendRequest(long watermark, TPipeTransferReq req) 
throws TException {
     final boolean endPointsChanged = tryFetchEndPointsIfNecessary();
+    checkOpen();
     tryConstructClients(endPointsChanged);
 
     final TEndPoint endPoint = endPoints[(int) Math.floorMod(watermark, 
endPoints.length)];
@@ -98,11 +119,15 @@ public class TwoStageAggregateSender implements 
AutoCloseable {
       client = reconstructIoTDBSyncClient(endPoint);
     }
 
+    checkOpen();
     LOGGER.info("Sending request {} (watermark = {}) to {}", req, watermark, 
endPoint);
 
     try {
       return client.pipeTransfer(req);
     } catch (Exception e) {
+      if (state.get() == State.CLOSED) {
+        throw e;
+      }
       LOGGER.warn("Failed to send request {} (watermark = {}) to {}", req, 
watermark, endPoint, e);
       try {
         reconstructIoTDBSyncClient(endPoint);
@@ -118,6 +143,22 @@ public class TwoStageAggregateSender implements 
AutoCloseable {
     }
   }
 
+  private void checkOpen() throws TTransportException {
+    if (state.get() == State.CLOSED) {
+      throw closedException();
+    }
+  }
+
+  private TTransportException closedException() {
+    return new TTransportException(
+        TTransportException.NOT_OPEN,
+        String.format(
+            DataNodePipeMessages
+                
.EXCEPTION_TWO_STAGE_AGGREGATE_SENDER_FOR_PIPE_ARG_CREATION_TIME_ARG_IS_CLOSED_D76F95EA,
+            pipeName,
+            creationTime));
+  }
+
   private static boolean tryFetchEndPointsIfNecessary() {
     final long currentTime = System.currentTimeMillis();
 
@@ -162,7 +203,7 @@ public class TwoStageAggregateSender implements 
AutoCloseable {
     return true;
   }
 
-  private void tryConstructClients(boolean endPointsChanged) {
+  private void tryConstructClients(boolean endPointsChanged) throws 
TTransportException {
     if (Objects.nonNull(endPoints) && !endPointsChanged) {
       return;
     }
@@ -185,6 +226,7 @@ public class TwoStageAggregateSender implements 
AutoCloseable {
         endPoints);
 
     for (final TEndPoint endPoint : endPoints) {
+      checkOpen();
       if (endPointIoTDBSyncClientMap.containsKey(endPoint)) {
         continue;
       }
@@ -222,6 +264,7 @@ public class TwoStageAggregateSender implements 
AutoCloseable {
   }
 
   private IoTDBSyncClient constructIoTDBSyncClient(TEndPoint endPoint) throws 
TException {
+    checkOpen();
     final IoTDBSyncClient client =
         new IoTDBSyncClient(
             new ThriftClientProperty.Builder()
@@ -233,8 +276,20 @@ public class TwoStageAggregateSender implements 
AutoCloseable {
             false,
             null,
             null);
-    openSession(client);
-    return client;
+    try {
+      checkOpen();
+      openSession(client);
+      return client;
+    } catch (TException | RuntimeException | Error failure) {
+      try {
+        client.close();
+      } catch (Exception | Error closeFailure) {
+        if (closeFailure != failure) {
+          failure.addSuppressed(closeFailure);
+        }
+      }
+      throw failure;
+    }
   }
 
   private void openSession(final IoTDBSyncClient client) throws TException {
@@ -265,6 +320,12 @@ public class TwoStageAggregateSender implements 
AutoCloseable {
 
   @Override
   public void close() {
+    if (state.getAndSet(State.CLOSED) == State.IDLE) {
+      closeClients();
+    }
+  }
+
+  private void closeClients() {
     for (final IoTDBSyncClient client : endPointIoTDBSyncClientMap.values()) {
       try {
         client.close();
diff --git 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/processor/twostage/exchange/sender/TwoStageAggregateSenderTest.java
 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/processor/twostage/exchange/sender/TwoStageAggregateSenderTest.java
new file mode 100644
index 00000000000..c23e226a04e
--- /dev/null
+++ 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/processor/twostage/exchange/sender/TwoStageAggregateSenderTest.java
@@ -0,0 +1,127 @@
+/*
+ * 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.iotdb.db.pipe.processor.twostage.exchange.sender;
+
+import org.apache.iotdb.common.rpc.thrift.TEndPoint;
+import org.apache.iotdb.commons.pipe.sink.client.IoTDBSyncClient;
+import org.apache.iotdb.pipe.api.exception.PipeException;
+import org.apache.iotdb.service.rpc.thrift.TPipeTransferReq;
+import org.apache.iotdb.service.rpc.thrift.TPipeTransferResp;
+
+import org.apache.thrift.transport.TTransportException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.powermock.reflect.Whitebox;
+
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class TwoStageAggregateSenderTest {
+
+  @Test
+  public void testCloseDefersClientCleanupUntilRequestFinishes() throws 
Exception {
+    final TEndPoint endpoint = new TEndPoint("127.0.0.1", 1);
+    final IoTDBSyncClient client = mock(IoTDBSyncClient.class);
+    final TPipeTransferReq request = new TPipeTransferReq();
+    final TPipeTransferResp response = new TPipeTransferResp();
+    final CountDownLatch entered = new CountDownLatch(1);
+    final CountDownLatch finish = new CountDownLatch(1);
+    when(client.pipeTransfer(request))
+        .thenAnswer(
+            invocation -> {
+              entered.countDown();
+              Assert.assertTrue(finish.await(10, TimeUnit.SECONDS));
+              return response;
+            });
+
+    final AtomicReference<Map<Integer, TEndPoint>> endpoints =
+        Whitebox.getInternalState(TwoStageAggregateSender.class, 
"DATANODE_ID_2_END_POINTS");
+    final AtomicLong lastUpdate =
+        Whitebox.getInternalState(
+            TwoStageAggregateSender.class, 
"DATANODE_ID_2_END_POINTS_LAST_UPDATE_TIME");
+    final Map<Integer, TEndPoint> previousEndpoints = 
endpoints.getAndSet(Map.of(1, endpoint));
+    final long previousUpdate = 
lastUpdate.getAndSet(System.currentTimeMillis());
+
+    final TwoStageAggregateSender sender = new 
TwoStageAggregateSender("testPipe", 1);
+    final ExecutorService executor = Executors.newFixedThreadPool(2);
+    try {
+      Whitebox.setInternalState(sender, "endPoints", (Object) new TEndPoint[] 
{endpoint});
+      final Map<TEndPoint, IoTDBSyncClient> clients =
+          Whitebox.getInternalState(sender, "endPointIoTDBSyncClientMap");
+      clients.put(endpoint, client);
+
+      final Future<TPipeTransferResp> inFlight = executor.submit(() -> 
sender.request(0, request));
+      Assert.assertTrue(entered.await(5, TimeUnit.SECONDS));
+      executor.submit(sender::close).get(5, TimeUnit.SECONDS);
+      verify(client, never()).close();
+
+      finish.countDown();
+      Assert.assertSame(response, inFlight.get(5, TimeUnit.SECONDS));
+      sender.close();
+      verify(client).close();
+      Assert.assertTrue(clients.isEmpty());
+      Assert.assertEquals(
+          TTransportException.NOT_OPEN,
+          Assert.assertThrows(TTransportException.class, () -> 
sender.request(0, request))
+              .getType());
+    } finally {
+      finish.countDown();
+      executor.shutdownNow();
+      try {
+        Assert.assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
+      } finally {
+        sender.close();
+        endpoints.set(previousEndpoints);
+        lastUpdate.set(previousUpdate);
+      }
+    }
+  }
+
+  @Test
+  public void testSessionSetupFailureClosesUncachedClient() throws Exception {
+    try (TwoStageAggregateSender sender = new 
TwoStageAggregateSender("testPipe", 1);
+        ServerSocket listener = new ServerSocket()) {
+      listener.bind(new InetSocketAddress("127.0.0.1", 0));
+      listener.setSoTimeout(5_000);
+      final TEndPoint endpoint = new TEndPoint("127.0.0.1", 
listener.getLocalPort());
+      Assert.assertThrows(
+          PipeException.class,
+          () -> Whitebox.invokeMethod(sender, "constructIoTDBSyncClient", 
endpoint));
+      try (Socket connection = listener.accept()) {
+        connection.setSoTimeout(5_000);
+        Assert.assertEquals(-1, connection.getInputStream().read());
+      }
+    }
+  }
+}

Reply via email to