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

gortiz 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 2f3fca637e5 Add an auto spool mode guarded against deadlocks and make 
it the default (#19944)
2f3fca637e5 is described below

commit 2f3fca637e55e8fcca3cd80f3e32f3b00a1c1401
Author: Gonzalo Ortiz Jaureguizar <[email protected]>
AuthorDate: Mon Nov 23 14:21:51 2026 +0100

    Add an auto spool mode guarded against deadlocks and make it the default 
(#19944)
---
 .../MultiStageBrokerRequestHandler.java            |   9 +-
 .../apache/pinot/common/metrics/BrokerMeter.java   |   4 +
 .../common/utils/config/QueryOptionsUtils.java     |   8 +
 .../common/utils/config/QueryOptionsUtilsTest.java |  12 +
 .../integration/tests/SpoolIntegrationTest.java    |  74 ++++
 .../org/apache/pinot/query/QueryEnvironment.java   |  38 +-
 .../planner/logical/EquivalentStagesFinder.java    |   7 +
 .../planner/logical/EquivalentStagesReplacer.java  |  81 +++-
 .../planner/logical/PinotLogicalQueryPlanner.java  |  73 +++-
 .../query/planner/logical/SpoolDeadlockGuard.java  | 471 +++++++++++++++++++++
 .../pinot/query/planner/logical/SpoolMode.java     |  72 ++++
 .../query/planner/logical/SpoolSubstitution.java   |  45 ++
 .../query/planner/logical/VolatileFunctions.java   | 139 ++++++
 .../query/planner/plannode/MailboxSendNode.java    |   8 +
 .../query/QueryEnvironmentSpoolOptionsTest.java    |  49 +++
 .../logical/EquivalentStagesFinderTest.java        |  61 +++
 .../logical/EquivalentStagesReplacerTest.java      |  94 +++-
 .../PinotLogicalQueryPlannerSpoolFeedbackTest.java |  50 +++
 .../planner/logical/SpoolDeadlockGuardTest.java    | 324 ++++++++++++++
 .../pinot/query/planner/logical/SpoolModeTest.java |  62 +++
 .../query/planner/logical/StagesTestBase.java      |  51 +++
 .../planner/physical/PinotDispatchPlannerTest.java |  40 ++
 .../apache/pinot/spi/utils/CommonConstants.java    |  18 +-
 23 files changed, 1752 insertions(+), 38 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 1ac05af3065..b02b643e0b6 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
@@ -86,6 +86,7 @@ import org.apache.pinot.query.ImmutableQueryEnvironment;
 import org.apache.pinot.query.QueryEnvironment;
 import org.apache.pinot.query.mailbox.MailboxService;
 import org.apache.pinot.query.planner.explain.AskingServerStageExplainer;
+import org.apache.pinot.query.planner.logical.SpoolMode;
 import org.apache.pinot.query.planner.physical.DispatchablePlanFragment;
 import org.apache.pinot.query.planner.physical.DispatchableSubPlan;
 import org.apache.pinot.query.planner.plannode.PlanNode;
@@ -159,6 +160,8 @@ public class MultiStageBrokerRequestHandler extends 
BaseBrokerRequestHandler {
   protected final String _defaultStreamingGroupByFlushThreshold;
   @Nullable
   protected final String _defaultStreamingDistinctFlushThreshold;
+  /// Parsed once so that an invalid [CommonConstants.Broker#CONFIG_OF_SPOOLS] 
fails the broker start, not every query.
+  private final SpoolMode _defaultSpoolMode;
 
   protected final PinotMeter _stagesStartedMeter = 
BrokerMeter.MSE_STAGES_STARTED.getGlobalMeter();
   protected final PinotMeter _stagesFinishedMeter = 
BrokerMeter.MSE_STAGES_COMPLETED.getGlobalMeter();
@@ -255,6 +258,8 @@ public class MultiStageBrokerRequestHandler extends 
BaseBrokerRequestHandler {
         CommonConstants.Broker.DEFAULT_MSE_STREAMING_DISTINCT_FLUSH_THRESHOLD);
     _defaultStreamingDistinctFlushThreshold =
         streamingDistinctFlushThreshold > 0 ? 
Integer.toString(streamingDistinctFlushThreshold) : null;
+    _defaultSpoolMode = 
SpoolMode.fromString(_config.getProperty(CommonConstants.Broker.CONFIG_OF_SPOOLS,
+        CommonConstants.Broker.DEFAULT_SPOOLS_MODE));
   }
 
   /// Returns the planner rules disabled by default: the comma-separated list 
in
@@ -556,8 +561,6 @@ public class MultiStageBrokerRequestHandler extends 
BaseBrokerRequestHandler {
     String database = 
DatabaseUtils.extractDatabaseFromQueryRequest(queryOptions, httpHeaders);
     boolean inferPartitionHint = 
_config.getProperty(CommonConstants.Broker.CONFIG_OF_INFER_PARTITION_HINT,
         CommonConstants.Broker.DEFAULT_INFER_PARTITION_HINT);
-    boolean defaultUseSpool = 
_config.getProperty(CommonConstants.Broker.CONFIG_OF_SPOOLS,
-        CommonConstants.Broker.DEFAULT_OF_SPOOLS);
     boolean defaultUseLeafServerForIntermediateStage = _config.getProperty(
         
CommonConstants.Broker.CONFIG_OF_USE_LEAF_SERVER_FOR_INTERMEDIATE_STAGE,
         CommonConstants.Broker.DEFAULT_USE_LEAF_SERVER_FOR_INTERMEDIATE_STAGE);
@@ -625,7 +628,7 @@ public class MultiStageBrokerRequestHandler extends 
BaseBrokerRequestHandler {
         .isCaseSensitive(caseSensitive)
         
.isNullHandlingEnabled(QueryOptionsUtils.isNullHandlingEnabled(queryOptions))
         .defaultInferPartitionHint(inferPartitionHint)
-        .defaultUseSpools(defaultUseSpool)
+        .defaultSpoolMode(_defaultSpoolMode)
         .defaultUnnestColumnPruning(defaultUnnestColumnPruning)
         
.defaultUseLeafServerForIntermediateStage(defaultUseLeafServerForIntermediateStage)
         .defaultEnableGroupTrim(defaultEnableGroupTrim)
diff --git 
a/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java 
b/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java
index e0a97a2824c..a5c22063ab6 100644
--- 
a/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java
+++ 
b/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java
@@ -266,6 +266,10 @@ public class BrokerMeter implements AbstractMetrics.Meter {
   ///
   /// For each query with at least one join, this meter is increased as many 
times as joins in the query.
   public static final BrokerMeter JOIN_COUNT = create("JOIN_COUNT", "queries", 
true);
+  /// How many times the multi-stage planner made a stage feed one more 
consumer stage (a spool).
+  public static final BrokerMeter SPOOLS_APPLIED = create("SPOOLS_APPLIED", 
"spools", true);
+  /// How many spools the multi-stage planner refused because the shared stage 
could block the query.
+  public static final BrokerMeter SPOOLS_REJECTED_BY_GUARD = 
create("SPOOLS_REJECTED_BY_GUARD", "spools", true);
   /// How many queries with window functions have been executed.
   ///
   /// For each query with at least one window function, this meter is 
increased exactly once.
diff --git 
a/pinot-common/src/main/java/org/apache/pinot/common/utils/config/QueryOptionsUtils.java
 
b/pinot-common/src/main/java/org/apache/pinot/common/utils/config/QueryOptionsUtils.java
index 3a4ab0cb61f..488afc538a4 100644
--- 
a/pinot-common/src/main/java/org/apache/pinot/common/utils/config/QueryOptionsUtils.java
+++ 
b/pinot-common/src/main/java/org/apache/pinot/common/utils/config/QueryOptionsUtils.java
@@ -1117,6 +1117,14 @@ public class QueryOptionsUtils {
         queryOptions.get(QueryOptionKey.VECTOR_USE_BOUNDED_QUEUE));
   }
 
+  /// Returns whether the response must describe the spool decisions of the 
multi-stage planner. Defaults to `false`.
+  ///
+  /// @throws IllegalArgumentException if the option is set to a value other 
than `true` or `false`
+  public static boolean isSpoolsFeedback(Map<String, String> queryOptions) {
+    return 
Boolean.TRUE.equals(checkedParseBooleanNullable(QueryOptionKey.SPOOLS_FEEDBACK,
+        queryOptions.get(QueryOptionKey.SPOOLS_FEEDBACK)));
+  }
+
   @Nullable
   private static Boolean checkedParseBooleanNullable(String optionName, 
@Nullable String optionValue) {
     if (optionValue == null) {
diff --git 
a/pinot-common/src/test/java/org/apache/pinot/common/utils/config/QueryOptionsUtilsTest.java
 
b/pinot-common/src/test/java/org/apache/pinot/common/utils/config/QueryOptionsUtilsTest.java
index a89eadb0892..9c854337d18 100644
--- 
a/pinot-common/src/test/java/org/apache/pinot/common/utils/config/QueryOptionsUtilsTest.java
+++ 
b/pinot-common/src/test/java/org/apache/pinot/common/utils/config/QueryOptionsUtilsTest.java
@@ -330,6 +330,18 @@ public class QueryOptionsUtilsTest {
     assertEquals(QueryOptionsUtils.getVectorNprobe(Map.of(VECTOR_NPROBE, 
"128")), Integer.valueOf(128));
   }
 
+  @Test
+  public void testSpoolsFeedback() {
+    assertFalse(QueryOptionsUtils.isSpoolsFeedback(Map.of()));
+    assertTrue(QueryOptionsUtils.isSpoolsFeedback(Map.of(SPOOLS_FEEDBACK, 
"true")));
+    assertTrue(QueryOptionsUtils.isSpoolsFeedback(Map.of(SPOOLS_FEEDBACK, " 
TRUE ")));
+    assertFalse(QueryOptionsUtils.isSpoolsFeedback(Map.of(SPOOLS_FEEDBACK, 
"false")));
+    expectThrows(IllegalArgumentException.class,
+        () -> QueryOptionsUtils.isSpoolsFeedback(Map.of(SPOOLS_FEEDBACK, 
"1")));
+    expectThrows(IllegalArgumentException.class,
+        () -> QueryOptionsUtils.isSpoolsFeedback(Map.of(SPOOLS_FEEDBACK, 
"yes")));
+  }
+
   @Test
   public void testVectorNprobeNull() {
     assertNull(QueryOptionsUtils.getVectorNprobe(Map.of()));
diff --git 
a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/SpoolIntegrationTest.java
 
b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/SpoolIntegrationTest.java
index 43131d2cddb..59ced6077be 100644
--- 
a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/SpoolIntegrationTest.java
+++ 
b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/SpoolIntegrationTest.java
@@ -127,6 +127,80 @@ public class SpoolIntegrationTest extends 
BaseClusterIntegrationTest
     checkSpoolSame(parsed, 4, 3, 7);
   }
 
+  /// The query of [#intermediateSpool()] spools stage 4 into the probe input 
of the join and, through an aggregate,
+  /// into its build input. The join reads the probe input only after the 
build input finishes, so with a full probe
+  /// mailbox the shared stage stops and the build input never finishes. 
`auto` must refuse that spool.
+  @Test
+  public void autoRejectsSpoolThatCanBlock()
+      throws Exception {
+    JsonNode jsonNode = postQuery("SET useSpools = 'auto';\n"
+        + "SET spoolsFeedback = true;\n"
+        + "WITH group_and_sum AS (\n"
+        + "  SELECT ArrTimeBlk, Dest, SUM(ArrTime) AS ArrTime\n"
+        + "  FROM mytable\n"
+        + "  GROUP BY ArrTimeBlk, Dest\n"
+        + "  limit 1000\n"
+        + "),\n"
+        + "aggregated_data AS (\n"
+        + "  SELECT Dest, SUM(ArrTime) AS ArrTime\n"
+        + "  FROM group_and_sum\n"
+        + "  GROUP BY Dest\n"
+        + ")\n"
+        + "SELECT s.Dest, s.ArrTime, o.ArrTime AS ArrTime2\n"
+        + "FROM group_and_sum s\n"
+        + "JOIN aggregated_data o\n"
+        + "ON s.Dest = o.Dest\n"
+        + "LIMIT 1");
+    assertNoError(jsonNode);
+    JsonNode spools = jsonNode.get("responseMetadata").get("spools");
+    Assert.assertEquals(spools.get("mode").asText(), "auto", 
spools.toString());
+    // The shared intermediate stage is refused. The leaf stage below it can 
still be shared, because both of its
+    // consumers aggregate it, so this test does not assert that no spool is 
applied.
+    Assert.assertTrue(hasOutcome(spools, "REJECTED_BY_GUARD"), 
spools.toString());
+  }
+
+  /// Both consumers of the shared stage aggregate it, so each consumer reads 
the whole shared stage before the join
+  /// waits for any input. `auto` must apply that spool, and the result must 
not change.
+  @Test
+  public void autoAppliesSpoolWhenConsumersAggregate()
+      throws Exception {
+    // The ORDER BY makes g deterministic. Without it, each copy of g can keep 
a different set of 1000 groups when
+    // spools are off, so the results differ for a reason that has nothing to 
do with spools.
+    String query = "WITH g AS (\n"
+        + "  SELECT ArrTimeBlk, Dest, SUM(ArrTime) AS ArrTime\n"
+        + "  FROM mytable\n"
+        + "  GROUP BY ArrTimeBlk, Dest\n"
+        + "  ORDER BY ArrTimeBlk, Dest\n"
+        + "  LIMIT 1000\n"
+        + ")\n"
+        + "SELECT a.Dest, a.s, b.m\n"
+        // Both consumers read the same columns of g. Otherwise the planner 
prunes each copy of g to different columns,
+        // and the two copies are not equivalent.
+        + "FROM (SELECT Dest, SUM(ArrTime) AS s FROM g GROUP BY Dest) a\n"
+        + "JOIN (SELECT Dest, MAX(ArrTime) AS m FROM g GROUP BY Dest) b\n"
+        + "ON a.Dest = b.Dest\n"
+        + "ORDER BY a.Dest\n"
+        + "LIMIT 10000";
+    JsonNode withSpools = postQuery("SET useSpools = 'auto';\nSET 
spoolsFeedback = true;\n" + query);
+    assertNoError(withSpools);
+    JsonNode spools = withSpools.get("responseMetadata").get("spools");
+    Assert.assertTrue(hasOutcome(spools, "APPLIED"), spools.toString());
+    Assert.assertFalse(hasOutcome(spools, "REJECTED_BY_GUARD"), 
spools.toString());
+
+    JsonNode withoutSpools = postQuery("SET useSpools = 'off';\n" + query);
+    assertNoError(withoutSpools);
+    Assert.assertEquals(withSpools.get("resultTable").get("rows"), 
withoutSpools.get("resultTable").get("rows"));
+  }
+
+  private static boolean hasOutcome(JsonNode spools, String outcome) {
+    for (JsonNode substitution : spools.get("substitutions")) {
+      if (substitution.get("outcome").asText().equals(outcome)) {
+        return true;
+      }
+    }
+    return false;
+  }
+
   /// Test a complex with nested spools.
   ///
   /// Don't try to understand the query, just check that the spools are 
correct.
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 3ffc2921385..c186faa2024 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
@@ -84,6 +84,7 @@ import 
org.apache.pinot.query.planner.explain.MultiStageExplainAskingServersUtil
 import org.apache.pinot.query.planner.explain.PhysicalExplainPlanVisitor;
 import org.apache.pinot.query.planner.logical.PinotLogicalQueryPlanner;
 import org.apache.pinot.query.planner.logical.RelToPlanNodeConverter;
+import org.apache.pinot.query.planner.logical.SpoolMode;
 import org.apache.pinot.query.planner.logical.TransformationTracker;
 import org.apache.pinot.query.planner.physical.DispatchableSubPlan;
 import org.apache.pinot.query.planner.physical.PinotDispatchPlanner;
@@ -578,8 +579,9 @@ public class QueryEnvironment {
           _envConfig.getWorkerManager(), requestId, 
_envConfig.getTableCache());
       return pinotDispatchPlanner.createDispatchableSubPlanV2(plan.getLeft(), 
plan.getRight());
     }
-    SubPlan plan = PinotLogicalQueryPlanner.makePlan(relRoot, tracker, 
useSpools(plannerContext.getOptions()),
-        _envConfig.defaultHashFunction(), 
pruneUnnestColumns(plannerContext.getOptions()));
+    Map<String, String> options = plannerContext.getOptions();
+    SubPlan plan = PinotLogicalQueryPlanner.makePlan(relRoot, tracker, 
getSpoolMode(options),
+        isSpoolsFeedback(options), _envConfig.defaultHashFunction(), 
pruneUnnestColumns(options));
     PinotDispatchPlanner pinotDispatchPlanner =
         new PinotDispatchPlanner(plannerContext, 
_envConfig.getWorkerManager(), _envConfig.getRequestId(),
             _envConfig.getTableCache());
@@ -756,12 +758,32 @@ public class QueryEnvironment {
     return ImmutableQueryEnvironment.Config.builder();
   }
 
-  public boolean useSpools(Map<String, String> options) {
+  /// Returns the spool mode of the query: the 
[CommonConstants.Broker.Request.QueryOptionKey#USE_SPOOLS] query option
+  /// when it is set, or [Config#defaultSpoolMode()] otherwise.
+  ///
+  /// @throws QueryException with [QueryErrorCode#QUERY_VALIDATION] if the 
query option is not a valid [SpoolMode].
+  public SpoolMode getSpoolMode(Map<String, String> options) {
     String optionValue = 
options.get(CommonConstants.Broker.Request.QueryOptionKey.USE_SPOOLS);
     if (optionValue == null) {
-      return _envConfig.defaultUseSpools();
+      return _envConfig.defaultSpoolMode();
+    }
+    try {
+      return SpoolMode.fromString(optionValue);
+    } catch (IllegalArgumentException e) {
+      throw QueryErrorCode.QUERY_VALIDATION.asException(e.getMessage(), e);
+    }
+  }
+
+  /// Whether the response must describe the spool decisions of the planner. 
See
+  /// [CommonConstants.Broker.Request.QueryOptionKey#SPOOLS_FEEDBACK].
+  ///
+  /// @throws QueryException with [QueryErrorCode#QUERY_VALIDATION] if the 
query option is not `true` or `false`.
+  public static boolean isSpoolsFeedback(Map<String, String> options) {
+    try {
+      return QueryOptionsUtils.isSpoolsFeedback(options);
+    } catch (IllegalArgumentException e) {
+      throw QueryErrorCode.QUERY_VALIDATION.asException(e.getMessage(), e);
     }
-    return Boolean.parseBoolean(optionValue);
   }
 
   /// Whether to prune unused input (passthrough) columns from the UNNEST 
output. Defaults to the broker config
@@ -821,15 +843,15 @@ public class QueryEnvironment {
       return CommonConstants.Broker.DEFAULT_INFER_PARTITION_HINT;
     }
 
-    /// Whether to use spools or not.
+    /// The spool mode.
     ///
     /// This is treated as the default value for the broker and it is expected 
to be obtained from a Pinot
     /// configuration.
     /// This default value can be always overridden at query level by the 
query option
     /// [CommonConstants.Broker.Request.QueryOptionKey#USE_SPOOLS].
     @Value.Default
-    default boolean defaultUseSpools() {
-      return CommonConstants.Broker.DEFAULT_OF_SPOOLS;
+    default SpoolMode defaultSpoolMode() {
+      return SpoolMode.fromString(CommonConstants.Broker.DEFAULT_SPOOLS_MODE);
     }
 
     /// Whether to prune unused input (passthrough) columns from the UNNEST 
output by default.
diff --git 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/EquivalentStagesFinder.java
 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/EquivalentStagesFinder.java
index 3a986225d8d..f9c8c28fc4a 100644
--- 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/EquivalentStagesFinder.java
+++ 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/EquivalentStagesFinder.java
@@ -78,6 +78,13 @@ public class EquivalentStagesFinder {
       // from O(n^3) to O(n^2).
       visitChildren(node, context);
 
+      // A stage that calls a volatile function must draw its own values, so 
it is never equivalent to another stage.
+      // The stages above it are not equivalent either, because their receives 
read from different groups.
+      if (VolatileFunctions.callsVolatileFunction(node)) {
+        _equivalentStages.addNewGroup(node);
+        return null;
+      }
+
       // first try to find if the current node/stage is equivalent to an 
already equivalent stages.
       for (MailboxSendNode uniqueStage : _equivalentStages.getLeaders()) {
         if (_nodeEquivalence.areEquivalent(node, uniqueStage)) {
diff --git 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/EquivalentStagesReplacer.java
 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/EquivalentStagesReplacer.java
index 2cd463c5ed8..73a18180140 100644
--- 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/EquivalentStagesReplacer.java
+++ 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/EquivalentStagesReplacer.java
@@ -18,6 +18,11 @@
  */
 package org.apache.pinot.query.planner.logical;
 
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Set;
 import org.apache.pinot.query.planner.plannode.MailboxReceiveNode;
 import org.apache.pinot.query.planner.plannode.MailboxSendNode;
 import org.apache.pinot.query.planner.plannode.PlanNode;
@@ -32,6 +37,9 @@ import 
org.apache.pinot.query.planner.plannode.PlanNodeVisitor;
 /// For each [MailboxReceiveNode] in the plan, if the sender is not the leader 
of the group,
 /// replaces the sender with the leader.
 /// The leader is also updated to include the receiver in its list of 
receivers.
+///
+/// When the replacement is guarded, each substitution is kept only if 
[SpoolDeadlockGuard] finds no risk in the
+/// resulting plan. Otherwise the substitution is undone and the original 
sender stays.
 public class EquivalentStagesReplacer {
   private EquivalentStagesReplacer() {
   }
@@ -40,12 +48,26 @@ public class EquivalentStagesReplacer {
     replaceEquivalentStages(root, equivalentStages, OnSubstitution.NO_OP);
   }
 
-  /// Replaces the equivalent stages in the query plan.
+  /// Replaces the equivalent stages in the query plan, without 
[SpoolDeadlockGuard].
   ///
   /// @param root Root plan node
   /// @param equivalentStages Equivalent stages
   public static void replaceEquivalentStages(PlanNode root, GroupedStages 
equivalentStages, OnSubstitution listener) {
-    root.visit(new Replacer(listener), equivalentStages);
+    replaceEquivalentStages(root, equivalentStages, listener, false);
+  }
+
+  /// Replaces the equivalent stages in the query plan.
+  ///
+  /// @param root Root plan node
+  /// @param equivalentStages Equivalent stages
+  /// @param listener Called once for each applied substitution
+  /// @param guarded Whether each substitution must pass [SpoolDeadlockGuard]
+  /// @return One entry for each receive whose sender is not the leader of its 
group, in the order of the decisions
+  public static List<SpoolSubstitution> replaceEquivalentStages(PlanNode root, 
GroupedStages equivalentStages,
+      OnSubstitution listener, boolean guarded) {
+    Replacer replacer = new Replacer(root, listener, guarded);
+    root.visit(replacer, equivalentStages);
+    return replacer._substitutions;
   }
 
   public interface OnSubstitution {
@@ -55,33 +77,58 @@ public class EquivalentStagesReplacer {
   }
 
   private static class Replacer extends 
PlanNodeVisitor.DepthFirstVisitor<Void, GroupedStages> {
+    private final PlanNode _root;
     private final OnSubstitution _listener;
+    private final boolean _guarded;
+    private final List<SpoolSubstitution> _substitutions = new ArrayList<>();
+    /// A stage can be visited more than once (for example the leader of a 
group), so a receive is decided only once.
+    private final Set<MailboxReceiveNode> _visitedReceives = 
Collections.newSetFromMap(new IdentityHashMap<>());
 
-    public Replacer(OnSubstitution listener) {
+    public Replacer(PlanNode root, OnSubstitution listener, boolean guarded) {
+      _root = root;
       _listener = listener;
+      _guarded = guarded;
     }
 
     @Override
     public Void visitMailboxReceive(MailboxReceiveNode node, GroupedStages 
equivalenceGroups) {
+      if (!_visitedReceives.add(node)) {
+        return null;
+      }
       MailboxSendNode sender = node.getSender();
       MailboxSendNode leader = equivalenceGroups.getGroup(sender).first();
-      if (canSubstitute(sender, leader)) {
-        // we don't want to visit the children of the node given it is going 
to be pruned
-        node.setSender(leader);
-        leader.addReceiver(node);
-        _listener.onSubstitution(node.getStageId(), sender.getStageId(), 
leader.getStageId());
-      } else {
+      if (sender == leader) {
         visitMailboxSend(leader, equivalenceGroups);
+        return null;
+      }
+      if (leader.sharesReceiverStages(sender)) {
+        // The leader is already sending to this stage. Given we don't have 
the ability to send to multiple
+        // receivers in the same stage, we cannot optimize this case right now.
+        _substitutions.add(new SpoolSubstitution(node.getStageId(), 
sender.getStageId(), leader.getStageId(),
+            SpoolSubstitution.Outcome.REJECTED_SAME_RECEIVER_STAGE, null));
+        // The original sender stays in the plan, so the stages below it can 
still be shared.
+        visitMailboxSend(sender, equivalenceGroups);
+        return null;
       }
+      node.setSender(leader);
+      leader.addReceiver(node);
+      if (_guarded) {
+        SpoolDeadlockGuard.DeadlockRisk risk = 
SpoolDeadlockGuard.findRisk(_root);
+        if (risk != null) {
+          leader.removeReceiver(node);
+          node.setSender(sender);
+          _substitutions.add(new SpoolSubstitution(node.getStageId(), 
sender.getStageId(), leader.getStageId(),
+              SpoolSubstitution.Outcome.REJECTED_BY_GUARD, risk.toString()));
+          // The original sender stays in the plan, so the stages below it can 
still be shared.
+          visitMailboxSend(sender, equivalenceGroups);
+          return null;
+        }
+      }
+      // we don't want to visit the children of the node given it is going to 
be pruned
+      _listener.onSubstitution(node.getStageId(), sender.getStageId(), 
leader.getStageId());
+      _substitutions.add(new SpoolSubstitution(node.getStageId(), 
sender.getStageId(), leader.getStageId(),
+          SpoolSubstitution.Outcome.APPLIED, null));
       return null;
     }
-
-    private boolean canSubstitute(MailboxSendNode actualSender, 
MailboxSendNode leader) {
-      return actualSender != leader // we don't need to replace the leader 
with itself
-          // the leader is already sending to this stage. Given we don't have 
the ability to send to multiple
-          // receivers in the same stage, we cannot optimize this case right 
now.
-          // If this case seems to be useful, it can be supported in the 
future.
-          && !leader.sharesReceiverStages(actualSender);
-    }
   }
 }
diff --git 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/PinotLogicalQueryPlanner.java
 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/PinotLogicalQueryPlanner.java
index e01301b9852..10115b2a589 100644
--- 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/PinotLogicalQueryPlanner.java
+++ 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/PinotLogicalQueryPlanner.java
@@ -18,6 +18,9 @@
  */
 package org.apache.pinot.query.planner.logical;
 
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Iterators;
 import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
@@ -27,6 +30,7 @@ import it.unimi.dsi.fastutil.ints.IntListIterator;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Locale;
 import java.util.Map;
 import javax.annotation.Nullable;
 import org.apache.calcite.rel.RelDistribution;
@@ -34,6 +38,8 @@ import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.RelRoot;
 import org.apache.commons.lang3.tuple.Pair;
 import org.apache.pinot.calcite.rel.logical.PinotRelExchangeType;
+import org.apache.pinot.common.metrics.BrokerMeter;
+import org.apache.pinot.common.metrics.BrokerMetrics;
 import org.apache.pinot.query.context.PhysicalPlannerContext;
 import org.apache.pinot.query.planner.PlanFragment;
 import org.apache.pinot.query.planner.SubPlan;
@@ -46,22 +52,27 @@ import org.apache.pinot.query.planner.plannode.ExchangeNode;
 import org.apache.pinot.query.planner.plannode.MailboxReceiveNode;
 import org.apache.pinot.query.planner.plannode.MailboxSendNode;
 import org.apache.pinot.query.planner.plannode.PlanNode;
+import org.apache.pinot.spi.query.QueryThreadContext;
 import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
 
 
 /// PinotLogicalQueryPlanner walks top-down from [RelRoot] and construct a 
forest of trees with [PlanNode].
 public class PinotLogicalQueryPlanner {
+  /// The key of the 
[CommonConstants.Broker.Request.QueryOptionKey#SPOOLS_FEEDBACK] entry in the 
response metadata.
+  public static final String SPOOLS_RESPONSE_METADATA_KEY = "spools";
+
   private PinotLogicalQueryPlanner() {
   }
 
   /// Converts a Calcite [RelRoot] into a Pinot [SubPlan].
   public static SubPlan makePlan(RelRoot relRoot,
-      @Nullable TransformationTracker.Builder<PlanNode, RelNode> tracker, 
boolean useSpools,
-      String hashFunction, boolean pruneUnnestColumns) {
+      @Nullable TransformationTracker.Builder<PlanNode, RelNode> tracker, 
SpoolMode spoolMode,
+      boolean spoolsFeedback, String hashFunction, boolean pruneUnnestColumns) 
{
     PlanNode rootNode = new RelToPlanNodeConverter(tracker, hashFunction,
         !CommonConstants.Helix.DEFAULT_ENABLE_CASE_INSENSITIVE, 
pruneUnnestColumns).toPlanNode(relRoot.rel);
 
-    PlanFragment rootFragment = planNodeToPlanFragment(rootNode, tracker, 
useSpools, hashFunction);
+    PlanFragment rootFragment = planNodeToPlanFragment(rootNode, tracker, 
spoolMode, spoolsFeedback, hashFunction);
     return new SubPlan(rootFragment,
         new 
SubPlanMetadata(RelToPlanNodeConverter.getTableNamesFromRelRoot(relRoot.rel), 
relRoot.fields), List.of());
 
@@ -106,16 +117,19 @@ public class PinotLogicalQueryPlanner {
   }
 
   private static PlanFragment planNodeToPlanFragment(
-      PlanNode node, @Nullable TransformationTracker.Builder<PlanNode, 
RelNode> tracker, boolean useSpools,
-      String hashFunction) {
+      PlanNode node, @Nullable TransformationTracker.Builder<PlanNode, 
RelNode> tracker, SpoolMode spoolMode,
+      boolean spoolsFeedback, String hashFunction) {
     PlanFragmenter fragmenter = new PlanFragmenter();
     PlanFragmenter.Context fragmenterContext = fragmenter.createContext();
     node = node.visit(fragmenter, fragmenterContext);
 
-    if (useSpools) {
+    List<SpoolSubstitution> substitutions = List.of();
+    if (spoolMode.isEnabled()) {
       GroupedStages equivalentStages = 
EquivalentStagesFinder.findEquivalentStages(node);
-      EquivalentStagesReplacer.replaceEquivalentStages(node, equivalentStages, 
fragmenter);
+      substitutions = EquivalentStagesReplacer.replaceEquivalentStages(node, 
equivalentStages, fragmenter,
+          spoolMode.isGuarded());
     }
+    reportSpools(spoolMode, spoolsFeedback, substitutions);
 
     Int2ObjectOpenHashMap<PlanFragment> planFragmentMap = 
fragmenter.getPlanFragmentMap();
     Int2ObjectOpenHashMap<IntList> childPlanFragmentIdsMap = 
fragmenter.getChildPlanFragmentIdsMap();
@@ -161,4 +175,49 @@ public class PinotLogicalQueryPlanner {
 
     return new PlanFragment(0, rootReceiveNode, List.of(planFragment1));
   }
+
+  /// Emits the spool meters and, when `spoolsFeedback` is set, attaches a 
`spools` entry to the response metadata.
+  ///
+  /// The entry is attached even when spools are off, so that a user who asks 
why nothing was shared learns the mode.
+  private static void reportSpools(SpoolMode spoolMode, boolean spoolsFeedback,
+      List<SpoolSubstitution> substitutions) {
+    int applied = 0;
+    int rejectedByGuard = 0;
+    for (SpoolSubstitution substitution : substitutions) {
+      if (substitution.outcome() == SpoolSubstitution.Outcome.APPLIED) {
+        applied++;
+      } else if (substitution.outcome() == 
SpoolSubstitution.Outcome.REJECTED_BY_GUARD) {
+        rejectedByGuard++;
+      }
+    }
+    BrokerMetrics brokerMetrics = BrokerMetrics.get();
+    if (applied > 0) {
+      brokerMetrics.addMeteredGlobalValue(BrokerMeter.SPOOLS_APPLIED, applied);
+    }
+    if (rejectedByGuard > 0) {
+      
brokerMetrics.addMeteredGlobalValue(BrokerMeter.SPOOLS_REJECTED_BY_GUARD, 
rejectedByGuard);
+    }
+    if (spoolsFeedback) {
+      
QueryThreadContext.addResponseBrokerMetadata(SPOOLS_RESPONSE_METADATA_KEY,
+          toFeedback(spoolMode, substitutions));
+    }
+  }
+
+  @VisibleForTesting
+  static ObjectNode toFeedback(SpoolMode spoolMode, List<SpoolSubstitution> 
substitutions) {
+    ObjectNode feedback = JsonUtils.newObjectNode();
+    feedback.put("mode", spoolMode.name().toLowerCase(Locale.ROOT));
+    ArrayNode entries = feedback.putArray("substitutions");
+    for (SpoolSubstitution substitution : substitutions) {
+      ObjectNode entry = entries.addObject();
+      entry.put("receiverStage", substitution.receiverStageId());
+      entry.put("replacedStage", substitution.replacedStageId());
+      entry.put("leaderStage", substitution.leaderStageId());
+      entry.put("outcome", substitution.outcome().name());
+      if (substitution.reason() != null) {
+        entry.put("reason", substitution.reason());
+      }
+    }
+    return feedback;
+  }
 }
diff --git 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/SpoolDeadlockGuard.java
 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/SpoolDeadlockGuard.java
new file mode 100644
index 00000000000..b62f9085845
--- /dev/null
+++ 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/SpoolDeadlockGuard.java
@@ -0,0 +1,471 @@
+/**
+ * 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.planner.logical;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.BitSet;
+import java.util.Collections;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nullable;
+import org.apache.pinot.calcite.rel.logical.PinotRelExchangeType;
+import org.apache.pinot.query.planner.plannode.AggregateNode;
+import org.apache.pinot.query.planner.plannode.JoinNode;
+import org.apache.pinot.query.planner.plannode.MailboxReceiveNode;
+import org.apache.pinot.query.planner.plannode.MailboxSendNode;
+import org.apache.pinot.query.planner.plannode.PlanNode;
+import org.apache.pinot.query.planner.plannode.SetOpNode;
+import org.apache.pinot.query.planner.plannode.SortNode;
+import org.apache.pinot.query.planner.plannode.WindowNode;
+
+
+/// Detects plans where a spool can block the query until it times out.
+///
+/// A spool is a stage that sends its output to more than one consumer stage. 
It sends each block to all its
+/// consumers, so it moves at the pace of the slowest consumer: when the 
mailbox of one consumer is full, the spool
+/// stops for everybody. Some operators read one input only after another 
input finishes:
+///
+/// - A join reads its left (probe) input only after its right (build) input 
finishes.
+/// - `INTERSECT` and `EXCEPT` read their left input only after their right 
input finishes.
+/// - `UNION` reads its inputs in order: input `i` only after inputs `0` to `i 
- 1` finish.
+/// - The main operator chain of a stage reads nothing until the pipeline 
breaker of that stage finishes, and the
+///   pipeline breaker reads its own receives in round-robin with blocking 
reads.
+///
+/// Such an operator *defers* the receives in its later input behind the 
receives in its earlier input. While a
+/// deferred receive waits, nobody reads it:
+///
+/// 1. Its mailbox fills up and its sender stops.
+/// 2. The sender stops reading its inputs, and the stop moves up through 
every stage on a *streaming* path.
+/// 3. Each spool on that path stops for all its consumers.
+///
+/// A waiting receive therefore *blocks* every deferral whose earlier input 
needs one of the stopped stages: that
+/// earlier input cannot finish, so the receives that this other deferral 
defers wait too. The query blocks when the
+/// deferrals block each other in a cycle. The simplest cycle has one 
deferral: a stage that the deferred receive stops
+/// is necessary for the earlier input of the same operator. Longer cycles 
span several operators, for example two
+/// joins where each one reads, as its build input, the spool that feeds the 
probe input of the other.
+///
+/// An operator that reads its whole input before it emits its first row ends 
a streaming path: an aggregate, a
+/// window, a sort with collations, the build input of a join, and the right 
input of `INTERSECT` and `EXCEPT`. The
+/// stop does not go through it, because it has already read everything when 
the stop comes.
+///
+/// The check is conservative: it does not use the size of the data, so it 
also refuses plans whose data fits in the
+/// mailbox buffers. It also does not trust an early end of the input (for 
example a `LIMIT`) to free a spool.
+///
+/// The rules above describe the operators that the runtime builds by default. 
Aggregate and join operators are
+/// pluggable: a `QueryOperatorFactoryProvider` can replace 
`AggregateOperatorFactory` and `JoinOperatorFactory`. A
+/// replacement that reads its inputs in another way (for example an aggregate 
that emits before it reads its whole
+/// input, or a join that reads its left input first) makes this check 
unsound, and `auto` can then build a spool that
+/// blocks. Such a replacement must keep the read order of the default 
operators, or this class must learn its order.
+///
+/// This class is stateless and thread-safe.
+public final class SpoolDeadlockGuard {
+  /// Marks the absence of a shared stage in the matrix of 
[Analysis#findRisk]. Stage ids are never negative.
+  private static final int NO_STAGE = -1;
+
+  private SpoolDeadlockGuard() {
+  }
+
+  /// Returns a cycle of deferrals that can block the plan that starts at 
`root`, or null if there is none.
+  ///
+  /// `root` is the root of the plan after fragmentation: the root of stage 1, 
or any [MailboxSendNode].
+  @Nullable
+  public static DeadlockRisk findRisk(PlanNode root) {
+    return new Analysis().findRisk(root);
+  }
+
+  /// A cycle of deferrals that can block the query.
+  ///
+  /// Each element of `cycle` is a wait that cannot end until the next wait 
(the first one after the last) ends.
+  public record DeadlockRisk(List<Wait> cycle) {
+    public DeadlockRisk {
+      cycle = List.copyOf(cycle);
+    }
+
+    @Override
+    public String toString() {
+      if (cycle.size() == 1) {
+        Wait wait = cycle.get(0);
+        return wait + ", and both depend on stage " + wait.sharedStageId();
+      }
+      StringBuilder builder = new StringBuilder("Circular wait: ");
+      for (int i = 0; i < cycle.size(); i++) {
+        Wait wait = cycle.get(i);
+        if (i > 0) {
+          builder.append("; ");
+        }
+        builder.append(wait).append(", and stage 
").append(wait.blockingSenderStageId())
+            .append(" depends on stage 
").append(wait.sharedStageId()).append(", which the next wait stops");
+      }
+      return builder.toString();
+    }
+  }
+
+  /// In stage `stageId`, the `operator` reads the receive from 
`waitingSenderStageId` only after the receive from
+  /// `blockingSenderStageId` finishes. The blocking receive needs 
`sharedStageId`, a stage that the next wait of the
+  /// cycle stops.
+  public record Wait(int stageId, String operator, int waitingSenderStageId, 
int blockingSenderStageId,
+                     int sharedStageId) {
+    @Override
+    public String toString() {
+      return "In stage " + stageId + ", " + operator + " reads the input from 
stage " + waitingSenderStageId
+          + " only after the input from stage " + blockingSenderStageId + " 
finishes";
+    }
+  }
+
+  /// Two groups of receives in one stage where each receive of `waiting` is 
read only after every receive of
+  /// `blocking` finishes.
+  ///
+  /// Grouping keeps the analysis small: a `UNION` of `n` inputs creates `n - 
1` deferrals instead of one for each
+  /// pair of receives. It does not lose precision, because an operator defers 
every receive of one group behind every
+  /// receive of the other. A cycle that enters a group through one blocking 
receive and leaves it through one waiting
+  /// receive is also a cycle of that pair of receives.
+  private record Deferral(List<MailboxReceiveNode> waiting, 
List<MailboxReceiveNode> blocking, String operator) {
+  }
+
+  /// The receives of one subtree inside a stage. The lists are mutable: 
[Analysis#collect] fills them while it walks
+  /// the subtree.
+  ///
+  /// @param all every receive in the subtree
+  /// @param streaming the receives that reach the root of the subtree through 
a streaming path
+  private record Receives(List<MailboxReceiveNode> all, 
List<MailboxReceiveNode> streaming) {
+    Receives() {
+      this(new ArrayList<>(), new ArrayList<>());
+    }
+
+    void addAll(Receives other) {
+      all.addAll(other.all);
+      streaming.addAll(other.streaming);
+    }
+  }
+
+  /// What the analysis knows about one stage.
+  private record StageInfo(Receives receives, List<Deferral> deferrals) {
+  }
+
+  /// One run of the check. Not thread-safe; each call to 
[SpoolDeadlockGuard#findRisk] creates its own instance.
+  private static final class Analysis {
+    private final Map<PlanNode, StageInfo> _stageInfos = new 
IdentityHashMap<>();
+    /// For each sender, the ids of the stages that stop when nobody reads the 
output of that sender.
+    private final Map<MailboxSendNode, BitSet> _stopped = new 
IdentityHashMap<>();
+    /// For each sender, the ids of the stages that must finish before that 
sender finishes.
+    private final Map<MailboxSendNode, BitSet> _needed = new 
IdentityHashMap<>();
+
+    @Nullable
+    DeadlockRisk findRisk(PlanNode root) {
+      List<Deferral> deferrals = collectDeferrals(root);
+      int numDeferrals = deferrals.size();
+      BitSet[] stopped = new BitSet[numDeferrals];
+      BitSet[] needed = new BitSet[numDeferrals];
+      for (int i = 0; i < numDeferrals; i++) {
+        stopped[i] = new BitSet();
+        for (MailboxReceiveNode receive : deferrals.get(i).waiting()) {
+          stopped[i].or(getStopped(receive.getSender()));
+        }
+        needed[i] = new BitSet();
+        for (MailboxReceiveNode receive : deferrals.get(i).blocking()) {
+          needed[i].or(getNeeded(receive.getSender()));
+        }
+      }
+      // shared[i][j] is the id of a stage that a waiting receive of deferral 
i stops and that a blocking receive of
+      // deferral j needs, or NO_STAGE. When it is not NO_STAGE, deferral i 
blocks deferral j.
+      int[][] shared = new int[numDeferrals][numDeferrals];
+      for (int i = 0; i < numDeferrals; i++) {
+        for (int j = 0; j < numDeferrals; j++) {
+          shared[i][j] = firstShared(stopped[i], needed[j]);
+        }
+      }
+      for (int i = 0; i < numDeferrals; i++) {
+        if (shared[i][i] != NO_STAGE) {
+          return new DeadlockRisk(List.of(toWait(deferrals.get(i), 
shared[i][i], shared[i][i])));
+        }
+      }
+      List<Integer> cycle = findCycle(shared);
+      if (cycle == null) {
+        return null;
+      }
+      // In the cycle, deferral cycle[k] blocks deferral cycle[k + 1]. A wait 
describes what keeps it waiting: its
+      // blocking receive needs a stage that the next wait stops, so the waits 
are listed in the reverse order.
+      int size = cycle.size();
+      List<Wait> waits = new ArrayList<>(size);
+      for (int k = size - 1; k >= 0; k--) {
+        int blocked = cycle.get(k);
+        int blocker = cycle.get((k + size - 1) % size);
+        int successor = cycle.get((k + 1) % size);
+        waits.add(toWait(deferrals.get(blocked), shared[blocker][blocked], 
shared[blocked][successor]));
+      }
+      return new DeadlockRisk(waits);
+    }
+
+    /// Picks the pair of receives of `deferral` that forms the cycle: the 
blocking receive that needs `neededStageId`
+    /// and the waiting receive that stops `stoppedStageId`.
+    ///
+    /// Both receives exist, because the stage ids come from the union of the 
same sets over the same receives.
+    private Wait toWait(Deferral deferral, int neededStageId, int 
stoppedStageId) {
+      MailboxReceiveNode waiting = null;
+      for (MailboxReceiveNode receive : deferral.waiting()) {
+        if (getStopped(receive.getSender()).get(stoppedStageId)) {
+          waiting = receive;
+          break;
+        }
+      }
+      MailboxReceiveNode blocking = null;
+      for (MailboxReceiveNode receive : deferral.blocking()) {
+        if (getNeeded(receive.getSender()).get(neededStageId)) {
+          blocking = receive;
+          break;
+        }
+      }
+      if (waiting == null || blocking == null) {
+        throw new IllegalStateException("No receive of the " + 
deferral.operator() + " deferral stops stage "
+            + stoppedStageId + " or needs stage " + neededStageId);
+      }
+      // Both receives of a deferral belong to the stage of the operator that 
defers one behind the other.
+      return new Wait(waiting.getStageId(), deferral.operator(), 
waiting.getSenderStageId(),
+          blocking.getSenderStageId(), neededStageId);
+    }
+
+    /// Returns the deferrals of every stage reachable from `root`.
+    ///
+    /// Returns an empty list when no stage sends to more than one stage. 
Without a spool, the stages form a tree: the
+    /// subtrees of two inputs never share a stage, so no deferral can block 
itself or take part in a cycle.
+    private List<Deferral> collectDeferrals(PlanNode root) {
+      List<Deferral> result = new ArrayList<>();
+      boolean hasSpool = false;
+      ArrayDeque<PlanNode> pending = new ArrayDeque<>();
+      Set<PlanNode> visited = Collections.newSetFromMap(new 
IdentityHashMap<>());
+      pending.add(root);
+      visited.add(root);
+      while (!pending.isEmpty()) {
+        PlanNode stageRoot = pending.poll();
+        hasSpool |= stageRoot instanceof MailboxSendNode && ((MailboxSendNode) 
stageRoot).isMultiSend();
+        StageInfo info = getStageInfo(stageRoot);
+        result.addAll(info.deferrals());
+        for (MailboxReceiveNode receive : info.receives().all()) {
+          MailboxSendNode sender = receive.getSender();
+          if (visited.add(sender)) {
+            pending.add(sender);
+          }
+        }
+      }
+      return hasSpool ? result : List.of();
+    }
+
+    /// Returns the nodes of a cycle in the graph where `i -> j` exists when 
`edges[i][j]` is not [#NO_STAGE], in the
+    /// order of the edges, or null if the graph has no cycle.
+    @Nullable
+    private static List<Integer> findCycle(int[][] edges) {
+      int numNodes = edges.length;
+      // 0 = not visited, 1 = on the current path, 2 = done
+      int[] state = new int[numNodes];
+      int[] parent = new int[numNodes];
+      for (int start = 0; start < numNodes; start++) {
+        if (state[start] != 0) {
+          continue;
+        }
+        // Iterative depth-first search: next[n] is the next successor of n to 
try.
+        int[] next = new int[numNodes];
+        ArrayDeque<Integer> path = new ArrayDeque<>();
+        path.push(start);
+        state[start] = 1;
+        parent[start] = -1;
+        while (!path.isEmpty()) {
+          int node = path.peek();
+          if (next[node] == numNodes) {
+            state[node] = 2;
+            path.pop();
+            continue;
+          }
+          int successor = next[node]++;
+          if (edges[node][successor] == NO_STAGE) {
+            continue;
+          }
+          if (state[successor] == 1) {
+            List<Integer> cycle = new ArrayList<>();
+            for (int n = node; n != successor; n = parent[n]) {
+              cycle.add(n);
+            }
+            cycle.add(successor);
+            Collections.reverse(cycle);
+            return cycle;
+          }
+          if (state[successor] == 0) {
+            state[successor] = 1;
+            parent[successor] = node;
+            path.push(successor);
+          }
+        }
+      }
+      return null;
+    }
+
+    /// Returns the lowest stage id present in both sets, or [#NO_STAGE].
+    private static int firstShared(BitSet stopped, BitSet needed) {
+      if (!stopped.intersects(needed)) {
+        return NO_STAGE;
+      }
+      BitSet shared = (BitSet) stopped.clone();
+      shared.and(needed);
+      return shared.nextSetBit(0);
+    }
+
+    /// The sets are indexed by stage id. Stage ids are unique among the 
stages reachable from the root, and they are
+    /// small consecutive integers, so a [BitSet] is compact and makes each 
intersection a word-level operation.
+    private BitSet getStopped(MailboxSendNode sender) {
+      BitSet result = _stopped.get(sender);
+      if (result == null) {
+        result = new BitSet();
+        result.set(sender.getStageId());
+        for (MailboxReceiveNode receive : 
getStageInfo(sender).receives().streaming()) {
+          result.or(getStopped(receive.getSender()));
+        }
+        _stopped.put(sender, result);
+      }
+      return result;
+    }
+
+    private BitSet getNeeded(MailboxSendNode sender) {
+      BitSet result = _needed.get(sender);
+      if (result == null) {
+        result = new BitSet();
+        result.set(sender.getStageId());
+        for (MailboxReceiveNode receive : 
getStageInfo(sender).receives().all()) {
+          result.or(getNeeded(receive.getSender()));
+        }
+        _needed.put(sender, result);
+      }
+      return result;
+    }
+
+    private StageInfo getStageInfo(PlanNode stageRoot) {
+      StageInfo info = _stageInfos.get(stageRoot);
+      if (info == null) {
+        List<Deferral> deferrals = new ArrayList<>();
+        Receives receives = new Receives();
+        PlanNode treeRoot = stageRoot instanceof MailboxSendNode ? 
stageRoot.getInputs().get(0) : stageRoot;
+        receives.addAll(collect(treeRoot, deferrals));
+        addPipelineBreakerDeferrals(receives, deferrals);
+        info = new StageInfo(receives, deferrals);
+        _stageInfos.put(stageRoot, info);
+      }
+      return info;
+    }
+
+    /// The main operator chain of a stage reads nothing until the pipeline 
breaker reads all its receives.
+    ///
+    /// The pipeline breaker itself reads its receives in round-robin with 
blocking reads, so a receive that has no data
+    /// can keep the others unread. Therefore each pipeline-breaker receive 
creates one deferral: every other receive of
+    /// the stage, including the other pipeline-breaker receives, waits behind 
it.
+    private static void addPipelineBreakerDeferrals(Receives receives, 
List<Deferral> deferrals) {
+      for (MailboxReceiveNode breaker : receives.all()) {
+        if (breaker.getExchangeType() != 
PinotRelExchangeType.PIPELINE_BREAKER) {
+          continue;
+        }
+        List<MailboxReceiveNode> waiting = new 
ArrayList<>(receives.all().size() - 1);
+        for (MailboxReceiveNode receive : receives.all()) {
+          if (receive != breaker) {
+            waiting.add(receive);
+          }
+        }
+        addDeferral(waiting, List.of(breaker), "the pipeline breaker", 
deferrals);
+      }
+      // The main operator chain reads only the receives that are not 
pipeline-breaker receives.
+      receives.streaming().removeIf(receive -> receive.getExchangeType() == 
PinotRelExchangeType.PIPELINE_BREAKER);
+    }
+
+    /// Collects the receives of the subtree that starts at `node`, without 
crossing into other stages, and adds to
+    /// `deferrals` every pair of receive groups that an operator of the 
subtree reads one after the other.
+    private static Receives collect(PlanNode node, List<Deferral> deferrals) {
+      Receives result = new Receives();
+      if (node instanceof MailboxReceiveNode) {
+        MailboxReceiveNode receive = (MailboxReceiveNode) node;
+        result.all().add(receive);
+        result.streaming().add(receive);
+        return result;
+      }
+      List<Receives> inputs = new ArrayList<>(node.getInputs().size());
+      for (PlanNode input : node.getInputs()) {
+        inputs.add(collect(input, deferrals));
+      }
+      if (node instanceof JoinNode) {
+        // BaseJoinOperator reads the whole right input to build its table 
before it reads the left input.
+        Receives left = inputs.get(0);
+        Receives right = inputs.get(1);
+        addDeferral(left.all(), right.all(), "JOIN", deferrals);
+        result.all().addAll(left.all());
+        result.all().addAll(right.all());
+        result.streaming().addAll(left.streaming());
+        return result;
+      }
+      if (node instanceof SetOpNode) {
+        SetOpNode setOp = (SetOpNode) node;
+        if (setOp.getSetOpType() == SetOpNode.SetOpType.UNION) {
+          // UnionOperator and UnionAllOperator read their inputs one after 
the other, each one until it finishes.
+          List<MailboxReceiveNode> earlier = new 
ArrayList<>(inputs.get(0).all());
+          for (int i = 1; i < inputs.size(); i++) {
+            addDeferral(inputs.get(i).all(), List.copyOf(earlier), 
setOp.getSetOpType().name(), deferrals);
+            earlier.addAll(inputs.get(i).all());
+          }
+          for (Receives input : inputs) {
+            result.addAll(input);
+          }
+        } else {
+          // BinarySetOperator reads the whole right input before it reads the 
left input.
+          Receives left = inputs.get(0);
+          Receives right = inputs.get(1);
+          addDeferral(left.all(), right.all(), setOp.getSetOpType().name(), 
deferrals);
+          result.all().addAll(left.all());
+          result.all().addAll(right.all());
+          result.streaming().addAll(left.streaming());
+        }
+        return result;
+      }
+      for (Receives input : inputs) {
+        result.addAll(input);
+      }
+      if (readsWholeInputFirst(node)) {
+        result.streaming().clear();
+      }
+      return result;
+    }
+
+    /// Adds a deferral of `waiting` behind `blocking`, unless one of the 
groups is empty.
+    private static void addDeferral(List<MailboxReceiveNode> waiting, 
List<MailboxReceiveNode> blocking,
+        String operator, List<Deferral> deferrals) {
+      if (!waiting.isEmpty() && !blocking.isEmpty()) {
+        deferrals.add(new Deferral(List.copyOf(waiting), 
List.copyOf(blocking), operator));
+      }
+    }
+
+    /// Returns true for single-input operators that read their whole input 
before they emit their first row.
+    ///
+    /// The streaming group-by and distinct operators of the leaf stage emit 
before they finish, but a leaf stage
+    /// receives data only through its pipeline breaker, which 
[#addPipelineBreakerDeferrals] already treats as read
+    /// in full.
+    private static boolean readsWholeInputFirst(PlanNode node) {
+      if (node instanceof AggregateNode || node instanceof WindowNode) {
+        return true;
+      }
+      // SortOperator streams when there are no collations 
(LimitSortOperator); otherwise it buffers every row.
+      return node instanceof SortNode && !((SortNode) 
node).getCollations().isEmpty();
+    }
+  }
+}
diff --git 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/SpoolMode.java
 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/SpoolMode.java
new file mode 100644
index 00000000000..f14ae7816aa
--- /dev/null
+++ 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/SpoolMode.java
@@ -0,0 +1,72 @@
+/**
+ * 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.planner.logical;
+
+import java.util.Locale;
+
+
+/// How the multi-stage planner shares equivalent stages between consumers 
(spools).
+///
+/// A spool replaces two or more equivalent stages with one stage that sends 
its output to every consumer. A spool
+/// can block a query: the shared stage sends to all its consumers at the pace 
of the slowest one, so a consumer that
+/// reads its input only after another input finishes can stop the stage that 
feeds that other input.
+/// [SpoolDeadlockGuard] detects that case.
+///
+/// The mode comes from the 
[org.apache.pinot.spi.utils.CommonConstants.Broker#CONFIG_OF_SPOOLS] broker 
config and the
+/// 
[org.apache.pinot.spi.utils.CommonConstants.Broker.Request.QueryOptionKey#USE_SPOOLS]
 query option.
+public enum SpoolMode {
+  /// Never share stages.
+  OFF,
+  /// Share equivalent stages only when [SpoolDeadlockGuard] accepts the 
result.
+  AUTO,
+  /// Share every equivalent stage the planner supports, without the guard. 
This is the behavior of the former
+  /// `useSpools=true`.
+  ON;
+
+  /// Returns true if the planner looks for equivalent stages in this mode.
+  public boolean isEnabled() {
+    return this != OFF;
+  }
+
+  /// Returns true if the planner must verify each spool with 
[SpoolDeadlockGuard] in this mode.
+  public boolean isGuarded() {
+    return this == AUTO;
+  }
+
+  /// Parses a mode, ignoring case. `false` and `no` are aliases of [#OFF], 
and `true` and `yes` are aliases of [#ON].
+  ///
+  /// @throws IllegalArgumentException if the value is not a known mode.
+  public static SpoolMode fromString(String value) {
+    switch (value.trim().toLowerCase(Locale.ROOT)) {
+      case "off":
+      case "false":
+      case "no":
+        return OFF;
+      case "auto":
+        return AUTO;
+      case "on":
+      case "true":
+      case "yes":
+        return ON;
+      default:
+        throw new IllegalArgumentException(
+            "Invalid spool mode '" + value + "'. Valid values are: off, auto, 
on (or false, no, true, yes)");
+    }
+  }
+}
diff --git 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/SpoolSubstitution.java
 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/SpoolSubstitution.java
new file mode 100644
index 00000000000..648903b6bf8
--- /dev/null
+++ 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/SpoolSubstitution.java
@@ -0,0 +1,45 @@
+/**
+ * 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.planner.logical;
+
+import javax.annotation.Nullable;
+
+
+/// One decision of [EquivalentStagesReplacer]: whether a receive that read 
from `replacedStageId` now reads from
+/// `leaderStageId`, the stage that the replacer keeps for the equivalence 
group.
+///
+/// @param reason why the substitution was rejected, or null when it was 
applied
+public record SpoolSubstitution(int receiverStageId, int replacedStageId, int 
leaderStageId, Outcome outcome,
+                                @Nullable String reason) {
+  /// The result of a decision.
+  public enum Outcome {
+    /// The receive reads from the leader, and the replaced stage is removed 
from the plan.
+    APPLIED,
+    /// [SpoolDeadlockGuard] found that the substitution can block the query, 
so the replaced stage stays.
+    REJECTED_BY_GUARD,
+    /// The leader already sends to the stage of the receive, and a stage can 
receive from a sender only once.
+    REJECTED_SAME_RECEIVER_STAGE
+  }
+
+  @Override
+  public String toString() {
+    return "stage " + receiverStageId + ": " + replacedStageId + " -> " + 
leaderStageId + " " + outcome
+        + (reason != null ? " (" + reason + ")" : "");
+  }
+}
diff --git 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/VolatileFunctions.java
 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/VolatileFunctions.java
new file mode 100644
index 00000000000..99a1146b8a0
--- /dev/null
+++ 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/VolatileFunctions.java
@@ -0,0 +1,139 @@
+/**
+ * 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.planner.logical;
+
+import java.util.List;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.function.FunctionInfo;
+import org.apache.pinot.common.function.FunctionRegistry;
+import org.apache.pinot.common.function.PinotScalarFunction;
+import org.apache.pinot.common.function.sql.PinotSqlFunction;
+import org.apache.pinot.query.planner.plannode.AggregateNode;
+import org.apache.pinot.query.planner.plannode.FilterNode;
+import org.apache.pinot.query.planner.plannode.JoinNode;
+import org.apache.pinot.query.planner.plannode.MailboxReceiveNode;
+import org.apache.pinot.query.planner.plannode.PlanNode;
+import org.apache.pinot.query.planner.plannode.ProjectNode;
+import org.apache.pinot.query.planner.plannode.UnnestNode;
+import org.apache.pinot.query.planner.plannode.WindowNode;
+import org.apache.pinot.spi.annotations.FunctionVolatility;
+
+
+/// Finds calls to volatile functions inside one stage.
+///
+/// A stage that calls a volatile function (for example `rand()`, `uuid_v4()` 
or `now()` with non-literal arguments)
+/// can return different rows each time it runs. Two such stages are not 
equivalent even when their plans are equal:
+/// Calcite inlines common table expressions before fragmentation, so two 
equal stages can come from two independent
+/// subqueries, and each one must draw its own values. 
[EquivalentStagesFinder] never groups such a stage with another.
+///
+/// The check follows the runtime: `FunctionOperand` resolves each call with 
[FunctionRegistry], by canonical name
+/// and number of arguments, so a call is volatile when the resolved function 
is [FunctionVolatility#VOLATILE]. When
+/// the number of arguments does not select one function, the check uses the 
marks of [PinotSqlFunction], which are set
+/// when any overload is volatile or non-deterministic. Calls to functions 
that are not in the registry, such as
+/// operators and aggregation functions, are not volatile.
+///
+/// This class is stateless and thread-safe.
+final class VolatileFunctions {
+  private VolatileFunctions() {
+  }
+
+  /// Returns true if any node of the stage whose root is `stageRoot` calls a 
volatile function. The walk stops at
+  /// the receives of the stage, because the stages below have their own check.
+  static boolean callsVolatileFunction(PlanNode stageRoot) {
+    for (PlanNode input : stageRoot.getInputs()) {
+      if (subtreeCallsVolatileFunction(input)) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  private static boolean subtreeCallsVolatileFunction(PlanNode node) {
+    if (node instanceof MailboxReceiveNode) {
+      return false;
+    }
+    if (nodeCallsVolatileFunction(node)) {
+      return true;
+    }
+    for (PlanNode input : node.getInputs()) {
+      if (subtreeCallsVolatileFunction(input)) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  private static boolean nodeCallsVolatileFunction(PlanNode node) {
+    if (node instanceof FilterNode) {
+      return isVolatile(((FilterNode) node).getCondition());
+    }
+    if (node instanceof ProjectNode) {
+      return anyVolatile(((ProjectNode) node).getProjects());
+    }
+    if (node instanceof AggregateNode) {
+      return anyVolatile(((AggregateNode) node).getAggCalls());
+    }
+    if (node instanceof JoinNode) {
+      JoinNode join = (JoinNode) node;
+      return anyVolatile(join.getNonEquiConditions()) || 
isVolatile(join.getMatchCondition());
+    }
+    if (node instanceof WindowNode) {
+      return anyVolatile(((WindowNode) node).getAggCalls());
+    }
+    if (node instanceof UnnestNode) {
+      return anyVolatile(((UnnestNode) node).getArrayExprs());
+    }
+    // The other nodes hold no expression that can call a function: scans, 
sorts, set operations, values (literals
+    // only) and exchanges.
+    return false;
+  }
+
+  private static boolean anyVolatile(List<? extends RexExpression> 
expressions) {
+    for (RexExpression expression : expressions) {
+      if (isVolatile(expression)) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  private static boolean isVolatile(@Nullable RexExpression expression) {
+    if (!(expression instanceof RexExpression.FunctionCall)) {
+      return false;
+    }
+    RexExpression.FunctionCall call = (RexExpression.FunctionCall) expression;
+    return isVolatileFunction(call.getFunctionName(), 
call.getFunctionOperands().size())
+        || anyVolatile(call.getFunctionOperands());
+  }
+
+  private static boolean isVolatileFunction(String functionName, int 
numArguments) {
+    PinotScalarFunction function = 
FunctionRegistry.getFunctions().get(FunctionRegistry.canonicalize(functionName));
+    if (function == null) {
+      return false;
+    }
+    FunctionInfo functionInfo = function.getFunctionInfo(numArguments);
+    if (functionInfo != null) {
+      return functionInfo.getVolatility() == FunctionVolatility.VOLATILE;
+    }
+    // No function matches this number of arguments by count alone. Fall back 
to the marks of the SQL function, which
+    // are conservative across overloads. Functions without one (operators 
registered elsewhere) are not volatile.
+    PinotSqlFunction sqlFunction = function.toPinotSqlFunction();
+    return sqlFunction != null && (sqlFunction.isVolatile() || 
!sqlFunction.isDeterministic());
+  }
+}
diff --git 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/plannode/MailboxSendNode.java
 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/plannode/MailboxSendNode.java
index e82950875a2..a7491405bf3 100644
--- 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/plannode/MailboxSendNode.java
+++ 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/plannode/MailboxSendNode.java
@@ -130,6 +130,14 @@ public class MailboxSendNode extends BasePlanNode {
     _receiverStages.set(node.getStageId());
   }
 
+  /// Undoes [#addReceiver(MailboxReceiveNode)].
+  public void removeReceiver(MailboxReceiveNode node) {
+    if (!_receiverStages.get(node.getStageId())) {
+      throw new IllegalStateException("Receiver not present: " + 
node.getStageId());
+    }
+    _receiverStages.clear(node.getStageId());
+  }
+
   public PinotRelExchangeType getExchangeType() {
     return _exchangeType;
   }
diff --git 
a/pinot-query-planner/src/test/java/org/apache/pinot/query/QueryEnvironmentSpoolOptionsTest.java
 
b/pinot-query-planner/src/test/java/org/apache/pinot/query/QueryEnvironmentSpoolOptionsTest.java
new file mode 100644
index 00000000000..b1092a81717
--- /dev/null
+++ 
b/pinot-query-planner/src/test/java/org/apache/pinot/query/QueryEnvironmentSpoolOptionsTest.java
@@ -0,0 +1,49 @@
+/**
+ * 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.Map;
+import org.apache.pinot.spi.exception.QueryErrorCode;
+import org.apache.pinot.spi.exception.QueryException;
+import 
org.apache.pinot.spi.utils.CommonConstants.Broker.Request.QueryOptionKey;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.expectThrows;
+
+
+/// Tests how [QueryEnvironment] reads the spool query options.
+public class QueryEnvironmentSpoolOptionsTest {
+
+  @Test
+  public void spoolsFeedbackAcceptsBooleans() {
+    assertFalse(QueryEnvironment.isSpoolsFeedback(Map.of()));
+    
assertTrue(QueryEnvironment.isSpoolsFeedback(Map.of(QueryOptionKey.SPOOLS_FEEDBACK,
 "true")));
+    
assertFalse(QueryEnvironment.isSpoolsFeedback(Map.of(QueryOptionKey.SPOOLS_FEEDBACK,
 "false")));
+  }
+
+  @Test
+  public void invalidSpoolsFeedbackIsAValidationError() {
+    QueryException e = expectThrows(QueryException.class,
+        () -> 
QueryEnvironment.isSpoolsFeedback(Map.of(QueryOptionKey.SPOOLS_FEEDBACK, 
"yes")));
+    assertEquals(e.getErrorCode(), QueryErrorCode.QUERY_VALIDATION);
+  }
+}
diff --git 
a/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/EquivalentStagesFinderTest.java
 
b/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/EquivalentStagesFinderTest.java
index 07f961c301a..c5e1ed7b6f9 100644
--- 
a/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/EquivalentStagesFinderTest.java
+++ 
b/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/EquivalentStagesFinderTest.java
@@ -414,4 +414,65 @@ public class EquivalentStagesFinderTest extends 
StagesTestBase {
     GroupedStages groupedStages = 
EquivalentStagesFinder.findEquivalentStages(stage(0));
     assertEquals(groupedStages.toString(), "[[0], [1], [2, 3]]");
   }
+
+  /// `rand() < 0.1` as a filter condition. `rand()` without arguments is 
volatile.
+  private static RexExpression randomSample() {
+    RexExpression.FunctionCall rand =
+        new RexExpression.FunctionCall(DataSchema.ColumnDataType.DOUBLE, 
"rand", List.of());
+    return new RexExpression.FunctionCall(DataSchema.ColumnDataType.BOOLEAN, 
SqlKind.LESS_THAN.name(),
+        List.of(rand, new 
RexExpression.Literal(DataSchema.ColumnDataType.DOUBLE, 0.1)));
+  }
+
+  /// Two equal stages that call a volatile function come from two subqueries 
that must draw their own values, so they
+  /// are not equivalent. The stages above them are not equivalent either.
+  @Test
+  public void stagesThatCallVolatileFunctionsAreNotEquivalent() {
+    when(
+        join(
+            exchange(1, aggregate(exchange(2, filter(tableScan("T1"), 
randomSample())), List.of())),
+            exchange(3, aggregate(exchange(4, filter(tableScan("T1"), 
randomSample())), List.of()))
+        )
+    );
+    GroupedStages result = 
EquivalentStagesFinder.findEquivalentStages(stage(0));
+    assertEquals(result.toString(), "[[0], [1], [2], [3], [4]]");
+  }
+
+  /// `rand(seed)` is deterministic, so the same equal stages are equivalent.
+  @Test
+  public void stagesThatCallSeededRandAreEquivalent() {
+    RexExpression.FunctionCall seededRand = new 
RexExpression.FunctionCall(DataSchema.ColumnDataType.DOUBLE, "rand",
+        List.of(new RexExpression.Literal(DataSchema.ColumnDataType.LONG, 
42L)));
+    RexExpression threshold = new 
RexExpression.Literal(DataSchema.ColumnDataType.DOUBLE, 0.1);
+    RexExpression condition = new 
RexExpression.FunctionCall(DataSchema.ColumnDataType.BOOLEAN,
+        SqlKind.LESS_THAN.name(), List.of(seededRand, threshold));
+    when(
+        join(
+            exchange(1, aggregate(exchange(2, filter(tableScan("T1"), 
condition)), List.of())),
+            exchange(3, aggregate(exchange(4, filter(tableScan("T1"), 
condition)), List.of()))
+        )
+    );
+    GroupedStages result = 
EquivalentStagesFinder.findEquivalentStages(stage(0));
+    assertEquals(result.toString(), "[[0], [1, 3], [2, 4]]");
+  }
+
+  /// A volatile call nested inside another expression also makes the stage 
volatile.
+  @Test
+  public void nestedVolatileCallsAreFound() {
+    RexExpression.FunctionCall rand =
+        new RexExpression.FunctionCall(DataSchema.ColumnDataType.DOUBLE, 
"rand", List.of());
+    RexExpression nested = new 
RexExpression.FunctionCall(DataSchema.ColumnDataType.BOOLEAN, 
SqlKind.AND.name(),
+        List.of(new RexExpression.Literal(DataSchema.ColumnDataType.BOOLEAN, 
1),
+            new RexExpression.FunctionCall(DataSchema.ColumnDataType.BOOLEAN, 
SqlKind.GREATER_THAN.name(),
+                List.of(new 
RexExpression.FunctionCall(DataSchema.ColumnDataType.DOUBLE, "plus",
+                    List.of(rand, new 
RexExpression.Literal(DataSchema.ColumnDataType.DOUBLE, 1.0))),
+                    new 
RexExpression.Literal(DataSchema.ColumnDataType.DOUBLE, 1.5)))));
+    when(
+        join(
+            exchange(1, filter(tableScan("T1"), nested)),
+            exchange(2, filter(tableScan("T1"), nested))
+        )
+    );
+    GroupedStages result = 
EquivalentStagesFinder.findEquivalentStages(stage(0));
+    assertEquals(result.toString(), "[[0], [1], [2]]");
+  }
 }
diff --git 
a/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/EquivalentStagesReplacerTest.java
 
b/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/EquivalentStagesReplacerTest.java
index 830c8a2d78f..6745026ac38 100644
--- 
a/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/EquivalentStagesReplacerTest.java
+++ 
b/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/EquivalentStagesReplacerTest.java
@@ -18,6 +18,7 @@
  */
 package org.apache.pinot.query.planner.logical;
 
+import java.util.List;
 import org.apache.pinot.query.planner.plannode.MailboxSendNode;
 import org.testng.annotations.Test;
 
@@ -91,7 +92,9 @@ public class EquivalentStagesReplacerTest extends 
StagesTestBase {
     assertEquals(groupedStages.toString(), "[[0], [1], [2, 3]]");
 
     MailboxSendNode rootStage = stage(0);
-    EquivalentStagesReplacer.replaceEquivalentStages(rootStage, groupedStages);
+    List<SpoolSubstitution> substitutions = 
EquivalentStagesReplacer.replaceEquivalentStages(rootStage,
+        groupedStages, EquivalentStagesReplacer.OnSubstitution.NO_OP, false);
+    assertEquals(substitutions.toString(), "[stage 1: 3 -> 2 
REJECTED_SAME_RECEIVER_STAGE]");
 
     cleanup();
     MailboxSendNode expected = when(// stage 0
@@ -105,6 +108,95 @@ public class EquivalentStagesReplacerTest extends 
StagesTestBase {
     assertEqualPlan(rootStage, expected);
   }
 
+  /// Same plan as [#test()]. Stage 1 reads stage 2 (the probe input) only 
after stage 5 finishes, and both depend on
+  /// the scan of T1, so the guard refuses to share it.
+  @Test
+  void guardRejectsSpoolThatCanBlock() {
+    when(// stage 0
+        exchange(1,
+            join(
+                exchange(2,
+                    join(
+                        exchange(3, tableScan("T1")),
+                        exchange(4, tableScan("T2"))
+                    )
+                ),
+                exchange(5,
+                    join(
+                        exchange(6, tableScan("T1")),
+                        exchange(7, tableScan("T3"))
+                    )
+                )
+            )
+        )
+    );
+    GroupedStages groupedStages = 
EquivalentStagesFinder.findEquivalentStages(stage(0));
+    MailboxSendNode rootStage = stage(0);
+    List<SpoolSubstitution> substitutions = 
EquivalentStagesReplacer.replaceEquivalentStages(rootStage,
+        groupedStages, EquivalentStagesReplacer.OnSubstitution.NO_OP, true);
+    assertEquals(substitutions.size(), 1);
+    SpoolSubstitution substitution = substitutions.get(0);
+    assertEquals(substitution.outcome(), 
SpoolSubstitution.Outcome.REJECTED_BY_GUARD);
+    assertEquals(substitution.receiverStageId(), 5);
+    assertEquals(substitution.replacedStageId(), 6);
+    assertEquals(substitution.leaderStageId(), 3);
+    assertEquals(substitution.reason(), "In stage 1, JOIN reads the input from 
stage 2 only after the input from "
+        + "stage 5 finishes, and both depend on stage 3");
+
+    cleanup();
+    MailboxSendNode expected = when(// stage 0
+        exchange(1,
+            join(
+                exchange(2,
+                    join(
+                        exchange(3, tableScan("T1")),
+                        exchange(4, tableScan("T2"))
+                    )
+                ),
+                exchange(5,
+                    join(
+                        exchange(6, tableScan("T1")),
+                        exchange(7, tableScan("T3"))
+                    )
+                )
+            )
+        )
+    );
+    assertEqualPlan(rootStage, expected);
+  }
+
+  /// Each consumer of the scan aggregates it, so the aggregates read the 
whole scan before the join of stage 1 waits.
+  @Test
+  void guardAcceptsSpoolWhenAggregatesReadItFirst() {
+    when(// stage 0
+        exchange(1,
+            join(
+                exchange(2, aggregate(exchange(3, tableScan("T1")), 
List.of())),
+                exchange(4, aggregate(exchange(5, tableScan("T1")), 
List.of(List.of(0))))
+            )
+        )
+    );
+    GroupedStages groupedStages = 
EquivalentStagesFinder.findEquivalentStages(stage(0));
+    assertEquals(groupedStages.toString(), "[[0], [1], [2], [3, 5], [4]]");
+
+    MailboxSendNode rootStage = stage(0);
+    List<SpoolSubstitution> substitutions = 
EquivalentStagesReplacer.replaceEquivalentStages(rootStage,
+        groupedStages, EquivalentStagesReplacer.OnSubstitution.NO_OP, true);
+    assertEquals(substitutions.toString(), "[stage 4: 5 -> 3 APPLIED]");
+
+    cleanup();
+    SpoolBuilder readT1 = new SpoolBuilder(3, tableScan("T1"));
+    MailboxSendNode expected = when(// stage 0
+        exchange(1,
+            join(
+                exchange(2, aggregate(readT1.newReceiver(), List.of())),
+                exchange(4, aggregate(readT1.newReceiver(), 
List.of(List.of(0))))
+            )
+        )
+    );
+    assertEqualPlan(rootStage, expected);
+  }
+
   @Test
   void groupSendingToTheSameStage() {
     when(// stage 0
diff --git 
a/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/PinotLogicalQueryPlannerSpoolFeedbackTest.java
 
b/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/PinotLogicalQueryPlannerSpoolFeedbackTest.java
new file mode 100644
index 00000000000..0ed43046cf5
--- /dev/null
+++ 
b/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/PinotLogicalQueryPlannerSpoolFeedbackTest.java
@@ -0,0 +1,50 @@
+/**
+ * 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.planner.logical;
+
+import java.util.List;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+
+
+public class PinotLogicalQueryPlannerSpoolFeedbackTest {
+
+  @Test
+  public void feedbackListsEverySubstitution()
+      throws Exception {
+    List<SpoolSubstitution> substitutions = List.of(
+        new SpoolSubstitution(4, 5, 3, SpoolSubstitution.Outcome.APPLIED, 
null),
+        new SpoolSubstitution(6, 7, 3, 
SpoolSubstitution.Outcome.REJECTED_BY_GUARD, "some reason"));
+    String expected = "{\"mode\":\"auto\",\"substitutions\":["
+        + 
"{\"receiverStage\":4,\"replacedStage\":5,\"leaderStage\":3,\"outcome\":\"APPLIED\"},"
+        + 
"{\"receiverStage\":6,\"replacedStage\":7,\"leaderStage\":3,\"outcome\":\"REJECTED_BY_GUARD\","
+        + "\"reason\":\"some reason\"}]}";
+    assertEquals(PinotLogicalQueryPlanner.toFeedback(SpoolMode.AUTO, 
substitutions),
+        JsonUtils.stringToJsonNode(expected));
+  }
+
+  @Test
+  public void feedbackReportsTheModeWhenSpoolsAreOff()
+      throws Exception {
+    assertEquals(PinotLogicalQueryPlanner.toFeedback(SpoolMode.OFF, List.of()),
+        JsonUtils.stringToJsonNode("{\"mode\":\"off\",\"substitutions\":[]}"));
+  }
+}
diff --git 
a/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/SpoolDeadlockGuardTest.java
 
b/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/SpoolDeadlockGuardTest.java
new file mode 100644
index 00000000000..38fddac77ce
--- /dev/null
+++ 
b/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/SpoolDeadlockGuardTest.java
@@ -0,0 +1,324 @@
+/**
+ * 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.planner.logical;
+
+import java.util.List;
+import java.util.Set;
+import javax.annotation.Nullable;
+import org.apache.pinot.query.planner.plannode.MailboxSendNode;
+import org.apache.pinot.query.planner.plannode.SetOpNode;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertNull;
+
+
+public class SpoolDeadlockGuardTest extends StagesTestBase {
+
+  @Test
+  public void treeHasNoRisk() {
+    MailboxSendNode root = when(
+        exchange(1,
+            join(
+                exchange(2, tableScan("T1")),
+                exchange(3, tableScan("T1"))
+            )
+        )
+    );
+    assertNull(SpoolDeadlockGuard.findRisk(root));
+  }
+
+  /// The spool feeds the probe input of stage 1 through stage 2, and the 
build input through stage 5.
+  @Test
+  public void spoolOnBothSidesOfAJoinThroughStreamingStages() {
+    SpoolBuilder spool = new SpoolBuilder(3, tableScan("T1"));
+    MailboxSendNode root = when(
+        exchange(1,
+            join(
+                exchange(2, join(spool.newReceiver(), exchange(4, 
tableScan("T2")))),
+                exchange(5, join(spool.newReceiver(), exchange(6, 
tableScan("T3"))))
+            )
+        )
+    );
+    assertRisk(SpoolDeadlockGuard.findRisk(root), 1, "JOIN", 2, 5, 3);
+  }
+
+  @Test
+  public void spoolFeedsProbeDirectly() {
+    SpoolBuilder spool = new SpoolBuilder(3, tableScan("T1"));
+    MailboxSendNode root = when(
+        exchange(1,
+            join(
+                exchange(2, spool.newReceiver()),
+                exchange(4, spool.newReceiver())
+            )
+        )
+    );
+    assertRisk(SpoolDeadlockGuard.findRisk(root), 1, "JOIN", 2, 4, 3);
+  }
+
+  /// The aggregate in stage 2 reads the whole spool before stage 1 starts to 
wait for the probe input.
+  @Test
+  public void aggregateOnProbePathReadsTheWholeSpool() {
+    SpoolBuilder spool = new SpoolBuilder(3, tableScan("T1"));
+    MailboxSendNode root = when(
+        exchange(1,
+            join(
+                exchange(2, aggregate(spool.newReceiver(), List.of())),
+                exchange(4, spool.newReceiver())
+            )
+        )
+    );
+    assertNull(SpoolDeadlockGuard.findRisk(root));
+  }
+
+  @Test
+  public void windowOnProbePathReadsTheWholeSpool() {
+    SpoolBuilder spool = new SpoolBuilder(3, tableScan("T1"));
+    MailboxSendNode root = when(
+        exchange(1,
+            join(
+                exchange(2, window(spool.newReceiver(), 
lastValueRespectingNulls())),
+                exchange(4, spool.newReceiver())
+            )
+        )
+    );
+    assertNull(SpoolDeadlockGuard.findRisk(root));
+  }
+
+  @Test
+  public void sortOnProbePathReadsTheWholeSpool() {
+    SpoolBuilder spool = new SpoolBuilder(3, tableScan("T1"));
+    MailboxSendNode root = when(
+        exchange(1,
+            join(
+                exchange(2, sort(spool.newReceiver())),
+                exchange(4, spool.newReceiver())
+            )
+        )
+    );
+    assertNull(SpoolDeadlockGuard.findRisk(root));
+  }
+
+  /// A sort without collations is a streaming limit, so it does not protect 
the spool.
+  @Test
+  public void limitOnProbePathStreams() {
+    SpoolBuilder spool = new SpoolBuilder(3, tableScan("T1"));
+    MailboxSendNode root = when(
+        exchange(1,
+            join(
+                exchange(2, limit(spool.newReceiver(), 10)),
+                exchange(4, spool.newReceiver())
+            )
+        )
+    );
+    assertRisk(SpoolDeadlockGuard.findRisk(root), 1, "JOIN", 2, 4, 3);
+  }
+
+  /// Stage 2 reads the spool as the build input of its own join, so the spool 
is read in full before stage 2 emits.
+  @Test
+  public void buildInputOnProbePathReadsTheWholeSpool() {
+    SpoolBuilder spool = new SpoolBuilder(3, tableScan("T1"));
+    MailboxSendNode root = when(
+        exchange(1,
+            join(
+                exchange(2, join(exchange(5, tableScan("T2")), 
spool.newReceiver())),
+                exchange(4, spool.newReceiver())
+            )
+        )
+    );
+    assertNull(SpoolDeadlockGuard.findRisk(root));
+  }
+
+  @Test
+  public void unionReadsItsInputsInOrder() {
+    SpoolBuilder spool = new SpoolBuilder(3, tableScan("T1"));
+    MailboxSendNode root = when(
+        exchange(1,
+            setOp(SetOpNode.SetOpType.UNION, List.of(
+                exchange(2, spool.newReceiver()),
+                exchange(4, spool.newReceiver())
+            ))
+        )
+    );
+    assertRisk(SpoolDeadlockGuard.findRisk(root), 1, "UNION", 4, 2, 3);
+  }
+
+  /// Input 2 waits behind inputs 0 and 1, but only input 1 needs the spool. 
The risk names that pair of receives.
+  @Test
+  public void unionDefersEachInputBehindAllEarlierInputs() {
+    SpoolBuilder spool = new SpoolBuilder(3, tableScan("T1"));
+    MailboxSendNode root = when(
+        exchange(1,
+            setOp(SetOpNode.SetOpType.UNION, List.of(
+                exchange(5, tableScan("T2")),
+                exchange(2, spool.newReceiver()),
+                exchange(4, spool.newReceiver())
+            ))
+        )
+    );
+    assertRisk(SpoolDeadlockGuard.findRisk(root), 1, "UNION", 4, 2, 3);
+  }
+
+  /// Both receives of the probe input wait behind the build input, but only 
stage 2 stops the spool. The risk names
+  /// that receive.
+  @Test
+  public void joinNamesTheProbeReceiveThatStopsTheSpool() {
+    SpoolBuilder spool = new SpoolBuilder(3, tableScan("T1"));
+    MailboxSendNode root = when(
+        exchange(1,
+            join(
+                setOp(SetOpNode.SetOpType.UNION, List.of(
+                    exchange(5, tableScan("T2")),
+                    exchange(2, spool.newReceiver())
+                )),
+                exchange(4, spool.newReceiver())
+            )
+        )
+    );
+    assertRisk(SpoolDeadlockGuard.findRisk(root), 1, "JOIN", 2, 4, 3);
+  }
+
+  @Test
+  public void unionWithAggregateOnLaterInput() {
+    SpoolBuilder spool = new SpoolBuilder(3, tableScan("T1"));
+    MailboxSendNode root = when(
+        exchange(1,
+            setOp(SetOpNode.SetOpType.UNION, List.of(
+                exchange(2, spool.newReceiver()),
+                exchange(4, aggregate(spool.newReceiver(), List.of()))
+            ))
+        )
+    );
+    assertNull(SpoolDeadlockGuard.findRisk(root));
+  }
+
+  @Test
+  public void intersectReadsRightInputFirst() {
+    SpoolBuilder spool = new SpoolBuilder(3, tableScan("T1"));
+    MailboxSendNode root = when(
+        exchange(1,
+            setOp(SetOpNode.SetOpType.INTERSECT, List.of(
+                exchange(2, spool.newReceiver()),
+                exchange(4, spool.newReceiver())
+            ))
+        )
+    );
+    assertRisk(SpoolDeadlockGuard.findRisk(root), 1, "INTERSECT", 2, 4, 3);
+  }
+
+  /// The join alone is safe here, because the aggregate in stage 2 reads the 
whole spool. The pipeline breaker is not:
+  /// stage 1 reads stage 4 only after the pipeline breaker reads stage 2 in 
full, and both need the spool.
+  @Test
+  public void pipelineBreakerDefersTheMainReceives() {
+    SpoolBuilder spool = new SpoolBuilder(3, tableScan("T1"));
+    MailboxSendNode root = when(
+        exchange(1,
+            join(
+                exchange(2, aggregate(spool.newReceiver(), 
List.of())).asPipelineBreaker(),
+                exchange(4, spool.newReceiver())
+            )
+        )
+    );
+    assertRisk(SpoolDeadlockGuard.findRisk(root), 1, "the pipeline breaker", 
4, 2, 3);
+  }
+
+  /// Both receives belong to the pipeline breaker, which reads them in 
round-robin with blocking reads. The join alone
+  /// is safe, because the aggregate in stage 2 reads the whole spool. But a 
blocking read on stage 2 keeps stage 4
+  /// unread, and stage 4 stops the spool that stage 2 needs.
+  @Test
+  public void pipelineBreakerReceivesDeferEachOther() {
+    SpoolBuilder spool = new SpoolBuilder(3, tableScan("T1"));
+    MailboxSendNode root = when(
+        exchange(1,
+            join(
+                exchange(2, aggregate(spool.newReceiver(), 
List.of())).asPipelineBreaker(),
+                exchange(4, spool.newReceiver()).asPipelineBreaker()
+            )
+        )
+    );
+    assertRisk(SpoolDeadlockGuard.findRisk(root), 1, "the pipeline breaker", 
4, 2, 3);
+  }
+
+  /// Two joins read the same two spools with the sides swapped. Each join 
alone is safe: its probe spool is not
+  /// needed by its own build input. Together they block: stage 2 waits for 
spool 4 to finish its build input while
+  /// spool 4 stops because stage 6 does not read its probe input, and stage 6 
waits for spool 3 in the same way.
+  @Test
+  public void joinsWithSwappedSidesBlockEachOther() {
+    SpoolBuilder spoolA = new SpoolBuilder(3, tableScan("A"));
+    SpoolBuilder spoolB = new SpoolBuilder(4, tableScan("B"));
+    MailboxSendNode root = when(
+        exchange(1,
+            setOp(SetOpNode.SetOpType.UNION, List.of(
+                exchange(2, aggregate(join(spoolA.newReceiver(), 
spoolB.newReceiver()), List.of())),
+                exchange(6, aggregate(join(spoolB.newReceiver(), 
spoolA.newReceiver()), List.of()))
+            ))
+        )
+    );
+    SpoolDeadlockGuard.DeadlockRisk risk = SpoolDeadlockGuard.findRisk(root);
+    assertNotNull(risk, "Expected a circular wait");
+    List<SpoolDeadlockGuard.Wait> cycle = risk.cycle();
+    assertEquals(cycle.size(), 2, risk.toString());
+    for (SpoolDeadlockGuard.Wait wait : cycle) {
+      assertEquals(wait.operator(), "JOIN", risk.toString());
+      // Each wait is kept by the spool it reads as build input, which the 
other wait stops.
+      assertEquals(wait.sharedStageId(), wait.blockingSenderStageId(), 
risk.toString());
+    }
+    assertEquals(Set.of(cycle.get(0).stageId(), cycle.get(1).stageId()), 
Set.of(2, 6), risk.toString());
+    assertEquals(risk.toString(), "Circular wait: "
+        + "In stage " + cycle.get(0).stageId() + ", JOIN reads the input from 
stage "
+        + cycle.get(0).waitingSenderStageId() + " only after the input from 
stage "
+        + cycle.get(0).blockingSenderStageId() + " finishes, and stage " + 
cycle.get(0).blockingSenderStageId()
+        + " depends on stage " + cycle.get(0).sharedStageId() + ", which the 
next wait stops; "
+        + "In stage " + cycle.get(1).stageId() + ", JOIN reads the input from 
stage "
+        + cycle.get(1).waitingSenderStageId() + " only after the input from 
stage "
+        + cycle.get(1).blockingSenderStageId() + " finishes, and stage " + 
cycle.get(1).blockingSenderStageId()
+        + " depends on stage " + cycle.get(1).sharedStageId() + ", which the 
next wait stops");
+  }
+
+  /// Same shape as [#joinsWithSwappedSidesBlockEachOther()], but both joins 
read spool 3 as the build input. Spool 3
+  /// is drained by both builds, so no wait stops it, and there is no cycle.
+  @Test
+  public void joinsWithTheSameSidesDoNotBlock() {
+    SpoolBuilder spoolA = new SpoolBuilder(3, tableScan("A"));
+    SpoolBuilder spoolB = new SpoolBuilder(4, tableScan("B"));
+    MailboxSendNode root = when(
+        exchange(1,
+            setOp(SetOpNode.SetOpType.UNION, List.of(
+                exchange(2, aggregate(join(spoolB.newReceiver(), 
spoolA.newReceiver()), List.of())),
+                exchange(6, aggregate(join(spoolB.newReceiver(), 
spoolA.newReceiver()), List.of(List.of(0))))
+            ))
+        )
+    );
+    assertNull(SpoolDeadlockGuard.findRisk(root));
+  }
+
+  private static void assertRisk(@Nullable SpoolDeadlockGuard.DeadlockRisk 
risk, int stageId, String operator,
+      int waitingSenderStageId, int blockingSenderStageId, int sharedStageId) {
+    assertNotNull(risk, "Expected a deadlock risk");
+    assertEquals(risk.cycle().size(), 1, risk.toString());
+    SpoolDeadlockGuard.Wait wait = risk.cycle().get(0);
+    assertEquals(wait.stageId(), stageId, risk.toString());
+    assertEquals(wait.operator(), operator, risk.toString());
+    assertEquals(wait.waitingSenderStageId(), waitingSenderStageId, 
risk.toString());
+    assertEquals(wait.blockingSenderStageId(), blockingSenderStageId, 
risk.toString());
+    assertEquals(wait.sharedStageId(), sharedStageId, risk.toString());
+  }
+}
diff --git 
a/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/SpoolModeTest.java
 
b/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/SpoolModeTest.java
new file mode 100644
index 00000000000..b56b3725068
--- /dev/null
+++ 
b/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/SpoolModeTest.java
@@ -0,0 +1,62 @@
+/**
+ * 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.planner.logical;
+
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertThrows;
+import static org.testng.Assert.assertTrue;
+
+
+public class SpoolModeTest {
+
+  @DataProvider
+  public static Object[][] validValues() {
+    return new Object[][]{
+        {"off", SpoolMode.OFF}, {"OFF", SpoolMode.OFF}, {"false", 
SpoolMode.OFF}, {"False", SpoolMode.OFF},
+        {"no", SpoolMode.OFF}, {"NO", SpoolMode.OFF},
+        {"auto", SpoolMode.AUTO}, {" Auto ", SpoolMode.AUTO},
+        {"on", SpoolMode.ON}, {"true", SpoolMode.ON}, {"TRUE", SpoolMode.ON},
+        {"yes", SpoolMode.ON}, {"Yes", SpoolMode.ON}
+    };
+  }
+
+  @Test(dataProvider = "validValues")
+  public void fromString(String value, SpoolMode expected) {
+    assertEquals(SpoolMode.fromString(value), expected);
+  }
+
+  @Test
+  public void fromStringRejectsUnknownValues() {
+    assertThrows(IllegalArgumentException.class, () -> 
SpoolMode.fromString("1"));
+    assertThrows(IllegalArgumentException.class, () -> 
SpoolMode.fromString(""));
+  }
+
+  @Test
+  public void flags() {
+    assertFalse(SpoolMode.OFF.isEnabled());
+    assertTrue(SpoolMode.AUTO.isEnabled());
+    assertTrue(SpoolMode.ON.isEnabled());
+    assertTrue(SpoolMode.AUTO.isGuarded());
+    assertFalse(SpoolMode.ON.isGuarded());
+  }
+}
diff --git 
a/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/StagesTestBase.java
 
b/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/StagesTestBase.java
index 8184392e1a4..8651b9219b4 100644
--- 
a/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/StagesTestBase.java
+++ 
b/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/logical/StagesTestBase.java
@@ -20,6 +20,7 @@ package org.apache.pinot.query.planner.logical;
 
 import com.google.common.base.Function;
 import com.google.common.base.Preconditions;
+import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.IdentityHashMap;
@@ -35,11 +36,14 @@ import 
org.apache.pinot.calcite.rel.logical.PinotRelExchangeType;
 import org.apache.pinot.common.utils.DataSchema;
 import org.apache.pinot.query.planner.partitioning.KeySelector;
 import org.apache.pinot.query.planner.plannode.AggregateNode;
+import org.apache.pinot.query.planner.plannode.FilterNode;
 import org.apache.pinot.query.planner.plannode.JoinNode;
 import org.apache.pinot.query.planner.plannode.MailboxReceiveNode;
 import org.apache.pinot.query.planner.plannode.MailboxSendNode;
 import org.apache.pinot.query.planner.plannode.PlanNode;
 import org.apache.pinot.query.planner.plannode.PlanNodeVisitor;
+import org.apache.pinot.query.planner.plannode.SetOpNode;
+import org.apache.pinot.query.planner.plannode.SortNode;
 import org.apache.pinot.query.planner.plannode.TableScanNode;
 import org.apache.pinot.query.planner.plannode.UnnestNode;
 import org.apache.pinot.query.planner.plannode.WindowNode;
@@ -135,6 +139,13 @@ public class StagesTestBase {
       return build(stageId, null, null, null, null, null, false, null, false, 
false);
     }
 
+    /// Returns a builder whose receive and send nodes use the 
[PinotRelExchangeType#PIPELINE_BREAKER] exchange type.
+    default ExchangeBuilder asPipelineBreaker() {
+      return (stageId, dataSchema, hints, _, distribution, keys, 
prePartitioned, collations, sort, sortedOnSender) ->
+          build(stageId, dataSchema, hints, 
PinotRelExchangeType.PIPELINE_BREAKER, distribution, keys, prePartitioned,
+              collations, sort, sortedOnSender);
+    }
+
     default ExchangeBuilder withDistributionType(RelDistribution.Type 
distribution) {
       return (stageId, dataSchema, hints, exchangeType, _, keys, 
prePartitioned, collations, sort, sortedOnSender) ->
           build(stageId, dataSchema, hints, exchangeType, distribution, keys, 
prePartitioned, collations, sort,
@@ -142,6 +153,46 @@ public class StagesTestBase {
     }
   }
 
+  /// Creates a set operation node of the given type over the given inputs, 
with `all` set to true.
+  public SimpleChildBuilder<SetOpNode> setOp(SetOpNode.SetOpType setOpType,
+      List<SimpleChildBuilder<? extends PlanNode>> inputBuilders) {
+    return (stageId, mySchema, myHints) -> {
+      List<PlanNode> inputs = new ArrayList<>(inputBuilders.size());
+      for (SimpleChildBuilder<? extends PlanNode> inputBuilder : 
inputBuilders) {
+        inputs.add(inputBuilder.build(stageId));
+      }
+      return new SetOpNode(stageId, mySchema, myHints, inputs, setOpType, 
true);
+    };
+  }
+
+  /// Creates a filter node with the given condition over the given child.
+  public SimpleChildBuilder<FilterNode> filter(SimpleChildBuilder<? extends 
PlanNode> childBuilder,
+      RexExpression condition) {
+    return (stageId, mySchema, myHints) -> {
+      PlanNode input = childBuilder.build(stageId);
+      DataSchema schema = mySchema != null ? mySchema : input.getDataSchema();
+      return new FilterNode(stageId, schema, myHints, List.of(input), 
condition);
+    };
+  }
+
+  /// Creates a sort node that orders by the first column, without a limit.
+  public SimpleChildBuilder<SortNode> sort(SimpleChildBuilder<? extends 
PlanNode> childBuilder) {
+    return (stageId, mySchema, myHints) -> {
+      PlanNode input = childBuilder.build(stageId);
+      DataSchema schema = mySchema != null ? mySchema : input.getDataSchema();
+      return new SortNode(stageId, schema, myHints, List.of(input), 
List.of(new RelFieldCollation(0)), -1, 0);
+    };
+  }
+
+  /// Creates a sort node with the given limit and no collations.
+  public SimpleChildBuilder<SortNode> limit(SimpleChildBuilder<? extends 
PlanNode> childBuilder, int fetch) {
+    return (stageId, mySchema, myHints) -> {
+      PlanNode input = childBuilder.build(stageId);
+      DataSchema schema = mySchema != null ? mySchema : input.getDataSchema();
+      return new SortNode(stageId, schema, myHints, List.of(input), List.of(), 
fetch, 0);
+    };
+  }
+
   /// Creates a table scan node with the given table name.
   public SimpleChildBuilder<TableScanNode> tableScan(String tableName) {
     return (stageId, mySchema, myHints) -> new TableScanNode(stageId, 
mySchema, myHints, List.of(), tableName,
diff --git 
a/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/physical/PinotDispatchPlannerTest.java
 
b/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/physical/PinotDispatchPlannerTest.java
index 08abe33540d..617e8fdfe21 100644
--- 
a/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/physical/PinotDispatchPlannerTest.java
+++ 
b/pinot-query-planner/src/test/java/org/apache/pinot/query/planner/physical/PinotDispatchPlannerTest.java
@@ -122,6 +122,46 @@ public class PinotDispatchPlannerTest extends 
QueryEnvironmentTestBase {
     }
   }
 
+  /// Both arms join the scans of a and b with the sides swapped. `on` shares 
both scans between the two joins. Each
+  /// join then reads, as its build input, the spool that feeds the probe 
input of the other one, which is a circular
+  /// wait. `auto` can share one of the scans, which is safe, but must refuse 
the second one.
+  @Test
+  public void testAutoSpoolsRejectCircularWaitBetweenJoins() {
+    String query = "SELECT COUNT(*) FROM a JOIN b ON a.col1 = b.col1 "
+        + "UNION ALL SELECT COUNT(*) FROM b JOIN a ON b.col1 = a.col1";
+    assertEquals(countMultiReceiverSends(_queryEnvironment.planQuery("SET 
useSpools='on'; " + query)), 2,
+        "Expected 'on' to share both scans, otherwise this test does not 
exercise the guard");
+    assertEquals(countMultiReceiverSends(_queryEnvironment.planQuery("SET 
useSpools='auto'; " + query)), 1);
+  }
+
+  /// Two independent subqueries draw two independent 10% samples with 
`RAND()`. Calcite produces two equal leaf
+  /// stages, and sharing them would give both subqueries the same sample. No 
mode may share them.
+  @Test
+  public void testStagesWithVolatileFunctionsAreNotShared() {
+    String sample = "(SELECT col1 FROM a WHERE %s ORDER BY col1 LIMIT 1000)";
+    String query = "SELECT x.c, y.c FROM (SELECT COUNT(*) AS c FROM " + sample 
+ ") x "
+        + "JOIN (SELECT MAX(col1) AS c FROM " + sample + ") y ON TRUE";
+    String deterministic = String.format(query, "col3 > 10", "col3 > 10");
+    assertEquals(countMultiReceiverSends(_queryEnvironment.planQuery("SET 
useSpools='on'; " + deterministic)), 1,
+        "Expected the deterministic query to share its scan, otherwise this 
test does not exercise the check");
+    String random = String.format(query, "RAND() < 0.1", "RAND() < 0.1");
+    for (String mode : List.of("on", "auto")) {
+      assertEquals(countMultiReceiverSends(_queryEnvironment.planQuery("SET 
useSpools='" + mode + "'; " + random)), 0,
+          "Mode " + mode + " shared a stage that calls RAND()");
+    }
+  }
+
+  private static int countMultiReceiverSends(DispatchableSubPlan subPlan) {
+    int count = 0;
+    for (DispatchablePlanFragment fragment : 
subPlan.getQueryStageMap().values()) {
+      PlanNode root = fragment.getPlanFragment().getFragmentRoot();
+      if (root instanceof MailboxSendNode && ((MailboxSendNode) 
root).isMultiSend()) {
+        count++;
+      }
+    }
+    return count;
+  }
+
   private static boolean hasMultiReceiverSend(DispatchableSubPlan subPlan) {
     for (DispatchablePlanFragment fragment : 
subPlan.getQueryStageMap().values()) {
       PlanNode root = fragment.getPlanFragment().getFragmentRoot();
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 dab8151dcdf..b09f66133a0 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
@@ -665,10 +665,19 @@ public class CommonConstants {
     public static final String CONFIG_OF_INFER_PARTITION_HINT = 
"pinot.broker.multistage.infer.partition.hint";
     public static final boolean DEFAULT_INFER_PARTITION_HINT = false;
 
-    /// Whether to use spools in multistage query engine by default.
+    /// The default spool mode of the multistage query engine: `off`, `auto` 
or `on`. `false` and `no` are aliases of
+    /// `off`, and `true` and `yes` are aliases of `on`.
+    ///
+    /// - `off` never shares a stage between consumers.
+    /// - `auto` shares a stage only when the planner can prove that the 
sharing cannot block the query.
+    /// - `on` shares every equivalent stage that the planner supports, 
without that safety check.
+    ///
+    /// Only the default planner applies spools. With 
[Request.QueryOptionKey#USE_PHYSICAL_OPTIMIZER] the mode is
+    /// ignored.
+    ///
     /// This value can always be overridden by 
[Request.QueryOptionKey#USE_SPOOLS] query option
     public static final String CONFIG_OF_SPOOLS = 
"pinot.broker.multistage.spools";
-    public static final boolean DEFAULT_OF_SPOOLS = false;
+    public static final String DEFAULT_SPOOLS_MODE = "auto";
 
     /// Whether the multistage query engine prunes unused input (passthrough) 
columns - notably the unnested source
     /// array - from the UNNEST output by default. This value can always be 
overridden by the
@@ -1050,7 +1059,12 @@ public class CommonConstants {
         public static final String INFER_PARTITION_HINT = "inferPartitionHint";
         public static final String ENABLE_NULL_HANDLING = "enableNullHandling";
         public static final String APPLICATION_NAME = "applicationName";
+        /// The spool mode for the query: `off`, `auto` or `on` (`false`/`no` 
and `true`/`yes` are aliases).
+        /// See [Broker#CONFIG_OF_SPOOLS].
         public static final String USE_SPOOLS = "useSpools";
+        /// When true, the broker response carries a `spools` entry in 
`responseMetadata` that lists each spool the
+        /// planner considered and whether it applied it.
+        public static final String SPOOLS_FEEDBACK = "spoolsFeedback";
         public static final String USE_PHYSICAL_OPTIMIZER = 
"usePhysicalOptimizer";
         // When true, the multi-stage planner prunes input (passthrough) 
columns - notably the unnested source array -
         // from the UNNEST output when they are not referenced downstream, 
avoiding copying them into every exploded


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

Reply via email to