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 43f1d962fc1 Report the error that triggered the stream-stats fan-out 
cancel instead of the cancellation (#20440)
43f1d962fc1 is described below

commit 43f1d962fc169fb818a63295c37d6811138e05ab
Author: Yash Mayya <[email protected]>
AuthorDate: Wed Dec 2 02:24:16 2026 +0530

    Report the error that triggered the stream-stats fan-out cancel instead of 
the cancellation (#20440)
---
 pinot-common/src/main/proto/worker.proto           |  3 +
 .../tests/StreamStatsReportingIntegrationTest.java | 29 ++++++++
 .../runtime/executor/OpChainSchedulerService.java  | 10 ++-
 .../query/service/dispatch/QueryDispatcher.java    | 40 ++++++++++-
 .../dispatch/streaming/StreamingQuerySession.java  | 47 +++++++++++++
 .../pinot/query/service/server/QueryServer.java    |  6 +-
 .../executor/OpChainSchedulerServiceTest.java      | 32 +++++++++
 .../service/dispatch/QueryDispatcherTest.java      | 78 ++++++++++++++++++++++
 .../streaming/StreamingQuerySessionTest.java       | 72 +++++++++++++++++++-
 9 files changed, 309 insertions(+), 8 deletions(-)

diff --git a/pinot-common/src/main/proto/worker.proto 
b/pinot-common/src/main/proto/worker.proto
index 38fbb29fedf..2a52d1f1061 100644
--- a/pinot-common/src/main/proto/worker.proto
+++ b/pinot-common/src/main/proto/worker.proto
@@ -174,6 +174,9 @@ message OpChainComplete {
   bool success = 3;
   string error_msg = 4;            // populated when success = false
   MultiStageStatsTree stats = 5;   // structured, tree-shaped stats payload
+  // QueryErrorCode id of the failure, populated when success = false. 0 means 
unknown: servers older than this
+  // field do not set it.
+  int32 error_code = 6;
 }
 
 // Final marker on the server-to-broker stream.
diff --git 
a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/StreamStatsReportingIntegrationTest.java
 
b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/StreamStatsReportingIntegrationTest.java
index 10821927115..9b84c70de7a 100644
--- 
a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/StreamStatsReportingIntegrationTest.java
+++ 
b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/StreamStatsReportingIntegrationTest.java
@@ -29,6 +29,7 @@ import org.apache.pinot.spi.config.table.TenantConfig;
 import org.apache.pinot.spi.data.Schema;
 import org.apache.pinot.spi.data.readers.FileFormat;
 import org.apache.pinot.spi.env.PinotConfiguration;
+import org.apache.pinot.spi.exception.QueryErrorCode;
 import org.apache.pinot.spi.utils.CommonConstants;
 import org.apache.pinot.util.TestUtils;
 import org.intellij.lang.annotations.Language;
@@ -54,6 +55,7 @@ import static org.testng.Assert.assertTrue;
 ///    for the known loss in the legacy flat-binary / inorder format when a 
set op has more than two inputs.
 /// 4. The cluster-level config (`pinot.broker.mse.stream.stats`) activates 
stream mode
 ///    for all queries without a per-query option.
+/// 5. A failed query reports the error that made the broker cancel it, not 
the cancellation itself.
 ///
 /// **Why this class spins up its own cluster instead of using the shared 
suite cluster:**
 /// [#testClusterLevelConfigActivatesStreamMode] requires the broker to start 
with
@@ -406,6 +408,33 @@ public class StreamStatsReportingIntegrationTest extends 
BaseClusterIntegrationT
     return false;
   }
 
+  /// When an opchain fails, the broker cancels every opchain of the query, 
and the cancellation errors race the real
+  /// error through the mailboxes. Here the leaf on the outer join's probe 
(left) side fails at once. The outer join
+  /// still builds from its right side, a self-join that emits up to the join 
row limit, so the real error waits unread
+  /// in the probe mailbox when the cancel arrives. The client must still get 
the real error, not
+  /// "Cancelled on: <server>".
+  @Test
+  public void testFailureIsNotHiddenByFanOutCancel()
+      throws Exception {
+    @Language("sql")
+    String sql = "SELECT a.AirlineID "
+        + "FROM (SELECT AirlineID FROM mytable WHERE CAST(Carrier AS INT) > 0) 
a "
+        + "JOIN (SELECT x.AirlineID FROM mytable x JOIN mytable y ON 
x.AirlineID = y.AirlineID) b "
+        + "ON a.AirlineID = b.AirlineID";
+    // BREAK stops the joins at the row limit without an error, so the right 
side is slow but cannot fail.
+    String queryOptions = STREAM_OPTION + ";" + 
CommonConstants.Broker.Request.QueryOptionKey.JOIN_OVERFLOW_MODE
+        + "=BREAK";
+    // Which error wins the race depends on timing, so run the query several 
times.
+    for (int i = 0; i < 5; i++) {
+      JsonNode response = postQueryWithOptions(sql, queryOptions);
+      assertTrue(hasExceptions(response), "Query should fail: " + response);
+      JsonNode exception = response.get("exceptions").get(0);
+      String message = exception.get("message").asText();
+      assertEquals(exception.get("errorCode").asInt(), 
QueryErrorCode.QUERY_EXECUTION.getId(), message);
+      assertTrue(message.contains("For input string"), message);
+    }
+  }
+
   /// Verifies that the cluster-level config 
