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

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


The following commit(s) were added to refs/heads/master by this push:
     new 311c056ef58 Stop leftover MSE mailboxes and finished tasks from 
keeping queries in memory (#20379)
311c056ef58 is described below

commit 311c056ef5893ac76f83473722a483e4a9454be1
Author: Yash Mayya <[email protected]>
AuthorDate: Thu Nov 26 03:21:08 2026 +0530

    Stop leftover MSE mailboxes and finished tasks from keeping queries in 
memory (#20379)
---
 .../core/util/QueryMultiThreadingUtilsTest.java    |  23 ++++
 .../apache/pinot/query/mailbox/MailboxService.java |   6 +-
 .../pinot/query/mailbox/ReceivingMailbox.java      |  46 +++++++
 .../runtime/executor/OpChainSchedulerService.java  |  13 +-
 .../operator/BaseMailboxReceiveOperator.java       |  20 ++-
 .../pinot/query/mailbox/ReceivingMailboxTest.java  |  27 ++++
 .../executor/OpChainSchedulerServiceTest.java      |  19 +++
 .../operator/MailboxReceiveOperatorTest.java       |  62 ++++++++-
 .../spi/executor/DecoratorExecutorService.java     |  26 +---
 .../pinot/spi/query/QueryExecutionContext.java     |  37 ++++-
 .../apache/pinot/spi/query/QueryThreadContext.java |  73 +++++++++-
 .../pinot/spi/query/QueryExecutionContextTest.java | 149 +++++++++++++++++++++
 12 files changed, 453 insertions(+), 48 deletions(-)

diff --git 
a/pinot-core/src/test/java/org/apache/pinot/core/util/QueryMultiThreadingUtilsTest.java
 
b/pinot-core/src/test/java/org/apache/pinot/core/util/QueryMultiThreadingUtilsTest.java
index 0c5c6ca555d..c55f204d69f 100644
--- 
a/pinot-core/src/test/java/org/apache/pinot/core/util/QueryMultiThreadingUtilsTest.java
+++ 
b/pinot-core/src/test/java/org/apache/pinot/core/util/QueryMultiThreadingUtilsTest.java
@@ -22,6 +22,9 @@ import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.TimeoutException;
 import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.pinot.spi.query.QueryExecutionContext;
+import org.apache.pinot.spi.query.QueryThreadContext;
+import org.apache.pinot.util.TestUtils;
 import org.testng.Assert;
 import org.testng.annotations.Test;
 
@@ -80,4 +83,24 @@ public class QueryMultiThreadingUtilsTest {
     }, sum::addAndGet, e -> err[0] = e, exec, System.currentTimeMillis() + 
500);
     Assert.assertTrue(err[0] instanceof TimeoutException);
   }
+
+  /// The results of the tasks can be large, for example the per-segment 
operators that CombinePlanNode builds. The
+  /// execution context of the query must not keep them once the tasks are 
done, because it can stay reachable after
+  /// the query ends.
+  @Test
+  public void testRunTasksWithDeadlineDoesNotKeepTasksInExecutionContext() {
+    ExecutorService baseExecutor = Executors.newCachedThreadPool();
+    try (QueryThreadContext threadContext = 
QueryThreadContext.openForSseTest()) {
+      ExecutorService exec = 
QueryThreadContext.contextAwareExecutorService(baseExecutor);
+      AtomicInteger sum = new AtomicInteger(0);
+      QueryMultiThreadingUtils.runTasksWithDeadline(5, index -> index, 
sum::addAndGet, e -> {
+      }, exec, System.currentTimeMillis() + 10_000L);
+      Assert.assertEquals(sum.get(), 10);
+      QueryExecutionContext executionContext = 
threadContext.getExecutionContext();
+      TestUtils.waitForCondition(aVoid -> executionContext.getNumTasks() == 0, 
10L, 10_000L,
+          "The execution context should not keep the tasks that are done");
+    } finally {
+      baseExecutor.shutdownNow();
+    }
+  }
 }
diff --git 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/mailbox/MailboxService.java
 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/mailbox/MailboxService.java
