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

ankitsultana 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 a231dbbe43 [multistage] Support Physical Optimizer E2E (#15698)
a231dbbe43 is described below

commit a231dbbe43e3ebdfa25d8f0b3254980eca617ab1
Author: Ankit Sultana <[email protected]>
AuthorDate: Mon May 5 17:16:01 2025 -0500

    [multistage] Support Physical Optimizer E2E (#15698)
---
 .../MultiStageBrokerRequestHandler.java            |   6 +-
 .../org/apache/pinot/query/QueryEnvironment.java   |  77 +++-
 .../query/context/PhysicalPlannerContext.java      |   8 +
 .../apache/pinot/query/context/PlannerContext.java |  15 +-
 .../planner/logical/PinotLogicalQueryPlanner.java  |  16 +
 .../planner/physical/PinotDispatchPlanner.java     |  15 +
 .../v2/PlanFragmentAndMailboxAssignment.java       | 273 +++++++++++++
 .../resources/queries/PhysicalOptimizerPlans.json  | 425 +++++++++++++++++++++
 .../apache/pinot/spi/utils/CommonConstants.java    |   1 +
 9 files changed, 814 insertions(+), 22 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 4ee9b69e0c..b0e1f6bbe3 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
@@ -277,7 +277,7 @@ public class MultiStageBrokerRequestHandler extends 
BaseBrokerRequestHandler {
     Map<String, String> queryOptions = sqlNodeAndOptions.getOptions();
 
     try {
-      ImmutableQueryEnvironment.Config queryEnvConf = 
getQueryEnvConf(httpHeaders, queryOptions);
+      ImmutableQueryEnvironment.Config queryEnvConf = 
getQueryEnvConf(httpHeaders, queryOptions, requestId);
       QueryEnvironment queryEnv = new QueryEnvironment(queryEnvConf);
       return callAsync(requestId, query, () -> queryEnv.compile(query, 
sqlNodeAndOptions), queryTimer);
     } catch (WebApplicationException e) {
@@ -306,7 +306,8 @@ public class MultiStageBrokerRequestHandler extends 
BaseBrokerRequestHandler {
     }
   }
 
-  private ImmutableQueryEnvironment.Config getQueryEnvConf(HttpHeaders 
httpHeaders, Map<String, String> queryOptions) {
+  private ImmutableQueryEnvironment.Config getQueryEnvConf(HttpHeaders 
httpHeaders, Map<String, String> queryOptions,
+      long requestId) {
     String database = 
DatabaseUtils.extractDatabaseFromQueryRequest(queryOptions, httpHeaders);
     boolean inferPartitionHint = 
_config.getProperty(CommonConstants.Broker.CONFIG_OF_INFER_PARTITION_HINT,
         CommonConstants.Broker.DEFAULT_INFER_PARTITION_HINT);
@@ -318,6 +319,7 @@ public class MultiStageBrokerRequestHandler extends 
BaseBrokerRequestHandler {
         
CommonConstants.Broker.CONFIG_OF_BROKER_ENABLE_DYNAMIC_FILTERING_SEMI_JOIN,
         CommonConstants.Broker.DEFAULT_ENABLE_DYNAMIC_FILTERING_SEMI_JOIN);
     return QueryEnvironment.configBuilder()
+        .requestId(requestId)
         .database(database)
         .tableCache(_tableCache)
         .workerManager(_workerManager)
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 51cd908942..8fe9aa7d0e 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
@@ -19,6 +19,7 @@
 package org.apache.pinot.query;
 
 import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
 import java.io.Closeable;
 import java.util.ArrayList;
 import java.util.HashMap;
@@ -53,6 +54,7 @@ import org.apache.calcite.sql2rel.SqlToRelConverter;
 import org.apache.calcite.tools.FrameworkConfig;
 import org.apache.calcite.tools.Frameworks;
 import org.apache.calcite.tools.RelBuilder;
+import org.apache.commons.lang3.tuple.Pair;
 import org.apache.pinot.calcite.rel.rules.PinotImplicitTableHintRule;
 import org.apache.pinot.calcite.rel.rules.PinotJoinToDynamicBroadcastRule;
 import org.apache.pinot.calcite.rel.rules.PinotQueryRuleSets;
@@ -63,6 +65,7 @@ import org.apache.pinot.calcite.sql2rel.PinotConvertletTable;
 import org.apache.pinot.common.config.provider.TableCache;
 import org.apache.pinot.common.utils.config.QueryOptionsUtils;
 import org.apache.pinot.query.catalog.PinotCatalog;
+import org.apache.pinot.query.context.PhysicalPlannerContext;
 import org.apache.pinot.query.context.PlannerContext;
 import org.apache.pinot.query.context.RuleTimingPlannerListener;
 import org.apache.pinot.query.planner.PlannerUtils;
@@ -75,6 +78,8 @@ import 
org.apache.pinot.query.planner.logical.RelToPlanNodeConverter;
 import org.apache.pinot.query.planner.logical.TransformationTracker;
 import org.apache.pinot.query.planner.physical.DispatchableSubPlan;
 import org.apache.pinot.query.planner.physical.PinotDispatchPlanner;
+import 
org.apache.pinot.query.planner.physical.v2.PlanFragmentAndMailboxAssignment;
+import org.apache.pinot.query.planner.physical.v2.RelToPRelConverter;
 import org.apache.pinot.query.planner.plannode.PlanNode;
 import org.apache.pinot.query.routing.WorkerManager;
 import org.apache.pinot.query.type.TypeFactory;
@@ -138,6 +143,7 @@ public class QueryEnvironment {
 
   public QueryEnvironment(String database, TableCache tableCache, @Nullable 
WorkerManager workerManager) {
     this(configBuilder()
+        .requestId(-1L)
         .database(database)
         .tableCache(tableCache)
         .workerManager(workerManager)
@@ -149,7 +155,8 @@ public class QueryEnvironment {
    */
   private PlannerContext getPlannerContext(SqlNodeAndOptions 
sqlNodeAndOptions) {
     WorkerManager workerManager = getWorkerManager(sqlNodeAndOptions);
-    HepProgram traitProgram = getTraitProgram(workerManager, _envConfig);
+    boolean usePhysicalOptimizer = 
PhysicalPlannerContext.isUsePhysicalOptimizer(sqlNodeAndOptions.getOptions());
+    HepProgram traitProgram = getTraitProgram(workerManager, _envConfig, 
usePhysicalOptimizer);
     SqlExplainFormat format = SqlExplainFormat.DOT;
     if (sqlNodeAndOptions.getSqlNode().getKind().equals(SqlKind.EXPLAIN)) {
       SqlExplain explain = (SqlExplain) sqlNodeAndOptions.getSqlNode();
@@ -157,8 +164,15 @@ public class QueryEnvironment {
         format = explain.getFormat();
       }
     }
+    PhysicalPlannerContext physicalPlannerContext = null;
+    if (usePhysicalOptimizer && _envConfig.getWorkerManager() != null) {
+      workerManager = _envConfig.getWorkerManager();
+      physicalPlannerContext = new 
PhysicalPlannerContext(workerManager.getRoutingManager(),
+          workerManager.getHostName(), workerManager.getPort(), 
_envConfig.getRequestId(),
+          workerManager.getInstanceId());
+    }
     return new PlannerContext(_config, _catalogReader, _typeFactory, 
_optProgram, traitProgram,
-        sqlNodeAndOptions.getOptions(), _envConfig, format);
+        sqlNodeAndOptions.getOptions(), _envConfig, format, 
physicalPlannerContext);
   }
 
   /// @deprecated Use [#compile] and then 
[plan][CompiledQuery#planQuery(long)] the returned query instead
@@ -309,6 +323,11 @@ public class QueryEnvironment {
     SqlNode validated = validate(sqlNode, plannerContext);
     RelRoot relation = toRelation(validated, plannerContext);
     RelNode optimized = optimize(relation, plannerContext);
+    if (plannerContext.isUsePhysicalOptimizer()) {
+      Preconditions.checkNotNull(plannerContext.getPhysicalPlannerContext(), 
"Physical planner context is null");
+      optimized = RelToPRelConverter.toPRelNode(optimized, 
plannerContext.getPhysicalPlannerContext(),
+          _envConfig.getTableCache()).unwrap();
+    }
     return relation.withRel(optimized);
   }
 
@@ -415,16 +434,25 @@ public class QueryEnvironment {
     }
   }
 
-  private DispatchableSubPlan toDispatchableSubPlan(RelRoot relRoot, 
PlannerContext plannerContext, long requestId) {
-    return toDispatchableSubPlan(relRoot, plannerContext, requestId, null);
+  private DispatchableSubPlan toDispatchableSubPlan(RelRoot relRoot, 
PlannerContext plannerContext) {
+    return toDispatchableSubPlan(relRoot, plannerContext, null);
   }
 
-  private DispatchableSubPlan toDispatchableSubPlan(RelRoot relRoot, 
PlannerContext plannerContext, long requestId,
+  private DispatchableSubPlan toDispatchableSubPlan(RelRoot relRoot, 
PlannerContext plannerContext,
       @Nullable TransformationTracker.Builder<PlanNode, RelNode> tracker) {
+    long requestId = _envConfig.getRequestId();
+    if (plannerContext.isUsePhysicalOptimizer()) {
+      Pair<SubPlan, PlanFragmentAndMailboxAssignment.Result> plan = 
PinotLogicalQueryPlanner.makePlanV2(relRoot,
+          plannerContext.getPhysicalPlannerContext());
+      PinotDispatchPlanner pinotDispatchPlanner = new 
PinotDispatchPlanner(plannerContext,
+          _envConfig.getWorkerManager(), requestId, 
_envConfig.getTableCache());
+      return pinotDispatchPlanner.createDispatchableSubPlanV2(plan.getLeft(), 
plan.getRight());
+    }
     SubPlan plan = PinotLogicalQueryPlanner.makePlan(relRoot, tracker,
         _envConfig.getTableCache(), useSpools(plannerContext.getOptions()));
     PinotDispatchPlanner pinotDispatchPlanner =
-        new PinotDispatchPlanner(plannerContext, 
_envConfig.getWorkerManager(), requestId, _envConfig.getTableCache());
+        new PinotDispatchPlanner(plannerContext, 
_envConfig.getWorkerManager(), _envConfig.getRequestId(),
+            _envConfig.getTableCache());
     return pinotDispatchPlanner.createDispatchableSubPlan(plan);
   }
 
@@ -462,7 +490,8 @@ public class QueryEnvironment {
     return hepProgramBuilder.build();
   }
 
-  private static HepProgram getTraitProgram(@Nullable WorkerManager 
workerManager, Config config) {
+  private static HepProgram getTraitProgram(@Nullable WorkerManager 
workerManager, Config config,
+      boolean usePhysicalOptimizer) {
     HepProgramBuilder hepProgramBuilder = new HepProgramBuilder();
 
     // Set the match order as BOTTOM_UP.
@@ -470,18 +499,26 @@ public class QueryEnvironment {
 
     // ----
     // Run pinot specific rules that should run after all other rules, using 1 
HepInstruction per rule.
-    for (RelOptRule relOptRule : PinotQueryRuleSets.PINOT_POST_RULES) {
-      if (isEligibleQueryPostRule(relOptRule, config)) {
-        hepProgramBuilder.addRuleInstance(relOptRule);
+    if (!usePhysicalOptimizer) {
+      for (RelOptRule relOptRule : PinotQueryRuleSets.PINOT_POST_RULES) {
+        if (isEligibleQueryPostRule(relOptRule, config)) {
+          hepProgramBuilder.addRuleInstance(relOptRule);
+        }
+      }
+    } else {
+      for (RelOptRule relOptRule : PinotQueryRuleSets.PINOT_POST_RULES_V2) {
+        if (isEligibleQueryPostRule(relOptRule, config)) {
+          hepProgramBuilder.addRuleInstance(relOptRule);
+        }
       }
     }
-
-    // apply RelDistribution trait to all nodes
-    if (workerManager != null) {
-      
hepProgramBuilder.addRuleInstance(PinotImplicitTableHintRule.withWorkerManager(workerManager));
+    if (!usePhysicalOptimizer) {
+      // apply RelDistribution trait to all nodes
+      if (workerManager != null) {
+        
hepProgramBuilder.addRuleInstance(PinotImplicitTableHintRule.withWorkerManager(workerManager));
+      }
+      
hepProgramBuilder.addRuleInstance(PinotRelDistributionTraitRule.INSTANCE);
     }
-    hepProgramBuilder.addRuleInstance(PinotRelDistributionTraitRule.INSTANCE);
-
     return hepProgramBuilder.build();
   }
 
@@ -507,6 +544,8 @@ public class QueryEnvironment {
 
   @Value.Immutable
   public interface Config {
+    long getRequestId();
+
     String getDatabase();
 
     /**
@@ -609,7 +648,7 @@ public class QueryEnvironment {
         SqlExplainFormat format = _plannerContext.getSqlExplainFormat();
         if (explain instanceof SqlPhysicalExplain) {
           // get the physical plan for query.
-          DispatchableSubPlan dispatchableSubPlan = 
toDispatchableSubPlan(_relRoot, _plannerContext, requestId);
+          DispatchableSubPlan dispatchableSubPlan = 
toDispatchableSubPlan(_relRoot, _plannerContext);
           return getQueryPlannerResult(_plannerContext, dispatchableSubPlan,
               PhysicalExplainPlanVisitor.explain(dispatchableSubPlan), 
dispatchableSubPlan.getTableNames());
         } else {
@@ -629,7 +668,7 @@ public class QueryEnvironment {
                 new TransformationTracker.ByIdentity.Builder<>();
             // Transform RelNodes into DispatchableSubPlan
             DispatchableSubPlan dispatchableSubPlan =
-                toDispatchableSubPlan(_relRoot, _plannerContext, requestId, 
nodeTracker);
+                toDispatchableSubPlan(_relRoot, _plannerContext, nodeTracker);
 
             AskingServerStageExplainer serversExplainer = new 
AskingServerStageExplainer(
                 onServerExplainer, explainPlanVerbose, 
RelBuilder.create(_config));
@@ -652,7 +691,7 @@ public class QueryEnvironment {
         // TODO: current code only assume one SubPlan per query, but we should 
support multiple SubPlans per query.
         // Each SubPlan should be able to run independently from Broker then 
set the results into the dependent
         // SubPlan for further processing.
-        DispatchableSubPlan dispatchableSubPlan = 
toDispatchableSubPlan(_relRoot, _plannerContext, requestId);
+        DispatchableSubPlan dispatchableSubPlan = 
toDispatchableSubPlan(_relRoot, _plannerContext);
         return getQueryPlannerResult(_plannerContext, dispatchableSubPlan, 
null, dispatchableSubPlan.getTableNames());
       } catch (QueryException e) {
         throw e;
diff --git 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/context/PhysicalPlannerContext.java
 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/context/PhysicalPlannerContext.java
index 08e5f464b9..6035306be8 100644
--- 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/context/PhysicalPlannerContext.java
+++ 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/context/PhysicalPlannerContext.java
@@ -24,6 +24,7 @@ import java.util.function.Supplier;
 import javax.annotation.Nullable;
 import org.apache.pinot.core.routing.RoutingManager;
 import org.apache.pinot.query.routing.QueryServerInstance;
+import 
org.apache.pinot.spi.utils.CommonConstants.Broker.Request.QueryOptionKey;
 
 
 /**
@@ -105,4 +106,11 @@ public class PhysicalPlannerContext {
   public String getInstanceId() {
     return _instanceId;
   }
+
+  public static boolean isUsePhysicalOptimizer(@Nullable Map<String, String> 
queryOptions) {
+    if (queryOptions == null) {
+      return false;
+    }
+    return 
Boolean.parseBoolean(queryOptions.getOrDefault(QueryOptionKey.USE_PHYSICAL_OPTIMIZER,
 "false"));
+  }
 }
diff --git 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/context/PlannerContext.java
 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/context/PlannerContext.java
index 886e69b040..ecf9704cee 100644
--- 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/context/PlannerContext.java
+++ 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/context/PlannerContext.java
@@ -21,6 +21,7 @@ package org.apache.pinot.query.context;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.Map;
+import javax.annotation.Nullable;
 import org.apache.calcite.plan.Contexts;
 import org.apache.calcite.plan.RelOptPlanner;
 import org.apache.calcite.plan.hep.HepProgram;
@@ -53,10 +54,12 @@ public class PlannerContext implements AutoCloseable {
   private final Map<String, String> _options;
   private final Map<String, String> _plannerOutput;
   private final SqlExplainFormat _sqlExplainFormat;
+  @Nullable
+  private final PhysicalPlannerContext _physicalPlannerContext;
 
   public PlannerContext(FrameworkConfig config, Prepare.CatalogReader 
catalogReader, RelDataTypeFactory typeFactory,
       HepProgram optProgram, HepProgram traitProgram, Map<String, String> 
options, QueryEnvironment.Config envConfig,
-      SqlExplainFormat sqlExplainFormat) {
+      SqlExplainFormat sqlExplainFormat, @Nullable PhysicalPlannerContext 
physicalPlannerContext) {
     _planner = new PlannerImpl(config);
     _validator = new Validator(config.getOperatorTable(), catalogReader, 
typeFactory);
     _relOptPlanner = new LogicalPlanner(optProgram, Contexts.EMPTY_CONTEXT, 
config.getTraitDefs());
@@ -65,6 +68,7 @@ public class PlannerContext implements AutoCloseable {
     _options = options;
     _plannerOutput = new HashMap<>();
     _sqlExplainFormat = sqlExplainFormat;
+    _physicalPlannerContext = physicalPlannerContext;
   }
 
   public PlannerImpl getPlanner() {
@@ -99,4 +103,13 @@ public class PlannerContext implements AutoCloseable {
   public SqlExplainFormat getSqlExplainFormat() {
     return _sqlExplainFormat;
   }
+
+  @Nullable
+  public PhysicalPlannerContext getPhysicalPlannerContext() {
+    return _physicalPlannerContext;
+  }
+
+  public boolean isUsePhysicalOptimizer() {
+    return _physicalPlannerContext != null;
+  }
 }
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 d20959e8e9..2c3ff26df3 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
@@ -33,11 +33,15 @@ import javax.annotation.Nullable;
 import org.apache.calcite.rel.RelDistribution;
 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.config.provider.TableCache;
+import org.apache.pinot.query.context.PhysicalPlannerContext;
 import org.apache.pinot.query.planner.PlanFragment;
 import org.apache.pinot.query.planner.SubPlan;
 import org.apache.pinot.query.planner.SubPlanMetadata;
+import org.apache.pinot.query.planner.physical.v2.PRelNode;
+import 
org.apache.pinot.query.planner.physical.v2.PlanFragmentAndMailboxAssignment;
 import org.apache.pinot.query.planner.plannode.BasePlanNode;
 import org.apache.pinot.query.planner.plannode.ExchangeNode;
 import org.apache.pinot.query.planner.plannode.MailboxReceiveNode;
@@ -89,6 +93,18 @@ public class PinotLogicalQueryPlanner {
 //    return subPlanMap.get(0);
   }
 
+  public static Pair<SubPlan, PlanFragmentAndMailboxAssignment.Result> 
makePlanV2(RelRoot relRoot,
+      PhysicalPlannerContext physicalPlannerContext) {
+    PRelNode pRelNode = (PRelNode) relRoot.rel;
+    PlanFragmentAndMailboxAssignment planFragmentAndMailboxAssignment = new 
PlanFragmentAndMailboxAssignment();
+    PlanFragmentAndMailboxAssignment.Result result =
+        planFragmentAndMailboxAssignment.compute(pRelNode, 
physicalPlannerContext);
+    PlanFragment rootFragment = result._planFragmentMap.get(0);
+    SubPlan subPlan = new SubPlan(rootFragment,
+        new 
SubPlanMetadata(RelToPlanNodeConverter.getTableNamesFromRelRoot(relRoot.rel), 
relRoot.fields), List.of());
+    return Pair.of(subPlan, result);
+  }
+
   private static PlanFragment planNodeToPlanFragment(
       PlanNode node, @Nullable TransformationTracker.Builder<PlanNode, 
RelNode> tracker, boolean useSpools) {
     PlanFragmenter fragmenter = new PlanFragmenter();
diff --git 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/physical/PinotDispatchPlanner.java
 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/physical/PinotDispatchPlanner.java
index 80ead2db2e..643684ab78 100644
--- 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/physical/PinotDispatchPlanner.java
+++ 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/physical/PinotDispatchPlanner.java
@@ -27,6 +27,7 @@ import org.apache.pinot.query.context.PlannerContext;
 import org.apache.pinot.query.planner.PlanFragment;
 import org.apache.pinot.query.planner.SubPlan;
 import 
org.apache.pinot.query.planner.physical.colocated.GreedyShuffleRewriteVisitor;
+import 
org.apache.pinot.query.planner.physical.v2.PlanFragmentAndMailboxAssignment;
 import org.apache.pinot.query.planner.plannode.PlanNode;
 import org.apache.pinot.query.planner.validation.ArrayToMvValidationVisitor;
 import org.apache.pinot.query.routing.WorkerManager;
@@ -74,6 +75,20 @@ public class PinotDispatchPlanner {
     return finalizeDispatchableSubPlan(rootFragment, context);
   }
 
+  public DispatchableSubPlan createDispatchableSubPlanV2(SubPlan subPlan,
+      PlanFragmentAndMailboxAssignment.Result result) {
+    // perform physical plan conversion and assign workers to each stage.
+    DispatchablePlanContext context = new 
DispatchablePlanContext(_workerManager, _requestId, _plannerContext,
+        subPlan.getSubPlanMetadata().getFields(), 
subPlan.getSubPlanMetadata().getTableNames());
+    PlanFragment rootFragment = subPlan.getSubPlanRoot();
+    
context.getDispatchablePlanMetadataMap().putAll(result._fragmentMetadataMap);
+    for (var entry : result._planFragmentMap.entrySet()) {
+      context.getDispatchablePlanStageRootMap().put(entry.getKey(), 
entry.getValue().getFragmentRoot());
+    }
+    runValidations(rootFragment, context);
+    return finalizeDispatchableSubPlan(rootFragment, context);
+  }
+
   /**
    * Run validations on the plan. Since there is only one validator right now, 
don't try to over-engineer it.
    */
diff --git 
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/physical/v2/PlanFragmentAndMailboxAssignment.java
 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/physical/v2/PlanFragmentAndMailboxAssignment.java
new file mode 100644
index 0000000000..a7733b1a28
--- /dev/null
+++ 
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/physical/v2/PlanFragmentAndMailboxAssignment.java
@@ -0,0 +1,273 @@
+/**
+ * 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.physical.v2;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import javax.annotation.Nullable;
+import org.apache.calcite.rel.RelDistribution;
+import org.apache.calcite.rel.core.Exchange;
+import org.apache.calcite.rel.core.TableScan;
+import org.apache.commons.collections4.MapUtils;
+import org.apache.pinot.calcite.rel.hint.PinotHintOptions;
+import org.apache.pinot.calcite.rel.logical.PinotRelExchangeType;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.query.context.PhysicalPlannerContext;
+import org.apache.pinot.query.planner.PlanFragment;
+import org.apache.pinot.query.planner.physical.DispatchablePlanMetadata;
+import org.apache.pinot.query.planner.physical.v2.nodes.PhysicalExchange;
+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.PlanNode.NodeHint;
+import org.apache.pinot.query.routing.MailboxInfo;
+import org.apache.pinot.query.routing.MailboxInfos;
+import org.apache.pinot.query.routing.QueryServerInstance;
+import org.apache.pinot.query.routing.SharedMailboxInfos;
+
+
+public class PlanFragmentAndMailboxAssignment {
+  private static final int ROOT_FRAGMENT_ID = 0;
+  private static final int FIRST_NON_ROOT_FRAGMENT_ID = 1;
+
+  public Result compute(PRelNode rootPRelNode, PhysicalPlannerContext 
physicalPlannerContext) {
+    Preconditions.checkState(!(rootPRelNode.unwrap() instanceof Exchange), 
"root node should never be exchange");
+    final DataSchema rootDataSchema = 
PRelToPlanNodeConverter.toDataSchema(rootPRelNode.unwrap().getRowType());
+    // Create input fragment's send node.
+    MailboxSendNode sendNode = new MailboxSendNode(FIRST_NON_ROOT_FRAGMENT_ID, 
rootDataSchema, new ArrayList<>(),
+        ROOT_FRAGMENT_ID, PinotRelExchangeType.getDefaultExchangeType(), 
RelDistribution.Type.SINGLETON,
+        null, false, null, false);
+    // Create root receive node.
+    MailboxReceiveNode rootReceiveNode = new 
MailboxReceiveNode(ROOT_FRAGMENT_ID, rootDataSchema,
+        FIRST_NON_ROOT_FRAGMENT_ID, 
PinotRelExchangeType.getDefaultExchangeType(),
+        RelDistribution.Type.BROADCAST_DISTRIBUTED, null, null, false, false, 
sendNode);
+    // Create the first two fragments.
+    Context context = new Context(physicalPlannerContext);
+    PlanFragment rootFragment = createFragment(ROOT_FRAGMENT_ID, 
rootReceiveNode, new ArrayList<>(), context);
+    PlanFragment firstInputFragment = 
createFragment(FIRST_NON_ROOT_FRAGMENT_ID, sendNode, new ArrayList<>(), 
context);
+    rootFragment.getChildren().add(firstInputFragment);
+    QueryServerInstance brokerInstance = new 
QueryServerInstance(physicalPlannerContext.getInstanceId(),
+        physicalPlannerContext.getHostName(), 
physicalPlannerContext.getPort(), physicalPlannerContext.getPort());
+    computeMailboxInfos(FIRST_NON_ROOT_FRAGMENT_ID, ROOT_FRAGMENT_ID,
+        
createWorkerMap(rootPRelNode.getPinotDataDistributionOrThrow().getWorkers(), 
context),
+        ImmutableMap.of(0, brokerInstance), 
ExchangeStrategy.SINGLETON_EXCHANGE, context);
+    // Traverse entire tree.
+    
context._fragmentMetadataMap.get(ROOT_FRAGMENT_ID).setWorkerIdToServerInstanceMap(ImmutableMap.of(
+        0, brokerInstance));
+    visit(rootPRelNode, sendNode, firstInputFragment, context);
+    Result result = new Result();
+    result._fragmentMetadataMap = context._fragmentMetadataMap;
+    result._planFragmentMap = context._planFragmentMap;
+    return result;
+  }
+
+  /**
+   * Invariants: 1. Parent PlanNode does not have current node in input yet. 
2. This node is NOT the fragment root. This
+   * is because each fragment root is a MailboxSendNode.
+   */
+  private void visit(PRelNode pRelNode, @Nullable PlanNode parent, 
PlanFragment currentFragment, Context context) {
+    int currentFragmentId = currentFragment.getFragmentId();
+    DispatchablePlanMetadata fragmentMetadata = 
context._fragmentMetadataMap.get(currentFragmentId);
+    if (MapUtils.isEmpty(fragmentMetadata.getWorkerIdToServerInstanceMap())) {
+      // TODO: This is quite a complex invariant.
+      fragmentMetadata.setWorkerIdToServerInstanceMap(createWorkerMap(
+          pRelNode.getPinotDataDistributionOrThrow().getWorkers(), context));
+    }
+    if (pRelNode.unwrap() instanceof TableScan) {
+      TableScanMetadata tableScanMetadata = 
Objects.requireNonNull(pRelNode.getTableScanMetadata(),
+          "No metadata in table scan PRelNode");
+      String tableName = 
tableScanMetadata.getScannedTables().stream().findFirst().orElseThrow();
+      if (!tableScanMetadata.getUnavailableSegmentsMap().isEmpty()) {
+        fragmentMetadata.addUnavailableSegments(tableName,
+            tableScanMetadata.getUnavailableSegmentsMap().get(tableName));
+      }
+      fragmentMetadata.addScannedTable(tableName);
+      
fragmentMetadata.setWorkerIdToSegmentsMap(tableScanMetadata.getWorkedIdToSegmentsMap());
+      NodeHint nodeHint = NodeHint.fromRelHints(((TableScan) 
pRelNode.unwrap()).getHints());
+      
fragmentMetadata.setTableOptions(nodeHint.getHintOptions().get(PinotHintOptions.TABLE_HINT_OPTIONS));
+      if (tableScanMetadata.getTimeBoundaryInfo() != null) {
+        
fragmentMetadata.setTimeBoundaryInfo(tableScanMetadata.getTimeBoundaryInfo());
+      }
+    }
+    if (pRelNode.unwrap() instanceof PhysicalExchange) {
+      PhysicalExchange physicalExchange = (PhysicalExchange) pRelNode.unwrap();
+      int senderFragmentId = context._planFragmentMap.size();
+      final DataSchema inputFragmentSchema = 
PRelToPlanNodeConverter.toDataSchema(
+          pRelNode.getPRelInput(0).unwrap().getRowType());
+      RelDistribution.Type distributionType = 
inferDistributionType(physicalExchange.getExchangeStrategy());
+      List<PlanNode> inputs = new ArrayList<>();
+      MailboxSendNode sendNode = new MailboxSendNode(senderFragmentId, 
inputFragmentSchema, inputs, currentFragmentId,
+          PinotRelExchangeType.getDefaultExchangeType(), distributionType, 
physicalExchange.getDistributionKeys(),
+          false, physicalExchange.getRelCollation().getFieldCollations(), 
false /* todo: set sortOnSender */);
+      MailboxReceiveNode receiveNode = new 
MailboxReceiveNode(currentFragmentId, inputFragmentSchema,
+          senderFragmentId, PinotRelExchangeType.getDefaultExchangeType(), 
distributionType,
+          physicalExchange.getDistributionKeys(), 
physicalExchange.getRelCollation().getFieldCollations(),
+          false /* TODO: set sort on receiver */, false /* TODO: set sort on 
sender */, sendNode);
+      PlanFragment newPlanFragment = createFragment(senderFragmentId, 
sendNode, new ArrayList<>(), context);
+      Map<Integer, QueryServerInstance> senderWorkers = 
createWorkerMap(pRelNode.getPRelInput(0)
+          .getPinotDataDistributionOrThrow().getWorkers(), context);
+      Map<Integer, QueryServerInstance> receiverWorkers = 
createWorkerMap(pRelNode.getPinotDataDistributionOrThrow()
+          .getWorkers(), context);
+      computeMailboxInfos(senderFragmentId, currentFragmentId, senderWorkers, 
receiverWorkers,
+          physicalExchange.getExchangeStrategy(), context);
+      currentFragment.getChildren().add(newPlanFragment);
+      visit(pRelNode.getPRelInput(0), sendNode, newPlanFragment, context);
+      if (parent != null) {
+        parent.getInputs().add(receiveNode);
+      }
+      return;
+    }
+    PlanNode planNode = PRelToPlanNodeConverter.toPlanNode(pRelNode, 
currentFragmentId);
+    for (PRelNode input : pRelNode.getPRelInputs()) {
+      visit(input, planNode, currentFragment, context);
+    }
+    if (parent != null) {
+      parent.getInputs().add(planNode);
+    }
+  }
+
+  private PlanFragment createFragment(int fragmentId, PlanNode planNode, 
List<PlanFragment> inputFragments,
+      Context context) {
+    PlanFragment fragment = new PlanFragment(fragmentId, planNode, 
inputFragments);
+    context._planFragmentMap.put(fragmentId, fragment);
+    context._fragmentMetadataMap.put(fragmentId, new 
DispatchablePlanMetadata());
+    return fragment;
+  }
+
+  private RelDistribution.Type inferDistributionType(ExchangeStrategy desc) {
+    RelDistribution.Type distributionType;
+    switch (desc) {
+      case PARTITIONING_EXCHANGE:
+        distributionType = RelDistribution.Type.HASH_DISTRIBUTED;
+        break;
+      case IDENTITY_EXCHANGE:
+        distributionType = RelDistribution.Type.HASH_DISTRIBUTED;
+        break;
+      case SINGLETON_EXCHANGE:
+        distributionType = RelDistribution.Type.SINGLETON;
+        break;
+      case BROADCAST_EXCHANGE:
+        distributionType = RelDistribution.Type.BROADCAST_DISTRIBUTED;
+        break;
+      default:
+        throw new IllegalStateException("");
+    }
+    return distributionType;
+  }
+
+  private Map<Integer, QueryServerInstance> createWorkerMap(List<String> 
workers, Context context) {
+    Map<Integer, QueryServerInstance> mp = new HashMap<>();
+    for (String instance : workers) {
+      String[] splits = instance.split("@");
+      mp.put(Integer.parseInt(splits[0]),
+          
context._physicalPlannerContext.getInstanceIdToQueryServerInstance().get(splits[1]));
+    }
+    return mp;
+  }
+
+  private void computeMailboxInfos(int senderStageId, int receiverStageId,
+      Map<Integer, QueryServerInstance> senderWorkers, Map<Integer, 
QueryServerInstance> receiverWorkers,
+      ExchangeStrategy exchangeDesc, Context context) {
+    DispatchablePlanMetadata senderMetadata = 
context._fragmentMetadataMap.get(senderStageId);
+    DispatchablePlanMetadata receiverMetadata = 
context._fragmentMetadataMap.get(receiverStageId);
+    Map<Integer, Map<Integer, MailboxInfos>> senderMailboxMap = 
senderMetadata.getWorkerIdToMailboxesMap();
+    Map<Integer, Map<Integer, MailboxInfos>> receiverMailboxMap = 
receiverMetadata.getWorkerIdToMailboxesMap();
+    switch (exchangeDesc) {
+      case IDENTITY_EXCHANGE:
+        Preconditions.checkState(senderWorkers.size() == 
receiverWorkers.size(),
+            "Identity exchange should mean same number of workers in 
sender/receiver");
+        for (int workerId = 0; workerId < senderWorkers.size(); workerId++) {
+          QueryServerInstance senderWorker = senderWorkers.get(workerId);
+          QueryServerInstance receiverWorker = receiverWorkers.get(workerId);
+          MailboxInfos mailboxInfosForSender = new SharedMailboxInfos(new 
MailboxInfo(receiverWorker.getHostname(),
+              receiverWorker.getQueryMailboxPort(), 
ImmutableList.of(workerId)));
+          MailboxInfos mailboxInfosForReceiver = new SharedMailboxInfos(new 
MailboxInfo(senderWorker.getHostname(),
+              senderWorker.getQueryMailboxPort(), ImmutableList.of(workerId)));
+          senderMailboxMap.computeIfAbsent(workerId, (x) -> new 
HashMap<>()).put(receiverStageId,
+              mailboxInfosForSender);
+          receiverMailboxMap.computeIfAbsent(workerId, (x) -> new 
HashMap<>()).put(
+              senderStageId, mailboxInfosForReceiver);
+        }
+        break;
+      case SINGLETON_EXCHANGE: {
+        Preconditions.checkState(receiverWorkers.size() == 1, "Singleton 
expects single instance in receiver");
+        QueryServerInstance receiverWorker = receiverWorkers.get(0);
+        MailboxInfos mailboxInfosForSender = new SharedMailboxInfos(
+            new MailboxInfo(receiverWorker.getHostname(), 
receiverWorker.getQueryMailboxPort(), ImmutableList.of(0)));
+        for (int workerId = 0; workerId < senderWorkers.size(); workerId++) {
+          senderMailboxMap.computeIfAbsent(workerId, (x) -> new HashMap<>())
+              .put(receiverStageId, mailboxInfosForSender);
+        }
+        List<MailboxInfo> mailboxInfoListForReceiver = 
createMailboxInfo(senderWorkers);
+        receiverMailboxMap.computeIfAbsent(0, (x) -> new HashMap<>())
+            .put(senderStageId, new 
SharedMailboxInfos(mailboxInfoListForReceiver));
+        break;
+      }
+      case PARTITIONING_EXCHANGE:
+      case BROADCAST_EXCHANGE: {
+        MailboxInfos mailboxInfoListForSender = new 
MailboxInfos(createMailboxInfo(receiverWorkers));
+        MailboxInfos mailboxInfoListForReceiver = new 
MailboxInfos(createMailboxInfo(senderWorkers));
+        for (int receiverWorkerId = 0; receiverWorkerId < 
receiverWorkers.size(); receiverWorkerId++) {
+          receiverMailboxMap.computeIfAbsent(receiverWorkerId, (x) -> new 
HashMap<>()).put(senderStageId,
+              mailboxInfoListForReceiver);
+        }
+        for (int senderWorkerId = 0; senderWorkerId < senderWorkers.size(); 
senderWorkerId++) {
+          senderMailboxMap.computeIfAbsent(senderWorkerId, (x) -> new 
HashMap<>()).put(receiverStageId,
+              mailboxInfoListForSender);
+        }
+        break;
+      }
+      default:
+        throw new UnsupportedOperationException("exchange desc not supported 
yet: " + exchangeDesc);
+    }
+  }
+
+  private static List<MailboxInfo> createMailboxInfo(Map<Integer, 
QueryServerInstance> workers) {
+    Map<QueryServerInstance, List<Integer>> workersByUniqueHostPort = new 
HashMap<>();
+    for (var entry : workers.entrySet()) {
+      workersByUniqueHostPort.computeIfAbsent(entry.getValue(), (x) -> new 
ArrayList<>()).add(entry.getKey());
+    }
+    List<MailboxInfo> result = new ArrayList<>();
+    for (var entry : workersByUniqueHostPort.entrySet()) {
+      result.add(new MailboxInfo(entry.getKey().getHostname(), 
entry.getKey().getQueryMailboxPort(), entry.getValue()));
+    }
+    return result;
+  }
+
+  public static class Context {
+    final PhysicalPlannerContext _physicalPlannerContext;
+    Map<Integer, PlanFragment> _planFragmentMap = new HashMap<>();
+    Map<Integer, DispatchablePlanMetadata> _fragmentMetadataMap = new 
HashMap<>();
+
+    public Context(PhysicalPlannerContext physicalPlannerContext) {
+      _physicalPlannerContext = physicalPlannerContext;
+    }
+  }
+
+  public static class Result {
+    public Map<Integer, PlanFragment> _planFragmentMap;
+    public Map<Integer, DispatchablePlanMetadata> _fragmentMetadataMap;
+  }
+}
diff --git 
a/pinot-query-planner/src/test/resources/queries/PhysicalOptimizerPlans.json 
b/pinot-query-planner/src/test/resources/queries/PhysicalOptimizerPlans.json
new file mode 100644
index 0000000000..581679739f
--- /dev/null
+++ b/pinot-query-planner/src/test/resources/queries/PhysicalOptimizerPlans.json
@@ -0,0 +1,425 @@
+{
+  "physical_opt_join_planning_tests": {
+    "queries": [
+      {
+        "description": "Inner join with order by",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR SELECT a.col1, 
a.ts, b.col3 FROM a JOIN b ON a.col1 = b.col2 ORDER BY a.col1",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalSort(sort0=[$0], dir0=[ASC])",
+          "\n  PhysicalExchange(exchangeStrategy=[SINGLETON_EXCHANGE], 
distKeys=[[]], execStrategy=[STREAMING], collation=[[]])",
+          "\n    PhysicalProject(col1=[$0], ts=[$1], col3=[$3])",
+          "\n      PhysicalJoin(condition=[=($0, $2)], joinType=[inner])",
+          "\n        
PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], distKeys=[[0]], 
execStrategy=[STREAMING], collation=[[]])",
+          "\n          PhysicalProject(col1=[$0], ts=[$7])",
+          "\n            PhysicalTableScan(table=[[default, a]])",
+          "\n        
PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], distKeys=[[0]], 
execStrategy=[STREAMING], collation=[[]])",
+          "\n          PhysicalProject(col2=[$1], col3=[$2])",
+          "\n            PhysicalTableScan(table=[[default, b]])",
+          "\n"
+        ]
+      },
+      {
+        "description": "Inner join with order by and select column with alias",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR SELECT a.col1 
AS value1, a.ts AS ts1, b.col3 FROM a JOIN b ON a.col1 = b.col2 ORDER BY 
a.col1",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalSort(sort0=[$0], dir0=[ASC])",
+          "\n  PhysicalExchange(exchangeStrategy=[SINGLETON_EXCHANGE], 
distKeys=[[]], execStrategy=[STREAMING], collation=[[]])",
+          "\n    PhysicalProject(value1=[$0], ts1=[$1], col3=[$3])",
+          "\n      PhysicalJoin(condition=[=($0, $2)], joinType=[inner])",
+          "\n        
PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], distKeys=[[0]], 
execStrategy=[STREAMING], collation=[[]])",
+          "\n          PhysicalProject(col1=[$0], ts=[$7])",
+          "\n            PhysicalTableScan(table=[[default, a]])",
+          "\n        
PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], distKeys=[[0]], 
execStrategy=[STREAMING], collation=[[]])",
+          "\n          PhysicalProject(col2=[$1], col3=[$2])",
+          "\n            PhysicalTableScan(table=[[default, b]])",
+          "\n"
+        ]
+      },
+      {
+        "description": "SELECT * inner join",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR SELECT * FROM 
a JOIN b ON a.col1 = b.col2",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalJoin(condition=[=($0, $10)], joinType=[inner])",
+          "\n  PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], 
distKeys=[[0]], execStrategy=[STREAMING], collation=[[]])",
+          "\n    PhysicalTableScan(table=[[default, a]])",
+          "\n  PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], 
distKeys=[[1]], execStrategy=[STREAMING], collation=[[]])",
+          "\n    PhysicalTableScan(table=[[default, b]])",
+          "\n"
+        ]
+      },
+      {
+        "description": "SELECT * inner join with filter on one table",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR SELECT * FROM 
a JOIN b ON a.col1 = b.col2 WHERE a.col3 >= 0",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalJoin(condition=[=($0, $10)], joinType=[inner])",
+          "\n  PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], 
distKeys=[[0]], execStrategy=[STREAMING], collation=[[]])",
+          "\n    PhysicalFilter(condition=[>=($2, 0)])",
+          "\n      PhysicalTableScan(table=[[default, a]])",
+          "\n  PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], 
distKeys=[[1]], execStrategy=[STREAMING], collation=[[]])",
+          "\n    PhysicalTableScan(table=[[default, b]])",
+          "\n"
+        ]
+      },
+      {
+        "description": "SELECT * inner join with filter",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR SELECT * FROM 
a JOIN b ON a.col1 = b.col2 WHERE a.col3 >= 0 AND a.col3 > b.col3",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalJoin(condition=[AND(=($0, $10), >($2, $11))], 
joinType=[inner])",
+          "\n  PhysicalExchange(exchangeStrategy=[IDENTITY_EXCHANGE], 
distKeys=[[]], execStrategy=[STREAMING], collation=[[]])",
+          "\n    PhysicalFilter(condition=[>=($2, 0)])",
+          "\n      PhysicalTableScan(table=[[default, a]])",
+          "\n  PhysicalExchange(exchangeStrategy=[BROADCAST_EXCHANGE], 
distKeys=[[]], execStrategy=[STREAMING], collation=[[]])",
+          "\n    PhysicalTableScan(table=[[default, b]])",
+          "\n"
+        ]
+      },
+      {
+        "description": "SELECT * inner join on 2 columns equality",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR SELECT * FROM 
a JOIN b on a.col1 = b.col1 AND a.col2 = b.col2",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalJoin(condition=[AND(=($0, $9), =($1, $10))], 
joinType=[inner])",
+          "\n  PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], 
distKeys=[[0, 1]], execStrategy=[STREAMING], collation=[[]])",
+          "\n    PhysicalTableScan(table=[[default, a]])",
+          "\n  PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], 
distKeys=[[0, 1]], execStrategy=[STREAMING], collation=[[]])",
+          "\n    PhysicalTableScan(table=[[default, b]])",
+          "\n"
+        ]
+      }
+    ]
+  },
+  "physical_opt_semi_join_planning_tests": {
+    "queries": [
+      {
+        "description": "Single semi-join",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR SELECT col1, 
col2 FROM a WHERE col3 IN (SELECT col3 FROM b)",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalProject(col1=[$0], col2=[$1])",
+          "\n  PhysicalJoin(condition=[=($2, $3)], joinType=[semi])",
+          "\n    PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], 
distKeys=[[2]], execStrategy=[STREAMING], collation=[[]])",
+          "\n      PhysicalProject(col1=[$0], col2=[$1], col3=[$2])",
+          "\n        PhysicalTableScan(table=[[default, a]])",
+          "\n    PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], 
distKeys=[[0]], execStrategy=[STREAMING], collation=[[]])",
+          "\n      PhysicalProject(col3=[$2])",
+          "\n        PhysicalTableScan(table=[[default, b]])",
+          "\n"
+        ]
+      },
+      {
+        "description": "self semi-join on single server table",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR SELECT col1, 
col2 FROM b WHERE col3 IN (SELECT col3 FROM b)",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalProject(col1=[$0], col2=[$1])",
+          "\n  PhysicalJoin(condition=[=($2, $3)], joinType=[semi])",
+          "\n    PhysicalExchange(exchangeStrategy=[IDENTITY_EXCHANGE], 
distKeys=[[]], execStrategy=[STREAMING], collation=[[]])",
+          "\n      PhysicalProject(col1=[$0], col2=[$1], col3=[$2])",
+          "\n        PhysicalTableScan(table=[[default, b]])",
+          "\n    PhysicalExchange(exchangeStrategy=[IDENTITY_EXCHANGE], 
distKeys=[[]], execStrategy=[STREAMING], collation=[[]])",
+          "\n      PhysicalProject(col3=[$2])",
+          "\n        PhysicalTableScan(table=[[default, b]])",
+          "\n"
+        ]
+      },
+      {
+        "description": "Multiple semi-join",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR SELECT col1, 
col2 FROM a WHERE col3 IN (SELECT col3 FROM b WHERE col2='foo') AND col3 IN 
(SELECT col3 FROM b WHERE col2='bar') AND col3 IN (SELECT col3 FROM b WHERE 
col2='lorem')",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalProject(col1=[$0], col2=[$1])",
+          "\n  PhysicalJoin(condition=[=($2, $3)], joinType=[semi])",
+          "\n    PhysicalJoin(condition=[=($2, $3)], joinType=[semi])",
+          "\n      PhysicalJoin(condition=[=($2, $3)], joinType=[semi])",
+          "\n        
PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], distKeys=[[2]], 
execStrategy=[STREAMING], collation=[[]])",
+          "\n          PhysicalProject(col1=[$0], col2=[$1], col3=[$2])",
+          "\n            PhysicalTableScan(table=[[default, a]])",
+          "\n        
PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], distKeys=[[0]], 
execStrategy=[STREAMING], collation=[[]])",
+          "\n          PhysicalProject(col3=[$2])",
+          "\n            PhysicalFilter(condition=[=($1, _UTF-8'foo')])",
+          "\n              PhysicalTableScan(table=[[default, b]])",
+          "\n      PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], 
distKeys=[[0]], execStrategy=[STREAMING], collation=[[]])",
+          "\n        PhysicalProject(col3=[$2])",
+          "\n          PhysicalFilter(condition=[=($1, _UTF-8'bar')])",
+          "\n            PhysicalTableScan(table=[[default, b]])",
+          "\n    PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], 
distKeys=[[0]], execStrategy=[STREAMING], collation=[[]])",
+          "\n      PhysicalProject(col3=[$2])",
+          "\n        PhysicalFilter(condition=[=($1, _UTF-8'lorem')])",
+          "\n          PhysicalTableScan(table=[[default, b]])",
+          "\n"
+        ]
+      },
+      {
+        "description": "semi-join, followed by anti semi-join with 
single-server table, followed by another semi-join",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR SELECT col1, 
col2 FROM a WHERE col3 IN (SELECT col3 FROM b WHERE col2='foo') AND col3 NOT IN 
(SELECT col3 FROM b WHERE col2='bar') AND col3 IN (SELECT col3 FROM b WHERE 
col2='lorem')",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalProject(col1=[$0], col2=[$1])",
+          "\n  PhysicalJoin(condition=[=($2, $3)], joinType=[semi])",
+          "\n    PhysicalProject(col1=[$0], col2=[$1], col3=[$2])",
+          "\n      PhysicalFilter(condition=[IS NOT TRUE($5)])",
+          "\n        PhysicalJoin(condition=[=($3, $4)], joinType=[left])",
+          "\n          PhysicalProject(col1=[$0], col2=[$1], col3=[$2], 
col31=[$2])",
+          "\n            PhysicalJoin(condition=[=($2, $3)], joinType=[semi])",
+          "\n              
PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], distKeys=[[2]], 
execStrategy=[STREAMING], collation=[[]])",
+          "\n                PhysicalProject(col1=[$0], col2=[$1], col3=[$2])",
+          "\n                  PhysicalTableScan(table=[[default, a]])",
+          "\n              
PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], distKeys=[[0]], 
execStrategy=[STREAMING], collation=[[]])",
+          "\n                PhysicalProject(col3=[$2])",
+          "\n                  PhysicalFilter(condition=[=($1, _UTF-8'foo')])",
+          "\n                    PhysicalTableScan(table=[[default, b]])",
+          "\n          
PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], distKeys=[[0]], 
execStrategy=[STREAMING], collation=[[]])",
+          "\n            PhysicalAggregate(group=[{0}], agg#0=[MIN($1)])",
+          "\n              PhysicalProject(col3=[$2], $f1=[true])",
+          "\n                PhysicalFilter(condition=[=($1, _UTF-8'bar')])",
+          "\n                  PhysicalTableScan(table=[[default, b]])",
+          "\n    PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], 
distKeys=[[0]], execStrategy=[STREAMING], collation=[[]])",
+          "\n      PhysicalProject(col3=[$2])",
+          "\n        PhysicalFilter(condition=[=($1, _UTF-8'lorem')])",
+          "\n          PhysicalTableScan(table=[[default, b]])",
+          "\n"
+        ]
+      },
+      {
+        "description": "semi-join, followed by anti semi-join on same fact 
table, followed by another semi-join",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR SELECT col1, 
col2 FROM a WHERE col3 IN (SELECT col3 FROM b WHERE col2='foo') AND col3 NOT IN 
(SELECT col3 FROM a WHERE col2='bar') AND col3 IN (SELECT col3 FROM b WHERE 
col2='lorem')",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalProject(col1=[$0], col2=[$1])",
+          "\n  PhysicalJoin(condition=[=($2, $3)], joinType=[semi])",
+          "\n    PhysicalProject(col1=[$0], col2=[$1], col3=[$2])",
+          "\n      PhysicalFilter(condition=[IS NOT TRUE($5)])",
+          "\n        PhysicalJoin(condition=[=($3, $4)], joinType=[left])",
+          "\n          PhysicalProject(col1=[$0], col2=[$1], col3=[$2], 
col31=[$2])",
+          "\n            PhysicalJoin(condition=[=($2, $3)], joinType=[semi])",
+          "\n              
PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], distKeys=[[2]], 
execStrategy=[STREAMING], collation=[[]])",
+          "\n                PhysicalProject(col1=[$0], col2=[$1], col3=[$2])",
+          "\n                  PhysicalTableScan(table=[[default, a]])",
+          "\n              
PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], distKeys=[[0]], 
execStrategy=[STREAMING], collation=[[]])",
+          "\n                PhysicalProject(col3=[$2])",
+          "\n                  PhysicalFilter(condition=[=($1, _UTF-8'foo')])",
+          "\n                    PhysicalTableScan(table=[[default, b]])",
+          "\n          PhysicalAggregate(group=[{0}], agg#0=[MIN($1)])",
+          "\n            
PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], distKeys=[[0]], 
execStrategy=[STREAMING], collation=[[]])",
+          "\n              PhysicalAggregate(group=[{0}], agg#0=[MIN($1)])",
+          "\n                PhysicalProject(col3=[$2], $f1=[true])",
+          "\n                  PhysicalFilter(condition=[=($1, _UTF-8'bar')])",
+          "\n                    PhysicalTableScan(table=[[default, a]])",
+          "\n    PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], 
distKeys=[[0]], execStrategy=[STREAMING], collation=[[]])",
+          "\n      PhysicalProject(col3=[$2])",
+          "\n        PhysicalFilter(condition=[=($1, _UTF-8'lorem')])",
+          "\n          PhysicalTableScan(table=[[default, b]])",
+          "\n"
+        ]
+      }
+    ]
+  },
+  "physical_opt_auto_identity_tests": {
+    "queries": [
+      {
+        "description": "Self semi-joins",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR SELECT col1, 
col2 FROM a WHERE col2 IN (SELECT col2 FROM a WHERE col3 = 'foo') AND col2 IN 
(SELECT col2 FROM a WHERE col3 = 'bar')",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalJoin(condition=[=($1, $2)], joinType=[semi])",
+          "\n  PhysicalJoin(condition=[=($1, $2)], joinType=[semi])",
+          "\n    PhysicalExchange(exchangeStrategy=[IDENTITY_EXCHANGE], 
distKeys=[[]], execStrategy=[STREAMING], collation=[[]])",
+          "\n      PhysicalProject(col1=[$0], col2=[$1])",
+          "\n        PhysicalTableScan(table=[[default, a]])",
+          "\n    PhysicalExchange(exchangeStrategy=[IDENTITY_EXCHANGE], 
distKeys=[[]], execStrategy=[STREAMING], collation=[[]])",
+          "\n      PhysicalProject(col2=[$1])",
+          "\n        PhysicalFilter(condition=[=($2, CAST(_UTF-8'foo'):INTEGER 
NOT NULL)])",
+          "\n          PhysicalTableScan(table=[[default, a]])",
+          "\n  PhysicalExchange(exchangeStrategy=[IDENTITY_EXCHANGE], 
distKeys=[[]], execStrategy=[STREAMING], collation=[[]])",
+          "\n    PhysicalProject(col2=[$1])",
+          "\n      PhysicalFilter(condition=[=($2, CAST(_UTF-8'bar'):INTEGER 
NOT NULL)])",
+          "\n        PhysicalTableScan(table=[[default, a]])",
+          "\n"
+        ]
+      },
+      {
+        "description": "Self semi and anti semi-joins",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR SELECT col1, 
col2 FROM a WHERE col2 IN (SELECT col2 FROM a WHERE col3 = 'foo') AND col2 NOT 
IN (SELECT col2 FROM a WHERE col3 = 'bar') AND col2 IN (SELECT col2 FROM a 
WHERE col3 = 'lorem')",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalJoin(condition=[=($1, $2)], joinType=[semi])",
+          "\n  PhysicalProject(col1=[$0], col2=[$1])",
+          "\n    PhysicalFilter(condition=[IS NOT TRUE($4)])",
+          "\n      PhysicalJoin(condition=[=($2, $3)], joinType=[left])",
+          "\n        PhysicalProject(col1=[$0], col2=[$1], col21=[$1])",
+          "\n          PhysicalJoin(condition=[=($1, $2)], joinType=[semi])",
+          "\n            
PhysicalExchange(exchangeStrategy=[IDENTITY_EXCHANGE], distKeys=[[]], 
execStrategy=[STREAMING], collation=[[]])",
+          "\n              PhysicalProject(col1=[$0], col2=[$1])",
+          "\n                PhysicalTableScan(table=[[default, a]])",
+          "\n            
PhysicalExchange(exchangeStrategy=[IDENTITY_EXCHANGE], distKeys=[[]], 
execStrategy=[STREAMING], collation=[[]])",
+          "\n              PhysicalProject(col2=[$1])",
+          "\n                PhysicalFilter(condition=[=($2, 
CAST(_UTF-8'foo'):INTEGER NOT NULL)])",
+          "\n                  PhysicalTableScan(table=[[default, a]])",
+          "\n        PhysicalExchange(exchangeStrategy=[IDENTITY_EXCHANGE], 
distKeys=[[]], execStrategy=[STREAMING], collation=[[]])",
+          "\n          PhysicalAggregate(group=[{0}], agg#0=[MIN($1)])",
+          "\n            PhysicalProject(col2=[$1], $f1=[true])",
+          "\n              PhysicalFilter(condition=[=($2, 
CAST(_UTF-8'bar'):INTEGER NOT NULL)])",
+          "\n                PhysicalTableScan(table=[[default, a]])",
+          "\n  PhysicalExchange(exchangeStrategy=[IDENTITY_EXCHANGE], 
distKeys=[[]], execStrategy=[STREAMING], collation=[[]])",
+          "\n    PhysicalProject(col2=[$1])",
+          "\n      PhysicalFilter(condition=[=($2, CAST(_UTF-8'lorem'):INTEGER 
NOT NULL)])",
+          "\n        PhysicalTableScan(table=[[default, a]])",
+          "\n"
+        ]
+      },
+      {
+        "description": "Self semi and anti semi-joins with aggregation in the 
end",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR SELECT col1, 
COUNT(*) FROM a WHERE col2 IN (SELECT col2 FROM a WHERE col3 = 'foo') AND col2 
NOT IN (SELECT col2 FROM a WHERE col3 = 'bar') AND col2 IN (SELECT col2 FROM a 
WHERE col3 = 'lorem') GROUP BY col1",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalAggregate(group=[{0}], agg#0=[COUNT($1)])",
+          "\n  PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], 
distKeys=[[0]], execStrategy=[STREAMING], collation=[[]])",
+          "\n    PhysicalAggregate(group=[{0}], agg#0=[COUNT()])",
+          "\n      PhysicalJoin(condition=[=($1, $2)], joinType=[semi])",
+          "\n        PhysicalProject(col1=[$0], col2=[$1])",
+          "\n          PhysicalFilter(condition=[IS NOT TRUE($4)])",
+          "\n            PhysicalJoin(condition=[=($2, $3)], joinType=[left])",
+          "\n              PhysicalProject(col1=[$0], col2=[$1], col21=[$1])",
+          "\n                PhysicalJoin(condition=[=($1, $2)], 
joinType=[semi])",
+          "\n                  
PhysicalExchange(exchangeStrategy=[IDENTITY_EXCHANGE], distKeys=[[]], 
execStrategy=[STREAMING], collation=[[]])",
+          "\n                    PhysicalProject(col1=[$0], col2=[$1])",
+          "\n                      PhysicalTableScan(table=[[default, a]])",
+          "\n                  
PhysicalExchange(exchangeStrategy=[IDENTITY_EXCHANGE], distKeys=[[]], 
execStrategy=[STREAMING], collation=[[]])",
+          "\n                    PhysicalProject(col2=[$1])",
+          "\n                      PhysicalFilter(condition=[=($2, 
CAST(_UTF-8'foo'):INTEGER NOT NULL)])",
+          "\n                        PhysicalTableScan(table=[[default, a]])",
+          "\n              
PhysicalExchange(exchangeStrategy=[IDENTITY_EXCHANGE], distKeys=[[]], 
execStrategy=[STREAMING], collation=[[]])",
+          "\n                PhysicalAggregate(group=[{0}], agg#0=[MIN($1)])",
+          "\n                  PhysicalProject(col2=[$1], $f1=[true])",
+          "\n                    PhysicalFilter(condition=[=($2, 
CAST(_UTF-8'bar'):INTEGER NOT NULL)])",
+          "\n                      PhysicalTableScan(table=[[default, a]])",
+          "\n        PhysicalExchange(exchangeStrategy=[IDENTITY_EXCHANGE], 
distKeys=[[]], execStrategy=[STREAMING], collation=[[]])",
+          "\n          PhysicalProject(col2=[$1])",
+          "\n            PhysicalFilter(condition=[=($2, 
CAST(_UTF-8'lorem'):INTEGER NOT NULL)])",
+          "\n              PhysicalTableScan(table=[[default, a]])",
+          "\n"
+        ]
+      }
+    ]
+  },
+  "physical_opt_misc_auto_identity": {
+    "queries": [
+      {
+        "description": "Union, distinct, etc. but still maximally identity 
exchange",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR WITH tmp AS 
(SELECT col2 FROM a WHERE col1 = 'foo' UNION ALL SELECT col2 FROM a WHERE col3 
= 'bar'), tmp2 AS (SELECT DISTINCT col2 FROM tmp) SELECT COUNT(*), col3 FROM a 
WHERE col2 IN (SELECT col2 FROM tmp2) GROUP BY col3",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalProject(EXPR$0=[$1], col3=[$0])",
+          "\n  PhysicalAggregate(group=[{0}], agg#0=[COUNT($1)])",
+          "\n    PhysicalExchange(exchangeStrategy=[PARTITIONING_EXCHANGE], 
distKeys=[[0]], execStrategy=[STREAMING], collation=[[]])",
+          "\n      PhysicalAggregate(group=[{1}], agg#0=[COUNT()])",
+          "\n        PhysicalJoin(condition=[=($0, $2)], joinType=[semi])",
+          "\n          PhysicalExchange(exchangeStrategy=[IDENTITY_EXCHANGE], 
distKeys=[[]], execStrategy=[STREAMING], collation=[[]])",
+          "\n            PhysicalProject(col2=[$1], col3=[$2])",
+          "\n              PhysicalTableScan(table=[[default, a]])",
+          "\n          PhysicalAggregate(group=[{0}])",
+          "\n            PhysicalUnion(all=[true])",
+          "\n              
PhysicalExchange(exchangeStrategy=[IDENTITY_EXCHANGE], distKeys=[[]], 
execStrategy=[STREAMING], collation=[[]])",
+          "\n                PhysicalProject(col2=[$1])",
+          "\n                  PhysicalFilter(condition=[=($0, _UTF-8'foo')])",
+          "\n                    PhysicalTableScan(table=[[default, a]])",
+          "\n              
PhysicalExchange(exchangeStrategy=[IDENTITY_EXCHANGE], distKeys=[[]], 
execStrategy=[STREAMING], collation=[[]])",
+          "\n                PhysicalProject(col2=[$1])",
+          "\n                  PhysicalFilter(condition=[=($2, 
CAST(_UTF-8'bar'):INTEGER NOT NULL)])",
+          "\n                    PhysicalTableScan(table=[[default, a]])",
+          "\n"
+        ]
+      }
+    ]
+  },
+  "physical_opt_simple_sort_queries": {
+    "queries": [
+      {
+        "description": "",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR SELECT col2, 
col3 FROM a WHERE col1 = 'foo' ORDER BY col2",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalSort(sort0=[$0], dir0=[ASC])",
+          "\n  PhysicalExchange(exchangeStrategy=[SINGLETON_EXCHANGE], 
distKeys=[[]], execStrategy=[STREAMING], collation=[[]])",
+          "\n    PhysicalProject(col2=[$1], col3=[$2])",
+          "\n      PhysicalFilter(condition=[=($0, _UTF-8'foo')])",
+          "\n        PhysicalTableScan(table=[[default, a]])",
+          "\n"
+        ]
+      },
+      {
+        "description": "",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR SELECT col2, 
col3 FROM a WHERE col1 = 'foo' ORDER BY col2 LIMIT 10",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalSort(sort0=[$0], dir0=[ASC], fetch=[10])",
+          "\n  PhysicalExchange(exchangeStrategy=[SINGLETON_EXCHANGE], 
distKeys=[[]], execStrategy=[STREAMING], collation=[[]])",
+          "\n    PhysicalSort(sort0=[$0], dir0=[ASC], fetch=[10])",
+          "\n      PhysicalProject(col2=[$1], col3=[$2])",
+          "\n        PhysicalFilter(condition=[=($0, _UTF-8'foo')])",
+          "\n          PhysicalTableScan(table=[[default, a]])",
+          "\n"
+        ]
+      },
+      {
+        "description": "",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR SELECT col2, 
col3 FROM a WHERE col1 = 'foo' ORDER BY col2 LIMIT 10, 11",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalSort(sort0=[$0], dir0=[ASC], offset=[10], fetch=[11])",
+          "\n  PhysicalExchange(exchangeStrategy=[SINGLETON_EXCHANGE], 
distKeys=[[]], execStrategy=[STREAMING], collation=[[]])",
+          "\n    PhysicalSort(sort0=[$0], dir0=[ASC], fetch=[21])",
+          "\n      PhysicalProject(col2=[$1], col3=[$2])",
+          "\n        PhysicalFilter(condition=[=($0, _UTF-8'foo')])",
+          "\n          PhysicalTableScan(table=[[default, a]])",
+          "\n"
+        ]
+      },
+      {
+        "description": "",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR SELECT col2, 
col3 FROM a WHERE col1 = 'foo' LIMIT 10, 11",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalSort(offset=[10], fetch=[11])",
+          "\n  PhysicalExchange(exchangeStrategy=[SINGLETON_EXCHANGE], 
distKeys=[[]], execStrategy=[STREAMING], collation=[[]])",
+          "\n    PhysicalSort(fetch=[21])",
+          "\n      PhysicalProject(col2=[$1], col3=[$2])",
+          "\n        PhysicalFilter(condition=[=($0, _UTF-8'foo')])",
+          "\n          PhysicalTableScan(table=[[default, a]])",
+          "\n"
+        ]
+      },
+      {
+        "description": "",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR SELECT col2, 
COUNT(*) as cnt FROM a GROUP BY col2 ORDER BY cnt LIMIT 100",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalSort(sort0=[$1], dir0=[ASC], fetch=[100])",
+          "\n  PhysicalExchange(exchangeStrategy=[SINGLETON_EXCHANGE], 
distKeys=[[]], execStrategy=[STREAMING], collation=[[]])",
+          "\n    PhysicalSort(sort0=[$1], dir0=[ASC], fetch=[100])",
+          "\n      PhysicalAggregate(group=[{1}], agg#0=[COUNT()])",
+          "\n        PhysicalTableScan(table=[[default, a]])",
+          "\n"
+        ]
+      },
+      {
+        "description": "",
+        "sql": "SET usePhysicalOptimizer=true; EXPLAIN PLAN FOR SELECT col2, 
COUNT(*) as cnt FROM b GROUP BY col2 ORDER BY cnt LIMIT 100",
+        "output": [
+          "Execution Plan",
+          "\nPhysicalSort(sort0=[$1], dir0=[ASC], fetch=[100])",
+          "\n  PhysicalExchange(exchangeStrategy=[IDENTITY_EXCHANGE], 
distKeys=[[]], execStrategy=[STREAMING], collation=[[]])",
+          "\n    PhysicalSort(sort0=[$1], dir0=[ASC], fetch=[100])",
+          "\n      PhysicalAggregate(group=[{1}], agg#0=[COUNT()])",
+          "\n        PhysicalTableScan(table=[[default, b]])",
+          "\n"
+        ]
+      }
+    ]
+  }
+}
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 11e8f0d71e..1fbe76a540 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
@@ -513,6 +513,7 @@ public class CommonConstants {
         public static final String ENABLE_NULL_HANDLING = "enableNullHandling";
         public static final String APPLICATION_NAME = "applicationName";
         public static final String USE_SPOOLS = "useSpools";
+        public static final String USE_PHYSICAL_OPTIMIZER = 
"usePhysicalOptimizer";
         /**
          * If set, changes the explain behavior in multi-stage engine.
          *


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

Reply via email to