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

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


The following commit(s) were added to refs/heads/master by this push:
     new fffd7d4d9db Fix delayed operator memory release on re-entrant and 
multi-channel sink close
fffd7d4d9db is described below

commit fffd7d4d9db551ff4dc723970a2be829cff0fe22
Author: Jackie Tien <[email protected]>
AuthorDate: Thu Dec 3 15:52:27 2026 +0800

    Fix delayed operator memory release on re-entrant and multi-channel sink 
close
---
 .../execution/exchange/MPPDataExchangeManager.java |  56 +-
 .../execution/exchange/SharedTsBlockQueue.java     |  83 +-
 .../execution/exchange/sink/ISinkChannel.java      |  11 +
 .../execution/exchange/sink/LocalSinkChannel.java  | 112 ++-
 .../execution/exchange/sink/ShuffleSinkHandle.java |  58 +-
 .../execution/exchange/sink/SinkChannel.java       |  82 +-
 .../exchange/source/LocalSourceHandle.java         |  10 +-
 .../exchange/MPPDataExchangeManagerTest.java       | 399 ++++++++++
 .../execution/exchange/ShuffleSinkHandleTest.java  | 847 +++++++++++++++++++++
 .../SinkChannelFailurePropagationTest.java         | 110 ++-
 10 files changed, 1650 insertions(+), 118 deletions(-)

diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeManager.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeManager.java
index 1d2ff03b2be..bb407260e52 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeManager.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeManager.java
@@ -627,17 +627,7 @@ public class MPPDataExchangeManager implements 
IMPPDataExchangeManager {
 
     private void decrementCnt() {
       if (hasDecremented.compareAndSet(false, true) && (cnt.decrementAndGet() 
== 0)) {
-        releaseShuffleSinkHandle();
-      }
-    }
-
-    private void releaseShuffleSinkHandle() {
-      ISinkHandle sinkHandle = shuffleSinkHandles.remove(shuffleSinkHandleId);
-      if (sinkHandle != null && !hasChannelFailedOrAborted.get()) {
-        if (LOGGER.isDebugEnabled()) {
-          LOGGER.debug(DataNodeQueryMessages.CLOSE_SHUFFLE_SINK_HANDLE, 
shuffleSinkHandleId);
-        }
-        sinkHandle.close();
+        releaseShuffleSinkHandle(shuffleSinkHandleId, 
hasChannelFailedOrAborted);
       }
     }
   }
@@ -803,6 +793,7 @@ public class MPPDataExchangeManager implements 
IMPPDataExchangeManager {
               instanceContext.isHighestPriority());
     }
 
+    onBeforeAttachLocalSinkChannel(localFragmentInstanceId, queue);
     return new LocalSinkChannel(
         localFragmentInstanceId,
         queue,
@@ -814,6 +805,13 @@ public class MPPDataExchangeManager implements 
IMPPDataExchangeManager {
             hasChannelFailedOrAborted));
   }
 
