github-actions[bot] commented on code in PR #64559: URL: https://github.com/apache/doris/pull/64559#discussion_r3432470206
########## fe/fe-core/src/main/java/org/apache/doris/nereids/stats/MemoStatsAndCostRecomputer.java: ########## @@ -0,0 +1,759 @@ +// 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.common.Pair; +import org.apache.doris.nereids.CascadesContext; +import org.apache.doris.nereids.cost.Cost; +import org.apache.doris.nereids.cost.CostCalculator; +import org.apache.doris.nereids.memo.Group; +import org.apache.doris.nereids.memo.GroupExpression; +import org.apache.doris.nereids.properties.PhysicalProperties; +import org.apache.doris.nereids.trees.expressions.CTEId; +import org.apache.doris.nereids.trees.plans.Plan; +import org.apache.doris.nereids.trees.plans.algebra.Join; +import org.apache.doris.nereids.trees.plans.logical.LogicalCTEConsumer; +import org.apache.doris.nereids.trees.plans.logical.LogicalCTEProducer; +import org.apache.doris.nereids.trees.plans.logical.LogicalProject; +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.PhysicalProject; +import org.apache.doris.qe.ConnectContext; +import org.apache.doris.statistics.Statistics; + +import com.google.common.collect.Lists; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * Re-estimate memo logical row counts and rebuild physical costs. + * and rebuild physical cost state. + */ +public final class MemoStatsAndCostRecomputer { + private static final double CHOSEN_PROJECT_STATS_DIVERGENCE_RATIO_THRESHOLD = 1_000D; + private final CascadesContext cascadesContext; + private final Map<CTEId, Statistics> cteIdToStats = new HashMap<>(); + private final LogicalExpressionRowCountSyncPolicy logicalExpressionRowCountSyncPolicy; + + private MemoStatsAndCostRecomputer(CascadesContext cascadesContext, + LogicalExpressionRowCountSyncPolicy logicalExpressionRowCountSyncPolicy) { + this.cascadesContext = cascadesContext; + this.logicalExpressionRowCountSyncPolicy = logicalExpressionRowCountSyncPolicy; + } + + /** + * recompute + */ + public static void recompute(Group rootGroup, PhysicalProperties physicalProperties, + CascadesContext cascadesContext) { + recompute(rootGroup, physicalProperties, cascadesContext, + LogicalExpressionRowCountSyncPolicy.KEEP_INDIVIDUAL_EXPRESSION_ROW_COUNT); + } + + /** + * recompute with configurable logical expression row count sync behavior. + */ + public static void recompute(Group rootGroup, PhysicalProperties physicalProperties, + CascadesContext cascadesContext, + LogicalExpressionRowCountSyncPolicy logicalExpressionRowCountSyncPolicy) { + MemoStatsAndCostRecomputer recomputer = new MemoStatsAndCostRecomputer(cascadesContext, + logicalExpressionRowCountSyncPolicy); + recomputer.seedProducerStats(rootGroup, new HashSet<>()); + recomputer.reestimateLogicalStatsBottomUp(rootGroup, new HashSet<>()); + // Run a second pass so CTE consumers and their ancestors can settle on producer stats refreshed above. + recomputer.reestimateLogicalStatsBottomUp(rootGroup, new HashSet<>()); + recomputer.recomputePhysicalCostsBottomUp(rootGroup, new HashSet<>()); + } + + private void seedProducerStats(Group group, Set<Group> visited) { + if (!visited.add(group)) { + return; + } + Statistics statistics = group.getStatistics(); + if (statistics != null) { + recordProducerStats(group, statistics); + } + for (Group child : getTraversalChildren(group)) { + seedProducerStats(child, visited); + } + } + + private void reestimateLogicalStatsBottomUp(Group group, Set<Group> visited) { + if (!visited.add(group)) { + return; + } + for (Group child : getTraversalChildren(group)) { + reestimateLogicalStatsBottomUp(child, visited); + } + reestimateCurrentGroup(group); + refreshEnforcerRowCount(group); + } + + private void reestimateCurrentGroup(Group group) { + List<GroupExpression> estimableExpressions = getEstimableLogicalExpressions(group); + if (estimableExpressions.isEmpty()) { + if (group.getLogicalExpressions().isEmpty()) { + reestimatePhysicalOnlyGroup(group); + } + return; + } + Statistics originalStatistics = group.getStatistics(); + Map<GroupExpression, Statistics> candidateStatisticsByExpression = new LinkedHashMap<>(); + for (GroupExpression logicalExpression : estimableExpressions) { + List<Statistics> originalChildStatistics = replaceChildStatisticsForLogicalEstimation(logicalExpression); + group.setStatistics(null); + try { + estimateStats(logicalExpression); + } finally { + restoreChildStatistics(logicalExpression, originalChildStatistics); + } + Statistics estimatedStatistics = group.getStatistics(); + if (estimatedStatistics == null || !isValidCandidateStatistics(estimatedStatistics)) { + continue; + } + logicalExpression.setEstOutputRowCount(estimatedStatistics.getRowCount()); + candidateStatisticsByExpression.put(logicalExpression, new Statistics(estimatedStatistics)); + } + if (candidateStatisticsByExpression.isEmpty()) { + group.setStatistics(originalStatistics); + return; + } + LogicalRowCountAggregationPolicy aggregationPolicy = getLogicalRowCountAggregationPolicy(); + Map<GroupExpression, Statistics> selectedCandidateStatisticsByExpression = filterCandidateStatisticsByPolicy( + aggregationPolicy, candidateStatisticsByExpression); + List<Statistics> candidateStatistics = new ArrayList<>(selectedCandidateStatisticsByExpression.values()); + double aggregatedRowCount = aggregationPolicy.aggregate(candidateStatistics); + Statistics updatedStatistics = resolveUpdatedGroupStatistics(group, selectedCandidateStatisticsByExpression, + candidateStatistics, aggregatedRowCount, originalStatistics); + group.setStatistics(updatedStatistics); + repairInvalidLogicalExpressionRowCounts(group, aggregatedRowCount); Review Comment: This sets the aggregated group statistics but leaves `Group.isStatsReliable` as the side effect from the last candidate estimated in the loop above. A reduced DPHyp group can contain alternatives like: ```text Group{A,B,C} LogicalJoin((A join B) join C) -- predicates have known stats LogicalJoin((A join C) join B) -- predicates include unknown stats ``` For each alternative this method clears `group.statistics`, so `StatsCalculator.estimate()` writes `ownerGroup.setStatsReliable(...)`. After `resolveUpdatedGroupStatistics(...)` picks or aggregates candidates, line 152 only replaces the stats; the reliability flag still reflects the final iteration order, not `updatedStatistics` or the selected candidate set. That flag is then read by `CostModel.visitPhysicalHashJoin()` during `recomputePhysicalCostsBottomUp()` and by `OptimizeGroupExpressionJob.getJoinRules()` after DPHyp, so the copied-out plan and follow-up join rules can flip depending on memo insertion order. Please preserve reliability per candidate and set the group flag consistently with the selected/aggregated stats, conservatively false if any selected candidate is unreliable. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
