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

xiangfu0 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 eec6794fbe0 Parallelize eligible fact scans and fuse adjacent 
broadcast joins in MSE (#20344)
eec6794fbe0 is described below

commit eec6794fbe076bf236eed9930165268488655177
Author: Xiang Fu <[email protected]>
AuthorDate: Tue Nov 24 05:48:05 2026 -0800

    Parallelize eligible fact scans and fuse adjacent broadcast joins in MSE 
(#20344)
    
    * Parallelize eligible fact leaves and fuse adjacent broadcast joins
    
    Split a single-server OFFLINE scan across local workers with 
leafStageWorkersPerServer. Set fuseBroadcastJoins for adjacent random-probe, 
broadcast-build inner joins to skip their intermediate exchange.
    
    * Preserve the join exchange with forced spools and verify offline leaf 
fanout
    
    Keep query and hint fusion opt-ins behind the resolved spool mode. AUTO can 
reject unsafe shared producers, while explicit unguarded spooling keeps the 
original stage boundary.
    
    Exercise the shared broadcast plan against H2 and compare all six fanout 
and fusion combinations on seven real offline segments. Check the leaf workers 
that actually executed, along with the resulting groups, counts, and sums.
---
 .../pinot/calcite/rel/hint/PinotHintOptions.java   |   3 +
 .../rel/rules/PinotJoinExchangeNodeInsertRule.java |  60 +++++++++-
 .../org/apache/pinot/query/QueryEnvironment.java   |   6 +-
 .../apache/pinot/query/context/PlannerContext.java |   5 +
 .../apache/pinot/query/routing/WorkerManager.java  |  62 ++++++++++
 .../pinot/query/BroadcastJoinStageFusionTest.java  | 125 +++++++++++++++++++++
 .../pinot/query/routing/WorkerManagerTest.java     |  42 +++++++
 .../plan/server/ServerPlanRequestUtils.java        |  22 ++++
 .../plan/server/ServerPlanRequestUtilsTest.java    |  41 +++++++
 .../query/runtime/queries/QueryRunnerTest.java     |  57 +++++++++-
 .../src/test/resources/queries/Spool.json          |   5 +
 .../apache/pinot/spi/utils/CommonConstants.java    |   7 ++
 12 files changed, 431 insertions(+), 4 deletions(-)

diff --git 
a/pinot-query-planner/src/main/java/org/apache/pinot/calcite/rel/hint/PinotHintOptions.java
 
b/pinot-query-planner/src/main/java/org/apache/pinot/calcite/rel/hint/PinotHintOptions.java
index 58facc68314..fddc0afcc3c 100644
--- 
a/pinot-query-planner/src/main/java/org/apache/pinot/calcite/rel/hint/PinotHintOptions.java
+++ 
b/pinot-query-planner/src/main/java/org/apache/pinot/calcite/rel/hint/PinotHintOptions.java
@@ -138,6 +138,9 @@ public class PinotHintOptions {
     public static final String LEFT_DISTRIBUTION_TYPE = 
"left_distribution_type";
     public static final String RIGHT_DISTRIBUTION_TYPE = 
"right_distribution_type";
 
+    /// Keep consecutive broadcast inner joins in the same stage when the 
probe rows are already distributed.
+    public static final String FUSE_BROADCAST_JOINS = "fuse_broadcast_joins";
+
     /// Max rows allowed to build the right table hash collection.
     public static final String MAX_ROWS_IN_JOIN = "max_rows_in_join";
 
diff --git 
a/pinot-query-planner/src/main/java/org/apache/pinot/calcite/rel/rules/PinotJoinExchangeNodeInsertRule.java
 
b/pinot-query-planner/src/main/java/org/apache/pinot/calcite/rel/rules/PinotJoinExchangeNodeInsertRule.java
index c9ff53023a0..5ebd2e1ae31 100644
--- 
a/pinot-query-planner/src/main/java/org/apache/pinot/calcite/rel/rules/PinotJoinExchangeNodeInsertRule.java
+++ 
b/pinot-query-planner/src/main/java/org/apache/pinot/calcite/rel/rules/PinotJoinExchangeNodeInsertRule.java
@@ -23,8 +23,10 @@ import com.google.common.base.Preconditions;
 import java.util.List;
 import java.util.Map;
 import javax.annotation.Nullable;
+import org.apache.calcite.plan.Context;
 import org.apache.calcite.plan.RelOptRule;
 import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.RelDistribution.Type;
 import org.apache.calcite.rel.RelDistributions;
 import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.core.Calc;
@@ -35,10 +37,16 @@ import org.apache.calcite.rel.core.JoinRelType;
 import org.apache.calcite.rel.core.Project;
 import org.apache.calcite.rel.core.TableScan;
 import org.apache.calcite.rel.logical.LogicalAsofJoin;
+import org.apache.calcite.rex.RexInputRef;
 import org.apache.calcite.tools.RelBuilderFactory;
 import org.apache.pinot.calcite.rel.hint.PinotHintOptions;
 import org.apache.pinot.calcite.rel.hint.PinotHintStrategyTable;
 import org.apache.pinot.calcite.rel.logical.PinotLogicalExchange;
+import org.apache.pinot.calcite.rel.logical.PinotRelExchangeType;
+import org.apache.pinot.query.context.PlannerContext;
+import org.apache.pinot.query.planner.logical.SpoolMode;
+import org.apache.pinot.spi.exception.QueryException;
+import 
org.apache.pinot.spi.utils.CommonConstants.Broker.Request.QueryOptionKey;
 
 
 /// Special rule for Pinot, this rule is fixed to always insert exchange after 
JOIN node.
@@ -102,7 +110,13 @@ public class PinotJoinExchangeNodeInsertRule extends 
RelOptRule {
       }
       validateDistributionTypes(leftDistributionType, rightDistributionType, 
isReplicatedTableScan(left),
           isReplicatedTableScan(right), joinInfo, join.getJoinType());
-      newLeft = createExchangeForHashJoin(leftDistributionType, 
joinInfo.leftKeys, left, prePartitioned);
+      boolean fuseProbe = join.getJoinType() == JoinRelType.INNER && 
prePartitioned == null
+          && !joinInfo.leftKeys.isEmpty() && joinInfo.isEqui()
+          && leftDistributionType == PinotHintOptions.DistributionType.RANDOM
+          && rightDistributionType == 
PinotHintOptions.DistributionType.BROADCAST
+          && fusionEnabled(call, joinHintOptions) && 
isBroadcastJoinOutput(left);
+      newLeft = fuseProbe ? left
+          : createExchangeForHashJoin(leftDistributionType, joinInfo.leftKeys, 
left, prePartitioned);
       newRight = createExchangeForHashJoin(rightDistributionType, 
joinInfo.rightKeys, right, prePartitioned);
     }
 
@@ -117,6 +131,50 @@ public class PinotJoinExchangeNodeInsertRule extends 
RelOptRule {
     }
   }
 
+  private static boolean fusionEnabled(RelOptRuleCall call, @Nullable 
Map<String, String> hint) {
+    Context context = call.getPlanner().getContext();
+    PlannerContext planner = context != null ? 
context.unwrap(PlannerContext.class) : null;
+    if (planner == null) {
+      return false;
+    }
+    String fuse = hint != null ? 
hint.get(PinotHintOptions.JoinHintOptions.FUSE_BROADCAST_JOINS) : null;
+    if (!Boolean.parseBoolean(fuse != null ? fuse : 
planner.getOptions().get(QueryOptionKey.FUSE_BROADCAST_JOINS))) {
+      return false;
+    }
+    // An unguarded spool can share a build input with another stage that must 
finish before the fused join reads it.
+    // Keep the exchange in ON mode. AUTO checks the finished plan before 
sharing any producer.
+    try {
+      return planner.getSpoolMode() != SpoolMode.ON;
+    } catch (QueryException e) {
+      // Dispatch planning reports an invalid spool option as a query 
validation error.
+      return false;
+    }
+  }
+
+  /// A random probe input already assigns each row to one worker. Since every 
worker receives the entire
+  /// right input of both inner joins, a second random exchange only moves the 
first join's results.
+  /// Restrict the intervening operators to column projections so 
stage-sensitive expressions keep their placement.
+  private static boolean isBroadcastJoinOutput(RelNode input) {
+    while (input instanceof Project project) {
+      if 
(!project.getProjects().stream().allMatch(RexInputRef.class::isInstance)) {
+        return false;
+      }
+      input = PinotRuleUtils.unboxRel(project.getInput());
+    }
+    if (!(input instanceof Join join) || join.getJoinType() != 
JoinRelType.INNER) {
+      return false;
+    }
+    JoinInfo info = join.analyzeCondition();
+    return info.isEqui() && !info.leftKeys.isEmpty() && 
isStreamingExchange(join.getLeft(), Type.RANDOM_DISTRIBUTED)
+        && isStreamingExchange(join.getRight(), Type.BROADCAST_DISTRIBUTED);
+  }
+
+  private static boolean isStreamingExchange(RelNode input, Type distribution) 
{
+    return PinotRuleUtils.unboxRel(input) instanceof PinotLogicalExchange 
exchange
+        && exchange.getDistribution().getType() == distribution && 
exchange.getPrePartitioned() == null
+        && exchange.getExchangeType() == PinotRelExchangeType.STREAMING;
+  }
+
   private static PinotLogicalExchange 
createExchangeForLookupJoin(PinotHintOptions.DistributionType distributionType,
       List<Integer> keys, RelNode child) {
     switch (distributionType) {
diff --git 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/QueryEnvironment.java
 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/QueryEnvironment.java
index c186faa2024..7be40eb7c69 100644
--- 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/QueryEnvironment.java
+++ 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/QueryEnvironment.java
@@ -763,9 +763,13 @@ public class QueryEnvironment {
   ///
   /// @throws QueryException with [QueryErrorCode#QUERY_VALIDATION] if the 
query option is not a valid [SpoolMode].
   public SpoolMode getSpoolMode(Map<String, String> options) {
+    return getSpoolMode(options, _envConfig.defaultSpoolMode());
+  }
+
+  public static SpoolMode getSpoolMode(Map<String, String> options, SpoolMode 
defaultMode) {
     String optionValue = 
options.get(CommonConstants.Broker.Request.QueryOptionKey.USE_SPOOLS);
     if (optionValue == null) {
-      return _envConfig.defaultSpoolMode();
+      return defaultMode;
     }
     try {
       return SpoolMode.fromString(optionValue);
diff --git 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/context/PlannerContext.java
 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/context/PlannerContext.java
index 811ce0040d3..62c5e5ddcf9 100644
--- 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/context/PlannerContext.java
+++ 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/context/PlannerContext.java
@@ -37,6 +37,7 @@ import org.apache.pinot.calcite.rex.SearchSealer;
 import org.apache.pinot.common.utils.config.QueryOptionsUtils;
 import org.apache.pinot.query.QueryEnvironment;
 import org.apache.pinot.query.planner.logical.LogicalPlanner;
+import org.apache.pinot.query.planner.logical.SpoolMode;
 import org.apache.pinot.query.validate.Validator;
 
 
@@ -174,6 +175,10 @@ public class PlannerContext implements AutoCloseable, 
Context {
     return _searchSealer;
   }
 
+  public SpoolMode getSpoolMode() {
+    return QueryEnvironment.getSpoolMode(_options, 
_envConfig.defaultSpoolMode());
+  }
+
   public boolean isUsePhysicalOptimizer() {
     return _physicalPlannerContext != null;
   }
diff --git 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/routing/WorkerManager.java
 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/routing/WorkerManager.java
index 3539df3720c..f4fb49b6362 100644
--- 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/routing/WorkerManager.java
+++ 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/routing/WorkerManager.java
@@ -55,10 +55,13 @@ import org.apache.pinot.core.routing.TableRouteInfo;
 import org.apache.pinot.core.routing.timeboundary.TimeBoundaryInfo;
 import org.apache.pinot.core.transport.ServerInstance;
 import org.apache.pinot.query.planner.PlanFragment;
+import org.apache.pinot.query.planner.logical.RexExpression;
 import org.apache.pinot.query.planner.physical.DispatchablePlanContext;
 import org.apache.pinot.query.planner.physical.DispatchablePlanMetadata;
 import org.apache.pinot.query.planner.plannode.MailboxSendNode;
 import org.apache.pinot.query.planner.plannode.PlanNode;
+import org.apache.pinot.query.planner.plannode.ProjectNode;
+import org.apache.pinot.query.planner.plannode.TableScanNode;
 import org.apache.pinot.spi.config.table.TableType;
 import org.apache.pinot.spi.exception.QueryErrorCode;
 import org.apache.pinot.spi.exception.QueryException;
@@ -991,6 +994,26 @@ public class WorkerManager {
         new ArrayList<>(serverInstanceToSegmentsMap.entrySet());
     sortedServerInstanceToSegmentsMap.sort(Comparator.comparing(entry -> 
entry.getKey().getInstanceId()));
 
+    // Only a plain, randomly distributed OFFLINE scan can be divided without 
changing ordering,
+    // partition affinity, replication, leaf limits or aggregation. Keep one 
worker otherwise.
+    if 
(context.getPlannerContext().getOptions().containsKey(QueryOptionKey.LEAF_STAGE_WORKERS_PER_SERVER)
+        && sortedServerInstanceToSegmentsMap.size() == 1) {
+      Map.Entry<ServerInstance, Map<String, List<String>>> entry = 
sortedServerInstanceToSegmentsMap.get(0);
+      List<String> segments = entry.getValue().get(TableType.OFFLINE.name());
+      if (entry.getValue().size() == 1 && segments != null && segments.size() 
> 1) {
+        int workers = getRandomScanWorkers(fragment.getFragmentRoot(), 
context.getPlannerContext().getOptions());
+        if (workers > 1) {
+          QueryServerInstance server = new QueryServerInstance(entry.getKey());
+          Map<Integer, Map<String, List<String>>> shards = 
shardOfflineSegments(segments, workers);
+          Map<Integer, QueryServerInstance> servers = 
Maps.newHashMapWithExpectedSize(shards.size());
+          shards.keySet().forEach(worker -> servers.put(worker, server));
+          metadata.setWorkerIdToServerInstanceMap(servers);
+          metadata.setWorkerIdToSegmentsMap(shards);
+          return;
+        }
+      }
+    }
+
     // Assign 1 worker per server
     int numWorkers = sortedServerInstanceToSegmentsMap.size();
     Map<Integer, QueryServerInstance> workerIdToServerInstanceMap = 
Maps.newHashMapWithExpectedSize(numWorkers);
@@ -1010,6 +1033,45 @@ public class WorkerManager {
     metadata.setWorkerIdToSegmentsMap(workerIdToSegmentsMap);
   }
 
+  private static int getRandomScanWorkers(PlanNode root, Map<String, String> 
options) {
+    String value = options.get(QueryOptionKey.LEAF_STAGE_WORKERS_PER_SERVER);
+    if (value == null || value.equals("1") || 
QueryOptionsUtils.getMultiStageLeafLimit(options) != null
+        || options.containsKey(QueryOptionKey.TABLE_SAMPLER) || !(root 
instanceof MailboxSendNode send)
+        || send.getDistributionType() != 
RelDistribution.Type.RANDOM_DISTRIBUTED
+        || send.isMultiSend() || send.isPrePartitioned() || send.isSort() || 
!send.getCollations().isEmpty()
+        || send.getInputs().size() != 1) {
+      return 1;
+    }
+    PlanNode input = send.getInputs().get(0);
+    if (input instanceof ProjectNode project && project.getInputs().size() == 1
+        && project.getProjects().stream().allMatch(expr -> expr instanceof 
RexExpression.InputRef)) {
+      input = project.getInputs().get(0);
+    }
+    if (!(input instanceof TableScanNode)) {
+      return 1;
+    }
+    int workers = Integer.parseInt(value);
+    Preconditions.checkArgument(workers >= 1 && workers <= 16, 
"leafStageWorkersPerServer must be in [1, 16]");
+    return workers;
+  }
+
+  private static Map<Integer, Map<String, List<String>>> 
shardOfflineSegments(List<String> segments,
+      int requestedWorkers) {
+    int workers = Math.min(requestedWorkers, segments.size());
+    List<List<String>> shards = new ArrayList<>(workers);
+    for (int worker = 0; worker < workers; worker++) {
+      shards.add(new ArrayList<>());
+    }
+    for (int i = 0; i < segments.size(); i++) {
+      shards.get(i % workers).add(segments.get(i));
+    }
+    Map<Integer, Map<String, List<String>>> result = 
Maps.newHashMapWithExpectedSize(workers);
+    for (int worker = 0; worker < workers; worker++) {
+      result.put(worker, Map.of(TableType.OFFLINE.name(), shards.get(worker)));
+    }
+    return result;
+  }
+
   /// Acquire routing table for items listed in 
[org.apache.pinot.query.planner.plannode.TableScanNode].
   /// Creates a bare `SELECT *` broker request with no filter, so no 
broker-side segment pruning occurs.
   ///
diff --git 
a/pinot-query-planner/src/test/java/org/apache/pinot/query/BroadcastJoinStageFusionTest.java
 
b/pinot-query-planner/src/test/java/org/apache/pinot/query/BroadcastJoinStageFusionTest.java
new file mode 100644
index 00000000000..62760fbce79
--- /dev/null
+++ 
b/pinot-query-planner/src/test/java/org/apache/pinot/query/BroadcastJoinStageFusionTest.java
@@ -0,0 +1,125 @@
+/**
+ * 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.query;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import org.apache.calcite.rel.RelDistribution;
+import org.apache.pinot.query.planner.logical.SpoolMode;
+import org.apache.pinot.query.planner.physical.DispatchableSubPlan;
+import org.apache.pinot.query.planner.plannode.JoinNode;
+import org.apache.pinot.query.planner.plannode.MailboxSendNode;
+import org.apache.pinot.query.planner.plannode.PlanNode;
+import org.apache.pinot.sql.parsers.CalciteSqlParser;
+import org.apache.pinot.sql.parsers.SqlNodeAndOptions;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+
+
+/// Verifies the worker-stage boundaries selected for adjacent broadcast joins.
+public class BroadcastJoinStageFusionTest extends QueryEnvironmentTestBase {
+  @DataProvider
+  public Object[][] distributions() {
+    return new Object[][]{
+        {"random", "broadcast", "", "JOIN", false, List.of(1, 1), 2, 3},
+        {"random", "broadcast", ", fuse_broadcast_joins='true'", "JOIN", 
false, List.of(2), 1, 3},
+        {"random", "broadcast", ", fuse_broadcast_joins='true'", "LEFT JOIN", 
false, List.of(1, 1), 2, 3},
+        {"random", "broadcast", "", "JOIN", true, List.of(2), 1, 3},
+        {"random", "broadcast", ", fuse_broadcast_joins='false'", "JOIN", 
true, List.of(1, 1), 2, 3},
+        {"hash", "hash", ", fuse_broadcast_joins='true'", "JOIN", false, 
List.of(1, 1), 0, 1}
+    };
+  }
+
+  @Test(dataProvider = "distributions")
+  public void testDispatchableJoinStages(String probe, String build, String 
fuseHint, String upperJoin, boolean option,
+      List<Integer> expectedJoinsPerStage, int expectedRandom, int 
expectedBroadcast) {
+    String query = "SELECT /*+ joinOptions(left_distribution_type='" + probe + 
"', right_distribution_type='" + build
+        + "'" + fuseHint + ") */ b.col3, c.col3, COUNT(*), SUM(a.col7) FROM a 
JOIN b ON a.col1=b.col1 "
+        + upperJoin + " c ON a.col2=c.col2 GROUP BY b.col3,c.col3";
+    SqlNodeAndOptions parsed = 
CalciteSqlParser.compileToSqlNodeAndOptions(query);
+    if (option) {
+      parsed.setExtraOptions(Map.of("fuseBroadcastJoins", "true"));
+    }
+    DispatchableSubPlan plan;
+    try (QueryEnvironment.CompiledQuery compiled = 
_queryEnvironment.compile(query, parsed)) {
+      plan = compiled.planQuery(1).getQueryPlan();
+    }
+    List<Integer> joinsPerStage = new ArrayList<>();
+    int random = 0;
+    int broadcast = 0;
+    for (var stage : plan.getQueryStages()) {
+      PlanNode root = stage.getPlanFragment().getFragmentRoot();
+      int joins = countJoins(root);
+      if (joins > 0) {
+        joinsPerStage.add(joins);
+      }
+      if (root instanceof MailboxSendNode send) {
+        if (send.getDistributionType() == 
RelDistribution.Type.RANDOM_DISTRIBUTED) {
+          random++;
+        } else if (send.getDistributionType() == 
RelDistribution.Type.BROADCAST_DISTRIBUTED) {
+          broadcast++;
+        }
+      }
+    }
+    assertEquals(joinsPerStage, expectedJoinsPerStage);
+    assertEquals(random, expectedRandom);
+    assertEquals(broadcast, expectedBroadcast);
+  }
+
+  @DataProvider
+  public Object[][] sharedBuildSpoolModes() {
+    return new Object[][]{
+        {SpoolMode.AUTO, "SET useSpools=true; SET fuseBroadcastJoins=true; ", 
"", List.of(1, 1, 1), 1},
+        {SpoolMode.ON, "", ", fuse_broadcast_joins='true'", List.of(1, 1, 1), 
1},
+        {SpoolMode.ON, "SET useSpools='auto'; SET fuseBroadcastJoins=true; ", 
"", List.of(1, 2), 0},
+        {SpoolMode.ON, "SET useSpools=false; SET fuseBroadcastJoins=true; ", 
"", List.of(1, 2), 0}
+    };
+  }
+
+  @Test(dataProvider = "sharedBuildSpoolModes")
+  public void testSharedBroadcastBuild(SpoolMode brokerMode, String options, 
String fuseHint,
+      List<Integer> expectedJoinsPerStage, int expectedSharedStages) {
+    QueryEnvironment environment;
+    try (QueryEnvironment.CompiledQuery seed = 
_queryEnvironment.compile("SELECT 1")) {
+      environment = new 
QueryEnvironment(QueryEnvironment.configBuilder().from(seed.getPlannerContext().getEnvConfig())
+          .defaultSpoolMode(brokerMode).build());
+    }
+    String hint = "/*+ joinOptions(left_distribution_type='random', 
right_distribution_type='broadcast'"
+        + fuseHint + ") */ ";
+    String query = options + "SELECT " + hint + "f.col3, b1.col3, r.amount 
FROM a f JOIN b b1 ON f.col1=b1.col1 "
+        + "JOIN (SELECT " + hint + "d.col1, b2.col3 AS amount FROM c d JOIN b 
b2 ON d.col1=b2.col1) r "
+        + "ON f.col1=r.col1";
+    try (QueryEnvironment.CompiledQuery compiled = environment.compile(query)) 
{
+      List<PlanNode> stages = 
compiled.planQuery(1).getQueryPlan().getQueryStages().stream()
+          .map(stage -> stage.getPlanFragment().getFragmentRoot()).toList();
+      
assertEquals(stages.stream().map(BroadcastJoinStageFusionTest::countJoins)
+          .filter(count -> count > 0).sorted().toList(), 
expectedJoinsPerStage);
+      assertEquals(stages.stream().filter(node -> node instanceof 
MailboxSendNode send && send.isMultiSend()).count(),
+          expectedSharedStages);
+    }
+  }
+
+  private static int countJoins(PlanNode node) {
+    return (node instanceof JoinNode ? 1 : 0)
+        + 
node.getInputs().stream().mapToInt(BroadcastJoinStageFusionTest::countJoins).sum();
+  }
+}
diff --git 
a/pinot-query-planner/src/test/java/org/apache/pinot/query/routing/WorkerManagerTest.java
 
b/pinot-query-planner/src/test/java/org/apache/pinot/query/routing/WorkerManagerTest.java
index af7a8ff345a..fd382c4ed13 100644
--- 
a/pinot-query-planner/src/test/java/org/apache/pinot/query/routing/WorkerManagerTest.java
+++ 
b/pinot-query-planner/src/test/java/org/apache/pinot/query/routing/WorkerManagerTest.java
@@ -25,6 +25,7 @@ import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.stream.IntStream;
 import javax.annotation.Nullable;
 import org.apache.helix.model.InstanceConfig;
 import org.apache.helix.zookeeper.datamodel.ZNRecord;
@@ -569,6 +570,47 @@ public class WorkerManagerTest {
     }
   }
 
+  @DataProvider
+  public Object[][] leafFanoutOptions() {
+    return new Object[][]{
+        {"", 1},
+        {"SET leafStageWorkersPerServer=4;", 4},
+        {"SET leafStageWorkersPerServer=16;", 7},
+        {"SET leafStageWorkersPerServer=4; SET multiStageLeafLimit=100;", 1}
+    };
+  }
+
+  @Test(dataProvider = "leafFanoutOptions")
+  public void testOptInFanoutWithFusedBroadcastJoins(String options, int 
factWorkers) {
+    Schema schema = getSchemaBuilder("testTable").build();
+    ServerInstance server = getServerInstance("localhost", 1);
+    List<String> segments = IntStream.range(0, 
7).mapToObj(Integer::toString).toList();
+    RoutingTable routing = new RoutingTable(Map.of(server, new 
SegmentsToQuery(segments, List.of())), List.of(), 0);
+    QueryEnvironment env = newQueryEnvironment(schema,
+        new CapturingRoutingManager(Map.of(server.getInstanceId(), server), 
Map.of("testTable_OFFLINE", routing)));
+    String query = options + " SET fuseBroadcastJoins=true; "
+        + "SELECT /*+ 
joinOptions(left_distribution_type='random',right_distribution_type='broadcast')
 */ "
+        + "f.col3,c.col2,p.col2 FROM testTable f JOIN testTable c ON 
f.col1=c.col1 "
+        + "JOIN testTable p ON f.col2=p.col2";
+    try (QueryEnvironment.CompiledQuery compiled = env.compile(query)) {
+      DispatchableSubPlan subPlan = compiled.planQuery(0).getQueryPlan();
+      List<Integer> fanouts = new ArrayList<>();
+      for (DispatchablePlanFragment stage : 
subPlan.getQueryStageMap().values()) {
+        Map<Integer, Map<String, List<String>>> assigned = 
stage.getWorkerIdToSegmentsMap();
+        if (assigned == null || assigned.isEmpty()) {
+          continue;
+        }
+        List<String> scanned = assigned.values().stream().flatMap(map -> 
map.get("OFFLINE").stream()).toList();
+        assertEquals(scanned.size(), segments.size());
+        assertEquals(new HashSet<>(scanned), new HashSet<>(segments));
+        assertEquals(stage.getServerInstanceToWorkerIdMap().size(), 1);
+        fanouts.add(assigned.size());
+      }
+      fanouts.sort(Integer::compare);
+      assertEquals(fanouts, List.of(1, 1, factWorkers)); // Each broadcast 
build remains single-worker.
+    }
+  }
+
   /// Builds a QueryEnvironment over a single offline table "testTable" backed 
by the given routing manager.
   private static QueryEnvironment newQueryEnvironment(Schema schema, 
RoutingManager routingManager) {
     Map<String, String> tableNameMap = new HashMap<>();
diff --git 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/plan/server/ServerPlanRequestUtils.java
 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/plan/server/ServerPlanRequestUtils.java
index 37a29140c07..3fd454b8a47 100644
--- 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/plan/server/ServerPlanRequestUtils.java
+++ 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/plan/server/ServerPlanRequestUtils.java
@@ -18,6 +18,7 @@
  */
 package org.apache.pinot.query.runtime.plan.server;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Preconditions;
 import java.math.BigDecimal;
 import java.util.ArrayList;
@@ -47,6 +48,7 @@ import 
org.apache.pinot.core.routing.timeboundary.TimeBoundaryInfo;
 import org.apache.pinot.query.planner.plannode.PlanNode;
 import org.apache.pinot.query.routing.StageMetadata;
 import org.apache.pinot.query.routing.StagePlan;
+import org.apache.pinot.query.routing.WorkerMetadata;
 import org.apache.pinot.query.runtime.operator.MultiStageOperator;
 import org.apache.pinot.query.runtime.operator.OpChain;
 import org.apache.pinot.query.runtime.plan.OpChainConverterDispatcher;
@@ -57,6 +59,7 @@ import org.apache.pinot.spi.data.FieldSpec;
 import org.apache.pinot.spi.data.Schema;
 import org.apache.pinot.spi.utils.ByteArray;
 import org.apache.pinot.spi.utils.CommonConstants;
+import 
org.apache.pinot.spi.utils.CommonConstants.Broker.Request.QueryOptionKey;
 import org.apache.pinot.spi.utils.builder.TableNameBuilder;
 import org.apache.pinot.sql.FilterKind;
 import 
org.apache.pinot.sql.parsers.rewriter.NonAggregationGroupByToDistinctQueryRewriter;
@@ -192,6 +195,18 @@ public class ServerPlanRequestUtils {
         segments, null);
   }
 
+  @VisibleForTesting
+  static long localLeafRequestId(long base, int workerId, List<WorkerMetadata> 
localWorkers) {
+    if (localWorkers.size() > 1 && localWorkers.size() <= 16) {
+      for (int ordinal = 0; ordinal < localWorkers.size(); ordinal++) {
+        if (localWorkers.get(ordinal).getWorkerId() == workerId) {
+          return base + ((long) ordinal << 1);
+        }
+      }
+    }
+    return base;
+  }
+
   /// Converts [PinotQuery] into an [InstanceRequest]. The schema is `null` 
when the table is not set up on the server.
   private static InstanceRequest 
compileInstanceRequest(OpChainExecutionContext executionContext, PinotQuery 
pinotQuery,
       @Nullable TimeBoundaryInfo timeBoundaryInfo, TableType tableType, String 
tableNameWithType,
@@ -226,6 +241,13 @@ public class ServerPlanRequestUtils {
     // TODO: Revisit if this is still necessary
     long requestId = (executionContext.getRequestId() << 16) + ((long) 
executionContext.getStageId() << 8) + (
         tableType == TableType.REALTIME ? 1 : 0);
+    // The dispatcher sends only this server's workers. Give concurrently 
assigned local leaves
+    // separate SSE request IDs for tracing/accounting; bit zero still 
identifies the table type.
+    String workers = 
executionContext.getOpChainMetadata().get(QueryOptionKey.LEAF_STAGE_WORKERS_PER_SERVER);
+    if (workers != null && !workers.equals("1")) {
+      requestId = localLeafRequestId(requestId, executionContext.getWorkerId(),
+          executionContext.getStageMetadata().getWorkerMetadataList());
+    }
     instanceRequest.setRequestId(requestId);
     instanceRequest.setCid(executionContext.getCid());
     instanceRequest.setBrokerId(executionContext.getBrokerId());
diff --git 
a/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/plan/server/ServerPlanRequestUtilsTest.java
 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/plan/server/ServerPlanRequestUtilsTest.java
new file mode 100644
index 00000000000..c771dbe3ac0
--- /dev/null
+++ 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/plan/server/ServerPlanRequestUtilsTest.java
@@ -0,0 +1,41 @@
+/**
+ * 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.query.runtime.plan.server;
+
+import java.util.List;
+import java.util.Map;
+import org.apache.pinot.query.routing.WorkerMetadata;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+
+
+/// Verifies request ID allocation for leaf workers sharing a server.
+public class ServerPlanRequestUtilsTest {
+  @Test
+  public void testLeafRequestIdsPreserveTableTypeAndSeparateLocalWorkers() {
+    var workers = List.of(new WorkerMetadata(11, Map.of()), new 
WorkerMetadata(37, Map.of()));
+    long offline = 4321L << 16;
+    for (long base : List.of(offline, offline + 1)) {
+      assertEquals(ServerPlanRequestUtils.localLeafRequestId(base, 11, 
workers), base);
+      assertEquals(ServerPlanRequestUtils.localLeafRequestId(base, 37, 
workers), base + 2);
+      assertEquals(ServerPlanRequestUtils.localLeafRequestId(base, 37, 
List.of(workers.get(1))), base);
+    }
+  }
+}
diff --git 
a/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/queries/QueryRunnerTest.java
 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/queries/QueryRunnerTest.java
index 73841027fa3..bda71eed755 100644
--- 
a/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/queries/QueryRunnerTest.java
+++ 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/queries/QueryRunnerTest.java
@@ -21,7 +21,6 @@ package org.apache.pinot.query.runtime.queries;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.node.ObjectNode;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
@@ -35,6 +34,7 @@ import org.apache.pinot.query.mailbox.MailboxService;
 import org.apache.pinot.query.planner.physical.DispatchablePlanFragment;
 import org.apache.pinot.query.routing.QueryServerInstance;
 import org.apache.pinot.query.runtime.MultiStageStatsTreeBuilder;
+import org.apache.pinot.query.runtime.operator.MultiStageOperator;
 import org.apache.pinot.query.service.dispatch.QueryDispatcher;
 import org.apache.pinot.query.testutils.MockInstanceDataManagerFactory;
 import org.apache.pinot.query.testutils.QueryTestUtils;
@@ -110,6 +110,7 @@ public class QueryRunnerTest extends QueryRunnerTestBase {
     MockInstanceDataManagerFactory factory1 = new 
MockInstanceDataManagerFactory("server1");
     factory1.registerTable(SCHEMA_BUILDER.setSchemaName("a").build(), 
"a_REALTIME");
     factory1.registerTable(SCHEMA_BUILDER.setSchemaName("b").build(), 
"b_REALTIME");
+    factory1.registerTable(SCHEMA_BUILDER.setSchemaName("fact").build(), 
"fact_OFFLINE");
     factory1.registerTable(SCHEMA_BUILDER.setSchemaName("c").build(), 
"c_OFFLINE");
     factory1.registerTable(SCHEMA_BUILDER.setSchemaName("d").build(), "d");
     
factory1.registerTable(SCHEMA_BUILDER.setSchemaName("tbl-escape-naming").build(),
 "tbl-escape-naming_OFFLINE");
@@ -119,6 +120,15 @@ public class QueryRunnerTest extends QueryRunnerTestBase {
     factory1.addSegment("c_OFFLINE", buildRows("c_OFFLINE"));
     factory1.addSegment("d_OFFLINE", buildRows("d_OFFLINE"));
     factory1.addSegment("tbl-escape-naming_OFFLINE", 
buildRows("tbl-escape-naming_OFFLINE"));
+    for (int segment = 0; segment < 7; segment++) {
+      // A distinct group per segment makes both lost and duplicated segments 
visible in the query result.
+      GenericRow row = new GenericRow();
+      row.putValue("col1", "segment-" + segment);
+      row.putValue("col2", "foo");
+      row.putValue("col3", segment % 2 == 0 ? 1 : 42);
+      row.putValue("ts", TimeUnit.DAYS.toMillis(19_000));
+      factory1.addSegment("fact_OFFLINE", List.of(row));
+    }
 
     MockInstanceDataManagerFactory factory2 = new 
MockInstanceDataManagerFactory("server2");
     factory2.registerTable(SCHEMA_BUILDER.setSchemaName("a").build(), 
"a_REALTIME");
@@ -133,7 +143,7 @@ public class QueryRunnerTest extends QueryRunnerTestBase {
     // Setting up H2 for validation
     setH2Connection();
     Schema schema = SCHEMA_BUILDER.build();
-    for (String tableName : Arrays.asList("a", "b", "c", "d")) {
+    for (String tableName : List.of("a", "b", "c", "d", "fact")) {
       addTableToH2(tableName, schema);
       addDataToH2(tableName, schema, 
factory1.buildTableRowsMap().get(tableName));
       addDataToH2(tableName, schema, 
factory2.buildTableRowsMap().get(tableName));
@@ -174,6 +184,49 @@ public class QueryRunnerTest extends QueryRunnerTestBase {
     _mailboxService.shutdown();
   }
 
+  @Test
+  public void testFusedBroadcastJoinsAcrossServers()
+      throws Exception {
+    // Both dimensions have duplicate join keys. COUNT and SUM detect missing 
or doubled probe rows.
+    String sql = "SELECT /*+ 
joinOptions(left_distribution_type='random',right_distribution_type='broadcast')
 */ "
+        + "b.col3, c.col3, COUNT(*), SUM(a.col3) FROM a JOIN b ON 
a.col2=b.col2 JOIN c ON a.col3=c.col3 "
+        + "GROUP BY b.col3, c.col3";
+    String fused = "SET fuseBroadcastJoins=true; " + sql;
+    assertEquals(planQuery(fused).getQueryPlan().getQueryStages().size(),
+        planQuery(sql).getQueryPlan().getQueryStages().size() - 1);
+    QueryDispatcher.QueryResult result = queryRunner(fused, false);
+    assertNull(result.getProcessingException());
+    compareRowEquals(result.getResultTable(), queryH2(sql));
+  }
+
+  @Test
+  public void testOfflineLeafFanoutWithBroadcastJoins()
+      throws Exception {
+    String sql = "SELECT /*+ 
joinOptions(left_distribution_type='random',right_distribution_type='broadcast')
 */ "
+        + "f.col1, COUNT(*), SUM(f.col3) FROM fact f JOIN b ON f.col2=b.col2 
JOIN c ON f.col3=c.col3 "
+        + "GROUP BY f.col1";
+    List<Object[]> expected = queryH2(sql);
+    assertEquals(expected.size(), 7);
+    for (int requestedWorkers : List.of(1, 4, 16)) {
+      for (boolean fusion : List.of(false, true)) {
+        String query = "SET leafStageWorkersPerServer=" + requestedWorkers + 
"; SET fuseBroadcastJoins=" + fusion
+            + "; " + sql;
+        QueryDispatcher.QueryResult result = queryRunner(query, true);
+        assertNull(result.getProcessingException());
+        compareRowEquals(result.getResultTable(), expected);
+
+        // The send's parallelism is the sum reported by the workers that 
actually ran this leaf stage.
+        JsonNode sendStats = result.getQueryStats().stream()
+            .filter(stage -> stage != null && !stage.isEmpty()
+                && stage.getOperatorType(0) == MultiStageOperator.Type.LEAF)
+            .filter(stage -> "fact".equals(
+                
TableNameBuilder.extractRawTableName(stage.getOperatorStats(0).asJson().path("table").asText())))
+            .findFirst().orElseThrow().getLastOperatorStats().asJson();
+        assertEquals(sendStats.path("parallelism").asInt(), 
Math.min(requestedWorkers, 7), query);
+      }
+    }
+  }
+
   /// The self stats of a node are the node's own value minus its children's. 
A mailbox send reports its stats from
   /// inside the getNextBlock() call whose time it is still spending, so 
unless that call is accounted first it
   /// reports less than the input whose call it contains and the subtraction 
goes negative. A query whose filter
diff --git a/pinot-query-runtime/src/test/resources/queries/Spool.json 
b/pinot-query-runtime/src/test/resources/queries/Spool.json
index dc67255ea19..a93206aac06 100644
--- a/pinot-query-runtime/src/test/resources/queries/Spool.json
+++ b/pinot-query-runtime/src/test/resources/queries/Spool.json
@@ -48,6 +48,11 @@
         "sql": "SET timeoutMs=10000; SET useSpools=true; SELECT a1.intCol1, 
a2.intCol1, a3.intCol1 FROM {tbl1} as a1 JOIN {tbl1} as a2 ON a1.strCol1 = 
a2.strCol1 JOIN {tbl1} as a3 ON a1.strCol1 = a3.strCol1",
         "h2Sql": "SELECT a1.intCol1, a2.intCol1, a3.intCol1 FROM {tbl1} as a1 
JOIN {tbl1} as a2 ON a1.strCol1 = a2.strCol1 JOIN {tbl1} as a3 ON a1.strCol1 = 
a3.strCol1"
       },
+      {
+        "description": "Both branches of a broadcast join read the same 
dimension with spool reuse and fusion requested",
+        "sql": "SET timeoutMs=10000; SET useSpools=true; SET 
fuseBroadcastJoins=true; SELECT /*+ 
joinOptions(left_distribution_type='random', 
right_distribution_type='broadcast') */ f.intCol1, b1.intCol1, r.ordCol, 
r.dimValue FROM {tbl2} f JOIN {tbl1} b1 ON f.strCol1 = b1.strCol1 JOIN (SELECT 
/*+ joinOptions(left_distribution_type='random', 
right_distribution_type='broadcast') */ d.grpCol, d.ordCol, b2.intCol1 AS 
dimValue FROM {tbl3} d JOIN {tbl1} b2 ON d.grpCol = b2.strCol1) r ON f.strC 
[...]
+        "h2Sql": "SELECT f.intCol1, b1.intCol1, r.ordCol, r.dimValue FROM 
{tbl2} f JOIN {tbl1} b1 ON f.strCol1 = b1.strCol1 JOIN (SELECT d.grpCol, 
d.ordCol, b2.intCol1 AS dimValue FROM {tbl3} d JOIN {tbl1} b2 ON d.grpCol = 
b2.strCol1) r ON f.strCol1 = r.grpCol"
+      },
       {
         "description": "Spool of an aggregated stage reused by a self join",
         "sql": "SET timeoutMs=10000; SET useSpools=true; WITH g AS (SELECT 
strCol1, SUM(intCol1) AS s FROM {tbl1} GROUP BY strCol1) SELECT a.strCol1, a.s, 
b.s FROM g a JOIN g b ON a.strCol1 = b.strCol1",
diff --git 
a/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java 
b/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
index b09f66133a0..592c8ec43a0 100644
--- a/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
+++ b/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
@@ -1118,6 +1118,10 @@ public class CommonConstants {
         // Query option key used to enable a given set of defaultly disabled 
rules
         public static final String USE_PLANNER_RULES = "usePlannerRules";
 
+        /// Keep adjacent inner equijoins with broadcast build sides in one 
multi-stage worker.
+        /// Unguarded spooling (`useSpools=on` or `true`) takes precedence and 
keeps the joins in separate stages.
+        public static final String FUSE_BROADCAST_JOINS = "fuseBroadcastJoins";
+
         public static final String ALLOW_REVERSE_ORDER = "allowReverseOrder";
         public static final boolean DEFAULT_ALLOW_REVERSE_ORDER = false;
 
@@ -1136,6 +1140,9 @@ public class CommonConstants {
         public static final String GROUP_TRIM_THRESHOLD = "groupTrimThreshold";
         public static final String STAGE_PARALLELISM = "stageParallelism";
 
+        /// Maximum local workers for a plain randomly distributed OFFLINE 
scan routed to one server (1–16, default 1).
+        public static final String LEAF_STAGE_WORKERS_PER_SERVER = 
"leafStageWorkersPerServer";
+
         public static final String IN_PREDICATE_PRE_SORTED = 
"inPredicatePreSorted";
         public static final String IN_PREDICATE_LOOKUP_ALGORITHM = 
"inPredicateLookupAlgorithm";
         /// Query-level override for `inpredicate.threshold`. Negative means 
always prune.


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

Reply via email to