+  @TestOnly
+  protected void onBeforeAttachLocalSinkChannel(
+      TFragmentInstanceId localFragmentInstanceId, SharedTsBlockQueue queue) {
+    // Hook for deterministic concurrency testing when LocalSourceHandle 
closes after queue
+    // selection and before LocalSinkChannel attaches to the queue.
+  }
+
   /**
    * As we know the upstream and downstream node of shared queue, we don't 
need to put it into the
    * sink map.
@@ -901,7 +899,12 @@ public class MPPDataExchangeManager implements 
IMPPDataExchangeManager {
     }
 
     int channelNum = downStreamChannelLocationList.size();
-    AtomicInteger cnt = new AtomicInteger(channelNum);
+    // Hold one extra registration permit until shuffleSinkHandles.put(...) 
completes: a downstream
+    // LocalSourceHandle.close() can finish the last channel right after 
createLocalSinkChannel()
+    // attaches it to SharedTsBlockQueue and before the parent 
ShuffleSinkHandle is published.
+    // Releasing this permit after put(...) guarantees that whichever thread 
drops cnt to 0 observes
+    // the published handle and closes it exactly once.
+    AtomicInteger cnt = new AtomicInteger(channelNum + 1);
     AtomicBoolean hasChannelFailedOrAborted = new AtomicBoolean(false);
     List<ISinkChannel> downStreamChannelList =
         downStreamChannelLocationList.stream()
@@ -923,10 +926,37 @@ public class MPPDataExchangeManager implements 
IMPPDataExchangeManager {
             downStreamChannelIndex,
             shuffleStrategyEnum,
             new ShuffleSinkListenerImpl(instanceContext, 
instanceContext::failed));
-    shuffleSinkHandles.put(localFragmentInstanceId, shuffleSinkHandle);
+    onBeforePublishShuffleSinkHandle(localFragmentInstanceId);
+    ISinkHandle previous =
+        shuffleSinkHandles.putIfAbsent(localFragmentInstanceId, 
shuffleSinkHandle);
+    if (previous != null) {
+      throw new IllegalStateException(
+          DataNodeQueryMessages.SHUFFLESINKHANDLE_ALREADY_IN_MAP
+              + localFragmentInstanceId
+              + DataNodeQueryMessages.IS_IN_THE_MAP);
+    }
+    if (cnt.decrementAndGet() == 0) {
+      releaseShuffleSinkHandle(localFragmentInstanceId, 
hasChannelFailedOrAborted);
+    }
     return shuffleSinkHandle;
   }
 
+  private void releaseShuffleSinkHandle(
+      TFragmentInstanceId shuffleSinkHandleId, AtomicBoolean 
hasChannelFailedOrAborted) {
+    ISinkHandle sinkHandle = shuffleSinkHandles.remove(shuffleSinkHandleId);
+    if (sinkHandle != null && !hasChannelFailedOrAborted.get()) {
+      if (LOGGER.isDebugEnabled()) {
+        LOGGER.debug(DataNodeQueryMessages.CLOSE_SHUFFLE_SINK_HANDLE, 
shuffleSinkHandleId);
+      }
+      sinkHandle.close();
+    }
+  }
+
+  @TestOnly
+  protected void onBeforePublishShuffleSinkHandle(TFragmentInstanceId 
localFragmentInstanceId) {
+    // Hook for deterministic concurrency testing when channels close before 
handle publication.
+  }
+
   private ISinkChannel createChannelForShuffleSink(
       TFragmentInstanceId localFragmentInstanceId,
       String localPlanNodeId,
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/SharedTsBlockQueue.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/SharedTsBlockQueue.java
index c37e004f87e..95645a1b3f3 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/SharedTsBlockQueue.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/SharedTsBlockQueue.java
@@ -80,6 +80,14 @@ public class SharedTsBlockQueue {
   private ListenableFuture<Void> blockedOnMemory;
 
   private volatile boolean closed = false;
+  // Tracks whether abort() was invoked (distinct from closed, which is set on 
both close and
+  // abort), so neither LocalSinkChannel nor LocalSourceHandle mistakes an 
aborted empty queue for
+  // normal end-of-stream completion.
+  private volatile boolean aborted = false;
+  // Set under synchronized(this) only after close() has finished releasing 
all buffered memory
+  // without throwing, allowing a LocalSinkChannel that attaches afterwards to 
observe a completed
+  // normal close while preserving abort and cleanup-retry semantics.
+  private boolean closeCompleted = false;
   private boolean alreadyRegistered = false;
 
   private LocalSourceHandle sourceHandle;
@@ -171,6 +179,14 @@ public class SharedTsBlockQueue {
     return closed;
   }
 
+  public boolean isAborted() {
+    return aborted;
+  }
+
+  public boolean isClosedNormally() {
+    return closeCompleted && !aborted;
+  }
+
   public int getNumOfBufferedTsBlocks() {
     return queue.size();
   }
@@ -329,7 +345,10 @@ public class SharedTsBlockQueue {
 
   /** Destroy the queue and complete the future. Should only be called in 
normal case */
   public void close() {
-    if (closed) {
+    // Only short-circuit once normal close has finished releasing all 
buffered reservations; if an
+    // earlier MemoryPool.free() threw, closeCompleted is still false so a 
retry can finish freeing
+    // bufferRetainedSizeInBytes.
+    if (aborted || closeCompleted) {
       return;
     }
     closed = true;
@@ -339,43 +358,28 @@ public class SharedTsBlockQueue {
     if (!canAddTsBlock.isDone()) {
       canAddTsBlock.set(null);
     }
-    if (blockedOnMemory != null) {
-      bufferRetainedSizeInBytes -= 
localMemoryManager.getQueryPool().tryCancel(blockedOnMemory);
-    }
-    queue.clear();
-    if (bufferRetainedSizeInBytes > 0L) {
-      localMemoryManager
-          .getQueryPool()
-          .free(
-              localFragmentInstanceId.getQueryId(),
-              fullFragmentInstanceId,
-              localPlanNodeId,
-              bufferRetainedSizeInBytes);
-      bufferRetainedSizeInBytes = 0;
-    }
+    releaseBufferedMemory();
+    closeCompleted = true;
     if (sinkChannel != null) {
       // attention: LocalSinkChannel of this SharedTsBlockQueue could be null 
when we
       // close
       // LocalSourceHandle(with limit clause it's possible) before 
constructing the
       // corresponding
-      // LocalSinkChannel.
-      // If this close method is invoked by LocalSourceHandle, listener of
-      // LocalSourceHandle will
-      // remove the LocalSourceHandle from the map of MppDataExchangeManager 
and later
-      // when
-      // LocalSinkChannel is initialized, it will construct a new 
SharedTsBlockQueue.
-      // It is still safe that we let the LocalSourceHandle close successfully 
in this
-      // case. Because
-      // the QueryTerminator will do the final cleaning logic.
+      // LocalSinkChannel. If createLocalSinkChannel() has already selected 
this queue,
+      // LocalSinkChannel.attachToQueue() synchronizes on this queue, observes 
isClosedNormally(),
+      // and closes itself so the finish callback is delivered once; if 
LocalSourceHandle closed
+      // before createLocalSinkChannel() looked up sourceHandles, 
QueryTerminator cleans up the
+      // unattached upstream FI.
       sinkChannel.close();
     }
   }
 
   /** Destroy the queue and cancel the future. Should only be called in 
abnormal case */
   public void abort() {
-    if (closed) {
+    if (closeCompleted || (aborted && bufferRetainedSizeInBytes == 0L && 
blockedOnMemory == null)) {
       return;
     }
+    aborted = true;
     closed = true;
     if (!blocked.isDone()) {
       blocked.cancel(true);
@@ -383,28 +387,18 @@ public class SharedTsBlockQueue {
     if (!canAddTsBlock.isDone()) {
       canAddTsBlock.set(null);
     }
-    if (blockedOnMemory != null) {
-      bufferRetainedSizeInBytes -= 
localMemoryManager.getQueryPool().tryCancel(blockedOnMemory);
-    }
-    queue.clear();
-    if (bufferRetainedSizeInBytes > 0L) {
-      localMemoryManager
-          .getQueryPool()
-          .free(
-              localFragmentInstanceId.getQueryId(),
-              fullFragmentInstanceId,
-              localPlanNodeId,
-              bufferRetainedSizeInBytes);
-      bufferRetainedSizeInBytes = 0;
-    }
+    releaseBufferedMemory();
   }
 
   /** Destroy the queue and cancel the future. Should only be called in 
abnormal case */
   public void abort(Throwable t) {
-    if (closed) {
+    if (closeCompleted || (aborted && bufferRetainedSizeInBytes == 0L && 
blockedOnMemory == null)) {
       return;
     }
-    abortedCause = t;
+    if (abortedCause == null) {
+      abortedCause = t;
+    }
+    aborted = true;
     closed = true;
     if (!blocked.isDone()) {
       blocked.setException(t);
@@ -412,8 +406,13 @@ public class SharedTsBlockQueue {
     if (!canAddTsBlock.isDone()) {
       canAddTsBlock.set(null);
     }
+    releaseBufferedMemory();
+  }
+
+  private void releaseBufferedMemory() {
     if (blockedOnMemory != null) {
       bufferRetainedSizeInBytes -= 
localMemoryManager.getQueryPool().tryCancel(blockedOnMemory);
+      blockedOnMemory = null;
     }
     queue.clear();
     if (bufferRetainedSizeInBytes > 0L) {
@@ -424,7 +423,7 @@ public class SharedTsBlockQueue {
               fullFragmentInstanceId,
               localPlanNodeId,
               bufferRetainedSizeInBytes);
-      bufferRetainedSizeInBytes = 0;
+      bufferRetainedSizeInBytes = 0L;
     }
   }
 
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/sink/ISinkChannel.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/sink/ISinkChannel.java
index 56f5104b603..16eda339e5c 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/sink/ISinkChannel.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/sink/ISinkChannel.java
@@ -30,5 +30,16 @@ public interface ISinkChannel extends ISink {
   /** Return the number of TsBlocks the channel has in buffer. */
   int getNumOfBufferedTsBlocks();
 
+  /**
+   * Return true if this channel has completed normal {@link #close()} cleanup.
+   *
+   * <p>Unlike {@link #close()}, which only returns {@code true} to the caller 
that performs the
+   * open-to-closed transition, and unlike {@link 
LocalSinkChannel#isClosed()}, which delegates to
+   * {@code SharedTsBlockQueue.isClosed()} and is also {@code true} after 
{@code queue.abort()},
+   * this method strictly indicates that the channel itself was closed 
normally (neither aborted nor
+   * failed) and has already released its {@code MemoryPool} reservations.
+   */
+  boolean isClosedNormally();
+
   void checkState();
 }
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/sink/LocalSinkChannel.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/sink/LocalSinkChannel.java
index 083db67359c..da0bb4486d4 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/sink/LocalSinkChannel.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/sink/LocalSinkChannel.java
@@ -52,9 +52,16 @@ public class LocalSinkChannel implements ISinkChannel {
   private volatile ListenableFuture<Void> blocked;
 
   private volatile boolean aborted = false;
+  // True only after close() has completed queue.close() (including MemoryPool 
cleanup).
   private volatile boolean closed = false;
+  // Re-entry guard while close() -> queue.close() -> sinkChannel.close() is 
on the call stack,
+  // kept separate from closed so a failed MemoryPool.free() can be retried 
before reporting
+  // isClosedNormally() == true.
+  private boolean closing = false;
 
   private boolean invokedOnFinished = false;
+  private boolean invokedOnAborted = false;
+  private Optional<Throwable> abortCause = Optional.empty();
 
   private static final DataExchangeCostMetricSet DATA_EXCHANGE_COST_METRIC_SET 
=
       DataExchangeCostMetricSet.getInstance();
@@ -71,8 +78,8 @@ public class LocalSinkChannel implements ISinkChannel {
             
DataNodeQueryMessages.EXCEPTION_SINKLISTENER_CAN_NOT_BE_NULL_DOT_32C9E7C0);
     this.queue =
         Validate.notNull(queue, 
DataNodeQueryMessages.EXCEPTION_QUEUE_CAN_NOT_BE_NULL_DOT_9BB286B1);
-    this.queue.setSinkChannel(this);
-    blocked = queue.getCanAddTsBlock();
+    this.blocked = this.queue.getCanAddTsBlock();
+    attachToQueue();
   }
 
   public LocalSinkChannel(
@@ -89,9 +96,23 @@ public class LocalSinkChannel implements ISinkChannel {
             
DataNodeQueryMessages.EXCEPTION_SINKLISTENER_CAN_NOT_BE_NULL_DOT_32C9E7C0);
     this.queue =
         Validate.notNull(queue, 
DataNodeQueryMessages.EXCEPTION_QUEUE_CAN_NOT_BE_NULL_DOT_9BB286B1);
-    this.queue.setSinkChannel(this);
     // SinkChannel can send data after SourceHandle asks it to
-    blocked = queue.getCanAddTsBlock();
+    this.blocked = this.queue.getCanAddTsBlock();
+    attachToQueue();
+  }
+
+  // Coordinate attachment with SharedTsBlockQueue.close() under 
synchronized(queue) after all
+  // fields of this channel are initialized: either queue.close() runs 
afterwards and sees the fully
+  // initialized sinkChannel, or queue.close() already completed while 
sinkChannel was null and this
+  // thread delivers close() (and onFinish) once. Aborted or failed-cleanup 
queues do not satisfy
+  // queue.isClosedNormally(), preserving abort and retry semantics.
+  private void attachToQueue() {
+    synchronized (queue) {
+      queue.setSinkChannel(this);
+      if (queue.isClosedNormally()) {
+        close();
+      }
+    }
   }
 
   @Override
@@ -123,20 +144,27 @@ public class LocalSinkChannel implements ISinkChannel {
   @Override
   public boolean isFinished() {
     synchronized (queue) {
-      return queue.hasNoMoreTsBlocks() && queue.isEmpty();
+      return !queue.isAborted() && queue.hasNoMoreTsBlocks() && 
queue.isEmpty();
     }
   }
 
   public void checkAndInvokeOnFinished() {
     synchronized (queue) {
-      if (isFinished()) {
-        synchronized (this) {
-          if (!invokedOnFinished) {
-            sinkListener.onFinish(this);
-            invokedOnFinished = true;
-          }
+      boolean shouldInvokeOnFinish = false;
+      synchronized (this) {
+        // Claim invokedOnFinished before calling onFinish so a re-entrant 
close() triggered by
+        // sinkListener.onFinish(this) -> ShuffleSinkHandle.close() cannot 
fire onFinish twice.
+        if (!aborted && isFinished() && !invokedOnFinished) {
+          invokedOnFinished = true;
+          shouldInvokeOnFinish = true;
         }
       }
+      // Keep synchronized(queue) held across onFinish so a consumer calling
+      // LocalSourceHandle.isFinished()/close() cannot observe completion and 
return to the client
+      // before ShuffleSinkHandle.close() releases the fragment's operator 
memory reservation.
+      if (shouldInvokeOnFinish) {
+        sinkListener.onFinish(this);
+      }
     }
   }
 
@@ -175,6 +203,7 @@ public class LocalSinkChannel implements ISinkChannel {
   @Override
   public void setNoMoreTsBlocks() {
     synchronized (queue) {
+      boolean shouldInvokeOnFinish = false;
       synchronized (this) {
         if (LOGGER.isDebugEnabled()) {
           
LOGGER.debug(DataNodeQueryMessages.START_SET_NO_MORE_TSBLOCKS_ON_LOCAL);
@@ -184,9 +213,22 @@ public class LocalSinkChannel implements ISinkChannel {
         }
         queue.setNoMoreTsBlocks(true);
         sinkListener.onEndOfBlocks(this);
+        // Check the full isFinished() predicate (!queue.isAborted() && 
queue.hasNoMoreTsBlocks() &&
+        // queue.isEmpty()): if LocalSourceHandle.abort() already closed the 
queue,
+        // queue.setNoMoreTsBlocks(true) returns early without setting 
noMoreTsBlocks, so an empty
+        // aborted queue must not claim normal finish.
+        if (isFinished() && !invokedOnFinished) {
+          invokedOnFinished = true;
+          shouldInvokeOnFinish = true;
+        }
+      }
+      // Keep synchronized(queue) held across onFinish so an awakened consumer 
cannot return from
+      // LocalSourceHandle.isFinished()/close() before 
ShuffleSinkHandle.close() releases the
+      // fragment's operator memory reservation.
+      if (shouldInvokeOnFinish) {
+        sinkListener.onFinish(this);
       }
     }
-    checkAndInvokeOnFinished();
     if (LOGGER.isDebugEnabled()) {
       LOGGER.debug(DataNodeQueryMessages.END_SET_NO_MORE_TSBLOCKS_ON_LOCAL);
     }
@@ -202,13 +244,16 @@ public class LocalSinkChannel implements ISinkChannel {
         if (aborted || closed) {
           return false;
         }
-        aborted = true;
-        Optional<Throwable> t = sinkListener.onAborted(this);
-        if (t.isPresent()) {
-          queue.abort(t.get());
+        if (!invokedOnAborted) {
+          abortCause = sinkListener.onAborted(this);
+          invokedOnAborted = true;
+        }
+        if (abortCause.isPresent()) {
+          queue.abort(abortCause.get());
         } else {
           queue.abort();
         }
+        aborted = true;
       }
     }
     if (LOGGER.isDebugEnabled()) {
@@ -223,17 +268,32 @@ public class LocalSinkChannel implements ISinkChannel {
       LOGGER.debug(DataNodeQueryMessages.START_CLOSE_LOCAL_SINK_CHANNEL);
     }
     synchronized (queue) {
+      boolean shouldInvokeOnFinish = false;
       synchronized (this) {
-        if (aborted || closed) {
+        if (aborted || closed || closing || queue.isAborted()) {
           return false;
         }
-        closed = true;
-        queue.close();
-        if (!invokedOnFinished) {
-          sinkListener.onFinish(this);
-          invokedOnFinished = true;
+        // Keep the mutual-recursion guard (closing) separate from completed 
cleanup (closed):
+        // 1. queue.close() re-enters sinkChannel.close() on the same thread; 
closing == true makes
+        //    that inner call a safe no-op.
+        // 2. closed (read by isClosedNormally()) is only set after 
queue.close() has released all
+        //    MemoryPool reservations without throwing, so a failed free() can 
be retried on a
+        //    subsequent close() before ShuffleSinkHandle reports FINISHED.
+        closing = true;
+        try {
+          queue.close();
+          closed = true;
+          if (!invokedOnFinished) {
+            invokedOnFinished = true;
+            shouldInvokeOnFinish = true;
+          }
+        } finally {
+          closing = false;
         }
       }
+      if (shouldInvokeOnFinish) {
+        sinkListener.onFinish(this);
+      }
     }
     if (LOGGER.isDebugEnabled()) {
       LOGGER.debug(DataNodeQueryMessages.END_CLOSE_LOCAL_SINK_CHANNEL);
@@ -307,5 +367,13 @@ public class LocalSinkChannel implements ISinkChannel {
     }
   }
 
+  // Return this.closed rather than queue.isClosed(): queue.isClosed() is also 
true after
+  // queue.abort() (kept in isClosed() so pipeline Drivers stop), whereas 
this.closed is only true
+  // when LocalSinkChannel.close() completed normal cleanup.
+  @Override
+  public boolean isClosedNormally() {
+    return closed;
+  }
+
   // end region
 }
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/sink/ShuffleSinkHandle.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/sink/ShuffleSinkHandle.java
index 4058023949e..ffb7e11fde7 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/sink/ShuffleSinkHandle.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/sink/ShuffleSinkHandle.java
@@ -19,6 +19,7 @@
 
 package org.apache.iotdb.db.queryengine.execution.exchange.sink;
 
+import org.apache.iotdb.commons.utils.TestOnly;
 import org.apache.iotdb.db.conf.IoTDBDescriptor;
 import org.apache.iotdb.db.i18n.DataNodeQueryMessages;
 import 
org.apache.iotdb.db.queryengine.execution.exchange.MPPDataExchangeManager;
@@ -202,8 +203,10 @@ public class ShuffleSinkHandle implements ISinkHandle {
     return closed;
   }
 
+  // aborted is volatile (matching isClosed()), so reading it without 
synchronized avoids
+  // unnecessary monitor contention or lock-order inversion with 
send()/isFull().
   @Override
-  public synchronized boolean isAborted() {
+  public boolean isAborted() {
     return aborted;
   }
 
@@ -229,11 +232,21 @@ public class ShuffleSinkHandle implements ISinkHandle {
       }
       boolean meetError = false;
       Exception firstException = null;
-      boolean selfAborted = true;
-      for (ISink channel : downStreamChannelList) {
+      boolean allChannelsTerminated = true;
+      for (ISinkChannel channel : downStreamChannelList) {
         try {
-          selfAborted = channel.abort();
+          // Always invoke channel.abort() on every channel (using 
non-short-circuiting &=) so that
+          // acquiring each channel's monitor acts as a barrier if another 
thread is still inside
+          // channel.close()/abort() freeing MemoryPool buffers before the 
fragment is deregistered.
+          // Aggregate across all channels rather than overwriting with the 
last channel's result:
+          // in multi-channel handles (or if abort() wins terminationClaim 
right after a channel
+          // closed), an already-closed channel returns false from abort() but 
isClosedNormally() is
+          // true, which must not mask other aborted channels or leave this 
handle non-terminal.
+          boolean channelTerminated =
+              channel.abort() || channel.isAborted() || 
channel.isClosedNormally();
+          allChannelsTerminated &= channelTerminated;
         } catch (Exception e) {
+          allChannelsTerminated = false;
           if (!meetError) {
             firstException = e;
             meetError = true;
@@ -243,7 +256,7 @@ public class ShuffleSinkHandle implements ISinkHandle {
       if (meetError) {
         
LOGGER.warn(DataNodeQueryMessages.ERROR_OCCURRED_WHEN_TRY_TO_ABORT_CHANNEL, 
firstException);
       }
-      if (selfAborted) {
+      if (allChannelsTerminated) {
         sinkListener.onAborted(this);
         aborted = true;
         if (LOGGER.isDebugEnabled()) {
@@ -274,11 +287,24 @@ public class ShuffleSinkHandle implements ISinkHandle {
       }
       boolean meetError = false;
       Exception firstException = null;
-      boolean selfClosed = true;
-      for (ISink channel : downStreamChannelList) {
+      boolean allChannelsClosed = true;
+      for (ISinkChannel channel : downStreamChannelList) {
         try {
-          selfClosed = channel.close();
+          // 1. Always call channel.close() first (with non-short-circuiting 
&=) so acquiring each
+          //    channel's monitor waits for any concurrent close()/abort() on 
another thread to
+          //    finish freeing MemoryPool buffers before this handle 
transitions to FINISHED.
+          // 2. When downstream closes early or races after the final TsBlock 
(LocalSourceHandle
+          //    .close() -> LocalSinkChannel.close() -> onFinish -> 
ShuffleSinkHandle.close()),
+          //    re-entering channel.close() on the same thread returns false 
because the channel is
+          //    already closed; likewise, in multi-channel handles some 
channels may have closed
+          //    earlier. Checking channel.isClosedNormally() accepts channels 
that completed normal
+          //    close() while still rejecting aborted or failed channels, 
ensuring
+          // context.finished()
+          //    fires immediately instead of delaying operator memory release 
for 1000 ms.
+          boolean channelClosed = channel.close() || 
channel.isClosedNormally();
+          allChannelsClosed &= channelClosed;
         } catch (Exception e) {
+          allChannelsClosed = false;
           if (!meetError) {
             firstException = e;
             meetError = true;
@@ -288,7 +314,7 @@ public class ShuffleSinkHandle implements ISinkHandle {
       if (meetError) {
         
LOGGER.warn(DataNodeQueryMessages.ERROR_OCCURRED_WHEN_TRY_TO_CLOSE_CHANNEL, 
firstException);
       }
-      if (selfClosed) {
+      if (allChannelsClosed) {
         sinkListener.onFinish(this);
         closed = true;
         if (LOGGER.isDebugEnabled()) {
@@ -330,9 +356,17 @@ public class ShuffleSinkHandle implements ISinkHandle {
   private TerminationClaim claimTermination(boolean waitForCurrentClaim) {
     TerminationClaim claim = new TerminationClaim();
     while (!aborted && !closed) {
+      onBeforeAcquireTerminationClaim();
       TerminationClaim currentClaim = terminationClaim.get();
       if (currentClaim == null) {
         if (terminationClaim.compareAndSet(null, claim)) {
+          // Re-validate terminal flags after winning the CAS: this thread may 
have passed the
+          // while (!aborted && !closed) check, paused while another thread 
completed close() or
+          // abort() and cleared terminationClaim, and then acquired a 
redundant claim.
+          if (aborted || closed) {
+            releaseTerminationClaim(claim);
+            return null;
+          }
           return claim;
         }
       } else {
@@ -353,6 +387,12 @@ public class ShuffleSinkHandle implements ISinkHandle {
     claim.completion.complete(null);
   }
 
+  @TestOnly
+  protected void onBeforeAcquireTerminationClaim() {
+    // Hook for deterministic concurrency testing of the TOCTOU window after 
checking !aborted &&
+    // !closed.
+  }
+
   private void switchChannelIfNecessary() {
     shuffleStrategy.shuffle();
   }
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/sink/SinkChannel.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/sink/SinkChannel.java
index cf95de3c07a..939e0cfb87a 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/sink/SinkChannel.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/sink/SinkChannel.java
@@ -134,11 +134,17 @@ public class SinkChannel implements ISinkChannel {
   /** The actual buffered memory in bytes, including the amount of memory 
being reserved. */
   private long bufferRetainedSizeInBytes;
 
-  private boolean aborted = false;
+  // Volatile because isClosed(), isClosedNormally(), isAborted(), 
isNoMoreTsBlocks(), and
+  // checkState() are read without synchronized(this) from Driver and 
ShuffleSinkHandle threads.
+  private volatile boolean aborted = false;
 
-  private boolean closed = false;
+  private volatile boolean closed = false;
 
-  private boolean noMoreTsBlocks = false;
+  // Set when claimFailure() wins, before FragmentInstanceExecution 
asynchronously calls abort().
+  // Prevents a late onCloseSinkChannelEvent from marking a failed channel as 
normally closed.
+  private volatile boolean failed = false;
+
+  private volatile boolean noMoreTsBlocks = false;
 
   // Guarded by this. Normal finish and notification failure compete for one 
terminal callback.
   private boolean terminalCallbackClaimed;
@@ -335,7 +341,6 @@ public class SinkChannel implements ISinkChannel {
     }
     terminalCallbackClaimed = true;
     stopNotifications(true);
-    sequenceIdToTsBlock.clear();
     if (blocked != null) {
       bufferRetainedSizeInBytes -= 
localMemoryManager.getQueryPool().tryCancel(blocked);
     }
@@ -349,6 +354,7 @@ public class SinkChannel implements ISinkChannel {
               bufferRetainedSizeInBytes);
       bufferRetainedSizeInBytes = 0;
     }
+    sequenceIdToTsBlock.clear();
     sinkListener.onAborted(this);
     aborted = true;
     if (LOGGER.isDebugEnabled()) {
@@ -358,30 +364,52 @@ public class SinkChannel implements ISinkChannel {
   }
 
   @Override
-  public synchronized boolean close() {
+  public boolean close() {
     if (LOGGER.isDebugEnabled()) {
       LOGGER.debug(DataNodeQueryMessages.START_CLOSE_SINK_CHANNEL);
     }
-    if (closed || aborted) {
-      return false;
-    }
-    stopNotifications(!terminalCallbackClaimed);
-    sequenceIdToTsBlock.clear();
-    if (blocked != null) {
-      bufferRetainedSizeInBytes -= 
localMemoryManager.getQueryPool().tryCancel(blocked);
+    boolean shouldInvokeOnFinish = false;
+    synchronized (this) {
+      // Reject close() if claimFailure() has already won (failed == true), 
leaving cleanup and
+      // aborted = true to the upcoming abort() call so ShuffleSinkHandle 
never treats a failed
+      // channel as normally closed.
+      if (closed || aborted || failed) {
+        return false;
+      }
+      if (blocked != null && blocked != immediateVoidFuture()) {
+        bufferRetainedSizeInBytes -= 
localMemoryManager.getQueryPool().tryCancel(blocked);
+        blocked = immediateVoidFuture();
+      }
+      if (bufferRetainedSizeInBytes > 0) {
+        localMemoryManager
+            .getQueryPool()
+            .free(
+                localFragmentInstanceId.getQueryId(),
+                fullFragmentInstanceId,
+                localPlanNodeId,
+                bufferRetainedSizeInBytes);
+        bufferRetainedSizeInBytes = 0;
+      }
+      sequenceIdToTsBlock.clear();
+      // Commit terminalCallbackClaimed, stopNotifications, and closed = true 
only after
+      // MemoryPool cleanup succeeds: if free() throws on the first attempt, a 
retried
+      // onCloseSinkChannelEvent can still finish releasing memory and deliver 
onFinish.
+      // If the channel already finished via 
endOfBlocksSent()/acknowledgeTsBlock(),
+      // terminalCallbackClaimed is true: pass interruptRunning = false so any 
in-flight RPC can
+      // return its socket cleanly to the client pool.
+      boolean interruptRunning = !terminalCallbackClaimed;
+      if (!terminalCallbackClaimed) {
+        terminalCallbackClaimed = true;
+        shouldInvokeOnFinish = true;
+      }
+      stopNotifications(interruptRunning);
+      closed = true;
     }
-    if (bufferRetainedSizeInBytes > 0) {
-      localMemoryManager
-          .getQueryPool()
-          .free(
-              localFragmentInstanceId.getQueryId(),
-              fullFragmentInstanceId,
-              localPlanNodeId,
-              bufferRetainedSizeInBytes);
-      bufferRetainedSizeInBytes = 0;
+    if (shouldInvokeOnFinish) {
+      // Invoke outside synchronized(this) (matching 
endOfBlocksSent()/acknowledgeTsBlock()) because
+      // onFinish may re-enter the owning ShuffleSinkHandle and close sibling 
channels.
+      sinkListener.onFinish(this);
     }
-    invokeOnFinished();
-    closed = true;
     if (LOGGER.isDebugEnabled()) {
       LOGGER.debug(DataNodeQueryMessages.END_CLOSE_SINK_CHANNEL);
     }
@@ -408,6 +436,7 @@ public class SinkChannel implements ISinkChannel {
       if (terminalCallbackClaimed || notificationsStopped) {
         return false;
       }
+      failed = true;
       terminalCallbackClaimed = true;
       stopNotifications(true);
       return true;
@@ -440,7 +469,12 @@ public class SinkChannel implements ISinkChannel {
   }
 
   @Override
-  public synchronized boolean isAborted() {
+  public boolean isClosedNormally() {
+    return closed;
+  }
+
+  @Override
+  public boolean isAborted() {
     return aborted;
   }
 
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/source/LocalSourceHandle.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/source/LocalSourceHandle.java
index e22fcd1d439..4e193dfd88b 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/source/LocalSourceHandle.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/source/LocalSourceHandle.java
@@ -75,12 +75,14 @@ public class LocalSourceHandle implements ISourceHandle {
       SharedTsBlockQueue queue, SourceHandleListener sourceHandleListener, 
String threadName) {
     this.queue =
         Validate.notNull(queue, 
DataNodeQueryMessages.EXCEPTION_QUEUE_CAN_NOT_BE_NULL_DOT_9BB286B1);
-    this.queue.setSourceHandle(this);
     this.sourceHandleListener =
         Validate.notNull(
             sourceHandleListener,
             
DataNodeQueryMessages.EXCEPTION_SOURCEHANDLELISTENER_CAN_NOT_BE_NULL_DOT_01817F52);
     this.threadName = threadName;
+    synchronized (this.queue) {
+      this.queue.setSourceHandle(this);
+    }
   }
 
   // For fragment
@@ -99,12 +101,14 @@ public class LocalSourceHandle implements ISourceHandle {
             
DataNodeQueryMessages.EXCEPTION_LOCALPLANNODEID_CAN_NOT_BE_NULL_DOT_44A34A33);
     this.queue =
         Validate.notNull(queue, 
DataNodeQueryMessages.EXCEPTION_QUEUE_CAN_NOT_BE_NULL_DOT_9BB286B1);
-    this.queue.setSourceHandle(this);
     this.sourceHandleListener =
         Validate.notNull(
             sourceHandleListener,
             
DataNodeQueryMessages.EXCEPTION_SOURCEHANDLELISTENER_CAN_NOT_BE_NULL_DOT_01817F52);
     this.threadName = createFullIdFrom(localFragmentInstanceId, 
localPlanNodeId);
+    synchronized (this.queue) {
+      this.queue.setSourceHandle(this);
+    }
   }
 
   @Override
@@ -178,7 +182,7 @@ public class LocalSourceHandle implements ISourceHandle {
   public boolean isFinished() {
     synchronized (queue) {
       checkSharedQueueIfAborted();
-      return queue.hasNoMoreTsBlocks() && queue.isEmpty();
+      return !aborted && !queue.isAborted() && queue.hasNoMoreTsBlocks() && 
queue.isEmpty();
     }
   }
 
diff --git 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeManagerTest.java
 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeManagerTest.java
index 668c02adee6..079dd44a8a5 100644
--- 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeManagerTest.java
+++ 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeManagerTest.java
@@ -53,6 +53,8 @@ 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.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
 
 public class MPPDataExchangeManagerTest {
   @Test
@@ -318,4 +320,401 @@ public class MPPDataExchangeManagerTest {
           0, pool.getFragmentMemoryReservedBytes(producer.queryId, producerId, 
MemorySide.OUTPUT));
     }
   }
+
+  @Test
+  public void 
testLocalSourceCloseBeforeShuffleSinkHandlePublishFinishesFragmentAndReleasesBudget()
+      throws Exception {
+    final String queryId = "q_publish_race";
+    final long operatorBudgetBytes = 64 * 1024L;
+    final FragmentInstanceId upstreamId =
+        new FragmentInstanceId(new PlanFragmentId(new QueryId(queryId), 1), 
"0");
+    final TFragmentInstanceId upstreamThriftId = upstreamId.toThrift();
+    final TFragmentInstanceId downstreamThriftId = new 
TFragmentInstanceId(queryId, 0, "0");
+    final TEndPoint localEndPoint =
+        new TEndPoint(
+            IoTDBDescriptor.getInstance().getConfig().getInternalAddress(),
+            
IoTDBDescriptor.getInstance().getConfig().getMppDataExchangePort());
+
+    CountDownLatch readyToPublish = new CountDownLatch(1);
+    CountDownLatch allowPublish = new CountDownLatch(1);
+    AtomicLong freeOperatorBudget = new AtomicLong(0L);
+    AtomicInteger finalTransitionCount = new AtomicInteger(0);
+    ExecutorService registrationExecutor = Executors.newSingleThreadExecutor();
+    ExecutorService exchangeExecutor = Executors.newSingleThreadExecutor();
+    ExecutorService notificationExecutor = Executors.newSingleThreadExecutor();
+    try {
+      LocalMemoryManager localMemoryManager = 
Mockito.mock(LocalMemoryManager.class);
+      MemoryManager memoryManager = new MemoryManager(1024 * 1024L);
+      MemoryPool memoryPool = new MemoryPool("test", memoryManager, 512 * 
1024L);
+      Mockito.when(localMemoryManager.getQueryPool()).thenReturn(memoryPool);
+
+      FragmentInstanceStateMachine stateMachine =
+          new FragmentInstanceStateMachine(upstreamId, notificationExecutor);
+      stateMachine.addFinalStateChangeListener(
+          ignored -> {
+            finalTransitionCount.incrementAndGet();
+            freeOperatorBudget.addAndGet(operatorBudgetBytes);
+          });
+      FragmentInstanceContext context =
+          FragmentInstanceContext.createFragmentInstanceContext(upstreamId, 
stateMachine);
+
+      MPPDataExchangeManager exchangeManager =
+          new MPPDataExchangeManager(
+              localMemoryManager,
+              new TsBlockSerdeFactory(),
+              exchangeExecutor,
+              Mockito.mock(MPPDataExchangeClientManager.class)) {
+            @Override
+            protected void onBeforePublishShuffleSinkHandle(
+                TFragmentInstanceId localFragmentInstanceId) {
+              if (upstreamThriftId.equals(localFragmentInstanceId)) {
+                readyToPublish.countDown();
+                try {
+                  Assert.assertTrue(allowPublish.await(5, TimeUnit.SECONDS));
+                } catch (InterruptedException e) {
+                  Thread.currentThread().interrupt();
+                }
+              }
+            }
+          };
+
+      ISourceHandle sourceHandle =
+          exchangeManager.createLocalSourceHandleForFragment(
+              downstreamThriftId,
+              "exchange_0",
+              "sink_0",
+              upstreamThriftId,
+              0,
+              context::failed,
+              false);
+      Future<ISinkHandle> sinkHandleFuture =
+          registrationExecutor.submit(
+              () ->
+                  exchangeManager.createShuffleSinkHandle(
+                      Collections.singletonList(
+                          new DownStreamChannelLocation(
+                              localEndPoint, downstreamThriftId, 
"exchange_0")),
+                      new DownStreamChannelIndex(0),
+                      ShuffleSinkHandle.ShuffleStrategyEnum.PLAIN,
+                      upstreamThriftId,
+                      "sink_0",
+                      context));
+
+      // Pause right after the LocalSinkChannel is attached to 
SharedTsBlockQueue and before the
+      // parent ShuffleSinkHandle is inserted into shuffleSinkHandles.
+      Assert.assertTrue(readyToPublish.await(5, TimeUnit.SECONDS));
+      sourceHandle.close();
+
+      // Resume registration: the registering thread must observe the 
completed channel, remove the
+      // handle from shuffleSinkHandles, close it once, and release the full 
operator budget.
+      allowPublish.countDown();
+      ISinkHandle sinkHandle = sinkHandleFuture.get(5, TimeUnit.SECONDS);
+      sinkHandle.setNoMoreTsBlocks();
+
+      Assert.assertTrue(sinkHandle.isClosed());
+      Assert.assertFalse(sinkHandle.isAborted());
+      Assert.assertEquals(FragmentInstanceState.FINISHED, 
stateMachine.getState());
+      Assert.assertEquals(1, finalTransitionCount.get());
+      Assert.assertEquals(0, exchangeManager.getShuffleSinkHandleSize());
+      Assert.assertEquals(0, exchangeManager.getSourceHandleSize());
+      Assert.assertTrue(freeOperatorBudget.compareAndSet(operatorBudgetBytes, 
0L));
+      Assert.assertEquals(0L, memoryPool.getReservedBytes());
+    } finally {
+      allowPublish.countDown();
+      registrationExecutor.shutdownNow();
+      exchangeExecutor.shutdownNow();
+      notificationExecutor.shutdownNow();
+    }
+  }
+
+  @Test
+  public void 
testLocalSourceCloseBeforeSinkChannelAttachFinishesFragmentOnceAndReleasesBudget()
+      throws Exception {
+    final String queryId = "q_attach_close_race";
+    final long operatorBudgetBytes = 64 * 1024L;
+    final FragmentInstanceId upstreamId =
+        new FragmentInstanceId(new PlanFragmentId(new QueryId(queryId), 1), 
"0");
+    final TFragmentInstanceId upstreamThriftId = upstreamId.toThrift();
+    final TFragmentInstanceId downstreamThriftId = new 
TFragmentInstanceId(queryId, 0, "0");
+    final TEndPoint localEndPoint =
+        new TEndPoint(
+            IoTDBDescriptor.getInstance().getConfig().getInternalAddress(),
+            
IoTDBDescriptor.getInstance().getConfig().getMppDataExchangePort());
+
+    CountDownLatch queueSelected = new CountDownLatch(1);
+    CountDownLatch allowAttach = new CountDownLatch(1);
+    AtomicLong freeOperatorBudget = new AtomicLong(0L);
+    AtomicInteger finalTransitionCount = new AtomicInteger(0);
+    ExecutorService registrationExecutor = Executors.newSingleThreadExecutor();
+    ExecutorService exchangeExecutor = Executors.newSingleThreadExecutor();
+    ExecutorService notificationExecutor = Executors.newSingleThreadExecutor();
+    try {
+      LocalMemoryManager localMemoryManager = 
Mockito.mock(LocalMemoryManager.class);
+      MemoryManager memoryManager = new MemoryManager(1024 * 1024L);
+      MemoryPool memoryPool = new MemoryPool("test", memoryManager, 512 * 
1024L);
+      Mockito.when(localMemoryManager.getQueryPool()).thenReturn(memoryPool);
+
+      FragmentInstanceStateMachine stateMachine =
+          new FragmentInstanceStateMachine(upstreamId, notificationExecutor);
+      stateMachine.addFinalStateChangeListener(
+          ignored -> {
+            finalTransitionCount.incrementAndGet();
+            freeOperatorBudget.addAndGet(operatorBudgetBytes);
+          });
+      FragmentInstanceContext context =
+          FragmentInstanceContext.createFragmentInstanceContext(upstreamId, 
stateMachine);
+
+      MPPDataExchangeManager exchangeManager =
+          new MPPDataExchangeManager(
+              localMemoryManager,
+              new TsBlockSerdeFactory(),
+              exchangeExecutor,
+              Mockito.mock(MPPDataExchangeClientManager.class)) {
+            @Override
+            protected void onBeforeAttachLocalSinkChannel(
+                TFragmentInstanceId localFragmentInstanceId, 
SharedTsBlockQueue queue) {
+              if (upstreamThriftId.equals(localFragmentInstanceId)) {
+                queueSelected.countDown();
+                try {
+                  Assert.assertTrue(allowAttach.await(5, TimeUnit.SECONDS));
+                } catch (InterruptedException e) {
+                  Thread.currentThread().interrupt();
+                }
+              }
+            }
+          };
+
+      ISourceHandle sourceHandle =
+          exchangeManager.createLocalSourceHandleForFragment(
+              downstreamThriftId,
+              "exchange_0",
+              "sink_0",
+              upstreamThriftId,
+              0,
+              context::failed,
+              false);
+      Future<ISinkHandle> sinkHandleFuture =
+          registrationExecutor.submit(
+              () ->
+                  exchangeManager.createShuffleSinkHandle(
+                      Collections.singletonList(
+                          new DownStreamChannelLocation(
+                              localEndPoint, downstreamThriftId, 
"exchange_0")),
+                      new DownStreamChannelIndex(0),
+                      ShuffleSinkHandle.ShuffleStrategyEnum.PLAIN,
+                      upstreamThriftId,
+                      "sink_0",
+                      context));
+
+      // Pause after createLocalSinkChannel() selected the shared queue and 
before
+      // queue.setSinkChannel.
+      Assert.assertTrue(queueSelected.await(5, TimeUnit.SECONDS));
+      sourceHandle.close();
+      Assert.assertTrue(
+          ((LocalSourceHandle) 
sourceHandle).getSharedTsBlockQueue().isClosedNormally());
+
+      // Resume construction: LocalSinkChannel.attachToQueue() must observe 
the completed normal
+      // close and deliver it once so registration finishes the fragment and 
releases all 64 KiB.
+      allowAttach.countDown();
+      ISinkHandle sinkHandle = sinkHandleFuture.get(5, TimeUnit.SECONDS);
+      sinkHandle.setNoMoreTsBlocks();
+
+      Assert.assertTrue(sinkHandle.isClosed());
+      Assert.assertFalse(sinkHandle.isAborted());
+      Assert.assertEquals(FragmentInstanceState.FINISHED, 
stateMachine.getState());
+      Assert.assertEquals(1, finalTransitionCount.get());
+      Assert.assertEquals(0, exchangeManager.getShuffleSinkHandleSize());
+      Assert.assertEquals(0, exchangeManager.getSourceHandleSize());
+      Assert.assertTrue(freeOperatorBudget.compareAndSet(operatorBudgetBytes, 
0L));
+      Assert.assertEquals(0L, memoryPool.getReservedBytes());
+    } finally {
+      allowAttach.countDown();
+      registrationExecutor.shutdownNow();
+      exchangeExecutor.shutdownNow();
+      notificationExecutor.shutdownNow();
+    }
+  }
+
+  @Test
+  public void testLocalSourceAbortBeforeSinkChannelAttachPreservesAbortPath() 
throws Exception {
+    final String queryId = "q_attach_abort_race";
+    final FragmentInstanceId upstreamId =
+        new FragmentInstanceId(new PlanFragmentId(new QueryId(queryId), 1), 
"0");
+    final TFragmentInstanceId upstreamThriftId = upstreamId.toThrift();
+    final TFragmentInstanceId downstreamThriftId = new 
TFragmentInstanceId(queryId, 0, "0");
+    final TEndPoint localEndPoint =
+        new TEndPoint(
+            IoTDBDescriptor.getInstance().getConfig().getInternalAddress(),
+            
IoTDBDescriptor.getInstance().getConfig().getMppDataExchangePort());
+
+    CountDownLatch queueSelected = new CountDownLatch(1);
+    CountDownLatch allowAttach = new CountDownLatch(1);
+    ExecutorService registrationExecutor = Executors.newSingleThreadExecutor();
+    ExecutorService exchangeExecutor = Executors.newSingleThreadExecutor();
+    ExecutorService notificationExecutor = Executors.newSingleThreadExecutor();
+    try {
+      LocalMemoryManager localMemoryManager = 
Mockito.mock(LocalMemoryManager.class);
+      MemoryManager memoryManager = new MemoryManager(1024 * 1024L);
+      MemoryPool memoryPool = new MemoryPool("test", memoryManager, 512 * 
1024L);
+      Mockito.when(localMemoryManager.getQueryPool()).thenReturn(memoryPool);
+
+      FragmentInstanceStateMachine stateMachine =
+          new FragmentInstanceStateMachine(upstreamId, notificationExecutor);
+      FragmentInstanceContext context =
+          FragmentInstanceContext.createFragmentInstanceContext(upstreamId, 
stateMachine);
+
+      MPPDataExchangeManager exchangeManager =
+          new MPPDataExchangeManager(
+              localMemoryManager,
+              new TsBlockSerdeFactory(),
+              exchangeExecutor,
+              Mockito.mock(MPPDataExchangeClientManager.class)) {
+            @Override
+            protected void onBeforeAttachLocalSinkChannel(
+                TFragmentInstanceId localFragmentInstanceId, 
SharedTsBlockQueue queue) {
+              if (upstreamThriftId.equals(localFragmentInstanceId)) {
+                queueSelected.countDown();
+                try {
+                  Assert.assertTrue(allowAttach.await(5, TimeUnit.SECONDS));
+                } catch (InterruptedException e) {
+                  Thread.currentThread().interrupt();
+                }
+              }
+            }
+          };
+
+      ISourceHandle sourceHandle =
+          exchangeManager.createLocalSourceHandleForFragment(
+              downstreamThriftId,
+              "exchange_0",
+              "sink_0",
+              upstreamThriftId,
+              0,
+              context::failed,
+              false);
+      Future<ISinkHandle> sinkHandleFuture =
+          registrationExecutor.submit(
+              () ->
+                  exchangeManager.createShuffleSinkHandle(
+                      Collections.singletonList(
+                          new DownStreamChannelLocation(
+                              localEndPoint, downstreamThriftId, 
"exchange_0")),
+                      new DownStreamChannelIndex(0),
+                      ShuffleSinkHandle.ShuffleStrategyEnum.PLAIN,
+                      upstreamThriftId,
+                      "sink_0",
+                      context));
+
+      Assert.assertTrue(queueSelected.await(5, TimeUnit.SECONDS));
+      sourceHandle.abort(new RuntimeException("downstream aborted"));
+
+      allowAttach.countDown();
+      ISinkHandle sinkHandle = sinkHandleFuture.get(5, TimeUnit.SECONDS);
+      sinkHandle.setNoMoreTsBlocks();
+
+      Assert.assertFalse(((LocalSinkChannel) 
sinkHandle.getChannel(0)).isClosedNormally());
+      Assert.assertFalse(sinkHandle.isClosed());
+      Assert.assertEquals(FragmentInstanceState.FLUSHING, 
stateMachine.getState());
+      Assert.assertEquals(1, exchangeManager.getShuffleSinkHandleSize());
+
+      Assert.assertTrue(sinkHandle.abort());
+      Assert.assertTrue(sinkHandle.isAborted());
+      Assert.assertEquals(0, exchangeManager.getShuffleSinkHandleSize());
+    } finally {
+      allowAttach.countDown();
+      registrationExecutor.shutdownNow();
+      exchangeExecutor.shutdownNow();
+      notificationExecutor.shutdownNow();
+    }
+  }
+
+  @Test
+  public void 
testQueueCloseFailureBeforeSinkChannelAttachPreservesCleanupRetry() throws 
Exception {
+    final String queryId = "q_attach_cleanup_retry";
+    final long mockTsBlockSize = 64 * 1024L;
+    final FragmentInstanceId upstreamId =
+        new FragmentInstanceId(new PlanFragmentId(new QueryId(queryId), 1), 
"0");
+    final TFragmentInstanceId upstreamThriftId = upstreamId.toThrift();
+    final TFragmentInstanceId downstreamThriftId = new 
TFragmentInstanceId(queryId, 0, "0");
+    final TEndPoint localEndPoint =
+        new TEndPoint(
+            IoTDBDescriptor.getInstance().getConfig().getInternalAddress(),
+            
IoTDBDescriptor.getInstance().getConfig().getMppDataExchangePort());
+
+    ExecutorService exchangeExecutor = Executors.newSingleThreadExecutor();
+    ExecutorService notificationExecutor = Executors.newSingleThreadExecutor();
+    try {
+      LocalMemoryManager localMemoryManager = 
Mockito.mock(LocalMemoryManager.class);
+      MemoryManager memoryManager = new MemoryManager(1024 * 1024L);
+      MemoryPool spyMemoryPool = Mockito.spy(new MemoryPool("test", 
memoryManager, 512 * 1024L));
+      Mockito.doThrow(new RuntimeException("injected first free failure"))
+          .doCallRealMethod()
+          .when(spyMemoryPool)
+          .free(
+              Mockito.eq(queryId),
+              Mockito.eq(upstreamId.getFragmentInstanceId()),
+              Mockito.eq("sink_0"),
+              Mockito.eq(mockTsBlockSize));
+      
Mockito.when(localMemoryManager.getQueryPool()).thenReturn(spyMemoryPool);
+
+      FragmentInstanceStateMachine stateMachine =
+          new FragmentInstanceStateMachine(upstreamId, notificationExecutor);
+      FragmentInstanceContext context =
+          FragmentInstanceContext.createFragmentInstanceContext(upstreamId, 
stateMachine);
+      MPPDataExchangeManager exchangeManager =
+          new MPPDataExchangeManager(
+              localMemoryManager,
+              new TsBlockSerdeFactory(),
+              exchangeExecutor,
+              Mockito.mock(MPPDataExchangeClientManager.class));
+
+      ISourceHandle sourceHandle =
+          exchangeManager.createLocalSourceHandleForFragment(
+              downstreamThriftId,
+              "exchange_0",
+              "sink_0",
+              upstreamThriftId,
+              0,
+              context::failed,
+              false);
+      SharedTsBlockQueue queue = ((LocalSourceHandle) 
sourceHandle).getSharedTsBlockQueue();
+      synchronized (queue) {
+        queue.allowAddingTsBlock();
+        queue.add(Utils.createMockTsBlock(mockTsBlockSize));
+      }
+      Assert.assertEquals(mockTsBlockSize, spyMemoryPool.getReservedBytes());
+
+      // First source close fails inside MemoryPool.free() while sinkChannel 
is still null.
+      Assert.assertThrows(RuntimeException.class, sourceHandle::close);
+      Assert.assertFalse(queue.isClosedNormally());
+      Assert.assertEquals(mockTsBlockSize, spyMemoryPool.getReservedBytes());
+
+      // Attaching the producer afterwards must not treat the incomplete close 
as completed.
+      ISinkHandle sinkHandle =
+          exchangeManager.createShuffleSinkHandle(
+              Collections.singletonList(
+                  new DownStreamChannelLocation(localEndPoint, 
downstreamThriftId, "exchange_0")),
+              new DownStreamChannelIndex(0),
+              ShuffleSinkHandle.ShuffleStrategyEnum.PLAIN,
+              upstreamThriftId,
+              "sink_0",
+              context);
+      Assert.assertFalse(((LocalSinkChannel) 
sinkHandle.getChannel(0)).isClosedNormally());
+      Assert.assertFalse(sinkHandle.isClosed());
+      Assert.assertNotEquals(FragmentInstanceState.FINISHED, 
stateMachine.getState());
+      Assert.assertEquals(mockTsBlockSize, spyMemoryPool.getReservedBytes());
+
+      // Retrying close finishes releasing the 64 KiB reservation and 
transitions to FINISHED.
+      sourceHandle.close();
+      Assert.assertEquals(0L, spyMemoryPool.getReservedBytes());
+      Assert.assertTrue(queue.isClosedNormally());
+      Assert.assertTrue(sinkHandle.isClosed());
+      Assert.assertEquals(FragmentInstanceState.FINISHED, 
stateMachine.getState());
+      Assert.assertEquals(0, exchangeManager.getShuffleSinkHandleSize());
+      Assert.assertEquals(0, exchangeManager.getSourceHandleSize());
+    } finally {
+      exchangeExecutor.shutdownNow();
+      notificationExecutor.shutdownNow();
+    }
+  }
 }
diff --git 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/ShuffleSinkHandleTest.java
 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/ShuffleSinkHandleTest.java
index 7c4a35af095..cfaab22bd81 100644
--- 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/ShuffleSinkHandleTest.java
+++ 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/ShuffleSinkHandleTest.java
@@ -19,13 +19,24 @@
 
 package org.apache.iotdb.db.queryengine.execution.exchange;
 
+import org.apache.iotdb.common.rpc.thrift.TEndPoint;
+import org.apache.iotdb.commons.client.sync.MPPDataExchangeClientManager;
 import org.apache.iotdb.commons.memory.MemoryManager;
+import org.apache.iotdb.db.conf.IoTDBDescriptor;
 import org.apache.iotdb.db.queryengine.common.FragmentInstanceId;
+import org.apache.iotdb.db.queryengine.common.PlanFragmentId;
+import org.apache.iotdb.db.queryengine.common.QueryId;
 import 
org.apache.iotdb.db.queryengine.execution.exchange.sink.DownStreamChannelIndex;
+import 
org.apache.iotdb.db.queryengine.execution.exchange.sink.DownStreamChannelLocation;
 import org.apache.iotdb.db.queryengine.execution.exchange.sink.ISinkChannel;
+import org.apache.iotdb.db.queryengine.execution.exchange.sink.ISinkHandle;
 import 
org.apache.iotdb.db.queryengine.execution.exchange.sink.LocalSinkChannel;
 import 
org.apache.iotdb.db.queryengine.execution.exchange.sink.ShuffleSinkHandle;
+import org.apache.iotdb.db.queryengine.execution.exchange.source.ISourceHandle;
 import 
org.apache.iotdb.db.queryengine.execution.exchange.source.LocalSourceHandle;
+import 
org.apache.iotdb.db.queryengine.execution.fragment.FragmentInstanceContext;
+import 
org.apache.iotdb.db.queryengine.execution.fragment.FragmentInstanceState;
+import 
org.apache.iotdb.db.queryengine.execution.fragment.FragmentInstanceStateMachine;
 import org.apache.iotdb.db.queryengine.execution.memory.LocalMemoryManager;
 import org.apache.iotdb.db.queryengine.execution.memory.MemoryPool;
 import org.apache.iotdb.mpp.rpc.thrift.TFragmentInstanceId;
@@ -35,12 +46,16 @@ import org.junit.Assert;
 import org.junit.Test;
 import org.mockito.Mockito;
 
+import java.util.Arrays;
 import java.util.Collections;
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.CyclicBarrier;
 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.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
 import java.util.concurrent.atomic.AtomicReference;
 
 import static 
org.apache.ratis.thirdparty.com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;
@@ -348,4 +363,836 @@ public class ShuffleSinkHandleTest {
     Assert.assertTrue(localSinkChannel.isAborted());
     Mockito.verify(mockSinkListener, 
Mockito.times(1)).onAborted(localSinkChannel);
   }
+
+  @Test
+  public void testDownstreamSourceCloseCompletesFragmentImmediately() {
+    final String queryId = "q_reentrant_close";
+    final long mockTsBlockSize = 64 * 1024L;
+    final FragmentInstanceId upstreamId =
+        new FragmentInstanceId(new PlanFragmentId(new QueryId(queryId), 1), 
"0");
+    final TFragmentInstanceId upstreamThriftId = upstreamId.toThrift();
+    final TFragmentInstanceId downstreamThriftId = new 
TFragmentInstanceId(queryId, 0, "0");
+    final TEndPoint localEndPoint =
+        new TEndPoint(
+            IoTDBDescriptor.getInstance().getConfig().getInternalAddress(),
+            
IoTDBDescriptor.getInstance().getConfig().getMppDataExchangePort());
+
+    ExecutorService exchangeExecutor = newDirectExecutorService();
+    ExecutorService notificationExecutor = Executors.newSingleThreadExecutor();
+    try {
+      LocalMemoryManager localMemoryManager = 
Mockito.mock(LocalMemoryManager.class);
+      MemoryManager memoryManager = new MemoryManager(10 * mockTsBlockSize);
+      MemoryPool memoryPool = new MemoryPool("test", memoryManager, 5 * 
mockTsBlockSize);
+      Mockito.when(localMemoryManager.getQueryPool()).thenReturn(memoryPool);
+
+      FragmentInstanceStateMachine stateMachine =
+          new FragmentInstanceStateMachine(upstreamId, notificationExecutor);
+      AtomicBoolean operatorMemoryReleased = new AtomicBoolean(false);
+      stateMachine.addFinalStateChangeListener(ignored -> 
operatorMemoryReleased.set(true));
+      FragmentInstanceContext context =
+          FragmentInstanceContext.createFragmentInstanceContext(upstreamId, 
stateMachine);
+
+      MPPDataExchangeManager exchangeManager =
+          new MPPDataExchangeManager(
+              localMemoryManager,
+              new TsBlockSerdeFactory(),
+              exchangeExecutor,
+              Mockito.mock(MPPDataExchangeClientManager.class));
+
+      ISourceHandle sourceHandle =
+          exchangeManager.createLocalSourceHandleForFragment(
+              downstreamThriftId,
+              "exchange_0",
+              "sink_0",
+              upstreamThriftId,
+              0,
+              context::failed,
+              false);
+      ISinkHandle sinkHandle =
+          exchangeManager.createShuffleSinkHandle(
+              Collections.singletonList(
+                  new DownStreamChannelLocation(localEndPoint, 
downstreamThriftId, "exchange_0")),
+              new DownStreamChannelIndex(0),
+              ShuffleSinkHandle.ShuffleStrategyEnum.PLAIN,
+              upstreamThriftId,
+              "sink_0",
+              context);
+
+      sourceHandle.isBlocked();
+      Assert.assertTrue(sinkHandle.isFull().isDone());
+      sinkHandle.send(Utils.createMockTsBlock(mockTsBlockSize));
+      Assert.assertEquals(mockTsBlockSize, memoryPool.getReservedBytes());
+
+      // Downstream closes early (or races right after final TsBlock wakeup), 
triggering re-entrant
+      // LocalSourceHandle.close() -> SharedTsBlockQueue.close() -> 
LocalSinkChannel.close() ->
+      // ShuffleSinkHandle.close().
+      sourceHandle.close();
+
+      Assert.assertTrue(sinkHandle.isClosed());
+      Assert.assertFalse(sinkHandle.isAborted());
+      Assert.assertEquals(FragmentInstanceState.FINISHED, 
stateMachine.getState());
+      Assert.assertTrue(operatorMemoryReleased.get());
+      Assert.assertEquals(0L, memoryPool.getReservedBytes());
+      Assert.assertEquals(0, exchangeManager.getShuffleSinkHandleSize());
+      Assert.assertEquals(0, exchangeManager.getSourceHandleSize());
+
+      exchangeManager.deRegisterFragmentInstanceFromMemoryPool(
+          queryId, upstreamId.getFragmentInstanceId(), true);
+      Assert.assertEquals(0L, memoryPool.getReservedBytes());
+    } finally {
+      notificationExecutor.shutdownNow();
+    }
+  }
+
+  @Test
+  public void testMultiChannelCloseWorksInBothChannelOrders() {
+    verifyMultiChannelCloseOrder(true);
+    verifyMultiChannelCloseOrder(false);
+  }
+
+  private void verifyMultiChannelCloseOrder(boolean closeFirstChannelEarly) {
+    final String queryId = "q_multi_close_" + closeFirstChannelEarly;
+    final FragmentInstanceId upstreamId =
+        new FragmentInstanceId(new PlanFragmentId(new QueryId(queryId), 1), 
"0");
+    final TFragmentInstanceId upstreamThriftId = upstreamId.toThrift();
+    final TFragmentInstanceId downstream0 = new TFragmentInstanceId(queryId, 
0, "0");
+    final TFragmentInstanceId downstream1 = new TFragmentInstanceId(queryId, 
0, "1");
+    final TEndPoint localEndPoint =
+        new TEndPoint(
+            IoTDBDescriptor.getInstance().getConfig().getInternalAddress(),
+            
IoTDBDescriptor.getInstance().getConfig().getMppDataExchangePort());
+
+    ExecutorService notificationExecutor = Executors.newSingleThreadExecutor();
+    try {
+      LocalMemoryManager localMemoryManager = 
Mockito.mock(LocalMemoryManager.class);
+      MemoryManager memoryManager = new MemoryManager(1024 * 1024L);
+      MemoryPool memoryPool = new MemoryPool("test", memoryManager, 512 * 
1024L);
+      Mockito.when(localMemoryManager.getQueryPool()).thenReturn(memoryPool);
+
+      FragmentInstanceStateMachine stateMachine =
+          new FragmentInstanceStateMachine(upstreamId, notificationExecutor);
+      FragmentInstanceContext context =
+          FragmentInstanceContext.createFragmentInstanceContext(upstreamId, 
stateMachine);
+
+      MPPDataExchangeManager exchangeManager =
+          new MPPDataExchangeManager(
+              localMemoryManager,
+              new TsBlockSerdeFactory(),
+              newDirectExecutorService(),
+              Mockito.mock(MPPDataExchangeClientManager.class));
+
+      ISourceHandle source0 =
+          exchangeManager.createLocalSourceHandleForFragment(
+              downstream0, "exchange_0", "sink_0", upstreamThriftId, 0, 
context::failed, false);
+      ISourceHandle source1 =
+          exchangeManager.createLocalSourceHandleForFragment(
+              downstream1, "exchange_1", "sink_0", upstreamThriftId, 1, 
context::failed, false);
+      ISinkHandle sinkHandle =
+          exchangeManager.createShuffleSinkHandle(
+              Arrays.asList(
+                  new DownStreamChannelLocation(localEndPoint, downstream0, 
"exchange_0"),
+                  new DownStreamChannelLocation(localEndPoint, downstream1, 
"exchange_1")),
+              new DownStreamChannelIndex(0),
+              ShuffleSinkHandle.ShuffleStrategyEnum.SIMPLE_ROUND_ROBIN,
+              upstreamThriftId,
+              "sink_0",
+              context);
+
+      if (closeFirstChannelEarly) {
+        source0.close();
+        Assert.assertFalse(sinkHandle.isClosed());
+        sinkHandle.setNoMoreTsBlocks();
+        source1.close();
+      } else {
+        source1.close();
+        Assert.assertFalse(sinkHandle.isClosed());
+        sinkHandle.setNoMoreTsBlocks();
+        source0.close();
+      }
+
+      Assert.assertTrue(sinkHandle.isClosed());
+      Assert.assertFalse(sinkHandle.isAborted());
+      Assert.assertEquals(FragmentInstanceState.FINISHED, 
stateMachine.getState());
+      Assert.assertEquals(0, exchangeManager.getShuffleSinkHandleSize());
+      Assert.assertEquals(0L, memoryPool.getReservedBytes());
+    } finally {
+      notificationExecutor.shutdownNow();
+    }
+  }
+
+  @Test
+  public void 
testConcurrentSetNoMoreTsBlocksAndSourceCloseAlwaysFinishesHandle() throws 
Exception {
+    final TEndPoint localEndPoint =
+        new TEndPoint(
+            IoTDBDescriptor.getInstance().getConfig().getInternalAddress(),
+            
IoTDBDescriptor.getInstance().getConfig().getMppDataExchangePort());
+    ExecutorService raceExecutor = Executors.newFixedThreadPool(2);
+    ExecutorService notificationExecutor = Executors.newSingleThreadExecutor();
+    try {
+      LocalMemoryManager localMemoryManager = 
Mockito.mock(LocalMemoryManager.class);
+      MemoryManager memoryManager = new MemoryManager(4 * 1024 * 1024L);
+      MemoryPool memoryPool = new MemoryPool("test", memoryManager, 2 * 1024 * 
1024L);
+      Mockito.when(localMemoryManager.getQueryPool()).thenReturn(memoryPool);
+      MPPDataExchangeManager exchangeManager =
+          new MPPDataExchangeManager(
+              localMemoryManager,
+              new TsBlockSerdeFactory(),
+              newDirectExecutorService(),
+              Mockito.mock(MPPDataExchangeClientManager.class));
+
+      for (int i = 0; i < 200; i++) {
+        String queryId = "q_race_" + i;
+        FragmentInstanceId upstreamId =
+            new FragmentInstanceId(new PlanFragmentId(new QueryId(queryId), 
1), "0");
+        TFragmentInstanceId upstreamThriftId = upstreamId.toThrift();
+        TFragmentInstanceId downstreamThriftId = new 
TFragmentInstanceId(queryId, 0, "0");
+
+        final long operatorBudgetBytes = 64 * 1024L;
+        AtomicLong freeOperatorBudget = new AtomicLong(0L);
+        FragmentInstanceStateMachine stateMachine =
+            new FragmentInstanceStateMachine(upstreamId, notificationExecutor);
+        stateMachine.addFinalStateChangeListener(
+            ignored -> freeOperatorBudget.addAndGet(operatorBudgetBytes));
+        FragmentInstanceContext context =
+            FragmentInstanceContext.createFragmentInstanceContext(upstreamId, 
stateMachine);
+
+        ISourceHandle sourceHandle =
+            exchangeManager.createLocalSourceHandleForFragment(
+                downstreamThriftId,
+                "exchange_0",
+                "sink_0",
+                upstreamThriftId,
+                0,
+                context::failed,
+                false);
+        ISinkHandle sinkHandle =
+            exchangeManager.createShuffleSinkHandle(
+                Collections.singletonList(
+                    new DownStreamChannelLocation(localEndPoint, 
downstreamThriftId, "exchange_0")),
+                new DownStreamChannelIndex(0),
+                ShuffleSinkHandle.ShuffleStrategyEnum.PLAIN,
+                upstreamThriftId,
+                "sink_0",
+                context);
+
+        ListenableFuture<?> blocked = sourceHandle.isBlocked();
+        if (i % 2 == 0) {
+          sinkHandle.send(Utils.createMockTsBlock(4096L));
+          Assert.assertNotNull(sourceHandle.receive());
+          blocked = sourceHandle.isBlocked();
+        }
+        ListenableFuture<?> waitFuture = blocked;
+        CountDownLatch startLatch = new CountDownLatch(1);
+        Future<?> driverFuture =
+            raceExecutor.submit(
+                () -> {
+                  startLatch.await();
+                  sinkHandle.setNoMoreTsBlocks();
+                  return null;
+                });
+        Future<?> clientFuture =
+            raceExecutor.submit(
+                () -> {
+                  startLatch.await();
+                  waitFuture.get(5, TimeUnit.SECONDS);
+                  Assert.assertTrue(sourceHandle.isFinished());
+                  sourceHandle.close();
+                  // Verify inside the client task immediately upon 
sourceHandle.close() returning
+                  // (without waiting for driverFuture) that the previous 
fragment is FINISHED and
+                  // the next query can immediately reserve the full operator 
memory budget.
+                  Assert.assertTrue(sinkHandle.isClosed());
+                  Assert.assertEquals(FragmentInstanceState.FINISHED, 
stateMachine.getState());
+                  
Assert.assertTrue(freeOperatorBudget.compareAndSet(operatorBudgetBytes, 0L));
+                  return null;
+                });
+        startLatch.countDown();
+        clientFuture.get(5, TimeUnit.SECONDS);
+        driverFuture.get(5, TimeUnit.SECONDS);
+
+        exchangeManager.deRegisterFragmentInstanceFromMemoryPool(
+            queryId, upstreamId.getFragmentInstanceId(), true);
+        Assert.assertEquals(0L, memoryPool.getReservedBytes());
+      }
+    } finally {
+      raceExecutor.shutdownNow();
+      notificationExecutor.shutdownNow();
+    }
+  }
+
+  @Test
+  public void 
testAbortWaitsForInFlightChannelCloseMemoryReleaseBeforeDeregister()
+      throws Exception {
+    final String queryId = "q_close_abort_barrier";
+    final long mockTsBlockSize = 64 * 1024L;
+    final FragmentInstanceId upstreamId =
+        new FragmentInstanceId(new PlanFragmentId(new QueryId(queryId), 1), 
"0");
+    final TFragmentInstanceId upstreamThriftId = upstreamId.toThrift();
+    final TFragmentInstanceId downstreamThriftId = new 
TFragmentInstanceId(queryId, 0, "0");
+    final TEndPoint localEndPoint =
+        new TEndPoint(
+            IoTDBDescriptor.getInstance().getConfig().getInternalAddress(),
+            
IoTDBDescriptor.getInstance().getConfig().getMppDataExchangePort());
+
+    CountDownLatch freeEntered = new CountDownLatch(1);
+    CountDownLatch allowFreeToComplete = new CountDownLatch(1);
+    AtomicBoolean freeCompletedBeforeAbortReturned = new AtomicBoolean(false);
+    ExecutorService executor = Executors.newFixedThreadPool(2);
+    ExecutorService notificationExecutor = Executors.newSingleThreadExecutor();
+    try {
+      LocalMemoryManager localMemoryManager = 
Mockito.mock(LocalMemoryManager.class);
+      MemoryManager memoryManager = new MemoryManager(10 * mockTsBlockSize);
+      MemoryPool spyMemoryPool =
+          Mockito.spy(new MemoryPool("test", memoryManager, 5 * 
mockTsBlockSize));
+      Mockito.doAnswer(
+              invocation -> {
+                freeEntered.countDown();
+                Assert.assertTrue(allowFreeToComplete.await(5, 
TimeUnit.SECONDS));
+                Object res = invocation.callRealMethod();
+                freeCompletedBeforeAbortReturned.set(true);
+                return res;
+              })
+          .when(spyMemoryPool)
+          .free(
+              Mockito.eq(queryId),
+              Mockito.eq(upstreamId.getFragmentInstanceId()),
+              Mockito.eq("sink_0"),
+              Mockito.eq(mockTsBlockSize));
+      
Mockito.when(localMemoryManager.getQueryPool()).thenReturn(spyMemoryPool);
+
+      FragmentInstanceStateMachine stateMachine =
+          new FragmentInstanceStateMachine(upstreamId, notificationExecutor);
+      FragmentInstanceContext context =
+          FragmentInstanceContext.createFragmentInstanceContext(upstreamId, 
stateMachine);
+      MPPDataExchangeManager exchangeManager =
+          new MPPDataExchangeManager(
+              localMemoryManager,
+              new TsBlockSerdeFactory(),
+              newDirectExecutorService(),
+              Mockito.mock(MPPDataExchangeClientManager.class));
+
+      ISourceHandle sourceHandle =
+          exchangeManager.createLocalSourceHandleForFragment(
+              downstreamThriftId,
+              "exchange_0",
+              "sink_0",
+              upstreamThriftId,
+              0,
+              context::failed,
+              false);
+      ISinkHandle sinkHandle =
+          exchangeManager.createShuffleSinkHandle(
+              Collections.singletonList(
+                  new DownStreamChannelLocation(localEndPoint, 
downstreamThriftId, "exchange_0")),
+              new DownStreamChannelIndex(0),
+              ShuffleSinkHandle.ShuffleStrategyEnum.PLAIN,
+              upstreamThriftId,
+              "sink_0",
+              context);
+
+      sourceHandle.isBlocked();
+      sinkHandle.send(Utils.createMockTsBlock(mockTsBlockSize));
+
+      Future<?> closeFuture =
+          executor.submit(
+              () -> {
+                sourceHandle.close();
+                return null;
+              });
+      Assert.assertTrue(freeEntered.await(5, TimeUnit.SECONDS));
+
+      CountDownLatch abortStarted = new CountDownLatch(1);
+      Future<?> abortAndDeregisterFuture =
+          executor.submit(
+              () -> {
+                abortStarted.countDown();
+                sinkHandle.abort();
+                Assert.assertTrue(freeCompletedBeforeAbortReturned.get());
+                exchangeManager.deRegisterFragmentInstanceFromMemoryPool(
+                    queryId, upstreamId.getFragmentInstanceId(), true);
+                return null;
+              });
+      Assert.assertTrue(abortStarted.await(5, TimeUnit.SECONDS));
+      Assert.assertFalse(abortAndDeregisterFuture.isDone());
+
+      allowFreeToComplete.countDown();
+      closeFuture.get(5, TimeUnit.SECONDS);
+      abortAndDeregisterFuture.get(5, TimeUnit.SECONDS);
+      Assert.assertEquals(0L, spyMemoryPool.getReservedBytes());
+    } finally {
+      allowFreeToComplete.countDown();
+      executor.shutdownNow();
+      notificationExecutor.shutdownNow();
+    }
+  }
+
+  @Test
+  public void 
testSourceAbortBeforeOrAfterDriverEndOfStreamDoesNotFinishFragment() {
+    verifySourceAbortDoesNotFinishFragment(false);
+    verifySourceAbortDoesNotFinishFragment(true);
+  }
+
+  private void verifySourceAbortDoesNotFinishFragment(boolean 
sendAndEndBeforeSourceAbort) {
+    final String queryId = "q_source_abort_" + sendAndEndBeforeSourceAbort;
+    final long mockTsBlockSize = 64 * 1024L;
+    final FragmentInstanceId upstreamId =
+        new FragmentInstanceId(new PlanFragmentId(new QueryId(queryId), 1), 
"0");
+    final TFragmentInstanceId upstreamThriftId = upstreamId.toThrift();
+    final TFragmentInstanceId downstreamThriftId = new 
TFragmentInstanceId(queryId, 0, "0");
+    final TEndPoint localEndPoint =
+        new TEndPoint(
+            IoTDBDescriptor.getInstance().getConfig().getInternalAddress(),
+            
IoTDBDescriptor.getInstance().getConfig().getMppDataExchangePort());
+
+    ExecutorService notificationExecutor = Executors.newSingleThreadExecutor();
+    try {
+      LocalMemoryManager localMemoryManager = 
Mockito.mock(LocalMemoryManager.class);
+      MemoryManager memoryManager = new MemoryManager(10 * mockTsBlockSize);
+      MemoryPool memoryPool = new MemoryPool("test", memoryManager, 5 * 
mockTsBlockSize);
+      Mockito.when(localMemoryManager.getQueryPool()).thenReturn(memoryPool);
+
+      FragmentInstanceStateMachine stateMachine =
+          new FragmentInstanceStateMachine(upstreamId, notificationExecutor);
+      FragmentInstanceContext context =
+          FragmentInstanceContext.createFragmentInstanceContext(upstreamId, 
stateMachine);
+      MPPDataExchangeManager exchangeManager =
+          new MPPDataExchangeManager(
+              localMemoryManager,
+              new TsBlockSerdeFactory(),
+              newDirectExecutorService(),
+              Mockito.mock(MPPDataExchangeClientManager.class));
+
+      ISourceHandle sourceHandle =
+          exchangeManager.createLocalSourceHandleForFragment(
+              downstreamThriftId,
+              "exchange_0",
+              "sink_0",
+              upstreamThriftId,
+              0,
+              context::failed,
+              false);
+      ISinkHandle sinkHandle =
+          exchangeManager.createShuffleSinkHandle(
+              Collections.singletonList(
+                  new DownStreamChannelLocation(localEndPoint, 
downstreamThriftId, "exchange_0")),
+              new DownStreamChannelIndex(0),
+              ShuffleSinkHandle.ShuffleStrategyEnum.PLAIN,
+              upstreamThriftId,
+              "sink_0",
+              context);
+      LocalSinkChannel channel = (LocalSinkChannel) sinkHandle.getChannel(0);
+
+      sourceHandle.isBlocked();
+      if (sendAndEndBeforeSourceAbort) {
+        sinkHandle.send(Utils.createMockTsBlock(mockTsBlockSize));
+        sinkHandle.setNoMoreTsBlocks();
+        Assert.assertEquals(FragmentInstanceState.FLUSHING, 
stateMachine.getState());
+        sourceHandle.abort(new RuntimeException("downstream aborted"));
+        channel.checkAndInvokeOnFinished();
+        Assert.assertFalse(channel.close());
+      } else {
+        sourceHandle.abort(new RuntimeException("downstream aborted"));
+        sinkHandle.setNoMoreTsBlocks();
+      }
+
+      Assert.assertFalse(channel.isFinished());
+      Assert.assertFalse(channel.isClosedNormally());
+      Assert.assertFalse(sinkHandle.isClosed());
+      Assert.assertEquals(FragmentInstanceState.FLUSHING, 
stateMachine.getState());
+
+      Assert.assertTrue(sinkHandle.abort());
+      Assert.assertTrue(sinkHandle.isAborted());
+      Assert.assertFalse(sinkHandle.isClosed());
+      Assert.assertEquals(0L, memoryPool.getReservedBytes());
+    } finally {
+      notificationExecutor.shutdownNow();
+    }
+  }
+
+  @Test
+  public void testLocalCloseRetryReleasesMemoryBeforeFinishingHandle() {
+    final String queryId = "q_local_close_retry";
+    final long mockTsBlockSize = 64 * 1024L;
+    final FragmentInstanceId upstreamId =
+        new FragmentInstanceId(new PlanFragmentId(new QueryId(queryId), 1), 
"0");
+    final TFragmentInstanceId upstreamThriftId = upstreamId.toThrift();
+    final TFragmentInstanceId downstreamThriftId = new 
TFragmentInstanceId(queryId, 0, "0");
+    final TEndPoint localEndPoint =
+        new TEndPoint(
+            IoTDBDescriptor.getInstance().getConfig().getInternalAddress(),
+            
IoTDBDescriptor.getInstance().getConfig().getMppDataExchangePort());
+
+    ExecutorService notificationExecutor = Executors.newSingleThreadExecutor();
+    try {
+      LocalMemoryManager localMemoryManager = 
Mockito.mock(LocalMemoryManager.class);
+      MemoryManager memoryManager = new MemoryManager(10 * mockTsBlockSize);
+      MemoryPool spyMemoryPool =
+          Mockito.spy(new MemoryPool("test", memoryManager, 5 * 
mockTsBlockSize));
+      Mockito.doThrow(new RuntimeException("injected first free failure"))
+          .doCallRealMethod()
+          .when(spyMemoryPool)
+          .free(
+              Mockito.eq(queryId),
+              Mockito.eq(upstreamId.getFragmentInstanceId()),
+              Mockito.eq("sink_0"),
+              Mockito.eq(mockTsBlockSize));
+      
Mockito.when(localMemoryManager.getQueryPool()).thenReturn(spyMemoryPool);
+
+      FragmentInstanceStateMachine stateMachine =
+          new FragmentInstanceStateMachine(upstreamId, notificationExecutor);
+      FragmentInstanceContext context =
+          FragmentInstanceContext.createFragmentInstanceContext(upstreamId, 
stateMachine);
+      MPPDataExchangeManager exchangeManager =
+          new MPPDataExchangeManager(
+              localMemoryManager,
+              new TsBlockSerdeFactory(),
+              newDirectExecutorService(),
+              Mockito.mock(MPPDataExchangeClientManager.class));
+
+      ISourceHandle sourceHandle =
+          exchangeManager.createLocalSourceHandleForFragment(
+              downstreamThriftId,
+              "exchange_0",
+              "sink_0",
+              upstreamThriftId,
+              0,
+              context::failed,
+              false);
+      ISinkHandle sinkHandle =
+          exchangeManager.createShuffleSinkHandle(
+              Collections.singletonList(
+                  new DownStreamChannelLocation(localEndPoint, 
downstreamThriftId, "exchange_0")),
+              new DownStreamChannelIndex(0),
+              ShuffleSinkHandle.ShuffleStrategyEnum.PLAIN,
+              upstreamThriftId,
+              "sink_0",
+              context);
+      LocalSinkChannel channel = (LocalSinkChannel) sinkHandle.getChannel(0);
+
+      sourceHandle.isBlocked();
+      sinkHandle.send(Utils.createMockTsBlock(mockTsBlockSize));
+      Assert.assertEquals(mockTsBlockSize, spyMemoryPool.getReservedBytes());
+
+      // First close fails inside MemoryPool.free(): reservation is still held 
and handle must not
+      // report closed or transition the fragment to FINISHED.
+      Assert.assertFalse(sinkHandle.close());
+      Assert.assertFalse(channel.isClosedNormally());
+      Assert.assertFalse(sinkHandle.isClosed());
+      Assert.assertNotEquals(FragmentInstanceState.FINISHED, 
stateMachine.getState());
+      Assert.assertEquals(mockTsBlockSize, spyMemoryPool.getReservedBytes());
+
+      // Retry releases the remaining 64 KiB and completes normal finish.
+      Assert.assertTrue(sinkHandle.close());
+      Assert.assertTrue(channel.isClosedNormally());
+      Assert.assertTrue(sinkHandle.isClosed());
+      Assert.assertEquals(FragmentInstanceState.FINISHED, 
stateMachine.getState());
+      Assert.assertEquals(0L, spyMemoryPool.getReservedBytes());
+    } finally {
+      notificationExecutor.shutdownNow();
+    }
+  }
+
+  @Test
+  public void 
testCloseAndAbortRemainMutuallyExclusiveUnderRaceAndPostCloseAbort()
+      throws Exception {
+    final TEndPoint localEndPoint =
+        new TEndPoint(
+            IoTDBDescriptor.getInstance().getConfig().getInternalAddress(),
+            
IoTDBDescriptor.getInstance().getConfig().getMppDataExchangePort());
+    ExecutorService executor = Executors.newFixedThreadPool(2);
+    ExecutorService notificationExecutor = Executors.newSingleThreadExecutor();
+    try {
+      LocalMemoryManager localMemoryManager = 
Mockito.mock(LocalMemoryManager.class);
+      MemoryManager memoryManager = new MemoryManager(4 * 1024 * 1024L);
+      MemoryPool memoryPool = new MemoryPool("test", memoryManager, 2 * 1024 * 
1024L);
+      Mockito.when(localMemoryManager.getQueryPool()).thenReturn(memoryPool);
+      MPPDataExchangeManager exchangeManager =
+          new MPPDataExchangeManager(
+              localMemoryManager,
+              new TsBlockSerdeFactory(),
+              newDirectExecutorService(),
+              Mockito.mock(MPPDataExchangeClientManager.class));
+
+      for (int i = 0; i < 200; i++) {
+        String queryId = "q_exclusive_" + i;
+        FragmentInstanceId upstreamId =
+            new FragmentInstanceId(new PlanFragmentId(new QueryId(queryId), 
1), "0");
+        TFragmentInstanceId upstreamThriftId = upstreamId.toThrift();
+        TFragmentInstanceId downstreamThriftId = new 
TFragmentInstanceId(queryId, 0, "0");
+
+        FragmentInstanceStateMachine stateMachine =
+            new FragmentInstanceStateMachine(upstreamId, notificationExecutor);
+        FragmentInstanceContext context =
+            FragmentInstanceContext.createFragmentInstanceContext(upstreamId, 
stateMachine);
+
+        exchangeManager.createLocalSourceHandleForFragment(
+            downstreamThriftId,
+            "exchange_0",
+            "sink_0",
+            upstreamThriftId,
+            0,
+            context::failed,
+            false);
+        ISinkHandle sinkHandle =
+            exchangeManager.createShuffleSinkHandle(
+                Collections.singletonList(
+                    new DownStreamChannelLocation(localEndPoint, 
downstreamThriftId, "exchange_0")),
+                new DownStreamChannelIndex(0),
+                ShuffleSinkHandle.ShuffleStrategyEnum.PLAIN,
+                upstreamThriftId,
+                "sink_0",
+                context);
+
+        CyclicBarrier barrier = new CyclicBarrier(2);
+        Future<Boolean> closeFuture =
+            executor.submit(
+                () -> {
+                  barrier.await(5, TimeUnit.SECONDS);
+                  return sinkHandle.close();
+                });
+        Future<Boolean> abortFuture =
+            executor.submit(
+                () -> {
+                  barrier.await(5, TimeUnit.SECONDS);
+                  return sinkHandle.abort();
+                });
+        boolean closedOk = closeFuture.get(5, TimeUnit.SECONDS);
+        boolean abortedOk = abortFuture.get(5, TimeUnit.SECONDS);
+
+        Assert.assertTrue("Exactly one of close or abort must win", closedOk ^ 
abortedOk);
+        Assert.assertEquals(closedOk, sinkHandle.isClosed());
+        Assert.assertEquals(abortedOk, sinkHandle.isAborted());
+        if (closedOk) {
+          Assert.assertFalse(sinkHandle.abort());
+          Assert.assertFalse(sinkHandle.isAborted());
+        } else {
+          Assert.assertFalse(sinkHandle.close());
+          Assert.assertFalse(sinkHandle.isClosed());
+        }
+      }
+    } finally {
+      executor.shutdownNow();
+      notificationExecutor.shutdownNow();
+    }
+  }
+
+  @Test
+  public void 
testClientCloseWaitsForPausedProducerEndOfBlocksToReleaseOperatorBudget()
+      throws Exception {
+    final String queryId = "q_paused_producer_eof";
+    final long operatorBudgetBytes = 64 * 1024L;
+    final FragmentInstanceId upstreamId =
+        new FragmentInstanceId(new PlanFragmentId(new QueryId(queryId), 1), 
"0");
+    final TFragmentInstanceId upstreamThriftId = upstreamId.toThrift();
+    final TFragmentInstanceId downstreamThriftId = new 
TFragmentInstanceId(queryId, 0, "0");
+
+    CountDownLatch producerAtEndOfBlocks = new CountDownLatch(1);
+    CountDownLatch allowProducerToProceed = new CountDownLatch(1);
+    AtomicLong freeOperatorBudget = new AtomicLong(0L);
+    ExecutorService executor = Executors.newFixedThreadPool(2);
+    ExecutorService notificationExecutor = Executors.newSingleThreadExecutor();
+    try {
+      LocalMemoryManager localMemoryManager = 
Mockito.mock(LocalMemoryManager.class);
+      MemoryManager memoryManager = new MemoryManager(1024 * 1024L);
+      MemoryPool memoryPool = new MemoryPool("test", memoryManager, 512 * 
1024L);
+      Mockito.when(localMemoryManager.getQueryPool()).thenReturn(memoryPool);
+
+      FragmentInstanceStateMachine stateMachine =
+          new FragmentInstanceStateMachine(upstreamId, notificationExecutor);
+      stateMachine.addFinalStateChangeListener(
+          ignored -> freeOperatorBudget.addAndGet(operatorBudgetBytes));
+      FragmentInstanceContext context =
+          FragmentInstanceContext.createFragmentInstanceContext(upstreamId, 
stateMachine);
+
+      SharedTsBlockQueue queue =
+          new SharedTsBlockQueue(
+              upstreamThriftId, "sink_0", localMemoryManager, 
newDirectExecutorService());
+      AtomicReference<ShuffleSinkHandle> handleRef = new AtomicReference<>();
+      MPPDataExchangeManager.SinkListener channelListener =
+          new MPPDataExchangeManager.SinkListener() {
+            private final AtomicBoolean closedHandle = new 
AtomicBoolean(false);
+
+            @Override
+            public void 
onFinish(org.apache.iotdb.db.queryengine.execution.exchange.sink.ISink s) {
+              if (closedHandle.compareAndSet(false, true)) {
+                handleRef.get().close();
+              }
+            }
+
+            @Override
+            public void onEndOfBlocks(
+                org.apache.iotdb.db.queryengine.execution.exchange.sink.ISink 
s) {
+              producerAtEndOfBlocks.countDown();
+              try {
+                Assert.assertTrue(allowProducerToProceed.await(5, 
TimeUnit.SECONDS));
+              } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
+              }
+            }
+
+            @Override
+            public java.util.Optional<Throwable> onAborted(
+                org.apache.iotdb.db.queryengine.execution.exchange.sink.ISink 
s) {
+              return context.getFailureCause();
+            }
+
+            @Override
+            public void onFailure(
+                org.apache.iotdb.db.queryengine.execution.exchange.sink.ISink 
s, Throwable t) {
+              context.failed(t);
+            }
+          };
+      LocalSinkChannel localSinkChannel =
+          new LocalSinkChannel(upstreamThriftId, queue, channelListener);
+      LocalSourceHandle sourceHandle =
+          new LocalSourceHandle(
+              downstreamThriftId,
+              "exchange_0",
+              queue,
+              Mockito.mock(MPPDataExchangeManager.SourceHandleListener.class));
+      ShuffleSinkHandle sinkHandle =
+          new ShuffleSinkHandle(
+              upstreamThriftId,
+              Collections.singletonList(localSinkChannel),
+              new DownStreamChannelIndex(0),
+              ShuffleSinkHandle.ShuffleStrategyEnum.PLAIN,
+              new MPPDataExchangeManager.SinkListener() {
+                @Override
+                public void onFinish(
+                    
org.apache.iotdb.db.queryengine.execution.exchange.sink.ISink sink) {
+                  context.finished();
+                }
+
+                @Override
+                public void onEndOfBlocks(
+                    
org.apache.iotdb.db.queryengine.execution.exchange.sink.ISink sink) {
+                  context.transitionToFlushing();
+                }
+
+                @Override
+                public java.util.Optional<Throwable> onAborted(
+                    
org.apache.iotdb.db.queryengine.execution.exchange.sink.ISink sink) {
+                  return context.getFailureCause();
+                }
+
+                @Override
+                public void onFailure(
+                    
org.apache.iotdb.db.queryengine.execution.exchange.sink.ISink sink,
+                    Throwable t) {
+                  context.failed(t);
+                }
+              });
+      handleRef.set(sinkHandle);
+
+      ListenableFuture<?> blocked = sourceHandle.isBlocked();
+      Future<?> producerFuture =
+          executor.submit(
+              () -> {
+                sinkHandle.setNoMoreTsBlocks();
+                return null;
+              });
+      Assert.assertTrue(producerAtEndOfBlocks.await(5, TimeUnit.SECONDS));
+
+      // blocked is already completed by queue.setNoMoreTsBlocks(true), while 
producer is paused
+      // before onFinish. Client must not return from sourceHandle.close() 
until operator budget is
+      // released.
+      Future<?> clientFuture =
+          executor.submit(
+              () -> {
+                blocked.get(5, TimeUnit.SECONDS);
+                Assert.assertTrue(sourceHandle.isFinished());
+                sourceHandle.close();
+                Assert.assertEquals(FragmentInstanceState.FINISHED, 
stateMachine.getState());
+                
Assert.assertTrue(freeOperatorBudget.compareAndSet(operatorBudgetBytes, 0L));
+                return null;
+              });
+      Assert.assertFalse(clientFuture.isDone());
+
+      allowProducerToProceed.countDown();
+      clientFuture.get(5, TimeUnit.SECONDS);
+      producerFuture.get(5, TimeUnit.SECONDS);
+    } finally {
+      allowProducerToProceed.countDown();
+      executor.shutdownNow();
+      notificationExecutor.shutdownNow();
+    }
+  }
+
+  @Test
+  public void testPausedAbortAfterLoopCheckDoesNotSucceedAfterCloseCompletes() 
throws Exception {
+    final String queryId = "q_paused_abort_aba";
+    final TFragmentInstanceId upstreamThriftId = new 
TFragmentInstanceId(queryId, 1, "0");
+    final TFragmentInstanceId downstreamThriftId = new 
TFragmentInstanceId(queryId, 0, "0");
+
+    CountDownLatch abortPassedLoopCheck = new CountDownLatch(1);
+    CountDownLatch allowAbortToAcquireClaim = new CountDownLatch(1);
+    AtomicReference<Thread> abortThreadRef = new AtomicReference<>();
+    ExecutorService executor = Executors.newSingleThreadExecutor();
+    try {
+      LocalMemoryManager localMemoryManager = 
Mockito.mock(LocalMemoryManager.class);
+      MemoryManager memoryManager = new MemoryManager(1024 * 1024L);
+      MemoryPool memoryPool = new MemoryPool("test", memoryManager, 512 * 
1024L);
+      Mockito.when(localMemoryManager.getQueryPool()).thenReturn(memoryPool);
+
+      SharedTsBlockQueue queue =
+          new SharedTsBlockQueue(
+              upstreamThriftId, "sink_0", localMemoryManager, 
newDirectExecutorService());
+      MPPDataExchangeManager.SinkListener channelListener =
+          Mockito.mock(MPPDataExchangeManager.SinkListener.class);
+      MPPDataExchangeManager.SinkListener handleListener =
+          Mockito.mock(MPPDataExchangeManager.SinkListener.class);
+      LocalSinkChannel localSinkChannel =
+          new LocalSinkChannel(upstreamThriftId, queue, channelListener);
+      new LocalSourceHandle(
+          downstreamThriftId,
+          "exchange_0",
+          queue,
+          Mockito.mock(MPPDataExchangeManager.SourceHandleListener.class));
+
+      ShuffleSinkHandle sinkHandle =
+          new ShuffleSinkHandle(
+              upstreamThriftId,
+              Collections.singletonList(localSinkChannel),
+              new DownStreamChannelIndex(0),
+              ShuffleSinkHandle.ShuffleStrategyEnum.PLAIN,
+              handleListener) {
+            @Override
+            protected void onBeforeAcquireTerminationClaim() {
+              if (Thread.currentThread() == abortThreadRef.get()) {
+                abortPassedLoopCheck.countDown();
+                try {
+                  Assert.assertTrue(allowAbortToAcquireClaim.await(5, 
TimeUnit.SECONDS));
+                } catch (InterruptedException e) {
+                  Thread.currentThread().interrupt();
+                }
+              }
+            }
+          };
+
+      Future<Boolean> abortFuture =
+          executor.submit(
+              () -> {
+                abortThreadRef.set(Thread.currentThread());
+                return sinkHandle.abort();
+              });
+      Assert.assertTrue(abortPassedLoopCheck.await(5, TimeUnit.SECONDS));
+
+      // Complete normal close() while abort() is paused right after passing 
!aborted && !closed.
+      Assert.assertTrue(sinkHandle.close());
+      Assert.assertTrue(sinkHandle.isClosed());
+      Assert.assertFalse(sinkHandle.isAborted());
+      Assert.assertTrue(localSinkChannel.isClosedNormally());
+
+      // Resume abort(): it wins a fresh CAS on terminationClaim, must detect 
closed == true,
+      // release its redundant claim, and return false without firing 
onAborted.
+      allowAbortToAcquireClaim.countDown();
+      Assert.assertFalse(abortFuture.get(5, TimeUnit.SECONDS));
+      Assert.assertTrue(sinkHandle.isClosed());
+      Assert.assertFalse(sinkHandle.isAborted());
+      Mockito.verify(handleListener, Mockito.times(1)).onFinish(sinkHandle);
+      Mockito.verify(handleListener, Mockito.never()).onAborted(sinkHandle);
+    } finally {
+      allowAbortToAcquireClaim.countDown();
+      executor.shutdownNow();
+    }
+  }
 }
diff --git 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/SinkChannelFailurePropagationTest.java
 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/SinkChannelFailurePropagationTest.java
index 12e2cc105fe..2a33458af07 100644
--- 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/SinkChannelFailurePropagationTest.java
+++ 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/exchange/SinkChannelFailurePropagationTest.java
@@ -25,6 +25,7 @@ import org.apache.iotdb.commons.client.IClientManager;
 import org.apache.iotdb.commons.client.sync.MPPDataExchangeClientManager;
 import org.apache.iotdb.commons.client.sync.SyncDataNodeInternalServiceClient;
 import 
org.apache.iotdb.commons.client.sync.SyncDataNodeMPPDataExchangeServiceClient;
+import org.apache.iotdb.commons.memory.MemoryManager;
 import org.apache.iotdb.db.queryengine.common.FragmentInstanceId;
 import org.apache.iotdb.db.queryengine.common.PlanFragmentId;
 import org.apache.iotdb.db.queryengine.common.QueryId;
@@ -45,6 +46,7 @@ import 
org.apache.iotdb.db.queryengine.execution.memory.LocalMemoryManager;
 import org.apache.iotdb.db.queryengine.execution.memory.MemoryPool;
 import org.apache.iotdb.db.queryengine.plan.planner.plan.FragmentInstance;
 import 
org.apache.iotdb.db.queryengine.plan.scheduler.FixedRateFragInsStateTracker;
+import org.apache.iotdb.mpp.rpc.thrift.TCloseSinkChannelEvent;
 import org.apache.iotdb.mpp.rpc.thrift.TFetchFragmentInstanceInfoReq;
 import org.apache.iotdb.mpp.rpc.thrift.TFragmentInstanceId;
 import org.apache.iotdb.mpp.rpc.thrift.TFragmentInstanceInfoResp;
@@ -117,12 +119,21 @@ public class SinkChannelFailurePropagationTest {
 
   @Test
   public void 
testApplicationExceptionFailsWithoutRetryAndPreventsNormalClose() throws 
Exception {
-    final String queryId = "q_failure_with_two_channels";
+    verifyMultiChannelFailurePreventsNormalClose(false);
+    verifyMultiChannelFailurePreventsNormalClose(true);
+  }
+
+  private void verifyMultiChannelFailurePreventsNormalClose(boolean 
failFirstChannel)
+      throws Exception {
+    final String queryId = "q_failure_with_two_channels_" + failFirstChannel;
     final TFragmentInstanceId upstreamThriftId = new 
TFragmentInstanceId(queryId, 1, "0");
     final FragmentInstanceId upstreamId =
         new FragmentInstanceId(new PlanFragmentId(new QueryId(queryId), 1), 
"0");
     final TEndPoint firstEndpoint = new TEndPoint("remote-exchange-0", 10740);
     final TEndPoint secondEndpoint = new TEndPoint("remote-exchange-1", 10740);
+    final TEndPoint failingEndpoint = failFirstChannel ? firstEndpoint : 
secondEndpoint;
+    final int failingChannelIndex = failFirstChannel ? 0 : 1;
+    final int normalChannelIndex = failFirstChannel ? 1 : 0;
 
     ExecutorService exchangeExecutor = Executors.newSingleThreadExecutor();
     ExecutorService fragmentNotificationExecutor = 
Executors.newSingleThreadExecutor();
@@ -144,7 +155,7 @@ public class SinkChannelFailurePropagationTest {
                   new TApplicationException(
                       TApplicationException.INTERNAL_ERROR,
                       "Internal error processing onNewDataBlockEvent")));
-      Mockito.when(exchangeClientManager.borrowClient(secondEndpoint, 
Long.MAX_VALUE))
+      Mockito.when(exchangeClientManager.borrowClient(failingEndpoint, 
Long.MAX_VALUE))
           .thenReturn(exchangeClient);
       Mockito.doThrow(expectedFailure)
           .when(exchangeClient)
@@ -167,13 +178,13 @@ public class SinkChannelFailurePropagationTest {
                       firstEndpoint, new TFragmentInstanceId(queryId, 0, "0"), 
"root-exchange-0"),
                   new DownStreamChannelLocation(
                       secondEndpoint, new TFragmentInstanceId(queryId, 0, 
"1"), "root-exchange-1")),
-              new DownStreamChannelIndex(1),
+              new DownStreamChannelIndex(failingChannelIndex),
               ShuffleSinkHandle.ShuffleStrategyEnum.PLAIN,
               upstreamThriftId,
               "upstream-sink",
               fragmentContext);
-      SinkChannel normallyFinishedChannel = (SinkChannel) 
sinkHandle.getChannel(0);
-      SinkChannel failedChannel = (SinkChannel) sinkHandle.getChannel(1);
+      SinkChannel normallyFinishedChannel = (SinkChannel) 
sinkHandle.getChannel(normalChannelIndex);
+      SinkChannel failedChannel = (SinkChannel) 
sinkHandle.getChannel(failingChannelIndex);
       failedChannel.setRetryIntervalInMs(0);
 
       Assert.assertTrue(sinkHandle.isFull().isDone());
@@ -189,6 +200,9 @@ public class SinkChannelFailurePropagationTest {
 
       Assert.assertEquals(FragmentInstanceState.FAILED, 
fragmentStateMachine.getState());
       Assert.assertEquals(expectedFailure, 
fragmentStateMachine.getFailureCauses().peek());
+      // A late close event on the failed channel must not mark it normally 
closed before abort().
+      Assert.assertFalse(failedChannel.close());
+      Assert.assertFalse(failedChannel.isClosed());
       Assert.assertTrue(normallyFinishedChannel.close());
 
       Assert.assertEquals(0, exchangeManager.getShuffleSinkHandleSize());
@@ -199,6 +213,92 @@ public class SinkChannelFailurePropagationTest {
       Assert.assertTrue(sinkHandle.isAborted());
       Assert.assertFalse(sinkHandle.isClosed());
       Assert.assertTrue(failedChannel.isAborted());
+      Assert.assertFalse(failedChannel.isClosed());
+    } finally {
+      exchangeExecutor.shutdownNow();
+      fragmentNotificationExecutor.shutdownNow();
+    }
+  }
+
+  @Test
+  public void testRemoteCloseRetryDeliversOnFinishAfterCleanupFailure() throws 
Exception {
+    final String queryId = "q_remote_close_retry";
+    final long mockTsBlockSize = 64 * 1024L;
+    final TFragmentInstanceId upstreamThriftId = new 
TFragmentInstanceId(queryId, 1, "0");
+    final FragmentInstanceId upstreamId =
+        new FragmentInstanceId(new PlanFragmentId(new QueryId(queryId), 1), 
"0");
+    final TEndPoint remoteEndpoint = new TEndPoint("remote-exchange", 10740);
+
+    ExecutorService exchangeExecutor = Executors.newSingleThreadExecutor();
+    ExecutorService fragmentNotificationExecutor = 
Executors.newSingleThreadExecutor();
+    try {
+      LocalMemoryManager localMemoryManager = 
Mockito.mock(LocalMemoryManager.class);
+      MemoryManager memoryManager = new MemoryManager(10 * 1024 * 1024L);
+      MemoryPool spyMemoryPool =
+          Mockito.spy(new MemoryPool("test", memoryManager, 5 * 1024 * 1024L));
+      Mockito.doThrow(new RuntimeException("injected first free failure"))
+          .doCallRealMethod()
+          .when(spyMemoryPool)
+          .free(
+              Mockito.eq(queryId),
+              Mockito.eq(upstreamId.getFragmentInstanceId()),
+              Mockito.eq("upstream-sink"),
+              Mockito.anyLong());
+      
Mockito.when(localMemoryManager.getQueryPool()).thenReturn(spyMemoryPool);
+
+      MPPDataExchangeClientManager exchangeClientManager =
+          Mockito.mock(MPPDataExchangeClientManager.class);
+      SyncDataNodeMPPDataExchangeServiceClient exchangeClient =
+          Mockito.mock(SyncDataNodeMPPDataExchangeServiceClient.class);
+      Mockito.when(exchangeClientManager.borrowClient(remoteEndpoint, 
Long.MAX_VALUE))
+          .thenReturn(exchangeClient);
+
+      FragmentInstanceStateMachine fragmentStateMachine =
+          new FragmentInstanceStateMachine(upstreamId, 
fragmentNotificationExecutor);
+      FragmentInstanceContext fragmentContext =
+          FragmentInstanceContext.createFragmentInstanceContext(upstreamId, 
fragmentStateMachine);
+      MPPDataExchangeManager exchangeManager =
+          new MPPDataExchangeManager(
+              localMemoryManager,
+              new TsBlockSerdeFactory(),
+              exchangeExecutor,
+              exchangeClientManager);
+      ISinkHandle sinkHandle =
+          exchangeManager.createShuffleSinkHandle(
+              Collections.singletonList(
+                  new DownStreamChannelLocation(
+                      remoteEndpoint, new TFragmentInstanceId(queryId, 0, 
"0"), "root-exchange")),
+              new DownStreamChannelIndex(0),
+              ShuffleSinkHandle.ShuffleStrategyEnum.PLAIN,
+              upstreamThriftId,
+              "upstream-sink",
+              fragmentContext);
+      SinkChannel sinkChannel = (SinkChannel) sinkHandle.getChannel(0);
+
+      Assert.assertTrue(sinkHandle.isFull().isDone());
+      sinkHandle.send(Utils.createMockTsBlocks(1, mockTsBlockSize).get(0));
+      Assert.assertTrue(spyMemoryPool.getReservedBytes() > 0L);
+
+      TCloseSinkChannelEvent closeEvent = new 
TCloseSinkChannelEvent(upstreamThriftId, 0);
+      Assert.assertThrows(
+          RuntimeException.class,
+          () ->
+              exchangeManager
+                  .getOrCreateMPPDataExchangeServiceImpl()
+                  .onCloseSinkChannelEvent(closeEvent));
+      Assert.assertFalse(sinkChannel.isClosed());
+      Assert.assertFalse(sinkHandle.isClosed());
+      Assert.assertEquals(1, exchangeManager.getShuffleSinkHandleSize());
+      Assert.assertNotEquals(FragmentInstanceState.FINISHED, 
fragmentStateMachine.getState());
+
+      // Retry of onCloseSinkChannelEvent releases buffers, removes the 
handle, and delivers
+      // onFinish so the fragment transitions to FINISHED.
+      
exchangeManager.getOrCreateMPPDataExchangeServiceImpl().onCloseSinkChannelEvent(closeEvent);
+      Assert.assertEquals(0L, spyMemoryPool.getReservedBytes());
+      Assert.assertTrue(sinkChannel.isClosed());
+      Assert.assertTrue(sinkHandle.isClosed());
+      Assert.assertEquals(0, exchangeManager.getShuffleSinkHandleSize());
+      Assert.assertEquals(FragmentInstanceState.FINISHED, 
fragmentStateMachine.getState());
     } finally {
       exchangeExecutor.shutdownNow();
       fragmentNotificationExecutor.shutdownNow();

Reply via email to