OIiveirra commented on code in PR #71331:
URL: https://github.com/apache/doris/pull/71331#discussion_r4795327875
##########
fe/fe-core/src/main/java/org/apache/doris/planner/AddLocalExchange.java:
##########
@@ -81,22 +88,54 @@ public class AddLocalExchange {
* (global=2, per-BE=1), causing pipeline task mismatch and deadlock. */
public void addLocalExchange(FragmentIdMapping<DistributedPlan>
distributedPlans,
PlanTranslatorContext context) {
+ // Most queries never need this check. Inspect assignments only for a
candidate scan fragment.
+ Supplier<Boolean> oneCapableBackend = Suppliers.memoize(() ->
allJobsUseOneCapableBackend(distributedPlans,
+ context.getConnectContext()));
for (DistributedPlan plan : distributedPlans.values()) {
PipelineDistributedPlan pipePlan = (PipelineDistributedPlan) plan;
- long maxPerBeInstances = pipePlan.getInstanceJobs().stream()
- .collect(java.util.stream.Collectors.groupingBy(
- j -> j.getAssignedWorker().id(),
java.util.stream.Collectors.counting()))
+ List<AssignedJob> jobs = pipePlan.getInstanceJobs();
+ long maxPerBeInstances = jobs.stream()
+ .collect(Collectors.groupingBy(j ->
j.getAssignedWorker().id(), Collectors.counting()))
.values().stream().mapToLong(Long::longValue).max().orElse(0);
if (maxPerBeInstances <= 1) {
continue;
}
+ PlanFragment fragment = pipePlan.getFragmentJob().getFragment();
+ context.setBlockAggregationEligible(fragment.getPlanRoot()
instanceof AggregationNode
+ && jobs.size() == AggregationNode.BLOCK_AGGREGATION_TASKS
+ && oneCapableBackend.get());
context.setCurrentFragmentBucketUpgradeEligible(
isBucketUpgradeEligible(pipePlan, maxPerBeInstances,
context));
- PlanFragment fragment = pipePlan.getFragmentJob().getFragment();
addLocalExchangeForFragment(fragment, context);
}
}
+ private static boolean
allJobsUseOneCapableBackend(FragmentIdMapping<DistributedPlan> plans,
+ ConnectContext connect) {
+ if (connect == null || connect.getEnv() == null ||
!connect.getEnv().isMaster()) {
+ return false;
+ }
+ Backend assigned = null;
+ for (DistributedPlan plan : plans.values()) {
+ for (AssignedJob job : ((PipelineDistributedPlan)
plan).getInstanceJobs()) {
+ DistributedPlanWorker worker = job.getAssignedWorker();
+ if (!(worker instanceof BackendWorker)) {
+ return false;
+ }
+ if (assigned == null) {
+ assigned = ((BackendWorker) worker).getBackend();
+ if (assigned.getPipelineExecutorSize() <
AggregationNode.BLOCK_AGGREGATION_TASKS
+ || !assigned.isAdaptiveDecimalAggV1Supported()) {
Review Comment:
Fixed in cbffc5d605d. The FE records the BE ID and process epoch for
fragments using private Decimal states and rechecks the assigned process and
heartbeat capability after admission, before dispatch. A mismatch triggers
bounded replanning. The admission and non-cloud retry tests pass.
##########
fe/fe-core/src/main/java/org/apache/doris/planner/AggregationNode.java:
##########
@@ -384,10 +424,169 @@ public Pair<PlanNode, LocalExchangeType>
enforceAndDeriveLocalExchange(
Pair<PlanNode, LocalExchangeType> enforceResult
= enforceRequire(translatorContext, children.get(0), 0,
requireChild);
+ if (pairedMerge != null) {
+ if (enforceResult.first instanceof LocalExchangeNode
+ && ((LocalExchangeNode)
enforceResult.first).getExchangeType() == LocalExchangeType.PASSTHROUGH) {
+ adaptiveDecimalStates = true;
+ pairedMerge.adaptiveDecimalStates = true;
+ } else {
+ enforceResult = enforceRequire(translatorContext,
children.get(0), 0,
+ LocalExchangeTypeRequire.requireHash());
+ }
+ }
children = Lists.newArrayList(enforceResult.first);
return Pair.of(this, enforceResult.second);
}
+ // Let each scan task contribute partial states when hashing a few groups
would idle tasks.
+ // The outgoing stream routes all partial states for the same group to the
same final reducer.
+ private boolean canDistributePartialGroups(PlanTranslatorContext context) {
+ if (!context.isBlockAggregationEligible() || queryCacheCandidate
+ || !Double.isFinite(estimatedInputRowsForLocalExchange)
+ || estimatedInputRowsForLocalExchange <
MIN_PARTIAL_AGG_INPUT_ROWS
+ || !Double.isFinite(estimatedGroupsForLocalExchange) ||
estimatedGroupsForLocalExchange <= 0
+ || estimatedGroupsForLocalExchange > BLOCK_AGGREGATION_TASKS
+ || needsFinalize || !aggInfo.isFirstPhase() || sortByGroupKey
!= null || hasLimit()
+ || (projectList != null && !projectList.isEmpty())
+ || !(getChild(0) instanceof FileQueryScanNode) ||
getChild(0).hasLimit()
+ ||
!getChild(0).isSerialOperatorOnBe(context.getConnectContext())
+ || getFragment() == null || getFragment().getPlanRoot() != this
+ || !(getFragment().getSink() instanceof DataStreamSink)) {
+ return false;
+ }
+
+ FileQueryScanNode scan = (FileQueryScanNode) getChild(0);
+ // Grouping NDVs are cached by table and column, without a snapshot or
scan selector.
+ if (scan.getQueryTableSnapshot() != null || scan.getScanParams() !=
null
+ || !getFragment().getTargetRuntimeFilterIds().isEmpty()) {
+ return false;
+ }
+ DataPartition partition = getFragment().getSink().getOutputPartition();
+ List<Expr> keys = aggInfo.getGroupingExprs();
+ if (partition == null || partition.getType() !=
TPartitionType.HASH_PARTITIONED
+ || keys.size() != 2 || partition.getPartitionExprs().size() !=
keys.size()
+ || aggInfo.getOutputTupleDesc().getSlots().size() <
keys.size()) {
+ return false;
+ }
+ for (int i = 0; i < keys.size(); i++) {
+ Expr output = partition.getPartitionExprs().get(i);
+ SlotDescriptor group =
aggInfo.getOutputTupleDesc().getSlots().get(i);
+ if (!(keys.get(i) instanceof SlotRef) ||
!keys.get(i).getType().isStringType()
+ || !(output instanceof SlotRef) || ((SlotRef)
output).getDesc() == null
+ || !group.getId().equals(((SlotRef) output).getSlotId())
+ || !aggInfo.getOutputTupleId().equals(((SlotRef)
output).getDesc().getParentId())) {
+ return false;
+ }
+ }
+
+ List<FunctionCallExpr> aggregates = aggInfo.getAggregateExprs();
+ return !aggregates.isEmpty() &&
aggregates.stream().allMatch(AggregationNode::canRepartitionAggregate)
+ && scan.getTableIf() instanceof PluginDrivenExternalTable
+ && ((PluginDrivenExternalTable)
scan.getTableIf()).hasPinnedIcebergDataSchema();
+ }
+
+ /**
+ * Only a one-to-one state channel between a local producer and its direct
final reducer can
+ * select the private ABI. Merge functions may consume a different
ordering of slots.
+ */
+ AggregationNode matchingDecimalMerge() {
+ PlanFragment fragment = getFragment();
+ ExchangeNode exchange = fragment.getDestNode();
+ PlanFragment dest = fragment.getDestFragment();
+ if (exchange == null || dest == null || fragment.getOutputExprs() !=
null
+ || exchange.getChildren().size() != 1 || exchange.getChild(0)
!= this
+ || (exchange.getProjectList() != null &&
!exchange.getProjectList().isEmpty())
+ || queryCacheCandidate) {
+ return null;
+ }
+ PlanNode n = dest.getPlanRoot();
+ while (n != null && n.getFragment() == dest && n.getChildren().size()
== 1
+ && !(n instanceof ExchangeNode)) {
+ if (n instanceof AggregationNode) {
+ AggregationNode merge = (AggregationNode) n;
+ PlanNode child = merge.getChild(0);
+ while (child instanceof LocalExchangeNode &&
child.getChildren().size() == 1
+ && (child.getProjectList() == null ||
child.getProjectList().isEmpty())) {
+ child = child.getChild(0);
+ }
+ return child == exchange && merge.needsFinalize &&
merge.aggInfo.isMerge()
+ && !merge.queryCacheCandidate &&
hasMatchingStateSlots(merge) ? merge : null;
+ }
+ n = n.getChild(0);
+ }
+ return null;
+ }
+
+ private boolean hasMatchingStateSlots(AggregationNode merge) {
+ List<SlotDescriptor> slots = aggInfo.getOutputTupleDesc().getSlots();
+ List<FunctionCallExpr> producers = aggInfo.getAggregateExprs();
+ int offset = aggInfo.getGroupingExprs().size();
+ if (slots.size() != offset + producers.size() || producers.size() !=
merge.aggInfo.getAggregateExprs().size()) {
+ return false;
+ }
+ Map<Integer, FunctionCallExpr> bySlot = new HashMap<>();
+ for (int i = 0; i < producers.size(); i++) {
+ bySlot.put(slots.get(offset + i).getId().asInt(),
producers.get(i));
+ }
+ for (FunctionCallExpr finalFn : merge.aggInfo.getAggregateExprs()) {
+ if (!finalFn.isMergeAggFn() || finalFn.getFn() == null ||
finalFn.getChildren().size() != 1
+ || !(finalFn.getChild(0) instanceof SlotRef)) {
+ return false;
+ }
+ SlotRef slot = (SlotRef) finalFn.getChild(0);
+ if (slot.getDesc() == null ||
!aggInfo.getOutputTupleId().equals(slot.getDesc().getParentId())) {
+ return false;
+ }
+ FunctionCallExpr producer =
bySlot.remove(slot.getSlotId().asInt());
+ if (producer == null ||
!producer.getFnName().getFunction().equals(finalFn.getFnName().getFunction())
+ || !Arrays.equals(producer.getFn().getArgs(),
finalFn.getFn().getArgs())
+ ||
!producer.getFn().getReturnType().equals(finalFn.getFn().getReturnType())) {
+ return false;
+ }
+ }
+ return bySlot.isEmpty();
+ }
+
+ private static String adaptiveWireName(FunctionCallExpr call) {
+ return "__doris_adaptive_decimal_" + call.getFnName().getFunction();
+ }
+
+ private static boolean usesDecimal128Accumulator(FunctionCallExpr call) {
+ Function fn = call.getFn();
+ String name = call.getFnName().getFunction();
+ if (fn == null || !("sum".equals(name) || "avg".equals(name)) ||
fn.getArgs().length != 1
+ || !fn.getArgs()[0].isDecimalV3() ||
fn.getArgs()[0].isScalarType(PrimitiveType.DECIMAL256)
+ || !fn.getReturnType().isScalarType(PrimitiveType.DECIMAL128))
{
+ return false;
+ }
+ int inputScale = ((ScalarType) fn.getArgs()[0]).getScalarScale();
+ ScalarType result = (ScalarType) fn.getReturnType();
+ return inputScale >= 0 && result.getScalarPrecision() == 38
+ && result.getScalarScale() == ("sum".equals(name) ? inputScale
: Math.max(4, inputScale));
+ }
+
+ private static boolean canRepartitionAggregate(FunctionCallExpr call) {
+ Function fn = call.getFn();
+ if (fn == null || fn.getBinaryType() != Function.BinaryType.BUILTIN
+ || call.getParams().isDistinct() ||
!call.getOrderByElements().isEmpty()) {
+ return false;
+ }
+ switch (call.getFnName().getFunction()) {
+ case "count":
+ return true;
+ case "sum":
+ case "avg":
+ Type[] args = fn.getArgs();
+ // DecimalV3 uses the resolved result type for its partial
sum. Splitting a group
+ // can overflow a signed Decimal128 subtotal even when its
final sum fits.
+ return args.length == 1 && (args[0].isFixedPointType()
Review Comment:
Fixed in 5a17baca3ad. SUM over integer inputs keeps the local aggregate on
hash, including mixed aggregate nodes. The planner tests cover integer
overloads, Decimal eligibility and fallback; the Iceberg regression also checks
the mixed BIGINT/Decimal SUM result against explicit hash.
--
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]