This is an automated email from the ASF dual-hosted git repository.
englefly pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/master by this push:
new d8e4e042193 [improvement](hbo) Build HBO struct info from detached
physical plans (#70636)
d8e4e042193 is described below
commit d8e4e04219309fbc97f066a9dd4fe8f35c1be24a
Author: minghong <[email protected]>
AuthorDate: Wed Dec 2 14:23:25 2026 +0800
[improvement](hbo) Build HBO struct info from detached physical plans
(#70636)
### Background
HBO identifies a plan subtree with GroupStructInfo and uses its
structural fingerprint to look up pinned and learned row counts. The
current builder follows Memo groups. Profile physical-plan copies
deliberately detach their GroupExpression references so that retained
profiles do not retain the optimizer.
### What problem does this PR solve?
Issue Number: None
Related PR: #69322 (prerequisite, cherry-picked), #70332 (prerequisite,
cherry-picked)
PR Type: Enhancement
Problem Summary:
Add an on-demand GroupStructInfo.fromPhysicalPlan entry point for
selected subtrees of a detached physical plan. It shares
node-description construction, expression normalization, rendering and
fingerprint encoding with the Memo builder. This enables a later
learned-HBO collector to select candidates after execution without
computing every fingerprint during planning or retaining Memo.
### Details
- **Change map:** The final enhancement commit changes one production
file (239 added / 40 removed lines) and adds 400 lines in two test
files. The branch also includes all prerequisite commits from #69322 and
#70332; review the final commit for this enhancement.
- **Before and after:** Previously, structInfo required a
GroupExpression or a group-ID-to-Group map. The new entry point follows
physical children directly and needs neither. Physical distributions and
sorts are transparent, inner join chains are flattened and ordered,
computed projection definitions are resolved, and aggregate execution
wrappers are replaced with their original function identity.
- **Stage semantics:** Matching two-stage non-distinct aggregates and
merge TopN implementations are normalized to their logical identity.
SplitLimit runs before Memo construction, so its two levels remain part
of the structural identity. Partial roots, DISTINCT aggregation phases,
unmatched aggregation/TopN stages and shared physical inputs return
explicit unsupported reasons.
- **Configs and defaults:** No new configuration or production caller.
Existing HBO collection, publishing and Profile behavior remain
unchanged. The caller must use the execution session context when
building/materializing session-dependent expressions; scan metadata is
read when the description is built.
- **Impact on existing users:** Existing Memo fingerprints and
serialized key formats are preserved. This does not introduce level 0
collection or replace the existing learned-HBO publishing path.
### Testing
- `./run-fe-ut.sh --run` with 22 explicitly named stats/Profile test
classes: 234 existing tests passed. Two fixture failures in the new
classes were corrected (clone the whole RF-connected plan; use analyzed
Union output slots).
- `MAVEN_OPTS="-Dmaven.main.skip=true" ./run-fe-ut.sh --run
'org.apache.doris.nereids.stats.PhysicalPlanStructInfoTest,org.apache.doris.nereids.stats.PhysicalPlanStructInfoPlannerTest'`:
all 11 new tests passed after those corrections. Production classes were
reused from the preceding full compilation; only test sources changed.
Combined result: 245 passing tests across 22 classes.
- The new tests compare canonical descriptions, shapes and fingerprints
in both literal modes; cover scan/filter/project, hash and nested-loop
joins, join reordering, single/two-stage aggregation and HAVING, nested
aggregates, distributed bounds, Union mappings and unsupported cases.
Real post-processed plans are compared after Memo release, and a pinned
entry keyed from a clone is applied during replanning.
- `mvn -f fe/pom.xml checkstyle:check -pl fe-core`: passed, zero
violations.
- `git diff --cached --check`: passed.
- Full BE/FE packaging and regression suites were not run locally; `run
buildall` and `/review` will be requested on this Draft PR.
### Notes for Reviewers
- Clone the complete physical plan before selecting candidate subtrees:
runtime filters can connect a subtree to other nodes. The planner test
uses a full clone and verifies that Memo has been released before
describing candidates.
- Concurrency and lifecycle: traversal state is local to one call; no
threads, locks or global caches are introduced. The physical visited set
is allocated only for the new entry point.
- Errors and observability: unsupported structures return an invalid
description with a reason, following the existing structInfo contract;
invariant failures are not silently converted into approximate keys.
- Memory: the new traversal never resolves a Group or group ID and
retains no Memo references from detached input plans.
- Correctness and compatibility: golden keys, both literal modes,
physical/Memo equivalence and pinned lookup are checked. Execution,
transaction visibility and persistent metadata are unchanged. BE
nullable handling is not applicable.
### Release note
None
### Check List (For Author)
- Behavior changed: No (new internal entry point only)
- Does this need documentation: No
- Pre-submission status: Partially verified: local FE tests and
Checkstyle; full build and regression CI pending. Submitted as Draft as
requested.
### AI Disclosure
- Tool: OpenAI Codex
- Generated: Implementation, tests, commit message and PR description.
- Human review: Not yet reviewed by the author; submitted as Draft.
---
.../AddMonotonicFunctionPruningPredicates.java | 9 +-
.../doris/nereids/stats/GroupStructInfo.java | 288 ++++++++++++++++++---
.../trees/plans/physical/PhysicalFilter.java | 22 +-
.../plans/physical/PhysicalPlanShallowCopier.java | 2 +
.../apache/doris/nereids/util/MutableState.java | 2 +
.../AddMonotonicFunctionPruningPredicatesTest.java | 4 +
.../stats/PhysicalPlanStructInfoPlannerTest.java | 162 ++++++++++++
.../nereids/stats/PhysicalPlanStructInfoTest.java | 269 +++++++++++++++++++
8 files changed, 710 insertions(+), 48 deletions(-)
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/AddMonotonicFunctionPruningPredicates.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/AddMonotonicFunctionPruningPredicates.java
index 67d1eb7af0f..18829a43b11 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/AddMonotonicFunctionPruningPredicates.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/AddMonotonicFunctionPruningPredicates.java
@@ -36,6 +36,7 @@ import
org.apache.doris.nereids.trees.plans.physical.PhysicalOlapScan;
import
org.apache.doris.nereids.trees.plans.physical.PhysicalStorageLayerAggregate;
import org.apache.doris.nereids.trees.plans.physical.PhysicalTVFRelation;
import org.apache.doris.nereids.util.ExpressionUtils;
+import org.apache.doris.nereids.util.MutableState;
import java.util.LinkedHashSet;
import java.util.Set;
@@ -64,8 +65,14 @@ public class AddMonotonicFunctionPruningPredicates extends
PlanPostProcessor {
if (rewrittenConjuncts.equals(filter.getConjuncts())) {
return filter;
}
- return filter.withConjunctsAndChild(rewrittenConjuncts, child)
+ AbstractPhysicalPlan rewritten =
filter.withConjunctsAndChild(rewrittenConjuncts, child)
.copyStatsAndGroupIdFrom((AbstractPhysicalPlan) filter);
+ // These execution-only bounds are absent from Memo's HBO key. Keep
the original
+ // immutable conjuncts, including any predicates inferred before
physical post-processing.
+ rewritten.setMutableState(MutableState.KEY_HBO_ORIGINAL_CONJUNCTS,
+
filter.<Set<Expression>>getMutableState(MutableState.KEY_HBO_ORIGINAL_CONJUNCTS)
+ .orElse(filter.getConjuncts()));
+ return rewritten;
}
private static boolean supportsStoragePruning(Plan plan) {
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/GroupStructInfo.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/GroupStructInfo.java
index 62ecc9f552d..80bdb4e47d1 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/GroupStructInfo.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/GroupStructInfo.java
@@ -22,6 +22,7 @@ import org.apache.doris.catalog.TableIf;
import org.apache.doris.nereids.memo.Group;
import org.apache.doris.nereids.memo.GroupExpression;
import org.apache.doris.nereids.properties.OrderKey;
+import org.apache.doris.nereids.trees.expressions.AggregateExpression;
import org.apache.doris.nereids.trees.expressions.Alias;
import org.apache.doris.nereids.trees.expressions.And;
import org.apache.doris.nereids.trees.expressions.ArrayItemReference;
@@ -50,7 +51,9 @@ import
org.apache.doris.nereids.trees.expressions.literal.NullLiteral;
import org.apache.doris.nereids.trees.expressions.literal.StringLiteral;
import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
import org.apache.doris.nereids.trees.plans.AbstractPlan;
+import org.apache.doris.nereids.trees.plans.AggPhase;
import org.apache.doris.nereids.trees.plans.JoinType;
+import org.apache.doris.nereids.trees.plans.LimitPhase;
import org.apache.doris.nereids.trees.plans.Plan;
import org.apache.doris.nereids.trees.plans.algebra.Aggregate;
import org.apache.doris.nereids.trees.plans.algebra.Except;
@@ -79,11 +82,17 @@ import
org.apache.doris.nereids.trees.plans.physical.PhysicalCTEConsumer;
import org.apache.doris.nereids.trees.plans.physical.PhysicalCTEProducer;
import org.apache.doris.nereids.trees.plans.physical.PhysicalDistribute;
import org.apache.doris.nereids.trees.plans.physical.PhysicalFileScan;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalFilter;
import org.apache.doris.nereids.trees.plans.physical.PhysicalGenerate;
import org.apache.doris.nereids.trees.plans.physical.PhysicalHashAggregate;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalLazyMaterialize;
+import
org.apache.doris.nereids.trees.plans.physical.PhysicalLazyMaterializeOlapScan;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalLimit;
import org.apache.doris.nereids.trees.plans.physical.PhysicalOlapScan;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalPlan;
import org.apache.doris.nereids.trees.plans.physical.PhysicalRelation;
import
org.apache.doris.nereids.trees.plans.physical.PhysicalStorageLayerAggregate;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalTopN;
import org.apache.doris.nereids.types.DataType;
import org.apache.doris.nereids.util.MutableState;
import org.apache.doris.qe.ConnectContext;
@@ -101,6 +110,7 @@ import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
+import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
@@ -768,10 +778,209 @@ public class GroupStructInfo {
}
/**
- * The description of a group: computed once per query and memoized on the
group (see
- * {@link Group#getOrComputeHboStructInfo}), so that a parent composes the
description of its
- * children instead of describing their sub trees again.
+ * Describe a selected physical subtree without accessing Memo, group ids
or HBO plan caches.
+ * Suitable for detached profile copies. The caller supplies the
execution's session context while
+ * building and materializing the result (expression identity can depend
on time zone and locale).
+ * Partial aggregation roots and physical transformations whose logical
identity cannot be recovered
+ * are reported as invalid, rather than publishing an entry under an
approximate key.
*/
+ public static GroupStructInfo fromPhysicalPlan(PhysicalPlan plan) {
+ // SplitLimit runs before Memo construction, so a local limit is part
of a parent's
+ // logical identity. Its own per-instance row count is not a logical
cardinality sample.
+ if (plan instanceof PhysicalLimit && ((PhysicalLimit<?>)
plan).getPhase() == LimitPhase.LOCAL) {
+ return invalidStructInfo("unsupported=local limit cardinality");
+ }
+ Ctx ctx = new Ctx();
+ ctx.physicalVisited = Collections.newSetFromMap(new
IdentityHashMap<>());
+ return describePhysical(plan, ctx);
+ }
+
+ private static GroupStructInfo describePhysical(PhysicalPlan plan, Ctx
ctx) {
+ if (!ctx.physicalVisited.add(plan)) {
+ return invalidStructInfo("sharing=physical plan reached twice");
+ }
+ if (plan instanceof PhysicalLazyMaterializeOlapScan) {
+ return describePhysical(((PhysicalLazyMaterializeOlapScan)
plan).getScan(), ctx);
+ }
+ Plan semanticPlan = plan;
+ if (plan instanceof PhysicalTopN) {
+ PhysicalTopN<?> topN = (PhysicalTopN<?>) plan;
+ if (topN.getSortPhase().isLocal()) {
+ return invalidStructInfo("unsupported=local topn cardinality");
+ }
+ Plan child = withoutDistribute(topN.child());
+ if (child instanceof PhysicalTopN && ((PhysicalTopN<?>)
child).getSortPhase().isLocal()) {
+ PhysicalTopN<?> local = (PhysicalTopN<?>) child;
+ if (local.getOffset() != 0 || local.getLimit() !=
topN.getLimit() + topN.getOffset()
+ || !local.getOrderKeys().equals(topN.getOrderKeys())) {
+ return invalidStructInfo("unsupported=topn stages differ");
+ }
+ semanticPlan =
topN.withChildren(Collections.singletonList(local.child()));
+ }
+ }
+ if (plan instanceof PhysicalHashAggregate) {
+ PhysicalHashAggregate<?> aggregate = (PhysicalHashAggregate<?>)
plan;
+ if (aggregate.getAggMode().productAggregateBuffer) {
+ return invalidStructInfo(PARTIAL_STAGE_REASON);
+ }
+ if (aggregate.getAggPhase() == AggPhase.DISTINCT_LOCAL
+ || aggregate.getAggPhase() == AggPhase.DISTINCT_GLOBAL) {
+ return invalidStructInfo("unsupported=distinct aggregation
stages");
+ }
+ if (aggregate.getAggMode().consumeAggregateBuffer) {
+ // The merge stage describes one logical aggregate, not an
aggregate of partial groups.
+ // Only bypass the matching producer; an independent nested
aggregation stays a boundary.
+ Plan producer = withoutDistribute(aggregate.child());
+ if (!(producer instanceof PhysicalHashAggregate)
+ || !((PhysicalHashAggregate<?>)
producer).getAggMode().productAggregateBuffer) {
+ return invalidStructInfo("unsupported=aggregate buffer
producer");
+ }
+ PhysicalHashAggregate<?> local = (PhysicalHashAggregate<?>)
producer;
+ if (local.getAggPhase() != AggPhase.LOCAL
+ ||
!aggregate.getGroupByExpressions().equals(local.getGroupByExpressions())) {
+ return invalidStructInfo("unsupported=aggregate grouping
changed between stages");
+ }
+ semanticPlan =
aggregate.withChildren(Collections.singletonList(local.child()));
+ }
+ }
+ Node root = buildNode(semanticPlan, new PhysicalInput((PhysicalPlan)
semanticPlan), ctx);
+ if (root == null || !ctx.valid) {
+ return invalidStructInfo(ctx.reason);
+ }
+ applyColumnDefinitions(semanticPlan, root);
+ GroupStructInfo result = ofNode(root);
+ int maxScans = hboMaxScansPerGroup();
+ if (maxScans > 0 && result.getScans().size() > maxScans) {
+ return invalidStructInfo("subtree scans=" +
result.getScans().size()
+ + " > hbo_max_scans_per_group=" + maxScans);
+ }
+ return result;
+ }
+
+ private static Plan withoutDistribute(Plan plan) {
+ while (plan instanceof PhysicalDistribute) {
+ plan = plan.child(0);
+ }
+ return plan;
+ }
+
+ /** Child traversal is the only distinction between Memo and detached
physical inputs. */
+ private interface BuildInput {
+ Plan getPlan();
+
+ int arity();
+
+ GroupStructInfo describeChild(int index, Ctx ctx);
+
+ Node joinChain(Join join, Ctx ctx);
+ }
+
+ private static final class MemoInput implements BuildInput {
+ private final GroupExpression expression;
+
+ private MemoInput(GroupExpression expression) {
+ this.expression = expression;
+ }
+
+ @Override
+ public Plan getPlan() {
+ return expression.getPlan();
+ }
+
+ @Override
+ public int arity() {
+ return expression.arity();
+ }
+
+ @Override
+ public GroupStructInfo describeChild(int index, Ctx ctx) {
+ GroupStructInfo child = describeGroup(expression.child(index),
ctx);
+ if (!child.isValid()) {
+ invalid(ctx, child.getSkipReason());
+ return null;
+ }
+ return child;
+ }
+
+ @Override
+ public Node joinChain(Join join, Ctx ctx) {
+ return joinChainNode(join, expression, ctx);
+ }
+ }
+
+ private static final class PhysicalInput implements BuildInput {
+ private final PhysicalPlan plan;
+
+ private PhysicalInput(PhysicalPlan plan) {
+ this.plan = plan;
+ }
+
+ @Override
+ public Plan getPlan() {
+ return plan;
+ }
+
+ @Override
+ public int arity() {
+ return plan.arity();
+ }
+
+ @Override
+ public GroupStructInfo describeChild(int index, Ctx ctx) {
+ GroupStructInfo child = describePhysical((PhysicalPlan)
plan.child(index), ctx);
+ if (!child.isValid()) {
+ invalid(ctx, child.getSkipReason());
+ return null;
+ }
+ return child;
+ }
+
+ @Override
+ public Node joinChain(Join join, Ctx ctx) {
+ List<Expression> conditions = joinConditions(join);
+ List<Leaf> leaves = new ArrayList<>();
+ for (Plan child : plan.children()) {
+ collectPhysicalChain((PhysicalPlan) child, conditions, leaves,
ctx);
+ }
+ if (!ctx.valid) {
+ return null;
+ }
+ leaves.sort(Comparator.comparing(Leaf::sortKey));
+ Node node = new Node(Kind.JOIN);
+ node.flattenable = true;
+ node.conditions = conditions;
+ for (Leaf leaf : leaves) {
+ node.children.add(new Child(leaf.getLeaf().root(), false));
+ }
+ return node;
+ }
+ }
+
+ private static void collectPhysicalChain(PhysicalPlan plan,
List<Expression> conditions,
+ List<Leaf> leaves, Ctx ctx) {
+ if (plan instanceof Join && isFlattenableJoinType(((Join)
plan).getJoinType())) {
+ if (!ctx.physicalVisited.add(plan)) {
+ invalid(ctx, "sharing=physical join reached twice");
+ return;
+ }
+ mergeConditions(conditions, joinConditions((Join) plan));
+ for (Plan child : plan.children()) {
+ collectPhysicalChain((PhysicalPlan) child, conditions, leaves,
ctx);
+ }
+ } else if (plan instanceof PhysicalDistribute
+ || plan instanceof Sort && !(plan instanceof TopN) ||
isTransparentProject(plan)) {
+ collectPhysicalChain((PhysicalPlan) plan.child(0), conditions,
leaves, ctx);
+ } else {
+ GroupStructInfo leaf = describePhysical(plan, ctx);
+ if (!leaf.isValid()) {
+ invalid(ctx, leaf.getSkipReason());
+ return;
+ }
+ leaves.add(new Leaf(leaf));
+ }
+ }
+
+ /** Build from the representative expressions of a Memo group. */
public static GroupStructInfo of(Group group) {
return describeGroup(group);
}
@@ -894,7 +1103,7 @@ public class GroupStructInfo {
private static GroupStructInfo describeExpression(Group group,
GroupExpression ge, Ctx ctx) {
Node root;
try {
- root = buildNode(ge.getPlan(), ge, ctx);
+ root = buildNode(ge.getPlan(), new MemoInput(ge), ctx);
if (root != null) {
applyColumnDefinitions(ge.getPlan(), root);
}
@@ -963,8 +1172,15 @@ public class GroupStructInfo {
Map<ExprId, Expression> definitions = new LinkedHashMap<>();
for (NamedExpression output : aggregate.getOutputExpressions()) {
if (output instanceof Alias) {
- definitions.put(output.getExprId(),
- resolveColumnDefinitions(((Alias) output).child(),
childDefinitions));
+ Expression definition = ((Alias) output).child();
+ if (aggregate instanceof PhysicalHashAggregate) {
+ // AggregateExpression carries execution phase/buffer
arguments. Its function keeps
+ // the original logical arguments, which are the identity
a HAVING predicate needs.
+ definition = definition.rewriteDownShortCircuit(
+ expression -> expression instanceof
AggregateExpression
+ ? ((AggregateExpression)
expression).getFunction() : expression);
+ }
+ definitions.put(output.getExprId(),
resolveColumnDefinitions(definition, childDefinitions));
}
}
return Collections.unmodifiableMap(definitions);
@@ -1198,24 +1414,6 @@ public class GroupStructInfo {
return null;
}
- /**
- * Step 1 of a node build: describe one child of this node. The child is
described once per query -
- * its memoized description is returned - and a child which cannot be
described invalidates this
- * node with the reason of the child, so that the first reason of the
failing sub tree is the one
- * which is reported.
- */
- private static GroupStructInfo describeChild(GroupExpression ge, int
index, Ctx ctx) {
- if (!ctx.valid) {
- return null;
- }
- GroupStructInfo child = describeGroup(ge.child(index), ctx);
- if (!child.isValid()) {
- invalid(ctx, child.getSkipReason());
- return null;
- }
- return child;
- }
-
/**
* The conditions and the leaves of a join chain, memoized per group: a
chain of n joins used to walk
* its own sub tree once per member (O(n^2) condition renderings for the
whole query), while the
@@ -1564,15 +1762,15 @@ public class GroupStructInfo {
}
}
- // ---------------------------------------------------------------- build
(memo level)
+ // ---------------------------------------------------------------- build
(shared node descriptions)
/**
* Build the description of one node. Every branch follows the same three
steps: the node's own
- * information is collected as objects, its children are described by
{@link #describeChild} (the
- * memoized description of a child group, never its sub tree again), and
both are put into a
+ * information is collected as objects, its children are described through
{@link BuildInput}
+ * (Memo inputs reuse the cached description of each child group), and
both are put into a
* {@link Node} - the rendering happens later and elsewhere.
*/
- private static Node buildNode(Plan plan, GroupExpression ge, Ctx ctx) {
+ private static Node buildNode(Plan plan, BuildInput ge, Ctx ctx) {
if (!ctx.valid) {
return null;
}
@@ -1582,7 +1780,13 @@ public class GroupStructInfo {
return olapScanNode((OlapScan) plan, ctx);
}
if (plan instanceof Filter) {
- return conditionsNode(Kind.FILTER, ((Filter) plan).getConjuncts(),
ge, ctx);
+ Collection<Expression> conjuncts = ((Filter) plan).getConjuncts();
+ if (ge instanceof PhysicalInput && plan instanceof PhysicalFilter)
{
+ conjuncts = ((PhysicalFilter<?>) plan)
+
.<Set<Expression>>getMutableState(MutableState.KEY_HBO_ORIGINAL_CONJUNCTS)
+ .orElse(((Filter) plan).getConjuncts());
+ }
+ return conditionsNode(Kind.FILTER, conjuncts, ge, ctx);
}
if (plan instanceof LogicalCTEConsumer || plan instanceof
PhysicalCTEConsumer) {
// both consumers are leaves which reference their producer by id,
and neither has a sub tree
@@ -1706,7 +1910,8 @@ public class GroupStructInfo {
if (plan instanceof Union || plan instanceof Intersect || plan
instanceof Except) {
return setOperationNode(plan, (SetOperation) plan, ge, ctx);
}
- if (plan instanceof PhysicalDistribute || plan instanceof
PhysicalAssertNumRows
+ if (plan instanceof PhysicalDistribute || plan instanceof
PhysicalLazyMaterialize
+ || plan instanceof PhysicalAssertNumRows
|| plan instanceof Project || plan instanceof Sort) {
// an enforcer, a project and a sort are transparent for structure
matching: none of them
// changes the number of rows, so the nodes above them are
described by the shape below and
@@ -1742,7 +1947,7 @@ public class GroupStructInfo {
}
/** A filter or an aggregation: a header made of its conditions, then its
single child. */
- private static Node conditionsNode(Kind kind, Collection<Expression>
conditions, GroupExpression ge,
+ private static Node conditionsNode(Kind kind, Collection<Expression>
conditions, BuildInput ge,
Ctx ctx) {
if (ge.arity() != 1) {
return invalidNode("arity=" + ge.arity() + " of " +
ge.getPlan().getClass().getSimpleName(), ctx);
@@ -1759,7 +1964,7 @@ public class GroupStructInfo {
* the chain (the first sub tree which is not part of it), while an outer
/ semi / anti / asof join
* keeps its type and the memo order of its two sides, because it cannot
be reassociated.
*/
- private static Node joinNode(Join join, GroupExpression ge, Ctx ctx) {
+ private static Node joinNode(Join join, BuildInput ge, Ctx ctx) {
if (!isFlattenableJoinType(join.getJoinType())) {
Node node = new Node(Kind.JOIN);
node.joinType = join.getJoinType();
@@ -1778,7 +1983,7 @@ public class GroupStructInfo {
}
return node;
}
- return joinChainNode(join, ge, ctx);
+ return ge.joinChain(join, ctx);
}
/**
@@ -1820,7 +2025,7 @@ public class GroupStructInfo {
* The branches are sorted - the memo may reorder them - together with
their mapping, because the
* mapping belongs to one branch and two branches of the same shape can
still feed different columns.
*/
- private static Node setOperationNode(Plan plan, SetOperation setOperation,
GroupExpression ge, Ctx ctx) {
+ private static Node setOperationNode(Plan plan, SetOperation setOperation,
BuildInput ge, Ctx ctx) {
Node node = new Node(Kind.SET_OPERATION);
node.setOperationPlan = plan;
node.setOperation = setOperation;
@@ -1916,7 +2121,7 @@ public class GroupStructInfo {
}
/** A node which only composes the child at {@code index} (an enforcer, a
project, a CTE edge). */
- private static Node passthroughNode(GroupExpression ge, int index, Ctx
ctx) {
+ private static Node passthroughNode(BuildInput ge, int index, Ctx ctx) {
Node node = new Node(Kind.PASSTHROUGH);
node.children = children(ge, ctx, index);
return node.children == null ? null : node;
@@ -2024,10 +2229,10 @@ public class GroupStructInfo {
}
/** The children at the given indexes, or null when one of them
invalidates this node. */
- private static List<Child> children(GroupExpression ge, Ctx ctx, int...
indexes) {
+ private static List<Child> children(BuildInput ge, Ctx ctx, int...
indexes) {
List<Child> children = new ArrayList<>(indexes.length);
for (int index : indexes) {
- GroupStructInfo child = describeChild(ge, index, ctx);
+ GroupStructInfo child = ge.describeChild(index, ctx);
if (child == null) {
return null;
}
@@ -2452,12 +2657,11 @@ public class GroupStructInfo {
* Step 1 for a node with an arbitrary number of children (a set
operation): describe every branch in
* memo order, or report the reason of the first branch which cannot be
described.
*/
- private static List<GroupStructInfo> describeBranches(GroupExpression ge,
Ctx ctx) {
+ private static List<GroupStructInfo> describeBranches(BuildInput ge, Ctx
ctx) {
List<GroupStructInfo> branches = new ArrayList<>(ge.arity());
for (int i = 0; i < ge.arity(); i++) {
- GroupStructInfo branch = describeGroup(ge.child(i), ctx);
- if (!branch.isValid()) {
- invalid(ctx, branch.getSkipReason());
+ GroupStructInfo branch = ge.describeChild(i, ctx);
+ if (branch == null) {
return null;
}
branches.add(branch);
@@ -3407,6 +3611,8 @@ public class GroupStructInfo {
/** why the description was refused: the first reason wins, it is
shown by EXPLAIN */
private String reason = "";
private final Set<Group> visited = new HashSet<>();
+ // Allocated only by the detached physical entry point; Memo builds
use visited above.
+ private Set<PhysicalPlan> physicalVisited;
}
}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/PhysicalFilter.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/PhysicalFilter.java
index c5dce59bb4b..8297a2e6d43 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/PhysicalFilter.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/PhysicalFilter.java
@@ -30,6 +30,7 @@ import org.apache.doris.nereids.trees.plans.PlanType;
import org.apache.doris.nereids.trees.plans.algebra.Filter;
import org.apache.doris.nereids.trees.plans.visitor.PlanVisitor;
import org.apache.doris.nereids.util.ExpressionUtils;
+import org.apache.doris.nereids.util.MutableState;
import org.apache.doris.nereids.util.Utils;
import org.apache.doris.statistics.model.Statistics;
@@ -112,14 +113,15 @@ public class PhysicalFilter<CHILD_TYPE extends Plan>
extends PhysicalUnary<CHILD
@Override
public PhysicalFilter<Plan> withChildren(List<Plan> children) {
Preconditions.checkArgument(children.size() == 1);
- return AbstractPlan.copyWithSameId(this, () -> new
PhysicalFilter<>(conjuncts, groupExpression,
- getLogicalProperties(), physicalProperties, statistics,
children.get(0)));
+ return copyHboConjunctsTo(AbstractPlan.copyWithSameId(this,
+ () -> new PhysicalFilter<>(conjuncts, groupExpression,
getLogicalProperties(),
+ physicalProperties, statistics, children.get(0))));
}
@Override
public PhysicalFilter<CHILD_TYPE>
withGroupExpression(Optional<GroupExpression> groupExpression) {
- return AbstractPlan.copyWithSameId(this, () -> new
PhysicalFilter<>(conjuncts, groupExpression,
- getLogicalProperties(), child()));
+ return copyHboConjunctsTo(AbstractPlan.copyWithSameId(this,
+ () -> new PhysicalFilter<>(conjuncts, groupExpression,
getLogicalProperties(), child())));
}
@Override
@@ -133,8 +135,9 @@ public class PhysicalFilter<CHILD_TYPE extends Plan>
extends PhysicalUnary<CHILD
@Override
public PhysicalFilter<CHILD_TYPE>
withPhysicalPropertiesAndStats(PhysicalProperties physicalProperties,
Statistics statistics) {
- return AbstractPlan.copyWithSameId(this, () -> new
PhysicalFilter<>(conjuncts, groupExpression,
- getLogicalProperties(), physicalProperties, statistics,
child()));
+ return copyHboConjunctsTo(AbstractPlan.copyWithSameId(this,
+ () -> new PhysicalFilter<>(conjuncts, groupExpression,
getLogicalProperties(),
+ physicalProperties, statistics, child())));
}
public PhysicalFilter<Plan> withConjunctsAndChild(Set<Expression>
conjuncts, Plan child) {
@@ -142,6 +145,13 @@ public class PhysicalFilter<CHILD_TYPE extends Plan>
extends PhysicalUnary<CHILD
getLogicalProperties(), physicalProperties, statistics,
child));
}
+ /** Preserve the HBO identity only for rebuilds that leave the predicates
unchanged. */
+ private <T extends PhysicalFilter<?>> T copyHboConjunctsTo(T copy) {
+
this.<Set<Expression>>getMutableState(MutableState.KEY_HBO_ORIGINAL_CONJUNCTS)
+ .ifPresent(conjuncts ->
copy.setMutableState(MutableState.KEY_HBO_ORIGINAL_CONJUNCTS, conjuncts));
+ return copy;
+ }
+
@Override
public String shapeInfo() {
StringBuilder builder = new StringBuilder();
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/PhysicalPlanShallowCopier.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/PhysicalPlanShallowCopier.java
index d5c803ac1cd..46640e2410b 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/PhysicalPlanShallowCopier.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/PhysicalPlanShallowCopier.java
@@ -67,6 +67,8 @@ public class PhysicalPlanShallowCopier {
AbstractPhysicalPlan source = (AbstractPhysicalPlan) plan;
AbstractPhysicalPlan copy = source.copyForProfile(this::copyNode);
copy.setMutableState(MutableState.KEY_GROUP,
source.getGroupIdAsString());
+ source.getMutableState(MutableState.KEY_HBO_ORIGINAL_CONJUNCTS)
+ .ifPresent(conjuncts ->
copy.setMutableState(MutableState.KEY_HBO_ORIGINAL_CONJUNCTS, conjuncts));
copy.setStatistics(source.getStats() == null ? null : new
Statistics(source.getStats()));
if (source instanceof PhysicalHashAggregate) {
PhysicalHashAggregate.TopnPushInfo topn =
((PhysicalHashAggregate<?>) source).getTopnPushInfo();
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/util/MutableState.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/util/MutableState.java
index 89b06ea5c36..2863b61043b 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/util/MutableState.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/util/MutableState.java
@@ -29,6 +29,8 @@ public interface MutableState {
String KEY_PARENT = "parent";
String KEY_RF_JUMP = "rf-jump";
String KEY_PUSH_TOPN_TO_AGG = "pushTopnToAgg";
+ /** Immutable filter conjuncts before physical-only pruning predicates
were appended. */
+ String KEY_HBO_ORIGINAL_CONJUNCTS = "hbo-original-conjuncts";
/** hbo fingerprint attached at planning time for explain printing */
String KEY_HBO_FP = "hbo-fingerprint";
/**
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/nereids/processor/post/AddMonotonicFunctionPruningPredicatesTest.java
b/fe/fe-core/src/test/java/org/apache/doris/nereids/processor/post/AddMonotonicFunctionPruningPredicatesTest.java
index aa9fb68ba5b..38556012c60 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/nereids/processor/post/AddMonotonicFunctionPruningPredicatesTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/nereids/processor/post/AddMonotonicFunctionPruningPredicatesTest.java
@@ -49,6 +49,7 @@ import
org.apache.doris.nereids.trees.plans.physical.PhysicalStorageLayerAggrega
import org.apache.doris.nereids.trees.plans.physical.PhysicalTVFRelation;
import org.apache.doris.nereids.types.DateTimeV2Type;
import org.apache.doris.nereids.types.VarcharType;
+import org.apache.doris.nereids.util.MutableState;
import org.apache.doris.nereids.util.PlanConstructor;
import com.google.common.collect.ImmutableList;
@@ -129,6 +130,9 @@ class AddMonotonicFunctionPruningPredicatesTest extends
ExpressionRewriteTestHel
Set<Expression> conjuncts = ((PhysicalFilter<?>)
rewritten).getConjuncts();
Assertions.assertEquals(3, conjuncts.size());
+ Assertions.assertEquals(ImmutableSet.of(original), rewritten
+
.<Set<Expression>>getMutableState(MutableState.KEY_HBO_ORIGINAL_CONJUNCTS).orElseThrow());
+ Assertions.assertSame(rewritten, rewritten.accept(processor,
cascadesContext));
Assertions.assertTrue(conjuncts.stream().anyMatch(conjunct -> conjunct
instanceof GreaterThanEqual
&& conjunct.child(0).equals(stringSlot) &&
conjunct.isInferred()));
Assertions.assertTrue(conjuncts.stream().anyMatch(conjunct -> conjunct
instanceof LessThan
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/PhysicalPlanStructInfoPlannerTest.java
b/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/PhysicalPlanStructInfoPlannerTest.java
new file mode 100644
index 00000000000..0d2ebc5618c
--- /dev/null
+++
b/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/PhysicalPlanStructInfoPlannerTest.java
@@ -0,0 +1,162 @@
+// 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.doris.nereids.stats;
+
+import org.apache.doris.catalog.Env;
+import org.apache.doris.common.Config;
+import org.apache.doris.nereids.NereidsPlanner;
+import org.apache.doris.nereids.StatementContext;
+import org.apache.doris.nereids.glue.LogicalPlanAdapter;
+import org.apache.doris.nereids.memo.Group;
+import org.apache.doris.nereids.parser.NereidsParser;
+import org.apache.doris.nereids.trees.plans.AbstractPlan;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.physical.AbstractPhysicalJoin;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalFilter;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalHashAggregate;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalPlan;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalPlanShallowCopier;
+import org.apache.doris.nereids.util.PlanChecker;
+import org.apache.doris.qe.OriginStatement;
+import org.apache.doris.utframe.TestWithFeService;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+/** Compare detached subtrees from real, post-processed plans with the pinned
lookup identity. */
+class PhysicalPlanStructInfoPlannerTest extends TestWithFeService {
+ @Override
+ protected void runBeforeAll() throws Exception {
+ createDatabase("physical_struct_info");
+ useDatabase("physical_struct_info");
+
connectContext.getSessionVariable().setDisableNereidsRules("PRUNE_EMPTY_PARTITION");
+ executeSql("set enable_hbo_optimization=true");
+ createTable("CREATE TABLE a (k INT, v BIGINT) DUPLICATE KEY(k) "
+ + "DISTRIBUTED BY HASH(k) BUCKETS 3
PROPERTIES('replication_num'='1')");
+ createTable("CREATE TABLE strings (k INT, s VARCHAR(32)) DUPLICATE
KEY(k) "
+ + "DISTRIBUTED BY HASH(k) BUCKETS 3
PROPERTIES('replication_num'='1')");
+ createTable("CREATE TABLE b (k INT, v BIGINT) DUPLICATE KEY(k) "
+ + "DISTRIBUTED BY HASH(k) BUCKETS 3
PROPERTIES('replication_num'='1')");
+ }
+
+ @Test
+ void detachedCandidatesMatchPinnedLookup() {
+ int compared = 0;
+ for (String sql : List.of(
+ "select * from a where v < 10",
+ "select * from strings where substring(s,1,3)='abc'",
+ "select * from strings where substring(s,1,3)='abc' and
s>='aaa'",
+ "select * from strings join b on strings.k=b.k where
substring(s,1,3)='abc'",
+ "select * from a join b on a.k=b.k where a.v < 10",
+ "select * from a left join b on a.k=b.k and a.v < b.v",
+ "select v, sum(k) from a group by v",
+ "select v, sum(k) s from a group by v having sum(k) > 10",
+ "select * from (select k+1 x from a) t where x < 10",
+ "select * from (select * from a limit 5) t where v < 10",
+ "select * from (select * from a order by v limit 5) t where k
< 10")) {
+ StatementContext context = new StatementContext(connectContext,
new OriginStatement(sql, 0));
+ connectContext.setStatementContext(context);
+ LogicalPlanAdapter statement = new LogicalPlanAdapter(new
NereidsParser().parseSingle(sql), context);
+ context.setParsedStatement(statement);
+ CapturingPlanner planner = new CapturingPlanner(context);
+ planner.plan(statement);
+ Assertions.assertNull(planner.getCascadesContext().getMemo());
+ PhysicalPlan original = planner.getPhysicalPlan();
+ PhysicalPlan copy = PhysicalPlanShallowCopier.copy(original);
+ compared += compare(original, copy, planner.groups, sql);
+ }
+ Assertions.assertTrue(compared >= 6, "expected real
filter/join/aggregation candidates");
+ }
+
+ @Test
+ void entryKeyedByDetachedPlanIsAppliedByPinnedReadSide() {
+
Assertions.assertTrue(connectContext.getSessionVariable().isEnableHboOptimization());
+ String sql = "select * from strings where substring(s,1,3)='abc'";
+ PhysicalPlan original =
PlanChecker.from(connectContext).plan(sql).getPhysicalPlan();
+ PhysicalFilter<?> filter =
original.collectToList(PhysicalFilter.class::isInstance).stream()
+ .map(node -> (PhysicalFilter<?>)
node).findFirst().orElseThrow();
+ Assertions.assertEquals(3, filter.getConjuncts().size(), "execution
keeps both inferred bounds");
+ GroupStructInfo info =
GroupStructInfo.fromPhysicalPlan(PhysicalPlanShallowCopier.copy(filter));
+ Assertions.assertTrue(info.isValid(), info.getSkipReason());
+ GroupStructInfo.LiteralMode mode =
GroupStructInfo.LiteralMode.WITH_LITERAL;
+ String key = info.getFingerprint(mode);
+ HboPlanStatisticsManager manager =
Env.getCurrentEnv().getHboPlanStatisticsManager();
+ boolean persist = Config.hbo_persist_pinned_to_internal_db;
+ Config.hbo_persist_pinned_to_internal_db = false;
+ try {
+ manager.putPinnedPlanStatistics(key, 7,
HboPlanStatisticsManager.PinnedType.EXACT,
+ info.getCanonical(mode),
HboPlanStatisticsManager.LiteralMode.WITH_LITERAL);
+ PhysicalPlan replanned =
PlanChecker.from(connectContext).plan(sql).getPhysicalPlan();
+ PhysicalFilter<?> learnedFilter =
replanned.collectToList(PhysicalFilter.class::isInstance).stream()
+ .map(node -> (PhysicalFilter<?>)
node).findFirst().orElseThrow();
+ Assertions.assertEquals(7, learnedFilter.getStats().getRowCount());
+ } finally {
+ manager.removePinnedPlanStatistics(key);
+ Config.hbo_persist_pinned_to_internal_db = persist;
+ }
+ }
+
+ private static class CapturingPlanner extends NereidsPlanner {
+ private final Map<Integer, Group> groups = new HashMap<>();
+
+ private CapturingPlanner(StatementContext context) {
+ super(context);
+ }
+
+ @Override
+ protected void splitFragments(PhysicalPlan plan) {
+ // The production path releases Memo after translation. Retain it
only on the test's
+ // reference side; the cloned-plan builder must compute the same
key without this map.
+ for (Group group : getCascadesContext().getMemo().getGroups()) {
+ groups.put(group.getGroupId().asInt(), group);
+ }
+ super.splitFragments(plan);
+ }
+ }
+
+ private int compare(Plan plan, PhysicalPlan copy, Map<Integer, Group>
groups, String sql) {
+ int compared = 0;
+ boolean candidate = plan instanceof PhysicalFilter || plan instanceof
AbstractPhysicalJoin
+ || plan instanceof PhysicalHashAggregate
+ && !((PhysicalHashAggregate<?>)
plan).getAggMode().productAggregateBuffer;
+ if (candidate) {
+ Optional<GroupStructInfo> expected =
GroupStructInfo.structInfoOfPlanNode(
+ (AbstractPlan) plan, groups);
+ if (expected.isPresent()) {
+ GroupStructInfo actual =
GroupStructInfo.fromPhysicalPlan(copy);
+ Assertions.assertTrue(actual.isValid(), sql + "\n" +
plan.treeString()
+ + "\n" + actual.getSkipReason());
+ for (GroupStructInfo.LiteralMode mode :
GroupStructInfo.LiteralMode.values()) {
+
Assertions.assertEquals(expected.get().getFingerprint(mode),
actual.getFingerprint(mode),
+ sql + "\n" + plan.treeString() + "\nexpected: " +
expected.get().getCanonical(mode)
+ + "\nactual: " +
actual.getCanonical(mode));
+ }
+ compared++;
+ }
+ }
+ for (int i = 0; i < plan.arity(); i++) {
+ compared += compare(plan.child(i), (PhysicalPlan) copy.child(i),
groups, sql);
+ }
+ return compared;
+ }
+}
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/PhysicalPlanStructInfoTest.java
b/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/PhysicalPlanStructInfoTest.java
new file mode 100644
index 00000000000..82a3a88edde
--- /dev/null
+++
b/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/PhysicalPlanStructInfoTest.java
@@ -0,0 +1,269 @@
+// 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.doris.nereids.stats;
+
+import org.apache.doris.nereids.hint.DistributeHint;
+import org.apache.doris.nereids.memo.Memo;
+import org.apache.doris.nereids.properties.DistributionSpecAny;
+import org.apache.doris.nereids.properties.OrderKey;
+import org.apache.doris.nereids.trees.expressions.Add;
+import org.apache.doris.nereids.trees.expressions.AggregateExpression;
+import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.EqualTo;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.GreaterThanEqual;
+import org.apache.doris.nereids.trees.expressions.NamedExpression;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.functions.agg.AggregateParam;
+import org.apache.doris.nereids.trees.expressions.functions.agg.Sum;
+import org.apache.doris.nereids.trees.expressions.literal.IntegerLiteral;
+import org.apache.doris.nereids.trees.plans.AggMode;
+import org.apache.doris.nereids.trees.plans.AggPhase;
+import org.apache.doris.nereids.trees.plans.DistributeType;
+import org.apache.doris.nereids.trees.plans.JoinType;
+import org.apache.doris.nereids.trees.plans.LimitPhase;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.SortPhase;
+import org.apache.doris.nereids.trees.plans.algebra.SetOperation;
+import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalJoin;
+import org.apache.doris.nereids.trees.plans.logical.LogicalLimit;
+import org.apache.doris.nereids.trees.plans.logical.LogicalOlapScan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
+import org.apache.doris.nereids.trees.plans.logical.LogicalTopN;
+import org.apache.doris.nereids.trees.plans.logical.LogicalUnion;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalDistribute;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalFilter;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalHashAggregate;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalHashJoin;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalLimit;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalNestedLoopJoin;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalOlapScan;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalPlan;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalPlanShallowCopier;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalProject;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalTopN;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalUnion;
+import org.apache.doris.nereids.util.MutableState;
+import org.apache.doris.nereids.util.PlanConstructor;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+class PhysicalPlanStructInfoTest {
+ private final LogicalOlapScan a = PlanConstructor.newLogicalOlapScan(0,
"a", 0);
+ private final LogicalOlapScan b = PlanConstructor.newLogicalOlapScan(1,
"b", 0);
+ private final LogicalOlapScan c = PlanConstructor.newLogicalOlapScan(2,
"c", 0);
+
+ @Test
+ void scanAndFilterMatchBothLiteralModes() {
+ equivalent(a, scan(a));
+ Set<Expression> conditions = Set.of(new EqualTo(a.getOutput().get(0),
new IntegerLiteral(10)));
+ LogicalFilter<?> logical = new LogicalFilter<>(conditions, a);
+ equivalent(logical, new PhysicalFilter<>(conditions,
logical.getLogicalProperties(), scan(a)));
+ }
+
+ @Test
+ void originalFilterConjunctsSurviveRebuildsAndDetachedCopies() {
+ Expression original = new EqualTo(a.getOutput().get(0), new
IntegerLiteral(10)).withInferred(true);
+ Expression pruning = new GreaterThanEqual(a.getOutput().get(0), new
IntegerLiteral(0));
+ Set<Expression> hboConjuncts = Set.of(original);
+ PhysicalFilter<?> filter = new PhysicalFilter<>(Set.of(original,
pruning),
+ a.getLogicalProperties(), scan(a));
+ filter.setMutableState(MutableState.KEY_HBO_ORIGINAL_CONJUNCTS,
hboConjuncts);
+ LogicalFilter<?> logical = new LogicalFilter<>(hboConjuncts, a);
+ for (PhysicalFilter<?> rebuilt : List.of(filter,
+ filter.withChildren(List.of(filter.child())),
+ filter.withGroupExpression(Optional.empty()),
+
filter.withPhysicalPropertiesAndStats(filter.getPhysicalProperties(),
filter.getStats()),
+ filter.resetLogicalProperties())) {
+ Assertions.assertEquals(Set.of(original, pruning),
rebuilt.getConjuncts());
+ PhysicalFilter<?> copy = (PhysicalFilter<?>)
PhysicalPlanShallowCopier.copy(rebuilt);
+ Assertions.assertEquals(hboConjuncts, copy
+
.<Set<Expression>>getMutableState(MutableState.KEY_HBO_ORIGINAL_CONJUNCTS).orElseThrow());
+ Assertions.assertEquals(Set.of(original, pruning),
copy.getConjuncts());
+ equivalent(logical, rebuilt);
+ }
+ }
+
+ @Test
+ void computedProjectDefinitionsReachFilter() {
+ Alias alias = new Alias(new Add(
+ a.getOutput().get(0), new IntegerLiteral(1)), "computed");
+ LogicalProject<?> project = new LogicalProject<>(List.of(alias), a);
+ PhysicalProject<?> physicalProject = new
PhysicalProject<>(List.of(alias),
+ project.getLogicalProperties(), scan(a));
+ Set<Expression> conditions = Set.of(new EqualTo(alias.toSlot(), new
IntegerLiteral(10)));
+ LogicalFilter<?> logical = new LogicalFilter<>(conditions, project);
+ equivalent(logical, new PhysicalFilter<>(conditions,
logical.getLogicalProperties(), physicalProject));
+ }
+
+ @Test
+ void joinAlgorithmsAndExchangesDoNotChangeIdentity() {
+ for (JoinType type : List.of(JoinType.INNER_JOIN,
JoinType.LEFT_OUTER_JOIN,
+ JoinType.LEFT_SEMI_JOIN, JoinType.LEFT_ANTI_JOIN,
JoinType.NULL_AWARE_LEFT_ANTI_JOIN)) {
+ Expression condition = new EqualTo(a.getOutput().get(0),
b.getOutput().get(0));
+ LogicalJoin<?, ?> logical = new LogicalJoin<>(type,
List.of(condition), List.of(),
+ a, b, null);
+ PhysicalHashJoin<?, ?> physical = new PhysicalHashJoin<>(type,
List.of(condition), List.of(),
+ new DistributeHint(DistributeType.NONE), Optional.empty(),
logical.getLogicalProperties(),
+ exchange(scan(a)), exchange(scan(b)));
+ equivalent(logical, physical);
+ equivalent(logical, new PhysicalNestedLoopJoin<>(type,
List.of(condition), List.of(),
+ Optional.empty(), Optional.empty(),
logical.getLogicalProperties(), scan(a), scan(b)));
+ }
+ }
+
+ @Test
+ void reorderedJoinChainMatchesMemo() {
+ LogicalJoin<?, ?> ab = new LogicalJoin<>(JoinType.CROSS_JOIN, a, b,
null);
+ LogicalJoin<?, ?> logical = new LogicalJoin<>(JoinType.CROSS_JOIN, ab,
c, null);
+ PhysicalPlan bc = cross(scan(c), scan(b));
+ equivalent(logical, cross(exchange(bc), scan(a)));
+ }
+
+ @Test
+ void oneAndTwoStageAggregatesMatchLogicalIdentityIncludingHaving() {
+ List<Expression> groups = List.of(a.getOutput().get(0));
+ Sum sum = new Sum(a.getOutput().get(0));
+ Alias logicalSum = new Alias(sum, "s");
+ List<NamedExpression> outputs = List.of(a.getOutput().get(0),
logicalSum);
+ LogicalAggregate<?> logical = new LogicalAggregate<>(groups, outputs,
true, a);
+ AggregateParam direct = new AggregateParam(AggPhase.GLOBAL,
AggMode.INPUT_TO_RESULT);
+ PhysicalHashAggregate<?> single = new PhysicalHashAggregate<>(groups,
+ List.of(a.getOutput().get(0), new Alias(logicalSum.getExprId(),
+ new AggregateExpression(sum, direct), "s")),
+ direct, false, logical.getLogicalProperties(), false, scan(a));
+ equivalent(logical, single);
+ AggregateParam partial = new AggregateParam(AggPhase.LOCAL,
AggMode.INPUT_TO_BUFFER);
+ Alias buffer = new Alias(new AggregateExpression(sum, partial),
"partial_s");
+ PhysicalHashAggregate<?> local = new PhysicalHashAggregate<>(groups,
+ List.of(a.getOutput().get(0), buffer), partial, false,
+ logical.getLogicalProperties(), false, scan(a));
+ AggregateParam merge = new AggregateParam(AggPhase.GLOBAL,
AggMode.BUFFER_TO_RESULT);
+ PhysicalHashAggregate<?> global = new PhysicalHashAggregate<>(groups,
+ List.of(a.getOutput().get(0), new Alias(logicalSum.getExprId(),
+ new AggregateExpression(sum, merge, buffer.toSlot()),
"s")),
+ merge, false, logical.getLogicalProperties(), false,
exchange(local));
+ equivalent(logical, global);
+ Set<Expression> conditions = Set.of(new EqualTo(logicalSum.toSlot(),
new IntegerLiteral(10)));
+ LogicalFilter<?> having = new LogicalFilter<>(conditions, logical);
+ equivalent(having, new PhysicalFilter<>(conditions,
having.getLogicalProperties(), global));
+ GroupStructInfo partialInfo = cloned(local);
+ Assertions.assertFalse(partialInfo.isValid());
+ Assertions.assertTrue(partialInfo.getSkipReason().contains("partial"),
partialInfo.getSkipReason());
+ }
+
+ @Test
+ void independentNestedAggregatesStaySeparate() {
+ List<Expression> groups = List.of(a.getOutput().get(0));
+ LogicalAggregate<?> inner = new LogicalAggregate<>(groups,
List.of(a.getOutput().get(0)), true, a);
+ LogicalAggregate<?> outer = new LogicalAggregate<>(List.of(),
List.of(), true, inner);
+ AggregateParam direct = new AggregateParam(AggPhase.GLOBAL,
AggMode.INPUT_TO_RESULT);
+ PhysicalHashAggregate<?> physicalInner = new
PhysicalHashAggregate<>(groups,
+ List.of(a.getOutput().get(0)), direct, false,
inner.getLogicalProperties(), false, scan(a));
+ equivalent(outer, new PhysicalHashAggregate<>(List.of(), List.of(),
direct, false,
+ outer.getLogicalProperties(), false, physicalInner));
+ }
+
+ @Test
+ void distributedBoundsAreNormalizedButPartialRootsAreNotLearnable() {
+ LogicalLimit<?> logicalLocal = new LogicalLimit<>(7, 0,
LimitPhase.LOCAL, a);
+ LogicalLimit<?> logicalLimit = new LogicalLimit<>(5, 2,
LimitPhase.GLOBAL, logicalLocal);
+ PhysicalLimit<?> localLimit = new PhysicalLimit<>(7, 0,
LimitPhase.LOCAL,
+ logicalLimit.getLogicalProperties(), scan(a));
+ equivalent(logicalLimit, new PhysicalLimit<>(5, 2, LimitPhase.GLOBAL,
+ logicalLimit.getLogicalProperties(), exchange(localLimit)));
+ Assertions.assertFalse(cloned(localLimit).isValid());
+ List<OrderKey> order = List.of(new OrderKey(a.getOutput().get(0),
true, true));
+ LogicalTopN<?> logicalTopN = new LogicalTopN<>(order, 5, 2, a);
+ PhysicalTopN<?> localTopN = new PhysicalTopN<>(order, 7, 0,
SortPhase.LOCAL_SORT,
+ logicalTopN.getLogicalProperties(), scan(a));
+ equivalent(logicalTopN, new PhysicalTopN<>(order, 5, 2,
SortPhase.MERGE_SORT,
+ logicalTopN.getLogicalProperties(), exchange(localTopN)));
+ Assertions.assertFalse(cloned(localTopN).isValid());
+ }
+
+ @Test
+ void unionKeepsBranchColumnMappings() {
+ for (SetOperation.Qualifier qualifier :
SetOperation.Qualifier.values()) {
+ List<NamedExpression> outputs = List.of(new
SlotReference("union_k", a.getOutput().get(0).getDataType()));
+ List<List<SlotReference>> mappings = List.of(
+ List.of((SlotReference) a.getOutput().get(0)),
+ List.of((SlotReference) b.getOutput().get(0)));
+ LogicalUnion logical = new LogicalUnion(qualifier, outputs,
mappings, List.of(), false, List.of(a, b));
+ equivalent(logical, new PhysicalUnion(qualifier, outputs,
mappings, List.of(),
+ logical.getLogicalProperties(), List.of(scan(a),
scan(b))));
+ }
+ }
+
+ @Test
+ void unsupportedDistinctStagesAndSharedInputsAreExplicit() {
+ AggregateParam distinct = new AggregateParam(AggPhase.DISTINCT_GLOBAL,
AggMode.INPUT_TO_RESULT);
+ PhysicalHashAggregate<?> aggregate = new
PhysicalHashAggregate<>(List.of(), List.of(), distinct,
+ false, a.getLogicalProperties(), false, scan(a));
+ GroupStructInfo unsupported = cloned(aggregate);
+ Assertions.assertFalse(unsupported.isValid());
+
Assertions.assertTrue(unsupported.getSkipReason().contains("distinct"));
+ PhysicalPlan shared = scan(a);
+ GroupStructInfo sharing = cloned(cross(shared, shared));
+ Assertions.assertFalse(sharing.isValid());
+ Assertions.assertTrue(sharing.getSkipReason().contains("sharing"));
+ }
+
+ private static PhysicalOlapScan scan(LogicalOlapScan scan) {
+ return new PhysicalOlapScan(scan.getRelationId(), scan.getTable(),
scan.getQualifier(),
+ scan.getSelectedIndexId(), scan.getSelectedTabletIds(),
scan.getSelectedPartitionIds(),
+ scan.hasPartitionPredicate(), DistributionSpecAny.INSTANCE,
scan.getPreAggStatus(), scan.getOutput(),
+ Optional.empty(), scan.getLogicalProperties(), null, null,
scan.getTableSample(),
+ scan.getOperativeSlots(), scan.getVirtualColumns(),
scan.getScoreOrderKeys(), scan.getScoreLimit(),
+ scan.getScoreRangeInfo(), scan.getAnnOrderKeys(),
scan.getAnnLimit(), scan.getTableAlias());
+ }
+
+ private static PhysicalPlan exchange(PhysicalPlan child) {
+ return new PhysicalDistribute<>(DistributionSpecAny.INSTANCE, child);
+ }
+
+ private static PhysicalPlan cross(PhysicalPlan left, PhysicalPlan right) {
+ return new PhysicalHashJoin<>(JoinType.CROSS_JOIN, List.of(),
List.of(),
+ new DistributeHint(DistributeType.NONE), Optional.empty(),
left.getLogicalProperties(), left, right);
+ }
+
+ private static GroupStructInfo cloned(PhysicalPlan physical) {
+ PhysicalPlan copy = PhysicalPlanShallowCopier.copy(physical);
+ Assertions.assertTrue(copy.getGroupExpression().isEmpty());
+ return GroupStructInfo.fromPhysicalPlan(copy);
+ }
+
+ private static void equivalent(Plan logical, PhysicalPlan physical) {
+ GroupStructInfo expected = GroupStructInfo.of(new Memo(null,
logical).getRoot());
+ GroupStructInfo actual = cloned(physical);
+ Assertions.assertTrue(expected.isValid(), expected.getSkipReason());
+ Assertions.assertTrue(actual.isValid(), actual.getSkipReason());
+ for (GroupStructInfo.LiteralMode mode :
GroupStructInfo.LiteralMode.values()) {
+ Assertions.assertEquals(expected.getCanonical(mode),
actual.getCanonical(mode));
+ Assertions.assertEquals(expected.getShape(mode),
actual.getShape(mode));
+ Assertions.assertEquals(expected.getFingerprint(mode),
actual.getFingerprint(mode));
+ }
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]