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 ca1e15c8ee8 Count only table-serving brokers in the MSE query 
throttler and run oversize queries alone (#20099)
ca1e15c8ee8 is described below

commit ca1e15c8ee8c3326083992e7f7fe29a5b96682d5
Author: Yash Mayya <[email protected]>
AuthorDate: Tue Nov 17 22:26:29 2026 +0530

    Count only table-serving brokers in the MSE query throttler and run 
oversize queries alone (#20099)
---
 .../MultiStageBrokerRequestHandler.java            |  4 +-
 .../requesthandler/MultiStageQueryThrottler.java   | 47 +++++++++++-----------
 .../MultiStageBrokerRequestHandlerTest.java        | 46 +++++++++++++++++++++
 .../MultiStageQueryThrottlerTest.java              | 37 ++++++++++++++---
 4 files changed, 103 insertions(+), 31 deletions(-)

diff --git 
a/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/MultiStageBrokerRequestHandler.java
 
b/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/MultiStageBrokerRequestHandler.java
index 577e7a9baeb..4486b199bd9 100644
--- 
a/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/MultiStageBrokerRequestHandler.java
+++ 
b/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/MultiStageBrokerRequestHandler.java
@@ -926,7 +926,9 @@ public class MultiStageBrokerRequestHandler extends 
BaseBrokerRequestHandler {
     // Short-circuit: if all leaf stages are empty (all segments pruned or 
table has no data),
     // run only the broker reduce stage locally. No server dispatch is 
attempted.
     boolean allLeafStagesEmpty = dispatchableSubPlan.isAllLeafStagesEmpty();
-    int estimatedNumQueryThreads = 
getEstimatedNumQueryThreads(dispatchableSubPlan);
+    // A query estimated above the throttler limit takes the whole limit, so 
it runs alone instead of never
+    int estimatedNumQueryThreads =
+        Math.min(getEstimatedNumQueryThreads(dispatchableSubPlan), 
_queryThrottler.getMaxPermits());
     try {
       // It's fine to block in this thread because we use a separate thread 
pool from the main Jersey server to process
       // these requests.
diff --git 
a/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/MultiStageQueryThrottler.java
 
b/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/MultiStageQueryThrottler.java
index ab7a2ac4ae9..78de3e39263 100644
--- 
a/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/MultiStageQueryThrottler.java
+++ 
b/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/MultiStageQueryThrottler.java
@@ -27,9 +27,11 @@ import org.apache.helix.HelixAdmin;
 import org.apache.helix.HelixConstants;
 import org.apache.helix.HelixManager;
 import org.apache.helix.model.HelixConfigScope;
+import org.apache.helix.model.IdealState;
 import org.apache.helix.model.builder.HelixConfigScopeBuilder;
 import org.apache.pinot.broker.broker.helix.ClusterChangeHandler;
 import org.apache.pinot.common.concurrency.AdjustableSemaphore;
+import org.apache.pinot.common.utils.helix.HelixHelper;
 import org.apache.pinot.spi.env.PinotConfiguration;
 import org.apache.pinot.spi.query.QueryThreadExceedStrategy;
 import org.apache.pinot.spi.utils.CommonConstants;
@@ -93,9 +95,7 @@ public class MultiStageQueryThrottler implements 
ClusterChangeHandler {
     _maxServerQueryThreads = calculateMaxServerQueryThreads();
 
     List<String> clusterInstances = 
_helixAdmin.getInstancesInCluster(_helixManager.getClusterName());
-    _numBrokers = Math.max(1, (int) clusterInstances.stream()
-        .filter(instance -> 
instance.startsWith(CommonConstants.Helix.PREFIX_OF_BROKER_INSTANCE))
-        .count());
+    _numBrokers = countBrokers();
     _numServers = Math.max(1, (int) clusterInstances.stream()
         .filter(instance -> 
instance.startsWith(CommonConstants.Helix.PREFIX_OF_SERVER_INSTANCE))
         .count());
@@ -116,9 +116,6 @@ public class MultiStageQueryThrottler implements 
ClusterChangeHandler {
   /// @param unit the time unit of the timeout argument
   ///
   /// @throws InterruptedException if the current thread is interrupted
-  /// @throws RuntimeException if the query can never be dispatched due to the 
number of estimated query server threads
-  /// being greater than the maximum number of server query threads calculated 
on the basis of
-  /// _CONFIG_OF_MULTI_STAGE_ENGINE_MAX_SERVER_QUERY_THREADS \* numServers / 
numBrokers_
   public boolean tryAcquire(int numQueryThreads, long timeout, TimeUnit unit)
       throws InterruptedException {
     if (_maxServerQueryThreads <= 0) {
@@ -126,21 +123,12 @@ public class MultiStageQueryThrottler implements 
ClusterChangeHandler {
       return true;
     }
 
-    if (numQueryThreads > _semaphore.getTotalPermits() && _exceedStrategy != 
QueryThreadExceedStrategy.LOG) {
-      throw new RuntimeException(
-          String.format("Can't dispatch query because the estimated number of 
server threads for this query is too "
-              + "large for the configured value of '%s' or '%s'. 
estimatedThreads=%d configuredLimit=%d",
-                  
CommonConstants.Helix.CONFIG_OF_MULTI_STAGE_ENGINE_MAX_SERVER_QUERY_THREADS,
-                  
CommonConstants.Broker.CONFIG_OF_MSE_MAX_SERVER_QUERY_THREADS,
-                  numQueryThreads, _semaphore.getTotalPermits()));
-    }
-
     if (_exceedStrategy == QueryThreadExceedStrategy.LOG) {
-      boolean wouldThrottle = _currentQueryServerThreads.get() + 
numQueryThreads > _maxServerQueryThreads;
+      boolean wouldThrottle = _currentQueryServerThreads.get() + 
numQueryThreads > _semaphore.getTotalPermits();
       if (wouldThrottle) {
         LOGGER.warn(
             "Exceed strategy LOG: Query would have been throttled. 
estimatedThreads: {} availableThreads: {}",
-            numQueryThreads, _maxServerQueryThreads - 
_currentQueryServerThreads.get());
+            numQueryThreads, _semaphore.getTotalPermits() - 
_currentQueryServerThreads.get());
       }
       _currentQueryServerThreads.addAndGet(numQueryThreads);
       return true;
@@ -172,10 +160,12 @@ public class MultiStageQueryThrottler implements 
ClusterChangeHandler {
         "MultiStageQuerySemaphore can only handle EXTERNAL_VIEW and 
CLUSTER_CONFIG changes");
 
     if (changeType == HelixConstants.ChangeType.EXTERNAL_VIEW) {
+      if (_maxServerQueryThreads <= 0) {
+        // Limiting is disabled, and enabling it requires a restart
+        return;
+      }
       List<String> clusterInstances = 
_helixAdmin.getInstancesInCluster(_helixManager.getClusterName());
-      int numBrokers = Math.max(1, (int) clusterInstances.stream()
-          .filter(instance -> 
instance.startsWith(CommonConstants.Helix.PREFIX_OF_BROKER_INSTANCE))
-          .count());
+      int numBrokers = countBrokers();
       int numServers = Math.max(1, (int) clusterInstances.stream()
           .filter(instance -> 
instance.startsWith(CommonConstants.Helix.PREFIX_OF_SERVER_INSTANCE))
           .count());
@@ -183,10 +173,7 @@ public class MultiStageQueryThrottler implements 
ClusterChangeHandler {
       if (numBrokers != _numBrokers || numServers != _numServers) {
         _numBrokers = numBrokers;
         _numServers = numServers;
-        if (_maxServerQueryThreads > 0) {
-          int semaphoreLimit = calculateSemaphoreLimit();
-          _semaphore.setPermits(semaphoreLimit);
-        }
+        _semaphore.setPermits(calculateSemaphoreLimit());
       }
     } else {
       int newMaxServerQueryThreads = calculateMaxServerQueryThreads();
@@ -216,6 +203,11 @@ public class MultiStageQueryThrottler implements 
ClusterChangeHandler {
     return _currentQueryServerThreads.get();
   }
 
+  /// Most query server threads a single query can acquire, or 
[Integer#MAX_VALUE] if limiting is disabled.
+  int getMaxPermits() {
+    return _maxServerQueryThreads > 0 ? _semaphore.getTotalPermits() : 
Integer.MAX_VALUE;
+  }
+
   @VisibleForTesting
   int availablePermits() {
     return _semaphore.availablePermits();
@@ -232,6 +224,13 @@ public class MultiStageQueryThrottler implements 
ClusterChangeHandler {
             
CommonConstants.Helix.DEFAULT_MULTI_STAGE_ENGINE_MAX_SERVER_QUERY_THREADS));
   }
 
+  /// Counts the brokers that serve a table. A broker that serves no table 
gets no queries, so it gets no share of the
+  /// server threads.
+  private int countBrokers() {
+    IdealState brokerResource = HelixHelper.getBrokerIdealStates(_helixAdmin, 
_helixManager.getClusterName());
+    return brokerResource != null ? Math.max(1, 
HelixHelper.getAllInstancesForResource(brokerResource).size()) : 1;
+  }
+
   private int calculateSemaphoreLimit() {
     int semaphoreLimit = Math.max(1, _maxServerQueryThreads * _numServers / 
_numBrokers);
     LOGGER.info("Calculating estimated server query threads limit: {} for 
maxServerQueryThreads: {}, "
diff --git 
a/pinot-broker/src/test/java/org/apache/pinot/broker/requesthandler/MultiStageBrokerRequestHandlerTest.java
 
b/pinot-broker/src/test/java/org/apache/pinot/broker/requesthandler/MultiStageBrokerRequestHandlerTest.java
index a7cf7bc1699..38fca87845f 100644
--- 
a/pinot-broker/src/test/java/org/apache/pinot/broker/requesthandler/MultiStageBrokerRequestHandlerTest.java
+++ 
b/pinot-broker/src/test/java/org/apache/pinot/broker/requesthandler/MultiStageBrokerRequestHandlerTest.java
@@ -84,6 +84,7 @@ import org.testng.Assert;
 import org.testng.annotations.Test;
 
 import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.anyLong;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.ArgumentMatchers.eq;
@@ -508,6 +509,51 @@ public class MultiStageBrokerRequestHandlerTest extends 
QueryEnvironmentTestBase
     };
   }
 
+  @Test
+  public void testThrottlerAcquiresAndReleasesCappedEstimate()
+      throws Exception {
+    MultiStageQueryThrottler throttler = mock(MultiStageQueryThrottler.class);
+    when(throttler.getMaxPermits()).thenReturn(1);
+    when(throttler.tryAcquire(anyInt(), anyLong(), any())).thenReturn(true);
+    // The table has no segments, so the broker runs the query without 
dispatching it to the server
+    MockRoutingManagerFactory factory = new MockRoutingManagerFactory(1);
+    factory.registerTable(TABLE_SCHEMAS.get("c_OFFLINE"), "c_OFFLINE");
+    factory.registerEmptyTable("c_OFFLINE");
+    RoutingManager routingManager = factory.buildRoutingManager(null);
+    WorkerManager workerManager =
+        new WorkerManager("Broker_localhost", "localhost", 
NetUtils.findOpenPort(), routingManager);
+    PinotConfiguration config = new PinotConfiguration();
+    config.setProperty(MultiStageQueryRunner.KEY_OF_QUERY_RUNNER_HOSTNAME, 
"localhost");
+    config.setProperty(MultiStageQueryRunner.KEY_OF_QUERY_RUNNER_PORT, 
Integer.toString(NetUtils.findOpenPort()));
+    BrokerQueryEventListenerFactory.init(config);
+    BrokerMetrics.register(mock(BrokerMetrics.class));
+    QueryQuotaManager queryQuotaManager = mock(QueryQuotaManager.class);
+    when(queryQuotaManager.acquire(anyString())).thenReturn(true);
+    when(queryQuotaManager.acquireDatabase(anyString())).thenReturn(true);
+    MultiStageBrokerRequestHandler handler = new 
MultiStageBrokerRequestHandler(config, "testBrokerId",
+        new BrokerRequestIdGenerator(), routingManager, new 
AllowAllAccessControlFactory(), queryQuotaManager,
+        factory.buildTableCache(), throttler, mock(FailureDetector.class), 
ThreadAccountantUtils.getNoOpAccountant(),
+        null, workerManager, workerManager) {
+      @Override
+      protected int getEstimatedNumQueryThreads(DispatchableSubPlan 
dispatchableSubPlan) {
+        return 10;
+      }
+    };
+
+    BrokerResponse response = handler.handleRequest("SELECT COUNT(*) FROM c");
+    assertEquals(response.getExceptions().size(), 0, 
response.getExceptions().toString());
+    // The estimate of 10 threads is capped to the throttler limit of 1
+    verify(throttler).tryAcquire(eq(1), anyLong(), any());
+    verify(throttler).release(1);
+
+    // With limiting disabled, the estimate is not capped
+    when(throttler.getMaxPermits()).thenReturn(Integer.MAX_VALUE);
+    response = handler.handleRequest("SELECT COUNT(*) FROM c");
+    assertEquals(response.getExceptions().size(), 0, 
response.getExceptions().toString());
+    verify(throttler).tryAcquire(eq(10), anyLong(), any());
+    verify(throttler).release(10);
+  }
+
   /// An access control can return an empty RLS filter list for a table 
without row filters. No predicate is attached
   /// for it, so the response must not report that RLS filters were applied.
   @Test
diff --git 
a/pinot-broker/src/test/java/org/apache/pinot/broker/requesthandler/MultiStageQueryThrottlerTest.java
 
b/pinot-broker/src/test/java/org/apache/pinot/broker/requesthandler/MultiStageQueryThrottlerTest.java
index bedfc080753..d6620e44cc0 100644
--- 
a/pinot-broker/src/test/java/org/apache/pinot/broker/requesthandler/MultiStageQueryThrottlerTest.java
+++ 
b/pinot-broker/src/test/java/org/apache/pinot/broker/requesthandler/MultiStageQueryThrottlerTest.java
@@ -25,6 +25,7 @@ import java.util.concurrent.TimeUnit;
 import org.apache.helix.HelixAdmin;
 import org.apache.helix.HelixConstants;
 import org.apache.helix.HelixManager;
+import org.apache.helix.model.IdealState;
 import org.apache.pinot.spi.env.PinotConfiguration;
 import org.apache.pinot.spi.utils.CommonConstants;
 import org.mockito.Mock;
@@ -58,6 +59,17 @@ public class MultiStageQueryThrottlerTest {
     
).thenReturn(Map.of(CommonConstants.Helix.CONFIG_OF_MULTI_STAGE_ENGINE_MAX_SERVER_QUERY_THREADS,
 "4"));
     when(_helixAdmin.getInstancesInCluster(eq("testCluster"))).thenReturn(
         List.of("Broker_0", "Broker_1", "Server_0", "Server_1"));
+    setBrokersServingTables("Broker_0", "Broker_1");
+  }
+
+  private void setBrokersServingTables(String... brokers) {
+    IdealState brokerResource = new 
IdealState(CommonConstants.Helix.BROKER_RESOURCE_INSTANCE);
+    brokerResource.setRebalanceMode(IdealState.RebalanceMode.CUSTOMIZED);
+    for (String broker : brokers) {
+      brokerResource.setPartitionState("myTable_OFFLINE", broker, "ONLINE");
+    }
+    when(_helixAdmin.getResourceIdealState(eq("testCluster"), 
eq(CommonConstants.Helix.BROKER_RESOURCE_INSTANCE)))
+        .thenReturn(brokerResource);
   }
 
   @AfterMethod
@@ -104,6 +116,7 @@ public class MultiStageQueryThrottlerTest {
     
configMap.put(CommonConstants.Broker.CONFIG_OF_MSE_MAX_SERVER_QUERY_THREADS_EXCEED_STRATEGY,
 "LOG");
     PinotConfiguration config = new PinotConfiguration(configMap);
     _multiStageQueryThrottler = new MultiStageQueryThrottler(config);
+    _multiStageQueryThrottler.init(_helixManager);
 
     Assert.assertTrue(_multiStageQueryThrottler.tryAcquire(1, 100, 
TimeUnit.MILLISECONDS));
     Assert.assertTrue(_multiStageQueryThrottler.tryAcquire(1, 100, 
TimeUnit.MILLISECONDS));
@@ -133,6 +146,7 @@ public class MultiStageQueryThrottlerTest {
     for (int i = 0; i < 100; i++) {
       Assert.assertTrue(_multiStageQueryThrottler.tryAcquire(10, 100, 
TimeUnit.MILLISECONDS));
     }
+    Assert.assertEquals(_multiStageQueryThrottler.getMaxPermits(), 
Integer.MAX_VALUE);
   }
 
   @Test
@@ -148,8 +162,7 @@ public class MultiStageQueryThrottlerTest {
     Assert.assertEquals(_multiStageQueryThrottler.availablePermits(), 0);
 
     // Increase the number of brokers
-    when(_helixAdmin.getInstancesInCluster(eq("testCluster"))).thenReturn(
-        List.of("Broker_0", "Broker_1", "Broker_2", "Broker_3", "Server_0", 
"Server_1"));
+    setBrokersServingTables("Broker_0", "Broker_1", "Broker_2", "Broker_3");
     
_multiStageQueryThrottler.processClusterChange(HelixConstants.ChangeType.EXTERNAL_VIEW);
 
     // Verify that the number of permits on this broker have been reduced to 
account for the new brokers
@@ -176,15 +189,28 @@ public class MultiStageQueryThrottlerTest {
     Assert.assertEquals(_multiStageQueryThrottler.availablePermits(), 0);
 
     // Decrease the number of brokers
-    
when(_helixAdmin.getInstancesInCluster(eq("testCluster"))).thenReturn(List.of("Broker_0",
 "Server_0", "Server_1"));
+    setBrokersServingTables("Broker_0");
     
_multiStageQueryThrottler.processClusterChange(HelixConstants.ChangeType.EXTERNAL_VIEW);
 
     // Ensure that the permits from the removed broker are added to this one.
     Assert.assertEquals(_multiStageQueryThrottler.availablePermits(), 4);
+    Assert.assertEquals(_multiStageQueryThrottler.getMaxPermits(), 8);
     Assert.assertTrue(_multiStageQueryThrottler.tryAcquire(3, 100, 
TimeUnit.MILLISECONDS));
     Assert.assertEquals(_multiStageQueryThrottler.availablePermits(), 1);
   }
 
+  @Test
+  public void testBrokerServingNoTableIsNotCounted() {
+    // Broker_2 serves no table, so it gets no queries
+    when(_helixAdmin.getInstancesInCluster(eq("testCluster"))).thenReturn(
+        List.of("Broker_0", "Broker_1", "Broker_2", "Server_0", "Server_1"));
+    _multiStageQueryThrottler = new MultiStageQueryThrottler(new 
PinotConfiguration());
+    _multiStageQueryThrottler.init(_helixManager);
+
+    // 4 threads per server * 2 servers / 2 brokers
+    Assert.assertEquals(_multiStageQueryThrottler.availablePermits(), 4);
+  }
+
   @Test
   public void testIncreaseNumServers()
       throws Exception {
@@ -405,9 +431,8 @@ public class MultiStageQueryThrottlerTest {
     _multiStageQueryThrottler.init(_helixManager);
 
     Assert.assertEquals(_multiStageQueryThrottler.availablePermits(), 4);
-    // Thrown if the estimated number of query threads is greater than the 
number of available permits to this broker
-    Assert.assertThrows(RuntimeException.class,
-        () -> _multiStageQueryThrottler.tryAcquire(10, 100, 
TimeUnit.MILLISECONDS));
+    // A query estimated above this limit acquires this limit instead of 
failing
+    Assert.assertEquals(_multiStageQueryThrottler.getMaxPermits(), 4);
   }
 
   @Test


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

Reply via email to