index 3f30df68492..967e10ba8ff 100644
--- 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/mailbox/MailboxService.java
+++ 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/mailbox/MailboxService.java
@@ -362,9 +362,9 @@ public class MailboxService {
   /// the sender starts sending data, and the receiver starts receiving the 
same without waiting for the OpChain to be
   /// registered. The ownership for the ReceivingMailbox hence lies with the 
MailboxService and not the OpChain.
   ///
-  /// We can safely release a receiving mailbox when all the data are received 
and processed by the OpChain. If there
-  /// might be data not received yet, we should not release the receiving 
mailbox to prevent a new receiving mailbox
-  /// being created.
+  /// We can safely release a receiving mailbox when its sender will not look 
it up again: after the sender has sent
+  /// its last block, or has been told that the mailbox takes no more blocks 
(see [ReceivingMailbox#isSenderFinished]).
+  /// Otherwise the sender could create a new receiving mailbox that nobody 
reads.
   public void releaseReceivingMailbox(ReceivingMailbox mailbox) {
     _receivingMailboxCache.invalidate(mailbox.getId());
   }
diff --git 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/mailbox/ReceivingMailbox.java
 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/mailbox/ReceivingMailbox.java
index 74e1c5bfdf9..9146b67eb88 100644
--- 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/mailbox/ReceivingMailbox.java
+++ 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/mailbox/ReceivingMailbox.java
@@ -100,8 +100,13 @@ public class ReceivingMailbox {
 
   private final StatMap<StatKey> _stats = new StatMap<>(StatKey.class);
 
+  /// Set once the sender has offered its last block, or has been told that 
the mailbox takes no more blocks. The sender
+  /// does not look the mailbox up again after that.
+  private volatile boolean _senderFinished;
+
   /// Following variables are protected with synchronized block.
   private long _lastArriveTime = System.currentTimeMillis();
+  @Nullable
   private QueryThreadContext _receiveOperatorThreadContext;
   private long _untrackedCpuTimeNs;
   private long _untrackedAllocatedBytes;
@@ -135,6 +140,30 @@ public class ReceivingMailbox {
     }
   }
 
+  /// Drops the [QueryThreadContext] registered with 
[#registerReceiveOperatorThreadContext]. Call it when the receive
+  /// operator will not read from this mailbox anymore. The resource usage of 
later [#offerRaw] calls is then not
+  /// charged to the query.
+  ///
+  /// The mailbox can stay in the [MailboxService] cache after the receive 
operator is done, and the
+  /// [QueryThreadContext] references the [QueryExecutionContext] that all the 
stages of the query on this instance
+  /// share. That context can reference large objects, for example the 
operators of a leaf stage.
+  public synchronized void unregisterReceiveOperatorThreadContext() {
+    _receiveOperatorThreadContext = null;
+  }
+
+  @VisibleForTesting
+  @Nullable
+  public synchronized QueryThreadContext getReceiveOperatorThreadContext() {
+    return _receiveOperatorThreadContext;
+  }
+
+  /// Returns true if the sender has offered its last block, or has been told 
that the mailbox takes no more blocks.
+  /// The sender does not look the mailbox up again after that, so the mailbox 
can be released from the
+  /// [MailboxService] without the risk that the sender creates a new one that 
nobody reads.
+  public boolean isSenderFinished() {
+    return _senderFinished;
+  }
+
   @VisibleForTesting
   void updateResourceUsage(QueryThreadContext threadContext, long cpuTimeNs, 
long allocatedBytes) {
     ThreadAccountant accountant = threadContext.getAccountant();
@@ -224,6 +253,19 @@ public class ReceivingMailbox {
 
   /// Offers a block into the mailbox within the timeout specified, returns 
the status of the mailbox.
   private ReceivingMailboxStatus offerPrivate(MseBlock block, List<DataBuffer> 
stats, long timeoutMs) {
+    if (block.isEos()) {
+      // Set before the reader can see the EOS
+      _senderFinished = true;
+    }
+    ReceivingMailboxStatus status = offerToQueue(block, stats, timeoutMs);
+    if (status == ReceivingMailboxStatus.LAST_BLOCK || status == 
ReceivingMailboxStatus.ALREADY_TERMINATED) {
+      // The sender stops sending when it gets either status
+      _senderFinished = true;
+    }
+    return status;
+  }
+
+  private ReceivingMailboxStatus offerToQueue(MseBlock block, List<DataBuffer> 
stats, long timeoutMs) {
     long start = System.currentTimeMillis();
     try {
       ReceivingMailboxStatus result;
@@ -278,7 +320,11 @@ public class ReceivingMailbox {
   }
 
   /// Sets an error block into the mailbox. No more blocks are accepted after 
calling this method.
+  ///
+  /// Called on the sender side, when the sender fails or is cancelled.
   public void setErrorBlock(ErrorMseBlock errorBlock, List<DataBuffer> 
serializedStats) {
+    // Set before the reader can see the error block
+    _senderFinished = true;
     _blocks.offerEos(errorBlock, serializedStats);
   }
 
diff --git 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/executor/OpChainSchedulerService.java
 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/executor/OpChainSchedulerService.java
index 694d54ebd41..99cb6d0291e 100644
--- 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/executor/OpChainSchedulerService.java
+++ 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/executor/OpChainSchedulerService.java
@@ -229,7 +229,7 @@ public class OpChainSchedulerService {
       }
     }, MoreExecutors.directExecutor());
 
-    OpChainTask opChainTask = new OpChainTask(listenableFutureTask);
+    OpChainTask opChainTask = new OpChainTask(listenableFutureTask, 
executionContext);
     try {
       // Use execute() and not submit(): submit() registers its Future with 
the execution context, and terminating the
       // query would cancel that Future, which drops the op chain if it has 
not started yet. See OpChainTask.
@@ -353,15 +353,19 @@ public class OpChainSchedulerService {
   ///
   /// `_lock` makes sure that an interrupt reaches the thread only while it 
runs the op chain, and never the next task
   /// of that thread.
+  ///
+  /// Once done, the task removes itself from the [QueryExecutionContext].
   private static final class OpChainTask extends AbstractFuture<Void> 
implements Runnable {
     private final Runnable _opChainRunner;
+    private final QueryExecutionContext _executionContext;
     private final Object _lock = new Object();
     @GuardedBy("_lock")
     @Nullable
     private Thread _thread;
 
-    OpChainTask(Runnable opChainRunner) {
+    OpChainTask(Runnable opChainRunner, QueryExecutionContext 
executionContext) {
       _opChainRunner = opChainRunner;
+      _executionContext = executionContext;
     }
 
     @Override
@@ -390,6 +394,11 @@ public class OpChainSchedulerService {
         }
       }
     }
+
+    @Override
+    protected void afterDone() {
+      _executionContext.removeTask(this);
+    }
   }
 
   private static class Metrics {
diff --git 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/operator/BaseMailboxReceiveOperator.java
 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/operator/BaseMailboxReceiveOperator.java
index da5afb98b9e..e29a30b0e59 100644
--- 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/operator/BaseMailboxReceiveOperator.java
+++ 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/operator/BaseMailboxReceiveOperator.java
@@ -167,10 +167,10 @@ public abstract class BaseMailboxReceiveOperator extends 
MultiStageOperator {
   /// Adapts a [ReceivingMailbox] to the [AsyncStream] the 
[BlockingMultiStreamConsumer] reads from.
   ///
   /// Deliberately holds the [MailboxService] and not the operator. The 
mailbox keeps this stream reachable through
-  /// the reader callback registered on it, and after a failed query the 
mailbox itself stays in the service's cache
-  /// until it expires (see [#poll()] for why it is not released earlier). A 
reference back to the operator from here
+  /// the reader callback registered on it, and a mailbox whose sender has not 
finished stays in the service's cache
+  /// until it expires (see [#cancel()] for why it is not released earlier). A 
reference back to the operator from here
   /// would keep the operator, its [OpChainExecutionContext] and everything 
reachable from them alive for that whole
-  /// time.
+  /// time. For the same reason, [#cancel()] drops the [QueryThreadContext] 
that the operator registered on the mailbox.
   private static class ReadMailboxAsyncStream implements 
AsyncStream<ReceivingMailbox.MseBlockWithStats> {
     final ReceivingMailbox _mailbox;
     final MailboxService _mailboxService;
@@ -193,9 +193,7 @@ public abstract class BaseMailboxReceiveOperator extends 
MultiStageOperator {
       if (blockWithStats != null) {
         MseBlock block = blockWithStats.getBlock();
 
-        // Only a successful EOS releases the mailbox from the service's 
cache. After an error the senders may still
-        // be running, and they have to find the cancelled mailbox rather than 
recreate a fresh one that nobody reads.
-        // The cache expiry takes care of it, and this stream holds nothing 
that makes that wait expensive.
+        // A successful EOS is the last block of the mailbox. The other ways 
out release the mailbox in cancel().
         if (block.isSuccess()) {
           _mailboxService.releaseReceivingMailbox(_mailbox);
         }
@@ -213,9 +211,19 @@ public abstract class BaseMailboxReceiveOperator extends 
MultiStageOperator {
       _mailbox.earlyTerminate();
     }
 
+    /// Called when the operator will not read from this mailbox anymore: 
after an error, a cancellation, or when the
+    /// operator closes.
+    ///
+    /// The mailbox is released from the service's cache only if its sender 
has finished. Otherwise the sender may still
+    /// look the mailbox up, and it has to find this cancelled mailbox rather 
than create a new one that nobody reads.
+    /// The cache expiry removes the mailbox later, and the mailbox no longer 
references the query after this call.
     @Override
     public void cancel() {
       _mailbox.cancel();
+      _mailbox.unregisterReceiveOperatorThreadContext();
+      if (_mailbox.isSenderFinished()) {
+        _mailboxService.releaseReceivingMailbox(_mailbox);
+      }
     }
   }
 
diff --git 
a/pinot-query-runtime/src/test/java/org/apache/pinot/query/mailbox/ReceivingMailboxTest.java
 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/mailbox/ReceivingMailboxTest.java
index 8cf48b42380..9f8a25bd2ee 100644
--- 
a/pinot-query-runtime/src/test/java/org/apache/pinot/query/mailbox/ReceivingMailboxTest.java
+++ 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/mailbox/ReceivingMailboxTest.java
@@ -110,6 +110,33 @@ public class ReceivingMailboxTest {
         "Should not be able to offer after EOS");
   }
 
+  /// The receive operator releases a mailbox that it stops reading only once 
the sender is done with it. Otherwise the
+  /// sender could look the mailbox up again and create a new one that nobody 
reads.
+  @Test
+  public void senderFinished() {
+    // The sender sends its EOS
+    ReceivingMailbox receivingMailbox = new ReceivingMailbox("id", 10);
+    assertFalse(receivingMailbox.isSenderFinished());
+    assertEquals(receivingMailbox.offer(DATA_BLOCK, List.of(), 10), 
ReceivingMailbox.ReceivingMailboxStatus.SUCCESS);
+    assertFalse(receivingMailbox.isSenderFinished());
+    assertEquals(receivingMailbox.offer(SuccessMseBlock.INSTANCE, List.of(), 
10),
+        ReceivingMailbox.ReceivingMailboxStatus.LAST_BLOCK);
+    assertTrue(receivingMailbox.isSenderFinished());
+
+    // The sender fails
+    receivingMailbox = new ReceivingMailbox("id", 10);
+    
receivingMailbox.setErrorBlock(ErrorMseBlock.fromError(QueryErrorCode.INTERNAL, 
"test"), List.of());
+    assertTrue(receivingMailbox.isSenderFinished());
+
+    // The receiver cancels the mailbox. The sender is finished only once it 
is told to stop.
+    receivingMailbox = new ReceivingMailbox("id", 10);
+    receivingMailbox.cancel();
+    assertFalse(receivingMailbox.isSenderFinished());
+    assertEquals(receivingMailbox.offer(DATA_BLOCK, List.of(), 10),
+        ReceivingMailbox.ReceivingMailboxStatus.ALREADY_TERMINATED);
+    assertTrue(receivingMailbox.isSenderFinished());
+  }
+
   @Test
   public void shouldReadDataInOrder() {
     ReceivingMailbox receivingMailbox = new ReceivingMailbox("id", 10);
diff --git 
a/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/executor/OpChainSchedulerServiceTest.java
 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/executor/OpChainSchedulerServiceTest.java
index eab550f6e99..7a1f6306f52 100644
--- 
a/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/executor/OpChainSchedulerServiceTest.java
+++ 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/executor/OpChainSchedulerServiceTest.java
@@ -43,7 +43,9 @@ import 
org.apache.pinot.query.runtime.plan.OpChainExecutionContext;
 import org.apache.pinot.spi.exception.QueryErrorCode;
 import org.apache.pinot.spi.executor.DecoratorExecutorService;
 import org.apache.pinot.spi.executor.ExecutorServiceUtils;
+import org.apache.pinot.spi.query.QueryExecutionContext;
 import org.apache.pinot.spi.query.QueryThreadContext;
+import org.apache.pinot.util.TestUtils;
 import org.mockito.ArgumentCaptor;
 import org.mockito.Mockito;
 import org.mockito.MockitoAnnotations;
@@ -153,6 +155,23 @@ public class OpChainSchedulerServiceTest {
     assertTrue(latch.await(10, TimeUnit.SECONDS), "expected await to be called 
in less than 10 seconds");
   }
 
+  /// A done task keeps its result, and the execution context of the query can 
stay reachable after the query ends. So
+  /// the op chains must not stay in the context once they are done.
+  @Test
+  public void shouldNotKeepFinishedOpChainsInTheExecutionContext() {
+    Mockito.when(_operatorA.nextBlock()).thenReturn(SuccessMseBlock.INSTANCE);
+
+    OpChainSchedulerService schedulerService = new 
OpChainSchedulerService(_executor);
+    QueryExecutionContext executionContext;
+    try (QueryThreadContext threadContext = 
QueryThreadContext.openForMseTest()) {
+      executionContext = threadContext.getExecutionContext();
+      schedulerService.register(getChain(_operatorA));
+    }
+
+    TestUtils.waitForCondition(aVoid -> executionContext.getNumTasks() == 0, 
10L, 10_000L,
+        "The execution context should not keep the op chains that are done");
+  }
+
   @Test
   public void shouldCallCancelOnOperatorsThatReturnErrorBlock()
       throws InterruptedException {
diff --git 
a/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/operator/MailboxReceiveOperatorTest.java
 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/operator/MailboxReceiveOperatorTest.java
index b2efc3652df..3cc170f7c4d 100644
--- 
a/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/operator/MailboxReceiveOperatorTest.java
+++ 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/operator/MailboxReceiveOperatorTest.java
@@ -39,11 +39,13 @@ import org.apache.pinot.query.routing.StageMetadata;
 import org.apache.pinot.query.routing.WorkerMetadata;
 import org.apache.pinot.query.runtime.blocks.ErrorMseBlock;
 import org.apache.pinot.query.runtime.blocks.MseBlock;
+import org.apache.pinot.query.runtime.blocks.SuccessMseBlock;
 import org.apache.pinot.query.runtime.operator.MultiStageOperator.Type;
 import org.apache.pinot.query.runtime.plan.MultiStageQueryStats;
 import org.apache.pinot.query.runtime.plan.OpChainExecutionContext;
 import org.apache.pinot.segment.spi.memory.DataBuffer;
 import org.apache.pinot.spi.exception.QueryErrorCode;
+import org.apache.pinot.spi.query.QueryThreadContext;
 import org.mockito.Mock;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeClass;
@@ -51,12 +53,16 @@ import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 
 import static org.apache.pinot.common.utils.DataSchema.ColumnDataType.INT;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.atLeastOnce;
 import static org.mockito.Mockito.eq;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 import static org.mockito.MockitoAnnotations.openMocks;
 import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
 import static org.testng.Assert.assertNull;
 import static org.testng.Assert.assertTrue;
 
@@ -246,9 +252,9 @@ public class MailboxReceiveOperatorTest {
     }
   }
 
-  /// After an error the mailbox stays in the service's cache until it 
expires, and the reader callback it holds keeps
-  /// the stream that adapts it reachable. That stream must not point back at 
the operator, or every failed query
-  /// would pin its operator tree and execution context for as long as the 
mailbox lingers.
+  /// A mailbox whose sender has not finished stays in the service's cache 
until it expires, and the reader callback
+  /// it holds keeps the stream that adapts it reachable. That stream must not 
point back at the operator, or every
+  /// failed query would pin its operator tree and execution context for as 
long as the mailbox lingers.
   @Test
   public void shouldNotStayReachableFromTheMailboxAfterAnError()
       throws InterruptedException {
@@ -268,6 +274,56 @@ public class MailboxReceiveOperatorTest {
     assertEquals(mailbox.getId(), MAILBOX_ID_1);
   }
 
+  /// A mailbox whose sender has not finished stays in the service's cache 
after the operator is done with it, so that
+  /// the sender finds it cancelled. Meanwhile it must not keep the 
[QueryThreadContext] of the operator: that context
+  /// references the execution context that all the stages of the query on the 
instance share, and through it large
+  /// objects such as the per-segment operators of the leaf stage.
+  @Test
+  public void shouldNotKeepTheQueryFromMailboxesOfRunningSendersWhenClosed() {
+    ReceivingMailbox mailbox1 = new ReceivingMailbox(MAILBOX_ID_1);
+    ReceivingMailbox mailbox2 = new ReceivingMailbox(MAILBOX_ID_2);
+    
when(_mailboxService.getReceivingMailbox(eq(MAILBOX_ID_1))).thenReturn(mailbox1);
+    
when(_mailboxService.getReceivingMailbox(eq(MAILBOX_ID_2))).thenReturn(mailbox2);
+    MailboxReceiveOperator operator;
+    try (QueryThreadContext ignore = QueryThreadContext.openForMseTest()) {
+      operator = getOperator(_stageMetadataBoth, 
RelDistribution.Type.HASH_DISTRIBUTED);
+    }
+    assertNotNull(mailbox1.getReceiveOperatorThreadContext());
+    assertNotNull(mailbox2.getReceiveOperatorThreadContext());
+
+    // Closed before the senders send anything, like a receive operator whose 
data another runtime reads
+    operator.close();
+
+    assertNull(mailbox1.getReceiveOperatorThreadContext());
+    assertNull(mailbox2.getReceiveOperatorThreadContext());
+    verify(_mailboxService, never()).releaseReceivingMailbox(any());
+  }
+
+  @Test
+  public void shouldReleaseMailboxesOfFinishedSendersAfterAnError() {
+    ReceivingMailbox mailbox1 = new ReceivingMailbox(MAILBOX_ID_1);
+    ReceivingMailbox mailbox2 = new ReceivingMailbox(MAILBOX_ID_2);
+    
when(_mailboxService.getReceivingMailbox(eq(MAILBOX_ID_1))).thenReturn(mailbox1);
+    
when(_mailboxService.getReceivingMailbox(eq(MAILBOX_ID_2))).thenReturn(mailbox2);
+    MailboxReceiveOperator operator;
+    try (QueryThreadContext ignore = QueryThreadContext.openForMseTest()) {
+      operator = getOperator(_stageMetadataBoth, 
RelDistribution.Type.HASH_DISTRIBUTED);
+    }
+    // Sender 1 fails, and sender 2 sends its data and finishes before the 
operator reads it
+    mailbox1.offer(ErrorMseBlock.fromException(new RuntimeException("TEST 
ERROR")), List.of(), 1000L);
+    mailbox2.offer(OperatorTestUtil.block(DATA_SCHEMA, new Object[]{1, 1}), 
List.of(), 1000L);
+    mailbox2.offer(SuccessMseBlock.INSTANCE, List.of(), 1000L);
+
+    assertTrue(operator.nextBlock().isError());
+    operator.cancel(new RuntimeException("TEST ERROR"));
+    operator.close();
+
+    assertNull(mailbox1.getReceiveOperatorThreadContext());
+    assertNull(mailbox2.getReceiveOperatorThreadContext());
+    verify(_mailboxService, atLeastOnce()).releaseReceivingMailbox(mailbox1);
+    verify(_mailboxService, atLeastOnce()).releaseReceivingMailbox(mailbox2);
+  }
+
   /// Waits for `ref` to be cleared, prompting collection as it goes. The 
reference queue does the waiting rather than a
   /// sleep loop over [WeakReference#get()], so the expected case costs one 
collection instead of a fixed delay, and the
   /// failing case still gives the collector several attempts before giving up.
diff --git 
a/pinot-spi/src/main/java/org/apache/pinot/spi/executor/DecoratorExecutorService.java
 
b/pinot-spi/src/main/java/org/apache/pinot/spi/executor/DecoratorExecutorService.java
index b2a0eb1bab5..06dc2b3d0bc 100644
--- 
a/pinot-spi/src/main/java/org/apache/pinot/spi/executor/DecoratorExecutorService.java
+++ 
b/pinot-spi/src/main/java/org/apache/pinot/spi/executor/DecoratorExecutorService.java
@@ -26,9 +26,7 @@ import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
-import java.util.function.Consumer;
 import java.util.stream.Collectors;
-import javax.annotation.Nullable;
 
 
 /// DecoratorExecutorService is an abstract class that provides a way to 
decorate an ExecutorService with additional
@@ -45,15 +43,9 @@ import javax.annotation.Nullable;
 /// TODO: Convert this class and its usages into an Executor instead of an 
ExecutorService
 public abstract class DecoratorExecutorService implements ExecutorService {
   protected final ExecutorService _executorService;
-  private final Consumer<Future<?>> _onSubmit;
 
   public DecoratorExecutorService(ExecutorService executorService) {
-    this(executorService, null);
-  }
-
-  public DecoratorExecutorService(ExecutorService executorService, @Nullable 
Consumer<Future<?>> onSubmit) {
     _executorService = executorService;
-    _onSubmit = onSubmit;
   }
 
   /// Decorates the callable task.
@@ -118,29 +110,17 @@ public abstract class DecoratorExecutorService implements 
ExecutorService {
 
   @Override
   public <T> Future<T> submit(Callable<T> task) {
-    Future<T> future = _executorService.submit(decorate(task));
-    if (_onSubmit != null) {
-      _onSubmit.accept(future);
-    }
-    return future;
+    return _executorService.submit(decorate(task));
   }
 
   @Override
   public <T> Future<T> submit(Runnable task, T result) {
-    Future<T> future = _executorService.submit(decorate(task), result);
-    if (_onSubmit != null) {
-      _onSubmit.accept(future);
-    }
-    return future;
+    return _executorService.submit(decorate(task), result);
   }
 
   @Override
   public Future<?> submit(Runnable task) {
-    Future<?> future = _executorService.submit(decorate(task));
-    if (_onSubmit != null) {
-      _onSubmit.accept(future);
-    }
-    return future;
+    return _executorService.submit(decorate(task));
   }
 
   @Override
diff --git 
a/pinot-spi/src/main/java/org/apache/pinot/spi/query/QueryExecutionContext.java 
b/pinot-spi/src/main/java/org/apache/pinot/spi/query/QueryExecutionContext.java
index 6692d5db2da..8ed8678da75 100644
--- 
a/pinot-spi/src/main/java/org/apache/pinot/spi/query/QueryExecutionContext.java
+++ 
b/pinot-spi/src/main/java/org/apache/pinot/spi/query/QueryExecutionContext.java
@@ -18,13 +18,17 @@
  */
 package org.apache.pinot.spi.query;
 
+import com.fasterxml.jackson.annotation.JsonIgnore;
 import com.fasterxml.jackson.annotation.JsonInclude;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.node.TextNode;
 import com.google.common.annotations.VisibleForTesting;
 import java.util.ArrayList;
+import java.util.Collections;
+import java.util.IdentityHashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.Future;
 import java.util.concurrent.atomic.AtomicBoolean;
@@ -64,8 +68,10 @@ public class QueryExecutionContext {
   private final String _instanceId;
   private final String _queryHash;
 
+  /// The tasks that are not done yet. A done task removes itself (see 
[#removeTask]), because a done [Future] keeps its
+  /// result, and this context can stay reachable after the query ends.
   @GuardedBy("this")
-  private final List<Future<?>> _tasks = new ArrayList<>();
+  private final Set<Future<?>> _tasks = Collections.newSetFromMap(new 
IdentityHashMap<>());
 
   private volatile TerminationException _terminateException;
 
@@ -210,25 +216,46 @@ public class QueryExecutionContext {
   }
 
   /// Adds a task to the execution context. If the query has been terminated, 
cancels the task immediately without
-  /// adding it to the context.
+  /// adding it to the context. A task that is already done is not added.
+  ///
+  /// The caller must call [#removeTask] once the task is done, so that this 
context does not keep the result of the
+  /// task reachable.
   public synchronized void addTask(Future<?> task) {
     if (_terminateException != null) {
       task.cancel(true);
-    } else {
+    } else if (!task.isDone()) {
       _tasks.add(task);
     }
   }
 
+  /// Removes a task added with [#addTask]. Call it once the task is done.
+  ///
+  /// A done [Future] keeps its result, which can be large: for example the 
per-segment operators that a leaf stage
+  /// builds in parallel. This context stays reachable for as long as anything 
references a [QueryThreadContext] of the
+  /// query, which can be after the query ends.
+  public synchronized void removeTask(Future<?> task) {
+    _tasks.remove(task);
+  }
+
+  /// Returns the number of tasks that were added and not removed yet.
+  @JsonIgnore
+  @VisibleForTesting
+  public synchronized int getNumTasks() {
+    return _tasks.size();
+  }
+
   /// Terminates the query execution with the given error code and message. 
Cancels and clears all the tasks.
   public synchronized boolean terminate(QueryErrorCode errorCode, String 
message) {
     if (_terminateException != null) {
       return false;
     }
     _terminateException = new TerminationException(errorCode, message);
-    for (Future<?> task : _tasks) {
+    // Copy first, because a task can remove itself from _tasks when it is 
cancelled
+    List<Future<?>> tasks = new ArrayList<>(_tasks);
+    _tasks.clear();
+    for (Future<?> task : tasks) {
       task.cancel(true);
     }
-    _tasks.clear();
     return true;
   }
 
diff --git 
a/pinot-spi/src/main/java/org/apache/pinot/spi/query/QueryThreadContext.java 
b/pinot-spi/src/main/java/org/apache/pinot/spi/query/QueryThreadContext.java
index 4b6092acf9c..984dc8f4ee5 100644
--- a/pinot-spi/src/main/java/org/apache/pinot/spi/query/QueryThreadContext.java
+++ b/pinot-spi/src/main/java/org/apache/pinot/spi/query/QueryThreadContext.java
@@ -26,7 +26,7 @@ import java.util.Set;
 import java.util.concurrent.Callable;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Future;
-import java.util.function.Consumer;
+import java.util.concurrent.FutureTask;
 import java.util.function.Supplier;
 import java.util.stream.Collectors;
 import javax.annotation.Nullable;
@@ -310,23 +310,63 @@ public class QueryThreadContext implements AutoCloseable {
 
   /// Returns a new [ExecutorService] whose tasks will be executed with the 
[QueryThreadContext] initialized with the
   /// state of the thread submitting the tasks. The [Future] of each task 
passed to `submit()` is registered for
-  /// cancellation when the query is terminated. Tasks passed to `execute()` 
are not registered.
+  /// cancellation when the query is terminated, until the task is done. Tasks 
passed to `execute()` are not registered.
   public static ExecutorService contextAwareExecutorService(ExecutorService 
executorService) {
     return contextAwareExecutorService(executorService, true);
   }
 
   /// Returns a new [ExecutorService] whose tasks will be executed with the 
[QueryThreadContext] initialized with the
   /// state of the thread submitting the tasks.
+  ///
+  /// When tasks are registered for cancellation, `submit()` wraps each task 
in its own [FutureTask] and passes it to
+  /// `execute()` of the given executor, not to its `submit()`. This makes no 
difference for executors that implement
+  /// `submit()` as a [FutureTask] plus `execute()`, like 
`AbstractExecutorService`.
   /// @param registerTaskForCancellation If true, tasks passed to `submit()` 
are registered with
   ///                                    QueryExecutionContext.addTask() and 
will be cancelled (via Thread.interrupt())
   ///                                    when the query is terminated. Set to 
false for executors where interrupt could
   ///                                    cause corruption
   public static ExecutorService contextAwareExecutorService(ExecutorService 
executorService,
       boolean registerTaskForCancellation) {
-    Consumer<Future<?>> onSubmit = registerTaskForCancellation
-        ? future -> get().getExecutionContext().addTask(future)
-        : null;
-    return new DecoratorExecutorService(executorService, onSubmit) {
+    return new DecoratorExecutorService(executorService) {
+      @Override
+      public <T> Future<T> submit(Callable<T> task) {
+        if (!registerTaskForCancellation) {
+          return super.submit(task);
+        }
+        QueryExecutionContext executionContext = get().getExecutionContext();
+        return executeRegistered(new RegisteredTask<>(decorate(task), 
executionContext), executionContext);
+      }
+
+      @Override
+      public <T> Future<T> submit(Runnable task, T result) {
+        if (!registerTaskForCancellation) {
+          return super.submit(task, result);
+        }
+        QueryExecutionContext executionContext = get().getExecutionContext();
+        return executeRegistered(new RegisteredTask<>(decorate(task), result, 
executionContext), executionContext);
+      }
+
+      @Override
+      public Future<?> submit(Runnable task) {
+        return submit(task, null);
+      }
+
+      /// Registers the task before it is handed to the executor, so that it 
cannot finish before it is registered.
+      /// If the query is already terminated, [QueryExecutionContext#addTask] 
cancels the task and it does not run.
+      private <T> Future<T> executeRegistered(RegisteredTask<T> task, 
QueryExecutionContext executionContext) {
+        executionContext.addTask(task);
+        if (task.isCancelled()) {
+          return task;
+        }
+        try {
+          _executorService.execute(task);
+        } catch (RuntimeException e) {
+          executionContext.removeTask(task);
+          throw e;
+        }
+        return task;
+      }
+
       @Override
       protected <T> Callable<T> decorate(Callable<T> task) {
         // NOTE: When registerTaskForCancellation is false, the task may not 
come from query execution, in which case
@@ -367,6 +407,27 @@ public class QueryThreadContext implements AutoCloseable {
     };
   }
 
+  /// A task registered with the [QueryExecutionContext] for cancellation. It 
removes itself from the context once it is
+  /// done, so that the context does not keep its result reachable.
+  private static final class RegisteredTask<T> extends FutureTask<T> {
+    private final QueryExecutionContext _executionContext;
+
+    RegisteredTask(Callable<T> callable, QueryExecutionContext 
executionContext) {
+      super(callable);
+      _executionContext = executionContext;
+    }
+
+    RegisteredTask(Runnable runnable, @Nullable T result, 
QueryExecutionContext executionContext) {
+      super(runnable, result);
+      _executionContext = executionContext;
+    }
+
+    @Override
+    protected void done() {
+      _executionContext.removeTask(this);
+    }
+  }
+
   /// Checks if the query should be terminated.
   /// @param scopeSupplier Supplier for the scope description to include in 
the exception message if the query is
   ///                      terminated.
diff --git 
a/pinot-spi/src/test/java/org/apache/pinot/spi/query/QueryExecutionContextTest.java
 
b/pinot-spi/src/test/java/org/apache/pinot/spi/query/QueryExecutionContextTest.java
new file mode 100644
index 00000000000..cc84499aa02
--- /dev/null
+++ 
b/pinot-spi/src/test/java/org/apache/pinot/spi/query/QueryExecutionContextTest.java
@@ -0,0 +1,149 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.spi.query;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.apache.pinot.spi.exception.QueryErrorCode;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertThrows;
+import static org.testng.Assert.assertTrue;
+
+
+public class QueryExecutionContextTest {
+  private ExecutorService _baseExecutorService;
+  private ExecutorService _executorService;
+
+  @BeforeClass
+  public void setUp() {
+    _baseExecutorService = Executors.newCachedThreadPool();
+    _executorService = 
QueryThreadContext.contextAwareExecutorService(_baseExecutorService);
+  }
+
+  @AfterClass
+  public void tearDown() {
+    _baseExecutorService.shutdownNow();
+  }
+
+  /// A done task keeps its result, and the execution context can stay 
reachable after the query ends (every thread of
+  /// the query references it). So the context must not keep the tasks that 
are done.
+  @Test
+  public void testDoesNotKeepDoneTasks()
+      throws Exception {
+    try (QueryThreadContext threadContext = 
QueryThreadContext.openForMseTest()) {
+      QueryExecutionContext executionContext = 
threadContext.getExecutionContext();
+      List<Future<?>> futures = List.of(
+          _executorService.submit(() -> new long[1000]),
+          _executorService.submit(() -> {
+            throw new IllegalStateException("test");
+          }),
+          _executorService.submit(() -> {
+          }),
+          _executorService.submit(() -> {
+          }, "result"));
+      for (Future<?> future : futures) {
+        try {
+          future.get(10, TimeUnit.SECONDS);
+        } catch (ExecutionException e) {
+          assertTrue(e.getCause() instanceof IllegalStateException);
+        }
+      }
+      // A task removes itself right after its result is set, so get() can 
return a little earlier
+      waitForNoTasks(executionContext);
+    }
+  }
+
+  @Test
+  public void testDoesNotAddDoneTask() {
+    QueryExecutionContext executionContext = 
QueryExecutionContext.forMseTest();
+    executionContext.addTask(CompletableFuture.completedFuture("result"));
+    assertEquals(executionContext.getNumTasks(), 0);
+  }
+
+  @Test
+  public void testDoesNotRegisterTasksWhenNotAsked()
+      throws Exception {
+    ExecutorService executorService = 
QueryThreadContext.contextAwareExecutorService(_baseExecutorService, false);
+    try (QueryThreadContext threadContext = 
QueryThreadContext.openForMseTest()) {
+      CountDownLatch release = new CountDownLatch(1);
+      Future<?> future = executorService.submit(() -> release.await(10, 
TimeUnit.SECONDS));
+      assertEquals(threadContext.getExecutionContext().getNumTasks(), 0);
+      release.countDown();
+      future.get(10, TimeUnit.SECONDS);
+    }
+  }
+
+  @Test
+  public void testTerminateCancelsRunningTasks()
+      throws Exception {
+    try (QueryThreadContext threadContext = 
QueryThreadContext.openForMseTest()) {
+      QueryExecutionContext executionContext = 
threadContext.getExecutionContext();
+      // Two tasks, because each one removes itself from the context while 
terminate() cancels them
+      int numTasks = 2;
+      CountDownLatch started = new CountDownLatch(numTasks);
+      List<Future<?>> running = new ArrayList<>();
+      for (int i = 0; i < numTasks; i++) {
+        running.add(_executorService.submit(() -> {
+          started.countDown();
+          Thread.sleep(60_000L);
+          return null;
+        }));
+      }
+      assertTrue(started.await(10, TimeUnit.SECONDS));
+      assertEquals(executionContext.getNumTasks(), numTasks);
+
+      assertTrue(executionContext.terminate(QueryErrorCode.QUERY_CANCELLATION, 
"test"));
+      for (Future<?> future : running) {
+        assertTrue(future.isCancelled());
+      }
+      assertEquals(executionContext.getNumTasks(), 0);
+
+      // A task submitted after the termination is cancelled and does not run
+      AtomicBoolean ran = new AtomicBoolean();
+      Future<?> late = _executorService.submit(() -> ran.set(true));
+      assertTrue(late.isCancelled());
+      assertThrows(CancellationException.class, late::get);
+      assertFalse(ran.get());
+      assertEquals(executionContext.getNumTasks(), 0);
+    }
+  }
+
+  private static void waitForNoTasks(QueryExecutionContext executionContext)
+      throws InterruptedException {
+    long deadlineMs = System.currentTimeMillis() + 10_000L;
+    while (executionContext.getNumTasks() > 0 && System.currentTimeMillis() < 
deadlineMs) {
+      Thread.sleep(10L);
+    }
+    assertEquals(executionContext.getNumTasks(), 0);
+  }
+}


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

Reply via email to