`pinot.broker.mse.stream.stats=true`
   /// activates stream mode for queries that do not carry the per-query 
option. The broker is restarted with the config
   /// set for this test class via [#overrideBrokerConf].
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 99cb6d0291e..cb9db782aa7 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
@@ -189,12 +189,13 @@ public class OpChainSchedulerService {
         if (result.isError()) {
           ErrorMseBlock errorBlock = (ErrorMseBlock) result;
           String serverId = errorBlock.getServerId() != null ? 
errorBlock.getServerId() : "unknown";
+          // The stats stay out of the message: in stream-stats mode the 
message goes to the broker, which can show it
+          // to the client. The failure log in the FutureCallback below adds 
the stats.
           throw errorBlock.getMainErrorCode().asException("Error block "
               + "from stage " + errorBlock.getStageId()
               + " worker " + errorBlock.getWorkerId()
               + " on " + serverId
-              + ". Msg: " + errorBlock.getErrorMessages()
-              + ". Stats: " + stats);
+              + ". Msg: " + errorBlock.getErrorMessages());
         } else {
           LOGGER.debug("({}): Completed {}", operatorChain, stats);
         }
@@ -211,7 +212,10 @@ public class OpChainSchedulerService {
 
       @Override
       public void onFailure(Throwable t) {
-        String logMsg = "Failed to execute operator chain: " + t.getMessage();
+        // Only an op chain that ended with an error block has stats here.
+        MultiStageQueryStats stats = statsRef.get();
+        String logMsg =
+            "Failed to execute operator chain: " + t.getMessage() + (stats != 
null ? ". Stats: " + stats : "");
         _metrics.onOpChainFinished(rootOperator);
         switch (QueryErrorCode.fromThrowable(t, QueryErrorCode.UNKNOWN)) {
           case UNKNOWN:
diff --git 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/service/dispatch/QueryDispatcher.java
 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/service/dispatch/QueryDispatcher.java
index bc4d2d7289b..3a50512bd3e 100644
--- 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/service/dispatch/QueryDispatcher.java
+++ 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/service/dispatch/QueryDispatcher.java
@@ -141,6 +141,9 @@ public class QueryDispatcher implements 
PinotClusterConfigChangeListener {
   private final int _dispatchMaxInboundMessageSizeBytes;
   // maps broker-generated query id to the set of servers that the query was 
dispatched to
   private final Map<Long, Set<QueryServerInstance>> _serversByQuery;
+  /// Maps broker-generated query id to the session of a stream-mode query, so 
that [#cancel(long)] can mark it. Set
+  /// together with [#_serversByQuery].
+  private final Map<Long, StreamingQuerySession> _streamSessionsByQuery;
   private final FailureDetector _failureDetector;
   private final Duration _cancelTimeout;
   /// Cluster-level default for stream-stats mode. Used as the fallback in 
[#submitAndReduce] when the query
@@ -214,8 +217,10 @@ public class QueryDispatcher implements 
PinotClusterConfigChangeListener {
 
     if (enableCancellation) {
       _serversByQuery = new ConcurrentHashMap<>();
+      _streamSessionsByQuery = new ConcurrentHashMap<>();
     } else {
       _serversByQuery = null;
+      _streamSessionsByQuery = null;
     }
   }
 
@@ -380,6 +385,7 @@ public class QueryDispatcher implements 
PinotClusterConfigChangeListener {
       }
       if (isQueryCancellationEnabled()) {
         _serversByQuery.remove(requestId);
+        _streamSessionsByQuery.remove(requestId);
       }
     }
   }
@@ -442,6 +448,8 @@ public class QueryDispatcher implements 
PinotClusterConfigChangeListener {
     }, deadline, ackQueue);
 
     if (isQueryCancellationEnabled()) {
+      // Session first: a cancel that finds the servers must also find the 
session
+      _streamSessionsByQuery.put(requestId, session);
       _serversByQuery.put(requestId, serversOut);
     }
   }
@@ -498,10 +506,34 @@ public class QueryDispatcher implements 
PinotClusterConfigChangeListener {
       // Stage 0 is broker-local and not tracked by the session; leave its 
entry null.
       stageCoverage.add(expected == 0 ? null : new 
QueryResult.StageCoverage(responded, mergeFailed, missing));
     }
-    return new QueryResult(brokerResult.getResultTable(), 
brokerResult.getProcessingException(), merged,
+    QueryProcessingException processingException =
+        resolveStreamModeError(brokerResult.getProcessingException(), 
session.getFanOutCause());
+    return new QueryResult(brokerResult.getResultTable(), processingException, 
merged,
         brokerResult.getBrokerReduceTimeMs(), stageCoverage, accumulator);
   }
 
+  /// Returns the error to report for a stream-mode query that failed with 
`error`.
+  ///
+  /// In stream mode the broker cancels every opchain as soon as one of them 
fails (see
+  /// [StreamingQuerySession#recordOpChainComplete]). The servers then end 
their opchains with `QUERY_CANCELLATION`
+  /// ("Cancelled on: <server>"), and these errors race the real error through 
the mailboxes. When the real error waits
+  /// behind a blocking operator, for example a hash join that still builds 
from its other input, a cancellation error
+  /// can reach stage 0 first. That cancellation only hides the failure that 
caused it, so this method returns that
+  /// failure instead, with the message of the server, which names where it 
occurred. It keeps `error` when the cause
+  /// is itself a cancellation, or when the server did not send an error code 
(servers older than
+  /// `OpChainComplete.error_code`).
+  @VisibleForTesting
+  @Nullable
+  static QueryProcessingException resolveStreamModeError(@Nullable 
QueryProcessingException error,
+      @Nullable StreamingQuerySession.OpChainFailure fanOutCause) {
+    int cancellation = QueryErrorCode.QUERY_CANCELLATION.getId();
+    if (error == null || error.getErrorCode() != cancellation || fanOutCause 
== null || fanOutCause.errorCode() <= 0
+        || fanOutCause.errorCode() == cancellation) {
+      return error;
+    }
+    return new QueryProcessingException(fanOutCause.errorCode(), 
fanOutCause.errorMessage());
+  }
+
   /// Tries to recover from an exception thrown during legacy (non-streaming) 
query dispatching.
   ///
   /// [QueryException] and [TimeoutException] are handled by returning a 
[QueryResult] with the error code and empty
@@ -903,6 +935,12 @@ public class QueryDispatcher implements 
PinotClusterConfigChangeListener {
 
   public boolean cancel(long requestId) {
     if (isQueryCancellationEnabled()) {
+      // Mark a stream-mode query before its opchains see this cancel, so that 
a failure the cancel causes does not
+      // replace the cancellation in the response (see #resolveStreamModeError)
+      StreamingQuerySession session = _streamSessionsByQuery.remove(requestId);
+      if (session != null) {
+        session.markCancelStarted();
+      }
       return cancel(requestId, _serversByQuery.remove(requestId));
     } else {
       return false;
diff --git 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/service/dispatch/streaming/StreamingQuerySession.java
 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/service/dispatch/streaming/StreamingQuerySession.java
index a7741d7b146..93bccd5a897 100644
--- 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/service/dispatch/streaming/StreamingQuerySession.java
+++ 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/service/dispatch/streaming/StreamingQuerySession.java
@@ -85,6 +85,16 @@ public class StreamingQuerySession {
   /// cancel idempotently.
   private boolean _peerErrorObserved = false;
 
+  /// True once the broker has started to cancel the query: through 
[#fanOutCancel()], or through
+  /// [#markCancelStarted()] for a cancel that goes another way (a user cancel 
uses the unary cancel RPC). Guarded by
+  /// [#_lock].
+  private boolean _cancelStarted = false;
+
+  /// The opchain failure that triggered the fan-out cancel, or `null` when 
none did: no peer error yet, or a stream
+  /// error or a cancel that the broker started came first. Guarded by 
[#_lock].
+  @Nullable
+  private OpChainFailure _fanOutCause;
+
   /// Set once [#snapshotCoverage()] has been taken (the broker has stopped 
waiting for stats). After this, late
   /// [#recordOpChainComplete] reports are ignored: the broker is about to 
flatten/serialize the snapshot on its
   /// own thread, and merging into the live accumulator would mutate 
[StatMap]s the broker may be reading. The
@@ -164,6 +174,11 @@ public class StreamingQuerySession {
         if (!_peerErrorObserved) {
           _peerErrorObserved = true;
           shouldFanOutCancel = true;
+          // After the broker has started a cancel, a failure can be a side 
effect of that cancel (for example a
+          // mailbox that the cancel closed), not the cause of the query error.
+          if (!_cancelStarted) {
+            _fanOutCause = new OpChainFailure(message.getErrorCode(), 
message.getErrorMsg());
+          }
         }
       }
       if (decodeError != null) {
@@ -281,6 +296,7 @@ public class StreamingQuerySession {
     Set<StreamingServerHandle> snapshot;
     _lock.lock();
     try {
+      _cancelStarted = true;
       snapshot = new LinkedHashSet<>(_openStreams);
     } finally {
       _lock.unlock();
@@ -300,6 +316,29 @@ public class StreamingQuerySession {
     }
   }
 
+  /// Records that the broker has started to cancel the query outside this 
session, for example a user cancel, which
+  /// uses the unary cancel RPC. After this, no opchain failure becomes the 
fan-out cause (see [#getFanOutCause()]).
+  public void markCancelStarted() {
+    _lock.lock();
+    try {
+      _cancelStarted = true;
+    } finally {
+      _lock.unlock();
+    }
+  }
+
+  /// Returns the opchain failure that triggered the fan-out cancel, or `null` 
when none did: no peer error yet, or a
+  /// stream error or a cancel that the broker started came first.
+  @Nullable
+  public OpChainFailure getFanOutCause() {
+    _lock.lock();
+    try {
+      return _fanOutCause;
+    } finally {
+      _lock.unlock();
+    }
+  }
+
   /// Blocks the calling thread until either every expected opchain has 
reported, or the timeout fires.
   ///
   /// Returns `true` when all opchains reported before the timeout (early 
completion is the common case in
@@ -333,6 +372,14 @@ public class StreamingQuerySession {
     }
   }
 
+  /// A failure that an opchain reported in [Worker.OpChainComplete].
+  ///
+  /// @param errorCode `QueryErrorCode` id of the failure, or 0 when the 
server did not send one (servers older than
+  ///                  `OpChainComplete.error_code`)
+  /// @param errorMessage the message of the failure, which names the server 
where it occurred
+  public record OpChainFailure(int errorCode, String errorMessage) {
+  }
+
   /// Snapshot of the accumulator and per-stage counters at a point in time.
   public static final class Coverage {
     private final Map<Integer, Integer> _respondedByStage;
diff --git 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/service/server/QueryServer.java
 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/service/server/QueryServer.java
index 863c998dce5..de846fbc9b9 100644
--- 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/service/server/QueryServer.java
+++ 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/service/server/QueryServer.java
@@ -69,6 +69,7 @@ import 
org.apache.pinot.query.runtime.plan.OpChainExecutionContext;
 import org.apache.pinot.spi.accounting.ThreadAccountant;
 import org.apache.pinot.spi.accounting.ThreadAccountantUtils;
 import org.apache.pinot.spi.env.PinotConfiguration;
+import org.apache.pinot.spi.exception.QueryErrorCode;
 import org.apache.pinot.spi.executor.ExecutorServiceUtils;
 import org.apache.pinot.spi.executor.MetricsExecutor;
 import org.apache.pinot.spi.query.QueryExecutionContext;
@@ -702,7 +703,10 @@ public class QueryServer extends 
PinotQueryWorkerGrpc.PinotQueryWorkerImplBase {
           .setWorkerId(opChainId.getVirtualServerId())
           .setSuccess(error == null);
       if (error != null) {
-        builder.setErrorMsg(error.getMessage() == null ? 
error.getClass().getSimpleName() : error.getMessage());
+        // The broker can report this error to the client in place of the 
cancellation errors that its fan-out cancel
+        // causes (see QueryDispatcher#resolveStreamModeError).
+        builder.setErrorMsg(error.getMessage() == null ? 
error.getClass().getSimpleName() : error.getMessage())
+            .setErrorCode(QueryErrorCode.fromThrowable(error, 
QueryErrorCode.UNKNOWN).getId());
       }
       // Claim any stashed pipeline-breaker root for this stage (remove() so 
the stash self-cleans, even on the
       // leaf-error path below where it is unused). The PB always completed 
before this leaf opchain (see
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 7a1f6306f52..7716e5a83a7 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
@@ -59,6 +59,7 @@ import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 import static org.testng.Assert.assertEquals;
 import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNotNull;
 import static org.testng.Assert.assertSame;
 import static org.testng.Assert.assertTrue;
 
@@ -393,6 +394,37 @@ public class OpChainSchedulerServiceTest {
     assertTrue(seenError.get() != null, "expected error to be propagated to 
listener");
   }
 
+  /// An op chain that ends with an error block fails with the error code of 
that block and hands its stats to the
+  /// listener. The error message tells where the error started and leaves the 
stats out, because in stream-stats mode
+  /// the broker can show it to the client.
+  @Test
+  public void shouldFireCompletionListenerWithErrorBlockError()
+      throws InterruptedException {
+    CountDownLatch completed = new CountDownLatch(1);
+    Mockito.when(_operatorA.nextBlock()).thenReturn(
+        new ErrorMseBlock(3, 1, "Server_1", 
Map.of(QueryErrorCode.SERVER_RESOURCE_LIMIT_EXCEEDED, "too many groups")));
+    Mockito.doAnswer(inv -> 
MultiStageQueryStats.emptyStats(0)).when(_operatorA).calculateStats();
+
+    OpChainSchedulerService schedulerService = new 
OpChainSchedulerService(_executor);
+    AtomicReference<Throwable> seenError = new AtomicReference<>();
+    AtomicReference<MultiStageQueryStats> seenStats = new AtomicReference<>();
+    schedulerService.registerCompletionListener(123L, (id, root, stats, ctx, 
error) -> {
+      seenError.set(error);
+      seenStats.set(stats);
+      completed.countDown();
+    });
+    try (QueryThreadContext ignore = QueryThreadContext.openForMseTest()) {
+      schedulerService.register(getChain(_operatorA));
+    }
+
+    assertTrue(completed.await(10, TimeUnit.SECONDS), "expected completion 
listener to fire on error");
+    assertEquals(QueryErrorCode.fromThrowable(seenError.get(), 
QueryErrorCode.UNKNOWN),
+        QueryErrorCode.SERVER_RESOURCE_LIMIT_EXCEEDED);
+    assertEquals(seenError.get().getMessage(),
+        "Error block from stage 3 worker 1 on Server_1. Msg: 
{SERVER_RESOURCE_LIMIT_EXCEEDED=too many groups}");
+    assertNotNull(seenStats.get());
+  }
+
   @Test
   public void shouldNotFireCompletionListenerAfterUnregister()
       throws InterruptedException {
diff --git 
a/pinot-query-runtime/src/test/java/org/apache/pinot/query/service/dispatch/QueryDispatcherTest.java
 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/service/dispatch/QueryDispatcherTest.java
index 384efb83279..5b4251d83fc 100644
--- 
a/pinot-query-runtime/src/test/java/org/apache/pinot/query/service/dispatch/QueryDispatcherTest.java
+++ 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/service/dispatch/QueryDispatcherTest.java
@@ -35,6 +35,7 @@ import org.apache.helix.model.InstanceConfig;
 import org.apache.pinot.common.failuredetector.FailureDetector;
 import org.apache.pinot.common.metrics.BrokerMetrics;
 import org.apache.pinot.common.proto.Worker;
+import org.apache.pinot.common.response.broker.QueryProcessingException;
 import org.apache.pinot.core.transport.ServerInstance;
 import 
org.apache.pinot.core.transport.server.routing.stats.ServerRoutingStatsManager;
 import org.apache.pinot.query.QueryEnvironment;
@@ -45,9 +46,12 @@ import 
org.apache.pinot.query.planner.physical.DispatchablePlanFragment;
 import org.apache.pinot.query.planner.physical.DispatchableSubPlan;
 import org.apache.pinot.query.routing.QueryServerInstance;
 import org.apache.pinot.query.runtime.QueryRunner;
+import org.apache.pinot.query.service.dispatch.streaming.StreamingQuerySession;
+import 
org.apache.pinot.query.service.dispatch.streaming.StreamingQuerySession.OpChainFailure;
 import org.apache.pinot.query.service.server.QueryServer;
 import org.apache.pinot.query.testutils.QueryTestUtils;
 import org.apache.pinot.spi.env.PinotConfiguration;
+import org.apache.pinot.spi.exception.QueryErrorCode;
 import org.apache.pinot.spi.metrics.PinotMetricUtils;
 import org.apache.pinot.spi.metrics.PinotMetricsRegistry;
 import org.apache.pinot.spi.query.QueryThreadContext;
@@ -59,8 +63,15 @@ import org.mockito.Mockito;
 import org.testng.Assert;
 import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
+import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
 
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertNull;
+import static org.testng.Assert.assertSame;
+import static org.testng.Assert.assertTrue;
+
 
 public class QueryDispatcherTest extends QueryTestSet {
   private static final AtomicLong REQUEST_ID_GEN = new AtomicLong();
@@ -511,4 +522,71 @@ public class QueryDispatcherTest extends QueryTestSet {
 
     statsManager.shutDown();
   }
+
+  @DataProvider
+  public Object[][] streamModeErrors() {
+    QueryProcessingException cancelled = new 
QueryProcessingException(QueryErrorCode.QUERY_CANCELLATION,
+        "Received 1 error from stage 1 on Server_2: Cancelled on: Server_2");
+    QueryProcessingException timedOut =
+        new QueryProcessingException(QueryErrorCode.EXECUTION_TIMEOUT, "Timed 
out on Server_2");
+    int resourceLimit = QueryErrorCode.SERVER_RESOURCE_LIMIT_EXCEEDED.getId();
+    OpChainFailure failure = new OpChainFailure(resourceLimit,
+        "Error block from stage 3 worker 1 on Server_1. Msg: 
{SERVER_RESOURCE_LIMIT_EXCEEDED=too many groups}");
+    QueryProcessingException reported = new 
QueryProcessingException(resourceLimit, failure.errorMessage());
+    return new Object[][]{
+        // The cancellation hides the failure that caused it.
+        {cancelled, failure, reported},
+        // An error that is not a cancellation reached stage 0 first, so it is 
real.
+        {timedOut, failure, timedOut},
+        // Nothing to report: no failure caused the cancel, the cause is a 
cancellation itself, or a server older than
+        // OpChainComplete.error_code sent it.
+        {cancelled, null, cancelled},
+        {cancelled, new 
OpChainFailure(QueryErrorCode.QUERY_CANCELLATION.getId(), "Cancelled on: 
Server_1"), cancelled},
+        {cancelled, new OpChainFailure(0, "too many groups"), cancelled}
+    };
+  }
+
+  /// In stream mode the broker's own fan-out cancel can hide the failure that 
triggered it. The broker reports that
+  /// failure instead, when it is known.
+  @Test(dataProvider = "streamModeErrors")
+  public void testResolveStreamModeError(QueryProcessingException error, 
OpChainFailure fanOutCause,
+      QueryProcessingException expected) {
+    QueryProcessingException resolved = 
QueryDispatcher.resolveStreamModeError(error, fanOutCause);
+    if (expected == error) {
+      assertSame(resolved, error);
+    } else {
+      assertNotNull(resolved);
+      assertEquals(resolved.getErrorCode(), expected.getErrorCode());
+      assertEquals(resolved.getMessage(), expected.getMessage());
+    }
+  }
+
+  @Test
+  public void testResolveStreamModeErrorWithoutError() {
+    assertNull(QueryDispatcher.resolveStreamModeError(null,
+        new OpChainFailure(QueryErrorCode.QUERY_EXECUTION.getId(), "boom")));
+  }
+
+  /// A user cancel of a stream-mode query goes over the unary cancel RPC, 
outside the session. The dispatcher still
+  /// marks the session, so that a failure the cancel causes does not replace 
the cancellation in the response.
+  @Test
+  public void testCancelMarksStreamSession()
+      throws Exception {
+    DispatchableSubPlan plan = _queryEnvironment.planQuery("SELECT * FROM a");
+    long requestId = REQUEST_ID_GEN.getAndIncrement();
+    StreamingQuerySession session = new StreamingQuerySession(requestId, 100);
+    try (QueryThreadContext ignore = QueryThreadContext.openForMseTest()) {
+      _queryDispatcher.submitWithStream(requestId, plan, 10_000L, new 
HashSet<>(), Map.of(), session);
+    }
+
+    assertTrue(_queryDispatcher.cancel(requestId));
+    // This failure also fans out a cancel, which closes the streams that the 
submit opened
+    session.recordOpChainComplete(Worker.OpChainComplete.newBuilder()
+        .setStageId(1)
+        .setSuccess(false)
+        .setErrorCode(QueryErrorCode.QUERY_EXECUTION.getId())
+        .setErrorMsg("Mailbox closed")
+        .build());
+    assertNull(session.getFanOutCause());
+  }
 }
diff --git 
a/pinot-query-runtime/src/test/java/org/apache/pinot/query/service/dispatch/streaming/StreamingQuerySessionTest.java
 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/service/dispatch/streaming/StreamingQuerySessionTest.java
index 0ccabd799a1..812dd37fdfb 100644
--- 
a/pinot-query-runtime/src/test/java/org/apache/pinot/query/service/dispatch/streaming/StreamingQuerySessionTest.java
+++ 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/service/dispatch/streaming/StreamingQuerySessionTest.java
@@ -31,6 +31,7 @@ import org.apache.pinot.common.datatable.StatMap;
 import org.apache.pinot.common.proto.Worker;
 import org.apache.pinot.query.runtime.operator.AggregateOperator;
 import org.apache.pinot.query.runtime.operator.MultiStageOperator;
+import org.apache.pinot.spi.exception.QueryErrorCode;
 import org.testng.Assert;
 import org.testng.annotations.Test;
 
@@ -146,14 +147,77 @@ public class StreamingQuerySessionTest {
 
     // Server B reports an error; should fan-out cancel to A and C (and B 
itself, since fan-out walks all open
     // streams — they're best-effort anyway).
-    session.recordOpChainComplete(buildErrorOpChainComplete(0, 1, "boom"));
+    session.recordOpChainComplete(buildErrorOpChainComplete(0, 1, 
QueryErrorCode.QUERY_EXECUTION, "boom"));
     Assert.assertEquals(cancelCalls.get(), 3);
 
     // A second error does not re-fire fan-out (idempotent).
-    session.recordOpChainComplete(buildErrorOpChainComplete(0, 2, "boom2"));
+    session.recordOpChainComplete(buildErrorOpChainComplete(0, 2, 
QueryErrorCode.QUERY_EXECUTION, "boom2"));
     Assert.assertEquals(cancelCalls.get(), 3);
   }
 
+  /// The session keeps the opchain failure that triggered the fan-out cancel. 
Later failures, usually the
+  /// cancellations that the fan-out caused, do not replace it.
+  @Test
+  public void testFanOutCauseIsTheFailureThatTriggeredTheCancel()
+      throws IOException {
+    StreamingQuerySession session = new StreamingQuerySession(1L, 3);
+    session.recordOpChainComplete(buildOpChainComplete(1, 0, 1, 5));
+    Assert.assertNull(session.getFanOutCause(), "a successful report must not 
set a cause");
+
+    session.recordOpChainComplete(
+        buildErrorOpChainComplete(2, 1, 
QueryErrorCode.SERVER_RESOURCE_LIMIT_EXCEEDED, "too many groups"));
+    session.recordOpChainComplete(
+        buildErrorOpChainComplete(1, 2, QueryErrorCode.QUERY_CANCELLATION, 
"Cancelled on: Server_1"));
+
+    Assert.assertEquals(session.getFanOutCause(), new 
StreamingQuerySession.OpChainFailure(
+        QueryErrorCode.SERVER_RESOURCE_LIMIT_EXCEEDED.getId(), "too many 
groups"));
+  }
+
+  /// A server older than `OpChainComplete.error_code` sends no error code, 
and the cause keeps 0 for it.
+  @Test
+  public void testFanOutCauseWithoutErrorCode() {
+    StreamingQuerySession session = new StreamingQuerySession(1L, 1);
+    session.recordOpChainComplete(Worker.OpChainComplete.newBuilder()
+        .setStageId(2)
+        .setWorkerId(0)
+        .setSuccess(false)
+        .setErrorMsg("boom")
+        .build());
+
+    Assert.assertEquals(session.getFanOutCause(), new 
StreamingQuerySession.OpChainFailure(0, "boom"));
+  }
+
+  /// When a stream error triggers the fan-out cancel, no opchain failure 
caused it.
+  @Test
+  public void testNoFanOutCauseWhenStreamErrorComesFirst() {
+    StreamingQuerySession session = new StreamingQuerySession(1L, 2);
+    StreamingServerHandle dead = req -> {
+    };
+    session.registerStream(dead);
+    session.recordStreamError(dead, new RuntimeException("transport"), 1);
+    session.recordOpChainComplete(buildErrorOpChainComplete(0, 1, 
QueryErrorCode.QUERY_EXECUTION, "boom"));
+
+    Assert.assertNull(session.getFanOutCause());
+  }
+
+  /// After the broker has started a cancel itself, a failure can be a side 
effect of that cancel, so it does not
+  /// become the cause. The broker cancels through the session after a reducer 
error, and through the unary cancel RPC
+  /// for a user cancel.
+  @Test
+  public void testNoFanOutCauseAfterBrokerCancel() {
+    StreamingQuerySession fannedOut = new StreamingQuerySession(1L, 1);
+    fannedOut.fanOutCancel();
+    fannedOut.recordOpChainComplete(
+        buildErrorOpChainComplete(0, 1, QueryErrorCode.QUERY_EXECUTION, 
"Mailbox closed"));
+    Assert.assertNull(fannedOut.getFanOutCause());
+
+    StreamingQuerySession userCancelled = new StreamingQuerySession(2L, 1);
+    userCancelled.markCancelStarted();
+    userCancelled.recordOpChainComplete(
+        buildErrorOpChainComplete(0, 1, QueryErrorCode.QUERY_EXECUTION, 
"Mailbox closed"));
+    Assert.assertNull(userCancelled.getFanOutCause());
+  }
+
   /// Stream onError (transport failure) drains the latch and triggers fan-out 
cancel; the dispatcher's
   /// remainingExpected variant lets it account for opchains that the dead 
server still owed.
   @Test
@@ -345,12 +409,14 @@ public class StreamingQuerySessionTest {
         .build();
   }
 
-  private static Worker.OpChainComplete buildErrorOpChainComplete(int stageId, 
int workerId, String errorMsg) {
+  private static Worker.OpChainComplete buildErrorOpChainComplete(int stageId, 
int workerId,
+      QueryErrorCode errorCode, String errorMsg) {
     return Worker.OpChainComplete.newBuilder()
         .setStageId(stageId)
         .setWorkerId(workerId)
         .setSuccess(false)
         .setErrorMsg(errorMsg)
+        .setErrorCode(errorCode.getId())
         .build();
   }
 


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

Reply via email to